PackageManagerService.java revision 5cdda3425ccf3c62e400a1646615f4479a8266af
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_SANDBOX_VERSION_DOWNGRADE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 57import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 58import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 59import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 60import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 61import static android.content.pm.PackageManager.INSTALL_INTERNAL; 62import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 67import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 68import static android.content.pm.PackageManager.MATCH_ALL; 69import static android.content.pm.PackageManager.MATCH_ANY_USER; 70import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 72import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 73import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 74import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 75import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 76import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 77import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 78import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 79import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 80import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 81import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 82import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 83import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 84import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 85import static android.content.pm.PackageManager.PERMISSION_DENIED; 86import static android.content.pm.PackageManager.PERMISSION_GRANTED; 87import static android.content.pm.PackageParser.isApkFile; 88import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 89import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 90import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 91import static android.system.OsConstants.O_CREAT; 92import static android.system.OsConstants.O_RDWR; 93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 94import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 95import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 96import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 97import static com.android.internal.util.ArrayUtils.appendInt; 98import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 100import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 101import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 102import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 104import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 105import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 106import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 107import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 108import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 109import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 110import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 111import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 112import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 113import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasCertificate; 114import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate; 115import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 117import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 118import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 119 120import android.Manifest; 121import android.annotation.IntDef; 122import android.annotation.NonNull; 123import android.annotation.Nullable; 124import android.app.ActivityManager; 125import android.app.AppOpsManager; 126import android.app.IActivityManager; 127import android.app.ResourcesManager; 128import android.app.admin.IDevicePolicyManager; 129import android.app.admin.SecurityLog; 130import android.app.backup.IBackupManager; 131import android.content.BroadcastReceiver; 132import android.content.ComponentName; 133import android.content.ContentResolver; 134import android.content.Context; 135import android.content.IIntentReceiver; 136import android.content.Intent; 137import android.content.IntentFilter; 138import android.content.IntentSender; 139import android.content.IntentSender.SendIntentException; 140import android.content.ServiceConnection; 141import android.content.pm.ActivityInfo; 142import android.content.pm.ApplicationInfo; 143import android.content.pm.AppsQueryHelper; 144import android.content.pm.AuxiliaryResolveInfo; 145import android.content.pm.ChangedPackages; 146import android.content.pm.ComponentInfo; 147import android.content.pm.FallbackCategoryProvider; 148import android.content.pm.FeatureInfo; 149import android.content.pm.IDexModuleRegisterCallback; 150import android.content.pm.IOnPermissionsChangeListener; 151import android.content.pm.IPackageDataObserver; 152import android.content.pm.IPackageDeleteObserver; 153import android.content.pm.IPackageDeleteObserver2; 154import android.content.pm.IPackageInstallObserver2; 155import android.content.pm.IPackageInstaller; 156import android.content.pm.IPackageManager; 157import android.content.pm.IPackageManagerNative; 158import android.content.pm.IPackageMoveObserver; 159import android.content.pm.IPackageStatsObserver; 160import android.content.pm.InstantAppInfo; 161import android.content.pm.InstantAppRequest; 162import android.content.pm.InstantAppResolveInfo; 163import android.content.pm.InstrumentationInfo; 164import android.content.pm.IntentFilterVerificationInfo; 165import android.content.pm.KeySet; 166import android.content.pm.PackageCleanItem; 167import android.content.pm.PackageInfo; 168import android.content.pm.PackageInfoLite; 169import android.content.pm.PackageInstaller; 170import android.content.pm.PackageList; 171import android.content.pm.PackageManager; 172import android.content.pm.PackageManagerInternal; 173import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 174import android.content.pm.PackageManagerInternal.PackageListObserver; 175import android.content.pm.PackageParser; 176import android.content.pm.PackageParser.ActivityIntentInfo; 177import android.content.pm.PackageParser.Package; 178import android.content.pm.PackageParser.PackageLite; 179import android.content.pm.PackageParser.PackageParserException; 180import android.content.pm.PackageParser.ParseFlags; 181import android.content.pm.PackageParser.ServiceIntentInfo; 182import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 183import android.content.pm.PackageStats; 184import android.content.pm.PackageUserState; 185import android.content.pm.ParceledListSlice; 186import android.content.pm.PermissionGroupInfo; 187import android.content.pm.PermissionInfo; 188import android.content.pm.ProviderInfo; 189import android.content.pm.ResolveInfo; 190import android.content.pm.ServiceInfo; 191import android.content.pm.SharedLibraryInfo; 192import android.content.pm.Signature; 193import android.content.pm.UserInfo; 194import android.content.pm.VerifierDeviceIdentity; 195import android.content.pm.VerifierInfo; 196import android.content.pm.VersionedPackage; 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.storage.DeviceStorageMonitorInternal; 317 318import dalvik.system.CloseGuard; 319import dalvik.system.VMRuntime; 320 321import libcore.io.IoUtils; 322 323import org.xmlpull.v1.XmlPullParser; 324import org.xmlpull.v1.XmlPullParserException; 325import org.xmlpull.v1.XmlSerializer; 326 327import java.io.BufferedOutputStream; 328import java.io.ByteArrayInputStream; 329import java.io.ByteArrayOutputStream; 330import java.io.File; 331import java.io.FileDescriptor; 332import java.io.FileInputStream; 333import java.io.FileOutputStream; 334import java.io.FilenameFilter; 335import java.io.IOException; 336import java.io.PrintWriter; 337import java.lang.annotation.Retention; 338import java.lang.annotation.RetentionPolicy; 339import java.nio.charset.StandardCharsets; 340import java.security.DigestInputStream; 341import java.security.MessageDigest; 342import java.security.NoSuchAlgorithmException; 343import java.security.PublicKey; 344import java.security.SecureRandom; 345import java.security.cert.CertificateException; 346import java.util.ArrayList; 347import java.util.Arrays; 348import java.util.Collection; 349import java.util.Collections; 350import java.util.Comparator; 351import java.util.HashMap; 352import java.util.HashSet; 353import java.util.Iterator; 354import java.util.LinkedHashSet; 355import java.util.List; 356import java.util.Map; 357import java.util.Objects; 358import java.util.Set; 359import java.util.concurrent.CountDownLatch; 360import java.util.concurrent.Future; 361import java.util.concurrent.TimeUnit; 362import java.util.concurrent.atomic.AtomicBoolean; 363import java.util.concurrent.atomic.AtomicInteger; 364 365/** 366 * Keep track of all those APKs everywhere. 367 * <p> 368 * Internally there are two important locks: 369 * <ul> 370 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 371 * and other related state. It is a fine-grained lock that should only be held 372 * momentarily, as it's one of the most contended locks in the system. 373 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 374 * operations typically involve heavy lifting of application data on disk. Since 375 * {@code installd} is single-threaded, and it's operations can often be slow, 376 * this lock should never be acquired while already holding {@link #mPackages}. 377 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 378 * holding {@link #mInstallLock}. 379 * </ul> 380 * Many internal methods rely on the caller to hold the appropriate locks, and 381 * this contract is expressed through method name suffixes: 382 * <ul> 383 * <li>fooLI(): the caller must hold {@link #mInstallLock} 384 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 385 * being modified must be frozen 386 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 387 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 388 * </ul> 389 * <p> 390 * Because this class is very central to the platform's security; please run all 391 * CTS and unit tests whenever making modifications: 392 * 393 * <pre> 394 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 395 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 396 * </pre> 397 */ 398public class PackageManagerService extends IPackageManager.Stub 399 implements PackageSender { 400 static final String TAG = "PackageManager"; 401 public static final boolean DEBUG_SETTINGS = false; 402 static final boolean DEBUG_PREFERRED = false; 403 static final boolean DEBUG_UPGRADE = false; 404 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 405 private static final boolean DEBUG_BACKUP = false; 406 public static final boolean DEBUG_INSTALL = false; 407 public static final boolean DEBUG_REMOVE = false; 408 private static final boolean DEBUG_BROADCASTS = false; 409 private static final boolean DEBUG_SHOW_INFO = false; 410 private static final boolean DEBUG_PACKAGE_INFO = false; 411 private static final boolean DEBUG_INTENT_MATCHING = false; 412 public static final boolean DEBUG_PACKAGE_SCANNING = false; 413 private static final boolean DEBUG_VERIFY = false; 414 private static final boolean DEBUG_FILTERS = false; 415 public static final boolean DEBUG_PERMISSIONS = false; 416 private static final boolean DEBUG_SHARED_LIBRARIES = false; 417 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 418 419 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 420 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 421 // user, but by default initialize to this. 422 public static final boolean DEBUG_DEXOPT = false; 423 424 private static final boolean DEBUG_ABI_SELECTION = false; 425 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 426 private static final boolean DEBUG_TRIAGED_MISSING = false; 427 private static final boolean DEBUG_APP_DATA = false; 428 429 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 430 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 431 432 private static final boolean HIDE_EPHEMERAL_APIS = false; 433 434 private static final boolean ENABLE_FREE_CACHE_V2 = 435 SystemProperties.getBoolean("fw.free_cache_v2", true); 436 437 private static final int RADIO_UID = Process.PHONE_UID; 438 private static final int LOG_UID = Process.LOG_UID; 439 private static final int NFC_UID = Process.NFC_UID; 440 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 441 private static final int SHELL_UID = Process.SHELL_UID; 442 443 // Suffix used during package installation when copying/moving 444 // package apks to install directory. 445 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 446 447 static final int SCAN_NO_DEX = 1<<0; 448 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 449 static final int SCAN_NEW_INSTALL = 1<<2; 450 static final int SCAN_UPDATE_TIME = 1<<3; 451 static final int SCAN_BOOTING = 1<<4; 452 static final int SCAN_TRUSTED_OVERLAY = 1<<5; 453 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 454 static final int SCAN_REQUIRE_KNOWN = 1<<7; 455 static final int SCAN_MOVE = 1<<8; 456 static final int SCAN_INITIAL = 1<<9; 457 static final int SCAN_CHECK_ONLY = 1<<10; 458 static final int SCAN_DONT_KILL_APP = 1<<11; 459 static final int SCAN_IGNORE_FROZEN = 1<<12; 460 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 461 static final int SCAN_AS_INSTANT_APP = 1<<14; 462 static final int SCAN_AS_FULL_APP = 1<<15; 463 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 464 static final int SCAN_AS_SYSTEM = 1<<17; 465 static final int SCAN_AS_PRIVILEGED = 1<<18; 466 static final int SCAN_AS_OEM = 1<<19; 467 static final int SCAN_AS_VENDOR = 1<<20; 468 469 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 470 SCAN_NO_DEX, 471 SCAN_UPDATE_SIGNATURE, 472 SCAN_NEW_INSTALL, 473 SCAN_UPDATE_TIME, 474 SCAN_BOOTING, 475 SCAN_TRUSTED_OVERLAY, 476 SCAN_DELETE_DATA_ON_FAILURES, 477 SCAN_REQUIRE_KNOWN, 478 SCAN_MOVE, 479 SCAN_INITIAL, 480 SCAN_CHECK_ONLY, 481 SCAN_DONT_KILL_APP, 482 SCAN_IGNORE_FROZEN, 483 SCAN_FIRST_BOOT_OR_UPGRADE, 484 SCAN_AS_INSTANT_APP, 485 SCAN_AS_FULL_APP, 486 SCAN_AS_VIRTUAL_PRELOAD, 487 }) 488 @Retention(RetentionPolicy.SOURCE) 489 public @interface ScanFlags {} 490 491 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 492 /** Extension of the compressed packages */ 493 public final static String COMPRESSED_EXTENSION = ".gz"; 494 /** Suffix of stub packages on the system partition */ 495 public final static String STUB_SUFFIX = "-Stub"; 496 497 private static final int[] EMPTY_INT_ARRAY = new int[0]; 498 499 private static final int TYPE_UNKNOWN = 0; 500 private static final int TYPE_ACTIVITY = 1; 501 private static final int TYPE_RECEIVER = 2; 502 private static final int TYPE_SERVICE = 3; 503 private static final int TYPE_PROVIDER = 4; 504 @IntDef(prefix = { "TYPE_" }, value = { 505 TYPE_UNKNOWN, 506 TYPE_ACTIVITY, 507 TYPE_RECEIVER, 508 TYPE_SERVICE, 509 TYPE_PROVIDER, 510 }) 511 @Retention(RetentionPolicy.SOURCE) 512 public @interface ComponentType {} 513 514 /** 515 * Timeout (in milliseconds) after which the watchdog should declare that 516 * our handler thread is wedged. The usual default for such things is one 517 * minute but we sometimes do very lengthy I/O operations on this thread, 518 * such as installing multi-gigabyte applications, so ours needs to be longer. 519 */ 520 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 521 522 /** 523 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 524 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 525 * settings entry if available, otherwise we use the hardcoded default. If it's been 526 * more than this long since the last fstrim, we force one during the boot sequence. 527 * 528 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 529 * one gets run at the next available charging+idle time. This final mandatory 530 * no-fstrim check kicks in only of the other scheduling criteria is never met. 531 */ 532 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 533 534 /** 535 * Whether verification is enabled by default. 536 */ 537 private static final boolean DEFAULT_VERIFY_ENABLE = true; 538 539 /** 540 * The default maximum time to wait for the verification agent to return in 541 * milliseconds. 542 */ 543 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 544 545 /** 546 * The default response for package verification timeout. 547 * 548 * This can be either PackageManager.VERIFICATION_ALLOW or 549 * PackageManager.VERIFICATION_REJECT. 550 */ 551 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 552 553 public static final String PLATFORM_PACKAGE_NAME = "android"; 554 555 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 556 557 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 558 DEFAULT_CONTAINER_PACKAGE, 559 "com.android.defcontainer.DefaultContainerService"); 560 561 private static final String KILL_APP_REASON_GIDS_CHANGED = 562 "permission grant or revoke changed gids"; 563 564 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 565 "permissions revoked"; 566 567 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 568 569 private static final String PACKAGE_SCHEME = "package"; 570 571 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 572 573 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 574 575 /** Canonical intent used to identify what counts as a "web browser" app */ 576 private static final Intent sBrowserIntent; 577 static { 578 sBrowserIntent = new Intent(); 579 sBrowserIntent.setAction(Intent.ACTION_VIEW); 580 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 581 sBrowserIntent.setData(Uri.parse("http:")); 582 } 583 584 /** 585 * The set of all protected actions [i.e. those actions for which a high priority 586 * intent filter is disallowed]. 587 */ 588 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 589 static { 590 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 591 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 592 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 593 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 594 } 595 596 // Compilation reasons. 597 public static final int REASON_FIRST_BOOT = 0; 598 public static final int REASON_BOOT = 1; 599 public static final int REASON_INSTALL = 2; 600 public static final int REASON_BACKGROUND_DEXOPT = 3; 601 public static final int REASON_AB_OTA = 4; 602 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 603 public static final int REASON_SHARED = 6; 604 605 public static final int REASON_LAST = REASON_SHARED; 606 607 /** 608 * Version number for the package parser cache. Increment this whenever the format or 609 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 610 */ 611 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 612 613 /** 614 * Whether the package parser cache is enabled. 615 */ 616 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 617 618 /** 619 * Permissions required in order to receive instant application lifecycle broadcasts. 620 */ 621 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 622 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 623 624 final ServiceThread mHandlerThread; 625 626 final PackageHandler mHandler; 627 628 private final ProcessLoggingHandler mProcessLoggingHandler; 629 630 /** 631 * Messages for {@link #mHandler} that need to wait for system ready before 632 * being dispatched. 633 */ 634 private ArrayList<Message> mPostSystemReadyMessages; 635 636 final int mSdkVersion = Build.VERSION.SDK_INT; 637 638 final Context mContext; 639 final boolean mFactoryTest; 640 final boolean mOnlyCore; 641 final DisplayMetrics mMetrics; 642 final int mDefParseFlags; 643 final String[] mSeparateProcesses; 644 final boolean mIsUpgrade; 645 final boolean mIsPreNUpgrade; 646 final boolean mIsPreNMR1Upgrade; 647 648 // Have we told the Activity Manager to whitelist the default container service by uid yet? 649 @GuardedBy("mPackages") 650 boolean mDefaultContainerWhitelisted = false; 651 652 @GuardedBy("mPackages") 653 private boolean mDexOptDialogShown; 654 655 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 656 // LOCK HELD. Can be called with mInstallLock held. 657 @GuardedBy("mInstallLock") 658 final Installer mInstaller; 659 660 /** Directory where installed applications are stored */ 661 private static final File sAppInstallDir = 662 new File(Environment.getDataDirectory(), "app"); 663 /** Directory where installed application's 32-bit native libraries are copied. */ 664 private static final File sAppLib32InstallDir = 665 new File(Environment.getDataDirectory(), "app-lib"); 666 /** Directory where code and non-resource assets of forward-locked applications are stored */ 667 private static final File sDrmAppPrivateInstallDir = 668 new File(Environment.getDataDirectory(), "app-private"); 669 670 // ---------------------------------------------------------------- 671 672 // Lock for state used when installing and doing other long running 673 // operations. Methods that must be called with this lock held have 674 // the suffix "LI". 675 final Object mInstallLock = new Object(); 676 677 // ---------------------------------------------------------------- 678 679 // Keys are String (package name), values are Package. This also serves 680 // as the lock for the global state. Methods that must be called with 681 // this lock held have the prefix "LP". 682 @GuardedBy("mPackages") 683 final ArrayMap<String, PackageParser.Package> mPackages = 684 new ArrayMap<String, PackageParser.Package>(); 685 686 final ArrayMap<String, Set<String>> mKnownCodebase = 687 new ArrayMap<String, Set<String>>(); 688 689 // Keys are isolated uids and values are the uid of the application 690 // that created the isolated proccess. 691 @GuardedBy("mPackages") 692 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 693 694 /** 695 * Tracks new system packages [received in an OTA] that we expect to 696 * find updated user-installed versions. Keys are package name, values 697 * are package location. 698 */ 699 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 700 /** 701 * Tracks high priority intent filters for protected actions. During boot, certain 702 * filter actions are protected and should never be allowed to have a high priority 703 * intent filter for them. However, there is one, and only one exception -- the 704 * setup wizard. It must be able to define a high priority intent filter for these 705 * actions to ensure there are no escapes from the wizard. We need to delay processing 706 * of these during boot as we need to look at all of the system packages in order 707 * to know which component is the setup wizard. 708 */ 709 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 710 /** 711 * Whether or not processing protected filters should be deferred. 712 */ 713 private boolean mDeferProtectedFilters = true; 714 715 /** 716 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 717 */ 718 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 719 /** 720 * Whether or not system app permissions should be promoted from install to runtime. 721 */ 722 boolean mPromoteSystemApps; 723 724 @GuardedBy("mPackages") 725 final Settings mSettings; 726 727 /** 728 * Set of package names that are currently "frozen", which means active 729 * surgery is being done on the code/data for that package. The platform 730 * will refuse to launch frozen packages to avoid race conditions. 731 * 732 * @see PackageFreezer 733 */ 734 @GuardedBy("mPackages") 735 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 736 737 final ProtectedPackages mProtectedPackages; 738 739 @GuardedBy("mLoadedVolumes") 740 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 741 742 boolean mFirstBoot; 743 744 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 745 746 @GuardedBy("mAvailableFeatures") 747 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 748 749 private final InstantAppRegistry mInstantAppRegistry; 750 751 @GuardedBy("mPackages") 752 int mChangedPackagesSequenceNumber; 753 /** 754 * List of changed [installed, removed or updated] packages. 755 * mapping from user id -> sequence number -> package name 756 */ 757 @GuardedBy("mPackages") 758 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 759 /** 760 * The sequence number of the last change to a package. 761 * mapping from user id -> package name -> sequence number 762 */ 763 @GuardedBy("mPackages") 764 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 765 766 @GuardedBy("mPackages") 767 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 768 769 class PackageParserCallback implements PackageParser.Callback { 770 @Override public final boolean hasFeature(String feature) { 771 return PackageManagerService.this.hasSystemFeature(feature, 0); 772 } 773 774 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 775 Collection<PackageParser.Package> allPackages, String targetPackageName) { 776 List<PackageParser.Package> overlayPackages = null; 777 for (PackageParser.Package p : allPackages) { 778 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 779 if (overlayPackages == null) { 780 overlayPackages = new ArrayList<PackageParser.Package>(); 781 } 782 overlayPackages.add(p); 783 } 784 } 785 if (overlayPackages != null) { 786 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 787 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 788 return p1.mOverlayPriority - p2.mOverlayPriority; 789 } 790 }; 791 Collections.sort(overlayPackages, cmp); 792 } 793 return overlayPackages; 794 } 795 796 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 797 String targetPackageName, String targetPath) { 798 if ("android".equals(targetPackageName)) { 799 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 800 // native AssetManager. 801 return null; 802 } 803 List<PackageParser.Package> overlayPackages = 804 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 805 if (overlayPackages == null || overlayPackages.isEmpty()) { 806 return null; 807 } 808 List<String> overlayPathList = null; 809 for (PackageParser.Package overlayPackage : overlayPackages) { 810 if (targetPath == null) { 811 if (overlayPathList == null) { 812 overlayPathList = new ArrayList<String>(); 813 } 814 overlayPathList.add(overlayPackage.baseCodePath); 815 continue; 816 } 817 818 try { 819 // Creates idmaps for system to parse correctly the Android manifest of the 820 // target package. 821 // 822 // OverlayManagerService will update each of them with a correct gid from its 823 // target package app id. 824 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 825 UserHandle.getSharedAppGid( 826 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 827 if (overlayPathList == null) { 828 overlayPathList = new ArrayList<String>(); 829 } 830 overlayPathList.add(overlayPackage.baseCodePath); 831 } catch (InstallerException e) { 832 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 833 overlayPackage.baseCodePath); 834 } 835 } 836 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 837 } 838 839 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 840 synchronized (mPackages) { 841 return getStaticOverlayPathsLocked( 842 mPackages.values(), targetPackageName, targetPath); 843 } 844 } 845 846 @Override public final String[] getOverlayApks(String targetPackageName) { 847 return getStaticOverlayPaths(targetPackageName, null); 848 } 849 850 @Override public final String[] getOverlayPaths(String targetPackageName, 851 String targetPath) { 852 return getStaticOverlayPaths(targetPackageName, targetPath); 853 } 854 } 855 856 class ParallelPackageParserCallback extends PackageParserCallback { 857 List<PackageParser.Package> mOverlayPackages = null; 858 859 void findStaticOverlayPackages() { 860 synchronized (mPackages) { 861 for (PackageParser.Package p : mPackages.values()) { 862 if (p.mIsStaticOverlay) { 863 if (mOverlayPackages == null) { 864 mOverlayPackages = new ArrayList<PackageParser.Package>(); 865 } 866 mOverlayPackages.add(p); 867 } 868 } 869 } 870 } 871 872 @Override 873 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 874 // We can trust mOverlayPackages without holding mPackages because package uninstall 875 // can't happen while running parallel parsing. 876 // Moreover holding mPackages on each parsing thread causes dead-lock. 877 return mOverlayPackages == null ? null : 878 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 879 } 880 } 881 882 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 883 final ParallelPackageParserCallback mParallelPackageParserCallback = 884 new ParallelPackageParserCallback(); 885 886 public static final class SharedLibraryEntry { 887 public final @Nullable String path; 888 public final @Nullable String apk; 889 public final @NonNull SharedLibraryInfo info; 890 891 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 892 String declaringPackageName, long declaringPackageVersionCode) { 893 path = _path; 894 apk = _apk; 895 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 896 declaringPackageName, declaringPackageVersionCode), null); 897 } 898 } 899 900 // Currently known shared libraries. 901 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 902 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 903 new ArrayMap<>(); 904 905 // All available activities, for your resolving pleasure. 906 final ActivityIntentResolver mActivities = 907 new ActivityIntentResolver(); 908 909 // All available receivers, for your resolving pleasure. 910 final ActivityIntentResolver mReceivers = 911 new ActivityIntentResolver(); 912 913 // All available services, for your resolving pleasure. 914 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 915 916 // All available providers, for your resolving pleasure. 917 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 918 919 // Mapping from provider base names (first directory in content URI codePath) 920 // to the provider information. 921 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 922 new ArrayMap<String, PackageParser.Provider>(); 923 924 // Mapping from instrumentation class names to info about them. 925 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 926 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 927 928 // Packages whose data we have transfered into another package, thus 929 // should no longer exist. 930 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 931 932 // Broadcast actions that are only available to the system. 933 @GuardedBy("mProtectedBroadcasts") 934 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 935 936 /** List of packages waiting for verification. */ 937 final SparseArray<PackageVerificationState> mPendingVerification 938 = new SparseArray<PackageVerificationState>(); 939 940 final PackageInstallerService mInstallerService; 941 942 final ArtManagerService mArtManagerService; 943 944 private final PackageDexOptimizer mPackageDexOptimizer; 945 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 946 // is used by other apps). 947 private final DexManager mDexManager; 948 949 private AtomicInteger mNextMoveId = new AtomicInteger(); 950 private final MoveCallbacks mMoveCallbacks; 951 952 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 953 954 // Cache of users who need badging. 955 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 956 957 /** Token for keys in mPendingVerification. */ 958 private int mPendingVerificationToken = 0; 959 960 volatile boolean mSystemReady; 961 volatile boolean mSafeMode; 962 volatile boolean mHasSystemUidErrors; 963 private volatile boolean mEphemeralAppsDisabled; 964 965 ApplicationInfo mAndroidApplication; 966 final ActivityInfo mResolveActivity = new ActivityInfo(); 967 final ResolveInfo mResolveInfo = new ResolveInfo(); 968 ComponentName mResolveComponentName; 969 PackageParser.Package mPlatformPackage; 970 ComponentName mCustomResolverComponentName; 971 972 boolean mResolverReplaced = false; 973 974 private final @Nullable ComponentName mIntentFilterVerifierComponent; 975 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 976 977 private int mIntentFilterVerificationToken = 0; 978 979 /** The service connection to the ephemeral resolver */ 980 final EphemeralResolverConnection mInstantAppResolverConnection; 981 /** Component used to show resolver settings for Instant Apps */ 982 final ComponentName mInstantAppResolverSettingsComponent; 983 984 /** Activity used to install instant applications */ 985 ActivityInfo mInstantAppInstallerActivity; 986 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 987 988 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 989 = new SparseArray<IntentFilterVerificationState>(); 990 991 // TODO remove this and go through mPermissonManager directly 992 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 993 private final PermissionManagerInternal mPermissionManager; 994 995 // List of packages names to keep cached, even if they are uninstalled for all users 996 private List<String> mKeepUninstalledPackages; 997 998 private UserManagerInternal mUserManagerInternal; 999 1000 private DeviceIdleController.LocalService mDeviceIdleController; 1001 1002 private File mCacheDir; 1003 1004 private Future<?> mPrepareAppDataFuture; 1005 1006 private static class IFVerificationParams { 1007 PackageParser.Package pkg; 1008 boolean replacing; 1009 int userId; 1010 int verifierUid; 1011 1012 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1013 int _userId, int _verifierUid) { 1014 pkg = _pkg; 1015 replacing = _replacing; 1016 userId = _userId; 1017 replacing = _replacing; 1018 verifierUid = _verifierUid; 1019 } 1020 } 1021 1022 private interface IntentFilterVerifier<T extends IntentFilter> { 1023 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1024 T filter, String packageName); 1025 void startVerifications(int userId); 1026 void receiveVerificationResponse(int verificationId); 1027 } 1028 1029 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1030 private Context mContext; 1031 private ComponentName mIntentFilterVerifierComponent; 1032 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1033 1034 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1035 mContext = context; 1036 mIntentFilterVerifierComponent = verifierComponent; 1037 } 1038 1039 private String getDefaultScheme() { 1040 return IntentFilter.SCHEME_HTTPS; 1041 } 1042 1043 @Override 1044 public void startVerifications(int userId) { 1045 // Launch verifications requests 1046 int count = mCurrentIntentFilterVerifications.size(); 1047 for (int n=0; n<count; n++) { 1048 int verificationId = mCurrentIntentFilterVerifications.get(n); 1049 final IntentFilterVerificationState ivs = 1050 mIntentFilterVerificationStates.get(verificationId); 1051 1052 String packageName = ivs.getPackageName(); 1053 1054 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1055 final int filterCount = filters.size(); 1056 ArraySet<String> domainsSet = new ArraySet<>(); 1057 for (int m=0; m<filterCount; m++) { 1058 PackageParser.ActivityIntentInfo filter = filters.get(m); 1059 domainsSet.addAll(filter.getHostsList()); 1060 } 1061 synchronized (mPackages) { 1062 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1063 packageName, domainsSet) != null) { 1064 scheduleWriteSettingsLocked(); 1065 } 1066 } 1067 sendVerificationRequest(verificationId, ivs); 1068 } 1069 mCurrentIntentFilterVerifications.clear(); 1070 } 1071 1072 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1073 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1074 verificationIntent.putExtra( 1075 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1076 verificationId); 1077 verificationIntent.putExtra( 1078 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1079 getDefaultScheme()); 1080 verificationIntent.putExtra( 1081 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1082 ivs.getHostsString()); 1083 verificationIntent.putExtra( 1084 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1085 ivs.getPackageName()); 1086 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1087 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1088 1089 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1090 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1091 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1092 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1093 1094 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1095 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1096 "Sending IntentFilter verification broadcast"); 1097 } 1098 1099 public void receiveVerificationResponse(int verificationId) { 1100 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1101 1102 final boolean verified = ivs.isVerified(); 1103 1104 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1105 final int count = filters.size(); 1106 if (DEBUG_DOMAIN_VERIFICATION) { 1107 Slog.i(TAG, "Received verification response " + verificationId 1108 + " for " + count + " filters, verified=" + verified); 1109 } 1110 for (int n=0; n<count; n++) { 1111 PackageParser.ActivityIntentInfo filter = filters.get(n); 1112 filter.setVerified(verified); 1113 1114 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1115 + " verified with result:" + verified + " and hosts:" 1116 + ivs.getHostsString()); 1117 } 1118 1119 mIntentFilterVerificationStates.remove(verificationId); 1120 1121 final String packageName = ivs.getPackageName(); 1122 IntentFilterVerificationInfo ivi = null; 1123 1124 synchronized (mPackages) { 1125 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1126 } 1127 if (ivi == null) { 1128 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1129 + verificationId + " packageName:" + packageName); 1130 return; 1131 } 1132 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1133 "Updating IntentFilterVerificationInfo for package " + packageName 1134 +" verificationId:" + verificationId); 1135 1136 synchronized (mPackages) { 1137 if (verified) { 1138 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1139 } else { 1140 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1141 } 1142 scheduleWriteSettingsLocked(); 1143 1144 final int userId = ivs.getUserId(); 1145 if (userId != UserHandle.USER_ALL) { 1146 final int userStatus = 1147 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1148 1149 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1150 boolean needUpdate = false; 1151 1152 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1153 // already been set by the User thru the Disambiguation dialog 1154 switch (userStatus) { 1155 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1156 if (verified) { 1157 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1158 } else { 1159 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1160 } 1161 needUpdate = true; 1162 break; 1163 1164 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1165 if (verified) { 1166 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1167 needUpdate = true; 1168 } 1169 break; 1170 1171 default: 1172 // Nothing to do 1173 } 1174 1175 if (needUpdate) { 1176 mSettings.updateIntentFilterVerificationStatusLPw( 1177 packageName, updatedStatus, userId); 1178 scheduleWritePackageRestrictionsLocked(userId); 1179 } 1180 } 1181 } 1182 } 1183 1184 @Override 1185 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1186 ActivityIntentInfo filter, String packageName) { 1187 if (!hasValidDomains(filter)) { 1188 return false; 1189 } 1190 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1191 if (ivs == null) { 1192 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1193 packageName); 1194 } 1195 if (DEBUG_DOMAIN_VERIFICATION) { 1196 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1197 } 1198 ivs.addFilter(filter); 1199 return true; 1200 } 1201 1202 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1203 int userId, int verificationId, String packageName) { 1204 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1205 verifierUid, userId, packageName); 1206 ivs.setPendingState(); 1207 synchronized (mPackages) { 1208 mIntentFilterVerificationStates.append(verificationId, ivs); 1209 mCurrentIntentFilterVerifications.add(verificationId); 1210 } 1211 return ivs; 1212 } 1213 } 1214 1215 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1216 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1217 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1218 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1219 } 1220 1221 // Set of pending broadcasts for aggregating enable/disable of components. 1222 static class PendingPackageBroadcasts { 1223 // for each user id, a map of <package name -> components within that package> 1224 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1225 1226 public PendingPackageBroadcasts() { 1227 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1228 } 1229 1230 public ArrayList<String> get(int userId, String packageName) { 1231 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1232 return packages.get(packageName); 1233 } 1234 1235 public void put(int userId, String packageName, ArrayList<String> components) { 1236 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1237 packages.put(packageName, components); 1238 } 1239 1240 public void remove(int userId, String packageName) { 1241 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1242 if (packages != null) { 1243 packages.remove(packageName); 1244 } 1245 } 1246 1247 public void remove(int userId) { 1248 mUidMap.remove(userId); 1249 } 1250 1251 public int userIdCount() { 1252 return mUidMap.size(); 1253 } 1254 1255 public int userIdAt(int n) { 1256 return mUidMap.keyAt(n); 1257 } 1258 1259 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1260 return mUidMap.get(userId); 1261 } 1262 1263 public int size() { 1264 // total number of pending broadcast entries across all userIds 1265 int num = 0; 1266 for (int i = 0; i< mUidMap.size(); i++) { 1267 num += mUidMap.valueAt(i).size(); 1268 } 1269 return num; 1270 } 1271 1272 public void clear() { 1273 mUidMap.clear(); 1274 } 1275 1276 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1277 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1278 if (map == null) { 1279 map = new ArrayMap<String, ArrayList<String>>(); 1280 mUidMap.put(userId, map); 1281 } 1282 return map; 1283 } 1284 } 1285 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1286 1287 // Service Connection to remote media container service to copy 1288 // package uri's from external media onto secure containers 1289 // or internal storage. 1290 private IMediaContainerService mContainerService = null; 1291 1292 static final int SEND_PENDING_BROADCAST = 1; 1293 static final int MCS_BOUND = 3; 1294 static final int END_COPY = 4; 1295 static final int INIT_COPY = 5; 1296 static final int MCS_UNBIND = 6; 1297 static final int START_CLEANING_PACKAGE = 7; 1298 static final int FIND_INSTALL_LOC = 8; 1299 static final int POST_INSTALL = 9; 1300 static final int MCS_RECONNECT = 10; 1301 static final int MCS_GIVE_UP = 11; 1302 static final int WRITE_SETTINGS = 13; 1303 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1304 static final int PACKAGE_VERIFIED = 15; 1305 static final int CHECK_PENDING_VERIFICATION = 16; 1306 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1307 static final int INTENT_FILTER_VERIFIED = 18; 1308 static final int WRITE_PACKAGE_LIST = 19; 1309 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1310 1311 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1312 1313 // Delay time in millisecs 1314 static final int BROADCAST_DELAY = 10 * 1000; 1315 1316 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1317 2 * 60 * 60 * 1000L; /* two hours */ 1318 1319 static UserManagerService sUserManager; 1320 1321 // Stores a list of users whose package restrictions file needs to be updated 1322 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1323 1324 final private DefaultContainerConnection mDefContainerConn = 1325 new DefaultContainerConnection(); 1326 class DefaultContainerConnection implements ServiceConnection { 1327 public void onServiceConnected(ComponentName name, IBinder service) { 1328 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1329 final IMediaContainerService imcs = IMediaContainerService.Stub 1330 .asInterface(Binder.allowBlocking(service)); 1331 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1332 } 1333 1334 public void onServiceDisconnected(ComponentName name) { 1335 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1336 } 1337 } 1338 1339 // Recordkeeping of restore-after-install operations that are currently in flight 1340 // between the Package Manager and the Backup Manager 1341 static class PostInstallData { 1342 public InstallArgs args; 1343 public PackageInstalledInfo res; 1344 1345 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1346 args = _a; 1347 res = _r; 1348 } 1349 } 1350 1351 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1352 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1353 1354 // XML tags for backup/restore of various bits of state 1355 private static final String TAG_PREFERRED_BACKUP = "pa"; 1356 private static final String TAG_DEFAULT_APPS = "da"; 1357 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1358 1359 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1360 private static final String TAG_ALL_GRANTS = "rt-grants"; 1361 private static final String TAG_GRANT = "grant"; 1362 private static final String ATTR_PACKAGE_NAME = "pkg"; 1363 1364 private static final String TAG_PERMISSION = "perm"; 1365 private static final String ATTR_PERMISSION_NAME = "name"; 1366 private static final String ATTR_IS_GRANTED = "g"; 1367 private static final String ATTR_USER_SET = "set"; 1368 private static final String ATTR_USER_FIXED = "fixed"; 1369 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1370 1371 // System/policy permission grants are not backed up 1372 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1373 FLAG_PERMISSION_POLICY_FIXED 1374 | FLAG_PERMISSION_SYSTEM_FIXED 1375 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1376 1377 // And we back up these user-adjusted states 1378 private static final int USER_RUNTIME_GRANT_MASK = 1379 FLAG_PERMISSION_USER_SET 1380 | FLAG_PERMISSION_USER_FIXED 1381 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1382 1383 final @Nullable String mRequiredVerifierPackage; 1384 final @NonNull String mRequiredInstallerPackage; 1385 final @NonNull String mRequiredUninstallerPackage; 1386 final @Nullable String mSetupWizardPackage; 1387 final @Nullable String mStorageManagerPackage; 1388 final @NonNull String mServicesSystemSharedLibraryPackageName; 1389 final @NonNull String mSharedSystemSharedLibraryPackageName; 1390 1391 private final PackageUsage mPackageUsage = new PackageUsage(); 1392 private final CompilerStats mCompilerStats = new CompilerStats(); 1393 1394 class PackageHandler extends Handler { 1395 private boolean mBound = false; 1396 final ArrayList<HandlerParams> mPendingInstalls = 1397 new ArrayList<HandlerParams>(); 1398 1399 private boolean connectToService() { 1400 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1401 " DefaultContainerService"); 1402 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1403 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1404 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1405 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 mBound = true; 1408 return true; 1409 } 1410 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1411 return false; 1412 } 1413 1414 private void disconnectService() { 1415 mContainerService = null; 1416 mBound = false; 1417 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1418 mContext.unbindService(mDefContainerConn); 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1420 } 1421 1422 PackageHandler(Looper looper) { 1423 super(looper); 1424 } 1425 1426 public void handleMessage(Message msg) { 1427 try { 1428 doHandleMessage(msg); 1429 } finally { 1430 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1431 } 1432 } 1433 1434 void doHandleMessage(Message msg) { 1435 switch (msg.what) { 1436 case INIT_COPY: { 1437 HandlerParams params = (HandlerParams) msg.obj; 1438 int idx = mPendingInstalls.size(); 1439 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1440 // If a bind was already initiated we dont really 1441 // need to do anything. The pending install 1442 // will be processed later on. 1443 if (!mBound) { 1444 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1445 System.identityHashCode(mHandler)); 1446 // If this is the only one pending we might 1447 // have to bind to the service again. 1448 if (!connectToService()) { 1449 Slog.e(TAG, "Failed to bind to media container service"); 1450 params.serviceError(); 1451 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1452 System.identityHashCode(mHandler)); 1453 if (params.traceMethod != null) { 1454 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1455 params.traceCookie); 1456 } 1457 return; 1458 } else { 1459 // Once we bind to the service, the first 1460 // pending request will be processed. 1461 mPendingInstalls.add(idx, params); 1462 } 1463 } else { 1464 mPendingInstalls.add(idx, params); 1465 // Already bound to the service. Just make 1466 // sure we trigger off processing the first request. 1467 if (idx == 0) { 1468 mHandler.sendEmptyMessage(MCS_BOUND); 1469 } 1470 } 1471 break; 1472 } 1473 case MCS_BOUND: { 1474 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1475 if (msg.obj != null) { 1476 mContainerService = (IMediaContainerService) msg.obj; 1477 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1478 System.identityHashCode(mHandler)); 1479 } 1480 if (mContainerService == null) { 1481 if (!mBound) { 1482 // Something seriously wrong since we are not bound and we are not 1483 // waiting for connection. Bail out. 1484 Slog.e(TAG, "Cannot bind to media container service"); 1485 for (HandlerParams params : mPendingInstalls) { 1486 // Indicate service bind error 1487 params.serviceError(); 1488 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1489 System.identityHashCode(params)); 1490 if (params.traceMethod != null) { 1491 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1492 params.traceMethod, params.traceCookie); 1493 } 1494 return; 1495 } 1496 mPendingInstalls.clear(); 1497 } else { 1498 Slog.w(TAG, "Waiting to connect to media container service"); 1499 } 1500 } else if (mPendingInstalls.size() > 0) { 1501 HandlerParams params = mPendingInstalls.get(0); 1502 if (params != null) { 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1504 System.identityHashCode(params)); 1505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1506 if (params.startCopy()) { 1507 // We are done... look for more work or to 1508 // go idle. 1509 if (DEBUG_SD_INSTALL) Log.i(TAG, 1510 "Checking for more work or unbind..."); 1511 // Delete pending install 1512 if (mPendingInstalls.size() > 0) { 1513 mPendingInstalls.remove(0); 1514 } 1515 if (mPendingInstalls.size() == 0) { 1516 if (mBound) { 1517 if (DEBUG_SD_INSTALL) Log.i(TAG, 1518 "Posting delayed MCS_UNBIND"); 1519 removeMessages(MCS_UNBIND); 1520 Message ubmsg = obtainMessage(MCS_UNBIND); 1521 // Unbind after a little delay, to avoid 1522 // continual thrashing. 1523 sendMessageDelayed(ubmsg, 10000); 1524 } 1525 } else { 1526 // There are more pending requests in queue. 1527 // Just post MCS_BOUND message to trigger processing 1528 // of next pending install. 1529 if (DEBUG_SD_INSTALL) Log.i(TAG, 1530 "Posting MCS_BOUND for next work"); 1531 mHandler.sendEmptyMessage(MCS_BOUND); 1532 } 1533 } 1534 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1535 } 1536 } else { 1537 // Should never happen ideally. 1538 Slog.w(TAG, "Empty queue"); 1539 } 1540 break; 1541 } 1542 case MCS_RECONNECT: { 1543 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1544 if (mPendingInstalls.size() > 0) { 1545 if (mBound) { 1546 disconnectService(); 1547 } 1548 if (!connectToService()) { 1549 Slog.e(TAG, "Failed to bind to media container service"); 1550 for (HandlerParams params : mPendingInstalls) { 1551 // Indicate service bind error 1552 params.serviceError(); 1553 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1554 System.identityHashCode(params)); 1555 } 1556 mPendingInstalls.clear(); 1557 } 1558 } 1559 break; 1560 } 1561 case MCS_UNBIND: { 1562 // If there is no actual work left, then time to unbind. 1563 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1564 1565 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1566 if (mBound) { 1567 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1568 1569 disconnectService(); 1570 } 1571 } else if (mPendingInstalls.size() > 0) { 1572 // There are more pending requests in queue. 1573 // Just post MCS_BOUND message to trigger processing 1574 // of next pending install. 1575 mHandler.sendEmptyMessage(MCS_BOUND); 1576 } 1577 1578 break; 1579 } 1580 case MCS_GIVE_UP: { 1581 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1582 HandlerParams params = mPendingInstalls.remove(0); 1583 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1584 System.identityHashCode(params)); 1585 break; 1586 } 1587 case SEND_PENDING_BROADCAST: { 1588 String packages[]; 1589 ArrayList<String> components[]; 1590 int size = 0; 1591 int uids[]; 1592 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1593 synchronized (mPackages) { 1594 if (mPendingBroadcasts == null) { 1595 return; 1596 } 1597 size = mPendingBroadcasts.size(); 1598 if (size <= 0) { 1599 // Nothing to be done. Just return 1600 return; 1601 } 1602 packages = new String[size]; 1603 components = new ArrayList[size]; 1604 uids = new int[size]; 1605 int i = 0; // filling out the above arrays 1606 1607 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1608 int packageUserId = mPendingBroadcasts.userIdAt(n); 1609 Iterator<Map.Entry<String, ArrayList<String>>> it 1610 = mPendingBroadcasts.packagesForUserId(packageUserId) 1611 .entrySet().iterator(); 1612 while (it.hasNext() && i < size) { 1613 Map.Entry<String, ArrayList<String>> ent = it.next(); 1614 packages[i] = ent.getKey(); 1615 components[i] = ent.getValue(); 1616 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1617 uids[i] = (ps != null) 1618 ? UserHandle.getUid(packageUserId, ps.appId) 1619 : -1; 1620 i++; 1621 } 1622 } 1623 size = i; 1624 mPendingBroadcasts.clear(); 1625 } 1626 // Send broadcasts 1627 for (int i = 0; i < size; i++) { 1628 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1629 } 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1631 break; 1632 } 1633 case START_CLEANING_PACKAGE: { 1634 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1635 final String packageName = (String)msg.obj; 1636 final int userId = msg.arg1; 1637 final boolean andCode = msg.arg2 != 0; 1638 synchronized (mPackages) { 1639 if (userId == UserHandle.USER_ALL) { 1640 int[] users = sUserManager.getUserIds(); 1641 for (int user : users) { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(user, packageName, andCode)); 1644 } 1645 } else { 1646 mSettings.addPackageToCleanLPw( 1647 new PackageCleanItem(userId, packageName, andCode)); 1648 } 1649 } 1650 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1651 startCleaningPackages(); 1652 } break; 1653 case POST_INSTALL: { 1654 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1655 1656 PostInstallData data = mRunningInstalls.get(msg.arg1); 1657 final boolean didRestore = (msg.arg2 != 0); 1658 mRunningInstalls.delete(msg.arg1); 1659 1660 if (data != null) { 1661 InstallArgs args = data.args; 1662 PackageInstalledInfo parentRes = data.res; 1663 1664 final boolean grantPermissions = (args.installFlags 1665 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1666 final boolean killApp = (args.installFlags 1667 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1668 final boolean virtualPreload = ((args.installFlags 1669 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1670 final String[] grantedPermissions = args.installGrantPermissions; 1671 1672 // Handle the parent package 1673 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1674 virtualPreload, grantedPermissions, didRestore, 1675 args.installerPackageName, args.observer); 1676 1677 // Handle the child packages 1678 final int childCount = (parentRes.addedChildPackages != null) 1679 ? parentRes.addedChildPackages.size() : 0; 1680 for (int i = 0; i < childCount; i++) { 1681 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1682 handlePackagePostInstall(childRes, grantPermissions, killApp, 1683 virtualPreload, grantedPermissions, false /*didRestore*/, 1684 args.installerPackageName, args.observer); 1685 } 1686 1687 // Log tracing if needed 1688 if (args.traceMethod != null) { 1689 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1690 args.traceCookie); 1691 } 1692 } else { 1693 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1694 } 1695 1696 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1697 } break; 1698 case WRITE_SETTINGS: { 1699 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1700 synchronized (mPackages) { 1701 removeMessages(WRITE_SETTINGS); 1702 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1703 mSettings.writeLPr(); 1704 mDirtyUsers.clear(); 1705 } 1706 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1707 } break; 1708 case WRITE_PACKAGE_RESTRICTIONS: { 1709 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1710 synchronized (mPackages) { 1711 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1712 for (int userId : mDirtyUsers) { 1713 mSettings.writePackageRestrictionsLPr(userId); 1714 } 1715 mDirtyUsers.clear(); 1716 } 1717 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1718 } break; 1719 case WRITE_PACKAGE_LIST: { 1720 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1721 synchronized (mPackages) { 1722 removeMessages(WRITE_PACKAGE_LIST); 1723 mSettings.writePackageListLPr(msg.arg1); 1724 } 1725 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1726 } break; 1727 case CHECK_PENDING_VERIFICATION: { 1728 final int verificationId = msg.arg1; 1729 final PackageVerificationState state = mPendingVerification.get(verificationId); 1730 1731 if ((state != null) && !state.timeoutExtended()) { 1732 final InstallArgs args = state.getInstallArgs(); 1733 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1734 1735 Slog.i(TAG, "Verification timed out for " + originUri); 1736 mPendingVerification.remove(verificationId); 1737 1738 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1739 1740 final UserHandle user = args.getUser(); 1741 if (getDefaultVerificationResponse(user) 1742 == PackageManager.VERIFICATION_ALLOW) { 1743 Slog.i(TAG, "Continuing with installation of " + originUri); 1744 state.setVerifierResponse(Binder.getCallingUid(), 1745 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1746 broadcastPackageVerified(verificationId, originUri, 1747 PackageManager.VERIFICATION_ALLOW, user); 1748 try { 1749 ret = args.copyApk(mContainerService, true); 1750 } catch (RemoteException e) { 1751 Slog.e(TAG, "Could not contact the ContainerService"); 1752 } 1753 } else { 1754 broadcastPackageVerified(verificationId, originUri, 1755 PackageManager.VERIFICATION_REJECT, user); 1756 } 1757 1758 Trace.asyncTraceEnd( 1759 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1760 1761 processPendingInstall(args, ret); 1762 mHandler.sendEmptyMessage(MCS_UNBIND); 1763 } 1764 break; 1765 } 1766 case PACKAGE_VERIFIED: { 1767 final int verificationId = msg.arg1; 1768 1769 final PackageVerificationState state = mPendingVerification.get(verificationId); 1770 if (state == null) { 1771 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1772 break; 1773 } 1774 1775 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1776 1777 state.setVerifierResponse(response.callerUid, response.code); 1778 1779 if (state.isVerificationComplete()) { 1780 mPendingVerification.remove(verificationId); 1781 1782 final InstallArgs args = state.getInstallArgs(); 1783 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1784 1785 int ret; 1786 if (state.isInstallAllowed()) { 1787 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1788 broadcastPackageVerified(verificationId, originUri, 1789 response.code, state.getInstallArgs().getUser()); 1790 try { 1791 ret = args.copyApk(mContainerService, true); 1792 } catch (RemoteException e) { 1793 Slog.e(TAG, "Could not contact the ContainerService"); 1794 } 1795 } else { 1796 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1797 } 1798 1799 Trace.asyncTraceEnd( 1800 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1801 1802 processPendingInstall(args, ret); 1803 mHandler.sendEmptyMessage(MCS_UNBIND); 1804 } 1805 1806 break; 1807 } 1808 case START_INTENT_FILTER_VERIFICATIONS: { 1809 IFVerificationParams params = (IFVerificationParams) msg.obj; 1810 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1811 params.replacing, params.pkg); 1812 break; 1813 } 1814 case INTENT_FILTER_VERIFIED: { 1815 final int verificationId = msg.arg1; 1816 1817 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1818 verificationId); 1819 if (state == null) { 1820 Slog.w(TAG, "Invalid IntentFilter verification token " 1821 + verificationId + " received"); 1822 break; 1823 } 1824 1825 final int userId = state.getUserId(); 1826 1827 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1828 "Processing IntentFilter verification with token:" 1829 + verificationId + " and userId:" + userId); 1830 1831 final IntentFilterVerificationResponse response = 1832 (IntentFilterVerificationResponse) msg.obj; 1833 1834 state.setVerifierResponse(response.callerUid, response.code); 1835 1836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1837 "IntentFilter verification with token:" + verificationId 1838 + " and userId:" + userId 1839 + " is settings verifier response with response code:" 1840 + response.code); 1841 1842 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1843 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1844 + response.getFailedDomainsString()); 1845 } 1846 1847 if (state.isVerificationComplete()) { 1848 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1849 } else { 1850 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1851 "IntentFilter verification with token:" + verificationId 1852 + " was not said to be complete"); 1853 } 1854 1855 break; 1856 } 1857 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1858 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1859 mInstantAppResolverConnection, 1860 (InstantAppRequest) msg.obj, 1861 mInstantAppInstallerActivity, 1862 mHandler); 1863 } 1864 } 1865 } 1866 } 1867 1868 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1869 @Override 1870 public void onGidsChanged(int appId, int userId) { 1871 mHandler.post(new Runnable() { 1872 @Override 1873 public void run() { 1874 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1875 } 1876 }); 1877 } 1878 @Override 1879 public void onPermissionGranted(int uid, int userId) { 1880 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1881 1882 // Not critical; if this is lost, the application has to request again. 1883 synchronized (mPackages) { 1884 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1885 } 1886 } 1887 @Override 1888 public void onInstallPermissionGranted() { 1889 synchronized (mPackages) { 1890 scheduleWriteSettingsLocked(); 1891 } 1892 } 1893 @Override 1894 public void onPermissionRevoked(int uid, int userId) { 1895 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1896 1897 synchronized (mPackages) { 1898 // Critical; after this call the application should never have the permission 1899 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1900 } 1901 1902 final int appId = UserHandle.getAppId(uid); 1903 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1904 } 1905 @Override 1906 public void onInstallPermissionRevoked() { 1907 synchronized (mPackages) { 1908 scheduleWriteSettingsLocked(); 1909 } 1910 } 1911 @Override 1912 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1913 synchronized (mPackages) { 1914 for (int userId : updatedUserIds) { 1915 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1916 } 1917 } 1918 } 1919 @Override 1920 public void onInstallPermissionUpdated() { 1921 synchronized (mPackages) { 1922 scheduleWriteSettingsLocked(); 1923 } 1924 } 1925 @Override 1926 public void onPermissionRemoved() { 1927 synchronized (mPackages) { 1928 mSettings.writeLPr(); 1929 } 1930 } 1931 }; 1932 1933 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1934 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1935 boolean launchedForRestore, String installerPackage, 1936 IPackageInstallObserver2 installObserver) { 1937 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1938 // Send the removed broadcasts 1939 if (res.removedInfo != null) { 1940 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1941 } 1942 1943 // Now that we successfully installed the package, grant runtime 1944 // permissions if requested before broadcasting the install. Also 1945 // for legacy apps in permission review mode we clear the permission 1946 // review flag which is used to emulate runtime permissions for 1947 // legacy apps. 1948 if (grantPermissions) { 1949 final int callingUid = Binder.getCallingUid(); 1950 mPermissionManager.grantRequestedRuntimePermissions( 1951 res.pkg, res.newUsers, grantedPermissions, callingUid, 1952 mPermissionCallback); 1953 } 1954 1955 final boolean update = res.removedInfo != null 1956 && res.removedInfo.removedPackage != null; 1957 final String installerPackageName = 1958 res.installerPackageName != null 1959 ? res.installerPackageName 1960 : res.removedInfo != null 1961 ? res.removedInfo.installerPackageName 1962 : null; 1963 1964 // If this is the first time we have child packages for a disabled privileged 1965 // app that had no children, we grant requested runtime permissions to the new 1966 // children if the parent on the system image had them already granted. 1967 if (res.pkg.parentPackage != null) { 1968 final int callingUid = Binder.getCallingUid(); 1969 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1970 res.pkg, callingUid, mPermissionCallback); 1971 } 1972 1973 synchronized (mPackages) { 1974 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1975 } 1976 1977 final String packageName = res.pkg.applicationInfo.packageName; 1978 1979 // Determine the set of users who are adding this package for 1980 // the first time vs. those who are seeing an update. 1981 int[] firstUserIds = EMPTY_INT_ARRAY; 1982 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1983 int[] updateUserIds = EMPTY_INT_ARRAY; 1984 int[] instantUserIds = EMPTY_INT_ARRAY; 1985 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1986 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1987 for (int newUser : res.newUsers) { 1988 final boolean isInstantApp = ps.getInstantApp(newUser); 1989 if (allNewUsers) { 1990 if (isInstantApp) { 1991 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1992 } else { 1993 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1994 } 1995 continue; 1996 } 1997 boolean isNew = true; 1998 for (int origUser : res.origUsers) { 1999 if (origUser == newUser) { 2000 isNew = false; 2001 break; 2002 } 2003 } 2004 if (isNew) { 2005 if (isInstantApp) { 2006 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2007 } else { 2008 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2009 } 2010 } else { 2011 if (isInstantApp) { 2012 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2013 } else { 2014 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2015 } 2016 } 2017 } 2018 2019 // Send installed broadcasts if the package is not a static shared lib. 2020 if (res.pkg.staticSharedLibName == null) { 2021 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2022 2023 // Send added for users that see the package for the first time 2024 // sendPackageAddedForNewUsers also deals with system apps 2025 int appId = UserHandle.getAppId(res.uid); 2026 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2027 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2028 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2029 2030 // Send added for users that don't see the package for the first time 2031 Bundle extras = new Bundle(1); 2032 extras.putInt(Intent.EXTRA_UID, res.uid); 2033 if (update) { 2034 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2035 } 2036 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2037 extras, 0 /*flags*/, 2038 null /*targetPackage*/, null /*finishedReceiver*/, 2039 updateUserIds, instantUserIds); 2040 if (installerPackageName != null) { 2041 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2042 extras, 0 /*flags*/, 2043 installerPackageName, null /*finishedReceiver*/, 2044 updateUserIds, instantUserIds); 2045 } 2046 2047 // Send replaced for users that don't see the package for the first time 2048 if (update) { 2049 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2050 packageName, extras, 0 /*flags*/, 2051 null /*targetPackage*/, null /*finishedReceiver*/, 2052 updateUserIds, instantUserIds); 2053 if (installerPackageName != null) { 2054 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2055 extras, 0 /*flags*/, 2056 installerPackageName, null /*finishedReceiver*/, 2057 updateUserIds, instantUserIds); 2058 } 2059 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2060 null /*package*/, null /*extras*/, 0 /*flags*/, 2061 packageName /*targetPackage*/, 2062 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2063 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2064 // First-install and we did a restore, so we're responsible for the 2065 // first-launch broadcast. 2066 if (DEBUG_BACKUP) { 2067 Slog.i(TAG, "Post-restore of " + packageName 2068 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2069 } 2070 sendFirstLaunchBroadcast(packageName, installerPackage, 2071 firstUserIds, firstInstantUserIds); 2072 } 2073 2074 // Send broadcast package appeared if forward locked/external for all users 2075 // treat asec-hosted packages like removable media on upgrade 2076 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2077 if (DEBUG_INSTALL) { 2078 Slog.i(TAG, "upgrading pkg " + res.pkg 2079 + " is ASEC-hosted -> AVAILABLE"); 2080 } 2081 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2082 ArrayList<String> pkgList = new ArrayList<>(1); 2083 pkgList.add(packageName); 2084 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2085 } 2086 } 2087 2088 // Work that needs to happen on first install within each user 2089 if (firstUserIds != null && firstUserIds.length > 0) { 2090 synchronized (mPackages) { 2091 for (int userId : firstUserIds) { 2092 // If this app is a browser and it's newly-installed for some 2093 // users, clear any default-browser state in those users. The 2094 // app's nature doesn't depend on the user, so we can just check 2095 // its browser nature in any user and generalize. 2096 if (packageIsBrowser(packageName, userId)) { 2097 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2098 } 2099 2100 // We may also need to apply pending (restored) runtime 2101 // permission grants within these users. 2102 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2103 } 2104 } 2105 } 2106 2107 if (allNewUsers && !update) { 2108 notifyPackageAdded(packageName); 2109 } 2110 2111 // Log current value of "unknown sources" setting 2112 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2113 getUnknownSourcesSettings()); 2114 2115 // Remove the replaced package's older resources safely now 2116 // We delete after a gc for applications on sdcard. 2117 if (res.removedInfo != null && res.removedInfo.args != null) { 2118 Runtime.getRuntime().gc(); 2119 synchronized (mInstallLock) { 2120 res.removedInfo.args.doPostDeleteLI(true); 2121 } 2122 } else { 2123 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2124 // and not block here. 2125 VMRuntime.getRuntime().requestConcurrentGC(); 2126 } 2127 2128 // Notify DexManager that the package was installed for new users. 2129 // The updated users should already be indexed and the package code paths 2130 // should not change. 2131 // Don't notify the manager for ephemeral apps as they are not expected to 2132 // survive long enough to benefit of background optimizations. 2133 for (int userId : firstUserIds) { 2134 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2135 // There's a race currently where some install events may interleave with an uninstall. 2136 // This can lead to package info being null (b/36642664). 2137 if (info != null) { 2138 mDexManager.notifyPackageInstalled(info, userId); 2139 } 2140 } 2141 } 2142 2143 // If someone is watching installs - notify them 2144 if (installObserver != null) { 2145 try { 2146 Bundle extras = extrasForInstallResult(res); 2147 installObserver.onPackageInstalled(res.name, res.returnCode, 2148 res.returnMsg, extras); 2149 } catch (RemoteException e) { 2150 Slog.i(TAG, "Observer no longer exists."); 2151 } 2152 } 2153 } 2154 2155 private StorageEventListener mStorageListener = new StorageEventListener() { 2156 @Override 2157 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2158 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2159 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2160 final String volumeUuid = vol.getFsUuid(); 2161 2162 // Clean up any users or apps that were removed or recreated 2163 // while this volume was missing 2164 sUserManager.reconcileUsers(volumeUuid); 2165 reconcileApps(volumeUuid); 2166 2167 // Clean up any install sessions that expired or were 2168 // cancelled while this volume was missing 2169 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2170 2171 loadPrivatePackages(vol); 2172 2173 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2174 unloadPrivatePackages(vol); 2175 } 2176 } 2177 } 2178 2179 @Override 2180 public void onVolumeForgotten(String fsUuid) { 2181 if (TextUtils.isEmpty(fsUuid)) { 2182 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2183 return; 2184 } 2185 2186 // Remove any apps installed on the forgotten volume 2187 synchronized (mPackages) { 2188 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2189 for (PackageSetting ps : packages) { 2190 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2191 deletePackageVersioned(new VersionedPackage(ps.name, 2192 PackageManager.VERSION_CODE_HIGHEST), 2193 new LegacyPackageDeleteObserver(null).getBinder(), 2194 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2195 // Try very hard to release any references to this package 2196 // so we don't risk the system server being killed due to 2197 // open FDs 2198 AttributeCache.instance().removePackage(ps.name); 2199 } 2200 2201 mSettings.onVolumeForgotten(fsUuid); 2202 mSettings.writeLPr(); 2203 } 2204 } 2205 }; 2206 2207 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2208 Bundle extras = null; 2209 switch (res.returnCode) { 2210 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2211 extras = new Bundle(); 2212 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2213 res.origPermission); 2214 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2215 res.origPackage); 2216 break; 2217 } 2218 case PackageManager.INSTALL_SUCCEEDED: { 2219 extras = new Bundle(); 2220 extras.putBoolean(Intent.EXTRA_REPLACING, 2221 res.removedInfo != null && res.removedInfo.removedPackage != null); 2222 break; 2223 } 2224 } 2225 return extras; 2226 } 2227 2228 void scheduleWriteSettingsLocked() { 2229 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2230 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2231 } 2232 } 2233 2234 void scheduleWritePackageListLocked(int userId) { 2235 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2236 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2237 msg.arg1 = userId; 2238 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2239 } 2240 } 2241 2242 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2243 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2244 scheduleWritePackageRestrictionsLocked(userId); 2245 } 2246 2247 void scheduleWritePackageRestrictionsLocked(int userId) { 2248 final int[] userIds = (userId == UserHandle.USER_ALL) 2249 ? sUserManager.getUserIds() : new int[]{userId}; 2250 for (int nextUserId : userIds) { 2251 if (!sUserManager.exists(nextUserId)) return; 2252 mDirtyUsers.add(nextUserId); 2253 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2254 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2255 } 2256 } 2257 } 2258 2259 public static PackageManagerService main(Context context, Installer installer, 2260 boolean factoryTest, boolean onlyCore) { 2261 // Self-check for initial settings. 2262 PackageManagerServiceCompilerMapping.checkProperties(); 2263 2264 PackageManagerService m = new PackageManagerService(context, installer, 2265 factoryTest, onlyCore); 2266 m.enableSystemUserPackages(); 2267 ServiceManager.addService("package", m); 2268 final PackageManagerNative pmn = m.new PackageManagerNative(); 2269 ServiceManager.addService("package_native", pmn); 2270 return m; 2271 } 2272 2273 private void enableSystemUserPackages() { 2274 if (!UserManager.isSplitSystemUser()) { 2275 return; 2276 } 2277 // For system user, enable apps based on the following conditions: 2278 // - app is whitelisted or belong to one of these groups: 2279 // -- system app which has no launcher icons 2280 // -- system app which has INTERACT_ACROSS_USERS permission 2281 // -- system IME app 2282 // - app is not in the blacklist 2283 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2284 Set<String> enableApps = new ArraySet<>(); 2285 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2286 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2287 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2288 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2289 enableApps.addAll(wlApps); 2290 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2291 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2292 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2293 enableApps.removeAll(blApps); 2294 Log.i(TAG, "Applications installed for system user: " + enableApps); 2295 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2296 UserHandle.SYSTEM); 2297 final int allAppsSize = allAps.size(); 2298 synchronized (mPackages) { 2299 for (int i = 0; i < allAppsSize; i++) { 2300 String pName = allAps.get(i); 2301 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2302 // Should not happen, but we shouldn't be failing if it does 2303 if (pkgSetting == null) { 2304 continue; 2305 } 2306 boolean install = enableApps.contains(pName); 2307 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2308 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2309 + " for system user"); 2310 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2311 } 2312 } 2313 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2314 } 2315 } 2316 2317 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2318 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2319 Context.DISPLAY_SERVICE); 2320 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2321 } 2322 2323 /** 2324 * Requests that files preopted on a secondary system partition be copied to the data partition 2325 * if possible. Note that the actual copying of the files is accomplished by init for security 2326 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2327 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2328 */ 2329 private static void requestCopyPreoptedFiles() { 2330 final int WAIT_TIME_MS = 100; 2331 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2332 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2333 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2334 // We will wait for up to 100 seconds. 2335 final long timeStart = SystemClock.uptimeMillis(); 2336 final long timeEnd = timeStart + 100 * 1000; 2337 long timeNow = timeStart; 2338 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2339 try { 2340 Thread.sleep(WAIT_TIME_MS); 2341 } catch (InterruptedException e) { 2342 // Do nothing 2343 } 2344 timeNow = SystemClock.uptimeMillis(); 2345 if (timeNow > timeEnd) { 2346 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2347 Slog.wtf(TAG, "cppreopt did not finish!"); 2348 break; 2349 } 2350 } 2351 2352 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2353 } 2354 } 2355 2356 public PackageManagerService(Context context, Installer installer, 2357 boolean factoryTest, boolean onlyCore) { 2358 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2360 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2361 SystemClock.uptimeMillis()); 2362 2363 if (mSdkVersion <= 0) { 2364 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2365 } 2366 2367 mContext = context; 2368 2369 mFactoryTest = factoryTest; 2370 mOnlyCore = onlyCore; 2371 mMetrics = new DisplayMetrics(); 2372 mInstaller = installer; 2373 2374 // Create sub-components that provide services / data. Order here is important. 2375 synchronized (mInstallLock) { 2376 synchronized (mPackages) { 2377 // Expose private service for system components to use. 2378 LocalServices.addService( 2379 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2380 sUserManager = new UserManagerService(context, this, 2381 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2382 mPermissionManager = PermissionManagerService.create(context, 2383 new DefaultPermissionGrantedCallback() { 2384 @Override 2385 public void onDefaultRuntimePermissionsGranted(int userId) { 2386 synchronized(mPackages) { 2387 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2388 } 2389 } 2390 }, mPackages /*externalLock*/); 2391 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2392 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2393 } 2394 } 2395 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2396 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2397 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2398 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2399 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2400 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2401 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2402 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2403 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2404 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2405 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2406 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2407 2408 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2409 if (separateProcesses != null && separateProcesses.length() > 0) { 2410 if ("*".equals(separateProcesses)) { 2411 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2412 mSeparateProcesses = null; 2413 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2414 } else { 2415 mDefParseFlags = 0; 2416 mSeparateProcesses = separateProcesses.split(","); 2417 Slog.w(TAG, "Running with debug.separate_processes: " 2418 + separateProcesses); 2419 } 2420 } else { 2421 mDefParseFlags = 0; 2422 mSeparateProcesses = null; 2423 } 2424 2425 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2426 "*dexopt*"); 2427 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2428 installer, mInstallLock); 2429 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2430 dexManagerListener); 2431 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2432 2433 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2434 FgThread.get().getLooper()); 2435 2436 getDefaultDisplayMetrics(context, mMetrics); 2437 2438 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2439 SystemConfig systemConfig = SystemConfig.getInstance(); 2440 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2441 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2442 2443 mProtectedPackages = new ProtectedPackages(mContext); 2444 2445 synchronized (mInstallLock) { 2446 // writer 2447 synchronized (mPackages) { 2448 mHandlerThread = new ServiceThread(TAG, 2449 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2450 mHandlerThread.start(); 2451 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2452 mProcessLoggingHandler = new ProcessLoggingHandler(); 2453 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2454 mInstantAppRegistry = new InstantAppRegistry(this); 2455 2456 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2457 final int builtInLibCount = libConfig.size(); 2458 for (int i = 0; i < builtInLibCount; i++) { 2459 String name = libConfig.keyAt(i); 2460 String path = libConfig.valueAt(i); 2461 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2462 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2463 } 2464 2465 SELinuxMMAC.readInstallPolicy(); 2466 2467 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2468 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2469 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2470 2471 // Clean up orphaned packages for which the code path doesn't exist 2472 // and they are an update to a system app - caused by bug/32321269 2473 final int packageSettingCount = mSettings.mPackages.size(); 2474 for (int i = packageSettingCount - 1; i >= 0; i--) { 2475 PackageSetting ps = mSettings.mPackages.valueAt(i); 2476 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2477 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2478 mSettings.mPackages.removeAt(i); 2479 mSettings.enableSystemPackageLPw(ps.name); 2480 } 2481 } 2482 2483 if (mFirstBoot) { 2484 requestCopyPreoptedFiles(); 2485 } 2486 2487 String customResolverActivity = Resources.getSystem().getString( 2488 R.string.config_customResolverActivity); 2489 if (TextUtils.isEmpty(customResolverActivity)) { 2490 customResolverActivity = null; 2491 } else { 2492 mCustomResolverComponentName = ComponentName.unflattenFromString( 2493 customResolverActivity); 2494 } 2495 2496 long startTime = SystemClock.uptimeMillis(); 2497 2498 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2499 startTime); 2500 2501 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2502 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2503 2504 if (bootClassPath == null) { 2505 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2506 } 2507 2508 if (systemServerClassPath == null) { 2509 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2510 } 2511 2512 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2513 2514 final VersionInfo ver = mSettings.getInternalVersion(); 2515 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2516 if (mIsUpgrade) { 2517 logCriticalInfo(Log.INFO, 2518 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2519 } 2520 2521 // when upgrading from pre-M, promote system app permissions from install to runtime 2522 mPromoteSystemApps = 2523 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2524 2525 // When upgrading from pre-N, we need to handle package extraction like first boot, 2526 // as there is no profiling data available. 2527 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2528 2529 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2530 2531 // save off the names of pre-existing system packages prior to scanning; we don't 2532 // want to automatically grant runtime permissions for new system apps 2533 if (mPromoteSystemApps) { 2534 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2535 while (pkgSettingIter.hasNext()) { 2536 PackageSetting ps = pkgSettingIter.next(); 2537 if (isSystemApp(ps)) { 2538 mExistingSystemPackages.add(ps.name); 2539 } 2540 } 2541 } 2542 2543 mCacheDir = preparePackageParserCache(mIsUpgrade); 2544 2545 // Set flag to monitor and not change apk file paths when 2546 // scanning install directories. 2547 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2548 2549 if (mIsUpgrade || mFirstBoot) { 2550 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2551 } 2552 2553 // Collect vendor overlay packages. (Do this before scanning any apps.) 2554 // For security and version matching reason, only consider 2555 // overlay packages if they reside in the right directory. 2556 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2557 mDefParseFlags 2558 | PackageParser.PARSE_IS_SYSTEM_DIR, 2559 scanFlags 2560 | SCAN_AS_SYSTEM 2561 | SCAN_TRUSTED_OVERLAY, 2562 0); 2563 2564 mParallelPackageParserCallback.findStaticOverlayPackages(); 2565 2566 // Find base frameworks (resource packages without code). 2567 scanDirTracedLI(frameworkDir, 2568 mDefParseFlags 2569 | PackageParser.PARSE_IS_SYSTEM_DIR, 2570 scanFlags 2571 | SCAN_NO_DEX 2572 | SCAN_AS_SYSTEM 2573 | SCAN_AS_PRIVILEGED, 2574 0); 2575 2576 // Collected privileged system packages. 2577 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2578 scanDirTracedLI(privilegedAppDir, 2579 mDefParseFlags 2580 | PackageParser.PARSE_IS_SYSTEM_DIR, 2581 scanFlags 2582 | SCAN_AS_SYSTEM 2583 | SCAN_AS_PRIVILEGED, 2584 0); 2585 2586 // Collect ordinary system packages. 2587 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2588 scanDirTracedLI(systemAppDir, 2589 mDefParseFlags 2590 | PackageParser.PARSE_IS_SYSTEM_DIR, 2591 scanFlags 2592 | SCAN_AS_SYSTEM, 2593 0); 2594 2595 // Collected privileged vendor packages. 2596 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), 2597 "priv-app"); 2598 try { 2599 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2600 } catch (IOException e) { 2601 // failed to look up canonical path, continue with original one 2602 } 2603 scanDirTracedLI(privilegedVendorAppDir, 2604 mDefParseFlags 2605 | PackageParser.PARSE_IS_SYSTEM_DIR, 2606 scanFlags 2607 | SCAN_AS_SYSTEM 2608 | SCAN_AS_VENDOR 2609 | SCAN_AS_PRIVILEGED, 2610 0); 2611 2612 // Collect ordinary vendor packages. 2613 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2614 try { 2615 vendorAppDir = vendorAppDir.getCanonicalFile(); 2616 } catch (IOException e) { 2617 // failed to look up canonical path, continue with original one 2618 } 2619 scanDirTracedLI(vendorAppDir, 2620 mDefParseFlags 2621 | PackageParser.PARSE_IS_SYSTEM_DIR, 2622 scanFlags 2623 | SCAN_AS_SYSTEM 2624 | SCAN_AS_VENDOR, 2625 0); 2626 2627 // Collect all OEM packages. 2628 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2629 scanDirTracedLI(oemAppDir, 2630 mDefParseFlags 2631 | PackageParser.PARSE_IS_SYSTEM_DIR, 2632 scanFlags 2633 | SCAN_AS_SYSTEM 2634 | SCAN_AS_OEM, 2635 0); 2636 2637 // Prune any system packages that no longer exist. 2638 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2639 // Stub packages must either be replaced with full versions in the /data 2640 // partition or be disabled. 2641 final List<String> stubSystemApps = new ArrayList<>(); 2642 if (!mOnlyCore) { 2643 // do this first before mucking with mPackages for the "expecting better" case 2644 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2645 while (pkgIterator.hasNext()) { 2646 final PackageParser.Package pkg = pkgIterator.next(); 2647 if (pkg.isStub) { 2648 stubSystemApps.add(pkg.packageName); 2649 } 2650 } 2651 2652 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2653 while (psit.hasNext()) { 2654 PackageSetting ps = psit.next(); 2655 2656 /* 2657 * If this is not a system app, it can't be a 2658 * disable system app. 2659 */ 2660 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2661 continue; 2662 } 2663 2664 /* 2665 * If the package is scanned, it's not erased. 2666 */ 2667 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2668 if (scannedPkg != null) { 2669 /* 2670 * If the system app is both scanned and in the 2671 * disabled packages list, then it must have been 2672 * added via OTA. Remove it from the currently 2673 * scanned package so the previously user-installed 2674 * application can be scanned. 2675 */ 2676 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2677 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2678 + ps.name + "; removing system app. Last known codePath=" 2679 + ps.codePathString + ", installStatus=" + ps.installStatus 2680 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2681 + scannedPkg.getLongVersionCode()); 2682 removePackageLI(scannedPkg, true); 2683 mExpectingBetter.put(ps.name, ps.codePath); 2684 } 2685 2686 continue; 2687 } 2688 2689 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2690 psit.remove(); 2691 logCriticalInfo(Log.WARN, "System package " + ps.name 2692 + " no longer exists; it's data will be wiped"); 2693 // Actual deletion of code and data will be handled by later 2694 // reconciliation step 2695 } else { 2696 // we still have a disabled system package, but, it still might have 2697 // been removed. check the code path still exists and check there's 2698 // still a package. the latter can happen if an OTA keeps the same 2699 // code path, but, changes the package name. 2700 final PackageSetting disabledPs = 2701 mSettings.getDisabledSystemPkgLPr(ps.name); 2702 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2703 || disabledPs.pkg == null) { 2704if (REFACTOR_DEBUG) { 2705Slog.e("TODD", 2706 "Possibly deleted app: " + ps.dumpState_temp() 2707 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2708 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2709} 2710 possiblyDeletedUpdatedSystemApps.add(ps.name); 2711 } 2712 } 2713 } 2714 } 2715 2716 //look for any incomplete package installations 2717 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2718 for (int i = 0; i < deletePkgsList.size(); i++) { 2719 // Actual deletion of code and data will be handled by later 2720 // reconciliation step 2721 final String packageName = deletePkgsList.get(i).name; 2722 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2723 synchronized (mPackages) { 2724 mSettings.removePackageLPw(packageName); 2725 } 2726 } 2727 2728 //delete tmp files 2729 deleteTempPackageFiles(); 2730 2731 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2732 2733 // Remove any shared userIDs that have no associated packages 2734 mSettings.pruneSharedUsersLPw(); 2735 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2736 final int systemPackagesCount = mPackages.size(); 2737 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2738 + " ms, packageCount: " + systemPackagesCount 2739 + " , timePerPackage: " 2740 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2741 + " , cached: " + cachedSystemApps); 2742 if (mIsUpgrade && systemPackagesCount > 0) { 2743 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2744 ((int) systemScanTime) / systemPackagesCount); 2745 } 2746 if (!mOnlyCore) { 2747 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2748 SystemClock.uptimeMillis()); 2749 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2750 2751 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2752 | PackageParser.PARSE_FORWARD_LOCK, 2753 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2754 2755 // Remove disable package settings for updated system apps that were 2756 // removed via an OTA. If the update is no longer present, remove the 2757 // app completely. Otherwise, revoke their system privileges. 2758 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2759 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2760 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2761if (REFACTOR_DEBUG) { 2762Slog.e("TODD", 2763 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2764} 2765 final String msg; 2766 if (deletedPkg == null) { 2767 // should have found an update, but, we didn't; remove everything 2768 msg = "Updated system package " + deletedAppName 2769 + " no longer exists; removing its data"; 2770 // Actual deletion of code and data will be handled by later 2771 // reconciliation step 2772 } else { 2773 // found an update; revoke system privileges 2774 msg = "Updated system package + " + deletedAppName 2775 + " no longer exists; revoking system privileges"; 2776 2777 // Don't do anything if a stub is removed from the system image. If 2778 // we were to remove the uncompressed version from the /data partition, 2779 // this is where it'd be done. 2780 2781 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2782 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2783 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2784 } 2785 logCriticalInfo(Log.WARN, msg); 2786 } 2787 2788 /* 2789 * Make sure all system apps that we expected to appear on 2790 * the userdata partition actually showed up. If they never 2791 * appeared, crawl back and revive the system version. 2792 */ 2793 for (int i = 0; i < mExpectingBetter.size(); i++) { 2794 final String packageName = mExpectingBetter.keyAt(i); 2795 if (!mPackages.containsKey(packageName)) { 2796 final File scanFile = mExpectingBetter.valueAt(i); 2797 2798 logCriticalInfo(Log.WARN, "Expected better " + packageName 2799 + " but never showed up; reverting to system"); 2800 2801 final @ParseFlags int reparseFlags; 2802 final @ScanFlags int rescanFlags; 2803 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2804 reparseFlags = 2805 mDefParseFlags | 2806 PackageParser.PARSE_IS_SYSTEM_DIR; 2807 rescanFlags = 2808 scanFlags 2809 | SCAN_AS_SYSTEM 2810 | SCAN_AS_PRIVILEGED; 2811 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2812 reparseFlags = 2813 mDefParseFlags | 2814 PackageParser.PARSE_IS_SYSTEM_DIR; 2815 rescanFlags = 2816 scanFlags 2817 | SCAN_AS_SYSTEM; 2818 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2819 reparseFlags = 2820 mDefParseFlags | 2821 PackageParser.PARSE_IS_SYSTEM_DIR; 2822 rescanFlags = 2823 scanFlags 2824 | SCAN_AS_SYSTEM 2825 | SCAN_AS_VENDOR 2826 | SCAN_AS_PRIVILEGED; 2827 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2828 reparseFlags = 2829 mDefParseFlags | 2830 PackageParser.PARSE_IS_SYSTEM_DIR; 2831 rescanFlags = 2832 scanFlags 2833 | SCAN_AS_SYSTEM 2834 | SCAN_AS_VENDOR; 2835 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2836 reparseFlags = 2837 mDefParseFlags | 2838 PackageParser.PARSE_IS_SYSTEM_DIR; 2839 rescanFlags = 2840 scanFlags 2841 | SCAN_AS_SYSTEM 2842 | SCAN_AS_OEM; 2843 } else { 2844 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2845 continue; 2846 } 2847 2848 mSettings.enableSystemPackageLPw(packageName); 2849 2850 try { 2851 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2852 } catch (PackageManagerException e) { 2853 Slog.e(TAG, "Failed to parse original system package: " 2854 + e.getMessage()); 2855 } 2856 } 2857 } 2858 2859 // Uncompress and install any stubbed system applications. 2860 // This must be done last to ensure all stubs are replaced or disabled. 2861 decompressSystemApplications(stubSystemApps, scanFlags); 2862 2863 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2864 - cachedSystemApps; 2865 2866 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2867 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2868 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2869 + " ms, packageCount: " + dataPackagesCount 2870 + " , timePerPackage: " 2871 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2872 + " , cached: " + cachedNonSystemApps); 2873 if (mIsUpgrade && dataPackagesCount > 0) { 2874 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2875 ((int) dataScanTime) / dataPackagesCount); 2876 } 2877 } 2878 mExpectingBetter.clear(); 2879 2880 // Resolve the storage manager. 2881 mStorageManagerPackage = getStorageManagerPackageName(); 2882 2883 // Resolve protected action filters. Only the setup wizard is allowed to 2884 // have a high priority filter for these actions. 2885 mSetupWizardPackage = getSetupWizardPackageName(); 2886 if (mProtectedFilters.size() > 0) { 2887 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2888 Slog.i(TAG, "No setup wizard;" 2889 + " All protected intents capped to priority 0"); 2890 } 2891 for (ActivityIntentInfo filter : mProtectedFilters) { 2892 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2893 if (DEBUG_FILTERS) { 2894 Slog.i(TAG, "Found setup wizard;" 2895 + " allow priority " + filter.getPriority() + ";" 2896 + " package: " + filter.activity.info.packageName 2897 + " activity: " + filter.activity.className 2898 + " priority: " + filter.getPriority()); 2899 } 2900 // skip setup wizard; allow it to keep the high priority filter 2901 continue; 2902 } 2903 if (DEBUG_FILTERS) { 2904 Slog.i(TAG, "Protected action; cap priority to 0;" 2905 + " package: " + filter.activity.info.packageName 2906 + " activity: " + filter.activity.className 2907 + " origPrio: " + filter.getPriority()); 2908 } 2909 filter.setPriority(0); 2910 } 2911 } 2912 mDeferProtectedFilters = false; 2913 mProtectedFilters.clear(); 2914 2915 // Now that we know all of the shared libraries, update all clients to have 2916 // the correct library paths. 2917 updateAllSharedLibrariesLPw(null); 2918 2919 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2920 // NOTE: We ignore potential failures here during a system scan (like 2921 // the rest of the commands above) because there's precious little we 2922 // can do about it. A settings error is reported, though. 2923 final List<String> changedAbiCodePath = 2924 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2925 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2926 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2927 final String codePathString = changedAbiCodePath.get(i); 2928 try { 2929 mInstaller.rmdex(codePathString, 2930 getDexCodeInstructionSet(getPreferredInstructionSet())); 2931 } catch (InstallerException ignored) { 2932 } 2933 } 2934 } 2935 } 2936 2937 // Now that we know all the packages we are keeping, 2938 // read and update their last usage times. 2939 mPackageUsage.read(mPackages); 2940 mCompilerStats.read(); 2941 2942 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2943 SystemClock.uptimeMillis()); 2944 Slog.i(TAG, "Time to scan packages: " 2945 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2946 + " seconds"); 2947 2948 // If the platform SDK has changed since the last time we booted, 2949 // we need to re-grant app permission to catch any new ones that 2950 // appear. This is really a hack, and means that apps can in some 2951 // cases get permissions that the user didn't initially explicitly 2952 // allow... it would be nice to have some better way to handle 2953 // this situation. 2954 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2955 if (sdkUpdated) { 2956 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2957 + mSdkVersion + "; regranting permissions for internal storage"); 2958 } 2959 mPermissionManager.updateAllPermissions( 2960 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2961 mPermissionCallback); 2962 ver.sdkVersion = mSdkVersion; 2963 2964 // If this is the first boot or an update from pre-M, and it is a normal 2965 // boot, then we need to initialize the default preferred apps across 2966 // all defined users. 2967 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2968 for (UserInfo user : sUserManager.getUsers(true)) { 2969 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2970 applyFactoryDefaultBrowserLPw(user.id); 2971 primeDomainVerificationsLPw(user.id); 2972 } 2973 } 2974 2975 // Prepare storage for system user really early during boot, 2976 // since core system apps like SettingsProvider and SystemUI 2977 // can't wait for user to start 2978 final int storageFlags; 2979 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2980 storageFlags = StorageManager.FLAG_STORAGE_DE; 2981 } else { 2982 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2983 } 2984 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2985 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2986 true /* onlyCoreApps */); 2987 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2988 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2989 Trace.TRACE_TAG_PACKAGE_MANAGER); 2990 traceLog.traceBegin("AppDataFixup"); 2991 try { 2992 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2993 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2994 } catch (InstallerException e) { 2995 Slog.w(TAG, "Trouble fixing GIDs", e); 2996 } 2997 traceLog.traceEnd(); 2998 2999 traceLog.traceBegin("AppDataPrepare"); 3000 if (deferPackages == null || deferPackages.isEmpty()) { 3001 return; 3002 } 3003 int count = 0; 3004 for (String pkgName : deferPackages) { 3005 PackageParser.Package pkg = null; 3006 synchronized (mPackages) { 3007 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3008 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3009 pkg = ps.pkg; 3010 } 3011 } 3012 if (pkg != null) { 3013 synchronized (mInstallLock) { 3014 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3015 true /* maybeMigrateAppData */); 3016 } 3017 count++; 3018 } 3019 } 3020 traceLog.traceEnd(); 3021 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3022 }, "prepareAppData"); 3023 3024 // If this is first boot after an OTA, and a normal boot, then 3025 // we need to clear code cache directories. 3026 // Note that we do *not* clear the application profiles. These remain valid 3027 // across OTAs and are used to drive profile verification (post OTA) and 3028 // profile compilation (without waiting to collect a fresh set of profiles). 3029 if (mIsUpgrade && !onlyCore) { 3030 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3031 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3032 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3033 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3034 // No apps are running this early, so no need to freeze 3035 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3036 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3037 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3038 } 3039 } 3040 ver.fingerprint = Build.FINGERPRINT; 3041 } 3042 3043 checkDefaultBrowser(); 3044 3045 // clear only after permissions and other defaults have been updated 3046 mExistingSystemPackages.clear(); 3047 mPromoteSystemApps = false; 3048 3049 // All the changes are done during package scanning. 3050 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3051 3052 // can downgrade to reader 3053 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3054 mSettings.writeLPr(); 3055 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3056 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3057 SystemClock.uptimeMillis()); 3058 3059 if (!mOnlyCore) { 3060 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3061 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3062 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3063 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3064 if (mIntentFilterVerifierComponent != null) { 3065 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3066 mIntentFilterVerifierComponent); 3067 } else { 3068 mIntentFilterVerifier = null; 3069 } 3070 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3071 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3072 SharedLibraryInfo.VERSION_UNDEFINED); 3073 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3074 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3075 SharedLibraryInfo.VERSION_UNDEFINED); 3076 } else { 3077 mRequiredVerifierPackage = null; 3078 mRequiredInstallerPackage = null; 3079 mRequiredUninstallerPackage = null; 3080 mIntentFilterVerifierComponent = null; 3081 mIntentFilterVerifier = null; 3082 mServicesSystemSharedLibraryPackageName = null; 3083 mSharedSystemSharedLibraryPackageName = null; 3084 } 3085 3086 mInstallerService = new PackageInstallerService(context, this); 3087 mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock); 3088 final Pair<ComponentName, String> instantAppResolverComponent = 3089 getInstantAppResolverLPr(); 3090 if (instantAppResolverComponent != null) { 3091 if (DEBUG_EPHEMERAL) { 3092 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3093 } 3094 mInstantAppResolverConnection = new EphemeralResolverConnection( 3095 mContext, instantAppResolverComponent.first, 3096 instantAppResolverComponent.second); 3097 mInstantAppResolverSettingsComponent = 3098 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3099 } else { 3100 mInstantAppResolverConnection = null; 3101 mInstantAppResolverSettingsComponent = null; 3102 } 3103 updateInstantAppInstallerLocked(null); 3104 3105 // Read and update the usage of dex files. 3106 // Do this at the end of PM init so that all the packages have their 3107 // data directory reconciled. 3108 // At this point we know the code paths of the packages, so we can validate 3109 // the disk file and build the internal cache. 3110 // The usage file is expected to be small so loading and verifying it 3111 // should take a fairly small time compare to the other activities (e.g. package 3112 // scanning). 3113 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3114 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3115 for (int userId : currentUserIds) { 3116 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3117 } 3118 mDexManager.load(userPackages); 3119 if (mIsUpgrade) { 3120 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3121 (int) (SystemClock.uptimeMillis() - startTime)); 3122 } 3123 } // synchronized (mPackages) 3124 } // synchronized (mInstallLock) 3125 3126 // Now after opening every single application zip, make sure they 3127 // are all flushed. Not really needed, but keeps things nice and 3128 // tidy. 3129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3130 Runtime.getRuntime().gc(); 3131 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3132 3133 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3134 FallbackCategoryProvider.loadFallbacks(); 3135 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3136 3137 // The initial scanning above does many calls into installd while 3138 // holding the mPackages lock, but we're mostly interested in yelling 3139 // once we have a booted system. 3140 mInstaller.setWarnIfHeld(mPackages); 3141 3142 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3143 } 3144 3145 /** 3146 * Uncompress and install stub applications. 3147 * <p>In order to save space on the system partition, some applications are shipped in a 3148 * compressed form. In addition the compressed bits for the full application, the 3149 * system image contains a tiny stub comprised of only the Android manifest. 3150 * <p>During the first boot, attempt to uncompress and install the full application. If 3151 * the application can't be installed for any reason, disable the stub and prevent 3152 * uncompressing the full application during future boots. 3153 * <p>In order to forcefully attempt an installation of a full application, go to app 3154 * settings and enable the application. 3155 */ 3156 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3157 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3158 final String pkgName = stubSystemApps.get(i); 3159 // skip if the system package is already disabled 3160 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3161 stubSystemApps.remove(i); 3162 continue; 3163 } 3164 // skip if the package isn't installed (?!); this should never happen 3165 final PackageParser.Package pkg = mPackages.get(pkgName); 3166 if (pkg == null) { 3167 stubSystemApps.remove(i); 3168 continue; 3169 } 3170 // skip if the package has been disabled by the user 3171 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3172 if (ps != null) { 3173 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3174 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3175 stubSystemApps.remove(i); 3176 continue; 3177 } 3178 } 3179 3180 if (DEBUG_COMPRESSION) { 3181 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3182 } 3183 3184 // uncompress the binary to its eventual destination on /data 3185 final File scanFile = decompressPackage(pkg); 3186 if (scanFile == null) { 3187 continue; 3188 } 3189 3190 // install the package to replace the stub on /system 3191 try { 3192 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3193 removePackageLI(pkg, true /*chatty*/); 3194 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3195 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3196 UserHandle.USER_SYSTEM, "android"); 3197 stubSystemApps.remove(i); 3198 continue; 3199 } catch (PackageManagerException e) { 3200 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3201 } 3202 3203 // any failed attempt to install the package will be cleaned up later 3204 } 3205 3206 // disable any stub still left; these failed to install the full application 3207 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3208 final String pkgName = stubSystemApps.get(i); 3209 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3210 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3211 UserHandle.USER_SYSTEM, "android"); 3212 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3213 } 3214 } 3215 3216 /** 3217 * Decompresses the given package on the system image onto 3218 * the /data partition. 3219 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3220 */ 3221 private File decompressPackage(PackageParser.Package pkg) { 3222 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3223 if (compressedFiles == null || compressedFiles.length == 0) { 3224 if (DEBUG_COMPRESSION) { 3225 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3226 } 3227 return null; 3228 } 3229 final File dstCodePath = 3230 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3231 int ret = PackageManager.INSTALL_SUCCEEDED; 3232 try { 3233 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3234 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3235 for (File srcFile : compressedFiles) { 3236 final String srcFileName = srcFile.getName(); 3237 final String dstFileName = srcFileName.substring( 3238 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3239 final File dstFile = new File(dstCodePath, dstFileName); 3240 ret = decompressFile(srcFile, dstFile); 3241 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3242 logCriticalInfo(Log.ERROR, "Failed to decompress" 3243 + "; pkg: " + pkg.packageName 3244 + ", file: " + dstFileName); 3245 break; 3246 } 3247 } 3248 } catch (ErrnoException e) { 3249 logCriticalInfo(Log.ERROR, "Failed to decompress" 3250 + "; pkg: " + pkg.packageName 3251 + ", err: " + e.errno); 3252 } 3253 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3254 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3255 NativeLibraryHelper.Handle handle = null; 3256 try { 3257 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3258 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3259 null /*abiOverride*/); 3260 } catch (IOException e) { 3261 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3262 + "; pkg: " + pkg.packageName); 3263 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3264 } finally { 3265 IoUtils.closeQuietly(handle); 3266 } 3267 } 3268 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3269 if (dstCodePath == null || !dstCodePath.exists()) { 3270 return null; 3271 } 3272 removeCodePathLI(dstCodePath); 3273 return null; 3274 } 3275 3276 return dstCodePath; 3277 } 3278 3279 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3280 // we're only interested in updating the installer appliction when 1) it's not 3281 // already set or 2) the modified package is the installer 3282 if (mInstantAppInstallerActivity != null 3283 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3284 .equals(modifiedPackage)) { 3285 return; 3286 } 3287 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3288 } 3289 3290 private static File preparePackageParserCache(boolean isUpgrade) { 3291 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3292 return null; 3293 } 3294 3295 // Disable package parsing on eng builds to allow for faster incremental development. 3296 if (Build.IS_ENG) { 3297 return null; 3298 } 3299 3300 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3301 Slog.i(TAG, "Disabling package parser cache due to system property."); 3302 return null; 3303 } 3304 3305 // The base directory for the package parser cache lives under /data/system/. 3306 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3307 "package_cache"); 3308 if (cacheBaseDir == null) { 3309 return null; 3310 } 3311 3312 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3313 // This also serves to "GC" unused entries when the package cache version changes (which 3314 // can only happen during upgrades). 3315 if (isUpgrade) { 3316 FileUtils.deleteContents(cacheBaseDir); 3317 } 3318 3319 3320 // Return the versioned package cache directory. This is something like 3321 // "/data/system/package_cache/1" 3322 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3323 3324 // The following is a workaround to aid development on non-numbered userdebug 3325 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3326 // the system partition is newer. 3327 // 3328 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3329 // that starts with "eng." to signify that this is an engineering build and not 3330 // destined for release. 3331 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3332 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3333 3334 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3335 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3336 // in general and should not be used for production changes. In this specific case, 3337 // we know that they will work. 3338 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3339 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3340 FileUtils.deleteContents(cacheBaseDir); 3341 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3342 } 3343 } 3344 3345 return cacheDir; 3346 } 3347 3348 @Override 3349 public boolean isFirstBoot() { 3350 // allow instant applications 3351 return mFirstBoot; 3352 } 3353 3354 @Override 3355 public boolean isOnlyCoreApps() { 3356 // allow instant applications 3357 return mOnlyCore; 3358 } 3359 3360 @Override 3361 public boolean isUpgrade() { 3362 // allow instant applications 3363 // The system property allows testing ota flow when upgraded to the same image. 3364 return mIsUpgrade || SystemProperties.getBoolean( 3365 "persist.pm.mock-upgrade", false /* default */); 3366 } 3367 3368 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3369 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3370 3371 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3372 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3373 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3374 if (matches.size() == 1) { 3375 return matches.get(0).getComponentInfo().packageName; 3376 } else if (matches.size() == 0) { 3377 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3378 return null; 3379 } 3380 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3381 } 3382 3383 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3384 synchronized (mPackages) { 3385 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3386 if (libraryEntry == null) { 3387 throw new IllegalStateException("Missing required shared library:" + name); 3388 } 3389 return libraryEntry.apk; 3390 } 3391 } 3392 3393 private @NonNull String getRequiredInstallerLPr() { 3394 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3395 intent.addCategory(Intent.CATEGORY_DEFAULT); 3396 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3397 3398 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3399 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3400 UserHandle.USER_SYSTEM); 3401 if (matches.size() == 1) { 3402 ResolveInfo resolveInfo = matches.get(0); 3403 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3404 throw new RuntimeException("The installer must be a privileged app"); 3405 } 3406 return matches.get(0).getComponentInfo().packageName; 3407 } else { 3408 throw new RuntimeException("There must be exactly one installer; found " + matches); 3409 } 3410 } 3411 3412 private @NonNull String getRequiredUninstallerLPr() { 3413 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3414 intent.addCategory(Intent.CATEGORY_DEFAULT); 3415 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3416 3417 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3418 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3419 UserHandle.USER_SYSTEM); 3420 if (resolveInfo == null || 3421 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3422 throw new RuntimeException("There must be exactly one uninstaller; found " 3423 + resolveInfo); 3424 } 3425 return resolveInfo.getComponentInfo().packageName; 3426 } 3427 3428 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3429 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3430 3431 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3432 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3433 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3434 ResolveInfo best = null; 3435 final int N = matches.size(); 3436 for (int i = 0; i < N; i++) { 3437 final ResolveInfo cur = matches.get(i); 3438 final String packageName = cur.getComponentInfo().packageName; 3439 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3440 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3441 continue; 3442 } 3443 3444 if (best == null || cur.priority > best.priority) { 3445 best = cur; 3446 } 3447 } 3448 3449 if (best != null) { 3450 return best.getComponentInfo().getComponentName(); 3451 } 3452 Slog.w(TAG, "Intent filter verifier not found"); 3453 return null; 3454 } 3455 3456 @Override 3457 public @Nullable ComponentName getInstantAppResolverComponent() { 3458 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3459 return null; 3460 } 3461 synchronized (mPackages) { 3462 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3463 if (instantAppResolver == null) { 3464 return null; 3465 } 3466 return instantAppResolver.first; 3467 } 3468 } 3469 3470 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3471 final String[] packageArray = 3472 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3473 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3474 if (DEBUG_EPHEMERAL) { 3475 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3476 } 3477 return null; 3478 } 3479 3480 final int callingUid = Binder.getCallingUid(); 3481 final int resolveFlags = 3482 MATCH_DIRECT_BOOT_AWARE 3483 | MATCH_DIRECT_BOOT_UNAWARE 3484 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3485 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3486 final Intent resolverIntent = new Intent(actionName); 3487 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3488 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3489 // temporarily look for the old action 3490 if (resolvers.size() == 0) { 3491 if (DEBUG_EPHEMERAL) { 3492 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3493 } 3494 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3495 resolverIntent.setAction(actionName); 3496 resolvers = queryIntentServicesInternal(resolverIntent, null, 3497 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3498 } 3499 final int N = resolvers.size(); 3500 if (N == 0) { 3501 if (DEBUG_EPHEMERAL) { 3502 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3503 } 3504 return null; 3505 } 3506 3507 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3508 for (int i = 0; i < N; i++) { 3509 final ResolveInfo info = resolvers.get(i); 3510 3511 if (info.serviceInfo == null) { 3512 continue; 3513 } 3514 3515 final String packageName = info.serviceInfo.packageName; 3516 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3517 if (DEBUG_EPHEMERAL) { 3518 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3519 + " pkg: " + packageName + ", info:" + info); 3520 } 3521 continue; 3522 } 3523 3524 if (DEBUG_EPHEMERAL) { 3525 Slog.v(TAG, "Ephemeral resolver found;" 3526 + " pkg: " + packageName + ", info:" + info); 3527 } 3528 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3529 } 3530 if (DEBUG_EPHEMERAL) { 3531 Slog.v(TAG, "Ephemeral resolver NOT found"); 3532 } 3533 return null; 3534 } 3535 3536 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3537 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3538 intent.addCategory(Intent.CATEGORY_DEFAULT); 3539 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3540 3541 final int resolveFlags = 3542 MATCH_DIRECT_BOOT_AWARE 3543 | MATCH_DIRECT_BOOT_UNAWARE 3544 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3545 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3546 resolveFlags, UserHandle.USER_SYSTEM); 3547 // temporarily look for the old action 3548 if (matches.isEmpty()) { 3549 if (DEBUG_EPHEMERAL) { 3550 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3551 } 3552 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3553 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3554 resolveFlags, UserHandle.USER_SYSTEM); 3555 } 3556 Iterator<ResolveInfo> iter = matches.iterator(); 3557 while (iter.hasNext()) { 3558 final ResolveInfo rInfo = iter.next(); 3559 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3560 if (ps != null) { 3561 final PermissionsState permissionsState = ps.getPermissionsState(); 3562 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3563 continue; 3564 } 3565 } 3566 iter.remove(); 3567 } 3568 if (matches.size() == 0) { 3569 return null; 3570 } else if (matches.size() == 1) { 3571 return (ActivityInfo) matches.get(0).getComponentInfo(); 3572 } else { 3573 throw new RuntimeException( 3574 "There must be at most one ephemeral installer; found " + matches); 3575 } 3576 } 3577 3578 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3579 @NonNull ComponentName resolver) { 3580 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3581 .addCategory(Intent.CATEGORY_DEFAULT) 3582 .setPackage(resolver.getPackageName()); 3583 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3584 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3585 UserHandle.USER_SYSTEM); 3586 // temporarily look for the old action 3587 if (matches.isEmpty()) { 3588 if (DEBUG_EPHEMERAL) { 3589 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3590 } 3591 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3592 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3593 UserHandle.USER_SYSTEM); 3594 } 3595 if (matches.isEmpty()) { 3596 return null; 3597 } 3598 return matches.get(0).getComponentInfo().getComponentName(); 3599 } 3600 3601 private void primeDomainVerificationsLPw(int userId) { 3602 if (DEBUG_DOMAIN_VERIFICATION) { 3603 Slog.d(TAG, "Priming domain verifications in user " + userId); 3604 } 3605 3606 SystemConfig systemConfig = SystemConfig.getInstance(); 3607 ArraySet<String> packages = systemConfig.getLinkedApps(); 3608 3609 for (String packageName : packages) { 3610 PackageParser.Package pkg = mPackages.get(packageName); 3611 if (pkg != null) { 3612 if (!pkg.isSystem()) { 3613 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3614 continue; 3615 } 3616 3617 ArraySet<String> domains = null; 3618 for (PackageParser.Activity a : pkg.activities) { 3619 for (ActivityIntentInfo filter : a.intents) { 3620 if (hasValidDomains(filter)) { 3621 if (domains == null) { 3622 domains = new ArraySet<String>(); 3623 } 3624 domains.addAll(filter.getHostsList()); 3625 } 3626 } 3627 } 3628 3629 if (domains != null && domains.size() > 0) { 3630 if (DEBUG_DOMAIN_VERIFICATION) { 3631 Slog.v(TAG, " + " + packageName); 3632 } 3633 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3634 // state w.r.t. the formal app-linkage "no verification attempted" state; 3635 // and then 'always' in the per-user state actually used for intent resolution. 3636 final IntentFilterVerificationInfo ivi; 3637 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3638 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3639 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3640 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3641 } else { 3642 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3643 + "' does not handle web links"); 3644 } 3645 } else { 3646 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3647 } 3648 } 3649 3650 scheduleWritePackageRestrictionsLocked(userId); 3651 scheduleWriteSettingsLocked(); 3652 } 3653 3654 private void applyFactoryDefaultBrowserLPw(int userId) { 3655 // The default browser app's package name is stored in a string resource, 3656 // with a product-specific overlay used for vendor customization. 3657 String browserPkg = mContext.getResources().getString( 3658 com.android.internal.R.string.default_browser); 3659 if (!TextUtils.isEmpty(browserPkg)) { 3660 // non-empty string => required to be a known package 3661 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3662 if (ps == null) { 3663 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3664 browserPkg = null; 3665 } else { 3666 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3667 } 3668 } 3669 3670 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3671 // default. If there's more than one, just leave everything alone. 3672 if (browserPkg == null) { 3673 calculateDefaultBrowserLPw(userId); 3674 } 3675 } 3676 3677 private void calculateDefaultBrowserLPw(int userId) { 3678 List<String> allBrowsers = resolveAllBrowserApps(userId); 3679 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3680 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3681 } 3682 3683 private List<String> resolveAllBrowserApps(int userId) { 3684 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3685 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3686 PackageManager.MATCH_ALL, userId); 3687 3688 final int count = list.size(); 3689 List<String> result = new ArrayList<String>(count); 3690 for (int i=0; i<count; i++) { 3691 ResolveInfo info = list.get(i); 3692 if (info.activityInfo == null 3693 || !info.handleAllWebDataURI 3694 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3695 || result.contains(info.activityInfo.packageName)) { 3696 continue; 3697 } 3698 result.add(info.activityInfo.packageName); 3699 } 3700 3701 return result; 3702 } 3703 3704 private boolean packageIsBrowser(String packageName, int userId) { 3705 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3706 PackageManager.MATCH_ALL, userId); 3707 final int N = list.size(); 3708 for (int i = 0; i < N; i++) { 3709 ResolveInfo info = list.get(i); 3710 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3711 return true; 3712 } 3713 } 3714 return false; 3715 } 3716 3717 private void checkDefaultBrowser() { 3718 final int myUserId = UserHandle.myUserId(); 3719 final String packageName = getDefaultBrowserPackageName(myUserId); 3720 if (packageName != null) { 3721 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3722 if (info == null) { 3723 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3724 synchronized (mPackages) { 3725 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3726 } 3727 } 3728 } 3729 } 3730 3731 @Override 3732 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3733 throws RemoteException { 3734 try { 3735 return super.onTransact(code, data, reply, flags); 3736 } catch (RuntimeException e) { 3737 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3738 Slog.wtf(TAG, "Package Manager Crash", e); 3739 } 3740 throw e; 3741 } 3742 } 3743 3744 static int[] appendInts(int[] cur, int[] add) { 3745 if (add == null) return cur; 3746 if (cur == null) return add; 3747 final int N = add.length; 3748 for (int i=0; i<N; i++) { 3749 cur = appendInt(cur, add[i]); 3750 } 3751 return cur; 3752 } 3753 3754 /** 3755 * Returns whether or not a full application can see an instant application. 3756 * <p> 3757 * Currently, there are three cases in which this can occur: 3758 * <ol> 3759 * <li>The calling application is a "special" process. Special processes 3760 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3761 * <li>The calling application has the permission 3762 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3763 * <li>The calling application is the default launcher on the 3764 * system partition.</li> 3765 * </ol> 3766 */ 3767 private boolean canViewInstantApps(int callingUid, int userId) { 3768 if (callingUid < Process.FIRST_APPLICATION_UID) { 3769 return true; 3770 } 3771 if (mContext.checkCallingOrSelfPermission( 3772 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3773 return true; 3774 } 3775 if (mContext.checkCallingOrSelfPermission( 3776 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3777 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3778 if (homeComponent != null 3779 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3780 return true; 3781 } 3782 } 3783 return false; 3784 } 3785 3786 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3787 if (!sUserManager.exists(userId)) return null; 3788 if (ps == null) { 3789 return null; 3790 } 3791 PackageParser.Package p = ps.pkg; 3792 if (p == null) { 3793 return null; 3794 } 3795 final int callingUid = Binder.getCallingUid(); 3796 // Filter out ephemeral app metadata: 3797 // * The system/shell/root can see metadata for any app 3798 // * An installed app can see metadata for 1) other installed apps 3799 // and 2) ephemeral apps that have explicitly interacted with it 3800 // * Ephemeral apps can only see their own data and exposed installed apps 3801 // * Holding a signature permission allows seeing instant apps 3802 if (filterAppAccessLPr(ps, callingUid, userId)) { 3803 return null; 3804 } 3805 3806 final PermissionsState permissionsState = ps.getPermissionsState(); 3807 3808 // Compute GIDs only if requested 3809 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3810 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3811 // Compute granted permissions only if package has requested permissions 3812 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3813 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3814 final PackageUserState state = ps.readUserState(userId); 3815 3816 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3817 && ps.isSystem()) { 3818 flags |= MATCH_ANY_USER; 3819 } 3820 3821 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3822 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3823 3824 if (packageInfo == null) { 3825 return null; 3826 } 3827 3828 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3829 resolveExternalPackageNameLPr(p); 3830 3831 return packageInfo; 3832 } 3833 3834 @Override 3835 public void checkPackageStartable(String packageName, int userId) { 3836 final int callingUid = Binder.getCallingUid(); 3837 if (getInstantAppPackageName(callingUid) != null) { 3838 throw new SecurityException("Instant applications don't have access to this method"); 3839 } 3840 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3841 synchronized (mPackages) { 3842 final PackageSetting ps = mSettings.mPackages.get(packageName); 3843 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3844 throw new SecurityException("Package " + packageName + " was not found!"); 3845 } 3846 3847 if (!ps.getInstalled(userId)) { 3848 throw new SecurityException( 3849 "Package " + packageName + " was not installed for user " + userId + "!"); 3850 } 3851 3852 if (mSafeMode && !ps.isSystem()) { 3853 throw new SecurityException("Package " + packageName + " not a system app!"); 3854 } 3855 3856 if (mFrozenPackages.contains(packageName)) { 3857 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3858 } 3859 3860 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3861 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3862 } 3863 } 3864 } 3865 3866 @Override 3867 public boolean isPackageAvailable(String packageName, int userId) { 3868 if (!sUserManager.exists(userId)) return false; 3869 final int callingUid = Binder.getCallingUid(); 3870 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3871 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3872 synchronized (mPackages) { 3873 PackageParser.Package p = mPackages.get(packageName); 3874 if (p != null) { 3875 final PackageSetting ps = (PackageSetting) p.mExtras; 3876 if (filterAppAccessLPr(ps, callingUid, userId)) { 3877 return false; 3878 } 3879 if (ps != null) { 3880 final PackageUserState state = ps.readUserState(userId); 3881 if (state != null) { 3882 return PackageParser.isAvailable(state); 3883 } 3884 } 3885 } 3886 } 3887 return false; 3888 } 3889 3890 @Override 3891 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3892 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3893 flags, Binder.getCallingUid(), userId); 3894 } 3895 3896 @Override 3897 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3898 int flags, int userId) { 3899 return getPackageInfoInternal(versionedPackage.getPackageName(), 3900 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3901 } 3902 3903 /** 3904 * Important: The provided filterCallingUid is used exclusively to filter out packages 3905 * that can be seen based on user state. It's typically the original caller uid prior 3906 * to clearing. Because it can only be provided by trusted code, it's value can be 3907 * trusted and will be used as-is; unlike userId which will be validated by this method. 3908 */ 3909 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3910 int flags, int filterCallingUid, int userId) { 3911 if (!sUserManager.exists(userId)) return null; 3912 flags = updateFlagsForPackage(flags, userId, packageName); 3913 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3914 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3915 3916 // reader 3917 synchronized (mPackages) { 3918 // Normalize package name to handle renamed packages and static libs 3919 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3920 3921 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3922 if (matchFactoryOnly) { 3923 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3924 if (ps != null) { 3925 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3926 return null; 3927 } 3928 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3929 return null; 3930 } 3931 return generatePackageInfo(ps, flags, userId); 3932 } 3933 } 3934 3935 PackageParser.Package p = mPackages.get(packageName); 3936 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3937 return null; 3938 } 3939 if (DEBUG_PACKAGE_INFO) 3940 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3941 if (p != null) { 3942 final PackageSetting ps = (PackageSetting) p.mExtras; 3943 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3944 return null; 3945 } 3946 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3947 return null; 3948 } 3949 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3950 } 3951 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3952 final PackageSetting ps = mSettings.mPackages.get(packageName); 3953 if (ps == null) return null; 3954 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3955 return null; 3956 } 3957 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3958 return null; 3959 } 3960 return generatePackageInfo(ps, flags, userId); 3961 } 3962 } 3963 return null; 3964 } 3965 3966 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3967 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3968 return true; 3969 } 3970 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3971 return true; 3972 } 3973 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3974 return true; 3975 } 3976 return false; 3977 } 3978 3979 private boolean isComponentVisibleToInstantApp( 3980 @Nullable ComponentName component, @ComponentType int type) { 3981 if (type == TYPE_ACTIVITY) { 3982 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3983 return activity != null 3984 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3985 : false; 3986 } else if (type == TYPE_RECEIVER) { 3987 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3988 return activity != null 3989 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3990 : false; 3991 } else if (type == TYPE_SERVICE) { 3992 final PackageParser.Service service = mServices.mServices.get(component); 3993 return service != null 3994 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3995 : false; 3996 } else if (type == TYPE_PROVIDER) { 3997 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3998 return provider != null 3999 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4000 : false; 4001 } else if (type == TYPE_UNKNOWN) { 4002 return isComponentVisibleToInstantApp(component); 4003 } 4004 return false; 4005 } 4006 4007 /** 4008 * Returns whether or not access to the application should be filtered. 4009 * <p> 4010 * Access may be limited based upon whether the calling or target applications 4011 * are instant applications. 4012 * 4013 * @see #canAccessInstantApps(int) 4014 */ 4015 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4016 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4017 // if we're in an isolated process, get the real calling UID 4018 if (Process.isIsolated(callingUid)) { 4019 callingUid = mIsolatedOwners.get(callingUid); 4020 } 4021 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4022 final boolean callerIsInstantApp = instantAppPkgName != null; 4023 if (ps == null) { 4024 if (callerIsInstantApp) { 4025 // pretend the application exists, but, needs to be filtered 4026 return true; 4027 } 4028 return false; 4029 } 4030 // if the target and caller are the same application, don't filter 4031 if (isCallerSameApp(ps.name, callingUid)) { 4032 return false; 4033 } 4034 if (callerIsInstantApp) { 4035 // request for a specific component; if it hasn't been explicitly exposed, filter 4036 if (component != null) { 4037 return !isComponentVisibleToInstantApp(component, componentType); 4038 } 4039 // request for application; if no components have been explicitly exposed, filter 4040 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4041 } 4042 if (ps.getInstantApp(userId)) { 4043 // caller can see all components of all instant applications, don't filter 4044 if (canViewInstantApps(callingUid, userId)) { 4045 return false; 4046 } 4047 // request for a specific instant application component, filter 4048 if (component != null) { 4049 return true; 4050 } 4051 // request for an instant application; if the caller hasn't been granted access, filter 4052 return !mInstantAppRegistry.isInstantAccessGranted( 4053 userId, UserHandle.getAppId(callingUid), ps.appId); 4054 } 4055 return false; 4056 } 4057 4058 /** 4059 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4060 */ 4061 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4062 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4063 } 4064 4065 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4066 int flags) { 4067 // Callers can access only the libs they depend on, otherwise they need to explicitly 4068 // ask for the shared libraries given the caller is allowed to access all static libs. 4069 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4070 // System/shell/root get to see all static libs 4071 final int appId = UserHandle.getAppId(uid); 4072 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4073 || appId == Process.ROOT_UID) { 4074 return false; 4075 } 4076 } 4077 4078 // No package means no static lib as it is always on internal storage 4079 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4080 return false; 4081 } 4082 4083 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4084 ps.pkg.staticSharedLibVersion); 4085 if (libEntry == null) { 4086 return false; 4087 } 4088 4089 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4090 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4091 if (uidPackageNames == null) { 4092 return true; 4093 } 4094 4095 for (String uidPackageName : uidPackageNames) { 4096 if (ps.name.equals(uidPackageName)) { 4097 return false; 4098 } 4099 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4100 if (uidPs != null) { 4101 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4102 libEntry.info.getName()); 4103 if (index < 0) { 4104 continue; 4105 } 4106 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4107 return false; 4108 } 4109 } 4110 } 4111 return true; 4112 } 4113 4114 @Override 4115 public String[] currentToCanonicalPackageNames(String[] names) { 4116 final int callingUid = Binder.getCallingUid(); 4117 if (getInstantAppPackageName(callingUid) != null) { 4118 return names; 4119 } 4120 final String[] out = new String[names.length]; 4121 // reader 4122 synchronized (mPackages) { 4123 final int callingUserId = UserHandle.getUserId(callingUid); 4124 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4125 for (int i=names.length-1; i>=0; i--) { 4126 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4127 boolean translateName = false; 4128 if (ps != null && ps.realName != null) { 4129 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4130 translateName = !targetIsInstantApp 4131 || canViewInstantApps 4132 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4133 UserHandle.getAppId(callingUid), ps.appId); 4134 } 4135 out[i] = translateName ? ps.realName : names[i]; 4136 } 4137 } 4138 return out; 4139 } 4140 4141 @Override 4142 public String[] canonicalToCurrentPackageNames(String[] names) { 4143 final int callingUid = Binder.getCallingUid(); 4144 if (getInstantAppPackageName(callingUid) != null) { 4145 return names; 4146 } 4147 final String[] out = new String[names.length]; 4148 // reader 4149 synchronized (mPackages) { 4150 final int callingUserId = UserHandle.getUserId(callingUid); 4151 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4152 for (int i=names.length-1; i>=0; i--) { 4153 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4154 boolean translateName = false; 4155 if (cur != null) { 4156 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4157 final boolean targetIsInstantApp = 4158 ps != null && ps.getInstantApp(callingUserId); 4159 translateName = !targetIsInstantApp 4160 || canViewInstantApps 4161 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4162 UserHandle.getAppId(callingUid), ps.appId); 4163 } 4164 out[i] = translateName ? cur : names[i]; 4165 } 4166 } 4167 return out; 4168 } 4169 4170 @Override 4171 public int getPackageUid(String packageName, int flags, int userId) { 4172 if (!sUserManager.exists(userId)) return -1; 4173 final int callingUid = Binder.getCallingUid(); 4174 flags = updateFlagsForPackage(flags, userId, packageName); 4175 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4176 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4177 4178 // reader 4179 synchronized (mPackages) { 4180 final PackageParser.Package p = mPackages.get(packageName); 4181 if (p != null && p.isMatch(flags)) { 4182 PackageSetting ps = (PackageSetting) p.mExtras; 4183 if (filterAppAccessLPr(ps, callingUid, userId)) { 4184 return -1; 4185 } 4186 return UserHandle.getUid(userId, p.applicationInfo.uid); 4187 } 4188 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4189 final PackageSetting ps = mSettings.mPackages.get(packageName); 4190 if (ps != null && ps.isMatch(flags) 4191 && !filterAppAccessLPr(ps, callingUid, userId)) { 4192 return UserHandle.getUid(userId, ps.appId); 4193 } 4194 } 4195 } 4196 4197 return -1; 4198 } 4199 4200 @Override 4201 public int[] getPackageGids(String packageName, int flags, int userId) { 4202 if (!sUserManager.exists(userId)) return null; 4203 final int callingUid = Binder.getCallingUid(); 4204 flags = updateFlagsForPackage(flags, userId, packageName); 4205 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4206 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4207 4208 // reader 4209 synchronized (mPackages) { 4210 final PackageParser.Package p = mPackages.get(packageName); 4211 if (p != null && p.isMatch(flags)) { 4212 PackageSetting ps = (PackageSetting) p.mExtras; 4213 if (filterAppAccessLPr(ps, callingUid, userId)) { 4214 return null; 4215 } 4216 // TODO: Shouldn't this be checking for package installed state for userId and 4217 // return null? 4218 return ps.getPermissionsState().computeGids(userId); 4219 } 4220 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4221 final PackageSetting ps = mSettings.mPackages.get(packageName); 4222 if (ps != null && ps.isMatch(flags) 4223 && !filterAppAccessLPr(ps, callingUid, userId)) { 4224 return ps.getPermissionsState().computeGids(userId); 4225 } 4226 } 4227 } 4228 4229 return null; 4230 } 4231 4232 @Override 4233 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4234 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4235 } 4236 4237 @Override 4238 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4239 int flags) { 4240 final List<PermissionInfo> permissionList = 4241 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4242 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4243 } 4244 4245 @Override 4246 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4247 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4248 } 4249 4250 @Override 4251 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4252 final List<PermissionGroupInfo> permissionList = 4253 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4254 return (permissionList == null) 4255 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4256 } 4257 4258 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4259 int filterCallingUid, int userId) { 4260 if (!sUserManager.exists(userId)) return null; 4261 PackageSetting ps = mSettings.mPackages.get(packageName); 4262 if (ps != null) { 4263 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4264 return null; 4265 } 4266 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4267 return null; 4268 } 4269 if (ps.pkg == null) { 4270 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4271 if (pInfo != null) { 4272 return pInfo.applicationInfo; 4273 } 4274 return null; 4275 } 4276 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4277 ps.readUserState(userId), userId); 4278 if (ai != null) { 4279 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4280 } 4281 return ai; 4282 } 4283 return null; 4284 } 4285 4286 @Override 4287 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4288 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4289 } 4290 4291 /** 4292 * Important: The provided filterCallingUid is used exclusively to filter out applications 4293 * that can be seen based on user state. It's typically the original caller uid prior 4294 * to clearing. Because it can only be provided by trusted code, it's value can be 4295 * trusted and will be used as-is; unlike userId which will be validated by this method. 4296 */ 4297 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4298 int filterCallingUid, int userId) { 4299 if (!sUserManager.exists(userId)) return null; 4300 flags = updateFlagsForApplication(flags, userId, packageName); 4301 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4302 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4303 4304 // writer 4305 synchronized (mPackages) { 4306 // Normalize package name to handle renamed packages and static libs 4307 packageName = resolveInternalPackageNameLPr(packageName, 4308 PackageManager.VERSION_CODE_HIGHEST); 4309 4310 PackageParser.Package p = mPackages.get(packageName); 4311 if (DEBUG_PACKAGE_INFO) Log.v( 4312 TAG, "getApplicationInfo " + packageName 4313 + ": " + p); 4314 if (p != null) { 4315 PackageSetting ps = mSettings.mPackages.get(packageName); 4316 if (ps == null) return null; 4317 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4318 return null; 4319 } 4320 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4321 return null; 4322 } 4323 // Note: isEnabledLP() does not apply here - always return info 4324 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4325 p, flags, ps.readUserState(userId), userId); 4326 if (ai != null) { 4327 ai.packageName = resolveExternalPackageNameLPr(p); 4328 } 4329 return ai; 4330 } 4331 if ("android".equals(packageName)||"system".equals(packageName)) { 4332 return mAndroidApplication; 4333 } 4334 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4335 // Already generates the external package name 4336 return generateApplicationInfoFromSettingsLPw(packageName, 4337 flags, filterCallingUid, userId); 4338 } 4339 } 4340 return null; 4341 } 4342 4343 private String normalizePackageNameLPr(String packageName) { 4344 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4345 return normalizedPackageName != null ? normalizedPackageName : packageName; 4346 } 4347 4348 @Override 4349 public void deletePreloadsFileCache() { 4350 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4351 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4352 } 4353 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4354 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4355 FileUtils.deleteContents(dir); 4356 } 4357 4358 @Override 4359 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4360 final int storageFlags, final IPackageDataObserver observer) { 4361 mContext.enforceCallingOrSelfPermission( 4362 android.Manifest.permission.CLEAR_APP_CACHE, null); 4363 mHandler.post(() -> { 4364 boolean success = false; 4365 try { 4366 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4367 success = true; 4368 } catch (IOException e) { 4369 Slog.w(TAG, e); 4370 } 4371 if (observer != null) { 4372 try { 4373 observer.onRemoveCompleted(null, success); 4374 } catch (RemoteException e) { 4375 Slog.w(TAG, e); 4376 } 4377 } 4378 }); 4379 } 4380 4381 @Override 4382 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4383 final int storageFlags, final IntentSender pi) { 4384 mContext.enforceCallingOrSelfPermission( 4385 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4386 mHandler.post(() -> { 4387 boolean success = false; 4388 try { 4389 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4390 success = true; 4391 } catch (IOException e) { 4392 Slog.w(TAG, e); 4393 } 4394 if (pi != null) { 4395 try { 4396 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4397 } catch (SendIntentException e) { 4398 Slog.w(TAG, e); 4399 } 4400 } 4401 }); 4402 } 4403 4404 /** 4405 * Blocking call to clear various types of cached data across the system 4406 * until the requested bytes are available. 4407 */ 4408 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4409 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4410 final File file = storage.findPathForUuid(volumeUuid); 4411 if (file.getUsableSpace() >= bytes) return; 4412 4413 if (ENABLE_FREE_CACHE_V2) { 4414 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4415 volumeUuid); 4416 final boolean aggressive = (storageFlags 4417 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4418 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4419 4420 // 1. Pre-flight to determine if we have any chance to succeed 4421 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4422 if (internalVolume && (aggressive || SystemProperties 4423 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4424 deletePreloadsFileCache(); 4425 if (file.getUsableSpace() >= bytes) return; 4426 } 4427 4428 // 3. Consider parsed APK data (aggressive only) 4429 if (internalVolume && aggressive) { 4430 FileUtils.deleteContents(mCacheDir); 4431 if (file.getUsableSpace() >= bytes) return; 4432 } 4433 4434 // 4. Consider cached app data (above quotas) 4435 try { 4436 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4437 Installer.FLAG_FREE_CACHE_V2); 4438 } catch (InstallerException ignored) { 4439 } 4440 if (file.getUsableSpace() >= bytes) return; 4441 4442 // 5. Consider shared libraries with refcount=0 and age>min cache period 4443 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4444 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4445 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4446 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4447 return; 4448 } 4449 4450 // 6. Consider dexopt output (aggressive only) 4451 // TODO: Implement 4452 4453 // 7. Consider installed instant apps unused longer than min cache period 4454 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4455 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4456 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4457 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4458 return; 4459 } 4460 4461 // 8. Consider cached app data (below quotas) 4462 try { 4463 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4464 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4465 } catch (InstallerException ignored) { 4466 } 4467 if (file.getUsableSpace() >= bytes) return; 4468 4469 // 9. Consider DropBox entries 4470 // TODO: Implement 4471 4472 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4473 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4474 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4475 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4476 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4477 return; 4478 } 4479 } else { 4480 try { 4481 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4482 } catch (InstallerException ignored) { 4483 } 4484 if (file.getUsableSpace() >= bytes) return; 4485 } 4486 4487 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4488 } 4489 4490 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4491 throws IOException { 4492 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4493 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4494 4495 List<VersionedPackage> packagesToDelete = null; 4496 final long now = System.currentTimeMillis(); 4497 4498 synchronized (mPackages) { 4499 final int[] allUsers = sUserManager.getUserIds(); 4500 final int libCount = mSharedLibraries.size(); 4501 for (int i = 0; i < libCount; i++) { 4502 final LongSparseArray<SharedLibraryEntry> versionedLib 4503 = mSharedLibraries.valueAt(i); 4504 if (versionedLib == null) { 4505 continue; 4506 } 4507 final int versionCount = versionedLib.size(); 4508 for (int j = 0; j < versionCount; j++) { 4509 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4510 // Skip packages that are not static shared libs. 4511 if (!libInfo.isStatic()) { 4512 break; 4513 } 4514 // Important: We skip static shared libs used for some user since 4515 // in such a case we need to keep the APK on the device. The check for 4516 // a lib being used for any user is performed by the uninstall call. 4517 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4518 // Resolve the package name - we use synthetic package names internally 4519 final String internalPackageName = resolveInternalPackageNameLPr( 4520 declaringPackage.getPackageName(), 4521 declaringPackage.getLongVersionCode()); 4522 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4523 // Skip unused static shared libs cached less than the min period 4524 // to prevent pruning a lib needed by a subsequently installed package. 4525 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4526 continue; 4527 } 4528 if (packagesToDelete == null) { 4529 packagesToDelete = new ArrayList<>(); 4530 } 4531 packagesToDelete.add(new VersionedPackage(internalPackageName, 4532 declaringPackage.getLongVersionCode())); 4533 } 4534 } 4535 } 4536 4537 if (packagesToDelete != null) { 4538 final int packageCount = packagesToDelete.size(); 4539 for (int i = 0; i < packageCount; i++) { 4540 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4541 // Delete the package synchronously (will fail of the lib used for any user). 4542 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4543 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4544 == PackageManager.DELETE_SUCCEEDED) { 4545 if (volume.getUsableSpace() >= neededSpace) { 4546 return true; 4547 } 4548 } 4549 } 4550 } 4551 4552 return false; 4553 } 4554 4555 /** 4556 * Update given flags based on encryption status of current user. 4557 */ 4558 private int updateFlags(int flags, int userId) { 4559 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4560 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4561 // Caller expressed an explicit opinion about what encryption 4562 // aware/unaware components they want to see, so fall through and 4563 // give them what they want 4564 } else { 4565 // Caller expressed no opinion, so match based on user state 4566 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4567 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4568 } else { 4569 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4570 } 4571 } 4572 return flags; 4573 } 4574 4575 private UserManagerInternal getUserManagerInternal() { 4576 if (mUserManagerInternal == null) { 4577 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4578 } 4579 return mUserManagerInternal; 4580 } 4581 4582 private DeviceIdleController.LocalService getDeviceIdleController() { 4583 if (mDeviceIdleController == null) { 4584 mDeviceIdleController = 4585 LocalServices.getService(DeviceIdleController.LocalService.class); 4586 } 4587 return mDeviceIdleController; 4588 } 4589 4590 /** 4591 * Update given flags when being used to request {@link PackageInfo}. 4592 */ 4593 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4594 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4595 boolean triaged = true; 4596 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4597 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4598 // Caller is asking for component details, so they'd better be 4599 // asking for specific encryption matching behavior, or be triaged 4600 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4601 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4602 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4603 triaged = false; 4604 } 4605 } 4606 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4607 | PackageManager.MATCH_SYSTEM_ONLY 4608 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4609 triaged = false; 4610 } 4611 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4612 mPermissionManager.enforceCrossUserPermission( 4613 Binder.getCallingUid(), userId, false, false, 4614 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4615 + Debug.getCallers(5)); 4616 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4617 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4618 // If the caller wants all packages and has a restricted profile associated with it, 4619 // then match all users. This is to make sure that launchers that need to access work 4620 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4621 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4622 flags |= PackageManager.MATCH_ANY_USER; 4623 } 4624 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4625 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4626 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4627 } 4628 return updateFlags(flags, userId); 4629 } 4630 4631 /** 4632 * Update given flags when being used to request {@link ApplicationInfo}. 4633 */ 4634 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4635 return updateFlagsForPackage(flags, userId, cookie); 4636 } 4637 4638 /** 4639 * Update given flags when being used to request {@link ComponentInfo}. 4640 */ 4641 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4642 if (cookie instanceof Intent) { 4643 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4644 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4645 } 4646 } 4647 4648 boolean triaged = true; 4649 // Caller is asking for component details, so they'd better be 4650 // asking for specific encryption matching behavior, or be triaged 4651 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4652 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4653 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4654 triaged = false; 4655 } 4656 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4657 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4658 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4659 } 4660 4661 return updateFlags(flags, userId); 4662 } 4663 4664 /** 4665 * Update given intent when being used to request {@link ResolveInfo}. 4666 */ 4667 private Intent updateIntentForResolve(Intent intent) { 4668 if (intent.getSelector() != null) { 4669 intent = intent.getSelector(); 4670 } 4671 if (DEBUG_PREFERRED) { 4672 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4673 } 4674 return intent; 4675 } 4676 4677 /** 4678 * Update given flags when being used to request {@link ResolveInfo}. 4679 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4680 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4681 * flag set. However, this flag is only honoured in three circumstances: 4682 * <ul> 4683 * <li>when called from a system process</li> 4684 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4685 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4686 * action and a {@code android.intent.category.BROWSABLE} category</li> 4687 * </ul> 4688 */ 4689 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4690 return updateFlagsForResolve(flags, userId, intent, callingUid, 4691 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4692 } 4693 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4694 boolean wantInstantApps) { 4695 return updateFlagsForResolve(flags, userId, intent, callingUid, 4696 wantInstantApps, false /*onlyExposedExplicitly*/); 4697 } 4698 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4699 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4700 // Safe mode means we shouldn't match any third-party components 4701 if (mSafeMode) { 4702 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4703 } 4704 if (getInstantAppPackageName(callingUid) != null) { 4705 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4706 if (onlyExposedExplicitly) { 4707 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4708 } 4709 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4710 flags |= PackageManager.MATCH_INSTANT; 4711 } else { 4712 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4713 final boolean allowMatchInstant = 4714 (wantInstantApps 4715 && Intent.ACTION_VIEW.equals(intent.getAction()) 4716 && hasWebURI(intent)) 4717 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4718 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4719 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4720 if (!allowMatchInstant) { 4721 flags &= ~PackageManager.MATCH_INSTANT; 4722 } 4723 } 4724 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4725 } 4726 4727 @Override 4728 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4729 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4730 } 4731 4732 /** 4733 * Important: The provided filterCallingUid is used exclusively to filter out activities 4734 * that can be seen based on user state. It's typically the original caller uid prior 4735 * to clearing. Because it can only be provided by trusted code, it's value can be 4736 * trusted and will be used as-is; unlike userId which will be validated by this method. 4737 */ 4738 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4739 int filterCallingUid, int userId) { 4740 if (!sUserManager.exists(userId)) return null; 4741 flags = updateFlagsForComponent(flags, userId, component); 4742 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4743 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4744 synchronized (mPackages) { 4745 PackageParser.Activity a = mActivities.mActivities.get(component); 4746 4747 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4748 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4749 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4750 if (ps == null) return null; 4751 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4752 return null; 4753 } 4754 return PackageParser.generateActivityInfo( 4755 a, flags, ps.readUserState(userId), userId); 4756 } 4757 if (mResolveComponentName.equals(component)) { 4758 return PackageParser.generateActivityInfo( 4759 mResolveActivity, flags, new PackageUserState(), userId); 4760 } 4761 } 4762 return null; 4763 } 4764 4765 @Override 4766 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4767 String resolvedType) { 4768 synchronized (mPackages) { 4769 if (component.equals(mResolveComponentName)) { 4770 // The resolver supports EVERYTHING! 4771 return true; 4772 } 4773 final int callingUid = Binder.getCallingUid(); 4774 final int callingUserId = UserHandle.getUserId(callingUid); 4775 PackageParser.Activity a = mActivities.mActivities.get(component); 4776 if (a == null) { 4777 return false; 4778 } 4779 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4780 if (ps == null) { 4781 return false; 4782 } 4783 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4784 return false; 4785 } 4786 for (int i=0; i<a.intents.size(); i++) { 4787 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4788 intent.getData(), intent.getCategories(), TAG) >= 0) { 4789 return true; 4790 } 4791 } 4792 return false; 4793 } 4794 } 4795 4796 @Override 4797 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4798 if (!sUserManager.exists(userId)) return null; 4799 final int callingUid = Binder.getCallingUid(); 4800 flags = updateFlagsForComponent(flags, userId, component); 4801 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4802 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4803 synchronized (mPackages) { 4804 PackageParser.Activity a = mReceivers.mActivities.get(component); 4805 if (DEBUG_PACKAGE_INFO) Log.v( 4806 TAG, "getReceiverInfo " + component + ": " + a); 4807 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4808 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4809 if (ps == null) return null; 4810 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4811 return null; 4812 } 4813 return PackageParser.generateActivityInfo( 4814 a, flags, ps.readUserState(userId), userId); 4815 } 4816 } 4817 return null; 4818 } 4819 4820 @Override 4821 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4822 int flags, int userId) { 4823 if (!sUserManager.exists(userId)) return null; 4824 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4825 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4826 return null; 4827 } 4828 4829 flags = updateFlagsForPackage(flags, userId, null); 4830 4831 final boolean canSeeStaticLibraries = 4832 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4833 == PERMISSION_GRANTED 4834 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4835 == PERMISSION_GRANTED 4836 || canRequestPackageInstallsInternal(packageName, 4837 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4838 false /* throwIfPermNotDeclared*/) 4839 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4840 == PERMISSION_GRANTED; 4841 4842 synchronized (mPackages) { 4843 List<SharedLibraryInfo> result = null; 4844 4845 final int libCount = mSharedLibraries.size(); 4846 for (int i = 0; i < libCount; i++) { 4847 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4848 if (versionedLib == null) { 4849 continue; 4850 } 4851 4852 final int versionCount = versionedLib.size(); 4853 for (int j = 0; j < versionCount; j++) { 4854 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4855 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4856 break; 4857 } 4858 final long identity = Binder.clearCallingIdentity(); 4859 try { 4860 PackageInfo packageInfo = getPackageInfoVersioned( 4861 libInfo.getDeclaringPackage(), flags 4862 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4863 if (packageInfo == null) { 4864 continue; 4865 } 4866 } finally { 4867 Binder.restoreCallingIdentity(identity); 4868 } 4869 4870 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4871 libInfo.getLongVersion(), libInfo.getType(), 4872 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4873 flags, userId)); 4874 4875 if (result == null) { 4876 result = new ArrayList<>(); 4877 } 4878 result.add(resLibInfo); 4879 } 4880 } 4881 4882 return result != null ? new ParceledListSlice<>(result) : null; 4883 } 4884 } 4885 4886 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4887 SharedLibraryInfo libInfo, int flags, int userId) { 4888 List<VersionedPackage> versionedPackages = null; 4889 final int packageCount = mSettings.mPackages.size(); 4890 for (int i = 0; i < packageCount; i++) { 4891 PackageSetting ps = mSettings.mPackages.valueAt(i); 4892 4893 if (ps == null) { 4894 continue; 4895 } 4896 4897 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4898 continue; 4899 } 4900 4901 final String libName = libInfo.getName(); 4902 if (libInfo.isStatic()) { 4903 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4904 if (libIdx < 0) { 4905 continue; 4906 } 4907 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4908 continue; 4909 } 4910 if (versionedPackages == null) { 4911 versionedPackages = new ArrayList<>(); 4912 } 4913 // If the dependent is a static shared lib, use the public package name 4914 String dependentPackageName = ps.name; 4915 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4916 dependentPackageName = ps.pkg.manifestPackageName; 4917 } 4918 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4919 } else if (ps.pkg != null) { 4920 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4921 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4922 if (versionedPackages == null) { 4923 versionedPackages = new ArrayList<>(); 4924 } 4925 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4926 } 4927 } 4928 } 4929 4930 return versionedPackages; 4931 } 4932 4933 @Override 4934 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4935 if (!sUserManager.exists(userId)) return null; 4936 final int callingUid = Binder.getCallingUid(); 4937 flags = updateFlagsForComponent(flags, userId, component); 4938 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4939 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4940 synchronized (mPackages) { 4941 PackageParser.Service s = mServices.mServices.get(component); 4942 if (DEBUG_PACKAGE_INFO) Log.v( 4943 TAG, "getServiceInfo " + component + ": " + s); 4944 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4945 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4946 if (ps == null) return null; 4947 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4948 return null; 4949 } 4950 return PackageParser.generateServiceInfo( 4951 s, flags, ps.readUserState(userId), userId); 4952 } 4953 } 4954 return null; 4955 } 4956 4957 @Override 4958 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4959 if (!sUserManager.exists(userId)) return null; 4960 final int callingUid = Binder.getCallingUid(); 4961 flags = updateFlagsForComponent(flags, userId, component); 4962 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4963 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4964 synchronized (mPackages) { 4965 PackageParser.Provider p = mProviders.mProviders.get(component); 4966 if (DEBUG_PACKAGE_INFO) Log.v( 4967 TAG, "getProviderInfo " + component + ": " + p); 4968 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4969 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4970 if (ps == null) return null; 4971 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4972 return null; 4973 } 4974 return PackageParser.generateProviderInfo( 4975 p, flags, ps.readUserState(userId), userId); 4976 } 4977 } 4978 return null; 4979 } 4980 4981 @Override 4982 public String[] getSystemSharedLibraryNames() { 4983 // allow instant applications 4984 synchronized (mPackages) { 4985 Set<String> libs = null; 4986 final int libCount = mSharedLibraries.size(); 4987 for (int i = 0; i < libCount; i++) { 4988 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4989 if (versionedLib == null) { 4990 continue; 4991 } 4992 final int versionCount = versionedLib.size(); 4993 for (int j = 0; j < versionCount; j++) { 4994 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4995 if (!libEntry.info.isStatic()) { 4996 if (libs == null) { 4997 libs = new ArraySet<>(); 4998 } 4999 libs.add(libEntry.info.getName()); 5000 break; 5001 } 5002 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5003 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5004 UserHandle.getUserId(Binder.getCallingUid()), 5005 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5006 if (libs == null) { 5007 libs = new ArraySet<>(); 5008 } 5009 libs.add(libEntry.info.getName()); 5010 break; 5011 } 5012 } 5013 } 5014 5015 if (libs != null) { 5016 String[] libsArray = new String[libs.size()]; 5017 libs.toArray(libsArray); 5018 return libsArray; 5019 } 5020 5021 return null; 5022 } 5023 } 5024 5025 @Override 5026 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5027 // allow instant applications 5028 synchronized (mPackages) { 5029 return mServicesSystemSharedLibraryPackageName; 5030 } 5031 } 5032 5033 @Override 5034 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5035 // allow instant applications 5036 synchronized (mPackages) { 5037 return mSharedSystemSharedLibraryPackageName; 5038 } 5039 } 5040 5041 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5042 for (int i = userList.length - 1; i >= 0; --i) { 5043 final int userId = userList[i]; 5044 // don't add instant app to the list of updates 5045 if (pkgSetting.getInstantApp(userId)) { 5046 continue; 5047 } 5048 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5049 if (changedPackages == null) { 5050 changedPackages = new SparseArray<>(); 5051 mChangedPackages.put(userId, changedPackages); 5052 } 5053 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5054 if (sequenceNumbers == null) { 5055 sequenceNumbers = new HashMap<>(); 5056 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5057 } 5058 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5059 if (sequenceNumber != null) { 5060 changedPackages.remove(sequenceNumber); 5061 } 5062 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5063 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5064 } 5065 mChangedPackagesSequenceNumber++; 5066 } 5067 5068 @Override 5069 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5070 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5071 return null; 5072 } 5073 synchronized (mPackages) { 5074 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5075 return null; 5076 } 5077 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5078 if (changedPackages == null) { 5079 return null; 5080 } 5081 final List<String> packageNames = 5082 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5083 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5084 final String packageName = changedPackages.get(i); 5085 if (packageName != null) { 5086 packageNames.add(packageName); 5087 } 5088 } 5089 return packageNames.isEmpty() 5090 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5091 } 5092 } 5093 5094 @Override 5095 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5096 // allow instant applications 5097 ArrayList<FeatureInfo> res; 5098 synchronized (mAvailableFeatures) { 5099 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5100 res.addAll(mAvailableFeatures.values()); 5101 } 5102 final FeatureInfo fi = new FeatureInfo(); 5103 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5104 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5105 res.add(fi); 5106 5107 return new ParceledListSlice<>(res); 5108 } 5109 5110 @Override 5111 public boolean hasSystemFeature(String name, int version) { 5112 // allow instant applications 5113 synchronized (mAvailableFeatures) { 5114 final FeatureInfo feat = mAvailableFeatures.get(name); 5115 if (feat == null) { 5116 return false; 5117 } else { 5118 return feat.version >= version; 5119 } 5120 } 5121 } 5122 5123 @Override 5124 public int checkPermission(String permName, String pkgName, int userId) { 5125 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5126 } 5127 5128 @Override 5129 public int checkUidPermission(String permName, int uid) { 5130 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5131 } 5132 5133 @Override 5134 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5135 if (UserHandle.getCallingUserId() != userId) { 5136 mContext.enforceCallingPermission( 5137 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5138 "isPermissionRevokedByPolicy for user " + userId); 5139 } 5140 5141 if (checkPermission(permission, packageName, userId) 5142 == PackageManager.PERMISSION_GRANTED) { 5143 return false; 5144 } 5145 5146 final int callingUid = Binder.getCallingUid(); 5147 if (getInstantAppPackageName(callingUid) != null) { 5148 if (!isCallerSameApp(packageName, callingUid)) { 5149 return false; 5150 } 5151 } else { 5152 if (isInstantApp(packageName, userId)) { 5153 return false; 5154 } 5155 } 5156 5157 final long identity = Binder.clearCallingIdentity(); 5158 try { 5159 final int flags = getPermissionFlags(permission, packageName, userId); 5160 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5161 } finally { 5162 Binder.restoreCallingIdentity(identity); 5163 } 5164 } 5165 5166 @Override 5167 public String getPermissionControllerPackageName() { 5168 synchronized (mPackages) { 5169 return mRequiredInstallerPackage; 5170 } 5171 } 5172 5173 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5174 return mPermissionManager.addDynamicPermission( 5175 info, async, getCallingUid(), new PermissionCallback() { 5176 @Override 5177 public void onPermissionChanged() { 5178 if (!async) { 5179 mSettings.writeLPr(); 5180 } else { 5181 scheduleWriteSettingsLocked(); 5182 } 5183 } 5184 }); 5185 } 5186 5187 @Override 5188 public boolean addPermission(PermissionInfo info) { 5189 synchronized (mPackages) { 5190 return addDynamicPermission(info, false); 5191 } 5192 } 5193 5194 @Override 5195 public boolean addPermissionAsync(PermissionInfo info) { 5196 synchronized (mPackages) { 5197 return addDynamicPermission(info, true); 5198 } 5199 } 5200 5201 @Override 5202 public void removePermission(String permName) { 5203 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5204 } 5205 5206 @Override 5207 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5208 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5209 getCallingUid(), userId, mPermissionCallback); 5210 } 5211 5212 @Override 5213 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5214 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5215 getCallingUid(), userId, mPermissionCallback); 5216 } 5217 5218 @Override 5219 public void resetRuntimePermissions() { 5220 mContext.enforceCallingOrSelfPermission( 5221 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5222 "revokeRuntimePermission"); 5223 5224 int callingUid = Binder.getCallingUid(); 5225 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5226 mContext.enforceCallingOrSelfPermission( 5227 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5228 "resetRuntimePermissions"); 5229 } 5230 5231 synchronized (mPackages) { 5232 mPermissionManager.updateAllPermissions( 5233 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5234 mPermissionCallback); 5235 for (int userId : UserManagerService.getInstance().getUserIds()) { 5236 final int packageCount = mPackages.size(); 5237 for (int i = 0; i < packageCount; i++) { 5238 PackageParser.Package pkg = mPackages.valueAt(i); 5239 if (!(pkg.mExtras instanceof PackageSetting)) { 5240 continue; 5241 } 5242 PackageSetting ps = (PackageSetting) pkg.mExtras; 5243 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5244 } 5245 } 5246 } 5247 } 5248 5249 @Override 5250 public int getPermissionFlags(String permName, String packageName, int userId) { 5251 return mPermissionManager.getPermissionFlags( 5252 permName, packageName, getCallingUid(), userId); 5253 } 5254 5255 @Override 5256 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5257 int flagValues, int userId) { 5258 mPermissionManager.updatePermissionFlags( 5259 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5260 mPermissionCallback); 5261 } 5262 5263 /** 5264 * Update the permission flags for all packages and runtime permissions of a user in order 5265 * to allow device or profile owner to remove POLICY_FIXED. 5266 */ 5267 @Override 5268 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5269 synchronized (mPackages) { 5270 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5271 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5272 mPermissionCallback); 5273 if (changed) { 5274 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5275 } 5276 } 5277 } 5278 5279 @Override 5280 public boolean shouldShowRequestPermissionRationale(String permissionName, 5281 String packageName, int userId) { 5282 if (UserHandle.getCallingUserId() != userId) { 5283 mContext.enforceCallingPermission( 5284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5285 "canShowRequestPermissionRationale for user " + userId); 5286 } 5287 5288 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5289 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5290 return false; 5291 } 5292 5293 if (checkPermission(permissionName, packageName, userId) 5294 == PackageManager.PERMISSION_GRANTED) { 5295 return false; 5296 } 5297 5298 final int flags; 5299 5300 final long identity = Binder.clearCallingIdentity(); 5301 try { 5302 flags = getPermissionFlags(permissionName, 5303 packageName, userId); 5304 } finally { 5305 Binder.restoreCallingIdentity(identity); 5306 } 5307 5308 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5309 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5310 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5311 5312 if ((flags & fixedFlags) != 0) { 5313 return false; 5314 } 5315 5316 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5317 } 5318 5319 @Override 5320 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5321 mContext.enforceCallingOrSelfPermission( 5322 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5323 "addOnPermissionsChangeListener"); 5324 5325 synchronized (mPackages) { 5326 mOnPermissionChangeListeners.addListenerLocked(listener); 5327 } 5328 } 5329 5330 @Override 5331 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5332 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5333 throw new SecurityException("Instant applications don't have access to this method"); 5334 } 5335 synchronized (mPackages) { 5336 mOnPermissionChangeListeners.removeListenerLocked(listener); 5337 } 5338 } 5339 5340 @Override 5341 public boolean isProtectedBroadcast(String actionName) { 5342 // allow instant applications 5343 synchronized (mProtectedBroadcasts) { 5344 if (mProtectedBroadcasts.contains(actionName)) { 5345 return true; 5346 } else if (actionName != null) { 5347 // TODO: remove these terrible hacks 5348 if (actionName.startsWith("android.net.netmon.lingerExpired") 5349 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5350 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5351 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5352 return true; 5353 } 5354 } 5355 } 5356 return false; 5357 } 5358 5359 @Override 5360 public int checkSignatures(String pkg1, String pkg2) { 5361 synchronized (mPackages) { 5362 final PackageParser.Package p1 = mPackages.get(pkg1); 5363 final PackageParser.Package p2 = mPackages.get(pkg2); 5364 if (p1 == null || p1.mExtras == null 5365 || p2 == null || p2.mExtras == null) { 5366 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5367 } 5368 final int callingUid = Binder.getCallingUid(); 5369 final int callingUserId = UserHandle.getUserId(callingUid); 5370 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5371 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5372 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5373 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5374 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5375 } 5376 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5377 } 5378 } 5379 5380 @Override 5381 public int checkUidSignatures(int uid1, int uid2) { 5382 final int callingUid = Binder.getCallingUid(); 5383 final int callingUserId = UserHandle.getUserId(callingUid); 5384 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5385 // Map to base uids. 5386 uid1 = UserHandle.getAppId(uid1); 5387 uid2 = UserHandle.getAppId(uid2); 5388 // reader 5389 synchronized (mPackages) { 5390 Signature[] s1; 5391 Signature[] s2; 5392 Object obj = mSettings.getUserIdLPr(uid1); 5393 if (obj != null) { 5394 if (obj instanceof SharedUserSetting) { 5395 if (isCallerInstantApp) { 5396 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5397 } 5398 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5399 } else if (obj instanceof PackageSetting) { 5400 final PackageSetting ps = (PackageSetting) obj; 5401 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5402 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5403 } 5404 s1 = ps.signatures.mSigningDetails.signatures; 5405 } else { 5406 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5407 } 5408 } else { 5409 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5410 } 5411 obj = mSettings.getUserIdLPr(uid2); 5412 if (obj != null) { 5413 if (obj instanceof SharedUserSetting) { 5414 if (isCallerInstantApp) { 5415 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5416 } 5417 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5418 } else if (obj instanceof PackageSetting) { 5419 final PackageSetting ps = (PackageSetting) obj; 5420 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5421 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5422 } 5423 s2 = ps.signatures.mSigningDetails.signatures; 5424 } else { 5425 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5426 } 5427 } else { 5428 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5429 } 5430 return compareSignatures(s1, s2); 5431 } 5432 } 5433 5434 @Override 5435 public boolean hasSigningCertificate( 5436 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5437 5438 synchronized (mPackages) { 5439 final PackageParser.Package p = mPackages.get(packageName); 5440 if (p == null || p.mExtras == null) { 5441 return false; 5442 } 5443 final int callingUid = Binder.getCallingUid(); 5444 final int callingUserId = UserHandle.getUserId(callingUid); 5445 final PackageSetting ps = (PackageSetting) p.mExtras; 5446 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5447 return false; 5448 } 5449 switch (type) { 5450 case CERT_INPUT_RAW_X509: 5451 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5452 case CERT_INPUT_SHA256: 5453 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5454 default: 5455 return false; 5456 } 5457 } 5458 } 5459 5460 @Override 5461 public boolean hasUidSigningCertificate( 5462 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5463 final int callingUid = Binder.getCallingUid(); 5464 final int callingUserId = UserHandle.getUserId(callingUid); 5465 // Map to base uids. 5466 uid = UserHandle.getAppId(uid); 5467 // reader 5468 synchronized (mPackages) { 5469 final PackageParser.SigningDetails signingDetails; 5470 final Object obj = mSettings.getUserIdLPr(uid); 5471 if (obj != null) { 5472 if (obj instanceof SharedUserSetting) { 5473 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5474 if (isCallerInstantApp) { 5475 return false; 5476 } 5477 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5478 } else if (obj instanceof PackageSetting) { 5479 final PackageSetting ps = (PackageSetting) obj; 5480 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5481 return false; 5482 } 5483 signingDetails = ps.signatures.mSigningDetails; 5484 } else { 5485 return false; 5486 } 5487 } else { 5488 return false; 5489 } 5490 switch (type) { 5491 case CERT_INPUT_RAW_X509: 5492 return signingDetailsHasCertificate(certificate, signingDetails); 5493 case CERT_INPUT_SHA256: 5494 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5495 default: 5496 return false; 5497 } 5498 } 5499 } 5500 5501 /** 5502 * This method should typically only be used when granting or revoking 5503 * permissions, since the app may immediately restart after this call. 5504 * <p> 5505 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5506 * guard your work against the app being relaunched. 5507 */ 5508 private void killUid(int appId, int userId, String reason) { 5509 final long identity = Binder.clearCallingIdentity(); 5510 try { 5511 IActivityManager am = ActivityManager.getService(); 5512 if (am != null) { 5513 try { 5514 am.killUid(appId, userId, reason); 5515 } catch (RemoteException e) { 5516 /* ignore - same process */ 5517 } 5518 } 5519 } finally { 5520 Binder.restoreCallingIdentity(identity); 5521 } 5522 } 5523 5524 /** 5525 * If the database version for this type of package (internal storage or 5526 * external storage) is less than the version where package signatures 5527 * were updated, return true. 5528 */ 5529 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5530 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5531 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5532 } 5533 5534 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5535 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5536 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5537 } 5538 5539 @Override 5540 public List<String> getAllPackages() { 5541 final int callingUid = Binder.getCallingUid(); 5542 final int callingUserId = UserHandle.getUserId(callingUid); 5543 synchronized (mPackages) { 5544 if (canViewInstantApps(callingUid, callingUserId)) { 5545 return new ArrayList<String>(mPackages.keySet()); 5546 } 5547 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5548 final List<String> result = new ArrayList<>(); 5549 if (instantAppPkgName != null) { 5550 // caller is an instant application; filter unexposed applications 5551 for (PackageParser.Package pkg : mPackages.values()) { 5552 if (!pkg.visibleToInstantApps) { 5553 continue; 5554 } 5555 result.add(pkg.packageName); 5556 } 5557 } else { 5558 // caller is a normal application; filter instant applications 5559 for (PackageParser.Package pkg : mPackages.values()) { 5560 final PackageSetting ps = 5561 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5562 if (ps != null 5563 && ps.getInstantApp(callingUserId) 5564 && !mInstantAppRegistry.isInstantAccessGranted( 5565 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5566 continue; 5567 } 5568 result.add(pkg.packageName); 5569 } 5570 } 5571 return result; 5572 } 5573 } 5574 5575 @Override 5576 public String[] getPackagesForUid(int uid) { 5577 final int callingUid = Binder.getCallingUid(); 5578 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5579 final int userId = UserHandle.getUserId(uid); 5580 uid = UserHandle.getAppId(uid); 5581 // reader 5582 synchronized (mPackages) { 5583 Object obj = mSettings.getUserIdLPr(uid); 5584 if (obj instanceof SharedUserSetting) { 5585 if (isCallerInstantApp) { 5586 return null; 5587 } 5588 final SharedUserSetting sus = (SharedUserSetting) obj; 5589 final int N = sus.packages.size(); 5590 String[] res = new String[N]; 5591 final Iterator<PackageSetting> it = sus.packages.iterator(); 5592 int i = 0; 5593 while (it.hasNext()) { 5594 PackageSetting ps = it.next(); 5595 if (ps.getInstalled(userId)) { 5596 res[i++] = ps.name; 5597 } else { 5598 res = ArrayUtils.removeElement(String.class, res, res[i]); 5599 } 5600 } 5601 return res; 5602 } else if (obj instanceof PackageSetting) { 5603 final PackageSetting ps = (PackageSetting) obj; 5604 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5605 return new String[]{ps.name}; 5606 } 5607 } 5608 } 5609 return null; 5610 } 5611 5612 @Override 5613 public String getNameForUid(int uid) { 5614 final int callingUid = Binder.getCallingUid(); 5615 if (getInstantAppPackageName(callingUid) != null) { 5616 return null; 5617 } 5618 synchronized (mPackages) { 5619 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5620 if (obj instanceof SharedUserSetting) { 5621 final SharedUserSetting sus = (SharedUserSetting) obj; 5622 return sus.name + ":" + sus.userId; 5623 } else if (obj instanceof PackageSetting) { 5624 final PackageSetting ps = (PackageSetting) obj; 5625 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5626 return null; 5627 } 5628 return ps.name; 5629 } 5630 return null; 5631 } 5632 } 5633 5634 @Override 5635 public String[] getNamesForUids(int[] uids) { 5636 if (uids == null || uids.length == 0) { 5637 return null; 5638 } 5639 final int callingUid = Binder.getCallingUid(); 5640 if (getInstantAppPackageName(callingUid) != null) { 5641 return null; 5642 } 5643 final String[] names = new String[uids.length]; 5644 synchronized (mPackages) { 5645 for (int i = uids.length - 1; i >= 0; i--) { 5646 final int uid = uids[i]; 5647 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5648 if (obj instanceof SharedUserSetting) { 5649 final SharedUserSetting sus = (SharedUserSetting) obj; 5650 names[i] = "shared:" + sus.name; 5651 } else if (obj instanceof PackageSetting) { 5652 final PackageSetting ps = (PackageSetting) obj; 5653 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5654 names[i] = null; 5655 } else { 5656 names[i] = ps.name; 5657 } 5658 } else { 5659 names[i] = null; 5660 } 5661 } 5662 } 5663 return names; 5664 } 5665 5666 @Override 5667 public int getUidForSharedUser(String sharedUserName) { 5668 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5669 return -1; 5670 } 5671 if (sharedUserName == null) { 5672 return -1; 5673 } 5674 // reader 5675 synchronized (mPackages) { 5676 SharedUserSetting suid; 5677 try { 5678 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5679 if (suid != null) { 5680 return suid.userId; 5681 } 5682 } catch (PackageManagerException ignore) { 5683 // can't happen, but, still need to catch it 5684 } 5685 return -1; 5686 } 5687 } 5688 5689 @Override 5690 public int getFlagsForUid(int uid) { 5691 final int callingUid = Binder.getCallingUid(); 5692 if (getInstantAppPackageName(callingUid) != null) { 5693 return 0; 5694 } 5695 synchronized (mPackages) { 5696 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5697 if (obj instanceof SharedUserSetting) { 5698 final SharedUserSetting sus = (SharedUserSetting) obj; 5699 return sus.pkgFlags; 5700 } else if (obj instanceof PackageSetting) { 5701 final PackageSetting ps = (PackageSetting) obj; 5702 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5703 return 0; 5704 } 5705 return ps.pkgFlags; 5706 } 5707 } 5708 return 0; 5709 } 5710 5711 @Override 5712 public int getPrivateFlagsForUid(int uid) { 5713 final int callingUid = Binder.getCallingUid(); 5714 if (getInstantAppPackageName(callingUid) != null) { 5715 return 0; 5716 } 5717 synchronized (mPackages) { 5718 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5719 if (obj instanceof SharedUserSetting) { 5720 final SharedUserSetting sus = (SharedUserSetting) obj; 5721 return sus.pkgPrivateFlags; 5722 } else if (obj instanceof PackageSetting) { 5723 final PackageSetting ps = (PackageSetting) obj; 5724 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5725 return 0; 5726 } 5727 return ps.pkgPrivateFlags; 5728 } 5729 } 5730 return 0; 5731 } 5732 5733 @Override 5734 public boolean isUidPrivileged(int uid) { 5735 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5736 return false; 5737 } 5738 uid = UserHandle.getAppId(uid); 5739 // reader 5740 synchronized (mPackages) { 5741 Object obj = mSettings.getUserIdLPr(uid); 5742 if (obj instanceof SharedUserSetting) { 5743 final SharedUserSetting sus = (SharedUserSetting) obj; 5744 final Iterator<PackageSetting> it = sus.packages.iterator(); 5745 while (it.hasNext()) { 5746 if (it.next().isPrivileged()) { 5747 return true; 5748 } 5749 } 5750 } else if (obj instanceof PackageSetting) { 5751 final PackageSetting ps = (PackageSetting) obj; 5752 return ps.isPrivileged(); 5753 } 5754 } 5755 return false; 5756 } 5757 5758 @Override 5759 public String[] getAppOpPermissionPackages(String permName) { 5760 return mPermissionManager.getAppOpPermissionPackages(permName); 5761 } 5762 5763 @Override 5764 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5765 int flags, int userId) { 5766 return resolveIntentInternal( 5767 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5768 } 5769 5770 /** 5771 * Normally instant apps can only be resolved when they're visible to the caller. 5772 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5773 * since we need to allow the system to start any installed application. 5774 */ 5775 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5776 int flags, int userId, boolean resolveForStart) { 5777 try { 5778 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5779 5780 if (!sUserManager.exists(userId)) return null; 5781 final int callingUid = Binder.getCallingUid(); 5782 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5783 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5784 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5785 5786 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5787 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5788 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5789 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5790 5791 final ResolveInfo bestChoice = 5792 chooseBestActivity(intent, resolvedType, flags, query, userId); 5793 return bestChoice; 5794 } finally { 5795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5796 } 5797 } 5798 5799 @Override 5800 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5801 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5802 throw new SecurityException( 5803 "findPersistentPreferredActivity can only be run by the system"); 5804 } 5805 if (!sUserManager.exists(userId)) { 5806 return null; 5807 } 5808 final int callingUid = Binder.getCallingUid(); 5809 intent = updateIntentForResolve(intent); 5810 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5811 final int flags = updateFlagsForResolve( 5812 0, userId, intent, callingUid, false /*includeInstantApps*/); 5813 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5814 userId); 5815 synchronized (mPackages) { 5816 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5817 userId); 5818 } 5819 } 5820 5821 @Override 5822 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5823 IntentFilter filter, int match, ComponentName activity) { 5824 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5825 return; 5826 } 5827 final int userId = UserHandle.getCallingUserId(); 5828 if (DEBUG_PREFERRED) { 5829 Log.v(TAG, "setLastChosenActivity intent=" + intent 5830 + " resolvedType=" + resolvedType 5831 + " flags=" + flags 5832 + " filter=" + filter 5833 + " match=" + match 5834 + " activity=" + activity); 5835 filter.dump(new PrintStreamPrinter(System.out), " "); 5836 } 5837 intent.setComponent(null); 5838 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5839 userId); 5840 // Find any earlier preferred or last chosen entries and nuke them 5841 findPreferredActivity(intent, resolvedType, 5842 flags, query, 0, false, true, false, userId); 5843 // Add the new activity as the last chosen for this filter 5844 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5845 "Setting last chosen"); 5846 } 5847 5848 @Override 5849 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5850 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5851 return null; 5852 } 5853 final int userId = UserHandle.getCallingUserId(); 5854 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5855 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5856 userId); 5857 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5858 false, false, false, userId); 5859 } 5860 5861 /** 5862 * Returns whether or not instant apps have been disabled remotely. 5863 */ 5864 private boolean isEphemeralDisabled() { 5865 return mEphemeralAppsDisabled; 5866 } 5867 5868 private boolean isInstantAppAllowed( 5869 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5870 boolean skipPackageCheck) { 5871 if (mInstantAppResolverConnection == null) { 5872 return false; 5873 } 5874 if (mInstantAppInstallerActivity == null) { 5875 return false; 5876 } 5877 if (intent.getComponent() != null) { 5878 return false; 5879 } 5880 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5881 return false; 5882 } 5883 if (!skipPackageCheck && intent.getPackage() != null) { 5884 return false; 5885 } 5886 final boolean isWebUri = hasWebURI(intent); 5887 if (!isWebUri || intent.getData().getHost() == null) { 5888 return false; 5889 } 5890 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5891 // Or if there's already an ephemeral app installed that handles the action 5892 synchronized (mPackages) { 5893 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5894 for (int n = 0; n < count; n++) { 5895 final ResolveInfo info = resolvedActivities.get(n); 5896 final String packageName = info.activityInfo.packageName; 5897 final PackageSetting ps = mSettings.mPackages.get(packageName); 5898 if (ps != null) { 5899 // only check domain verification status if the app is not a browser 5900 if (!info.handleAllWebDataURI) { 5901 // Try to get the status from User settings first 5902 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5903 final int status = (int) (packedStatus >> 32); 5904 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5905 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5906 if (DEBUG_EPHEMERAL) { 5907 Slog.v(TAG, "DENY instant app;" 5908 + " pkg: " + packageName + ", status: " + status); 5909 } 5910 return false; 5911 } 5912 } 5913 if (ps.getInstantApp(userId)) { 5914 if (DEBUG_EPHEMERAL) { 5915 Slog.v(TAG, "DENY instant app installed;" 5916 + " pkg: " + packageName); 5917 } 5918 return false; 5919 } 5920 } 5921 } 5922 } 5923 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5924 return true; 5925 } 5926 5927 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5928 Intent origIntent, String resolvedType, String callingPackage, 5929 Bundle verificationBundle, int userId) { 5930 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5931 new InstantAppRequest(responseObj, origIntent, resolvedType, 5932 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 5933 mHandler.sendMessage(msg); 5934 } 5935 5936 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5937 int flags, List<ResolveInfo> query, int userId) { 5938 if (query != null) { 5939 final int N = query.size(); 5940 if (N == 1) { 5941 return query.get(0); 5942 } else if (N > 1) { 5943 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5944 // If there is more than one activity with the same priority, 5945 // then let the user decide between them. 5946 ResolveInfo r0 = query.get(0); 5947 ResolveInfo r1 = query.get(1); 5948 if (DEBUG_INTENT_MATCHING || debug) { 5949 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5950 + r1.activityInfo.name + "=" + r1.priority); 5951 } 5952 // If the first activity has a higher priority, or a different 5953 // default, then it is always desirable to pick it. 5954 if (r0.priority != r1.priority 5955 || r0.preferredOrder != r1.preferredOrder 5956 || r0.isDefault != r1.isDefault) { 5957 return query.get(0); 5958 } 5959 // If we have saved a preference for a preferred activity for 5960 // this Intent, use that. 5961 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5962 flags, query, r0.priority, true, false, debug, userId); 5963 if (ri != null) { 5964 return ri; 5965 } 5966 // If we have an ephemeral app, use it 5967 for (int i = 0; i < N; i++) { 5968 ri = query.get(i); 5969 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5970 final String packageName = ri.activityInfo.packageName; 5971 final PackageSetting ps = mSettings.mPackages.get(packageName); 5972 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5973 final int status = (int)(packedStatus >> 32); 5974 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5975 return ri; 5976 } 5977 } 5978 } 5979 ri = new ResolveInfo(mResolveInfo); 5980 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5981 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5982 // If all of the options come from the same package, show the application's 5983 // label and icon instead of the generic resolver's. 5984 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5985 // and then throw away the ResolveInfo itself, meaning that the caller loses 5986 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5987 // a fallback for this case; we only set the target package's resources on 5988 // the ResolveInfo, not the ActivityInfo. 5989 final String intentPackage = intent.getPackage(); 5990 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5991 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5992 ri.resolvePackageName = intentPackage; 5993 if (userNeedsBadging(userId)) { 5994 ri.noResourceId = true; 5995 } else { 5996 ri.icon = appi.icon; 5997 } 5998 ri.iconResourceId = appi.icon; 5999 ri.labelRes = appi.labelRes; 6000 } 6001 ri.activityInfo.applicationInfo = new ApplicationInfo( 6002 ri.activityInfo.applicationInfo); 6003 if (userId != 0) { 6004 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6005 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6006 } 6007 // Make sure that the resolver is displayable in car mode 6008 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6009 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6010 return ri; 6011 } 6012 } 6013 return null; 6014 } 6015 6016 /** 6017 * Return true if the given list is not empty and all of its contents have 6018 * an activityInfo with the given package name. 6019 */ 6020 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6021 if (ArrayUtils.isEmpty(list)) { 6022 return false; 6023 } 6024 for (int i = 0, N = list.size(); i < N; i++) { 6025 final ResolveInfo ri = list.get(i); 6026 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6027 if (ai == null || !packageName.equals(ai.packageName)) { 6028 return false; 6029 } 6030 } 6031 return true; 6032 } 6033 6034 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6035 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6036 final int N = query.size(); 6037 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6038 .get(userId); 6039 // Get the list of persistent preferred activities that handle the intent 6040 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6041 List<PersistentPreferredActivity> pprefs = ppir != null 6042 ? ppir.queryIntent(intent, resolvedType, 6043 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6044 userId) 6045 : null; 6046 if (pprefs != null && pprefs.size() > 0) { 6047 final int M = pprefs.size(); 6048 for (int i=0; i<M; i++) { 6049 final PersistentPreferredActivity ppa = pprefs.get(i); 6050 if (DEBUG_PREFERRED || debug) { 6051 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6052 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6053 + "\n component=" + ppa.mComponent); 6054 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6055 } 6056 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6057 flags | MATCH_DISABLED_COMPONENTS, userId); 6058 if (DEBUG_PREFERRED || debug) { 6059 Slog.v(TAG, "Found persistent preferred activity:"); 6060 if (ai != null) { 6061 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6062 } else { 6063 Slog.v(TAG, " null"); 6064 } 6065 } 6066 if (ai == null) { 6067 // This previously registered persistent preferred activity 6068 // component is no longer known. Ignore it and do NOT remove it. 6069 continue; 6070 } 6071 for (int j=0; j<N; j++) { 6072 final ResolveInfo ri = query.get(j); 6073 if (!ri.activityInfo.applicationInfo.packageName 6074 .equals(ai.applicationInfo.packageName)) { 6075 continue; 6076 } 6077 if (!ri.activityInfo.name.equals(ai.name)) { 6078 continue; 6079 } 6080 // Found a persistent preference that can handle the intent. 6081 if (DEBUG_PREFERRED || debug) { 6082 Slog.v(TAG, "Returning persistent preferred activity: " + 6083 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6084 } 6085 return ri; 6086 } 6087 } 6088 } 6089 return null; 6090 } 6091 6092 // TODO: handle preferred activities missing while user has amnesia 6093 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6094 List<ResolveInfo> query, int priority, boolean always, 6095 boolean removeMatches, boolean debug, int userId) { 6096 if (!sUserManager.exists(userId)) return null; 6097 final int callingUid = Binder.getCallingUid(); 6098 flags = updateFlagsForResolve( 6099 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6100 intent = updateIntentForResolve(intent); 6101 // writer 6102 synchronized (mPackages) { 6103 // Try to find a matching persistent preferred activity. 6104 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6105 debug, userId); 6106 6107 // If a persistent preferred activity matched, use it. 6108 if (pri != null) { 6109 return pri; 6110 } 6111 6112 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6113 // Get the list of preferred activities that handle the intent 6114 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6115 List<PreferredActivity> prefs = pir != null 6116 ? pir.queryIntent(intent, resolvedType, 6117 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6118 userId) 6119 : null; 6120 if (prefs != null && prefs.size() > 0) { 6121 boolean changed = false; 6122 try { 6123 // First figure out how good the original match set is. 6124 // We will only allow preferred activities that came 6125 // from the same match quality. 6126 int match = 0; 6127 6128 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6129 6130 final int N = query.size(); 6131 for (int j=0; j<N; j++) { 6132 final ResolveInfo ri = query.get(j); 6133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6134 + ": 0x" + Integer.toHexString(match)); 6135 if (ri.match > match) { 6136 match = ri.match; 6137 } 6138 } 6139 6140 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6141 + Integer.toHexString(match)); 6142 6143 match &= IntentFilter.MATCH_CATEGORY_MASK; 6144 final int M = prefs.size(); 6145 for (int i=0; i<M; i++) { 6146 final PreferredActivity pa = prefs.get(i); 6147 if (DEBUG_PREFERRED || debug) { 6148 Slog.v(TAG, "Checking PreferredActivity ds=" 6149 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6150 + "\n component=" + pa.mPref.mComponent); 6151 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6152 } 6153 if (pa.mPref.mMatch != match) { 6154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6155 + Integer.toHexString(pa.mPref.mMatch)); 6156 continue; 6157 } 6158 // If it's not an "always" type preferred activity and that's what we're 6159 // looking for, skip it. 6160 if (always && !pa.mPref.mAlways) { 6161 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6162 continue; 6163 } 6164 final ActivityInfo ai = getActivityInfo( 6165 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6166 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6167 userId); 6168 if (DEBUG_PREFERRED || debug) { 6169 Slog.v(TAG, "Found preferred activity:"); 6170 if (ai != null) { 6171 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6172 } else { 6173 Slog.v(TAG, " null"); 6174 } 6175 } 6176 if (ai == null) { 6177 // This previously registered preferred activity 6178 // component is no longer known. Most likely an update 6179 // to the app was installed and in the new version this 6180 // component no longer exists. Clean it up by removing 6181 // it from the preferred activities list, and skip it. 6182 Slog.w(TAG, "Removing dangling preferred activity: " 6183 + pa.mPref.mComponent); 6184 pir.removeFilter(pa); 6185 changed = true; 6186 continue; 6187 } 6188 for (int j=0; j<N; j++) { 6189 final ResolveInfo ri = query.get(j); 6190 if (!ri.activityInfo.applicationInfo.packageName 6191 .equals(ai.applicationInfo.packageName)) { 6192 continue; 6193 } 6194 if (!ri.activityInfo.name.equals(ai.name)) { 6195 continue; 6196 } 6197 6198 if (removeMatches) { 6199 pir.removeFilter(pa); 6200 changed = true; 6201 if (DEBUG_PREFERRED) { 6202 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6203 } 6204 break; 6205 } 6206 6207 // Okay we found a previously set preferred or last chosen app. 6208 // If the result set is different from when this 6209 // was created, and is not a subset of the preferred set, we need to 6210 // clear it and re-ask the user their preference, if we're looking for 6211 // an "always" type entry. 6212 if (always && !pa.mPref.sameSet(query)) { 6213 if (pa.mPref.isSuperset(query)) { 6214 // some components of the set are no longer present in 6215 // the query, but the preferred activity can still be reused 6216 if (DEBUG_PREFERRED) { 6217 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6218 + " still valid as only non-preferred components" 6219 + " were removed for " + intent + " type " 6220 + resolvedType); 6221 } 6222 // remove obsolete components and re-add the up-to-date filter 6223 PreferredActivity freshPa = new PreferredActivity(pa, 6224 pa.mPref.mMatch, 6225 pa.mPref.discardObsoleteComponents(query), 6226 pa.mPref.mComponent, 6227 pa.mPref.mAlways); 6228 pir.removeFilter(pa); 6229 pir.addFilter(freshPa); 6230 changed = true; 6231 } else { 6232 Slog.i(TAG, 6233 "Result set changed, dropping preferred activity for " 6234 + intent + " type " + resolvedType); 6235 if (DEBUG_PREFERRED) { 6236 Slog.v(TAG, "Removing preferred activity since set changed " 6237 + pa.mPref.mComponent); 6238 } 6239 pir.removeFilter(pa); 6240 // Re-add the filter as a "last chosen" entry (!always) 6241 PreferredActivity lastChosen = new PreferredActivity( 6242 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6243 pir.addFilter(lastChosen); 6244 changed = true; 6245 return null; 6246 } 6247 } 6248 6249 // Yay! Either the set matched or we're looking for the last chosen 6250 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6251 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6252 return ri; 6253 } 6254 } 6255 } finally { 6256 if (changed) { 6257 if (DEBUG_PREFERRED) { 6258 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6259 } 6260 scheduleWritePackageRestrictionsLocked(userId); 6261 } 6262 } 6263 } 6264 } 6265 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6266 return null; 6267 } 6268 6269 /* 6270 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6271 */ 6272 @Override 6273 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6274 int targetUserId) { 6275 mContext.enforceCallingOrSelfPermission( 6276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6277 List<CrossProfileIntentFilter> matches = 6278 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6279 if (matches != null) { 6280 int size = matches.size(); 6281 for (int i = 0; i < size; i++) { 6282 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6283 } 6284 } 6285 if (hasWebURI(intent)) { 6286 // cross-profile app linking works only towards the parent. 6287 final int callingUid = Binder.getCallingUid(); 6288 final UserInfo parent = getProfileParent(sourceUserId); 6289 synchronized(mPackages) { 6290 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6291 false /*includeInstantApps*/); 6292 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6293 intent, resolvedType, flags, sourceUserId, parent.id); 6294 return xpDomainInfo != null; 6295 } 6296 } 6297 return false; 6298 } 6299 6300 private UserInfo getProfileParent(int userId) { 6301 final long identity = Binder.clearCallingIdentity(); 6302 try { 6303 return sUserManager.getProfileParent(userId); 6304 } finally { 6305 Binder.restoreCallingIdentity(identity); 6306 } 6307 } 6308 6309 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6310 String resolvedType, int userId) { 6311 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6312 if (resolver != null) { 6313 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6314 } 6315 return null; 6316 } 6317 6318 @Override 6319 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6320 String resolvedType, int flags, int userId) { 6321 try { 6322 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6323 6324 return new ParceledListSlice<>( 6325 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6326 } finally { 6327 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6328 } 6329 } 6330 6331 /** 6332 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6333 * instant, returns {@code null}. 6334 */ 6335 private String getInstantAppPackageName(int callingUid) { 6336 synchronized (mPackages) { 6337 // If the caller is an isolated app use the owner's uid for the lookup. 6338 if (Process.isIsolated(callingUid)) { 6339 callingUid = mIsolatedOwners.get(callingUid); 6340 } 6341 final int appId = UserHandle.getAppId(callingUid); 6342 final Object obj = mSettings.getUserIdLPr(appId); 6343 if (obj instanceof PackageSetting) { 6344 final PackageSetting ps = (PackageSetting) obj; 6345 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6346 return isInstantApp ? ps.pkg.packageName : null; 6347 } 6348 } 6349 return null; 6350 } 6351 6352 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6353 String resolvedType, int flags, int userId) { 6354 return queryIntentActivitiesInternal( 6355 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6356 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6357 } 6358 6359 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6360 String resolvedType, int flags, int filterCallingUid, int userId, 6361 boolean resolveForStart, boolean allowDynamicSplits) { 6362 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6363 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6364 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6365 false /* requireFullPermission */, false /* checkShell */, 6366 "query intent activities"); 6367 final String pkgName = intent.getPackage(); 6368 ComponentName comp = intent.getComponent(); 6369 if (comp == null) { 6370 if (intent.getSelector() != null) { 6371 intent = intent.getSelector(); 6372 comp = intent.getComponent(); 6373 } 6374 } 6375 6376 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6377 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6378 if (comp != null) { 6379 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6380 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6381 if (ai != null) { 6382 // When specifying an explicit component, we prevent the activity from being 6383 // used when either 1) the calling package is normal and the activity is within 6384 // an ephemeral application or 2) the calling package is ephemeral and the 6385 // activity is not visible to ephemeral applications. 6386 final boolean matchInstantApp = 6387 (flags & PackageManager.MATCH_INSTANT) != 0; 6388 final boolean matchVisibleToInstantAppOnly = 6389 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6390 final boolean matchExplicitlyVisibleOnly = 6391 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6392 final boolean isCallerInstantApp = 6393 instantAppPkgName != null; 6394 final boolean isTargetSameInstantApp = 6395 comp.getPackageName().equals(instantAppPkgName); 6396 final boolean isTargetInstantApp = 6397 (ai.applicationInfo.privateFlags 6398 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6399 final boolean isTargetVisibleToInstantApp = 6400 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6401 final boolean isTargetExplicitlyVisibleToInstantApp = 6402 isTargetVisibleToInstantApp 6403 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6404 final boolean isTargetHiddenFromInstantApp = 6405 !isTargetVisibleToInstantApp 6406 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6407 final boolean blockResolution = 6408 !isTargetSameInstantApp 6409 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6410 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6411 && isTargetHiddenFromInstantApp)); 6412 if (!blockResolution) { 6413 final ResolveInfo ri = new ResolveInfo(); 6414 ri.activityInfo = ai; 6415 list.add(ri); 6416 } 6417 } 6418 return applyPostResolutionFilter( 6419 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6420 } 6421 6422 // reader 6423 boolean sortResult = false; 6424 boolean addEphemeral = false; 6425 List<ResolveInfo> result; 6426 final boolean ephemeralDisabled = isEphemeralDisabled(); 6427 synchronized (mPackages) { 6428 if (pkgName == null) { 6429 List<CrossProfileIntentFilter> matchingFilters = 6430 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6431 // Check for results that need to skip the current profile. 6432 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6433 resolvedType, flags, userId); 6434 if (xpResolveInfo != null) { 6435 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6436 xpResult.add(xpResolveInfo); 6437 return applyPostResolutionFilter( 6438 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6439 allowDynamicSplits, filterCallingUid, userId); 6440 } 6441 6442 // Check for results in the current profile. 6443 result = filterIfNotSystemUser(mActivities.queryIntent( 6444 intent, resolvedType, flags, userId), userId); 6445 addEphemeral = !ephemeralDisabled 6446 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6447 // Check for cross profile results. 6448 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6449 xpResolveInfo = queryCrossProfileIntents( 6450 matchingFilters, intent, resolvedType, flags, userId, 6451 hasNonNegativePriorityResult); 6452 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6453 boolean isVisibleToUser = filterIfNotSystemUser( 6454 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6455 if (isVisibleToUser) { 6456 result.add(xpResolveInfo); 6457 sortResult = true; 6458 } 6459 } 6460 if (hasWebURI(intent)) { 6461 CrossProfileDomainInfo xpDomainInfo = null; 6462 final UserInfo parent = getProfileParent(userId); 6463 if (parent != null) { 6464 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6465 flags, userId, parent.id); 6466 } 6467 if (xpDomainInfo != null) { 6468 if (xpResolveInfo != null) { 6469 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6470 // in the result. 6471 result.remove(xpResolveInfo); 6472 } 6473 if (result.size() == 0 && !addEphemeral) { 6474 // No result in current profile, but found candidate in parent user. 6475 // And we are not going to add emphemeral app, so we can return the 6476 // result straight away. 6477 result.add(xpDomainInfo.resolveInfo); 6478 return applyPostResolutionFilter(result, instantAppPkgName, 6479 allowDynamicSplits, filterCallingUid, userId); 6480 } 6481 } else if (result.size() <= 1 && !addEphemeral) { 6482 // No result in parent user and <= 1 result in current profile, and we 6483 // are not going to add emphemeral app, so we can return the result without 6484 // further processing. 6485 return applyPostResolutionFilter(result, instantAppPkgName, 6486 allowDynamicSplits, filterCallingUid, userId); 6487 } 6488 // We have more than one candidate (combining results from current and parent 6489 // profile), so we need filtering and sorting. 6490 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6491 intent, flags, result, xpDomainInfo, userId); 6492 sortResult = true; 6493 } 6494 } else { 6495 final PackageParser.Package pkg = mPackages.get(pkgName); 6496 result = null; 6497 if (pkg != null) { 6498 result = filterIfNotSystemUser( 6499 mActivities.queryIntentForPackage( 6500 intent, resolvedType, flags, pkg.activities, userId), 6501 userId); 6502 } 6503 if (result == null || result.size() == 0) { 6504 // the caller wants to resolve for a particular package; however, there 6505 // were no installed results, so, try to find an ephemeral result 6506 addEphemeral = !ephemeralDisabled 6507 && isInstantAppAllowed( 6508 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6509 if (result == null) { 6510 result = new ArrayList<>(); 6511 } 6512 } 6513 } 6514 } 6515 if (addEphemeral) { 6516 result = maybeAddInstantAppInstaller( 6517 result, intent, resolvedType, flags, userId, resolveForStart); 6518 } 6519 if (sortResult) { 6520 Collections.sort(result, mResolvePrioritySorter); 6521 } 6522 return applyPostResolutionFilter( 6523 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6524 } 6525 6526 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6527 String resolvedType, int flags, int userId, boolean resolveForStart) { 6528 // first, check to see if we've got an instant app already installed 6529 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6530 ResolveInfo localInstantApp = null; 6531 boolean blockResolution = false; 6532 if (!alreadyResolvedLocally) { 6533 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6534 flags 6535 | PackageManager.GET_RESOLVED_FILTER 6536 | PackageManager.MATCH_INSTANT 6537 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6538 userId); 6539 for (int i = instantApps.size() - 1; i >= 0; --i) { 6540 final ResolveInfo info = instantApps.get(i); 6541 final String packageName = info.activityInfo.packageName; 6542 final PackageSetting ps = mSettings.mPackages.get(packageName); 6543 if (ps.getInstantApp(userId)) { 6544 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6545 final int status = (int)(packedStatus >> 32); 6546 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6547 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6548 // there's a local instant application installed, but, the user has 6549 // chosen to never use it; skip resolution and don't acknowledge 6550 // an instant application is even available 6551 if (DEBUG_EPHEMERAL) { 6552 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6553 } 6554 blockResolution = true; 6555 break; 6556 } else { 6557 // we have a locally installed instant application; skip resolution 6558 // but acknowledge there's an instant application available 6559 if (DEBUG_EPHEMERAL) { 6560 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6561 } 6562 localInstantApp = info; 6563 break; 6564 } 6565 } 6566 } 6567 } 6568 // no app installed, let's see if one's available 6569 AuxiliaryResolveInfo auxiliaryResponse = null; 6570 if (!blockResolution) { 6571 if (localInstantApp == null) { 6572 // we don't have an instant app locally, resolve externally 6573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6574 final InstantAppRequest requestObject = new InstantAppRequest( 6575 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6576 null /*callingPackage*/, userId, null /*verificationBundle*/, 6577 resolveForStart); 6578 auxiliaryResponse = 6579 InstantAppResolver.doInstantAppResolutionPhaseOne( 6580 mContext, mInstantAppResolverConnection, requestObject); 6581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6582 } else { 6583 // we have an instant application locally, but, we can't admit that since 6584 // callers shouldn't be able to determine prior browsing. create a dummy 6585 // auxiliary response so the downstream code behaves as if there's an 6586 // instant application available externally. when it comes time to start 6587 // the instant application, we'll do the right thing. 6588 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6589 auxiliaryResponse = new AuxiliaryResolveInfo( 6590 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6591 ai.versionCode, null /*failureIntent*/); 6592 } 6593 } 6594 if (auxiliaryResponse != null) { 6595 if (DEBUG_EPHEMERAL) { 6596 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6597 } 6598 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6599 final PackageSetting ps = 6600 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6601 if (ps != null) { 6602 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6603 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6604 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6605 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6606 // make sure this resolver is the default 6607 ephemeralInstaller.isDefault = true; 6608 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6609 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6610 // add a non-generic filter 6611 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6612 ephemeralInstaller.filter.addDataPath( 6613 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6614 ephemeralInstaller.isInstantAppAvailable = true; 6615 result.add(ephemeralInstaller); 6616 } 6617 } 6618 return result; 6619 } 6620 6621 private static class CrossProfileDomainInfo { 6622 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6623 ResolveInfo resolveInfo; 6624 /* Best domain verification status of the activities found in the other profile */ 6625 int bestDomainVerificationStatus; 6626 } 6627 6628 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6629 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6630 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6631 sourceUserId)) { 6632 return null; 6633 } 6634 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6635 resolvedType, flags, parentUserId); 6636 6637 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6638 return null; 6639 } 6640 CrossProfileDomainInfo result = null; 6641 int size = resultTargetUser.size(); 6642 for (int i = 0; i < size; i++) { 6643 ResolveInfo riTargetUser = resultTargetUser.get(i); 6644 // Intent filter verification is only for filters that specify a host. So don't return 6645 // those that handle all web uris. 6646 if (riTargetUser.handleAllWebDataURI) { 6647 continue; 6648 } 6649 String packageName = riTargetUser.activityInfo.packageName; 6650 PackageSetting ps = mSettings.mPackages.get(packageName); 6651 if (ps == null) { 6652 continue; 6653 } 6654 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6655 int status = (int)(verificationState >> 32); 6656 if (result == null) { 6657 result = new CrossProfileDomainInfo(); 6658 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6659 sourceUserId, parentUserId); 6660 result.bestDomainVerificationStatus = status; 6661 } else { 6662 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6663 result.bestDomainVerificationStatus); 6664 } 6665 } 6666 // Don't consider matches with status NEVER across profiles. 6667 if (result != null && result.bestDomainVerificationStatus 6668 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6669 return null; 6670 } 6671 return result; 6672 } 6673 6674 /** 6675 * Verification statuses are ordered from the worse to the best, except for 6676 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6677 */ 6678 private int bestDomainVerificationStatus(int status1, int status2) { 6679 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6680 return status2; 6681 } 6682 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6683 return status1; 6684 } 6685 return (int) MathUtils.max(status1, status2); 6686 } 6687 6688 private boolean isUserEnabled(int userId) { 6689 long callingId = Binder.clearCallingIdentity(); 6690 try { 6691 UserInfo userInfo = sUserManager.getUserInfo(userId); 6692 return userInfo != null && userInfo.isEnabled(); 6693 } finally { 6694 Binder.restoreCallingIdentity(callingId); 6695 } 6696 } 6697 6698 /** 6699 * Filter out activities with systemUserOnly flag set, when current user is not System. 6700 * 6701 * @return filtered list 6702 */ 6703 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6704 if (userId == UserHandle.USER_SYSTEM) { 6705 return resolveInfos; 6706 } 6707 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6708 ResolveInfo info = resolveInfos.get(i); 6709 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6710 resolveInfos.remove(i); 6711 } 6712 } 6713 return resolveInfos; 6714 } 6715 6716 /** 6717 * Filters out ephemeral activities. 6718 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6719 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6720 * 6721 * @param resolveInfos The pre-filtered list of resolved activities 6722 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6723 * is performed. 6724 * @return A filtered list of resolved activities. 6725 */ 6726 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6727 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6728 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6729 final ResolveInfo info = resolveInfos.get(i); 6730 // allow activities that are defined in the provided package 6731 if (allowDynamicSplits 6732 && info.activityInfo.splitName != null 6733 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6734 info.activityInfo.splitName)) { 6735 if (mInstantAppInstallerInfo == null) { 6736 if (DEBUG_INSTALL) { 6737 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6738 } 6739 resolveInfos.remove(i); 6740 continue; 6741 } 6742 // requested activity is defined in a split that hasn't been installed yet. 6743 // add the installer to the resolve list 6744 if (DEBUG_INSTALL) { 6745 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6746 } 6747 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6748 final ComponentName installFailureActivity = findInstallFailureActivity( 6749 info.activityInfo.packageName, filterCallingUid, userId); 6750 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6751 info.activityInfo.packageName, info.activityInfo.splitName, 6752 installFailureActivity, 6753 info.activityInfo.applicationInfo.versionCode, 6754 null /*failureIntent*/); 6755 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6756 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6757 // add a non-generic filter 6758 installerInfo.filter = new IntentFilter(); 6759 6760 // This resolve info may appear in the chooser UI, so let us make it 6761 // look as the one it replaces as far as the user is concerned which 6762 // requires loading the correct label and icon for the resolve info. 6763 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6764 installerInfo.labelRes = info.resolveLabelResId(); 6765 installerInfo.icon = info.resolveIconResId(); 6766 6767 // propagate priority/preferred order/default 6768 installerInfo.priority = info.priority; 6769 installerInfo.preferredOrder = info.preferredOrder; 6770 installerInfo.isDefault = info.isDefault; 6771 resolveInfos.set(i, installerInfo); 6772 continue; 6773 } 6774 // caller is a full app, don't need to apply any other filtering 6775 if (ephemeralPkgName == null) { 6776 continue; 6777 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6778 // caller is same app; don't need to apply any other filtering 6779 continue; 6780 } 6781 // allow activities that have been explicitly exposed to ephemeral apps 6782 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6783 if (!isEphemeralApp 6784 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6785 continue; 6786 } 6787 resolveInfos.remove(i); 6788 } 6789 return resolveInfos; 6790 } 6791 6792 /** 6793 * Returns the activity component that can handle install failures. 6794 * <p>By default, the instant application installer handles failures. However, an 6795 * application may want to handle failures on its own. Applications do this by 6796 * creating an activity with an intent filter that handles the action 6797 * {@link Intent#ACTION_INSTALL_FAILURE}. 6798 */ 6799 private @Nullable ComponentName findInstallFailureActivity( 6800 String packageName, int filterCallingUid, int userId) { 6801 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6802 failureActivityIntent.setPackage(packageName); 6803 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6804 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6805 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6806 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6807 final int NR = result.size(); 6808 if (NR > 0) { 6809 for (int i = 0; i < NR; i++) { 6810 final ResolveInfo info = result.get(i); 6811 if (info.activityInfo.splitName != null) { 6812 continue; 6813 } 6814 return new ComponentName(packageName, info.activityInfo.name); 6815 } 6816 } 6817 return null; 6818 } 6819 6820 /** 6821 * @param resolveInfos list of resolve infos in descending priority order 6822 * @return if the list contains a resolve info with non-negative priority 6823 */ 6824 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6825 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6826 } 6827 6828 private static boolean hasWebURI(Intent intent) { 6829 if (intent.getData() == null) { 6830 return false; 6831 } 6832 final String scheme = intent.getScheme(); 6833 if (TextUtils.isEmpty(scheme)) { 6834 return false; 6835 } 6836 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6837 } 6838 6839 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6840 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6841 int userId) { 6842 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6843 6844 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6845 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6846 candidates.size()); 6847 } 6848 6849 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6850 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6851 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6852 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6853 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6854 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6855 6856 synchronized (mPackages) { 6857 final int count = candidates.size(); 6858 // First, try to use linked apps. Partition the candidates into four lists: 6859 // one for the final results, one for the "do not use ever", one for "undefined status" 6860 // and finally one for "browser app type". 6861 for (int n=0; n<count; n++) { 6862 ResolveInfo info = candidates.get(n); 6863 String packageName = info.activityInfo.packageName; 6864 PackageSetting ps = mSettings.mPackages.get(packageName); 6865 if (ps != null) { 6866 // Add to the special match all list (Browser use case) 6867 if (info.handleAllWebDataURI) { 6868 matchAllList.add(info); 6869 continue; 6870 } 6871 // Try to get the status from User settings first 6872 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6873 int status = (int)(packedStatus >> 32); 6874 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6875 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6876 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6877 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6878 + " : linkgen=" + linkGeneration); 6879 } 6880 // Use link-enabled generation as preferredOrder, i.e. 6881 // prefer newly-enabled over earlier-enabled. 6882 info.preferredOrder = linkGeneration; 6883 alwaysList.add(info); 6884 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6885 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6886 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6887 } 6888 neverList.add(info); 6889 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6890 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6891 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6892 } 6893 alwaysAskList.add(info); 6894 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6895 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6896 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6897 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6898 } 6899 undefinedList.add(info); 6900 } 6901 } 6902 } 6903 6904 // We'll want to include browser possibilities in a few cases 6905 boolean includeBrowser = false; 6906 6907 // First try to add the "always" resolution(s) for the current user, if any 6908 if (alwaysList.size() > 0) { 6909 result.addAll(alwaysList); 6910 } else { 6911 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6912 result.addAll(undefinedList); 6913 // Maybe add one for the other profile. 6914 if (xpDomainInfo != null && ( 6915 xpDomainInfo.bestDomainVerificationStatus 6916 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6917 result.add(xpDomainInfo.resolveInfo); 6918 } 6919 includeBrowser = true; 6920 } 6921 6922 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6923 // If there were 'always' entries their preferred order has been set, so we also 6924 // back that off to make the alternatives equivalent 6925 if (alwaysAskList.size() > 0) { 6926 for (ResolveInfo i : result) { 6927 i.preferredOrder = 0; 6928 } 6929 result.addAll(alwaysAskList); 6930 includeBrowser = true; 6931 } 6932 6933 if (includeBrowser) { 6934 // Also add browsers (all of them or only the default one) 6935 if (DEBUG_DOMAIN_VERIFICATION) { 6936 Slog.v(TAG, " ...including browsers in candidate set"); 6937 } 6938 if ((matchFlags & MATCH_ALL) != 0) { 6939 result.addAll(matchAllList); 6940 } else { 6941 // Browser/generic handling case. If there's a default browser, go straight 6942 // to that (but only if there is no other higher-priority match). 6943 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6944 int maxMatchPrio = 0; 6945 ResolveInfo defaultBrowserMatch = null; 6946 final int numCandidates = matchAllList.size(); 6947 for (int n = 0; n < numCandidates; n++) { 6948 ResolveInfo info = matchAllList.get(n); 6949 // track the highest overall match priority... 6950 if (info.priority > maxMatchPrio) { 6951 maxMatchPrio = info.priority; 6952 } 6953 // ...and the highest-priority default browser match 6954 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6955 if (defaultBrowserMatch == null 6956 || (defaultBrowserMatch.priority < info.priority)) { 6957 if (debug) { 6958 Slog.v(TAG, "Considering default browser match " + info); 6959 } 6960 defaultBrowserMatch = info; 6961 } 6962 } 6963 } 6964 if (defaultBrowserMatch != null 6965 && defaultBrowserMatch.priority >= maxMatchPrio 6966 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6967 { 6968 if (debug) { 6969 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6970 } 6971 result.add(defaultBrowserMatch); 6972 } else { 6973 result.addAll(matchAllList); 6974 } 6975 } 6976 6977 // If there is nothing selected, add all candidates and remove the ones that the user 6978 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6979 if (result.size() == 0) { 6980 result.addAll(candidates); 6981 result.removeAll(neverList); 6982 } 6983 } 6984 } 6985 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6986 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6987 result.size()); 6988 for (ResolveInfo info : result) { 6989 Slog.v(TAG, " + " + info.activityInfo); 6990 } 6991 } 6992 return result; 6993 } 6994 6995 // Returns a packed value as a long: 6996 // 6997 // high 'int'-sized word: link status: undefined/ask/never/always. 6998 // low 'int'-sized word: relative priority among 'always' results. 6999 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7000 long result = ps.getDomainVerificationStatusForUser(userId); 7001 // if none available, get the master status 7002 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7003 if (ps.getIntentFilterVerificationInfo() != null) { 7004 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7005 } 7006 } 7007 return result; 7008 } 7009 7010 private ResolveInfo querySkipCurrentProfileIntents( 7011 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7012 int flags, int sourceUserId) { 7013 if (matchingFilters != null) { 7014 int size = matchingFilters.size(); 7015 for (int i = 0; i < size; i ++) { 7016 CrossProfileIntentFilter filter = matchingFilters.get(i); 7017 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7018 // Checking if there are activities in the target user that can handle the 7019 // intent. 7020 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7021 resolvedType, flags, sourceUserId); 7022 if (resolveInfo != null) { 7023 return resolveInfo; 7024 } 7025 } 7026 } 7027 } 7028 return null; 7029 } 7030 7031 // Return matching ResolveInfo in target user if any. 7032 private ResolveInfo queryCrossProfileIntents( 7033 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7034 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7035 if (matchingFilters != null) { 7036 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7037 // match the same intent. For performance reasons, it is better not to 7038 // run queryIntent twice for the same userId 7039 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7040 int size = matchingFilters.size(); 7041 for (int i = 0; i < size; i++) { 7042 CrossProfileIntentFilter filter = matchingFilters.get(i); 7043 int targetUserId = filter.getTargetUserId(); 7044 boolean skipCurrentProfile = 7045 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7046 boolean skipCurrentProfileIfNoMatchFound = 7047 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7048 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7049 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7050 // Checking if there are activities in the target user that can handle the 7051 // intent. 7052 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7053 resolvedType, flags, sourceUserId); 7054 if (resolveInfo != null) return resolveInfo; 7055 alreadyTriedUserIds.put(targetUserId, true); 7056 } 7057 } 7058 } 7059 return null; 7060 } 7061 7062 /** 7063 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7064 * will forward the intent to the filter's target user. 7065 * Otherwise, returns null. 7066 */ 7067 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7068 String resolvedType, int flags, int sourceUserId) { 7069 int targetUserId = filter.getTargetUserId(); 7070 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7071 resolvedType, flags, targetUserId); 7072 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7073 // If all the matches in the target profile are suspended, return null. 7074 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7075 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7076 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7077 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7078 targetUserId); 7079 } 7080 } 7081 } 7082 return null; 7083 } 7084 7085 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7086 int sourceUserId, int targetUserId) { 7087 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7088 long ident = Binder.clearCallingIdentity(); 7089 boolean targetIsProfile; 7090 try { 7091 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7092 } finally { 7093 Binder.restoreCallingIdentity(ident); 7094 } 7095 String className; 7096 if (targetIsProfile) { 7097 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7098 } else { 7099 className = FORWARD_INTENT_TO_PARENT; 7100 } 7101 ComponentName forwardingActivityComponentName = new ComponentName( 7102 mAndroidApplication.packageName, className); 7103 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7104 sourceUserId); 7105 if (!targetIsProfile) { 7106 forwardingActivityInfo.showUserIcon = targetUserId; 7107 forwardingResolveInfo.noResourceId = true; 7108 } 7109 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7110 forwardingResolveInfo.priority = 0; 7111 forwardingResolveInfo.preferredOrder = 0; 7112 forwardingResolveInfo.match = 0; 7113 forwardingResolveInfo.isDefault = true; 7114 forwardingResolveInfo.filter = filter; 7115 forwardingResolveInfo.targetUserId = targetUserId; 7116 return forwardingResolveInfo; 7117 } 7118 7119 @Override 7120 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7121 Intent[] specifics, String[] specificTypes, Intent intent, 7122 String resolvedType, int flags, int userId) { 7123 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7124 specificTypes, intent, resolvedType, flags, userId)); 7125 } 7126 7127 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7128 Intent[] specifics, String[] specificTypes, Intent intent, 7129 String resolvedType, int flags, int userId) { 7130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7131 final int callingUid = Binder.getCallingUid(); 7132 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7133 false /*includeInstantApps*/); 7134 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7135 false /*requireFullPermission*/, false /*checkShell*/, 7136 "query intent activity options"); 7137 final String resultsAction = intent.getAction(); 7138 7139 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7140 | PackageManager.GET_RESOLVED_FILTER, userId); 7141 7142 if (DEBUG_INTENT_MATCHING) { 7143 Log.v(TAG, "Query " + intent + ": " + results); 7144 } 7145 7146 int specificsPos = 0; 7147 int N; 7148 7149 // todo: note that the algorithm used here is O(N^2). This 7150 // isn't a problem in our current environment, but if we start running 7151 // into situations where we have more than 5 or 10 matches then this 7152 // should probably be changed to something smarter... 7153 7154 // First we go through and resolve each of the specific items 7155 // that were supplied, taking care of removing any corresponding 7156 // duplicate items in the generic resolve list. 7157 if (specifics != null) { 7158 for (int i=0; i<specifics.length; i++) { 7159 final Intent sintent = specifics[i]; 7160 if (sintent == null) { 7161 continue; 7162 } 7163 7164 if (DEBUG_INTENT_MATCHING) { 7165 Log.v(TAG, "Specific #" + i + ": " + sintent); 7166 } 7167 7168 String action = sintent.getAction(); 7169 if (resultsAction != null && resultsAction.equals(action)) { 7170 // If this action was explicitly requested, then don't 7171 // remove things that have it. 7172 action = null; 7173 } 7174 7175 ResolveInfo ri = null; 7176 ActivityInfo ai = null; 7177 7178 ComponentName comp = sintent.getComponent(); 7179 if (comp == null) { 7180 ri = resolveIntent( 7181 sintent, 7182 specificTypes != null ? specificTypes[i] : null, 7183 flags, userId); 7184 if (ri == null) { 7185 continue; 7186 } 7187 if (ri == mResolveInfo) { 7188 // ACK! Must do something better with this. 7189 } 7190 ai = ri.activityInfo; 7191 comp = new ComponentName(ai.applicationInfo.packageName, 7192 ai.name); 7193 } else { 7194 ai = getActivityInfo(comp, flags, userId); 7195 if (ai == null) { 7196 continue; 7197 } 7198 } 7199 7200 // Look for any generic query activities that are duplicates 7201 // of this specific one, and remove them from the results. 7202 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7203 N = results.size(); 7204 int j; 7205 for (j=specificsPos; j<N; j++) { 7206 ResolveInfo sri = results.get(j); 7207 if ((sri.activityInfo.name.equals(comp.getClassName()) 7208 && sri.activityInfo.applicationInfo.packageName.equals( 7209 comp.getPackageName())) 7210 || (action != null && sri.filter.matchAction(action))) { 7211 results.remove(j); 7212 if (DEBUG_INTENT_MATCHING) Log.v( 7213 TAG, "Removing duplicate item from " + j 7214 + " due to specific " + specificsPos); 7215 if (ri == null) { 7216 ri = sri; 7217 } 7218 j--; 7219 N--; 7220 } 7221 } 7222 7223 // Add this specific item to its proper place. 7224 if (ri == null) { 7225 ri = new ResolveInfo(); 7226 ri.activityInfo = ai; 7227 } 7228 results.add(specificsPos, ri); 7229 ri.specificIndex = i; 7230 specificsPos++; 7231 } 7232 } 7233 7234 // Now we go through the remaining generic results and remove any 7235 // duplicate actions that are found here. 7236 N = results.size(); 7237 for (int i=specificsPos; i<N-1; i++) { 7238 final ResolveInfo rii = results.get(i); 7239 if (rii.filter == null) { 7240 continue; 7241 } 7242 7243 // Iterate over all of the actions of this result's intent 7244 // filter... typically this should be just one. 7245 final Iterator<String> it = rii.filter.actionsIterator(); 7246 if (it == null) { 7247 continue; 7248 } 7249 while (it.hasNext()) { 7250 final String action = it.next(); 7251 if (resultsAction != null && resultsAction.equals(action)) { 7252 // If this action was explicitly requested, then don't 7253 // remove things that have it. 7254 continue; 7255 } 7256 for (int j=i+1; j<N; j++) { 7257 final ResolveInfo rij = results.get(j); 7258 if (rij.filter != null && rij.filter.hasAction(action)) { 7259 results.remove(j); 7260 if (DEBUG_INTENT_MATCHING) Log.v( 7261 TAG, "Removing duplicate item from " + j 7262 + " due to action " + action + " at " + i); 7263 j--; 7264 N--; 7265 } 7266 } 7267 } 7268 7269 // If the caller didn't request filter information, drop it now 7270 // so we don't have to marshall/unmarshall it. 7271 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7272 rii.filter = null; 7273 } 7274 } 7275 7276 // Filter out the caller activity if so requested. 7277 if (caller != null) { 7278 N = results.size(); 7279 for (int i=0; i<N; i++) { 7280 ActivityInfo ainfo = results.get(i).activityInfo; 7281 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7282 && caller.getClassName().equals(ainfo.name)) { 7283 results.remove(i); 7284 break; 7285 } 7286 } 7287 } 7288 7289 // If the caller didn't request filter information, 7290 // drop them now so we don't have to 7291 // marshall/unmarshall it. 7292 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7293 N = results.size(); 7294 for (int i=0; i<N; i++) { 7295 results.get(i).filter = null; 7296 } 7297 } 7298 7299 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7300 return results; 7301 } 7302 7303 @Override 7304 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7305 String resolvedType, int flags, int userId) { 7306 return new ParceledListSlice<>( 7307 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7308 false /*allowDynamicSplits*/)); 7309 } 7310 7311 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7312 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7313 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7314 final int callingUid = Binder.getCallingUid(); 7315 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7316 false /*requireFullPermission*/, false /*checkShell*/, 7317 "query intent receivers"); 7318 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7319 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7320 false /*includeInstantApps*/); 7321 ComponentName comp = intent.getComponent(); 7322 if (comp == null) { 7323 if (intent.getSelector() != null) { 7324 intent = intent.getSelector(); 7325 comp = intent.getComponent(); 7326 } 7327 } 7328 if (comp != null) { 7329 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7330 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7331 if (ai != null) { 7332 // When specifying an explicit component, we prevent the activity from being 7333 // used when either 1) the calling package is normal and the activity is within 7334 // an instant application or 2) the calling package is ephemeral and the 7335 // activity is not visible to instant applications. 7336 final boolean matchInstantApp = 7337 (flags & PackageManager.MATCH_INSTANT) != 0; 7338 final boolean matchVisibleToInstantAppOnly = 7339 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7340 final boolean matchExplicitlyVisibleOnly = 7341 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7342 final boolean isCallerInstantApp = 7343 instantAppPkgName != null; 7344 final boolean isTargetSameInstantApp = 7345 comp.getPackageName().equals(instantAppPkgName); 7346 final boolean isTargetInstantApp = 7347 (ai.applicationInfo.privateFlags 7348 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7349 final boolean isTargetVisibleToInstantApp = 7350 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7351 final boolean isTargetExplicitlyVisibleToInstantApp = 7352 isTargetVisibleToInstantApp 7353 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7354 final boolean isTargetHiddenFromInstantApp = 7355 !isTargetVisibleToInstantApp 7356 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7357 final boolean blockResolution = 7358 !isTargetSameInstantApp 7359 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7360 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7361 && isTargetHiddenFromInstantApp)); 7362 if (!blockResolution) { 7363 ResolveInfo ri = new ResolveInfo(); 7364 ri.activityInfo = ai; 7365 list.add(ri); 7366 } 7367 } 7368 return applyPostResolutionFilter( 7369 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7370 } 7371 7372 // reader 7373 synchronized (mPackages) { 7374 String pkgName = intent.getPackage(); 7375 if (pkgName == null) { 7376 final List<ResolveInfo> result = 7377 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7378 return applyPostResolutionFilter( 7379 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7380 } 7381 final PackageParser.Package pkg = mPackages.get(pkgName); 7382 if (pkg != null) { 7383 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7384 intent, resolvedType, flags, pkg.receivers, userId); 7385 return applyPostResolutionFilter( 7386 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7387 } 7388 return Collections.emptyList(); 7389 } 7390 } 7391 7392 @Override 7393 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7394 final int callingUid = Binder.getCallingUid(); 7395 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7396 } 7397 7398 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7399 int userId, int callingUid) { 7400 if (!sUserManager.exists(userId)) return null; 7401 flags = updateFlagsForResolve( 7402 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7403 List<ResolveInfo> query = queryIntentServicesInternal( 7404 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7405 if (query != null) { 7406 if (query.size() >= 1) { 7407 // If there is more than one service with the same priority, 7408 // just arbitrarily pick the first one. 7409 return query.get(0); 7410 } 7411 } 7412 return null; 7413 } 7414 7415 @Override 7416 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7417 String resolvedType, int flags, int userId) { 7418 final int callingUid = Binder.getCallingUid(); 7419 return new ParceledListSlice<>(queryIntentServicesInternal( 7420 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7421 } 7422 7423 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7424 String resolvedType, int flags, int userId, int callingUid, 7425 boolean includeInstantApps) { 7426 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7427 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7428 false /*requireFullPermission*/, false /*checkShell*/, 7429 "query intent receivers"); 7430 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7431 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7432 ComponentName comp = intent.getComponent(); 7433 if (comp == null) { 7434 if (intent.getSelector() != null) { 7435 intent = intent.getSelector(); 7436 comp = intent.getComponent(); 7437 } 7438 } 7439 if (comp != null) { 7440 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7441 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7442 if (si != null) { 7443 // When specifying an explicit component, we prevent the service from being 7444 // used when either 1) the service is in an instant application and the 7445 // caller is not the same instant application or 2) the calling package is 7446 // ephemeral and the activity is not visible to ephemeral applications. 7447 final boolean matchInstantApp = 7448 (flags & PackageManager.MATCH_INSTANT) != 0; 7449 final boolean matchVisibleToInstantAppOnly = 7450 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7451 final boolean isCallerInstantApp = 7452 instantAppPkgName != null; 7453 final boolean isTargetSameInstantApp = 7454 comp.getPackageName().equals(instantAppPkgName); 7455 final boolean isTargetInstantApp = 7456 (si.applicationInfo.privateFlags 7457 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7458 final boolean isTargetHiddenFromInstantApp = 7459 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7460 final boolean blockResolution = 7461 !isTargetSameInstantApp 7462 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7463 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7464 && isTargetHiddenFromInstantApp)); 7465 if (!blockResolution) { 7466 final ResolveInfo ri = new ResolveInfo(); 7467 ri.serviceInfo = si; 7468 list.add(ri); 7469 } 7470 } 7471 return list; 7472 } 7473 7474 // reader 7475 synchronized (mPackages) { 7476 String pkgName = intent.getPackage(); 7477 if (pkgName == null) { 7478 return applyPostServiceResolutionFilter( 7479 mServices.queryIntent(intent, resolvedType, flags, userId), 7480 instantAppPkgName); 7481 } 7482 final PackageParser.Package pkg = mPackages.get(pkgName); 7483 if (pkg != null) { 7484 return applyPostServiceResolutionFilter( 7485 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7486 userId), 7487 instantAppPkgName); 7488 } 7489 return Collections.emptyList(); 7490 } 7491 } 7492 7493 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7494 String instantAppPkgName) { 7495 if (instantAppPkgName == null) { 7496 return resolveInfos; 7497 } 7498 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7499 final ResolveInfo info = resolveInfos.get(i); 7500 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7501 // allow services that are defined in the provided package 7502 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7503 if (info.serviceInfo.splitName != null 7504 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7505 info.serviceInfo.splitName)) { 7506 // requested service is defined in a split that hasn't been installed yet. 7507 // add the installer to the resolve list 7508 if (DEBUG_EPHEMERAL) { 7509 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7510 } 7511 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7512 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7513 info.serviceInfo.packageName, info.serviceInfo.splitName, 7514 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7515 null /*failureIntent*/); 7516 // make sure this resolver is the default 7517 installerInfo.isDefault = true; 7518 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7519 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7520 // add a non-generic filter 7521 installerInfo.filter = new IntentFilter(); 7522 // load resources from the correct package 7523 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7524 resolveInfos.set(i, installerInfo); 7525 } 7526 continue; 7527 } 7528 // allow services that have been explicitly exposed to ephemeral apps 7529 if (!isEphemeralApp 7530 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7531 continue; 7532 } 7533 resolveInfos.remove(i); 7534 } 7535 return resolveInfos; 7536 } 7537 7538 @Override 7539 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7540 String resolvedType, int flags, int userId) { 7541 return new ParceledListSlice<>( 7542 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7543 } 7544 7545 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7546 Intent intent, String resolvedType, int flags, int userId) { 7547 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7548 final int callingUid = Binder.getCallingUid(); 7549 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7550 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7551 false /*includeInstantApps*/); 7552 ComponentName comp = intent.getComponent(); 7553 if (comp == null) { 7554 if (intent.getSelector() != null) { 7555 intent = intent.getSelector(); 7556 comp = intent.getComponent(); 7557 } 7558 } 7559 if (comp != null) { 7560 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7561 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7562 if (pi != null) { 7563 // When specifying an explicit component, we prevent the provider from being 7564 // used when either 1) the provider is in an instant application and the 7565 // caller is not the same instant application or 2) the calling package is an 7566 // instant application and the provider is not visible to instant applications. 7567 final boolean matchInstantApp = 7568 (flags & PackageManager.MATCH_INSTANT) != 0; 7569 final boolean matchVisibleToInstantAppOnly = 7570 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7571 final boolean isCallerInstantApp = 7572 instantAppPkgName != null; 7573 final boolean isTargetSameInstantApp = 7574 comp.getPackageName().equals(instantAppPkgName); 7575 final boolean isTargetInstantApp = 7576 (pi.applicationInfo.privateFlags 7577 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7578 final boolean isTargetHiddenFromInstantApp = 7579 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7580 final boolean blockResolution = 7581 !isTargetSameInstantApp 7582 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7583 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7584 && isTargetHiddenFromInstantApp)); 7585 if (!blockResolution) { 7586 final ResolveInfo ri = new ResolveInfo(); 7587 ri.providerInfo = pi; 7588 list.add(ri); 7589 } 7590 } 7591 return list; 7592 } 7593 7594 // reader 7595 synchronized (mPackages) { 7596 String pkgName = intent.getPackage(); 7597 if (pkgName == null) { 7598 return applyPostContentProviderResolutionFilter( 7599 mProviders.queryIntent(intent, resolvedType, flags, userId), 7600 instantAppPkgName); 7601 } 7602 final PackageParser.Package pkg = mPackages.get(pkgName); 7603 if (pkg != null) { 7604 return applyPostContentProviderResolutionFilter( 7605 mProviders.queryIntentForPackage( 7606 intent, resolvedType, flags, pkg.providers, userId), 7607 instantAppPkgName); 7608 } 7609 return Collections.emptyList(); 7610 } 7611 } 7612 7613 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7614 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7615 if (instantAppPkgName == null) { 7616 return resolveInfos; 7617 } 7618 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7619 final ResolveInfo info = resolveInfos.get(i); 7620 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7621 // allow providers that are defined in the provided package 7622 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7623 if (info.providerInfo.splitName != null 7624 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7625 info.providerInfo.splitName)) { 7626 // requested provider is defined in a split that hasn't been installed yet. 7627 // add the installer to the resolve list 7628 if (DEBUG_EPHEMERAL) { 7629 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7630 } 7631 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7632 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7633 info.providerInfo.packageName, info.providerInfo.splitName, 7634 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7635 null /*failureIntent*/); 7636 // make sure this resolver is the default 7637 installerInfo.isDefault = true; 7638 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7639 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7640 // add a non-generic filter 7641 installerInfo.filter = new IntentFilter(); 7642 // load resources from the correct package 7643 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7644 resolveInfos.set(i, installerInfo); 7645 } 7646 continue; 7647 } 7648 // allow providers that have been explicitly exposed to instant applications 7649 if (!isEphemeralApp 7650 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7651 continue; 7652 } 7653 resolveInfos.remove(i); 7654 } 7655 return resolveInfos; 7656 } 7657 7658 @Override 7659 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7660 final int callingUid = Binder.getCallingUid(); 7661 if (getInstantAppPackageName(callingUid) != null) { 7662 return ParceledListSlice.emptyList(); 7663 } 7664 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7665 flags = updateFlagsForPackage(flags, userId, null); 7666 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7667 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7668 true /* requireFullPermission */, false /* checkShell */, 7669 "get installed packages"); 7670 7671 // writer 7672 synchronized (mPackages) { 7673 ArrayList<PackageInfo> list; 7674 if (listUninstalled) { 7675 list = new ArrayList<>(mSettings.mPackages.size()); 7676 for (PackageSetting ps : mSettings.mPackages.values()) { 7677 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7678 continue; 7679 } 7680 if (filterAppAccessLPr(ps, callingUid, userId)) { 7681 continue; 7682 } 7683 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7684 if (pi != null) { 7685 list.add(pi); 7686 } 7687 } 7688 } else { 7689 list = new ArrayList<>(mPackages.size()); 7690 for (PackageParser.Package p : mPackages.values()) { 7691 final PackageSetting ps = (PackageSetting) p.mExtras; 7692 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7693 continue; 7694 } 7695 if (filterAppAccessLPr(ps, callingUid, userId)) { 7696 continue; 7697 } 7698 final PackageInfo pi = generatePackageInfo((PackageSetting) 7699 p.mExtras, flags, userId); 7700 if (pi != null) { 7701 list.add(pi); 7702 } 7703 } 7704 } 7705 7706 return new ParceledListSlice<>(list); 7707 } 7708 } 7709 7710 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7711 String[] permissions, boolean[] tmp, int flags, int userId) { 7712 int numMatch = 0; 7713 final PermissionsState permissionsState = ps.getPermissionsState(); 7714 for (int i=0; i<permissions.length; i++) { 7715 final String permission = permissions[i]; 7716 if (permissionsState.hasPermission(permission, userId)) { 7717 tmp[i] = true; 7718 numMatch++; 7719 } else { 7720 tmp[i] = false; 7721 } 7722 } 7723 if (numMatch == 0) { 7724 return; 7725 } 7726 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7727 7728 // The above might return null in cases of uninstalled apps or install-state 7729 // skew across users/profiles. 7730 if (pi != null) { 7731 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7732 if (numMatch == permissions.length) { 7733 pi.requestedPermissions = permissions; 7734 } else { 7735 pi.requestedPermissions = new String[numMatch]; 7736 numMatch = 0; 7737 for (int i=0; i<permissions.length; i++) { 7738 if (tmp[i]) { 7739 pi.requestedPermissions[numMatch] = permissions[i]; 7740 numMatch++; 7741 } 7742 } 7743 } 7744 } 7745 list.add(pi); 7746 } 7747 } 7748 7749 @Override 7750 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7751 String[] permissions, int flags, int userId) { 7752 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7753 flags = updateFlagsForPackage(flags, userId, permissions); 7754 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7755 true /* requireFullPermission */, false /* checkShell */, 7756 "get packages holding permissions"); 7757 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7758 7759 // writer 7760 synchronized (mPackages) { 7761 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7762 boolean[] tmpBools = new boolean[permissions.length]; 7763 if (listUninstalled) { 7764 for (PackageSetting ps : mSettings.mPackages.values()) { 7765 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7766 userId); 7767 } 7768 } else { 7769 for (PackageParser.Package pkg : mPackages.values()) { 7770 PackageSetting ps = (PackageSetting)pkg.mExtras; 7771 if (ps != null) { 7772 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7773 userId); 7774 } 7775 } 7776 } 7777 7778 return new ParceledListSlice<PackageInfo>(list); 7779 } 7780 } 7781 7782 @Override 7783 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7784 final int callingUid = Binder.getCallingUid(); 7785 if (getInstantAppPackageName(callingUid) != null) { 7786 return ParceledListSlice.emptyList(); 7787 } 7788 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7789 flags = updateFlagsForApplication(flags, userId, null); 7790 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7791 7792 // writer 7793 synchronized (mPackages) { 7794 ArrayList<ApplicationInfo> list; 7795 if (listUninstalled) { 7796 list = new ArrayList<>(mSettings.mPackages.size()); 7797 for (PackageSetting ps : mSettings.mPackages.values()) { 7798 ApplicationInfo ai; 7799 int effectiveFlags = flags; 7800 if (ps.isSystem()) { 7801 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7802 } 7803 if (ps.pkg != null) { 7804 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7805 continue; 7806 } 7807 if (filterAppAccessLPr(ps, callingUid, userId)) { 7808 continue; 7809 } 7810 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7811 ps.readUserState(userId), userId); 7812 if (ai != null) { 7813 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7814 } 7815 } else { 7816 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7817 // and already converts to externally visible package name 7818 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7819 callingUid, effectiveFlags, userId); 7820 } 7821 if (ai != null) { 7822 list.add(ai); 7823 } 7824 } 7825 } else { 7826 list = new ArrayList<>(mPackages.size()); 7827 for (PackageParser.Package p : mPackages.values()) { 7828 if (p.mExtras != null) { 7829 PackageSetting ps = (PackageSetting) p.mExtras; 7830 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7831 continue; 7832 } 7833 if (filterAppAccessLPr(ps, callingUid, userId)) { 7834 continue; 7835 } 7836 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7837 ps.readUserState(userId), userId); 7838 if (ai != null) { 7839 ai.packageName = resolveExternalPackageNameLPr(p); 7840 list.add(ai); 7841 } 7842 } 7843 } 7844 } 7845 7846 return new ParceledListSlice<>(list); 7847 } 7848 } 7849 7850 @Override 7851 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7852 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7853 return null; 7854 } 7855 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7856 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7857 "getEphemeralApplications"); 7858 } 7859 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7860 true /* requireFullPermission */, false /* checkShell */, 7861 "getEphemeralApplications"); 7862 synchronized (mPackages) { 7863 List<InstantAppInfo> instantApps = mInstantAppRegistry 7864 .getInstantAppsLPr(userId); 7865 if (instantApps != null) { 7866 return new ParceledListSlice<>(instantApps); 7867 } 7868 } 7869 return null; 7870 } 7871 7872 @Override 7873 public boolean isInstantApp(String packageName, int userId) { 7874 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7875 true /* requireFullPermission */, false /* checkShell */, 7876 "isInstantApp"); 7877 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7878 return false; 7879 } 7880 7881 synchronized (mPackages) { 7882 int callingUid = Binder.getCallingUid(); 7883 if (Process.isIsolated(callingUid)) { 7884 callingUid = mIsolatedOwners.get(callingUid); 7885 } 7886 final PackageSetting ps = mSettings.mPackages.get(packageName); 7887 PackageParser.Package pkg = mPackages.get(packageName); 7888 final boolean returnAllowed = 7889 ps != null 7890 && (isCallerSameApp(packageName, callingUid) 7891 || canViewInstantApps(callingUid, userId) 7892 || mInstantAppRegistry.isInstantAccessGranted( 7893 userId, UserHandle.getAppId(callingUid), ps.appId)); 7894 if (returnAllowed) { 7895 return ps.getInstantApp(userId); 7896 } 7897 } 7898 return false; 7899 } 7900 7901 @Override 7902 public byte[] getInstantAppCookie(String packageName, int userId) { 7903 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7904 return null; 7905 } 7906 7907 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7908 true /* requireFullPermission */, false /* checkShell */, 7909 "getInstantAppCookie"); 7910 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7911 return null; 7912 } 7913 synchronized (mPackages) { 7914 return mInstantAppRegistry.getInstantAppCookieLPw( 7915 packageName, userId); 7916 } 7917 } 7918 7919 @Override 7920 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7921 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7922 return true; 7923 } 7924 7925 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7926 true /* requireFullPermission */, true /* checkShell */, 7927 "setInstantAppCookie"); 7928 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7929 return false; 7930 } 7931 synchronized (mPackages) { 7932 return mInstantAppRegistry.setInstantAppCookieLPw( 7933 packageName, cookie, userId); 7934 } 7935 } 7936 7937 @Override 7938 public Bitmap getInstantAppIcon(String packageName, int userId) { 7939 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7940 return null; 7941 } 7942 7943 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7944 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7945 "getInstantAppIcon"); 7946 } 7947 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7948 true /* requireFullPermission */, false /* checkShell */, 7949 "getInstantAppIcon"); 7950 7951 synchronized (mPackages) { 7952 return mInstantAppRegistry.getInstantAppIconLPw( 7953 packageName, userId); 7954 } 7955 } 7956 7957 private boolean isCallerSameApp(String packageName, int uid) { 7958 PackageParser.Package pkg = mPackages.get(packageName); 7959 return pkg != null 7960 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7961 } 7962 7963 @Override 7964 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7965 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7966 return ParceledListSlice.emptyList(); 7967 } 7968 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7969 } 7970 7971 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7972 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7973 7974 // reader 7975 synchronized (mPackages) { 7976 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7977 final int userId = UserHandle.getCallingUserId(); 7978 while (i.hasNext()) { 7979 final PackageParser.Package p = i.next(); 7980 if (p.applicationInfo == null) continue; 7981 7982 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7983 && !p.applicationInfo.isDirectBootAware(); 7984 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7985 && p.applicationInfo.isDirectBootAware(); 7986 7987 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7988 && (!mSafeMode || isSystemApp(p)) 7989 && (matchesUnaware || matchesAware)) { 7990 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7991 if (ps != null) { 7992 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7993 ps.readUserState(userId), userId); 7994 if (ai != null) { 7995 finalList.add(ai); 7996 } 7997 } 7998 } 7999 } 8000 } 8001 8002 return finalList; 8003 } 8004 8005 @Override 8006 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8007 return resolveContentProviderInternal(name, flags, userId); 8008 } 8009 8010 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8011 if (!sUserManager.exists(userId)) return null; 8012 flags = updateFlagsForComponent(flags, userId, name); 8013 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8014 // reader 8015 synchronized (mPackages) { 8016 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8017 PackageSetting ps = provider != null 8018 ? mSettings.mPackages.get(provider.owner.packageName) 8019 : null; 8020 if (ps != null) { 8021 final boolean isInstantApp = ps.getInstantApp(userId); 8022 // normal application; filter out instant application provider 8023 if (instantAppPkgName == null && isInstantApp) { 8024 return null; 8025 } 8026 // instant application; filter out other instant applications 8027 if (instantAppPkgName != null 8028 && isInstantApp 8029 && !provider.owner.packageName.equals(instantAppPkgName)) { 8030 return null; 8031 } 8032 // instant application; filter out non-exposed provider 8033 if (instantAppPkgName != null 8034 && !isInstantApp 8035 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8036 return null; 8037 } 8038 // provider not enabled 8039 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8040 return null; 8041 } 8042 return PackageParser.generateProviderInfo( 8043 provider, flags, ps.readUserState(userId), userId); 8044 } 8045 return null; 8046 } 8047 } 8048 8049 /** 8050 * @deprecated 8051 */ 8052 @Deprecated 8053 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8054 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8055 return; 8056 } 8057 // reader 8058 synchronized (mPackages) { 8059 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8060 .entrySet().iterator(); 8061 final int userId = UserHandle.getCallingUserId(); 8062 while (i.hasNext()) { 8063 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8064 PackageParser.Provider p = entry.getValue(); 8065 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8066 8067 if (ps != null && p.syncable 8068 && (!mSafeMode || (p.info.applicationInfo.flags 8069 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8070 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8071 ps.readUserState(userId), userId); 8072 if (info != null) { 8073 outNames.add(entry.getKey()); 8074 outInfo.add(info); 8075 } 8076 } 8077 } 8078 } 8079 } 8080 8081 @Override 8082 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8083 int uid, int flags, String metaDataKey) { 8084 final int callingUid = Binder.getCallingUid(); 8085 final int userId = processName != null ? UserHandle.getUserId(uid) 8086 : UserHandle.getCallingUserId(); 8087 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8088 flags = updateFlagsForComponent(flags, userId, processName); 8089 ArrayList<ProviderInfo> finalList = null; 8090 // reader 8091 synchronized (mPackages) { 8092 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8093 while (i.hasNext()) { 8094 final PackageParser.Provider p = i.next(); 8095 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8096 if (ps != null && p.info.authority != null 8097 && (processName == null 8098 || (p.info.processName.equals(processName) 8099 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8100 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8101 8102 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8103 // parameter. 8104 if (metaDataKey != null 8105 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8106 continue; 8107 } 8108 final ComponentName component = 8109 new ComponentName(p.info.packageName, p.info.name); 8110 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8111 continue; 8112 } 8113 if (finalList == null) { 8114 finalList = new ArrayList<ProviderInfo>(3); 8115 } 8116 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8117 ps.readUserState(userId), userId); 8118 if (info != null) { 8119 finalList.add(info); 8120 } 8121 } 8122 } 8123 } 8124 8125 if (finalList != null) { 8126 Collections.sort(finalList, mProviderInitOrderSorter); 8127 return new ParceledListSlice<ProviderInfo>(finalList); 8128 } 8129 8130 return ParceledListSlice.emptyList(); 8131 } 8132 8133 @Override 8134 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8135 // reader 8136 synchronized (mPackages) { 8137 final int callingUid = Binder.getCallingUid(); 8138 final int callingUserId = UserHandle.getUserId(callingUid); 8139 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8140 if (ps == null) return null; 8141 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8142 return null; 8143 } 8144 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8145 return PackageParser.generateInstrumentationInfo(i, flags); 8146 } 8147 } 8148 8149 @Override 8150 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8151 String targetPackage, int flags) { 8152 final int callingUid = Binder.getCallingUid(); 8153 final int callingUserId = UserHandle.getUserId(callingUid); 8154 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8155 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8156 return ParceledListSlice.emptyList(); 8157 } 8158 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8159 } 8160 8161 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8162 int flags) { 8163 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8164 8165 // reader 8166 synchronized (mPackages) { 8167 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8168 while (i.hasNext()) { 8169 final PackageParser.Instrumentation p = i.next(); 8170 if (targetPackage == null 8171 || targetPackage.equals(p.info.targetPackage)) { 8172 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8173 flags); 8174 if (ii != null) { 8175 finalList.add(ii); 8176 } 8177 } 8178 } 8179 } 8180 8181 return finalList; 8182 } 8183 8184 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8185 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8186 try { 8187 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8188 } finally { 8189 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8190 } 8191 } 8192 8193 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8194 final File[] files = scanDir.listFiles(); 8195 if (ArrayUtils.isEmpty(files)) { 8196 Log.d(TAG, "No files in app dir " + scanDir); 8197 return; 8198 } 8199 8200 if (DEBUG_PACKAGE_SCANNING) { 8201 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8202 + " flags=0x" + Integer.toHexString(parseFlags)); 8203 } 8204 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8205 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8206 mParallelPackageParserCallback)) { 8207 // Submit files for parsing in parallel 8208 int fileCount = 0; 8209 for (File file : files) { 8210 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8211 && !PackageInstallerService.isStageName(file.getName()); 8212 if (!isPackage) { 8213 // Ignore entries which are not packages 8214 continue; 8215 } 8216 parallelPackageParser.submit(file, parseFlags); 8217 fileCount++; 8218 } 8219 8220 // Process results one by one 8221 for (; fileCount > 0; fileCount--) { 8222 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8223 Throwable throwable = parseResult.throwable; 8224 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8225 8226 if (throwable == null) { 8227 // TODO(toddke): move lower in the scan chain 8228 // Static shared libraries have synthetic package names 8229 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8230 renameStaticSharedLibraryPackage(parseResult.pkg); 8231 } 8232 try { 8233 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8234 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8235 currentTime, null); 8236 } 8237 } catch (PackageManagerException e) { 8238 errorCode = e.error; 8239 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8240 } 8241 } else if (throwable instanceof PackageParser.PackageParserException) { 8242 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8243 throwable; 8244 errorCode = e.error; 8245 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8246 } else { 8247 throw new IllegalStateException("Unexpected exception occurred while parsing " 8248 + parseResult.scanFile, throwable); 8249 } 8250 8251 // Delete invalid userdata apps 8252 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8253 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8254 logCriticalInfo(Log.WARN, 8255 "Deleting invalid package at " + parseResult.scanFile); 8256 removeCodePathLI(parseResult.scanFile); 8257 } 8258 } 8259 } 8260 } 8261 8262 public static void reportSettingsProblem(int priority, String msg) { 8263 logCriticalInfo(priority, msg); 8264 } 8265 8266 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8267 final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException { 8268 // When upgrading from pre-N MR1, verify the package time stamp using the package 8269 // directory and not the APK file. 8270 final long lastModifiedTime = mIsPreNMR1Upgrade 8271 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8272 if (ps != null && !forceCollect 8273 && ps.codePathString.equals(pkg.codePath) 8274 && ps.timeStamp == lastModifiedTime 8275 && !isCompatSignatureUpdateNeeded(pkg) 8276 && !isRecoverSignatureUpdateNeeded(pkg)) { 8277 if (ps.signatures.mSigningDetails.signatures != null 8278 && ps.signatures.mSigningDetails.signatures.length != 0 8279 && ps.signatures.mSigningDetails.signatureSchemeVersion 8280 != SignatureSchemeVersion.UNKNOWN) { 8281 // Optimization: reuse the existing cached signing data 8282 // if the package appears to be unchanged. 8283 pkg.mSigningDetails = 8284 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8285 return; 8286 } 8287 8288 Slog.w(TAG, "PackageSetting for " + ps.name 8289 + " is missing signatures. Collecting certs again to recover them."); 8290 } else { 8291 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8292 (forceCollect ? " (forced)" : "")); 8293 } 8294 8295 try { 8296 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8297 PackageParser.collectCertificates(pkg, parseFlags); 8298 } catch (PackageParserException e) { 8299 throw PackageManagerException.from(e); 8300 } finally { 8301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8302 } 8303 } 8304 8305 /** 8306 * Traces a package scan. 8307 * @see #scanPackageLI(File, int, int, long, UserHandle) 8308 */ 8309 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8310 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8311 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8312 try { 8313 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8314 } finally { 8315 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8316 } 8317 } 8318 8319 /** 8320 * Scans a package and returns the newly parsed package. 8321 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8322 */ 8323 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8324 long currentTime, UserHandle user) throws PackageManagerException { 8325 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8326 PackageParser pp = new PackageParser(); 8327 pp.setSeparateProcesses(mSeparateProcesses); 8328 pp.setOnlyCoreApps(mOnlyCore); 8329 pp.setDisplayMetrics(mMetrics); 8330 pp.setCallback(mPackageParserCallback); 8331 8332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8333 final PackageParser.Package pkg; 8334 try { 8335 pkg = pp.parsePackage(scanFile, parseFlags); 8336 } catch (PackageParserException e) { 8337 throw PackageManagerException.from(e); 8338 } finally { 8339 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8340 } 8341 8342 // Static shared libraries have synthetic package names 8343 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8344 renameStaticSharedLibraryPackage(pkg); 8345 } 8346 8347 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8348 } 8349 8350 /** 8351 * Scans a package and returns the newly parsed package. 8352 * @throws PackageManagerException on a parse error. 8353 */ 8354 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8355 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8356 @Nullable UserHandle user) 8357 throws PackageManagerException { 8358 // If the package has children and this is the first dive in the function 8359 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8360 // packages (parent and children) would be successfully scanned before the 8361 // actual scan since scanning mutates internal state and we want to atomically 8362 // install the package and its children. 8363 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8364 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8365 scanFlags |= SCAN_CHECK_ONLY; 8366 } 8367 } else { 8368 scanFlags &= ~SCAN_CHECK_ONLY; 8369 } 8370 8371 // Scan the parent 8372 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8373 scanFlags, currentTime, user); 8374 8375 // Scan the children 8376 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8377 for (int i = 0; i < childCount; i++) { 8378 PackageParser.Package childPackage = pkg.childPackages.get(i); 8379 addForInitLI(childPackage, parseFlags, scanFlags, 8380 currentTime, user); 8381 } 8382 8383 8384 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8385 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8386 } 8387 8388 return scannedPkg; 8389 } 8390 8391 // Temporary to catch potential issues with refactoring 8392 private static boolean REFACTOR_DEBUG = true; 8393 /** 8394 * Adds a new package to the internal data structures during platform initialization. 8395 * <p>After adding, the package is known to the system and available for querying. 8396 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8397 * etc...], additional checks are performed. Basic verification [such as ensuring 8398 * matching signatures, checking version codes, etc...] occurs if the package is 8399 * identical to a previously known package. If the package fails a signature check, 8400 * the version installed on /data will be removed. If the version of the new package 8401 * is less than or equal than the version on /data, it will be ignored. 8402 * <p>Regardless of the package location, the results are applied to the internal 8403 * structures and the package is made available to the rest of the system. 8404 * <p>NOTE: The return value should be removed. It's the passed in package object. 8405 */ 8406 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8407 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8408 @Nullable UserHandle user) 8409 throws PackageManagerException { 8410 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8411 final String renamedPkgName; 8412 final PackageSetting disabledPkgSetting; 8413 final boolean isSystemPkgUpdated; 8414 final boolean pkgAlreadyExists; 8415 PackageSetting pkgSetting; 8416 8417 // NOTE: installPackageLI() has the same code to setup the package's 8418 // application info. This probably should be done lower in the call 8419 // stack [such as scanPackageOnly()]. However, we verify the application 8420 // info prior to that [in scanPackageNew()] and thus have to setup 8421 // the application info early. 8422 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8423 pkg.setApplicationInfoCodePath(pkg.codePath); 8424 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8425 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8426 pkg.setApplicationInfoResourcePath(pkg.codePath); 8427 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8428 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8429 8430 synchronized (mPackages) { 8431 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8432 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8433if (REFACTOR_DEBUG) { 8434Slog.e("TODD", 8435 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8436} 8437 if (realPkgName != null) { 8438 ensurePackageRenamed(pkg, renamedPkgName); 8439 } 8440 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8441 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8442 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8443 pkgAlreadyExists = pkgSetting != null; 8444 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8445 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8446 isSystemPkgUpdated = disabledPkgSetting != null; 8447 8448 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8449 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8450 } 8451if (REFACTOR_DEBUG) { 8452Slog.e("TODD", 8453 "SSP? " + scanSystemPartition 8454 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8455 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8456} 8457 8458 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8459 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8460 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8461 : null; 8462 if (DEBUG_PACKAGE_SCANNING 8463 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8464 && sharedUserSetting != null) { 8465 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8466 + " (uid=" + sharedUserSetting.userId + "):" 8467 + " packages=" + sharedUserSetting.packages); 8468if (REFACTOR_DEBUG) { 8469Slog.e("TODD", 8470 "Shared UserID " + pkg.mSharedUserId 8471 + " (uid=" + sharedUserSetting.userId + "):" 8472 + " packages=" + sharedUserSetting.packages); 8473} 8474 } 8475 8476 if (scanSystemPartition) { 8477 // Potentially prune child packages. If the application on the /system 8478 // partition has been updated via OTA, but, is still disabled by a 8479 // version on /data, cycle through all of its children packages and 8480 // remove children that are no longer defined. 8481 if (isSystemPkgUpdated) { 8482if (REFACTOR_DEBUG) { 8483Slog.e("TODD", 8484 "Disable child packages"); 8485} 8486 final int scannedChildCount = (pkg.childPackages != null) 8487 ? pkg.childPackages.size() : 0; 8488 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8489 ? disabledPkgSetting.childPackageNames.size() : 0; 8490 for (int i = 0; i < disabledChildCount; i++) { 8491 String disabledChildPackageName = 8492 disabledPkgSetting.childPackageNames.get(i); 8493 boolean disabledPackageAvailable = false; 8494 for (int j = 0; j < scannedChildCount; j++) { 8495 PackageParser.Package childPkg = pkg.childPackages.get(j); 8496 if (childPkg.packageName.equals(disabledChildPackageName)) { 8497if (REFACTOR_DEBUG) { 8498Slog.e("TODD", 8499 "Ignore " + disabledChildPackageName); 8500} 8501 disabledPackageAvailable = true; 8502 break; 8503 } 8504 } 8505 if (!disabledPackageAvailable) { 8506if (REFACTOR_DEBUG) { 8507Slog.e("TODD", 8508 "Disable " + disabledChildPackageName); 8509} 8510 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8511 } 8512 } 8513 // we're updating the disabled package, so, scan it as the package setting 8514 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8515 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8516 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8517 (pkg == mPlatformPackage), user); 8518if (REFACTOR_DEBUG) { 8519Slog.e("TODD", 8520 "Scan disabled system package"); 8521Slog.e("TODD", 8522 "Pre: " + request.pkgSetting.dumpState_temp()); 8523} 8524final ScanResult result = 8525 scanPackageOnlyLI(request, mFactoryTest, -1L); 8526if (REFACTOR_DEBUG) { 8527Slog.e("TODD", 8528 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8529} 8530 } 8531 } 8532 } 8533 8534 final boolean newPkgChangedPaths = 8535 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8536if (REFACTOR_DEBUG) { 8537Slog.e("TODD", 8538 "paths changed? " + newPkgChangedPaths 8539 + "; old: " + pkg.codePath 8540 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8541} 8542 final boolean newPkgVersionGreater = 8543 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8544if (REFACTOR_DEBUG) { 8545Slog.e("TODD", 8546 "version greater? " + newPkgVersionGreater 8547 + "; old: " + pkg.getLongVersionCode() 8548 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8549} 8550 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8551 && newPkgChangedPaths && newPkgVersionGreater; 8552if (REFACTOR_DEBUG) { 8553 Slog.e("TODD", 8554 "system better? " + isSystemPkgBetter); 8555} 8556 if (isSystemPkgBetter) { 8557 // The version of the application on /system is greater than the version on 8558 // /data. Switch back to the application on /system. 8559 // It's safe to assume the application on /system will correctly scan. If not, 8560 // there won't be a working copy of the application. 8561 synchronized (mPackages) { 8562 // just remove the loaded entries from package lists 8563 mPackages.remove(pkgSetting.name); 8564 } 8565 8566 logCriticalInfo(Log.WARN, 8567 "System package updated;" 8568 + " name: " + pkgSetting.name 8569 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8570 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8571if (REFACTOR_DEBUG) { 8572Slog.e("TODD", 8573 "System package changed;" 8574 + " name: " + pkgSetting.name 8575 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8576 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8577} 8578 8579 final InstallArgs args = createInstallArgsForExisting( 8580 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8581 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8582 args.cleanUpResourcesLI(); 8583 synchronized (mPackages) { 8584 mSettings.enableSystemPackageLPw(pkgSetting.name); 8585 } 8586 } 8587 8588 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8589if (REFACTOR_DEBUG) { 8590Slog.e("TODD", 8591 "THROW exception; system pkg version not good enough"); 8592} 8593 // The version of the application on the /system partition is less than or 8594 // equal to the version on the /data partition. Throw an exception and use 8595 // the application already installed on the /data partition. 8596 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8597 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8598 + " better than this " + pkg.getLongVersionCode()); 8599 } 8600 8601 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8602 // force the verification. Full apk verification will happen unless apk verity is set up for 8603 // the file. In that case, only small part of the apk is verified upfront. 8604 collectCertificatesLI(pkgSetting, pkg, parseFlags, 8605 PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting)); 8606 8607 boolean shouldHideSystemApp = false; 8608 // A new application appeared on /system, but, we already have a copy of 8609 // the application installed on /data. 8610 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8611 && !pkgSetting.isSystem()) { 8612 // if the signatures don't match, wipe the installed application and its data 8613 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8614 pkg.mSigningDetails.signatures) 8615 != PackageManager.SIGNATURE_MATCH) { 8616 logCriticalInfo(Log.WARN, 8617 "System package signature mismatch;" 8618 + " name: " + pkgSetting.name); 8619if (REFACTOR_DEBUG) { 8620Slog.e("TODD", 8621 "System package signature mismatch;" 8622 + " name: " + pkgSetting.name); 8623} 8624 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8625 "scanPackageInternalLI")) { 8626 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8627 } 8628 pkgSetting = null; 8629 } else if (newPkgVersionGreater) { 8630 // The application on /system is newer than the application on /data. 8631 // Simply remove the application on /data [keeping application data] 8632 // and replace it with the version on /system. 8633 logCriticalInfo(Log.WARN, 8634 "System package enabled;" 8635 + " name: " + pkgSetting.name 8636 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8637 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8638if (REFACTOR_DEBUG) { 8639Slog.e("TODD", 8640 "System package enabled;" 8641 + " name: " + pkgSetting.name 8642 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8643 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8644} 8645 InstallArgs args = createInstallArgsForExisting( 8646 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8647 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8648 synchronized (mInstallLock) { 8649 args.cleanUpResourcesLI(); 8650 } 8651 } else { 8652 // The application on /system is older than the application on /data. Hide 8653 // the application on /system and the version on /data will be scanned later 8654 // and re-added like an update. 8655 shouldHideSystemApp = true; 8656 logCriticalInfo(Log.INFO, 8657 "System package disabled;" 8658 + " name: " + pkgSetting.name 8659 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8660 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8661if (REFACTOR_DEBUG) { 8662Slog.e("TODD", 8663 "System package disabled;" 8664 + " name: " + pkgSetting.name 8665 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8666 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8667} 8668 } 8669 } 8670 8671if (REFACTOR_DEBUG) { 8672Slog.e("TODD", 8673 "Scan package"); 8674Slog.e("TODD", 8675 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8676} 8677 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8678 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8679if (REFACTOR_DEBUG) { 8680pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8681Slog.e("TODD", 8682 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8683} 8684 8685 if (shouldHideSystemApp) { 8686if (REFACTOR_DEBUG) { 8687Slog.e("TODD", 8688 "Disable package: " + pkg.packageName); 8689} 8690 synchronized (mPackages) { 8691 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8692 } 8693 } 8694 return scannedPkg; 8695 } 8696 8697 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8698 // Derive the new package synthetic package name 8699 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8700 + pkg.staticSharedLibVersion); 8701 } 8702 8703 private static String fixProcessName(String defProcessName, 8704 String processName) { 8705 if (processName == null) { 8706 return defProcessName; 8707 } 8708 return processName; 8709 } 8710 8711 /** 8712 * Enforces that only the system UID or root's UID can call a method exposed 8713 * via Binder. 8714 * 8715 * @param message used as message if SecurityException is thrown 8716 * @throws SecurityException if the caller is not system or root 8717 */ 8718 private static final void enforceSystemOrRoot(String message) { 8719 final int uid = Binder.getCallingUid(); 8720 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8721 throw new SecurityException(message); 8722 } 8723 } 8724 8725 @Override 8726 public void performFstrimIfNeeded() { 8727 enforceSystemOrRoot("Only the system can request fstrim"); 8728 8729 // Before everything else, see whether we need to fstrim. 8730 try { 8731 IStorageManager sm = PackageHelper.getStorageManager(); 8732 if (sm != null) { 8733 boolean doTrim = false; 8734 final long interval = android.provider.Settings.Global.getLong( 8735 mContext.getContentResolver(), 8736 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8737 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8738 if (interval > 0) { 8739 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8740 if (timeSinceLast > interval) { 8741 doTrim = true; 8742 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8743 + "; running immediately"); 8744 } 8745 } 8746 if (doTrim) { 8747 final boolean dexOptDialogShown; 8748 synchronized (mPackages) { 8749 dexOptDialogShown = mDexOptDialogShown; 8750 } 8751 if (!isFirstBoot() && dexOptDialogShown) { 8752 try { 8753 ActivityManager.getService().showBootMessage( 8754 mContext.getResources().getString( 8755 R.string.android_upgrading_fstrim), true); 8756 } catch (RemoteException e) { 8757 } 8758 } 8759 sm.runMaintenance(); 8760 } 8761 } else { 8762 Slog.e(TAG, "storageManager service unavailable!"); 8763 } 8764 } catch (RemoteException e) { 8765 // Can't happen; StorageManagerService is local 8766 } 8767 } 8768 8769 @Override 8770 public void updatePackagesIfNeeded() { 8771 enforceSystemOrRoot("Only the system can request package update"); 8772 8773 // We need to re-extract after an OTA. 8774 boolean causeUpgrade = isUpgrade(); 8775 8776 // First boot or factory reset. 8777 // Note: we also handle devices that are upgrading to N right now as if it is their 8778 // first boot, as they do not have profile data. 8779 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8780 8781 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8782 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8783 8784 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8785 return; 8786 } 8787 8788 List<PackageParser.Package> pkgs; 8789 synchronized (mPackages) { 8790 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8791 } 8792 8793 final long startTime = System.nanoTime(); 8794 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8795 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8796 false /* bootComplete */); 8797 8798 final int elapsedTimeSeconds = 8799 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8800 8801 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8802 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8803 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8804 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8805 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8806 } 8807 8808 /* 8809 * Return the prebuilt profile path given a package base code path. 8810 */ 8811 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8812 return pkg.baseCodePath + ".prof"; 8813 } 8814 8815 /** 8816 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8817 * containing statistics about the invocation. The array consists of three elements, 8818 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8819 * and {@code numberOfPackagesFailed}. 8820 */ 8821 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8822 final String compilerFilter, boolean bootComplete) { 8823 8824 int numberOfPackagesVisited = 0; 8825 int numberOfPackagesOptimized = 0; 8826 int numberOfPackagesSkipped = 0; 8827 int numberOfPackagesFailed = 0; 8828 final int numberOfPackagesToDexopt = pkgs.size(); 8829 8830 for (PackageParser.Package pkg : pkgs) { 8831 numberOfPackagesVisited++; 8832 8833 boolean useProfileForDexopt = false; 8834 8835 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8836 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8837 // that are already compiled. 8838 File profileFile = new File(getPrebuildProfilePath(pkg)); 8839 // Copy profile if it exists. 8840 if (profileFile.exists()) { 8841 try { 8842 // We could also do this lazily before calling dexopt in 8843 // PackageDexOptimizer to prevent this happening on first boot. The issue 8844 // is that we don't have a good way to say "do this only once". 8845 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8846 pkg.applicationInfo.uid, pkg.packageName)) { 8847 Log.e(TAG, "Installer failed to copy system profile!"); 8848 } else { 8849 // Disabled as this causes speed-profile compilation during first boot 8850 // even if things are already compiled. 8851 // useProfileForDexopt = true; 8852 } 8853 } catch (Exception e) { 8854 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8855 e); 8856 } 8857 } else { 8858 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8859 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8860 // minimize the number off apps being speed-profile compiled during first boot. 8861 // The other paths will not change the filter. 8862 if (disabledPs != null && disabledPs.pkg.isStub) { 8863 // The package is the stub one, remove the stub suffix to get the normal 8864 // package and APK names. 8865 String systemProfilePath = 8866 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8867 profileFile = new File(systemProfilePath); 8868 // If we have a profile for a compressed APK, copy it to the reference 8869 // location. 8870 // Note that copying the profile here will cause it to override the 8871 // reference profile every OTA even though the existing reference profile 8872 // may have more data. We can't copy during decompression since the 8873 // directories are not set up at that point. 8874 if (profileFile.exists()) { 8875 try { 8876 // We could also do this lazily before calling dexopt in 8877 // PackageDexOptimizer to prevent this happening on first boot. The 8878 // issue is that we don't have a good way to say "do this only 8879 // once". 8880 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8881 pkg.applicationInfo.uid, pkg.packageName)) { 8882 Log.e(TAG, "Failed to copy system profile for stub package!"); 8883 } else { 8884 useProfileForDexopt = true; 8885 } 8886 } catch (Exception e) { 8887 Log.e(TAG, "Failed to copy profile " + 8888 profileFile.getAbsolutePath() + " ", e); 8889 } 8890 } 8891 } 8892 } 8893 } 8894 8895 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8896 if (DEBUG_DEXOPT) { 8897 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8898 } 8899 numberOfPackagesSkipped++; 8900 continue; 8901 } 8902 8903 if (DEBUG_DEXOPT) { 8904 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8905 numberOfPackagesToDexopt + ": " + pkg.packageName); 8906 } 8907 8908 if (showDialog) { 8909 try { 8910 ActivityManager.getService().showBootMessage( 8911 mContext.getResources().getString(R.string.android_upgrading_apk, 8912 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8913 } catch (RemoteException e) { 8914 } 8915 synchronized (mPackages) { 8916 mDexOptDialogShown = true; 8917 } 8918 } 8919 8920 String pkgCompilerFilter = compilerFilter; 8921 if (useProfileForDexopt) { 8922 // Use background dexopt mode to try and use the profile. Note that this does not 8923 // guarantee usage of the profile. 8924 pkgCompilerFilter = 8925 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 8926 PackageManagerService.REASON_BACKGROUND_DEXOPT); 8927 } 8928 8929 // checkProfiles is false to avoid merging profiles during boot which 8930 // might interfere with background compilation (b/28612421). 8931 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8932 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8933 // trade-off worth doing to save boot time work. 8934 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8935 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8936 pkg.packageName, 8937 pkgCompilerFilter, 8938 dexoptFlags)); 8939 8940 switch (primaryDexOptStaus) { 8941 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8942 numberOfPackagesOptimized++; 8943 break; 8944 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8945 numberOfPackagesSkipped++; 8946 break; 8947 case PackageDexOptimizer.DEX_OPT_FAILED: 8948 numberOfPackagesFailed++; 8949 break; 8950 default: 8951 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 8952 break; 8953 } 8954 } 8955 8956 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8957 numberOfPackagesFailed }; 8958 } 8959 8960 @Override 8961 public void notifyPackageUse(String packageName, int reason) { 8962 synchronized (mPackages) { 8963 final int callingUid = Binder.getCallingUid(); 8964 final int callingUserId = UserHandle.getUserId(callingUid); 8965 if (getInstantAppPackageName(callingUid) != null) { 8966 if (!isCallerSameApp(packageName, callingUid)) { 8967 return; 8968 } 8969 } else { 8970 if (isInstantApp(packageName, callingUserId)) { 8971 return; 8972 } 8973 } 8974 notifyPackageUseLocked(packageName, reason); 8975 } 8976 } 8977 8978 private void notifyPackageUseLocked(String packageName, int reason) { 8979 final PackageParser.Package p = mPackages.get(packageName); 8980 if (p == null) { 8981 return; 8982 } 8983 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8984 } 8985 8986 @Override 8987 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 8988 List<String> classPaths, String loaderIsa) { 8989 int userId = UserHandle.getCallingUserId(); 8990 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8991 if (ai == null) { 8992 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8993 + loadingPackageName + ", user=" + userId); 8994 return; 8995 } 8996 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 8997 } 8998 8999 @Override 9000 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9001 IDexModuleRegisterCallback callback) { 9002 int userId = UserHandle.getCallingUserId(); 9003 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9004 DexManager.RegisterDexModuleResult result; 9005 if (ai == null) { 9006 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9007 " calling user. package=" + packageName + ", user=" + userId); 9008 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9009 } else { 9010 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9011 } 9012 9013 if (callback != null) { 9014 mHandler.post(() -> { 9015 try { 9016 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9017 } catch (RemoteException e) { 9018 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9019 } 9020 }); 9021 } 9022 } 9023 9024 /** 9025 * Ask the package manager to perform a dex-opt with the given compiler filter. 9026 * 9027 * Note: exposed only for the shell command to allow moving packages explicitly to a 9028 * definite state. 9029 */ 9030 @Override 9031 public boolean performDexOptMode(String packageName, 9032 boolean checkProfiles, String targetCompilerFilter, boolean force, 9033 boolean bootComplete, String splitName) { 9034 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9035 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9036 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9037 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9038 splitName, flags)); 9039 } 9040 9041 /** 9042 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9043 * secondary dex files belonging to the given package. 9044 * 9045 * Note: exposed only for the shell command to allow moving packages explicitly to a 9046 * definite state. 9047 */ 9048 @Override 9049 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9050 boolean force) { 9051 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9052 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9053 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9054 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9055 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9056 } 9057 9058 /*package*/ boolean performDexOpt(DexoptOptions options) { 9059 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9060 return false; 9061 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9062 return false; 9063 } 9064 9065 if (options.isDexoptOnlySecondaryDex()) { 9066 return mDexManager.dexoptSecondaryDex(options); 9067 } else { 9068 int dexoptStatus = performDexOptWithStatus(options); 9069 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9070 } 9071 } 9072 9073 /** 9074 * Perform dexopt on the given package and return one of following result: 9075 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9076 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9077 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9078 */ 9079 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9080 return performDexOptTraced(options); 9081 } 9082 9083 private int performDexOptTraced(DexoptOptions options) { 9084 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9085 try { 9086 return performDexOptInternal(options); 9087 } finally { 9088 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9089 } 9090 } 9091 9092 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9093 // if the package can now be considered up to date for the given filter. 9094 private int performDexOptInternal(DexoptOptions options) { 9095 PackageParser.Package p; 9096 synchronized (mPackages) { 9097 p = mPackages.get(options.getPackageName()); 9098 if (p == null) { 9099 // Package could not be found. Report failure. 9100 return PackageDexOptimizer.DEX_OPT_FAILED; 9101 } 9102 mPackageUsage.maybeWriteAsync(mPackages); 9103 mCompilerStats.maybeWriteAsync(); 9104 } 9105 long callingId = Binder.clearCallingIdentity(); 9106 try { 9107 synchronized (mInstallLock) { 9108 return performDexOptInternalWithDependenciesLI(p, options); 9109 } 9110 } finally { 9111 Binder.restoreCallingIdentity(callingId); 9112 } 9113 } 9114 9115 public ArraySet<String> getOptimizablePackages() { 9116 ArraySet<String> pkgs = new ArraySet<String>(); 9117 synchronized (mPackages) { 9118 for (PackageParser.Package p : mPackages.values()) { 9119 if (PackageDexOptimizer.canOptimizePackage(p)) { 9120 pkgs.add(p.packageName); 9121 } 9122 } 9123 } 9124 return pkgs; 9125 } 9126 9127 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9128 DexoptOptions options) { 9129 // Select the dex optimizer based on the force parameter. 9130 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9131 // allocate an object here. 9132 PackageDexOptimizer pdo = options.isForce() 9133 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9134 : mPackageDexOptimizer; 9135 9136 // Dexopt all dependencies first. Note: we ignore the return value and march on 9137 // on errors. 9138 // Note that we are going to call performDexOpt on those libraries as many times as 9139 // they are referenced in packages. When we do a batch of performDexOpt (for example 9140 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9141 // and the first package that uses the library will dexopt it. The 9142 // others will see that the compiled code for the library is up to date. 9143 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9144 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9145 if (!deps.isEmpty()) { 9146 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9147 options.getCompilerFilter(), options.getSplitName(), 9148 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9149 for (PackageParser.Package depPackage : deps) { 9150 // TODO: Analyze and investigate if we (should) profile libraries. 9151 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9152 getOrCreateCompilerPackageStats(depPackage), 9153 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9154 } 9155 } 9156 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9157 getOrCreateCompilerPackageStats(p), 9158 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9159 } 9160 9161 /** 9162 * Reconcile the information we have about the secondary dex files belonging to 9163 * {@code packagName} and the actual dex files. For all dex files that were 9164 * deleted, update the internal records and delete the generated oat files. 9165 */ 9166 @Override 9167 public void reconcileSecondaryDexFiles(String packageName) { 9168 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9169 return; 9170 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9171 return; 9172 } 9173 mDexManager.reconcileSecondaryDexFiles(packageName); 9174 } 9175 9176 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9177 // a reference there. 9178 /*package*/ DexManager getDexManager() { 9179 return mDexManager; 9180 } 9181 9182 /** 9183 * Execute the background dexopt job immediately. 9184 */ 9185 @Override 9186 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9187 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9188 return false; 9189 } 9190 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9191 } 9192 9193 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9194 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9195 || p.usesStaticLibraries != null) { 9196 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9197 Set<String> collectedNames = new HashSet<>(); 9198 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9199 9200 retValue.remove(p); 9201 9202 return retValue; 9203 } else { 9204 return Collections.emptyList(); 9205 } 9206 } 9207 9208 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9209 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9210 if (!collectedNames.contains(p.packageName)) { 9211 collectedNames.add(p.packageName); 9212 collected.add(p); 9213 9214 if (p.usesLibraries != null) { 9215 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9216 null, collected, collectedNames); 9217 } 9218 if (p.usesOptionalLibraries != null) { 9219 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9220 null, collected, collectedNames); 9221 } 9222 if (p.usesStaticLibraries != null) { 9223 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9224 p.usesStaticLibrariesVersions, collected, collectedNames); 9225 } 9226 } 9227 } 9228 9229 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9230 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9231 final int libNameCount = libs.size(); 9232 for (int i = 0; i < libNameCount; i++) { 9233 String libName = libs.get(i); 9234 long version = (versions != null && versions.length == libNameCount) 9235 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9236 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9237 if (libPkg != null) { 9238 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9239 } 9240 } 9241 } 9242 9243 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9244 synchronized (mPackages) { 9245 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9246 if (libEntry != null) { 9247 return mPackages.get(libEntry.apk); 9248 } 9249 return null; 9250 } 9251 } 9252 9253 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9254 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9255 if (versionedLib == null) { 9256 return null; 9257 } 9258 return versionedLib.get(version); 9259 } 9260 9261 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9262 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9263 pkg.staticSharedLibName); 9264 if (versionedLib == null) { 9265 return null; 9266 } 9267 long previousLibVersion = -1; 9268 final int versionCount = versionedLib.size(); 9269 for (int i = 0; i < versionCount; i++) { 9270 final long libVersion = versionedLib.keyAt(i); 9271 if (libVersion < pkg.staticSharedLibVersion) { 9272 previousLibVersion = Math.max(previousLibVersion, libVersion); 9273 } 9274 } 9275 if (previousLibVersion >= 0) { 9276 return versionedLib.get(previousLibVersion); 9277 } 9278 return null; 9279 } 9280 9281 public void shutdown() { 9282 mPackageUsage.writeNow(mPackages); 9283 mCompilerStats.writeNow(); 9284 mDexManager.writePackageDexUsageNow(); 9285 } 9286 9287 @Override 9288 public void dumpProfiles(String packageName) { 9289 PackageParser.Package pkg; 9290 synchronized (mPackages) { 9291 pkg = mPackages.get(packageName); 9292 if (pkg == null) { 9293 throw new IllegalArgumentException("Unknown package: " + packageName); 9294 } 9295 } 9296 /* Only the shell, root, or the app user should be able to dump profiles. */ 9297 int callingUid = Binder.getCallingUid(); 9298 if (callingUid != Process.SHELL_UID && 9299 callingUid != Process.ROOT_UID && 9300 callingUid != pkg.applicationInfo.uid) { 9301 throw new SecurityException("dumpProfiles"); 9302 } 9303 9304 synchronized (mInstallLock) { 9305 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9306 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9307 try { 9308 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9309 String codePaths = TextUtils.join(";", allCodePaths); 9310 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9311 } catch (InstallerException e) { 9312 Slog.w(TAG, "Failed to dump profiles", e); 9313 } 9314 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9315 } 9316 } 9317 9318 @Override 9319 public void forceDexOpt(String packageName) { 9320 enforceSystemOrRoot("forceDexOpt"); 9321 9322 PackageParser.Package pkg; 9323 synchronized (mPackages) { 9324 pkg = mPackages.get(packageName); 9325 if (pkg == null) { 9326 throw new IllegalArgumentException("Unknown package: " + packageName); 9327 } 9328 } 9329 9330 synchronized (mInstallLock) { 9331 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9332 9333 // Whoever is calling forceDexOpt wants a compiled package. 9334 // Don't use profiles since that may cause compilation to be skipped. 9335 final int res = performDexOptInternalWithDependenciesLI( 9336 pkg, 9337 new DexoptOptions(packageName, 9338 getDefaultCompilerFilter(), 9339 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9340 9341 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9342 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9343 throw new IllegalStateException("Failed to dexopt: " + res); 9344 } 9345 } 9346 } 9347 9348 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9349 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9350 Slog.w(TAG, "Unable to update from " + oldPkg.name 9351 + " to " + newPkg.packageName 9352 + ": old package not in system partition"); 9353 return false; 9354 } else if (mPackages.get(oldPkg.name) != null) { 9355 Slog.w(TAG, "Unable to update from " + oldPkg.name 9356 + " to " + newPkg.packageName 9357 + ": old package still exists"); 9358 return false; 9359 } 9360 return true; 9361 } 9362 9363 void removeCodePathLI(File codePath) { 9364 if (codePath.isDirectory()) { 9365 try { 9366 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9367 } catch (InstallerException e) { 9368 Slog.w(TAG, "Failed to remove code path", e); 9369 } 9370 } else { 9371 codePath.delete(); 9372 } 9373 } 9374 9375 private int[] resolveUserIds(int userId) { 9376 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9377 } 9378 9379 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9380 if (pkg == null) { 9381 Slog.wtf(TAG, "Package was null!", new Throwable()); 9382 return; 9383 } 9384 clearAppDataLeafLIF(pkg, userId, flags); 9385 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9386 for (int i = 0; i < childCount; i++) { 9387 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9388 } 9389 } 9390 9391 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9392 final PackageSetting ps; 9393 synchronized (mPackages) { 9394 ps = mSettings.mPackages.get(pkg.packageName); 9395 } 9396 for (int realUserId : resolveUserIds(userId)) { 9397 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9398 try { 9399 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9400 ceDataInode); 9401 } catch (InstallerException e) { 9402 Slog.w(TAG, String.valueOf(e)); 9403 } 9404 } 9405 } 9406 9407 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9408 if (pkg == null) { 9409 Slog.wtf(TAG, "Package was null!", new Throwable()); 9410 return; 9411 } 9412 destroyAppDataLeafLIF(pkg, userId, flags); 9413 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9414 for (int i = 0; i < childCount; i++) { 9415 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9416 } 9417 } 9418 9419 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9420 final PackageSetting ps; 9421 synchronized (mPackages) { 9422 ps = mSettings.mPackages.get(pkg.packageName); 9423 } 9424 for (int realUserId : resolveUserIds(userId)) { 9425 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9426 try { 9427 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9428 ceDataInode); 9429 } catch (InstallerException e) { 9430 Slog.w(TAG, String.valueOf(e)); 9431 } 9432 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9433 } 9434 } 9435 9436 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9437 if (pkg == null) { 9438 Slog.wtf(TAG, "Package was null!", new Throwable()); 9439 return; 9440 } 9441 destroyAppProfilesLeafLIF(pkg); 9442 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9443 for (int i = 0; i < childCount; i++) { 9444 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9445 } 9446 } 9447 9448 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9449 try { 9450 mInstaller.destroyAppProfiles(pkg.packageName); 9451 } catch (InstallerException e) { 9452 Slog.w(TAG, String.valueOf(e)); 9453 } 9454 } 9455 9456 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9457 if (pkg == null) { 9458 Slog.wtf(TAG, "Package was null!", new Throwable()); 9459 return; 9460 } 9461 clearAppProfilesLeafLIF(pkg); 9462 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9463 for (int i = 0; i < childCount; i++) { 9464 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9465 } 9466 } 9467 9468 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9469 try { 9470 mInstaller.clearAppProfiles(pkg.packageName); 9471 } catch (InstallerException e) { 9472 Slog.w(TAG, String.valueOf(e)); 9473 } 9474 } 9475 9476 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9477 long lastUpdateTime) { 9478 // Set parent install/update time 9479 PackageSetting ps = (PackageSetting) pkg.mExtras; 9480 if (ps != null) { 9481 ps.firstInstallTime = firstInstallTime; 9482 ps.lastUpdateTime = lastUpdateTime; 9483 } 9484 // Set children install/update time 9485 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9486 for (int i = 0; i < childCount; i++) { 9487 PackageParser.Package childPkg = pkg.childPackages.get(i); 9488 ps = (PackageSetting) childPkg.mExtras; 9489 if (ps != null) { 9490 ps.firstInstallTime = firstInstallTime; 9491 ps.lastUpdateTime = lastUpdateTime; 9492 } 9493 } 9494 } 9495 9496 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9497 SharedLibraryEntry file, 9498 PackageParser.Package changingLib) { 9499 if (file.path != null) { 9500 usesLibraryFiles.add(file.path); 9501 return; 9502 } 9503 PackageParser.Package p = mPackages.get(file.apk); 9504 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9505 // If we are doing this while in the middle of updating a library apk, 9506 // then we need to make sure to use that new apk for determining the 9507 // dependencies here. (We haven't yet finished committing the new apk 9508 // to the package manager state.) 9509 if (p == null || p.packageName.equals(changingLib.packageName)) { 9510 p = changingLib; 9511 } 9512 } 9513 if (p != null) { 9514 usesLibraryFiles.addAll(p.getAllCodePaths()); 9515 if (p.usesLibraryFiles != null) { 9516 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9517 } 9518 } 9519 } 9520 9521 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9522 PackageParser.Package changingLib) throws PackageManagerException { 9523 if (pkg == null) { 9524 return; 9525 } 9526 // The collection used here must maintain the order of addition (so 9527 // that libraries are searched in the correct order) and must have no 9528 // duplicates. 9529 Set<String> usesLibraryFiles = null; 9530 if (pkg.usesLibraries != null) { 9531 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9532 null, null, pkg.packageName, changingLib, true, 9533 pkg.applicationInfo.targetSdkVersion, null); 9534 } 9535 if (pkg.usesStaticLibraries != null) { 9536 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9537 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9538 pkg.packageName, changingLib, true, 9539 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9540 } 9541 if (pkg.usesOptionalLibraries != null) { 9542 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9543 null, null, pkg.packageName, changingLib, false, 9544 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9545 } 9546 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9547 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9548 } else { 9549 pkg.usesLibraryFiles = null; 9550 } 9551 } 9552 9553 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9554 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9555 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9556 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9557 throws PackageManagerException { 9558 final int libCount = requestedLibraries.size(); 9559 for (int i = 0; i < libCount; i++) { 9560 final String libName = requestedLibraries.get(i); 9561 final long libVersion = requiredVersions != null ? requiredVersions[i] 9562 : SharedLibraryInfo.VERSION_UNDEFINED; 9563 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9564 if (libEntry == null) { 9565 if (required) { 9566 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9567 "Package " + packageName + " requires unavailable shared library " 9568 + libName + "; failing!"); 9569 } else if (DEBUG_SHARED_LIBRARIES) { 9570 Slog.i(TAG, "Package " + packageName 9571 + " desires unavailable shared library " 9572 + libName + "; ignoring!"); 9573 } 9574 } else { 9575 if (requiredVersions != null && requiredCertDigests != null) { 9576 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9577 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9578 "Package " + packageName + " requires unavailable static shared" 9579 + " library " + libName + " version " 9580 + libEntry.info.getLongVersion() + "; failing!"); 9581 } 9582 9583 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9584 if (libPkg == null) { 9585 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9586 "Package " + packageName + " requires unavailable static shared" 9587 + " library; failing!"); 9588 } 9589 9590 final String[] expectedCertDigests = requiredCertDigests[i]; 9591 // For apps targeting O MR1 we require explicit enumeration of all certs. 9592 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9593 ? PackageUtils.computeSignaturesSha256Digests( 9594 libPkg.mSigningDetails.signatures) 9595 : PackageUtils.computeSignaturesSha256Digests( 9596 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9597 9598 // Take a shortcut if sizes don't match. Note that if an app doesn't 9599 // target O we don't parse the "additional-certificate" tags similarly 9600 // how we only consider all certs only for apps targeting O (see above). 9601 // Therefore, the size check is safe to make. 9602 if (expectedCertDigests.length != libCertDigests.length) { 9603 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9604 "Package " + packageName + " requires differently signed" + 9605 " static shared library; failing!"); 9606 } 9607 9608 // Use a predictable order as signature order may vary 9609 Arrays.sort(libCertDigests); 9610 Arrays.sort(expectedCertDigests); 9611 9612 final int certCount = libCertDigests.length; 9613 for (int j = 0; j < certCount; j++) { 9614 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9615 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9616 "Package " + packageName + " requires differently signed" + 9617 " static shared library; failing!"); 9618 } 9619 } 9620 } 9621 9622 if (outUsedLibraries == null) { 9623 // Use LinkedHashSet to preserve the order of files added to 9624 // usesLibraryFiles while eliminating duplicates. 9625 outUsedLibraries = new LinkedHashSet<>(); 9626 } 9627 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9628 } 9629 } 9630 return outUsedLibraries; 9631 } 9632 9633 private static boolean hasString(List<String> list, List<String> which) { 9634 if (list == null) { 9635 return false; 9636 } 9637 for (int i=list.size()-1; i>=0; i--) { 9638 for (int j=which.size()-1; j>=0; j--) { 9639 if (which.get(j).equals(list.get(i))) { 9640 return true; 9641 } 9642 } 9643 } 9644 return false; 9645 } 9646 9647 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9648 PackageParser.Package changingPkg) { 9649 ArrayList<PackageParser.Package> res = null; 9650 for (PackageParser.Package pkg : mPackages.values()) { 9651 if (changingPkg != null 9652 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9653 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9654 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9655 changingPkg.staticSharedLibName)) { 9656 return null; 9657 } 9658 if (res == null) { 9659 res = new ArrayList<>(); 9660 } 9661 res.add(pkg); 9662 try { 9663 updateSharedLibrariesLPr(pkg, changingPkg); 9664 } catch (PackageManagerException e) { 9665 // If a system app update or an app and a required lib missing we 9666 // delete the package and for updated system apps keep the data as 9667 // it is better for the user to reinstall than to be in an limbo 9668 // state. Also libs disappearing under an app should never happen 9669 // - just in case. 9670 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9671 final int flags = pkg.isUpdatedSystemApp() 9672 ? PackageManager.DELETE_KEEP_DATA : 0; 9673 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9674 flags , null, true, null); 9675 } 9676 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9677 } 9678 } 9679 return res; 9680 } 9681 9682 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9683 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9684 @Nullable UserHandle user) throws PackageManagerException { 9685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9686 // If the package has children and this is the first dive in the function 9687 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9688 // whether all packages (parent and children) would be successfully scanned 9689 // before the actual scan since scanning mutates internal state and we want 9690 // to atomically install the package and its children. 9691 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9692 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9693 scanFlags |= SCAN_CHECK_ONLY; 9694 } 9695 } else { 9696 scanFlags &= ~SCAN_CHECK_ONLY; 9697 } 9698 9699 final PackageParser.Package scannedPkg; 9700 try { 9701 // Scan the parent 9702 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9703 // Scan the children 9704 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9705 for (int i = 0; i < childCount; i++) { 9706 PackageParser.Package childPkg = pkg.childPackages.get(i); 9707 scanPackageNewLI(childPkg, parseFlags, 9708 scanFlags, currentTime, user); 9709 } 9710 } finally { 9711 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9712 } 9713 9714 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9715 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9716 } 9717 9718 return scannedPkg; 9719 } 9720 9721 /** The result of a package scan. */ 9722 private static class ScanResult { 9723 /** Whether or not the package scan was successful */ 9724 public final boolean success; 9725 /** 9726 * The final package settings. This may be the same object passed in 9727 * the {@link ScanRequest}, but, with modified values. 9728 */ 9729 @Nullable public final PackageSetting pkgSetting; 9730 /** ABI code paths that have changed in the package scan */ 9731 @Nullable public final List<String> changedAbiCodePath; 9732 public ScanResult( 9733 boolean success, 9734 @Nullable PackageSetting pkgSetting, 9735 @Nullable List<String> changedAbiCodePath) { 9736 this.success = success; 9737 this.pkgSetting = pkgSetting; 9738 this.changedAbiCodePath = changedAbiCodePath; 9739 } 9740 } 9741 9742 /** A package to be scanned */ 9743 private static class ScanRequest { 9744 /** The parsed package */ 9745 @NonNull public final PackageParser.Package pkg; 9746 /** Shared user settings, if the package has a shared user */ 9747 @Nullable public final SharedUserSetting sharedUserSetting; 9748 /** 9749 * Package settings of the currently installed version. 9750 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9751 * during scan. 9752 */ 9753 @Nullable public final PackageSetting pkgSetting; 9754 /** A copy of the settings for the currently installed version */ 9755 @Nullable public final PackageSetting oldPkgSetting; 9756 /** Package settings for the disabled version on the /system partition */ 9757 @Nullable public final PackageSetting disabledPkgSetting; 9758 /** Package settings for the installed version under its original package name */ 9759 @Nullable public final PackageSetting originalPkgSetting; 9760 /** The real package name of a renamed application */ 9761 @Nullable public final String realPkgName; 9762 public final @ParseFlags int parseFlags; 9763 public final @ScanFlags int scanFlags; 9764 /** The user for which the package is being scanned */ 9765 @Nullable public final UserHandle user; 9766 /** Whether or not the platform package is being scanned */ 9767 public final boolean isPlatformPackage; 9768 public ScanRequest( 9769 @NonNull PackageParser.Package pkg, 9770 @Nullable SharedUserSetting sharedUserSetting, 9771 @Nullable PackageSetting pkgSetting, 9772 @Nullable PackageSetting disabledPkgSetting, 9773 @Nullable PackageSetting originalPkgSetting, 9774 @Nullable String realPkgName, 9775 @ParseFlags int parseFlags, 9776 @ScanFlags int scanFlags, 9777 boolean isPlatformPackage, 9778 @Nullable UserHandle user) { 9779 this.pkg = pkg; 9780 this.pkgSetting = pkgSetting; 9781 this.sharedUserSetting = sharedUserSetting; 9782 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9783 this.disabledPkgSetting = disabledPkgSetting; 9784 this.originalPkgSetting = originalPkgSetting; 9785 this.realPkgName = realPkgName; 9786 this.parseFlags = parseFlags; 9787 this.scanFlags = scanFlags; 9788 this.isPlatformPackage = isPlatformPackage; 9789 this.user = user; 9790 } 9791 } 9792 9793 /** 9794 * Returns the actual scan flags depending upon the state of the other settings. 9795 * <p>Updated system applications will not have the following flags set 9796 * by default and need to be adjusted after the fact: 9797 * <ul> 9798 * <li>{@link #SCAN_AS_SYSTEM}</li> 9799 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9800 * <li>{@link #SCAN_AS_OEM}</li> 9801 * <li>{@link #SCAN_AS_VENDOR}</li> 9802 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9803 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9804 * </ul> 9805 */ 9806 private static @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9807 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user) { 9808 if (disabledPkgSetting != null) { 9809 // updated system application, must at least have SCAN_AS_SYSTEM 9810 scanFlags |= SCAN_AS_SYSTEM; 9811 if ((disabledPkgSetting.pkgPrivateFlags 9812 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9813 scanFlags |= SCAN_AS_PRIVILEGED; 9814 } 9815 if ((disabledPkgSetting.pkgPrivateFlags 9816 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9817 scanFlags |= SCAN_AS_OEM; 9818 } 9819 if ((disabledPkgSetting.pkgPrivateFlags 9820 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9821 scanFlags |= SCAN_AS_VENDOR; 9822 } 9823 } 9824 if (pkgSetting != null) { 9825 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9826 if (pkgSetting.getInstantApp(userId)) { 9827 scanFlags |= SCAN_AS_INSTANT_APP; 9828 } 9829 if (pkgSetting.getVirtulalPreload(userId)) { 9830 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9831 } 9832 } 9833 return scanFlags; 9834 } 9835 9836 @GuardedBy("mInstallLock") 9837 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9838 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9839 @Nullable UserHandle user) throws PackageManagerException { 9840 9841 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9842 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9843 if (realPkgName != null) { 9844 ensurePackageRenamed(pkg, renamedPkgName); 9845 } 9846 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9847 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9848 final PackageSetting disabledPkgSetting = 9849 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9850 9851 if (mTransferedPackages.contains(pkg.packageName)) { 9852 Slog.w(TAG, "Package " + pkg.packageName 9853 + " was transferred to another, but its .apk remains"); 9854 } 9855 9856 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user); 9857 synchronized (mPackages) { 9858 applyPolicy(pkg, parseFlags, scanFlags); 9859 assertPackageIsValid(pkg, parseFlags, scanFlags); 9860 9861 SharedUserSetting sharedUserSetting = null; 9862 if (pkg.mSharedUserId != null) { 9863 // SIDE EFFECTS; may potentially allocate a new shared user 9864 sharedUserSetting = mSettings.getSharedUserLPw( 9865 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9866 if (DEBUG_PACKAGE_SCANNING) { 9867 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9868 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9869 + " (uid=" + sharedUserSetting.userId + "):" 9870 + " packages=" + sharedUserSetting.packages); 9871 } 9872 } 9873 9874 boolean scanSucceeded = false; 9875 try { 9876 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9877 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9878 (pkg == mPlatformPackage), user); 9879 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9880 if (result.success) { 9881 commitScanResultsLocked(request, result); 9882 } 9883 scanSucceeded = true; 9884 } finally { 9885 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9886 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9887 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9888 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9889 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9890 } 9891 } 9892 } 9893 return pkg; 9894 } 9895 9896 /** 9897 * Commits the package scan and modifies system state. 9898 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 9899 * of committing the package, leaving the system in an inconsistent state. 9900 * This needs to be fixed so, once we get to this point, no errors are 9901 * possible and the system is not left in an inconsistent state. 9902 */ 9903 @GuardedBy("mPackages") 9904 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 9905 throws PackageManagerException { 9906 final PackageParser.Package pkg = request.pkg; 9907 final @ParseFlags int parseFlags = request.parseFlags; 9908 final @ScanFlags int scanFlags = request.scanFlags; 9909 final PackageSetting oldPkgSetting = request.oldPkgSetting; 9910 final PackageSetting originalPkgSetting = request.originalPkgSetting; 9911 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 9912 final UserHandle user = request.user; 9913 final String realPkgName = request.realPkgName; 9914 final PackageSetting pkgSetting = result.pkgSetting; 9915 final List<String> changedAbiCodePath = result.changedAbiCodePath; 9916 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 9917 9918 if (newPkgSettingCreated) { 9919 if (originalPkgSetting != null) { 9920 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 9921 } 9922 // THROWS: when we can't allocate a user id. add call to check if there's 9923 // enough space to ensure we won't throw; otherwise, don't modify state 9924 mSettings.addUserToSettingLPw(pkgSetting); 9925 9926 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 9927 mTransferedPackages.add(originalPkgSetting.name); 9928 } 9929 } 9930 // TODO(toddke): Consider a method specifically for modifying the Package object 9931 // post scan; or, moving this stuff out of the Package object since it has nothing 9932 // to do with the package on disk. 9933 // We need to have this here because addUserToSettingLPw() is sometimes responsible 9934 // for creating the application ID. If we did this earlier, we would be saving the 9935 // correct ID. 9936 pkg.applicationInfo.uid = pkgSetting.appId; 9937 9938 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9939 9940 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 9941 mTransferedPackages.add(pkg.packageName); 9942 } 9943 9944 // THROWS: when requested libraries that can't be found. it only changes 9945 // the state of the passed in pkg object, so, move to the top of the method 9946 // and allow it to abort 9947 if ((scanFlags & SCAN_BOOTING) == 0 9948 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9949 // Check all shared libraries and map to their actual file path. 9950 // We only do this here for apps not on a system dir, because those 9951 // are the only ones that can fail an install due to this. We 9952 // will take care of the system apps by updating all of their 9953 // library paths after the scan is done. Also during the initial 9954 // scan don't update any libs as we do this wholesale after all 9955 // apps are scanned to avoid dependency based scanning. 9956 updateSharedLibrariesLPr(pkg, null); 9957 } 9958 9959 // All versions of a static shared library are referenced with the same 9960 // package name. Internally, we use a synthetic package name to allow 9961 // multiple versions of the same shared library to be installed. So, 9962 // we need to generate the synthetic package name of the latest shared 9963 // library in order to compare signatures. 9964 PackageSetting signatureCheckPs = pkgSetting; 9965 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9966 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9967 if (libraryEntry != null) { 9968 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9969 } 9970 } 9971 9972 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 9973 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 9974 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 9975 // We just determined the app is signed correctly, so bring 9976 // over the latest parsed certs. 9977 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 9978 } else { 9979 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9980 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9981 "Package " + pkg.packageName + " upgrade keys do not match the " 9982 + "previously installed version"); 9983 } else { 9984 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 9985 String msg = "System package " + pkg.packageName 9986 + " signature changed; retaining data."; 9987 reportSettingsProblem(Log.WARN, msg); 9988 } 9989 } 9990 } else { 9991 try { 9992 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 9993 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 9994 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 9995 pkg.mSigningDetails, compareCompat, compareRecover); 9996 // The new KeySets will be re-added later in the scanning process. 9997 if (compatMatch) { 9998 synchronized (mPackages) { 9999 ksms.removeAppKeySetDataLPw(pkg.packageName); 10000 } 10001 } 10002 // We just determined the app is signed correctly, so bring 10003 // over the latest parsed certs. 10004 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10005 } catch (PackageManagerException e) { 10006 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10007 throw e; 10008 } 10009 // The signature has changed, but this package is in the system 10010 // image... let's recover! 10011 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10012 // However... if this package is part of a shared user, but it 10013 // doesn't match the signature of the shared user, let's fail. 10014 // What this means is that you can't change the signatures 10015 // associated with an overall shared user, which doesn't seem all 10016 // that unreasonable. 10017 if (signatureCheckPs.sharedUser != null) { 10018 if (compareSignatures( 10019 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10020 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10021 throw new PackageManagerException( 10022 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10023 "Signature mismatch for shared user: " 10024 + pkgSetting.sharedUser); 10025 } 10026 } 10027 // File a report about this. 10028 String msg = "System package " + pkg.packageName 10029 + " signature changed; retaining data."; 10030 reportSettingsProblem(Log.WARN, msg); 10031 } 10032 } 10033 10034 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10035 // This package wants to adopt ownership of permissions from 10036 // another package. 10037 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10038 final String origName = pkg.mAdoptPermissions.get(i); 10039 final PackageSetting orig = mSettings.getPackageLPr(origName); 10040 if (orig != null) { 10041 if (verifyPackageUpdateLPr(orig, pkg)) { 10042 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10043 + pkg.packageName); 10044 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10045 } 10046 } 10047 } 10048 } 10049 10050 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10051 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10052 final String codePathString = changedAbiCodePath.get(i); 10053 try { 10054 mInstaller.rmdex(codePathString, 10055 getDexCodeInstructionSet(getPreferredInstructionSet())); 10056 } catch (InstallerException ignored) { 10057 } 10058 } 10059 } 10060 10061 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10062 if (oldPkgSetting != null) { 10063 synchronized (mPackages) { 10064 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10065 } 10066 } 10067 } else { 10068 final int userId = user == null ? 0 : user.getIdentifier(); 10069 // Modify state for the given package setting 10070 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10071 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10072 if (pkgSetting.getInstantApp(userId)) { 10073 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10074 } 10075 } 10076 } 10077 10078 /** 10079 * Returns the "real" name of the package. 10080 * <p>This may differ from the package's actual name if the application has already 10081 * been installed under one of this package's original names. 10082 */ 10083 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10084 @Nullable String renamedPkgName) { 10085 if (isPackageRenamed(pkg, renamedPkgName)) { 10086 return pkg.mRealPackage; 10087 } 10088 return null; 10089 } 10090 10091 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10092 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10093 @Nullable String renamedPkgName) { 10094 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10095 } 10096 10097 /** 10098 * Returns the original package setting. 10099 * <p>A package can migrate its name during an update. In this scenario, a package 10100 * designates a set of names that it considers as one of its original names. 10101 * <p>An original package must be signed identically and it must have the same 10102 * shared user [if any]. 10103 */ 10104 @GuardedBy("mPackages") 10105 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10106 @Nullable String renamedPkgName) { 10107 if (!isPackageRenamed(pkg, renamedPkgName)) { 10108 return null; 10109 } 10110 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10111 final PackageSetting originalPs = 10112 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10113 if (originalPs != null) { 10114 // the package is already installed under its original name... 10115 // but, should we use it? 10116 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10117 // the new package is incompatible with the original 10118 continue; 10119 } else if (originalPs.sharedUser != null) { 10120 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10121 // the shared user id is incompatible with the original 10122 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10123 + " to " + pkg.packageName + ": old uid " 10124 + originalPs.sharedUser.name 10125 + " differs from " + pkg.mSharedUserId); 10126 continue; 10127 } 10128 // TODO: Add case when shared user id is added [b/28144775] 10129 } else { 10130 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10131 + pkg.packageName + " to old name " + originalPs.name); 10132 } 10133 return originalPs; 10134 } 10135 } 10136 return null; 10137 } 10138 10139 /** 10140 * Renames the package if it was installed under a different name. 10141 * <p>When we've already installed the package under an original name, update 10142 * the new package so we can continue to have the old name. 10143 */ 10144 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10145 @NonNull String renamedPackageName) { 10146 if (pkg.mOriginalPackages == null 10147 || !pkg.mOriginalPackages.contains(renamedPackageName) 10148 || pkg.packageName.equals(renamedPackageName)) { 10149 return; 10150 } 10151 pkg.setPackageName(renamedPackageName); 10152 } 10153 10154 /** 10155 * Just scans the package without any side effects. 10156 * <p>Not entirely true at the moment. There is still one side effect -- this 10157 * method potentially modifies a live {@link PackageSetting} object representing 10158 * the package being scanned. This will be resolved in the future. 10159 * 10160 * @param request Information about the package to be scanned 10161 * @param isUnderFactoryTest Whether or not the device is under factory test 10162 * @param currentTime The current time, in millis 10163 * @return The results of the scan 10164 */ 10165 @GuardedBy("mInstallLock") 10166 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10167 boolean isUnderFactoryTest, long currentTime) 10168 throws PackageManagerException { 10169 final PackageParser.Package pkg = request.pkg; 10170 PackageSetting pkgSetting = request.pkgSetting; 10171 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10172 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10173 final @ParseFlags int parseFlags = request.parseFlags; 10174 final @ScanFlags int scanFlags = request.scanFlags; 10175 final String realPkgName = request.realPkgName; 10176 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10177 final UserHandle user = request.user; 10178 final boolean isPlatformPackage = request.isPlatformPackage; 10179 10180 List<String> changedAbiCodePath = null; 10181 10182 if (DEBUG_PACKAGE_SCANNING) { 10183 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10184 Log.d(TAG, "Scanning package " + pkg.packageName); 10185 } 10186 10187 if (Build.IS_DEBUGGABLE && 10188 pkg.isPrivileged() && 10189 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10190 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10191 } 10192 10193 // Initialize package source and resource directories 10194 final File scanFile = new File(pkg.codePath); 10195 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10196 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10197 10198 // We keep references to the derived CPU Abis from settings in oder to reuse 10199 // them in the case where we're not upgrading or booting for the first time. 10200 String primaryCpuAbiFromSettings = null; 10201 String secondaryCpuAbiFromSettings = null; 10202 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10203 10204 if (!needToDeriveAbi) { 10205 if (pkgSetting != null) { 10206 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10207 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10208 } else { 10209 // Re-scanning a system package after uninstalling updates; need to derive ABI 10210 needToDeriveAbi = true; 10211 } 10212 } 10213 10214 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10215 PackageManagerService.reportSettingsProblem(Log.WARN, 10216 "Package " + pkg.packageName + " shared user changed from " 10217 + (pkgSetting.sharedUser != null 10218 ? pkgSetting.sharedUser.name : "<nothing>") 10219 + " to " 10220 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10221 + "; replacing with new"); 10222 pkgSetting = null; 10223 } 10224 10225 String[] usesStaticLibraries = null; 10226 if (pkg.usesStaticLibraries != null) { 10227 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10228 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10229 } 10230 final boolean createNewPackage = (pkgSetting == null); 10231 if (createNewPackage) { 10232 final String parentPackageName = (pkg.parentPackage != null) 10233 ? pkg.parentPackage.packageName : null; 10234 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10235 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10236 // REMOVE SharedUserSetting from method; update in a separate call 10237 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10238 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10239 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10240 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10241 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10242 user, true /*allowInstall*/, instantApp, virtualPreload, 10243 parentPackageName, pkg.getChildPackageNames(), 10244 UserManagerService.getInstance(), usesStaticLibraries, 10245 pkg.usesStaticLibrariesVersions); 10246 } else { 10247 // REMOVE SharedUserSetting from method; update in a separate call. 10248 // 10249 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10250 // secondaryCpuAbi are not known at this point so we always update them 10251 // to null here, only to reset them at a later point. 10252 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10253 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10254 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10255 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10256 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10257 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10258 } 10259 if (createNewPackage && originalPkgSetting != null) { 10260 // This is the initial transition from the original package, so, 10261 // fix up the new package's name now. We must do this after looking 10262 // up the package under its new name, so getPackageLP takes care of 10263 // fiddling things correctly. 10264 pkg.setPackageName(originalPkgSetting.name); 10265 10266 // File a report about this. 10267 String msg = "New package " + pkgSetting.realName 10268 + " renamed to replace old package " + pkgSetting.name; 10269 reportSettingsProblem(Log.WARN, msg); 10270 } 10271 10272 if (disabledPkgSetting != null) { 10273 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10274 } 10275 10276 SELinuxMMAC.assignSeInfoValue(pkg); 10277 10278 pkg.mExtras = pkgSetting; 10279 pkg.applicationInfo.processName = fixProcessName( 10280 pkg.applicationInfo.packageName, 10281 pkg.applicationInfo.processName); 10282 10283 if (!isPlatformPackage) { 10284 // Get all of our default paths setup 10285 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10286 } 10287 10288 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10289 10290 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10291 if (needToDeriveAbi) { 10292 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10293 final boolean extractNativeLibs = !pkg.isLibrary(); 10294 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10295 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10296 10297 // Some system apps still use directory structure for native libraries 10298 // in which case we might end up not detecting abi solely based on apk 10299 // structure. Try to detect abi based on directory structure. 10300 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10301 pkg.applicationInfo.primaryCpuAbi == null) { 10302 setBundledAppAbisAndRoots(pkg, pkgSetting); 10303 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10304 } 10305 } else { 10306 // This is not a first boot or an upgrade, don't bother deriving the 10307 // ABI during the scan. Instead, trust the value that was stored in the 10308 // package setting. 10309 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10310 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10311 10312 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10313 10314 if (DEBUG_ABI_SELECTION) { 10315 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10316 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10317 pkg.applicationInfo.secondaryCpuAbi); 10318 } 10319 } 10320 } else { 10321 if ((scanFlags & SCAN_MOVE) != 0) { 10322 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10323 // but we already have this packages package info in the PackageSetting. We just 10324 // use that and derive the native library path based on the new codepath. 10325 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10326 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10327 } 10328 10329 // Set native library paths again. For moves, the path will be updated based on the 10330 // ABIs we've determined above. For non-moves, the path will be updated based on the 10331 // ABIs we determined during compilation, but the path will depend on the final 10332 // package path (after the rename away from the stage path). 10333 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10334 } 10335 10336 // This is a special case for the "system" package, where the ABI is 10337 // dictated by the zygote configuration (and init.rc). We should keep track 10338 // of this ABI so that we can deal with "normal" applications that run under 10339 // the same UID correctly. 10340 if (isPlatformPackage) { 10341 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10342 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10343 } 10344 10345 // If there's a mismatch between the abi-override in the package setting 10346 // and the abiOverride specified for the install. Warn about this because we 10347 // would've already compiled the app without taking the package setting into 10348 // account. 10349 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10350 if (cpuAbiOverride == null && pkg.packageName != null) { 10351 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10352 " for package " + pkg.packageName); 10353 } 10354 } 10355 10356 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10357 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10358 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10359 10360 // Copy the derived override back to the parsed package, so that we can 10361 // update the package settings accordingly. 10362 pkg.cpuAbiOverride = cpuAbiOverride; 10363 10364 if (DEBUG_ABI_SELECTION) { 10365 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10366 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10367 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10368 } 10369 10370 // Push the derived path down into PackageSettings so we know what to 10371 // clean up at uninstall time. 10372 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10373 10374 if (DEBUG_ABI_SELECTION) { 10375 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10376 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10377 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10378 } 10379 10380 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10381 // We don't do this here during boot because we can do it all 10382 // at once after scanning all existing packages. 10383 // 10384 // We also do this *before* we perform dexopt on this package, so that 10385 // we can avoid redundant dexopts, and also to make sure we've got the 10386 // code and package path correct. 10387 changedAbiCodePath = 10388 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10389 } 10390 10391 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10392 android.Manifest.permission.FACTORY_TEST)) { 10393 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10394 } 10395 10396 if (isSystemApp(pkg)) { 10397 pkgSetting.isOrphaned = true; 10398 } 10399 10400 // Take care of first install / last update times. 10401 final long scanFileTime = getLastModifiedTime(pkg); 10402 if (currentTime != 0) { 10403 if (pkgSetting.firstInstallTime == 0) { 10404 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10405 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10406 pkgSetting.lastUpdateTime = currentTime; 10407 } 10408 } else if (pkgSetting.firstInstallTime == 0) { 10409 // We need *something*. Take time time stamp of the file. 10410 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10411 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10412 if (scanFileTime != pkgSetting.timeStamp) { 10413 // A package on the system image has changed; consider this 10414 // to be an update. 10415 pkgSetting.lastUpdateTime = scanFileTime; 10416 } 10417 } 10418 pkgSetting.setTimeStamp(scanFileTime); 10419 10420 pkgSetting.pkg = pkg; 10421 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10422 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10423 pkgSetting.versionCode = pkg.getLongVersionCode(); 10424 } 10425 // Update volume if needed 10426 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10427 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10428 Slog.i(PackageManagerService.TAG, 10429 "Update" + (pkgSetting.isSystem() ? " system" : "") 10430 + " package " + pkg.packageName 10431 + " volume from " + pkgSetting.volumeUuid 10432 + " to " + volumeUuid); 10433 pkgSetting.volumeUuid = volumeUuid; 10434 } 10435 10436 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10437 } 10438 10439 /** 10440 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10441 */ 10442 private static boolean apkHasCode(String fileName) { 10443 StrictJarFile jarFile = null; 10444 try { 10445 jarFile = new StrictJarFile(fileName, 10446 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10447 return jarFile.findEntry("classes.dex") != null; 10448 } catch (IOException ignore) { 10449 } finally { 10450 try { 10451 if (jarFile != null) { 10452 jarFile.close(); 10453 } 10454 } catch (IOException ignore) {} 10455 } 10456 return false; 10457 } 10458 10459 /** 10460 * Enforces code policy for the package. This ensures that if an APK has 10461 * declared hasCode="true" in its manifest that the APK actually contains 10462 * code. 10463 * 10464 * @throws PackageManagerException If bytecode could not be found when it should exist 10465 */ 10466 private static void assertCodePolicy(PackageParser.Package pkg) 10467 throws PackageManagerException { 10468 final boolean shouldHaveCode = 10469 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10470 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10471 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10472 "Package " + pkg.baseCodePath + " code is missing"); 10473 } 10474 10475 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10476 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10477 final boolean splitShouldHaveCode = 10478 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10479 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10480 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10481 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10482 } 10483 } 10484 } 10485 } 10486 10487 /** 10488 * Applies policy to the parsed package based upon the given policy flags. 10489 * Ensures the package is in a good state. 10490 * <p> 10491 * Implementation detail: This method must NOT have any side effect. It would 10492 * ideally be static, but, it requires locks to read system state. 10493 */ 10494 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10495 final @ScanFlags int scanFlags) { 10496 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10497 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10498 if (pkg.applicationInfo.isDirectBootAware()) { 10499 // we're direct boot aware; set for all components 10500 for (PackageParser.Service s : pkg.services) { 10501 s.info.encryptionAware = s.info.directBootAware = true; 10502 } 10503 for (PackageParser.Provider p : pkg.providers) { 10504 p.info.encryptionAware = p.info.directBootAware = true; 10505 } 10506 for (PackageParser.Activity a : pkg.activities) { 10507 a.info.encryptionAware = a.info.directBootAware = true; 10508 } 10509 for (PackageParser.Activity r : pkg.receivers) { 10510 r.info.encryptionAware = r.info.directBootAware = true; 10511 } 10512 } 10513 if (compressedFileExists(pkg.codePath)) { 10514 pkg.isStub = true; 10515 } 10516 } else { 10517 // non system apps can't be flagged as core 10518 pkg.coreApp = false; 10519 // clear flags not applicable to regular apps 10520 pkg.applicationInfo.flags &= 10521 ~ApplicationInfo.FLAG_PERSISTENT; 10522 pkg.applicationInfo.privateFlags &= 10523 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10524 pkg.applicationInfo.privateFlags &= 10525 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10526 // clear protected broadcasts 10527 pkg.protectedBroadcasts = null; 10528 // cap permission priorities 10529 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10530 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10531 pkg.permissionGroups.get(i).info.priority = 0; 10532 } 10533 } 10534 } 10535 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10536 // ignore export request for single user receivers 10537 if (pkg.receivers != null) { 10538 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10539 final PackageParser.Activity receiver = pkg.receivers.get(i); 10540 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10541 receiver.info.exported = false; 10542 } 10543 } 10544 } 10545 // ignore export request for single user services 10546 if (pkg.services != null) { 10547 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10548 final PackageParser.Service service = pkg.services.get(i); 10549 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10550 service.info.exported = false; 10551 } 10552 } 10553 } 10554 // ignore export request for single user providers 10555 if (pkg.providers != null) { 10556 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10557 final PackageParser.Provider provider = pkg.providers.get(i); 10558 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10559 provider.info.exported = false; 10560 } 10561 } 10562 } 10563 } 10564 pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0; 10565 10566 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10567 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10568 } 10569 10570 if ((scanFlags & SCAN_AS_OEM) != 0) { 10571 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10572 } 10573 10574 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10575 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10576 } 10577 10578 if (!isSystemApp(pkg)) { 10579 // Only system apps can use these features. 10580 pkg.mOriginalPackages = null; 10581 pkg.mRealPackage = null; 10582 pkg.mAdoptPermissions = null; 10583 } 10584 } 10585 10586 /** 10587 * Asserts the parsed package is valid according to the given policy. If the 10588 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10589 * <p> 10590 * Implementation detail: This method must NOT have any side effects. It would 10591 * ideally be static, but, it requires locks to read system state. 10592 * 10593 * @throws PackageManagerException If the package fails any of the validation checks 10594 */ 10595 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10596 final @ScanFlags int scanFlags) 10597 throws PackageManagerException { 10598 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10599 assertCodePolicy(pkg); 10600 } 10601 10602 if (pkg.applicationInfo.getCodePath() == null || 10603 pkg.applicationInfo.getResourcePath() == null) { 10604 // Bail out. The resource and code paths haven't been set. 10605 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10606 "Code and resource paths haven't been set correctly"); 10607 } 10608 10609 // Make sure we're not adding any bogus keyset info 10610 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10611 ksms.assertScannedPackageValid(pkg); 10612 10613 synchronized (mPackages) { 10614 // The special "android" package can only be defined once 10615 if (pkg.packageName.equals("android")) { 10616 if (mAndroidApplication != null) { 10617 Slog.w(TAG, "*************************************************"); 10618 Slog.w(TAG, "Core android package being redefined. Skipping."); 10619 Slog.w(TAG, " codePath=" + pkg.codePath); 10620 Slog.w(TAG, "*************************************************"); 10621 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10622 "Core android package being redefined. Skipping."); 10623 } 10624 } 10625 10626 // A package name must be unique; don't allow duplicates 10627 if (mPackages.containsKey(pkg.packageName)) { 10628 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10629 "Application package " + pkg.packageName 10630 + " already installed. Skipping duplicate."); 10631 } 10632 10633 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10634 // Static libs have a synthetic package name containing the version 10635 // but we still want the base name to be unique. 10636 if (mPackages.containsKey(pkg.manifestPackageName)) { 10637 throw new PackageManagerException( 10638 "Duplicate static shared lib provider package"); 10639 } 10640 10641 // Static shared libraries should have at least O target SDK 10642 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10643 throw new PackageManagerException( 10644 "Packages declaring static-shared libs must target O SDK or higher"); 10645 } 10646 10647 // Package declaring static a shared lib cannot be instant apps 10648 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10649 throw new PackageManagerException( 10650 "Packages declaring static-shared libs cannot be instant apps"); 10651 } 10652 10653 // Package declaring static a shared lib cannot be renamed since the package 10654 // name is synthetic and apps can't code around package manager internals. 10655 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10656 throw new PackageManagerException( 10657 "Packages declaring static-shared libs cannot be renamed"); 10658 } 10659 10660 // Package declaring static a shared lib cannot declare child packages 10661 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10662 throw new PackageManagerException( 10663 "Packages declaring static-shared libs cannot have child packages"); 10664 } 10665 10666 // Package declaring static a shared lib cannot declare dynamic libs 10667 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10668 throw new PackageManagerException( 10669 "Packages declaring static-shared libs cannot declare dynamic libs"); 10670 } 10671 10672 // Package declaring static a shared lib cannot declare shared users 10673 if (pkg.mSharedUserId != null) { 10674 throw new PackageManagerException( 10675 "Packages declaring static-shared libs cannot declare shared users"); 10676 } 10677 10678 // Static shared libs cannot declare activities 10679 if (!pkg.activities.isEmpty()) { 10680 throw new PackageManagerException( 10681 "Static shared libs cannot declare activities"); 10682 } 10683 10684 // Static shared libs cannot declare services 10685 if (!pkg.services.isEmpty()) { 10686 throw new PackageManagerException( 10687 "Static shared libs cannot declare services"); 10688 } 10689 10690 // Static shared libs cannot declare providers 10691 if (!pkg.providers.isEmpty()) { 10692 throw new PackageManagerException( 10693 "Static shared libs cannot declare content providers"); 10694 } 10695 10696 // Static shared libs cannot declare receivers 10697 if (!pkg.receivers.isEmpty()) { 10698 throw new PackageManagerException( 10699 "Static shared libs cannot declare broadcast receivers"); 10700 } 10701 10702 // Static shared libs cannot declare permission groups 10703 if (!pkg.permissionGroups.isEmpty()) { 10704 throw new PackageManagerException( 10705 "Static shared libs cannot declare permission groups"); 10706 } 10707 10708 // Static shared libs cannot declare permissions 10709 if (!pkg.permissions.isEmpty()) { 10710 throw new PackageManagerException( 10711 "Static shared libs cannot declare permissions"); 10712 } 10713 10714 // Static shared libs cannot declare protected broadcasts 10715 if (pkg.protectedBroadcasts != null) { 10716 throw new PackageManagerException( 10717 "Static shared libs cannot declare protected broadcasts"); 10718 } 10719 10720 // Static shared libs cannot be overlay targets 10721 if (pkg.mOverlayTarget != null) { 10722 throw new PackageManagerException( 10723 "Static shared libs cannot be overlay targets"); 10724 } 10725 10726 // The version codes must be ordered as lib versions 10727 long minVersionCode = Long.MIN_VALUE; 10728 long maxVersionCode = Long.MAX_VALUE; 10729 10730 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10731 pkg.staticSharedLibName); 10732 if (versionedLib != null) { 10733 final int versionCount = versionedLib.size(); 10734 for (int i = 0; i < versionCount; i++) { 10735 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10736 final long libVersionCode = libInfo.getDeclaringPackage() 10737 .getLongVersionCode(); 10738 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10739 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10740 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10741 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10742 } else { 10743 minVersionCode = maxVersionCode = libVersionCode; 10744 break; 10745 } 10746 } 10747 } 10748 if (pkg.getLongVersionCode() < minVersionCode 10749 || pkg.getLongVersionCode() > maxVersionCode) { 10750 throw new PackageManagerException("Static shared" 10751 + " lib version codes must be ordered as lib versions"); 10752 } 10753 } 10754 10755 // Only privileged apps and updated privileged apps can add child packages. 10756 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10757 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10758 throw new PackageManagerException("Only privileged apps can add child " 10759 + "packages. Ignoring package " + pkg.packageName); 10760 } 10761 final int childCount = pkg.childPackages.size(); 10762 for (int i = 0; i < childCount; i++) { 10763 PackageParser.Package childPkg = pkg.childPackages.get(i); 10764 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10765 childPkg.packageName)) { 10766 throw new PackageManagerException("Can't override child of " 10767 + "another disabled app. Ignoring package " + pkg.packageName); 10768 } 10769 } 10770 } 10771 10772 // If we're only installing presumed-existing packages, require that the 10773 // scanned APK is both already known and at the path previously established 10774 // for it. Previously unknown packages we pick up normally, but if we have an 10775 // a priori expectation about this package's install presence, enforce it. 10776 // With a singular exception for new system packages. When an OTA contains 10777 // a new system package, we allow the codepath to change from a system location 10778 // to the user-installed location. If we don't allow this change, any newer, 10779 // user-installed version of the application will be ignored. 10780 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10781 if (mExpectingBetter.containsKey(pkg.packageName)) { 10782 logCriticalInfo(Log.WARN, 10783 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10784 } else { 10785 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10786 if (known != null) { 10787 if (DEBUG_PACKAGE_SCANNING) { 10788 Log.d(TAG, "Examining " + pkg.codePath 10789 + " and requiring known paths " + known.codePathString 10790 + " & " + known.resourcePathString); 10791 } 10792 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10793 || !pkg.applicationInfo.getResourcePath().equals( 10794 known.resourcePathString)) { 10795 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10796 "Application package " + pkg.packageName 10797 + " found at " + pkg.applicationInfo.getCodePath() 10798 + " but expected at " + known.codePathString 10799 + "; ignoring."); 10800 } 10801 } else { 10802 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10803 "Application package " + pkg.packageName 10804 + " not found; ignoring."); 10805 } 10806 } 10807 } 10808 10809 // Verify that this new package doesn't have any content providers 10810 // that conflict with existing packages. Only do this if the 10811 // package isn't already installed, since we don't want to break 10812 // things that are installed. 10813 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10814 final int N = pkg.providers.size(); 10815 int i; 10816 for (i=0; i<N; i++) { 10817 PackageParser.Provider p = pkg.providers.get(i); 10818 if (p.info.authority != null) { 10819 String names[] = p.info.authority.split(";"); 10820 for (int j = 0; j < names.length; j++) { 10821 if (mProvidersByAuthority.containsKey(names[j])) { 10822 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10823 final String otherPackageName = 10824 ((other != null && other.getComponentName() != null) ? 10825 other.getComponentName().getPackageName() : "?"); 10826 throw new PackageManagerException( 10827 INSTALL_FAILED_CONFLICTING_PROVIDER, 10828 "Can't install because provider name " + names[j] 10829 + " (in package " + pkg.applicationInfo.packageName 10830 + ") is already used by " + otherPackageName); 10831 } 10832 } 10833 } 10834 } 10835 } 10836 10837 // Verify that packages sharing a user with a privileged app are marked as privileged. 10838 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 10839 SharedUserSetting sharedUserSetting = null; 10840 try { 10841 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10842 } catch (PackageManagerException ignore) {} 10843 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10844 // Exempt SharedUsers signed with the platform key. 10845 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10846 if ((platformPkgSetting.signatures.mSigningDetails 10847 != PackageParser.SigningDetails.UNKNOWN) 10848 && (compareSignatures( 10849 platformPkgSetting.signatures.mSigningDetails.signatures, 10850 pkg.mSigningDetails.signatures) 10851 != PackageManager.SIGNATURE_MATCH)) { 10852 throw new PackageManagerException("Apps that share a user with a " + 10853 "privileged app must themselves be marked as privileged. " + 10854 pkg.packageName + " shares privileged user " + 10855 pkg.mSharedUserId + "."); 10856 } 10857 } 10858 } 10859 } 10860 } 10861 10862 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 10863 int type, String declaringPackageName, long declaringVersionCode) { 10864 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10865 if (versionedLib == null) { 10866 versionedLib = new LongSparseArray<>(); 10867 mSharedLibraries.put(name, versionedLib); 10868 if (type == SharedLibraryInfo.TYPE_STATIC) { 10869 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10870 } 10871 } else if (versionedLib.indexOfKey(version) >= 0) { 10872 return false; 10873 } 10874 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10875 version, type, declaringPackageName, declaringVersionCode); 10876 versionedLib.put(version, libEntry); 10877 return true; 10878 } 10879 10880 private boolean removeSharedLibraryLPw(String name, long version) { 10881 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10882 if (versionedLib == null) { 10883 return false; 10884 } 10885 final int libIdx = versionedLib.indexOfKey(version); 10886 if (libIdx < 0) { 10887 return false; 10888 } 10889 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10890 versionedLib.remove(version); 10891 if (versionedLib.size() <= 0) { 10892 mSharedLibraries.remove(name); 10893 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10894 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10895 .getPackageName()); 10896 } 10897 } 10898 return true; 10899 } 10900 10901 /** 10902 * Adds a scanned package to the system. When this method is finished, the package will 10903 * be available for query, resolution, etc... 10904 */ 10905 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10906 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 10907 final String pkgName = pkg.packageName; 10908 if (mCustomResolverComponentName != null && 10909 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10910 setUpCustomResolverActivity(pkg); 10911 } 10912 10913 if (pkg.packageName.equals("android")) { 10914 synchronized (mPackages) { 10915 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10916 // Set up information for our fall-back user intent resolution activity. 10917 mPlatformPackage = pkg; 10918 pkg.mVersionCode = mSdkVersion; 10919 pkg.mVersionCodeMajor = 0; 10920 mAndroidApplication = pkg.applicationInfo; 10921 if (!mResolverReplaced) { 10922 mResolveActivity.applicationInfo = mAndroidApplication; 10923 mResolveActivity.name = ResolverActivity.class.getName(); 10924 mResolveActivity.packageName = mAndroidApplication.packageName; 10925 mResolveActivity.processName = "system:ui"; 10926 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10927 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10928 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10929 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10930 mResolveActivity.exported = true; 10931 mResolveActivity.enabled = true; 10932 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10933 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10934 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10935 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10936 | ActivityInfo.CONFIG_ORIENTATION 10937 | ActivityInfo.CONFIG_KEYBOARD 10938 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10939 mResolveInfo.activityInfo = mResolveActivity; 10940 mResolveInfo.priority = 0; 10941 mResolveInfo.preferredOrder = 0; 10942 mResolveInfo.match = 0; 10943 mResolveComponentName = new ComponentName( 10944 mAndroidApplication.packageName, mResolveActivity.name); 10945 } 10946 } 10947 } 10948 } 10949 10950 ArrayList<PackageParser.Package> clientLibPkgs = null; 10951 // writer 10952 synchronized (mPackages) { 10953 boolean hasStaticSharedLibs = false; 10954 10955 // Any app can add new static shared libraries 10956 if (pkg.staticSharedLibName != null) { 10957 // Static shared libs don't allow renaming as they have synthetic package 10958 // names to allow install of multiple versions, so use name from manifest. 10959 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10960 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10961 pkg.manifestPackageName, pkg.getLongVersionCode())) { 10962 hasStaticSharedLibs = true; 10963 } else { 10964 Slog.w(TAG, "Package " + pkg.packageName + " library " 10965 + pkg.staticSharedLibName + " already exists; skipping"); 10966 } 10967 // Static shared libs cannot be updated once installed since they 10968 // use synthetic package name which includes the version code, so 10969 // not need to update other packages's shared lib dependencies. 10970 } 10971 10972 if (!hasStaticSharedLibs 10973 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10974 // Only system apps can add new dynamic shared libraries. 10975 if (pkg.libraryNames != null) { 10976 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10977 String name = pkg.libraryNames.get(i); 10978 boolean allowed = false; 10979 if (pkg.isUpdatedSystemApp()) { 10980 // New library entries can only be added through the 10981 // system image. This is important to get rid of a lot 10982 // of nasty edge cases: for example if we allowed a non- 10983 // system update of the app to add a library, then uninstalling 10984 // the update would make the library go away, and assumptions 10985 // we made such as through app install filtering would now 10986 // have allowed apps on the device which aren't compatible 10987 // with it. Better to just have the restriction here, be 10988 // conservative, and create many fewer cases that can negatively 10989 // impact the user experience. 10990 final PackageSetting sysPs = mSettings 10991 .getDisabledSystemPkgLPr(pkg.packageName); 10992 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10993 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10994 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10995 allowed = true; 10996 break; 10997 } 10998 } 10999 } 11000 } else { 11001 allowed = true; 11002 } 11003 if (allowed) { 11004 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11005 SharedLibraryInfo.VERSION_UNDEFINED, 11006 SharedLibraryInfo.TYPE_DYNAMIC, 11007 pkg.packageName, pkg.getLongVersionCode())) { 11008 Slog.w(TAG, "Package " + pkg.packageName + " library " 11009 + name + " already exists; skipping"); 11010 } 11011 } else { 11012 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11013 + name + " that is not declared on system image; skipping"); 11014 } 11015 } 11016 11017 if ((scanFlags & SCAN_BOOTING) == 0) { 11018 // If we are not booting, we need to update any applications 11019 // that are clients of our shared library. If we are booting, 11020 // this will all be done once the scan is complete. 11021 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11022 } 11023 } 11024 } 11025 } 11026 11027 if ((scanFlags & SCAN_BOOTING) != 0) { 11028 // No apps can run during boot scan, so they don't need to be frozen 11029 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11030 // Caller asked to not kill app, so it's probably not frozen 11031 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11032 // Caller asked us to ignore frozen check for some reason; they 11033 // probably didn't know the package name 11034 } else { 11035 // We're doing major surgery on this package, so it better be frozen 11036 // right now to keep it from launching 11037 checkPackageFrozen(pkgName); 11038 } 11039 11040 // Also need to kill any apps that are dependent on the library. 11041 if (clientLibPkgs != null) { 11042 for (int i=0; i<clientLibPkgs.size(); i++) { 11043 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11044 killApplication(clientPkg.applicationInfo.packageName, 11045 clientPkg.applicationInfo.uid, "update lib"); 11046 } 11047 } 11048 11049 // writer 11050 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11051 11052 synchronized (mPackages) { 11053 // We don't expect installation to fail beyond this point 11054 11055 // Add the new setting to mSettings 11056 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11057 // Add the new setting to mPackages 11058 mPackages.put(pkg.applicationInfo.packageName, pkg); 11059 // Make sure we don't accidentally delete its data. 11060 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11061 while (iter.hasNext()) { 11062 PackageCleanItem item = iter.next(); 11063 if (pkgName.equals(item.packageName)) { 11064 iter.remove(); 11065 } 11066 } 11067 11068 // Add the package's KeySets to the global KeySetManagerService 11069 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11070 ksms.addScannedPackageLPw(pkg); 11071 11072 int N = pkg.providers.size(); 11073 StringBuilder r = null; 11074 int i; 11075 for (i=0; i<N; i++) { 11076 PackageParser.Provider p = pkg.providers.get(i); 11077 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11078 p.info.processName); 11079 mProviders.addProvider(p); 11080 p.syncable = p.info.isSyncable; 11081 if (p.info.authority != null) { 11082 String names[] = p.info.authority.split(";"); 11083 p.info.authority = null; 11084 for (int j = 0; j < names.length; j++) { 11085 if (j == 1 && p.syncable) { 11086 // We only want the first authority for a provider to possibly be 11087 // syncable, so if we already added this provider using a different 11088 // authority clear the syncable flag. We copy the provider before 11089 // changing it because the mProviders object contains a reference 11090 // to a provider that we don't want to change. 11091 // Only do this for the second authority since the resulting provider 11092 // object can be the same for all future authorities for this provider. 11093 p = new PackageParser.Provider(p); 11094 p.syncable = false; 11095 } 11096 if (!mProvidersByAuthority.containsKey(names[j])) { 11097 mProvidersByAuthority.put(names[j], p); 11098 if (p.info.authority == null) { 11099 p.info.authority = names[j]; 11100 } else { 11101 p.info.authority = p.info.authority + ";" + names[j]; 11102 } 11103 if (DEBUG_PACKAGE_SCANNING) { 11104 if (chatty) 11105 Log.d(TAG, "Registered content provider: " + names[j] 11106 + ", className = " + p.info.name + ", isSyncable = " 11107 + p.info.isSyncable); 11108 } 11109 } else { 11110 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11111 Slog.w(TAG, "Skipping provider name " + names[j] + 11112 " (in package " + pkg.applicationInfo.packageName + 11113 "): name already used by " 11114 + ((other != null && other.getComponentName() != null) 11115 ? other.getComponentName().getPackageName() : "?")); 11116 } 11117 } 11118 } 11119 if (chatty) { 11120 if (r == null) { 11121 r = new StringBuilder(256); 11122 } else { 11123 r.append(' '); 11124 } 11125 r.append(p.info.name); 11126 } 11127 } 11128 if (r != null) { 11129 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11130 } 11131 11132 N = pkg.services.size(); 11133 r = null; 11134 for (i=0; i<N; i++) { 11135 PackageParser.Service s = pkg.services.get(i); 11136 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11137 s.info.processName); 11138 mServices.addService(s); 11139 if (chatty) { 11140 if (r == null) { 11141 r = new StringBuilder(256); 11142 } else { 11143 r.append(' '); 11144 } 11145 r.append(s.info.name); 11146 } 11147 } 11148 if (r != null) { 11149 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11150 } 11151 11152 N = pkg.receivers.size(); 11153 r = null; 11154 for (i=0; i<N; i++) { 11155 PackageParser.Activity a = pkg.receivers.get(i); 11156 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11157 a.info.processName); 11158 mReceivers.addActivity(a, "receiver"); 11159 if (chatty) { 11160 if (r == null) { 11161 r = new StringBuilder(256); 11162 } else { 11163 r.append(' '); 11164 } 11165 r.append(a.info.name); 11166 } 11167 } 11168 if (r != null) { 11169 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11170 } 11171 11172 N = pkg.activities.size(); 11173 r = null; 11174 for (i=0; i<N; i++) { 11175 PackageParser.Activity a = pkg.activities.get(i); 11176 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11177 a.info.processName); 11178 mActivities.addActivity(a, "activity"); 11179 if (chatty) { 11180 if (r == null) { 11181 r = new StringBuilder(256); 11182 } else { 11183 r.append(' '); 11184 } 11185 r.append(a.info.name); 11186 } 11187 } 11188 if (r != null) { 11189 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11190 } 11191 11192 // Don't allow ephemeral applications to define new permissions groups. 11193 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11194 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11195 + " ignored: instant apps cannot define new permission groups."); 11196 } else { 11197 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11198 } 11199 11200 // Don't allow ephemeral applications to define new permissions. 11201 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11202 Slog.w(TAG, "Permissions from package " + pkg.packageName 11203 + " ignored: instant apps cannot define new permissions."); 11204 } else { 11205 mPermissionManager.addAllPermissions(pkg, chatty); 11206 } 11207 11208 N = pkg.instrumentation.size(); 11209 r = null; 11210 for (i=0; i<N; i++) { 11211 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11212 a.info.packageName = pkg.applicationInfo.packageName; 11213 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11214 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11215 a.info.splitNames = pkg.splitNames; 11216 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11217 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11218 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11219 a.info.dataDir = pkg.applicationInfo.dataDir; 11220 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11221 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11222 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11223 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11224 mInstrumentation.put(a.getComponentName(), a); 11225 if (chatty) { 11226 if (r == null) { 11227 r = new StringBuilder(256); 11228 } else { 11229 r.append(' '); 11230 } 11231 r.append(a.info.name); 11232 } 11233 } 11234 if (r != null) { 11235 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11236 } 11237 11238 if (pkg.protectedBroadcasts != null) { 11239 N = pkg.protectedBroadcasts.size(); 11240 synchronized (mProtectedBroadcasts) { 11241 for (i = 0; i < N; i++) { 11242 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11243 } 11244 } 11245 } 11246 } 11247 11248 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11249 } 11250 11251 /** 11252 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11253 * is derived purely on the basis of the contents of {@code scanFile} and 11254 * {@code cpuAbiOverride}. 11255 * 11256 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11257 */ 11258 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11259 boolean extractLibs) 11260 throws PackageManagerException { 11261 // Give ourselves some initial paths; we'll come back for another 11262 // pass once we've determined ABI below. 11263 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11264 11265 // We would never need to extract libs for forward-locked and external packages, 11266 // since the container service will do it for us. We shouldn't attempt to 11267 // extract libs from system app when it was not updated. 11268 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11269 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11270 extractLibs = false; 11271 } 11272 11273 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11274 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11275 11276 NativeLibraryHelper.Handle handle = null; 11277 try { 11278 handle = NativeLibraryHelper.Handle.create(pkg); 11279 // TODO(multiArch): This can be null for apps that didn't go through the 11280 // usual installation process. We can calculate it again, like we 11281 // do during install time. 11282 // 11283 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11284 // unnecessary. 11285 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11286 11287 // Null out the abis so that they can be recalculated. 11288 pkg.applicationInfo.primaryCpuAbi = null; 11289 pkg.applicationInfo.secondaryCpuAbi = null; 11290 if (isMultiArch(pkg.applicationInfo)) { 11291 // Warn if we've set an abiOverride for multi-lib packages.. 11292 // By definition, we need to copy both 32 and 64 bit libraries for 11293 // such packages. 11294 if (pkg.cpuAbiOverride != null 11295 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11296 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11297 } 11298 11299 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11300 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11301 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11302 if (extractLibs) { 11303 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11304 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11305 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11306 useIsaSpecificSubdirs); 11307 } else { 11308 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11309 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11310 } 11311 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11312 } 11313 11314 // Shared library native code should be in the APK zip aligned 11315 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11316 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11317 "Shared library native lib extraction not supported"); 11318 } 11319 11320 maybeThrowExceptionForMultiArchCopy( 11321 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11322 11323 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11324 if (extractLibs) { 11325 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11326 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11327 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11328 useIsaSpecificSubdirs); 11329 } else { 11330 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11331 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11332 } 11333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11334 } 11335 11336 maybeThrowExceptionForMultiArchCopy( 11337 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11338 11339 if (abi64 >= 0) { 11340 // Shared library native libs should be in the APK zip aligned 11341 if (extractLibs && pkg.isLibrary()) { 11342 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11343 "Shared library native lib extraction not supported"); 11344 } 11345 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11346 } 11347 11348 if (abi32 >= 0) { 11349 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11350 if (abi64 >= 0) { 11351 if (pkg.use32bitAbi) { 11352 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11353 pkg.applicationInfo.primaryCpuAbi = abi; 11354 } else { 11355 pkg.applicationInfo.secondaryCpuAbi = abi; 11356 } 11357 } else { 11358 pkg.applicationInfo.primaryCpuAbi = abi; 11359 } 11360 } 11361 } else { 11362 String[] abiList = (cpuAbiOverride != null) ? 11363 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11364 11365 // Enable gross and lame hacks for apps that are built with old 11366 // SDK tools. We must scan their APKs for renderscript bitcode and 11367 // not launch them if it's present. Don't bother checking on devices 11368 // that don't have 64 bit support. 11369 boolean needsRenderScriptOverride = false; 11370 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11371 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11372 abiList = Build.SUPPORTED_32_BIT_ABIS; 11373 needsRenderScriptOverride = true; 11374 } 11375 11376 final int copyRet; 11377 if (extractLibs) { 11378 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11379 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11380 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11381 } else { 11382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11383 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11384 } 11385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11386 11387 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11388 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11389 "Error unpackaging native libs for app, errorCode=" + copyRet); 11390 } 11391 11392 if (copyRet >= 0) { 11393 // Shared libraries that have native libs must be multi-architecture 11394 if (pkg.isLibrary()) { 11395 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11396 "Shared library with native libs must be multiarch"); 11397 } 11398 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11399 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11400 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11401 } else if (needsRenderScriptOverride) { 11402 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11403 } 11404 } 11405 } catch (IOException ioe) { 11406 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11407 } finally { 11408 IoUtils.closeQuietly(handle); 11409 } 11410 11411 // Now that we've calculated the ABIs and determined if it's an internal app, 11412 // we will go ahead and populate the nativeLibraryPath. 11413 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11414 } 11415 11416 /** 11417 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11418 * i.e, so that all packages can be run inside a single process if required. 11419 * 11420 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11421 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11422 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11423 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11424 * updating a package that belongs to a shared user. 11425 * 11426 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11427 * adds unnecessary complexity. 11428 */ 11429 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11430 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11431 List<String> changedAbiCodePath = null; 11432 String requiredInstructionSet = null; 11433 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11434 requiredInstructionSet = VMRuntime.getInstructionSet( 11435 scannedPackage.applicationInfo.primaryCpuAbi); 11436 } 11437 11438 PackageSetting requirer = null; 11439 for (PackageSetting ps : packagesForUser) { 11440 // If packagesForUser contains scannedPackage, we skip it. This will happen 11441 // when scannedPackage is an update of an existing package. Without this check, 11442 // we will never be able to change the ABI of any package belonging to a shared 11443 // user, even if it's compatible with other packages. 11444 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11445 if (ps.primaryCpuAbiString == null) { 11446 continue; 11447 } 11448 11449 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11450 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11451 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11452 // this but there's not much we can do. 11453 String errorMessage = "Instruction set mismatch, " 11454 + ((requirer == null) ? "[caller]" : requirer) 11455 + " requires " + requiredInstructionSet + " whereas " + ps 11456 + " requires " + instructionSet; 11457 Slog.w(TAG, errorMessage); 11458 } 11459 11460 if (requiredInstructionSet == null) { 11461 requiredInstructionSet = instructionSet; 11462 requirer = ps; 11463 } 11464 } 11465 } 11466 11467 if (requiredInstructionSet != null) { 11468 String adjustedAbi; 11469 if (requirer != null) { 11470 // requirer != null implies that either scannedPackage was null or that scannedPackage 11471 // did not require an ABI, in which case we have to adjust scannedPackage to match 11472 // the ABI of the set (which is the same as requirer's ABI) 11473 adjustedAbi = requirer.primaryCpuAbiString; 11474 if (scannedPackage != null) { 11475 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11476 } 11477 } else { 11478 // requirer == null implies that we're updating all ABIs in the set to 11479 // match scannedPackage. 11480 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11481 } 11482 11483 for (PackageSetting ps : packagesForUser) { 11484 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11485 if (ps.primaryCpuAbiString != null) { 11486 continue; 11487 } 11488 11489 ps.primaryCpuAbiString = adjustedAbi; 11490 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11491 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11492 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11493 if (DEBUG_ABI_SELECTION) { 11494 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11495 + " (requirer=" 11496 + (requirer != null ? requirer.pkg : "null") 11497 + ", scannedPackage=" 11498 + (scannedPackage != null ? scannedPackage : "null") 11499 + ")"); 11500 } 11501 if (changedAbiCodePath == null) { 11502 changedAbiCodePath = new ArrayList<>(); 11503 } 11504 changedAbiCodePath.add(ps.codePathString); 11505 } 11506 } 11507 } 11508 } 11509 return changedAbiCodePath; 11510 } 11511 11512 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11513 synchronized (mPackages) { 11514 mResolverReplaced = true; 11515 // Set up information for custom user intent resolution activity. 11516 mResolveActivity.applicationInfo = pkg.applicationInfo; 11517 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11518 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11519 mResolveActivity.processName = pkg.applicationInfo.packageName; 11520 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11521 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11522 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11523 mResolveActivity.theme = 0; 11524 mResolveActivity.exported = true; 11525 mResolveActivity.enabled = true; 11526 mResolveInfo.activityInfo = mResolveActivity; 11527 mResolveInfo.priority = 0; 11528 mResolveInfo.preferredOrder = 0; 11529 mResolveInfo.match = 0; 11530 mResolveComponentName = mCustomResolverComponentName; 11531 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11532 mResolveComponentName); 11533 } 11534 } 11535 11536 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11537 if (installerActivity == null) { 11538 if (DEBUG_EPHEMERAL) { 11539 Slog.d(TAG, "Clear ephemeral installer activity"); 11540 } 11541 mInstantAppInstallerActivity = null; 11542 return; 11543 } 11544 11545 if (DEBUG_EPHEMERAL) { 11546 Slog.d(TAG, "Set ephemeral installer activity: " 11547 + installerActivity.getComponentName()); 11548 } 11549 // Set up information for ephemeral installer activity 11550 mInstantAppInstallerActivity = installerActivity; 11551 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11552 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11553 mInstantAppInstallerActivity.exported = true; 11554 mInstantAppInstallerActivity.enabled = true; 11555 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11556 mInstantAppInstallerInfo.priority = 0; 11557 mInstantAppInstallerInfo.preferredOrder = 1; 11558 mInstantAppInstallerInfo.isDefault = true; 11559 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11560 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11561 } 11562 11563 private static String calculateBundledApkRoot(final String codePathString) { 11564 final File codePath = new File(codePathString); 11565 final File codeRoot; 11566 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11567 codeRoot = Environment.getRootDirectory(); 11568 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11569 codeRoot = Environment.getOemDirectory(); 11570 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11571 codeRoot = Environment.getVendorDirectory(); 11572 } else { 11573 // Unrecognized code path; take its top real segment as the apk root: 11574 // e.g. /something/app/blah.apk => /something 11575 try { 11576 File f = codePath.getCanonicalFile(); 11577 File parent = f.getParentFile(); // non-null because codePath is a file 11578 File tmp; 11579 while ((tmp = parent.getParentFile()) != null) { 11580 f = parent; 11581 parent = tmp; 11582 } 11583 codeRoot = f; 11584 Slog.w(TAG, "Unrecognized code path " 11585 + codePath + " - using " + codeRoot); 11586 } catch (IOException e) { 11587 // Can't canonicalize the code path -- shenanigans? 11588 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11589 return Environment.getRootDirectory().getPath(); 11590 } 11591 } 11592 return codeRoot.getPath(); 11593 } 11594 11595 /** 11596 * Derive and set the location of native libraries for the given package, 11597 * which varies depending on where and how the package was installed. 11598 */ 11599 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11600 final ApplicationInfo info = pkg.applicationInfo; 11601 final String codePath = pkg.codePath; 11602 final File codeFile = new File(codePath); 11603 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11604 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11605 11606 info.nativeLibraryRootDir = null; 11607 info.nativeLibraryRootRequiresIsa = false; 11608 info.nativeLibraryDir = null; 11609 info.secondaryNativeLibraryDir = null; 11610 11611 if (isApkFile(codeFile)) { 11612 // Monolithic install 11613 if (bundledApp) { 11614 // If "/system/lib64/apkname" exists, assume that is the per-package 11615 // native library directory to use; otherwise use "/system/lib/apkname". 11616 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11617 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11618 getPrimaryInstructionSet(info)); 11619 11620 // This is a bundled system app so choose the path based on the ABI. 11621 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11622 // is just the default path. 11623 final String apkName = deriveCodePathName(codePath); 11624 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11625 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11626 apkName).getAbsolutePath(); 11627 11628 if (info.secondaryCpuAbi != null) { 11629 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11630 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11631 secondaryLibDir, apkName).getAbsolutePath(); 11632 } 11633 } else if (asecApp) { 11634 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11635 .getAbsolutePath(); 11636 } else { 11637 final String apkName = deriveCodePathName(codePath); 11638 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11639 .getAbsolutePath(); 11640 } 11641 11642 info.nativeLibraryRootRequiresIsa = false; 11643 info.nativeLibraryDir = info.nativeLibraryRootDir; 11644 } else { 11645 // Cluster install 11646 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11647 info.nativeLibraryRootRequiresIsa = true; 11648 11649 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11650 getPrimaryInstructionSet(info)).getAbsolutePath(); 11651 11652 if (info.secondaryCpuAbi != null) { 11653 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11654 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11655 } 11656 } 11657 } 11658 11659 /** 11660 * Calculate the abis and roots for a bundled app. These can uniquely 11661 * be determined from the contents of the system partition, i.e whether 11662 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11663 * of this information, and instead assume that the system was built 11664 * sensibly. 11665 */ 11666 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11667 PackageSetting pkgSetting) { 11668 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11669 11670 // If "/system/lib64/apkname" exists, assume that is the per-package 11671 // native library directory to use; otherwise use "/system/lib/apkname". 11672 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11673 setBundledAppAbi(pkg, apkRoot, apkName); 11674 // pkgSetting might be null during rescan following uninstall of updates 11675 // to a bundled app, so accommodate that possibility. The settings in 11676 // that case will be established later from the parsed package. 11677 // 11678 // If the settings aren't null, sync them up with what we've just derived. 11679 // note that apkRoot isn't stored in the package settings. 11680 if (pkgSetting != null) { 11681 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11682 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11683 } 11684 } 11685 11686 /** 11687 * Deduces the ABI of a bundled app and sets the relevant fields on the 11688 * parsed pkg object. 11689 * 11690 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11691 * under which system libraries are installed. 11692 * @param apkName the name of the installed package. 11693 */ 11694 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11695 final File codeFile = new File(pkg.codePath); 11696 11697 final boolean has64BitLibs; 11698 final boolean has32BitLibs; 11699 if (isApkFile(codeFile)) { 11700 // Monolithic install 11701 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11702 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11703 } else { 11704 // Cluster install 11705 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11706 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11707 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11708 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11709 has64BitLibs = (new File(rootDir, isa)).exists(); 11710 } else { 11711 has64BitLibs = false; 11712 } 11713 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11714 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11715 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11716 has32BitLibs = (new File(rootDir, isa)).exists(); 11717 } else { 11718 has32BitLibs = false; 11719 } 11720 } 11721 11722 if (has64BitLibs && !has32BitLibs) { 11723 // The package has 64 bit libs, but not 32 bit libs. Its primary 11724 // ABI should be 64 bit. We can safely assume here that the bundled 11725 // native libraries correspond to the most preferred ABI in the list. 11726 11727 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11728 pkg.applicationInfo.secondaryCpuAbi = null; 11729 } else if (has32BitLibs && !has64BitLibs) { 11730 // The package has 32 bit libs but not 64 bit libs. Its primary 11731 // ABI should be 32 bit. 11732 11733 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11734 pkg.applicationInfo.secondaryCpuAbi = null; 11735 } else if (has32BitLibs && has64BitLibs) { 11736 // The application has both 64 and 32 bit bundled libraries. We check 11737 // here that the app declares multiArch support, and warn if it doesn't. 11738 // 11739 // We will be lenient here and record both ABIs. The primary will be the 11740 // ABI that's higher on the list, i.e, a device that's configured to prefer 11741 // 64 bit apps will see a 64 bit primary ABI, 11742 11743 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11744 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11745 } 11746 11747 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11748 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11749 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11750 } else { 11751 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11752 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11753 } 11754 } else { 11755 pkg.applicationInfo.primaryCpuAbi = null; 11756 pkg.applicationInfo.secondaryCpuAbi = null; 11757 } 11758 } 11759 11760 private void killApplication(String pkgName, int appId, String reason) { 11761 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11762 } 11763 11764 private void killApplication(String pkgName, int appId, int userId, String reason) { 11765 // Request the ActivityManager to kill the process(only for existing packages) 11766 // so that we do not end up in a confused state while the user is still using the older 11767 // version of the application while the new one gets installed. 11768 final long token = Binder.clearCallingIdentity(); 11769 try { 11770 IActivityManager am = ActivityManager.getService(); 11771 if (am != null) { 11772 try { 11773 am.killApplication(pkgName, appId, userId, reason); 11774 } catch (RemoteException e) { 11775 } 11776 } 11777 } finally { 11778 Binder.restoreCallingIdentity(token); 11779 } 11780 } 11781 11782 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11783 // Remove the parent package setting 11784 PackageSetting ps = (PackageSetting) pkg.mExtras; 11785 if (ps != null) { 11786 removePackageLI(ps, chatty); 11787 } 11788 // Remove the child package setting 11789 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11790 for (int i = 0; i < childCount; i++) { 11791 PackageParser.Package childPkg = pkg.childPackages.get(i); 11792 ps = (PackageSetting) childPkg.mExtras; 11793 if (ps != null) { 11794 removePackageLI(ps, chatty); 11795 } 11796 } 11797 } 11798 11799 void removePackageLI(PackageSetting ps, boolean chatty) { 11800 if (DEBUG_INSTALL) { 11801 if (chatty) 11802 Log.d(TAG, "Removing package " + ps.name); 11803 } 11804 11805 // writer 11806 synchronized (mPackages) { 11807 mPackages.remove(ps.name); 11808 final PackageParser.Package pkg = ps.pkg; 11809 if (pkg != null) { 11810 cleanPackageDataStructuresLILPw(pkg, chatty); 11811 } 11812 } 11813 } 11814 11815 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11816 if (DEBUG_INSTALL) { 11817 if (chatty) 11818 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11819 } 11820 11821 // writer 11822 synchronized (mPackages) { 11823 // Remove the parent package 11824 mPackages.remove(pkg.applicationInfo.packageName); 11825 cleanPackageDataStructuresLILPw(pkg, chatty); 11826 11827 // Remove the child packages 11828 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11829 for (int i = 0; i < childCount; i++) { 11830 PackageParser.Package childPkg = pkg.childPackages.get(i); 11831 mPackages.remove(childPkg.applicationInfo.packageName); 11832 cleanPackageDataStructuresLILPw(childPkg, chatty); 11833 } 11834 } 11835 } 11836 11837 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11838 int N = pkg.providers.size(); 11839 StringBuilder r = null; 11840 int i; 11841 for (i=0; i<N; i++) { 11842 PackageParser.Provider p = pkg.providers.get(i); 11843 mProviders.removeProvider(p); 11844 if (p.info.authority == null) { 11845 11846 /* There was another ContentProvider with this authority when 11847 * this app was installed so this authority is null, 11848 * Ignore it as we don't have to unregister the provider. 11849 */ 11850 continue; 11851 } 11852 String names[] = p.info.authority.split(";"); 11853 for (int j = 0; j < names.length; j++) { 11854 if (mProvidersByAuthority.get(names[j]) == p) { 11855 mProvidersByAuthority.remove(names[j]); 11856 if (DEBUG_REMOVE) { 11857 if (chatty) 11858 Log.d(TAG, "Unregistered content provider: " + names[j] 11859 + ", className = " + p.info.name + ", isSyncable = " 11860 + p.info.isSyncable); 11861 } 11862 } 11863 } 11864 if (DEBUG_REMOVE && chatty) { 11865 if (r == null) { 11866 r = new StringBuilder(256); 11867 } else { 11868 r.append(' '); 11869 } 11870 r.append(p.info.name); 11871 } 11872 } 11873 if (r != null) { 11874 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11875 } 11876 11877 N = pkg.services.size(); 11878 r = null; 11879 for (i=0; i<N; i++) { 11880 PackageParser.Service s = pkg.services.get(i); 11881 mServices.removeService(s); 11882 if (chatty) { 11883 if (r == null) { 11884 r = new StringBuilder(256); 11885 } else { 11886 r.append(' '); 11887 } 11888 r.append(s.info.name); 11889 } 11890 } 11891 if (r != null) { 11892 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11893 } 11894 11895 N = pkg.receivers.size(); 11896 r = null; 11897 for (i=0; i<N; i++) { 11898 PackageParser.Activity a = pkg.receivers.get(i); 11899 mReceivers.removeActivity(a, "receiver"); 11900 if (DEBUG_REMOVE && chatty) { 11901 if (r == null) { 11902 r = new StringBuilder(256); 11903 } else { 11904 r.append(' '); 11905 } 11906 r.append(a.info.name); 11907 } 11908 } 11909 if (r != null) { 11910 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11911 } 11912 11913 N = pkg.activities.size(); 11914 r = null; 11915 for (i=0; i<N; i++) { 11916 PackageParser.Activity a = pkg.activities.get(i); 11917 mActivities.removeActivity(a, "activity"); 11918 if (DEBUG_REMOVE && chatty) { 11919 if (r == null) { 11920 r = new StringBuilder(256); 11921 } else { 11922 r.append(' '); 11923 } 11924 r.append(a.info.name); 11925 } 11926 } 11927 if (r != null) { 11928 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11929 } 11930 11931 mPermissionManager.removeAllPermissions(pkg, chatty); 11932 11933 N = pkg.instrumentation.size(); 11934 r = null; 11935 for (i=0; i<N; i++) { 11936 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11937 mInstrumentation.remove(a.getComponentName()); 11938 if (DEBUG_REMOVE && chatty) { 11939 if (r == null) { 11940 r = new StringBuilder(256); 11941 } else { 11942 r.append(' '); 11943 } 11944 r.append(a.info.name); 11945 } 11946 } 11947 if (r != null) { 11948 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11949 } 11950 11951 r = null; 11952 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11953 // Only system apps can hold shared libraries. 11954 if (pkg.libraryNames != null) { 11955 for (i = 0; i < pkg.libraryNames.size(); i++) { 11956 String name = pkg.libraryNames.get(i); 11957 if (removeSharedLibraryLPw(name, 0)) { 11958 if (DEBUG_REMOVE && chatty) { 11959 if (r == null) { 11960 r = new StringBuilder(256); 11961 } else { 11962 r.append(' '); 11963 } 11964 r.append(name); 11965 } 11966 } 11967 } 11968 } 11969 } 11970 11971 r = null; 11972 11973 // Any package can hold static shared libraries. 11974 if (pkg.staticSharedLibName != null) { 11975 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11976 if (DEBUG_REMOVE && chatty) { 11977 if (r == null) { 11978 r = new StringBuilder(256); 11979 } else { 11980 r.append(' '); 11981 } 11982 r.append(pkg.staticSharedLibName); 11983 } 11984 } 11985 } 11986 11987 if (r != null) { 11988 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11989 } 11990 } 11991 11992 11993 final class ActivityIntentResolver 11994 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11995 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11996 boolean defaultOnly, int userId) { 11997 if (!sUserManager.exists(userId)) return null; 11998 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11999 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12000 } 12001 12002 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12003 int userId) { 12004 if (!sUserManager.exists(userId)) return null; 12005 mFlags = flags; 12006 return super.queryIntent(intent, resolvedType, 12007 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12008 userId); 12009 } 12010 12011 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12012 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12013 if (!sUserManager.exists(userId)) return null; 12014 if (packageActivities == null) { 12015 return null; 12016 } 12017 mFlags = flags; 12018 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12019 final int N = packageActivities.size(); 12020 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12021 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12022 12023 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12024 for (int i = 0; i < N; ++i) { 12025 intentFilters = packageActivities.get(i).intents; 12026 if (intentFilters != null && intentFilters.size() > 0) { 12027 PackageParser.ActivityIntentInfo[] array = 12028 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12029 intentFilters.toArray(array); 12030 listCut.add(array); 12031 } 12032 } 12033 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12034 } 12035 12036 /** 12037 * Finds a privileged activity that matches the specified activity names. 12038 */ 12039 private PackageParser.Activity findMatchingActivity( 12040 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12041 for (PackageParser.Activity sysActivity : activityList) { 12042 if (sysActivity.info.name.equals(activityInfo.name)) { 12043 return sysActivity; 12044 } 12045 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12046 return sysActivity; 12047 } 12048 if (sysActivity.info.targetActivity != null) { 12049 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12050 return sysActivity; 12051 } 12052 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12053 return sysActivity; 12054 } 12055 } 12056 } 12057 return null; 12058 } 12059 12060 public class IterGenerator<E> { 12061 public Iterator<E> generate(ActivityIntentInfo info) { 12062 return null; 12063 } 12064 } 12065 12066 public class ActionIterGenerator extends IterGenerator<String> { 12067 @Override 12068 public Iterator<String> generate(ActivityIntentInfo info) { 12069 return info.actionsIterator(); 12070 } 12071 } 12072 12073 public class CategoriesIterGenerator extends IterGenerator<String> { 12074 @Override 12075 public Iterator<String> generate(ActivityIntentInfo info) { 12076 return info.categoriesIterator(); 12077 } 12078 } 12079 12080 public class SchemesIterGenerator extends IterGenerator<String> { 12081 @Override 12082 public Iterator<String> generate(ActivityIntentInfo info) { 12083 return info.schemesIterator(); 12084 } 12085 } 12086 12087 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12088 @Override 12089 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12090 return info.authoritiesIterator(); 12091 } 12092 } 12093 12094 /** 12095 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12096 * MODIFIED. Do not pass in a list that should not be changed. 12097 */ 12098 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12099 IterGenerator<T> generator, Iterator<T> searchIterator) { 12100 // loop through the set of actions; every one must be found in the intent filter 12101 while (searchIterator.hasNext()) { 12102 // we must have at least one filter in the list to consider a match 12103 if (intentList.size() == 0) { 12104 break; 12105 } 12106 12107 final T searchAction = searchIterator.next(); 12108 12109 // loop through the set of intent filters 12110 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12111 while (intentIter.hasNext()) { 12112 final ActivityIntentInfo intentInfo = intentIter.next(); 12113 boolean selectionFound = false; 12114 12115 // loop through the intent filter's selection criteria; at least one 12116 // of them must match the searched criteria 12117 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12118 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12119 final T intentSelection = intentSelectionIter.next(); 12120 if (intentSelection != null && intentSelection.equals(searchAction)) { 12121 selectionFound = true; 12122 break; 12123 } 12124 } 12125 12126 // the selection criteria wasn't found in this filter's set; this filter 12127 // is not a potential match 12128 if (!selectionFound) { 12129 intentIter.remove(); 12130 } 12131 } 12132 } 12133 } 12134 12135 private boolean isProtectedAction(ActivityIntentInfo filter) { 12136 final Iterator<String> actionsIter = filter.actionsIterator(); 12137 while (actionsIter != null && actionsIter.hasNext()) { 12138 final String filterAction = actionsIter.next(); 12139 if (PROTECTED_ACTIONS.contains(filterAction)) { 12140 return true; 12141 } 12142 } 12143 return false; 12144 } 12145 12146 /** 12147 * Adjusts the priority of the given intent filter according to policy. 12148 * <p> 12149 * <ul> 12150 * <li>The priority for non privileged applications is capped to '0'</li> 12151 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12152 * <li>The priority for unbundled updates to privileged applications is capped to the 12153 * priority defined on the system partition</li> 12154 * </ul> 12155 * <p> 12156 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12157 * allowed to obtain any priority on any action. 12158 */ 12159 private void adjustPriority( 12160 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12161 // nothing to do; priority is fine as-is 12162 if (intent.getPriority() <= 0) { 12163 return; 12164 } 12165 12166 final ActivityInfo activityInfo = intent.activity.info; 12167 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12168 12169 final boolean privilegedApp = 12170 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12171 if (!privilegedApp) { 12172 // non-privileged applications can never define a priority >0 12173 if (DEBUG_FILTERS) { 12174 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12175 + " package: " + applicationInfo.packageName 12176 + " activity: " + intent.activity.className 12177 + " origPrio: " + intent.getPriority()); 12178 } 12179 intent.setPriority(0); 12180 return; 12181 } 12182 12183 if (systemActivities == null) { 12184 // the system package is not disabled; we're parsing the system partition 12185 if (isProtectedAction(intent)) { 12186 if (mDeferProtectedFilters) { 12187 // We can't deal with these just yet. No component should ever obtain a 12188 // >0 priority for a protected actions, with ONE exception -- the setup 12189 // wizard. The setup wizard, however, cannot be known until we're able to 12190 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12191 // until all intent filters have been processed. Chicken, meet egg. 12192 // Let the filter temporarily have a high priority and rectify the 12193 // priorities after all system packages have been scanned. 12194 mProtectedFilters.add(intent); 12195 if (DEBUG_FILTERS) { 12196 Slog.i(TAG, "Protected action; save for later;" 12197 + " package: " + applicationInfo.packageName 12198 + " activity: " + intent.activity.className 12199 + " origPrio: " + intent.getPriority()); 12200 } 12201 return; 12202 } else { 12203 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12204 Slog.i(TAG, "No setup wizard;" 12205 + " All protected intents capped to priority 0"); 12206 } 12207 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12208 if (DEBUG_FILTERS) { 12209 Slog.i(TAG, "Found setup wizard;" 12210 + " allow priority " + intent.getPriority() + ";" 12211 + " package: " + intent.activity.info.packageName 12212 + " activity: " + intent.activity.className 12213 + " priority: " + intent.getPriority()); 12214 } 12215 // setup wizard gets whatever it wants 12216 return; 12217 } 12218 if (DEBUG_FILTERS) { 12219 Slog.i(TAG, "Protected action; cap priority to 0;" 12220 + " package: " + intent.activity.info.packageName 12221 + " activity: " + intent.activity.className 12222 + " origPrio: " + intent.getPriority()); 12223 } 12224 intent.setPriority(0); 12225 return; 12226 } 12227 } 12228 // privileged apps on the system image get whatever priority they request 12229 return; 12230 } 12231 12232 // privileged app unbundled update ... try to find the same activity 12233 final PackageParser.Activity foundActivity = 12234 findMatchingActivity(systemActivities, activityInfo); 12235 if (foundActivity == null) { 12236 // this is a new activity; it cannot obtain >0 priority 12237 if (DEBUG_FILTERS) { 12238 Slog.i(TAG, "New activity; cap priority to 0;" 12239 + " package: " + applicationInfo.packageName 12240 + " activity: " + intent.activity.className 12241 + " origPrio: " + intent.getPriority()); 12242 } 12243 intent.setPriority(0); 12244 return; 12245 } 12246 12247 // found activity, now check for filter equivalence 12248 12249 // a shallow copy is enough; we modify the list, not its contents 12250 final List<ActivityIntentInfo> intentListCopy = 12251 new ArrayList<>(foundActivity.intents); 12252 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12253 12254 // find matching action subsets 12255 final Iterator<String> actionsIterator = intent.actionsIterator(); 12256 if (actionsIterator != null) { 12257 getIntentListSubset( 12258 intentListCopy, new ActionIterGenerator(), actionsIterator); 12259 if (intentListCopy.size() == 0) { 12260 // no more intents to match; we're not equivalent 12261 if (DEBUG_FILTERS) { 12262 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12263 + " package: " + applicationInfo.packageName 12264 + " activity: " + intent.activity.className 12265 + " origPrio: " + intent.getPriority()); 12266 } 12267 intent.setPriority(0); 12268 return; 12269 } 12270 } 12271 12272 // find matching category subsets 12273 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12274 if (categoriesIterator != null) { 12275 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12276 categoriesIterator); 12277 if (intentListCopy.size() == 0) { 12278 // no more intents to match; we're not equivalent 12279 if (DEBUG_FILTERS) { 12280 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12281 + " package: " + applicationInfo.packageName 12282 + " activity: " + intent.activity.className 12283 + " origPrio: " + intent.getPriority()); 12284 } 12285 intent.setPriority(0); 12286 return; 12287 } 12288 } 12289 12290 // find matching schemes subsets 12291 final Iterator<String> schemesIterator = intent.schemesIterator(); 12292 if (schemesIterator != null) { 12293 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12294 schemesIterator); 12295 if (intentListCopy.size() == 0) { 12296 // no more intents to match; we're not equivalent 12297 if (DEBUG_FILTERS) { 12298 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12299 + " package: " + applicationInfo.packageName 12300 + " activity: " + intent.activity.className 12301 + " origPrio: " + intent.getPriority()); 12302 } 12303 intent.setPriority(0); 12304 return; 12305 } 12306 } 12307 12308 // find matching authorities subsets 12309 final Iterator<IntentFilter.AuthorityEntry> 12310 authoritiesIterator = intent.authoritiesIterator(); 12311 if (authoritiesIterator != null) { 12312 getIntentListSubset(intentListCopy, 12313 new AuthoritiesIterGenerator(), 12314 authoritiesIterator); 12315 if (intentListCopy.size() == 0) { 12316 // no more intents to match; we're not equivalent 12317 if (DEBUG_FILTERS) { 12318 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12319 + " package: " + applicationInfo.packageName 12320 + " activity: " + intent.activity.className 12321 + " origPrio: " + intent.getPriority()); 12322 } 12323 intent.setPriority(0); 12324 return; 12325 } 12326 } 12327 12328 // we found matching filter(s); app gets the max priority of all intents 12329 int cappedPriority = 0; 12330 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12331 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12332 } 12333 if (intent.getPriority() > cappedPriority) { 12334 if (DEBUG_FILTERS) { 12335 Slog.i(TAG, "Found matching filter(s);" 12336 + " cap priority to " + cappedPriority + ";" 12337 + " package: " + applicationInfo.packageName 12338 + " activity: " + intent.activity.className 12339 + " origPrio: " + intent.getPriority()); 12340 } 12341 intent.setPriority(cappedPriority); 12342 return; 12343 } 12344 // all this for nothing; the requested priority was <= what was on the system 12345 } 12346 12347 public final void addActivity(PackageParser.Activity a, String type) { 12348 mActivities.put(a.getComponentName(), a); 12349 if (DEBUG_SHOW_INFO) 12350 Log.v( 12351 TAG, " " + type + " " + 12352 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12353 if (DEBUG_SHOW_INFO) 12354 Log.v(TAG, " Class=" + a.info.name); 12355 final int NI = a.intents.size(); 12356 for (int j=0; j<NI; j++) { 12357 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12358 if ("activity".equals(type)) { 12359 final PackageSetting ps = 12360 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12361 final List<PackageParser.Activity> systemActivities = 12362 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12363 adjustPriority(systemActivities, intent); 12364 } 12365 if (DEBUG_SHOW_INFO) { 12366 Log.v(TAG, " IntentFilter:"); 12367 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12368 } 12369 if (!intent.debugCheck()) { 12370 Log.w(TAG, "==> For Activity " + a.info.name); 12371 } 12372 addFilter(intent); 12373 } 12374 } 12375 12376 public final void removeActivity(PackageParser.Activity a, String type) { 12377 mActivities.remove(a.getComponentName()); 12378 if (DEBUG_SHOW_INFO) { 12379 Log.v(TAG, " " + type + " " 12380 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12381 : a.info.name) + ":"); 12382 Log.v(TAG, " Class=" + a.info.name); 12383 } 12384 final int NI = a.intents.size(); 12385 for (int j=0; j<NI; j++) { 12386 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12387 if (DEBUG_SHOW_INFO) { 12388 Log.v(TAG, " IntentFilter:"); 12389 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12390 } 12391 removeFilter(intent); 12392 } 12393 } 12394 12395 @Override 12396 protected boolean allowFilterResult( 12397 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12398 ActivityInfo filterAi = filter.activity.info; 12399 for (int i=dest.size()-1; i>=0; i--) { 12400 ActivityInfo destAi = dest.get(i).activityInfo; 12401 if (destAi.name == filterAi.name 12402 && destAi.packageName == filterAi.packageName) { 12403 return false; 12404 } 12405 } 12406 return true; 12407 } 12408 12409 @Override 12410 protected ActivityIntentInfo[] newArray(int size) { 12411 return new ActivityIntentInfo[size]; 12412 } 12413 12414 @Override 12415 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12416 if (!sUserManager.exists(userId)) return true; 12417 PackageParser.Package p = filter.activity.owner; 12418 if (p != null) { 12419 PackageSetting ps = (PackageSetting)p.mExtras; 12420 if (ps != null) { 12421 // System apps are never considered stopped for purposes of 12422 // filtering, because there may be no way for the user to 12423 // actually re-launch them. 12424 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12425 && ps.getStopped(userId); 12426 } 12427 } 12428 return false; 12429 } 12430 12431 @Override 12432 protected boolean isPackageForFilter(String packageName, 12433 PackageParser.ActivityIntentInfo info) { 12434 return packageName.equals(info.activity.owner.packageName); 12435 } 12436 12437 @Override 12438 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12439 int match, int userId) { 12440 if (!sUserManager.exists(userId)) return null; 12441 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12442 return null; 12443 } 12444 final PackageParser.Activity activity = info.activity; 12445 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12446 if (ps == null) { 12447 return null; 12448 } 12449 final PackageUserState userState = ps.readUserState(userId); 12450 ActivityInfo ai = 12451 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12452 if (ai == null) { 12453 return null; 12454 } 12455 final boolean matchExplicitlyVisibleOnly = 12456 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12457 final boolean matchVisibleToInstantApp = 12458 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12459 final boolean componentVisible = 12460 matchVisibleToInstantApp 12461 && info.isVisibleToInstantApp() 12462 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12463 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12464 // throw out filters that aren't visible to ephemeral apps 12465 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12466 return null; 12467 } 12468 // throw out instant app filters if we're not explicitly requesting them 12469 if (!matchInstantApp && userState.instantApp) { 12470 return null; 12471 } 12472 // throw out instant app filters if updates are available; will trigger 12473 // instant app resolution 12474 if (userState.instantApp && ps.isUpdateAvailable()) { 12475 return null; 12476 } 12477 final ResolveInfo res = new ResolveInfo(); 12478 res.activityInfo = ai; 12479 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12480 res.filter = info; 12481 } 12482 if (info != null) { 12483 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12484 } 12485 res.priority = info.getPriority(); 12486 res.preferredOrder = activity.owner.mPreferredOrder; 12487 //System.out.println("Result: " + res.activityInfo.className + 12488 // " = " + res.priority); 12489 res.match = match; 12490 res.isDefault = info.hasDefault; 12491 res.labelRes = info.labelRes; 12492 res.nonLocalizedLabel = info.nonLocalizedLabel; 12493 if (userNeedsBadging(userId)) { 12494 res.noResourceId = true; 12495 } else { 12496 res.icon = info.icon; 12497 } 12498 res.iconResourceId = info.icon; 12499 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12500 res.isInstantAppAvailable = userState.instantApp; 12501 return res; 12502 } 12503 12504 @Override 12505 protected void sortResults(List<ResolveInfo> results) { 12506 Collections.sort(results, mResolvePrioritySorter); 12507 } 12508 12509 @Override 12510 protected void dumpFilter(PrintWriter out, String prefix, 12511 PackageParser.ActivityIntentInfo filter) { 12512 out.print(prefix); out.print( 12513 Integer.toHexString(System.identityHashCode(filter.activity))); 12514 out.print(' '); 12515 filter.activity.printComponentShortName(out); 12516 out.print(" filter "); 12517 out.println(Integer.toHexString(System.identityHashCode(filter))); 12518 } 12519 12520 @Override 12521 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12522 return filter.activity; 12523 } 12524 12525 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12526 PackageParser.Activity activity = (PackageParser.Activity)label; 12527 out.print(prefix); out.print( 12528 Integer.toHexString(System.identityHashCode(activity))); 12529 out.print(' '); 12530 activity.printComponentShortName(out); 12531 if (count > 1) { 12532 out.print(" ("); out.print(count); out.print(" filters)"); 12533 } 12534 out.println(); 12535 } 12536 12537 // Keys are String (activity class name), values are Activity. 12538 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12539 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12540 private int mFlags; 12541 } 12542 12543 private final class ServiceIntentResolver 12544 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12545 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12546 boolean defaultOnly, int userId) { 12547 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12548 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12549 } 12550 12551 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12552 int userId) { 12553 if (!sUserManager.exists(userId)) return null; 12554 mFlags = flags; 12555 return super.queryIntent(intent, resolvedType, 12556 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12557 userId); 12558 } 12559 12560 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12561 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12562 if (!sUserManager.exists(userId)) return null; 12563 if (packageServices == null) { 12564 return null; 12565 } 12566 mFlags = flags; 12567 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12568 final int N = packageServices.size(); 12569 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12570 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12571 12572 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12573 for (int i = 0; i < N; ++i) { 12574 intentFilters = packageServices.get(i).intents; 12575 if (intentFilters != null && intentFilters.size() > 0) { 12576 PackageParser.ServiceIntentInfo[] array = 12577 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12578 intentFilters.toArray(array); 12579 listCut.add(array); 12580 } 12581 } 12582 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12583 } 12584 12585 public final void addService(PackageParser.Service s) { 12586 mServices.put(s.getComponentName(), s); 12587 if (DEBUG_SHOW_INFO) { 12588 Log.v(TAG, " " 12589 + (s.info.nonLocalizedLabel != null 12590 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12591 Log.v(TAG, " Class=" + s.info.name); 12592 } 12593 final int NI = s.intents.size(); 12594 int j; 12595 for (j=0; j<NI; j++) { 12596 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12597 if (DEBUG_SHOW_INFO) { 12598 Log.v(TAG, " IntentFilter:"); 12599 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12600 } 12601 if (!intent.debugCheck()) { 12602 Log.w(TAG, "==> For Service " + s.info.name); 12603 } 12604 addFilter(intent); 12605 } 12606 } 12607 12608 public final void removeService(PackageParser.Service s) { 12609 mServices.remove(s.getComponentName()); 12610 if (DEBUG_SHOW_INFO) { 12611 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12612 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12613 Log.v(TAG, " Class=" + s.info.name); 12614 } 12615 final int NI = s.intents.size(); 12616 int j; 12617 for (j=0; j<NI; j++) { 12618 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12619 if (DEBUG_SHOW_INFO) { 12620 Log.v(TAG, " IntentFilter:"); 12621 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12622 } 12623 removeFilter(intent); 12624 } 12625 } 12626 12627 @Override 12628 protected boolean allowFilterResult( 12629 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12630 ServiceInfo filterSi = filter.service.info; 12631 for (int i=dest.size()-1; i>=0; i--) { 12632 ServiceInfo destAi = dest.get(i).serviceInfo; 12633 if (destAi.name == filterSi.name 12634 && destAi.packageName == filterSi.packageName) { 12635 return false; 12636 } 12637 } 12638 return true; 12639 } 12640 12641 @Override 12642 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12643 return new PackageParser.ServiceIntentInfo[size]; 12644 } 12645 12646 @Override 12647 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12648 if (!sUserManager.exists(userId)) return true; 12649 PackageParser.Package p = filter.service.owner; 12650 if (p != null) { 12651 PackageSetting ps = (PackageSetting)p.mExtras; 12652 if (ps != null) { 12653 // System apps are never considered stopped for purposes of 12654 // filtering, because there may be no way for the user to 12655 // actually re-launch them. 12656 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12657 && ps.getStopped(userId); 12658 } 12659 } 12660 return false; 12661 } 12662 12663 @Override 12664 protected boolean isPackageForFilter(String packageName, 12665 PackageParser.ServiceIntentInfo info) { 12666 return packageName.equals(info.service.owner.packageName); 12667 } 12668 12669 @Override 12670 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12671 int match, int userId) { 12672 if (!sUserManager.exists(userId)) return null; 12673 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12674 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12675 return null; 12676 } 12677 final PackageParser.Service service = info.service; 12678 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12679 if (ps == null) { 12680 return null; 12681 } 12682 final PackageUserState userState = ps.readUserState(userId); 12683 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12684 userState, userId); 12685 if (si == null) { 12686 return null; 12687 } 12688 final boolean matchVisibleToInstantApp = 12689 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12690 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12691 // throw out filters that aren't visible to ephemeral apps 12692 if (matchVisibleToInstantApp 12693 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12694 return null; 12695 } 12696 // throw out ephemeral filters if we're not explicitly requesting them 12697 if (!isInstantApp && userState.instantApp) { 12698 return null; 12699 } 12700 // throw out instant app filters if updates are available; will trigger 12701 // instant app resolution 12702 if (userState.instantApp && ps.isUpdateAvailable()) { 12703 return null; 12704 } 12705 final ResolveInfo res = new ResolveInfo(); 12706 res.serviceInfo = si; 12707 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12708 res.filter = filter; 12709 } 12710 res.priority = info.getPriority(); 12711 res.preferredOrder = service.owner.mPreferredOrder; 12712 res.match = match; 12713 res.isDefault = info.hasDefault; 12714 res.labelRes = info.labelRes; 12715 res.nonLocalizedLabel = info.nonLocalizedLabel; 12716 res.icon = info.icon; 12717 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12718 return res; 12719 } 12720 12721 @Override 12722 protected void sortResults(List<ResolveInfo> results) { 12723 Collections.sort(results, mResolvePrioritySorter); 12724 } 12725 12726 @Override 12727 protected void dumpFilter(PrintWriter out, String prefix, 12728 PackageParser.ServiceIntentInfo filter) { 12729 out.print(prefix); out.print( 12730 Integer.toHexString(System.identityHashCode(filter.service))); 12731 out.print(' '); 12732 filter.service.printComponentShortName(out); 12733 out.print(" filter "); 12734 out.print(Integer.toHexString(System.identityHashCode(filter))); 12735 if (filter.service.info.permission != null) { 12736 out.print(" permission "); out.println(filter.service.info.permission); 12737 } else { 12738 out.println(); 12739 } 12740 } 12741 12742 @Override 12743 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12744 return filter.service; 12745 } 12746 12747 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12748 PackageParser.Service service = (PackageParser.Service)label; 12749 out.print(prefix); out.print( 12750 Integer.toHexString(System.identityHashCode(service))); 12751 out.print(' '); 12752 service.printComponentShortName(out); 12753 if (count > 1) { 12754 out.print(" ("); out.print(count); out.print(" filters)"); 12755 } 12756 out.println(); 12757 } 12758 12759// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12760// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12761// final List<ResolveInfo> retList = Lists.newArrayList(); 12762// while (i.hasNext()) { 12763// final ResolveInfo resolveInfo = (ResolveInfo) i; 12764// if (isEnabledLP(resolveInfo.serviceInfo)) { 12765// retList.add(resolveInfo); 12766// } 12767// } 12768// return retList; 12769// } 12770 12771 // Keys are String (activity class name), values are Activity. 12772 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12773 = new ArrayMap<ComponentName, PackageParser.Service>(); 12774 private int mFlags; 12775 } 12776 12777 private final class ProviderIntentResolver 12778 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12779 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12780 boolean defaultOnly, int userId) { 12781 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12782 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12783 } 12784 12785 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12786 int userId) { 12787 if (!sUserManager.exists(userId)) 12788 return null; 12789 mFlags = flags; 12790 return super.queryIntent(intent, resolvedType, 12791 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12792 userId); 12793 } 12794 12795 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12796 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12797 if (!sUserManager.exists(userId)) 12798 return null; 12799 if (packageProviders == null) { 12800 return null; 12801 } 12802 mFlags = flags; 12803 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12804 final int N = packageProviders.size(); 12805 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12806 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12807 12808 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12809 for (int i = 0; i < N; ++i) { 12810 intentFilters = packageProviders.get(i).intents; 12811 if (intentFilters != null && intentFilters.size() > 0) { 12812 PackageParser.ProviderIntentInfo[] array = 12813 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12814 intentFilters.toArray(array); 12815 listCut.add(array); 12816 } 12817 } 12818 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12819 } 12820 12821 public final void addProvider(PackageParser.Provider p) { 12822 if (mProviders.containsKey(p.getComponentName())) { 12823 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12824 return; 12825 } 12826 12827 mProviders.put(p.getComponentName(), p); 12828 if (DEBUG_SHOW_INFO) { 12829 Log.v(TAG, " " 12830 + (p.info.nonLocalizedLabel != null 12831 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12832 Log.v(TAG, " Class=" + p.info.name); 12833 } 12834 final int NI = p.intents.size(); 12835 int j; 12836 for (j = 0; j < NI; j++) { 12837 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12838 if (DEBUG_SHOW_INFO) { 12839 Log.v(TAG, " IntentFilter:"); 12840 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12841 } 12842 if (!intent.debugCheck()) { 12843 Log.w(TAG, "==> For Provider " + p.info.name); 12844 } 12845 addFilter(intent); 12846 } 12847 } 12848 12849 public final void removeProvider(PackageParser.Provider p) { 12850 mProviders.remove(p.getComponentName()); 12851 if (DEBUG_SHOW_INFO) { 12852 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12853 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12854 Log.v(TAG, " Class=" + p.info.name); 12855 } 12856 final int NI = p.intents.size(); 12857 int j; 12858 for (j = 0; j < NI; j++) { 12859 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12860 if (DEBUG_SHOW_INFO) { 12861 Log.v(TAG, " IntentFilter:"); 12862 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12863 } 12864 removeFilter(intent); 12865 } 12866 } 12867 12868 @Override 12869 protected boolean allowFilterResult( 12870 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12871 ProviderInfo filterPi = filter.provider.info; 12872 for (int i = dest.size() - 1; i >= 0; i--) { 12873 ProviderInfo destPi = dest.get(i).providerInfo; 12874 if (destPi.name == filterPi.name 12875 && destPi.packageName == filterPi.packageName) { 12876 return false; 12877 } 12878 } 12879 return true; 12880 } 12881 12882 @Override 12883 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12884 return new PackageParser.ProviderIntentInfo[size]; 12885 } 12886 12887 @Override 12888 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12889 if (!sUserManager.exists(userId)) 12890 return true; 12891 PackageParser.Package p = filter.provider.owner; 12892 if (p != null) { 12893 PackageSetting ps = (PackageSetting) p.mExtras; 12894 if (ps != null) { 12895 // System apps are never considered stopped for purposes of 12896 // filtering, because there may be no way for the user to 12897 // actually re-launch them. 12898 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12899 && ps.getStopped(userId); 12900 } 12901 } 12902 return false; 12903 } 12904 12905 @Override 12906 protected boolean isPackageForFilter(String packageName, 12907 PackageParser.ProviderIntentInfo info) { 12908 return packageName.equals(info.provider.owner.packageName); 12909 } 12910 12911 @Override 12912 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12913 int match, int userId) { 12914 if (!sUserManager.exists(userId)) 12915 return null; 12916 final PackageParser.ProviderIntentInfo info = filter; 12917 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12918 return null; 12919 } 12920 final PackageParser.Provider provider = info.provider; 12921 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12922 if (ps == null) { 12923 return null; 12924 } 12925 final PackageUserState userState = ps.readUserState(userId); 12926 final boolean matchVisibleToInstantApp = 12927 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12928 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12929 // throw out filters that aren't visible to instant applications 12930 if (matchVisibleToInstantApp 12931 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12932 return null; 12933 } 12934 // throw out instant application filters if we're not explicitly requesting them 12935 if (!isInstantApp && userState.instantApp) { 12936 return null; 12937 } 12938 // throw out instant application filters if updates are available; will trigger 12939 // instant application resolution 12940 if (userState.instantApp && ps.isUpdateAvailable()) { 12941 return null; 12942 } 12943 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12944 userState, userId); 12945 if (pi == null) { 12946 return null; 12947 } 12948 final ResolveInfo res = new ResolveInfo(); 12949 res.providerInfo = pi; 12950 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12951 res.filter = filter; 12952 } 12953 res.priority = info.getPriority(); 12954 res.preferredOrder = provider.owner.mPreferredOrder; 12955 res.match = match; 12956 res.isDefault = info.hasDefault; 12957 res.labelRes = info.labelRes; 12958 res.nonLocalizedLabel = info.nonLocalizedLabel; 12959 res.icon = info.icon; 12960 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12961 return res; 12962 } 12963 12964 @Override 12965 protected void sortResults(List<ResolveInfo> results) { 12966 Collections.sort(results, mResolvePrioritySorter); 12967 } 12968 12969 @Override 12970 protected void dumpFilter(PrintWriter out, String prefix, 12971 PackageParser.ProviderIntentInfo filter) { 12972 out.print(prefix); 12973 out.print( 12974 Integer.toHexString(System.identityHashCode(filter.provider))); 12975 out.print(' '); 12976 filter.provider.printComponentShortName(out); 12977 out.print(" filter "); 12978 out.println(Integer.toHexString(System.identityHashCode(filter))); 12979 } 12980 12981 @Override 12982 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12983 return filter.provider; 12984 } 12985 12986 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12987 PackageParser.Provider provider = (PackageParser.Provider)label; 12988 out.print(prefix); out.print( 12989 Integer.toHexString(System.identityHashCode(provider))); 12990 out.print(' '); 12991 provider.printComponentShortName(out); 12992 if (count > 1) { 12993 out.print(" ("); out.print(count); out.print(" filters)"); 12994 } 12995 out.println(); 12996 } 12997 12998 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12999 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13000 private int mFlags; 13001 } 13002 13003 static final class EphemeralIntentResolver 13004 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13005 /** 13006 * The result that has the highest defined order. Ordering applies on a 13007 * per-package basis. Mapping is from package name to Pair of order and 13008 * EphemeralResolveInfo. 13009 * <p> 13010 * NOTE: This is implemented as a field variable for convenience and efficiency. 13011 * By having a field variable, we're able to track filter ordering as soon as 13012 * a non-zero order is defined. Otherwise, multiple loops across the result set 13013 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13014 * this needs to be contained entirely within {@link #filterResults}. 13015 */ 13016 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13017 13018 @Override 13019 protected AuxiliaryResolveInfo[] newArray(int size) { 13020 return new AuxiliaryResolveInfo[size]; 13021 } 13022 13023 @Override 13024 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13025 return true; 13026 } 13027 13028 @Override 13029 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13030 int userId) { 13031 if (!sUserManager.exists(userId)) { 13032 return null; 13033 } 13034 final String packageName = responseObj.resolveInfo.getPackageName(); 13035 final Integer order = responseObj.getOrder(); 13036 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13037 mOrderResult.get(packageName); 13038 // ordering is enabled and this item's order isn't high enough 13039 if (lastOrderResult != null && lastOrderResult.first >= order) { 13040 return null; 13041 } 13042 final InstantAppResolveInfo res = responseObj.resolveInfo; 13043 if (order > 0) { 13044 // non-zero order, enable ordering 13045 mOrderResult.put(packageName, new Pair<>(order, res)); 13046 } 13047 return responseObj; 13048 } 13049 13050 @Override 13051 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13052 // only do work if ordering is enabled [most of the time it won't be] 13053 if (mOrderResult.size() == 0) { 13054 return; 13055 } 13056 int resultSize = results.size(); 13057 for (int i = 0; i < resultSize; i++) { 13058 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13059 final String packageName = info.getPackageName(); 13060 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13061 if (savedInfo == null) { 13062 // package doesn't having ordering 13063 continue; 13064 } 13065 if (savedInfo.second == info) { 13066 // circled back to the highest ordered item; remove from order list 13067 mOrderResult.remove(packageName); 13068 if (mOrderResult.size() == 0) { 13069 // no more ordered items 13070 break; 13071 } 13072 continue; 13073 } 13074 // item has a worse order, remove it from the result list 13075 results.remove(i); 13076 resultSize--; 13077 i--; 13078 } 13079 } 13080 } 13081 13082 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13083 new Comparator<ResolveInfo>() { 13084 public int compare(ResolveInfo r1, ResolveInfo r2) { 13085 int v1 = r1.priority; 13086 int v2 = r2.priority; 13087 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13088 if (v1 != v2) { 13089 return (v1 > v2) ? -1 : 1; 13090 } 13091 v1 = r1.preferredOrder; 13092 v2 = r2.preferredOrder; 13093 if (v1 != v2) { 13094 return (v1 > v2) ? -1 : 1; 13095 } 13096 if (r1.isDefault != r2.isDefault) { 13097 return r1.isDefault ? -1 : 1; 13098 } 13099 v1 = r1.match; 13100 v2 = r2.match; 13101 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13102 if (v1 != v2) { 13103 return (v1 > v2) ? -1 : 1; 13104 } 13105 if (r1.system != r2.system) { 13106 return r1.system ? -1 : 1; 13107 } 13108 if (r1.activityInfo != null) { 13109 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13110 } 13111 if (r1.serviceInfo != null) { 13112 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13113 } 13114 if (r1.providerInfo != null) { 13115 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13116 } 13117 return 0; 13118 } 13119 }; 13120 13121 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13122 new Comparator<ProviderInfo>() { 13123 public int compare(ProviderInfo p1, ProviderInfo p2) { 13124 final int v1 = p1.initOrder; 13125 final int v2 = p2.initOrder; 13126 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13127 } 13128 }; 13129 13130 @Override 13131 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13132 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13133 final int[] userIds, int[] instantUserIds) { 13134 mHandler.post(new Runnable() { 13135 @Override 13136 public void run() { 13137 try { 13138 final IActivityManager am = ActivityManager.getService(); 13139 if (am == null) return; 13140 final int[] resolvedUserIds; 13141 if (userIds == null) { 13142 resolvedUserIds = am.getRunningUserIds(); 13143 } else { 13144 resolvedUserIds = userIds; 13145 } 13146 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13147 resolvedUserIds, false); 13148 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13149 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13150 instantUserIds, true); 13151 } 13152 } catch (RemoteException ex) { 13153 } 13154 } 13155 }); 13156 } 13157 13158 @Override 13159 public void notifyPackageAdded(String packageName) { 13160 final PackageListObserver[] observers; 13161 synchronized (mPackages) { 13162 if (mPackageListObservers.size() == 0) { 13163 return; 13164 } 13165 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13166 } 13167 for (int i = observers.length - 1; i >= 0; --i) { 13168 observers[i].onPackageAdded(packageName); 13169 } 13170 } 13171 13172 @Override 13173 public void notifyPackageRemoved(String packageName) { 13174 final PackageListObserver[] observers; 13175 synchronized (mPackages) { 13176 if (mPackageListObservers.size() == 0) { 13177 return; 13178 } 13179 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13180 } 13181 for (int i = observers.length - 1; i >= 0; --i) { 13182 observers[i].onPackageRemoved(packageName); 13183 } 13184 } 13185 13186 /** 13187 * Sends a broadcast for the given action. 13188 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13189 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13190 * the system and applications allowed to see instant applications to receive package 13191 * lifecycle events for instant applications. 13192 */ 13193 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13194 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13195 int[] userIds, boolean isInstantApp) 13196 throws RemoteException { 13197 for (int id : userIds) { 13198 final Intent intent = new Intent(action, 13199 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13200 final String[] requiredPermissions = 13201 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13202 if (extras != null) { 13203 intent.putExtras(extras); 13204 } 13205 if (targetPkg != null) { 13206 intent.setPackage(targetPkg); 13207 } 13208 // Modify the UID when posting to other users 13209 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13210 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13211 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13212 intent.putExtra(Intent.EXTRA_UID, uid); 13213 } 13214 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13215 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13216 if (DEBUG_BROADCASTS) { 13217 RuntimeException here = new RuntimeException("here"); 13218 here.fillInStackTrace(); 13219 Slog.d(TAG, "Sending to user " + id + ": " 13220 + intent.toShortString(false, true, false, false) 13221 + " " + intent.getExtras(), here); 13222 } 13223 am.broadcastIntent(null, intent, null, finishedReceiver, 13224 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13225 null, finishedReceiver != null, false, id); 13226 } 13227 } 13228 13229 /** 13230 * Check if the external storage media is available. This is true if there 13231 * is a mounted external storage medium or if the external storage is 13232 * emulated. 13233 */ 13234 private boolean isExternalMediaAvailable() { 13235 return mMediaMounted || Environment.isExternalStorageEmulated(); 13236 } 13237 13238 @Override 13239 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13240 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13241 return null; 13242 } 13243 if (!isExternalMediaAvailable()) { 13244 // If the external storage is no longer mounted at this point, 13245 // the caller may not have been able to delete all of this 13246 // packages files and can not delete any more. Bail. 13247 return null; 13248 } 13249 synchronized (mPackages) { 13250 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13251 if (lastPackage != null) { 13252 pkgs.remove(lastPackage); 13253 } 13254 if (pkgs.size() > 0) { 13255 return pkgs.get(0); 13256 } 13257 } 13258 return null; 13259 } 13260 13261 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13262 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13263 userId, andCode ? 1 : 0, packageName); 13264 if (mSystemReady) { 13265 msg.sendToTarget(); 13266 } else { 13267 if (mPostSystemReadyMessages == null) { 13268 mPostSystemReadyMessages = new ArrayList<>(); 13269 } 13270 mPostSystemReadyMessages.add(msg); 13271 } 13272 } 13273 13274 void startCleaningPackages() { 13275 // reader 13276 if (!isExternalMediaAvailable()) { 13277 return; 13278 } 13279 synchronized (mPackages) { 13280 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13281 return; 13282 } 13283 } 13284 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13285 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13286 IActivityManager am = ActivityManager.getService(); 13287 if (am != null) { 13288 int dcsUid = -1; 13289 synchronized (mPackages) { 13290 if (!mDefaultContainerWhitelisted) { 13291 mDefaultContainerWhitelisted = true; 13292 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13293 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13294 } 13295 } 13296 try { 13297 if (dcsUid > 0) { 13298 am.backgroundWhitelistUid(dcsUid); 13299 } 13300 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13301 UserHandle.USER_SYSTEM); 13302 } catch (RemoteException e) { 13303 } 13304 } 13305 } 13306 13307 /** 13308 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13309 * it is acting on behalf on an enterprise or the user). 13310 * 13311 * Note that the ordering of the conditionals in this method is important. The checks we perform 13312 * are as follows, in this order: 13313 * 13314 * 1) If the install is being performed by a system app, we can trust the app to have set the 13315 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13316 * what it is. 13317 * 2) If the install is being performed by a device or profile owner app, the install reason 13318 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13319 * set the install reason correctly. If the app targets an older SDK version where install 13320 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13321 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13322 * 3) In all other cases, the install is being performed by a regular app that is neither part 13323 * of the system nor a device or profile owner. We have no reason to believe that this app is 13324 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13325 * set to enterprise policy and if so, change it to unknown instead. 13326 */ 13327 private int fixUpInstallReason(String installerPackageName, int installerUid, 13328 int installReason) { 13329 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13330 == PERMISSION_GRANTED) { 13331 // If the install is being performed by a system app, we trust that app to have set the 13332 // install reason correctly. 13333 return installReason; 13334 } 13335 13336 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13337 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13338 if (dpm != null) { 13339 ComponentName owner = null; 13340 try { 13341 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13342 if (owner == null) { 13343 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13344 } 13345 } catch (RemoteException e) { 13346 } 13347 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13348 // If the install is being performed by a device or profile owner, the install 13349 // reason should be enterprise policy. 13350 return PackageManager.INSTALL_REASON_POLICY; 13351 } 13352 } 13353 13354 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13355 // If the install is being performed by a regular app (i.e. neither system app nor 13356 // device or profile owner), we have no reason to believe that the app is acting on 13357 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13358 // change it to unknown instead. 13359 return PackageManager.INSTALL_REASON_UNKNOWN; 13360 } 13361 13362 // If the install is being performed by a regular app and the install reason was set to any 13363 // value but enterprise policy, leave the install reason unchanged. 13364 return installReason; 13365 } 13366 13367 void installStage(String packageName, File stagedDir, 13368 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13369 String installerPackageName, int installerUid, UserHandle user, 13370 PackageParser.SigningDetails signingDetails) { 13371 if (DEBUG_EPHEMERAL) { 13372 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13373 Slog.d(TAG, "Ephemeral install of " + packageName); 13374 } 13375 } 13376 final VerificationInfo verificationInfo = new VerificationInfo( 13377 sessionParams.originatingUri, sessionParams.referrerUri, 13378 sessionParams.originatingUid, installerUid); 13379 13380 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13381 13382 final Message msg = mHandler.obtainMessage(INIT_COPY); 13383 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13384 sessionParams.installReason); 13385 final InstallParams params = new InstallParams(origin, null, observer, 13386 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13387 verificationInfo, user, sessionParams.abiOverride, 13388 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13389 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13390 msg.obj = params; 13391 13392 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13393 System.identityHashCode(msg.obj)); 13394 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13395 System.identityHashCode(msg.obj)); 13396 13397 mHandler.sendMessage(msg); 13398 } 13399 13400 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13401 int userId) { 13402 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13403 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13404 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13405 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13406 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13407 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13408 13409 // Send a session commit broadcast 13410 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13411 info.installReason = pkgSetting.getInstallReason(userId); 13412 info.appPackageName = packageName; 13413 sendSessionCommitBroadcast(info, userId); 13414 } 13415 13416 @Override 13417 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13418 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13419 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13420 return; 13421 } 13422 Bundle extras = new Bundle(1); 13423 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13424 final int uid = UserHandle.getUid( 13425 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13426 extras.putInt(Intent.EXTRA_UID, uid); 13427 13428 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13429 packageName, extras, 0, null, null, userIds, instantUserIds); 13430 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13431 mHandler.post(() -> { 13432 for (int userId : userIds) { 13433 sendBootCompletedBroadcastToSystemApp( 13434 packageName, includeStopped, userId); 13435 } 13436 } 13437 ); 13438 } 13439 } 13440 13441 /** 13442 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13443 * automatically without needing an explicit launch. 13444 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13445 */ 13446 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13447 int userId) { 13448 // If user is not running, the app didn't miss any broadcast 13449 if (!mUserManagerInternal.isUserRunning(userId)) { 13450 return; 13451 } 13452 final IActivityManager am = ActivityManager.getService(); 13453 try { 13454 // Deliver LOCKED_BOOT_COMPLETED first 13455 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13456 .setPackage(packageName); 13457 if (includeStopped) { 13458 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13459 } 13460 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13461 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13462 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13463 13464 // Deliver BOOT_COMPLETED only if user is unlocked 13465 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13466 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13467 if (includeStopped) { 13468 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13469 } 13470 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13471 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13472 } 13473 } catch (RemoteException e) { 13474 throw e.rethrowFromSystemServer(); 13475 } 13476 } 13477 13478 @Override 13479 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13480 int userId) { 13481 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13482 PackageSetting pkgSetting; 13483 final int callingUid = Binder.getCallingUid(); 13484 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13485 true /* requireFullPermission */, true /* checkShell */, 13486 "setApplicationHiddenSetting for user " + userId); 13487 13488 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13489 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13490 return false; 13491 } 13492 13493 long callingId = Binder.clearCallingIdentity(); 13494 try { 13495 boolean sendAdded = false; 13496 boolean sendRemoved = false; 13497 // writer 13498 synchronized (mPackages) { 13499 pkgSetting = mSettings.mPackages.get(packageName); 13500 if (pkgSetting == null) { 13501 return false; 13502 } 13503 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13504 return false; 13505 } 13506 // Do not allow "android" is being disabled 13507 if ("android".equals(packageName)) { 13508 Slog.w(TAG, "Cannot hide package: android"); 13509 return false; 13510 } 13511 // Cannot hide static shared libs as they are considered 13512 // a part of the using app (emulating static linking). Also 13513 // static libs are installed always on internal storage. 13514 PackageParser.Package pkg = mPackages.get(packageName); 13515 if (pkg != null && pkg.staticSharedLibName != null) { 13516 Slog.w(TAG, "Cannot hide package: " + packageName 13517 + " providing static shared library: " 13518 + pkg.staticSharedLibName); 13519 return false; 13520 } 13521 // Only allow protected packages to hide themselves. 13522 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13523 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13524 Slog.w(TAG, "Not hiding protected package: " + packageName); 13525 return false; 13526 } 13527 13528 if (pkgSetting.getHidden(userId) != hidden) { 13529 pkgSetting.setHidden(hidden, userId); 13530 mSettings.writePackageRestrictionsLPr(userId); 13531 if (hidden) { 13532 sendRemoved = true; 13533 } else { 13534 sendAdded = true; 13535 } 13536 } 13537 } 13538 if (sendAdded) { 13539 sendPackageAddedForUser(packageName, pkgSetting, userId); 13540 return true; 13541 } 13542 if (sendRemoved) { 13543 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13544 "hiding pkg"); 13545 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13546 return true; 13547 } 13548 } finally { 13549 Binder.restoreCallingIdentity(callingId); 13550 } 13551 return false; 13552 } 13553 13554 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13555 int userId) { 13556 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13557 info.removedPackage = packageName; 13558 info.installerPackageName = pkgSetting.installerPackageName; 13559 info.removedUsers = new int[] {userId}; 13560 info.broadcastUsers = new int[] {userId}; 13561 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13562 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13563 } 13564 13565 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13566 if (pkgList.length > 0) { 13567 Bundle extras = new Bundle(1); 13568 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13569 13570 sendPackageBroadcast( 13571 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13572 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13573 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13574 new int[] {userId}, null); 13575 } 13576 } 13577 13578 /** 13579 * Returns true if application is not found or there was an error. Otherwise it returns 13580 * the hidden state of the package for the given user. 13581 */ 13582 @Override 13583 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13585 final int callingUid = Binder.getCallingUid(); 13586 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13587 true /* requireFullPermission */, false /* checkShell */, 13588 "getApplicationHidden for user " + userId); 13589 PackageSetting ps; 13590 long callingId = Binder.clearCallingIdentity(); 13591 try { 13592 // writer 13593 synchronized (mPackages) { 13594 ps = mSettings.mPackages.get(packageName); 13595 if (ps == null) { 13596 return true; 13597 } 13598 if (filterAppAccessLPr(ps, callingUid, userId)) { 13599 return true; 13600 } 13601 return ps.getHidden(userId); 13602 } 13603 } finally { 13604 Binder.restoreCallingIdentity(callingId); 13605 } 13606 } 13607 13608 /** 13609 * @hide 13610 */ 13611 @Override 13612 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13613 int installReason) { 13614 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13615 null); 13616 PackageSetting pkgSetting; 13617 final int callingUid = Binder.getCallingUid(); 13618 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13619 true /* requireFullPermission */, true /* checkShell */, 13620 "installExistingPackage for user " + userId); 13621 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13622 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13623 } 13624 13625 long callingId = Binder.clearCallingIdentity(); 13626 try { 13627 boolean installed = false; 13628 final boolean instantApp = 13629 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13630 final boolean fullApp = 13631 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13632 13633 // writer 13634 synchronized (mPackages) { 13635 pkgSetting = mSettings.mPackages.get(packageName); 13636 if (pkgSetting == null) { 13637 return PackageManager.INSTALL_FAILED_INVALID_URI; 13638 } 13639 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13640 // only allow the existing package to be used if it's installed as a full 13641 // application for at least one user 13642 boolean installAllowed = false; 13643 for (int checkUserId : sUserManager.getUserIds()) { 13644 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13645 if (installAllowed) { 13646 break; 13647 } 13648 } 13649 if (!installAllowed) { 13650 return PackageManager.INSTALL_FAILED_INVALID_URI; 13651 } 13652 } 13653 if (!pkgSetting.getInstalled(userId)) { 13654 pkgSetting.setInstalled(true, userId); 13655 pkgSetting.setHidden(false, userId); 13656 pkgSetting.setInstallReason(installReason, userId); 13657 mSettings.writePackageRestrictionsLPr(userId); 13658 mSettings.writeKernelMappingLPr(pkgSetting); 13659 installed = true; 13660 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13661 // upgrade app from instant to full; we don't allow app downgrade 13662 installed = true; 13663 } 13664 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13665 } 13666 13667 if (installed) { 13668 if (pkgSetting.pkg != null) { 13669 synchronized (mInstallLock) { 13670 // We don't need to freeze for a brand new install 13671 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13672 } 13673 } 13674 sendPackageAddedForUser(packageName, pkgSetting, userId); 13675 synchronized (mPackages) { 13676 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13677 } 13678 } 13679 } finally { 13680 Binder.restoreCallingIdentity(callingId); 13681 } 13682 13683 return PackageManager.INSTALL_SUCCEEDED; 13684 } 13685 13686 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13687 boolean instantApp, boolean fullApp) { 13688 // no state specified; do nothing 13689 if (!instantApp && !fullApp) { 13690 return; 13691 } 13692 if (userId != UserHandle.USER_ALL) { 13693 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13694 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13695 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13696 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13697 } 13698 } else { 13699 for (int currentUserId : sUserManager.getUserIds()) { 13700 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13701 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13702 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13703 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13704 } 13705 } 13706 } 13707 } 13708 13709 boolean isUserRestricted(int userId, String restrictionKey) { 13710 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13711 if (restrictions.getBoolean(restrictionKey, false)) { 13712 Log.w(TAG, "User is restricted: " + restrictionKey); 13713 return true; 13714 } 13715 return false; 13716 } 13717 13718 @Override 13719 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13720 int userId) { 13721 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13722 final int callingUid = Binder.getCallingUid(); 13723 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13724 true /* requireFullPermission */, true /* checkShell */, 13725 "setPackagesSuspended for user " + userId); 13726 13727 if (ArrayUtils.isEmpty(packageNames)) { 13728 return packageNames; 13729 } 13730 13731 // List of package names for whom the suspended state has changed. 13732 List<String> changedPackages = new ArrayList<>(packageNames.length); 13733 // List of package names for whom the suspended state is not set as requested in this 13734 // method. 13735 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13736 long callingId = Binder.clearCallingIdentity(); 13737 try { 13738 for (int i = 0; i < packageNames.length; i++) { 13739 String packageName = packageNames[i]; 13740 boolean changed = false; 13741 final int appId; 13742 synchronized (mPackages) { 13743 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13744 if (pkgSetting == null 13745 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13746 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13747 + "\". Skipping suspending/un-suspending."); 13748 unactionedPackages.add(packageName); 13749 continue; 13750 } 13751 appId = pkgSetting.appId; 13752 if (pkgSetting.getSuspended(userId) != suspended) { 13753 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13754 unactionedPackages.add(packageName); 13755 continue; 13756 } 13757 pkgSetting.setSuspended(suspended, userId); 13758 mSettings.writePackageRestrictionsLPr(userId); 13759 changed = true; 13760 changedPackages.add(packageName); 13761 } 13762 } 13763 13764 if (changed && suspended) { 13765 killApplication(packageName, UserHandle.getUid(userId, appId), 13766 "suspending package"); 13767 } 13768 } 13769 } finally { 13770 Binder.restoreCallingIdentity(callingId); 13771 } 13772 13773 if (!changedPackages.isEmpty()) { 13774 sendPackagesSuspendedForUser(changedPackages.toArray( 13775 new String[changedPackages.size()]), userId, suspended); 13776 } 13777 13778 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13779 } 13780 13781 @Override 13782 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13783 final int callingUid = Binder.getCallingUid(); 13784 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13785 true /* requireFullPermission */, false /* checkShell */, 13786 "isPackageSuspendedForUser for user " + userId); 13787 synchronized (mPackages) { 13788 final PackageSetting ps = mSettings.mPackages.get(packageName); 13789 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13790 throw new IllegalArgumentException("Unknown target package: " + packageName); 13791 } 13792 return ps.getSuspended(userId); 13793 } 13794 } 13795 13796 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13797 if (isPackageDeviceAdmin(packageName, userId)) { 13798 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13799 + "\": has an active device admin"); 13800 return false; 13801 } 13802 13803 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13804 if (packageName.equals(activeLauncherPackageName)) { 13805 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13806 + "\": contains the active launcher"); 13807 return false; 13808 } 13809 13810 if (packageName.equals(mRequiredInstallerPackage)) { 13811 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13812 + "\": required for package installation"); 13813 return false; 13814 } 13815 13816 if (packageName.equals(mRequiredUninstallerPackage)) { 13817 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13818 + "\": required for package uninstallation"); 13819 return false; 13820 } 13821 13822 if (packageName.equals(mRequiredVerifierPackage)) { 13823 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13824 + "\": required for package verification"); 13825 return false; 13826 } 13827 13828 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13829 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13830 + "\": is the default dialer"); 13831 return false; 13832 } 13833 13834 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13835 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13836 + "\": protected package"); 13837 return false; 13838 } 13839 13840 // Cannot suspend static shared libs as they are considered 13841 // a part of the using app (emulating static linking). Also 13842 // static libs are installed always on internal storage. 13843 PackageParser.Package pkg = mPackages.get(packageName); 13844 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13845 Slog.w(TAG, "Cannot suspend package: " + packageName 13846 + " providing static shared library: " 13847 + pkg.staticSharedLibName); 13848 return false; 13849 } 13850 13851 return true; 13852 } 13853 13854 private String getActiveLauncherPackageName(int userId) { 13855 Intent intent = new Intent(Intent.ACTION_MAIN); 13856 intent.addCategory(Intent.CATEGORY_HOME); 13857 ResolveInfo resolveInfo = resolveIntent( 13858 intent, 13859 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13860 PackageManager.MATCH_DEFAULT_ONLY, 13861 userId); 13862 13863 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13864 } 13865 13866 private String getDefaultDialerPackageName(int userId) { 13867 synchronized (mPackages) { 13868 return mSettings.getDefaultDialerPackageNameLPw(userId); 13869 } 13870 } 13871 13872 @Override 13873 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13874 mContext.enforceCallingOrSelfPermission( 13875 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13876 "Only package verification agents can verify applications"); 13877 13878 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13879 final PackageVerificationResponse response = new PackageVerificationResponse( 13880 verificationCode, Binder.getCallingUid()); 13881 msg.arg1 = id; 13882 msg.obj = response; 13883 mHandler.sendMessage(msg); 13884 } 13885 13886 @Override 13887 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13888 long millisecondsToDelay) { 13889 mContext.enforceCallingOrSelfPermission( 13890 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13891 "Only package verification agents can extend verification timeouts"); 13892 13893 final PackageVerificationState state = mPendingVerification.get(id); 13894 final PackageVerificationResponse response = new PackageVerificationResponse( 13895 verificationCodeAtTimeout, Binder.getCallingUid()); 13896 13897 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13898 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13899 } 13900 if (millisecondsToDelay < 0) { 13901 millisecondsToDelay = 0; 13902 } 13903 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13904 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13905 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13906 } 13907 13908 if ((state != null) && !state.timeoutExtended()) { 13909 state.extendTimeout(); 13910 13911 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13912 msg.arg1 = id; 13913 msg.obj = response; 13914 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13915 } 13916 } 13917 13918 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13919 int verificationCode, UserHandle user) { 13920 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13921 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13922 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13923 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13924 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13925 13926 mContext.sendBroadcastAsUser(intent, user, 13927 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13928 } 13929 13930 private ComponentName matchComponentForVerifier(String packageName, 13931 List<ResolveInfo> receivers) { 13932 ActivityInfo targetReceiver = null; 13933 13934 final int NR = receivers.size(); 13935 for (int i = 0; i < NR; i++) { 13936 final ResolveInfo info = receivers.get(i); 13937 if (info.activityInfo == null) { 13938 continue; 13939 } 13940 13941 if (packageName.equals(info.activityInfo.packageName)) { 13942 targetReceiver = info.activityInfo; 13943 break; 13944 } 13945 } 13946 13947 if (targetReceiver == null) { 13948 return null; 13949 } 13950 13951 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13952 } 13953 13954 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13955 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13956 if (pkgInfo.verifiers.length == 0) { 13957 return null; 13958 } 13959 13960 final int N = pkgInfo.verifiers.length; 13961 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13962 for (int i = 0; i < N; i++) { 13963 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13964 13965 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13966 receivers); 13967 if (comp == null) { 13968 continue; 13969 } 13970 13971 final int verifierUid = getUidForVerifier(verifierInfo); 13972 if (verifierUid == -1) { 13973 continue; 13974 } 13975 13976 if (DEBUG_VERIFY) { 13977 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13978 + " with the correct signature"); 13979 } 13980 sufficientVerifiers.add(comp); 13981 verificationState.addSufficientVerifier(verifierUid); 13982 } 13983 13984 return sufficientVerifiers; 13985 } 13986 13987 private int getUidForVerifier(VerifierInfo verifierInfo) { 13988 synchronized (mPackages) { 13989 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13990 if (pkg == null) { 13991 return -1; 13992 } else if (pkg.mSigningDetails.signatures.length != 1) { 13993 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13994 + " has more than one signature; ignoring"); 13995 return -1; 13996 } 13997 13998 /* 13999 * If the public key of the package's signature does not match 14000 * our expected public key, then this is a different package and 14001 * we should skip. 14002 */ 14003 14004 final byte[] expectedPublicKey; 14005 try { 14006 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14007 final PublicKey publicKey = verifierSig.getPublicKey(); 14008 expectedPublicKey = publicKey.getEncoded(); 14009 } catch (CertificateException e) { 14010 return -1; 14011 } 14012 14013 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14014 14015 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14016 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14017 + " does not have the expected public key; ignoring"); 14018 return -1; 14019 } 14020 14021 return pkg.applicationInfo.uid; 14022 } 14023 } 14024 14025 @Override 14026 public void finishPackageInstall(int token, boolean didLaunch) { 14027 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14028 14029 if (DEBUG_INSTALL) { 14030 Slog.v(TAG, "BM finishing package install for " + token); 14031 } 14032 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14033 14034 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14035 mHandler.sendMessage(msg); 14036 } 14037 14038 /** 14039 * Get the verification agent timeout. Used for both the APK verifier and the 14040 * intent filter verifier. 14041 * 14042 * @return verification timeout in milliseconds 14043 */ 14044 private long getVerificationTimeout() { 14045 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14046 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14047 DEFAULT_VERIFICATION_TIMEOUT); 14048 } 14049 14050 /** 14051 * Get the default verification agent response code. 14052 * 14053 * @return default verification response code 14054 */ 14055 private int getDefaultVerificationResponse(UserHandle user) { 14056 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14057 return PackageManager.VERIFICATION_REJECT; 14058 } 14059 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14060 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14061 DEFAULT_VERIFICATION_RESPONSE); 14062 } 14063 14064 /** 14065 * Check whether or not package verification has been enabled. 14066 * 14067 * @return true if verification should be performed 14068 */ 14069 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14070 if (!DEFAULT_VERIFY_ENABLE) { 14071 return false; 14072 } 14073 14074 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14075 14076 // Check if installing from ADB 14077 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14078 // Do not run verification in a test harness environment 14079 if (ActivityManager.isRunningInTestHarness()) { 14080 return false; 14081 } 14082 if (ensureVerifyAppsEnabled) { 14083 return true; 14084 } 14085 // Check if the developer does not want package verification for ADB installs 14086 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14087 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14088 return false; 14089 } 14090 } else { 14091 // only when not installed from ADB, skip verification for instant apps when 14092 // the installer and verifier are the same. 14093 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14094 if (mInstantAppInstallerActivity != null 14095 && mInstantAppInstallerActivity.packageName.equals( 14096 mRequiredVerifierPackage)) { 14097 try { 14098 mContext.getSystemService(AppOpsManager.class) 14099 .checkPackage(installerUid, mRequiredVerifierPackage); 14100 if (DEBUG_VERIFY) { 14101 Slog.i(TAG, "disable verification for instant app"); 14102 } 14103 return false; 14104 } catch (SecurityException ignore) { } 14105 } 14106 } 14107 } 14108 14109 if (ensureVerifyAppsEnabled) { 14110 return true; 14111 } 14112 14113 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14114 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14115 } 14116 14117 @Override 14118 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14119 throws RemoteException { 14120 mContext.enforceCallingOrSelfPermission( 14121 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14122 "Only intentfilter verification agents can verify applications"); 14123 14124 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14125 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14126 Binder.getCallingUid(), verificationCode, failedDomains); 14127 msg.arg1 = id; 14128 msg.obj = response; 14129 mHandler.sendMessage(msg); 14130 } 14131 14132 @Override 14133 public int getIntentVerificationStatus(String packageName, int userId) { 14134 final int callingUid = Binder.getCallingUid(); 14135 if (UserHandle.getUserId(callingUid) != userId) { 14136 mContext.enforceCallingOrSelfPermission( 14137 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14138 "getIntentVerificationStatus" + userId); 14139 } 14140 if (getInstantAppPackageName(callingUid) != null) { 14141 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14142 } 14143 synchronized (mPackages) { 14144 final PackageSetting ps = mSettings.mPackages.get(packageName); 14145 if (ps == null 14146 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14147 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14148 } 14149 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14150 } 14151 } 14152 14153 @Override 14154 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14155 mContext.enforceCallingOrSelfPermission( 14156 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14157 14158 boolean result = false; 14159 synchronized (mPackages) { 14160 final PackageSetting ps = mSettings.mPackages.get(packageName); 14161 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14162 return false; 14163 } 14164 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14165 } 14166 if (result) { 14167 scheduleWritePackageRestrictionsLocked(userId); 14168 } 14169 return result; 14170 } 14171 14172 @Override 14173 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14174 String packageName) { 14175 final int callingUid = Binder.getCallingUid(); 14176 if (getInstantAppPackageName(callingUid) != null) { 14177 return ParceledListSlice.emptyList(); 14178 } 14179 synchronized (mPackages) { 14180 final PackageSetting ps = mSettings.mPackages.get(packageName); 14181 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14182 return ParceledListSlice.emptyList(); 14183 } 14184 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14185 } 14186 } 14187 14188 @Override 14189 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14190 if (TextUtils.isEmpty(packageName)) { 14191 return ParceledListSlice.emptyList(); 14192 } 14193 final int callingUid = Binder.getCallingUid(); 14194 final int callingUserId = UserHandle.getUserId(callingUid); 14195 synchronized (mPackages) { 14196 PackageParser.Package pkg = mPackages.get(packageName); 14197 if (pkg == null || pkg.activities == null) { 14198 return ParceledListSlice.emptyList(); 14199 } 14200 if (pkg.mExtras == null) { 14201 return ParceledListSlice.emptyList(); 14202 } 14203 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14204 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14205 return ParceledListSlice.emptyList(); 14206 } 14207 final int count = pkg.activities.size(); 14208 ArrayList<IntentFilter> result = new ArrayList<>(); 14209 for (int n=0; n<count; n++) { 14210 PackageParser.Activity activity = pkg.activities.get(n); 14211 if (activity.intents != null && activity.intents.size() > 0) { 14212 result.addAll(activity.intents); 14213 } 14214 } 14215 return new ParceledListSlice<>(result); 14216 } 14217 } 14218 14219 @Override 14220 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14221 mContext.enforceCallingOrSelfPermission( 14222 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14223 if (UserHandle.getCallingUserId() != userId) { 14224 mContext.enforceCallingOrSelfPermission( 14225 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14226 } 14227 14228 synchronized (mPackages) { 14229 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14230 if (packageName != null) { 14231 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14232 packageName, userId); 14233 } 14234 return result; 14235 } 14236 } 14237 14238 @Override 14239 public String getDefaultBrowserPackageName(int userId) { 14240 if (UserHandle.getCallingUserId() != userId) { 14241 mContext.enforceCallingOrSelfPermission( 14242 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14243 } 14244 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14245 return null; 14246 } 14247 synchronized (mPackages) { 14248 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14249 } 14250 } 14251 14252 /** 14253 * Get the "allow unknown sources" setting. 14254 * 14255 * @return the current "allow unknown sources" setting 14256 */ 14257 private int getUnknownSourcesSettings() { 14258 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14259 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14260 -1); 14261 } 14262 14263 @Override 14264 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14265 final int callingUid = Binder.getCallingUid(); 14266 if (getInstantAppPackageName(callingUid) != null) { 14267 return; 14268 } 14269 // writer 14270 synchronized (mPackages) { 14271 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14272 if (targetPackageSetting == null 14273 || filterAppAccessLPr( 14274 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14275 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14276 } 14277 14278 PackageSetting installerPackageSetting; 14279 if (installerPackageName != null) { 14280 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14281 if (installerPackageSetting == null) { 14282 throw new IllegalArgumentException("Unknown installer package: " 14283 + installerPackageName); 14284 } 14285 } else { 14286 installerPackageSetting = null; 14287 } 14288 14289 Signature[] callerSignature; 14290 Object obj = mSettings.getUserIdLPr(callingUid); 14291 if (obj != null) { 14292 if (obj instanceof SharedUserSetting) { 14293 callerSignature = 14294 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14295 } else if (obj instanceof PackageSetting) { 14296 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14297 } else { 14298 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14299 } 14300 } else { 14301 throw new SecurityException("Unknown calling UID: " + callingUid); 14302 } 14303 14304 // Verify: can't set installerPackageName to a package that is 14305 // not signed with the same cert as the caller. 14306 if (installerPackageSetting != null) { 14307 if (compareSignatures(callerSignature, 14308 installerPackageSetting.signatures.mSigningDetails.signatures) 14309 != PackageManager.SIGNATURE_MATCH) { 14310 throw new SecurityException( 14311 "Caller does not have same cert as new installer package " 14312 + installerPackageName); 14313 } 14314 } 14315 14316 // Verify: if target already has an installer package, it must 14317 // be signed with the same cert as the caller. 14318 if (targetPackageSetting.installerPackageName != null) { 14319 PackageSetting setting = mSettings.mPackages.get( 14320 targetPackageSetting.installerPackageName); 14321 // If the currently set package isn't valid, then it's always 14322 // okay to change it. 14323 if (setting != null) { 14324 if (compareSignatures(callerSignature, 14325 setting.signatures.mSigningDetails.signatures) 14326 != PackageManager.SIGNATURE_MATCH) { 14327 throw new SecurityException( 14328 "Caller does not have same cert as old installer package " 14329 + targetPackageSetting.installerPackageName); 14330 } 14331 } 14332 } 14333 14334 // Okay! 14335 targetPackageSetting.installerPackageName = installerPackageName; 14336 if (installerPackageName != null) { 14337 mSettings.mInstallerPackages.add(installerPackageName); 14338 } 14339 scheduleWriteSettingsLocked(); 14340 } 14341 } 14342 14343 @Override 14344 public void setApplicationCategoryHint(String packageName, int categoryHint, 14345 String callerPackageName) { 14346 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14347 throw new SecurityException("Instant applications don't have access to this method"); 14348 } 14349 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14350 callerPackageName); 14351 synchronized (mPackages) { 14352 PackageSetting ps = mSettings.mPackages.get(packageName); 14353 if (ps == null) { 14354 throw new IllegalArgumentException("Unknown target package " + packageName); 14355 } 14356 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14357 throw new IllegalArgumentException("Unknown target package " + packageName); 14358 } 14359 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14360 throw new IllegalArgumentException("Calling package " + callerPackageName 14361 + " is not installer for " + packageName); 14362 } 14363 14364 if (ps.categoryHint != categoryHint) { 14365 ps.categoryHint = categoryHint; 14366 scheduleWriteSettingsLocked(); 14367 } 14368 } 14369 } 14370 14371 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14372 // Queue up an async operation since the package installation may take a little while. 14373 mHandler.post(new Runnable() { 14374 public void run() { 14375 mHandler.removeCallbacks(this); 14376 // Result object to be returned 14377 PackageInstalledInfo res = new PackageInstalledInfo(); 14378 res.setReturnCode(currentStatus); 14379 res.uid = -1; 14380 res.pkg = null; 14381 res.removedInfo = null; 14382 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14383 args.doPreInstall(res.returnCode); 14384 synchronized (mInstallLock) { 14385 installPackageTracedLI(args, res); 14386 } 14387 args.doPostInstall(res.returnCode, res.uid); 14388 } 14389 14390 // A restore should be performed at this point if (a) the install 14391 // succeeded, (b) the operation is not an update, and (c) the new 14392 // package has not opted out of backup participation. 14393 final boolean update = res.removedInfo != null 14394 && res.removedInfo.removedPackage != null; 14395 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14396 boolean doRestore = !update 14397 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14398 14399 // Set up the post-install work request bookkeeping. This will be used 14400 // and cleaned up by the post-install event handling regardless of whether 14401 // there's a restore pass performed. Token values are >= 1. 14402 int token; 14403 if (mNextInstallToken < 0) mNextInstallToken = 1; 14404 token = mNextInstallToken++; 14405 14406 PostInstallData data = new PostInstallData(args, res); 14407 mRunningInstalls.put(token, data); 14408 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14409 14410 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14411 // Pass responsibility to the Backup Manager. It will perform a 14412 // restore if appropriate, then pass responsibility back to the 14413 // Package Manager to run the post-install observer callbacks 14414 // and broadcasts. 14415 IBackupManager bm = IBackupManager.Stub.asInterface( 14416 ServiceManager.getService(Context.BACKUP_SERVICE)); 14417 if (bm != null) { 14418 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14419 + " to BM for possible restore"); 14420 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14421 try { 14422 // TODO: http://b/22388012 14423 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14424 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14425 } else { 14426 doRestore = false; 14427 } 14428 } catch (RemoteException e) { 14429 // can't happen; the backup manager is local 14430 } catch (Exception e) { 14431 Slog.e(TAG, "Exception trying to enqueue restore", e); 14432 doRestore = false; 14433 } 14434 } else { 14435 Slog.e(TAG, "Backup Manager not found!"); 14436 doRestore = false; 14437 } 14438 } 14439 14440 if (!doRestore) { 14441 // No restore possible, or the Backup Manager was mysteriously not 14442 // available -- just fire the post-install work request directly. 14443 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14444 14445 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14446 14447 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14448 mHandler.sendMessage(msg); 14449 } 14450 } 14451 }); 14452 } 14453 14454 /** 14455 * Callback from PackageSettings whenever an app is first transitioned out of the 14456 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14457 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14458 * here whether the app is the target of an ongoing install, and only send the 14459 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14460 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14461 * handling. 14462 */ 14463 void notifyFirstLaunch(final String packageName, final String installerPackage, 14464 final int userId) { 14465 // Serialize this with the rest of the install-process message chain. In the 14466 // restore-at-install case, this Runnable will necessarily run before the 14467 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14468 // are coherent. In the non-restore case, the app has already completed install 14469 // and been launched through some other means, so it is not in a problematic 14470 // state for observers to see the FIRST_LAUNCH signal. 14471 mHandler.post(new Runnable() { 14472 @Override 14473 public void run() { 14474 for (int i = 0; i < mRunningInstalls.size(); i++) { 14475 final PostInstallData data = mRunningInstalls.valueAt(i); 14476 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14477 continue; 14478 } 14479 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14480 // right package; but is it for the right user? 14481 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14482 if (userId == data.res.newUsers[uIndex]) { 14483 if (DEBUG_BACKUP) { 14484 Slog.i(TAG, "Package " + packageName 14485 + " being restored so deferring FIRST_LAUNCH"); 14486 } 14487 return; 14488 } 14489 } 14490 } 14491 } 14492 // didn't find it, so not being restored 14493 if (DEBUG_BACKUP) { 14494 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14495 } 14496 final boolean isInstantApp = isInstantApp(packageName, userId); 14497 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14498 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14499 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14500 } 14501 }); 14502 } 14503 14504 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14505 int[] userIds, int[] instantUserIds) { 14506 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14507 installerPkg, null, userIds, instantUserIds); 14508 } 14509 14510 private abstract class HandlerParams { 14511 private static final int MAX_RETRIES = 4; 14512 14513 /** 14514 * Number of times startCopy() has been attempted and had a non-fatal 14515 * error. 14516 */ 14517 private int mRetries = 0; 14518 14519 /** User handle for the user requesting the information or installation. */ 14520 private final UserHandle mUser; 14521 String traceMethod; 14522 int traceCookie; 14523 14524 HandlerParams(UserHandle user) { 14525 mUser = user; 14526 } 14527 14528 UserHandle getUser() { 14529 return mUser; 14530 } 14531 14532 HandlerParams setTraceMethod(String traceMethod) { 14533 this.traceMethod = traceMethod; 14534 return this; 14535 } 14536 14537 HandlerParams setTraceCookie(int traceCookie) { 14538 this.traceCookie = traceCookie; 14539 return this; 14540 } 14541 14542 final boolean startCopy() { 14543 boolean res; 14544 try { 14545 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14546 14547 if (++mRetries > MAX_RETRIES) { 14548 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14549 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14550 handleServiceError(); 14551 return false; 14552 } else { 14553 handleStartCopy(); 14554 res = true; 14555 } 14556 } catch (RemoteException e) { 14557 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14558 mHandler.sendEmptyMessage(MCS_RECONNECT); 14559 res = false; 14560 } 14561 handleReturnCode(); 14562 return res; 14563 } 14564 14565 final void serviceError() { 14566 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14567 handleServiceError(); 14568 handleReturnCode(); 14569 } 14570 14571 abstract void handleStartCopy() throws RemoteException; 14572 abstract void handleServiceError(); 14573 abstract void handleReturnCode(); 14574 } 14575 14576 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14577 for (File path : paths) { 14578 try { 14579 mcs.clearDirectory(path.getAbsolutePath()); 14580 } catch (RemoteException e) { 14581 } 14582 } 14583 } 14584 14585 static class OriginInfo { 14586 /** 14587 * Location where install is coming from, before it has been 14588 * copied/renamed into place. This could be a single monolithic APK 14589 * file, or a cluster directory. This location may be untrusted. 14590 */ 14591 final File file; 14592 14593 /** 14594 * Flag indicating that {@link #file} or {@link #cid} has already been 14595 * staged, meaning downstream users don't need to defensively copy the 14596 * contents. 14597 */ 14598 final boolean staged; 14599 14600 /** 14601 * Flag indicating that {@link #file} or {@link #cid} is an already 14602 * installed app that is being moved. 14603 */ 14604 final boolean existing; 14605 14606 final String resolvedPath; 14607 final File resolvedFile; 14608 14609 static OriginInfo fromNothing() { 14610 return new OriginInfo(null, false, false); 14611 } 14612 14613 static OriginInfo fromUntrustedFile(File file) { 14614 return new OriginInfo(file, false, false); 14615 } 14616 14617 static OriginInfo fromExistingFile(File file) { 14618 return new OriginInfo(file, false, true); 14619 } 14620 14621 static OriginInfo fromStagedFile(File file) { 14622 return new OriginInfo(file, true, false); 14623 } 14624 14625 private OriginInfo(File file, boolean staged, boolean existing) { 14626 this.file = file; 14627 this.staged = staged; 14628 this.existing = existing; 14629 14630 if (file != null) { 14631 resolvedPath = file.getAbsolutePath(); 14632 resolvedFile = file; 14633 } else { 14634 resolvedPath = null; 14635 resolvedFile = null; 14636 } 14637 } 14638 } 14639 14640 static class MoveInfo { 14641 final int moveId; 14642 final String fromUuid; 14643 final String toUuid; 14644 final String packageName; 14645 final String dataAppName; 14646 final int appId; 14647 final String seinfo; 14648 final int targetSdkVersion; 14649 14650 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14651 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14652 this.moveId = moveId; 14653 this.fromUuid = fromUuid; 14654 this.toUuid = toUuid; 14655 this.packageName = packageName; 14656 this.dataAppName = dataAppName; 14657 this.appId = appId; 14658 this.seinfo = seinfo; 14659 this.targetSdkVersion = targetSdkVersion; 14660 } 14661 } 14662 14663 static class VerificationInfo { 14664 /** A constant used to indicate that a uid value is not present. */ 14665 public static final int NO_UID = -1; 14666 14667 /** URI referencing where the package was downloaded from. */ 14668 final Uri originatingUri; 14669 14670 /** HTTP referrer URI associated with the originatingURI. */ 14671 final Uri referrer; 14672 14673 /** UID of the application that the install request originated from. */ 14674 final int originatingUid; 14675 14676 /** UID of application requesting the install */ 14677 final int installerUid; 14678 14679 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14680 this.originatingUri = originatingUri; 14681 this.referrer = referrer; 14682 this.originatingUid = originatingUid; 14683 this.installerUid = installerUid; 14684 } 14685 } 14686 14687 class InstallParams extends HandlerParams { 14688 final OriginInfo origin; 14689 final MoveInfo move; 14690 final IPackageInstallObserver2 observer; 14691 int installFlags; 14692 final String installerPackageName; 14693 final String volumeUuid; 14694 private InstallArgs mArgs; 14695 private int mRet; 14696 final String packageAbiOverride; 14697 final String[] grantedRuntimePermissions; 14698 final VerificationInfo verificationInfo; 14699 final PackageParser.SigningDetails signingDetails; 14700 final int installReason; 14701 14702 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14703 int installFlags, String installerPackageName, String volumeUuid, 14704 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14705 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14706 super(user); 14707 this.origin = origin; 14708 this.move = move; 14709 this.observer = observer; 14710 this.installFlags = installFlags; 14711 this.installerPackageName = installerPackageName; 14712 this.volumeUuid = volumeUuid; 14713 this.verificationInfo = verificationInfo; 14714 this.packageAbiOverride = packageAbiOverride; 14715 this.grantedRuntimePermissions = grantedPermissions; 14716 this.signingDetails = signingDetails; 14717 this.installReason = installReason; 14718 } 14719 14720 @Override 14721 public String toString() { 14722 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14723 + " file=" + origin.file + "}"; 14724 } 14725 14726 private int installLocationPolicy(PackageInfoLite pkgLite) { 14727 String packageName = pkgLite.packageName; 14728 int installLocation = pkgLite.installLocation; 14729 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14730 // reader 14731 synchronized (mPackages) { 14732 // Currently installed package which the new package is attempting to replace or 14733 // null if no such package is installed. 14734 PackageParser.Package installedPkg = mPackages.get(packageName); 14735 // Package which currently owns the data which the new package will own if installed. 14736 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14737 // will be null whereas dataOwnerPkg will contain information about the package 14738 // which was uninstalled while keeping its data. 14739 PackageParser.Package dataOwnerPkg = installedPkg; 14740 if (dataOwnerPkg == null) { 14741 PackageSetting ps = mSettings.mPackages.get(packageName); 14742 if (ps != null) { 14743 dataOwnerPkg = ps.pkg; 14744 } 14745 } 14746 14747 if (dataOwnerPkg != null) { 14748 // If installed, the package will get access to data left on the device by its 14749 // predecessor. As a security measure, this is permited only if this is not a 14750 // version downgrade or if the predecessor package is marked as debuggable and 14751 // a downgrade is explicitly requested. 14752 // 14753 // On debuggable platform builds, downgrades are permitted even for 14754 // non-debuggable packages to make testing easier. Debuggable platform builds do 14755 // not offer security guarantees and thus it's OK to disable some security 14756 // mechanisms to make debugging/testing easier on those builds. However, even on 14757 // debuggable builds downgrades of packages are permitted only if requested via 14758 // installFlags. This is because we aim to keep the behavior of debuggable 14759 // platform builds as close as possible to the behavior of non-debuggable 14760 // platform builds. 14761 final boolean downgradeRequested = 14762 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14763 final boolean packageDebuggable = 14764 (dataOwnerPkg.applicationInfo.flags 14765 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14766 final boolean downgradePermitted = 14767 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14768 if (!downgradePermitted) { 14769 try { 14770 checkDowngrade(dataOwnerPkg, pkgLite); 14771 } catch (PackageManagerException e) { 14772 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14773 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14774 } 14775 } 14776 } 14777 14778 if (installedPkg != null) { 14779 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14780 // Check for updated system application. 14781 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14782 if (onSd) { 14783 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14784 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14785 } 14786 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14787 } else { 14788 if (onSd) { 14789 // Install flag overrides everything. 14790 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14791 } 14792 // If current upgrade specifies particular preference 14793 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14794 // Application explicitly specified internal. 14795 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14796 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14797 // App explictly prefers external. Let policy decide 14798 } else { 14799 // Prefer previous location 14800 if (isExternal(installedPkg)) { 14801 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14802 } 14803 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14804 } 14805 } 14806 } else { 14807 // Invalid install. Return error code 14808 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14809 } 14810 } 14811 } 14812 // All the special cases have been taken care of. 14813 // Return result based on recommended install location. 14814 if (onSd) { 14815 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14816 } 14817 return pkgLite.recommendedInstallLocation; 14818 } 14819 14820 /* 14821 * Invoke remote method to get package information and install 14822 * location values. Override install location based on default 14823 * policy if needed and then create install arguments based 14824 * on the install location. 14825 */ 14826 public void handleStartCopy() throws RemoteException { 14827 int ret = PackageManager.INSTALL_SUCCEEDED; 14828 14829 // If we're already staged, we've firmly committed to an install location 14830 if (origin.staged) { 14831 if (origin.file != null) { 14832 installFlags |= PackageManager.INSTALL_INTERNAL; 14833 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14834 } else { 14835 throw new IllegalStateException("Invalid stage location"); 14836 } 14837 } 14838 14839 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14840 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14841 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14842 PackageInfoLite pkgLite = null; 14843 14844 if (onInt && onSd) { 14845 // Check if both bits are set. 14846 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14847 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14848 } else if (onSd && ephemeral) { 14849 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14850 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14851 } else { 14852 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14853 packageAbiOverride); 14854 14855 if (DEBUG_EPHEMERAL && ephemeral) { 14856 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14857 } 14858 14859 /* 14860 * If we have too little free space, try to free cache 14861 * before giving up. 14862 */ 14863 if (!origin.staged && pkgLite.recommendedInstallLocation 14864 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14865 // TODO: focus freeing disk space on the target device 14866 final StorageManager storage = StorageManager.from(mContext); 14867 final long lowThreshold = storage.getStorageLowBytes( 14868 Environment.getDataDirectory()); 14869 14870 final long sizeBytes = mContainerService.calculateInstalledSize( 14871 origin.resolvedPath, packageAbiOverride); 14872 14873 try { 14874 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14875 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14876 installFlags, packageAbiOverride); 14877 } catch (InstallerException e) { 14878 Slog.w(TAG, "Failed to free cache", e); 14879 } 14880 14881 /* 14882 * The cache free must have deleted the file we 14883 * downloaded to install. 14884 * 14885 * TODO: fix the "freeCache" call to not delete 14886 * the file we care about. 14887 */ 14888 if (pkgLite.recommendedInstallLocation 14889 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14890 pkgLite.recommendedInstallLocation 14891 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14892 } 14893 } 14894 } 14895 14896 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14897 int loc = pkgLite.recommendedInstallLocation; 14898 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14899 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14900 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14901 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14902 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14903 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14904 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14905 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14906 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14907 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14908 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14909 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14910 } else { 14911 // Override with defaults if needed. 14912 loc = installLocationPolicy(pkgLite); 14913 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14914 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14915 } else if (!onSd && !onInt) { 14916 // Override install location with flags 14917 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14918 // Set the flag to install on external media. 14919 installFlags |= PackageManager.INSTALL_EXTERNAL; 14920 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14921 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14922 if (DEBUG_EPHEMERAL) { 14923 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14924 } 14925 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14926 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14927 |PackageManager.INSTALL_INTERNAL); 14928 } else { 14929 // Make sure the flag for installing on external 14930 // media is unset 14931 installFlags |= PackageManager.INSTALL_INTERNAL; 14932 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14933 } 14934 } 14935 } 14936 } 14937 14938 final InstallArgs args = createInstallArgs(this); 14939 mArgs = args; 14940 14941 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14942 // TODO: http://b/22976637 14943 // Apps installed for "all" users use the device owner to verify the app 14944 UserHandle verifierUser = getUser(); 14945 if (verifierUser == UserHandle.ALL) { 14946 verifierUser = UserHandle.SYSTEM; 14947 } 14948 14949 /* 14950 * Determine if we have any installed package verifiers. If we 14951 * do, then we'll defer to them to verify the packages. 14952 */ 14953 final int requiredUid = mRequiredVerifierPackage == null ? -1 14954 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14955 verifierUser.getIdentifier()); 14956 final int installerUid = 14957 verificationInfo == null ? -1 : verificationInfo.installerUid; 14958 if (!origin.existing && requiredUid != -1 14959 && isVerificationEnabled( 14960 verifierUser.getIdentifier(), installFlags, installerUid)) { 14961 final Intent verification = new Intent( 14962 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14963 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14964 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14965 PACKAGE_MIME_TYPE); 14966 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14967 14968 // Query all live verifiers based on current user state 14969 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14970 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14971 false /*allowDynamicSplits*/); 14972 14973 if (DEBUG_VERIFY) { 14974 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14975 + verification.toString() + " with " + pkgLite.verifiers.length 14976 + " optional verifiers"); 14977 } 14978 14979 final int verificationId = mPendingVerificationToken++; 14980 14981 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14982 14983 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14984 installerPackageName); 14985 14986 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14987 installFlags); 14988 14989 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14990 pkgLite.packageName); 14991 14992 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14993 pkgLite.versionCode); 14994 14995 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 14996 pkgLite.getLongVersionCode()); 14997 14998 if (verificationInfo != null) { 14999 if (verificationInfo.originatingUri != null) { 15000 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15001 verificationInfo.originatingUri); 15002 } 15003 if (verificationInfo.referrer != null) { 15004 verification.putExtra(Intent.EXTRA_REFERRER, 15005 verificationInfo.referrer); 15006 } 15007 if (verificationInfo.originatingUid >= 0) { 15008 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15009 verificationInfo.originatingUid); 15010 } 15011 if (verificationInfo.installerUid >= 0) { 15012 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15013 verificationInfo.installerUid); 15014 } 15015 } 15016 15017 final PackageVerificationState verificationState = new PackageVerificationState( 15018 requiredUid, args); 15019 15020 mPendingVerification.append(verificationId, verificationState); 15021 15022 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15023 receivers, verificationState); 15024 15025 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15026 final long idleDuration = getVerificationTimeout(); 15027 15028 /* 15029 * If any sufficient verifiers were listed in the package 15030 * manifest, attempt to ask them. 15031 */ 15032 if (sufficientVerifiers != null) { 15033 final int N = sufficientVerifiers.size(); 15034 if (N == 0) { 15035 Slog.i(TAG, "Additional verifiers required, but none installed."); 15036 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15037 } else { 15038 for (int i = 0; i < N; i++) { 15039 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15040 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15041 verifierComponent.getPackageName(), idleDuration, 15042 verifierUser.getIdentifier(), false, "package verifier"); 15043 15044 final Intent sufficientIntent = new Intent(verification); 15045 sufficientIntent.setComponent(verifierComponent); 15046 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15047 } 15048 } 15049 } 15050 15051 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15052 mRequiredVerifierPackage, receivers); 15053 if (ret == PackageManager.INSTALL_SUCCEEDED 15054 && mRequiredVerifierPackage != null) { 15055 Trace.asyncTraceBegin( 15056 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15057 /* 15058 * Send the intent to the required verification agent, 15059 * but only start the verification timeout after the 15060 * target BroadcastReceivers have run. 15061 */ 15062 verification.setComponent(requiredVerifierComponent); 15063 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15064 mRequiredVerifierPackage, idleDuration, 15065 verifierUser.getIdentifier(), false, "package verifier"); 15066 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15067 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15068 new BroadcastReceiver() { 15069 @Override 15070 public void onReceive(Context context, Intent intent) { 15071 final Message msg = mHandler 15072 .obtainMessage(CHECK_PENDING_VERIFICATION); 15073 msg.arg1 = verificationId; 15074 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15075 } 15076 }, null, 0, null, null); 15077 15078 /* 15079 * We don't want the copy to proceed until verification 15080 * succeeds, so null out this field. 15081 */ 15082 mArgs = null; 15083 } 15084 } else { 15085 /* 15086 * No package verification is enabled, so immediately start 15087 * the remote call to initiate copy using temporary file. 15088 */ 15089 ret = args.copyApk(mContainerService, true); 15090 } 15091 } 15092 15093 mRet = ret; 15094 } 15095 15096 @Override 15097 void handleReturnCode() { 15098 // If mArgs is null, then MCS couldn't be reached. When it 15099 // reconnects, it will try again to install. At that point, this 15100 // will succeed. 15101 if (mArgs != null) { 15102 processPendingInstall(mArgs, mRet); 15103 } 15104 } 15105 15106 @Override 15107 void handleServiceError() { 15108 mArgs = createInstallArgs(this); 15109 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15110 } 15111 } 15112 15113 private InstallArgs createInstallArgs(InstallParams params) { 15114 if (params.move != null) { 15115 return new MoveInstallArgs(params); 15116 } else { 15117 return new FileInstallArgs(params); 15118 } 15119 } 15120 15121 /** 15122 * Create args that describe an existing installed package. Typically used 15123 * when cleaning up old installs, or used as a move source. 15124 */ 15125 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15126 String resourcePath, String[] instructionSets) { 15127 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15128 } 15129 15130 static abstract class InstallArgs { 15131 /** @see InstallParams#origin */ 15132 final OriginInfo origin; 15133 /** @see InstallParams#move */ 15134 final MoveInfo move; 15135 15136 final IPackageInstallObserver2 observer; 15137 // Always refers to PackageManager flags only 15138 final int installFlags; 15139 final String installerPackageName; 15140 final String volumeUuid; 15141 final UserHandle user; 15142 final String abiOverride; 15143 final String[] installGrantPermissions; 15144 /** If non-null, drop an async trace when the install completes */ 15145 final String traceMethod; 15146 final int traceCookie; 15147 final PackageParser.SigningDetails signingDetails; 15148 final int installReason; 15149 15150 // The list of instruction sets supported by this app. This is currently 15151 // only used during the rmdex() phase to clean up resources. We can get rid of this 15152 // if we move dex files under the common app path. 15153 /* nullable */ String[] instructionSets; 15154 15155 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15156 int installFlags, String installerPackageName, String volumeUuid, 15157 UserHandle user, String[] instructionSets, 15158 String abiOverride, String[] installGrantPermissions, 15159 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15160 int installReason) { 15161 this.origin = origin; 15162 this.move = move; 15163 this.installFlags = installFlags; 15164 this.observer = observer; 15165 this.installerPackageName = installerPackageName; 15166 this.volumeUuid = volumeUuid; 15167 this.user = user; 15168 this.instructionSets = instructionSets; 15169 this.abiOverride = abiOverride; 15170 this.installGrantPermissions = installGrantPermissions; 15171 this.traceMethod = traceMethod; 15172 this.traceCookie = traceCookie; 15173 this.signingDetails = signingDetails; 15174 this.installReason = installReason; 15175 } 15176 15177 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15178 abstract int doPreInstall(int status); 15179 15180 /** 15181 * Rename package into final resting place. All paths on the given 15182 * scanned package should be updated to reflect the rename. 15183 */ 15184 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15185 abstract int doPostInstall(int status, int uid); 15186 15187 /** @see PackageSettingBase#codePathString */ 15188 abstract String getCodePath(); 15189 /** @see PackageSettingBase#resourcePathString */ 15190 abstract String getResourcePath(); 15191 15192 // Need installer lock especially for dex file removal. 15193 abstract void cleanUpResourcesLI(); 15194 abstract boolean doPostDeleteLI(boolean delete); 15195 15196 /** 15197 * Called before the source arguments are copied. This is used mostly 15198 * for MoveParams when it needs to read the source file to put it in the 15199 * destination. 15200 */ 15201 int doPreCopy() { 15202 return PackageManager.INSTALL_SUCCEEDED; 15203 } 15204 15205 /** 15206 * Called after the source arguments are copied. This is used mostly for 15207 * MoveParams when it needs to read the source file to put it in the 15208 * destination. 15209 */ 15210 int doPostCopy(int uid) { 15211 return PackageManager.INSTALL_SUCCEEDED; 15212 } 15213 15214 protected boolean isFwdLocked() { 15215 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15216 } 15217 15218 protected boolean isExternalAsec() { 15219 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15220 } 15221 15222 protected boolean isEphemeral() { 15223 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15224 } 15225 15226 UserHandle getUser() { 15227 return user; 15228 } 15229 } 15230 15231 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15232 if (!allCodePaths.isEmpty()) { 15233 if (instructionSets == null) { 15234 throw new IllegalStateException("instructionSet == null"); 15235 } 15236 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15237 for (String codePath : allCodePaths) { 15238 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15239 try { 15240 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15241 } catch (InstallerException ignored) { 15242 } 15243 } 15244 } 15245 } 15246 } 15247 15248 /** 15249 * Logic to handle installation of non-ASEC applications, including copying 15250 * and renaming logic. 15251 */ 15252 class FileInstallArgs extends InstallArgs { 15253 private File codeFile; 15254 private File resourceFile; 15255 15256 // Example topology: 15257 // /data/app/com.example/base.apk 15258 // /data/app/com.example/split_foo.apk 15259 // /data/app/com.example/lib/arm/libfoo.so 15260 // /data/app/com.example/lib/arm64/libfoo.so 15261 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15262 15263 /** New install */ 15264 FileInstallArgs(InstallParams params) { 15265 super(params.origin, params.move, params.observer, params.installFlags, 15266 params.installerPackageName, params.volumeUuid, 15267 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15268 params.grantedRuntimePermissions, 15269 params.traceMethod, params.traceCookie, params.signingDetails, 15270 params.installReason); 15271 if (isFwdLocked()) { 15272 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15273 } 15274 } 15275 15276 /** Existing install */ 15277 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15278 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15279 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15280 PackageManager.INSTALL_REASON_UNKNOWN); 15281 this.codeFile = (codePath != null) ? new File(codePath) : null; 15282 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15283 } 15284 15285 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15287 try { 15288 return doCopyApk(imcs, temp); 15289 } finally { 15290 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15291 } 15292 } 15293 15294 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15295 if (origin.staged) { 15296 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15297 codeFile = origin.file; 15298 resourceFile = origin.file; 15299 return PackageManager.INSTALL_SUCCEEDED; 15300 } 15301 15302 try { 15303 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15304 final File tempDir = 15305 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15306 codeFile = tempDir; 15307 resourceFile = tempDir; 15308 } catch (IOException e) { 15309 Slog.w(TAG, "Failed to create copy file: " + e); 15310 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15311 } 15312 15313 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15314 @Override 15315 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15316 if (!FileUtils.isValidExtFilename(name)) { 15317 throw new IllegalArgumentException("Invalid filename: " + name); 15318 } 15319 try { 15320 final File file = new File(codeFile, name); 15321 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15322 O_RDWR | O_CREAT, 0644); 15323 Os.chmod(file.getAbsolutePath(), 0644); 15324 return new ParcelFileDescriptor(fd); 15325 } catch (ErrnoException e) { 15326 throw new RemoteException("Failed to open: " + e.getMessage()); 15327 } 15328 } 15329 }; 15330 15331 int ret = PackageManager.INSTALL_SUCCEEDED; 15332 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15333 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15334 Slog.e(TAG, "Failed to copy package"); 15335 return ret; 15336 } 15337 15338 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15339 NativeLibraryHelper.Handle handle = null; 15340 try { 15341 handle = NativeLibraryHelper.Handle.create(codeFile); 15342 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15343 abiOverride); 15344 } catch (IOException e) { 15345 Slog.e(TAG, "Copying native libraries failed", e); 15346 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15347 } finally { 15348 IoUtils.closeQuietly(handle); 15349 } 15350 15351 return ret; 15352 } 15353 15354 int doPreInstall(int status) { 15355 if (status != PackageManager.INSTALL_SUCCEEDED) { 15356 cleanUp(); 15357 } 15358 return status; 15359 } 15360 15361 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15362 if (status != PackageManager.INSTALL_SUCCEEDED) { 15363 cleanUp(); 15364 return false; 15365 } 15366 15367 final File targetDir = codeFile.getParentFile(); 15368 final File beforeCodeFile = codeFile; 15369 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15370 15371 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15372 try { 15373 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15374 } catch (ErrnoException e) { 15375 Slog.w(TAG, "Failed to rename", e); 15376 return false; 15377 } 15378 15379 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15380 Slog.w(TAG, "Failed to restorecon"); 15381 return false; 15382 } 15383 15384 // Reflect the rename internally 15385 codeFile = afterCodeFile; 15386 resourceFile = afterCodeFile; 15387 15388 // Reflect the rename in scanned details 15389 try { 15390 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15391 } catch (IOException e) { 15392 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15393 return false; 15394 } 15395 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15396 afterCodeFile, pkg.baseCodePath)); 15397 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15398 afterCodeFile, pkg.splitCodePaths)); 15399 15400 // Reflect the rename in app info 15401 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15402 pkg.setApplicationInfoCodePath(pkg.codePath); 15403 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15404 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15405 pkg.setApplicationInfoResourcePath(pkg.codePath); 15406 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15407 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15408 15409 return true; 15410 } 15411 15412 int doPostInstall(int status, int uid) { 15413 if (status != PackageManager.INSTALL_SUCCEEDED) { 15414 cleanUp(); 15415 } 15416 return status; 15417 } 15418 15419 @Override 15420 String getCodePath() { 15421 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15422 } 15423 15424 @Override 15425 String getResourcePath() { 15426 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15427 } 15428 15429 private boolean cleanUp() { 15430 if (codeFile == null || !codeFile.exists()) { 15431 return false; 15432 } 15433 15434 removeCodePathLI(codeFile); 15435 15436 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15437 resourceFile.delete(); 15438 } 15439 15440 return true; 15441 } 15442 15443 void cleanUpResourcesLI() { 15444 // Try enumerating all code paths before deleting 15445 List<String> allCodePaths = Collections.EMPTY_LIST; 15446 if (codeFile != null && codeFile.exists()) { 15447 try { 15448 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15449 allCodePaths = pkg.getAllCodePaths(); 15450 } catch (PackageParserException e) { 15451 // Ignored; we tried our best 15452 } 15453 } 15454 15455 cleanUp(); 15456 removeDexFiles(allCodePaths, instructionSets); 15457 } 15458 15459 boolean doPostDeleteLI(boolean delete) { 15460 // XXX err, shouldn't we respect the delete flag? 15461 cleanUpResourcesLI(); 15462 return true; 15463 } 15464 } 15465 15466 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15467 PackageManagerException { 15468 if (copyRet < 0) { 15469 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15470 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15471 throw new PackageManagerException(copyRet, message); 15472 } 15473 } 15474 } 15475 15476 /** 15477 * Extract the StorageManagerService "container ID" from the full code path of an 15478 * .apk. 15479 */ 15480 static String cidFromCodePath(String fullCodePath) { 15481 int eidx = fullCodePath.lastIndexOf("/"); 15482 String subStr1 = fullCodePath.substring(0, eidx); 15483 int sidx = subStr1.lastIndexOf("/"); 15484 return subStr1.substring(sidx+1, eidx); 15485 } 15486 15487 /** 15488 * Logic to handle movement of existing installed applications. 15489 */ 15490 class MoveInstallArgs extends InstallArgs { 15491 private File codeFile; 15492 private File resourceFile; 15493 15494 /** New install */ 15495 MoveInstallArgs(InstallParams params) { 15496 super(params.origin, params.move, params.observer, params.installFlags, 15497 params.installerPackageName, params.volumeUuid, 15498 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15499 params.grantedRuntimePermissions, 15500 params.traceMethod, params.traceCookie, params.signingDetails, 15501 params.installReason); 15502 } 15503 15504 int copyApk(IMediaContainerService imcs, boolean temp) { 15505 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15506 + move.fromUuid + " to " + move.toUuid); 15507 synchronized (mInstaller) { 15508 try { 15509 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15510 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15511 } catch (InstallerException e) { 15512 Slog.w(TAG, "Failed to move app", e); 15513 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15514 } 15515 } 15516 15517 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15518 resourceFile = codeFile; 15519 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15520 15521 return PackageManager.INSTALL_SUCCEEDED; 15522 } 15523 15524 int doPreInstall(int status) { 15525 if (status != PackageManager.INSTALL_SUCCEEDED) { 15526 cleanUp(move.toUuid); 15527 } 15528 return status; 15529 } 15530 15531 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15532 if (status != PackageManager.INSTALL_SUCCEEDED) { 15533 cleanUp(move.toUuid); 15534 return false; 15535 } 15536 15537 // Reflect the move in app info 15538 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15539 pkg.setApplicationInfoCodePath(pkg.codePath); 15540 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15541 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15542 pkg.setApplicationInfoResourcePath(pkg.codePath); 15543 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15544 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15545 15546 return true; 15547 } 15548 15549 int doPostInstall(int status, int uid) { 15550 if (status == PackageManager.INSTALL_SUCCEEDED) { 15551 cleanUp(move.fromUuid); 15552 } else { 15553 cleanUp(move.toUuid); 15554 } 15555 return status; 15556 } 15557 15558 @Override 15559 String getCodePath() { 15560 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15561 } 15562 15563 @Override 15564 String getResourcePath() { 15565 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15566 } 15567 15568 private boolean cleanUp(String volumeUuid) { 15569 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15570 move.dataAppName); 15571 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15572 final int[] userIds = sUserManager.getUserIds(); 15573 synchronized (mInstallLock) { 15574 // Clean up both app data and code 15575 // All package moves are frozen until finished 15576 for (int userId : userIds) { 15577 try { 15578 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15579 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15580 } catch (InstallerException e) { 15581 Slog.w(TAG, String.valueOf(e)); 15582 } 15583 } 15584 removeCodePathLI(codeFile); 15585 } 15586 return true; 15587 } 15588 15589 void cleanUpResourcesLI() { 15590 throw new UnsupportedOperationException(); 15591 } 15592 15593 boolean doPostDeleteLI(boolean delete) { 15594 throw new UnsupportedOperationException(); 15595 } 15596 } 15597 15598 static String getAsecPackageName(String packageCid) { 15599 int idx = packageCid.lastIndexOf("-"); 15600 if (idx == -1) { 15601 return packageCid; 15602 } 15603 return packageCid.substring(0, idx); 15604 } 15605 15606 // Utility method used to create code paths based on package name and available index. 15607 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15608 String idxStr = ""; 15609 int idx = 1; 15610 // Fall back to default value of idx=1 if prefix is not 15611 // part of oldCodePath 15612 if (oldCodePath != null) { 15613 String subStr = oldCodePath; 15614 // Drop the suffix right away 15615 if (suffix != null && subStr.endsWith(suffix)) { 15616 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15617 } 15618 // If oldCodePath already contains prefix find out the 15619 // ending index to either increment or decrement. 15620 int sidx = subStr.lastIndexOf(prefix); 15621 if (sidx != -1) { 15622 subStr = subStr.substring(sidx + prefix.length()); 15623 if (subStr != null) { 15624 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15625 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15626 } 15627 try { 15628 idx = Integer.parseInt(subStr); 15629 if (idx <= 1) { 15630 idx++; 15631 } else { 15632 idx--; 15633 } 15634 } catch(NumberFormatException e) { 15635 } 15636 } 15637 } 15638 } 15639 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15640 return prefix + idxStr; 15641 } 15642 15643 private File getNextCodePath(File targetDir, String packageName) { 15644 File result; 15645 SecureRandom random = new SecureRandom(); 15646 byte[] bytes = new byte[16]; 15647 do { 15648 random.nextBytes(bytes); 15649 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15650 result = new File(targetDir, packageName + "-" + suffix); 15651 } while (result.exists()); 15652 return result; 15653 } 15654 15655 // Utility method that returns the relative package path with respect 15656 // to the installation directory. Like say for /data/data/com.test-1.apk 15657 // string com.test-1 is returned. 15658 static String deriveCodePathName(String codePath) { 15659 if (codePath == null) { 15660 return null; 15661 } 15662 final File codeFile = new File(codePath); 15663 final String name = codeFile.getName(); 15664 if (codeFile.isDirectory()) { 15665 return name; 15666 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15667 final int lastDot = name.lastIndexOf('.'); 15668 return name.substring(0, lastDot); 15669 } else { 15670 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15671 return null; 15672 } 15673 } 15674 15675 static class PackageInstalledInfo { 15676 String name; 15677 int uid; 15678 // The set of users that originally had this package installed. 15679 int[] origUsers; 15680 // The set of users that now have this package installed. 15681 int[] newUsers; 15682 PackageParser.Package pkg; 15683 int returnCode; 15684 String returnMsg; 15685 String installerPackageName; 15686 PackageRemovedInfo removedInfo; 15687 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15688 15689 public void setError(int code, String msg) { 15690 setReturnCode(code); 15691 setReturnMessage(msg); 15692 Slog.w(TAG, msg); 15693 } 15694 15695 public void setError(String msg, PackageParserException e) { 15696 setReturnCode(e.error); 15697 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15698 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15699 for (int i = 0; i < childCount; i++) { 15700 addedChildPackages.valueAt(i).setError(msg, e); 15701 } 15702 Slog.w(TAG, msg, e); 15703 } 15704 15705 public void setError(String msg, PackageManagerException e) { 15706 returnCode = e.error; 15707 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15708 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15709 for (int i = 0; i < childCount; i++) { 15710 addedChildPackages.valueAt(i).setError(msg, e); 15711 } 15712 Slog.w(TAG, msg, e); 15713 } 15714 15715 public void setReturnCode(int returnCode) { 15716 this.returnCode = returnCode; 15717 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15718 for (int i = 0; i < childCount; i++) { 15719 addedChildPackages.valueAt(i).returnCode = returnCode; 15720 } 15721 } 15722 15723 private void setReturnMessage(String returnMsg) { 15724 this.returnMsg = returnMsg; 15725 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15726 for (int i = 0; i < childCount; i++) { 15727 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15728 } 15729 } 15730 15731 // In some error cases we want to convey more info back to the observer 15732 String origPackage; 15733 String origPermission; 15734 } 15735 15736 /* 15737 * Install a non-existing package. 15738 */ 15739 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15740 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15741 String volumeUuid, PackageInstalledInfo res, int installReason) { 15742 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15743 15744 // Remember this for later, in case we need to rollback this install 15745 String pkgName = pkg.packageName; 15746 15747 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15748 15749 synchronized(mPackages) { 15750 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15751 if (renamedPackage != null) { 15752 // A package with the same name is already installed, though 15753 // it has been renamed to an older name. The package we 15754 // are trying to install should be installed as an update to 15755 // the existing one, but that has not been requested, so bail. 15756 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15757 + " without first uninstalling package running as " 15758 + renamedPackage); 15759 return; 15760 } 15761 if (mPackages.containsKey(pkgName)) { 15762 // Don't allow installation over an existing package with the same name. 15763 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15764 + " without first uninstalling."); 15765 return; 15766 } 15767 } 15768 15769 try { 15770 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15771 System.currentTimeMillis(), user); 15772 15773 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15774 15775 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15776 prepareAppDataAfterInstallLIF(newPackage); 15777 15778 } else { 15779 // Remove package from internal structures, but keep around any 15780 // data that might have already existed 15781 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15782 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15783 } 15784 } catch (PackageManagerException e) { 15785 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15786 } 15787 15788 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15789 } 15790 15791 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15792 try (DigestInputStream digestStream = 15793 new DigestInputStream(new FileInputStream(file), digest)) { 15794 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15795 } 15796 } 15797 15798 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15799 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15800 PackageInstalledInfo res, int installReason) { 15801 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15802 15803 final PackageParser.Package oldPackage; 15804 final PackageSetting ps; 15805 final String pkgName = pkg.packageName; 15806 final int[] allUsers; 15807 final int[] installedUsers; 15808 15809 synchronized(mPackages) { 15810 oldPackage = mPackages.get(pkgName); 15811 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15812 15813 // don't allow upgrade to target a release SDK from a pre-release SDK 15814 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15815 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15816 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15817 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15818 if (oldTargetsPreRelease 15819 && !newTargetsPreRelease 15820 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15821 Slog.w(TAG, "Can't install package targeting released sdk"); 15822 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15823 return; 15824 } 15825 15826 ps = mSettings.mPackages.get(pkgName); 15827 15828 // verify signatures are valid 15829 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15830 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15831 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15832 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15833 "New package not signed by keys specified by upgrade-keysets: " 15834 + pkgName); 15835 return; 15836 } 15837 } else { 15838 // default to original signature matching 15839 if (compareSignatures(oldPackage.mSigningDetails.signatures, 15840 pkg.mSigningDetails.signatures) 15841 != PackageManager.SIGNATURE_MATCH) { 15842 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15843 "New package has a different signature: " + pkgName); 15844 return; 15845 } 15846 } 15847 15848 // don't allow a system upgrade unless the upgrade hash matches 15849 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15850 byte[] digestBytes = null; 15851 try { 15852 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15853 updateDigest(digest, new File(pkg.baseCodePath)); 15854 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15855 for (String path : pkg.splitCodePaths) { 15856 updateDigest(digest, new File(path)); 15857 } 15858 } 15859 digestBytes = digest.digest(); 15860 } catch (NoSuchAlgorithmException | IOException e) { 15861 res.setError(INSTALL_FAILED_INVALID_APK, 15862 "Could not compute hash: " + pkgName); 15863 return; 15864 } 15865 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15866 res.setError(INSTALL_FAILED_INVALID_APK, 15867 "New package fails restrict-update check: " + pkgName); 15868 return; 15869 } 15870 // retain upgrade restriction 15871 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15872 } 15873 15874 // Check for shared user id changes 15875 String invalidPackageName = 15876 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15877 if (invalidPackageName != null) { 15878 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15879 "Package " + invalidPackageName + " tried to change user " 15880 + oldPackage.mSharedUserId); 15881 return; 15882 } 15883 15884 // check if the new package supports all of the abis which the old package supports 15885 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 15886 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 15887 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 15888 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15889 "Update to package " + pkgName + " doesn't support multi arch"); 15890 return; 15891 } 15892 15893 // In case of rollback, remember per-user/profile install state 15894 allUsers = sUserManager.getUserIds(); 15895 installedUsers = ps.queryInstalledUsers(allUsers, true); 15896 15897 // don't allow an upgrade from full to ephemeral 15898 if (isInstantApp) { 15899 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15900 for (int currentUser : allUsers) { 15901 if (!ps.getInstantApp(currentUser)) { 15902 // can't downgrade from full to instant 15903 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15904 + " for user: " + currentUser); 15905 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15906 return; 15907 } 15908 } 15909 } else if (!ps.getInstantApp(user.getIdentifier())) { 15910 // can't downgrade from full to instant 15911 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15912 + " for user: " + user.getIdentifier()); 15913 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15914 return; 15915 } 15916 } 15917 } 15918 15919 // Update what is removed 15920 res.removedInfo = new PackageRemovedInfo(this); 15921 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15922 res.removedInfo.removedPackage = oldPackage.packageName; 15923 res.removedInfo.installerPackageName = ps.installerPackageName; 15924 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15925 res.removedInfo.isUpdate = true; 15926 res.removedInfo.origUsers = installedUsers; 15927 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15928 for (int i = 0; i < installedUsers.length; i++) { 15929 final int userId = installedUsers[i]; 15930 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15931 } 15932 15933 final int childCount = (oldPackage.childPackages != null) 15934 ? oldPackage.childPackages.size() : 0; 15935 for (int i = 0; i < childCount; i++) { 15936 boolean childPackageUpdated = false; 15937 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15938 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15939 if (res.addedChildPackages != null) { 15940 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15941 if (childRes != null) { 15942 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15943 childRes.removedInfo.removedPackage = childPkg.packageName; 15944 if (childPs != null) { 15945 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15946 } 15947 childRes.removedInfo.isUpdate = true; 15948 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15949 childPackageUpdated = true; 15950 } 15951 } 15952 if (!childPackageUpdated) { 15953 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15954 childRemovedRes.removedPackage = childPkg.packageName; 15955 if (childPs != null) { 15956 childRemovedRes.installerPackageName = childPs.installerPackageName; 15957 } 15958 childRemovedRes.isUpdate = false; 15959 childRemovedRes.dataRemoved = true; 15960 synchronized (mPackages) { 15961 if (childPs != null) { 15962 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15963 } 15964 } 15965 if (res.removedInfo.removedChildPackages == null) { 15966 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15967 } 15968 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15969 } 15970 } 15971 15972 boolean sysPkg = (isSystemApp(oldPackage)); 15973 if (sysPkg) { 15974 // Set the system/privileged/oem/vendor flags as needed 15975 final boolean privileged = 15976 (oldPackage.applicationInfo.privateFlags 15977 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15978 final boolean oem = 15979 (oldPackage.applicationInfo.privateFlags 15980 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15981 final boolean vendor = 15982 (oldPackage.applicationInfo.privateFlags 15983 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 15984 final @ParseFlags int systemParseFlags = parseFlags; 15985 final @ScanFlags int systemScanFlags = scanFlags 15986 | SCAN_AS_SYSTEM 15987 | (privileged ? SCAN_AS_PRIVILEGED : 0) 15988 | (oem ? SCAN_AS_OEM : 0) 15989 | (vendor ? SCAN_AS_VENDOR : 0); 15990 15991 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 15992 user, allUsers, installerPackageName, res, installReason); 15993 } else { 15994 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 15995 user, allUsers, installerPackageName, res, installReason); 15996 } 15997 } 15998 15999 @Override 16000 public List<String> getPreviousCodePaths(String packageName) { 16001 final int callingUid = Binder.getCallingUid(); 16002 final List<String> result = new ArrayList<>(); 16003 if (getInstantAppPackageName(callingUid) != null) { 16004 return result; 16005 } 16006 final PackageSetting ps = mSettings.mPackages.get(packageName); 16007 if (ps != null 16008 && ps.oldCodePaths != null 16009 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16010 result.addAll(ps.oldCodePaths); 16011 } 16012 return result; 16013 } 16014 16015 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16016 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16017 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16018 String installerPackageName, PackageInstalledInfo res, int installReason) { 16019 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16020 + deletedPackage); 16021 16022 String pkgName = deletedPackage.packageName; 16023 boolean deletedPkg = true; 16024 boolean addedPkg = false; 16025 boolean updatedSettings = false; 16026 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16027 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16028 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16029 16030 final long origUpdateTime = (pkg.mExtras != null) 16031 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16032 16033 // First delete the existing package while retaining the data directory 16034 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16035 res.removedInfo, true, pkg)) { 16036 // If the existing package wasn't successfully deleted 16037 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16038 deletedPkg = false; 16039 } else { 16040 // Successfully deleted the old package; proceed with replace. 16041 16042 // If deleted package lived in a container, give users a chance to 16043 // relinquish resources before killing. 16044 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16045 if (DEBUG_INSTALL) { 16046 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16047 } 16048 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16049 final ArrayList<String> pkgList = new ArrayList<String>(1); 16050 pkgList.add(deletedPackage.applicationInfo.packageName); 16051 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16052 } 16053 16054 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16055 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16056 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16057 16058 try { 16059 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16060 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16061 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16062 installReason); 16063 16064 // Update the in-memory copy of the previous code paths. 16065 PackageSetting ps = mSettings.mPackages.get(pkgName); 16066 if (!killApp) { 16067 if (ps.oldCodePaths == null) { 16068 ps.oldCodePaths = new ArraySet<>(); 16069 } 16070 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16071 if (deletedPackage.splitCodePaths != null) { 16072 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16073 } 16074 } else { 16075 ps.oldCodePaths = null; 16076 } 16077 if (ps.childPackageNames != null) { 16078 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16079 final String childPkgName = ps.childPackageNames.get(i); 16080 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16081 childPs.oldCodePaths = ps.oldCodePaths; 16082 } 16083 } 16084 // set instant app status, but, only if it's explicitly specified 16085 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16086 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16087 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16088 prepareAppDataAfterInstallLIF(newPackage); 16089 addedPkg = true; 16090 mDexManager.notifyPackageUpdated(newPackage.packageName, 16091 newPackage.baseCodePath, newPackage.splitCodePaths); 16092 } catch (PackageManagerException e) { 16093 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16094 } 16095 } 16096 16097 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16098 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16099 16100 // Revert all internal state mutations and added folders for the failed install 16101 if (addedPkg) { 16102 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16103 res.removedInfo, true, null); 16104 } 16105 16106 // Restore the old package 16107 if (deletedPkg) { 16108 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16109 File restoreFile = new File(deletedPackage.codePath); 16110 // Parse old package 16111 boolean oldExternal = isExternal(deletedPackage); 16112 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16113 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16114 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16115 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16116 try { 16117 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16118 null); 16119 } catch (PackageManagerException e) { 16120 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16121 + e.getMessage()); 16122 return; 16123 } 16124 16125 synchronized (mPackages) { 16126 // Ensure the installer package name up to date 16127 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16128 16129 // Update permissions for restored package 16130 mPermissionManager.updatePermissions( 16131 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16132 mPermissionCallback); 16133 16134 mSettings.writeLPr(); 16135 } 16136 16137 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16138 } 16139 } else { 16140 synchronized (mPackages) { 16141 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16142 if (ps != null) { 16143 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16144 if (res.removedInfo.removedChildPackages != null) { 16145 final int childCount = res.removedInfo.removedChildPackages.size(); 16146 // Iterate in reverse as we may modify the collection 16147 for (int i = childCount - 1; i >= 0; i--) { 16148 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16149 if (res.addedChildPackages.containsKey(childPackageName)) { 16150 res.removedInfo.removedChildPackages.removeAt(i); 16151 } else { 16152 PackageRemovedInfo childInfo = res.removedInfo 16153 .removedChildPackages.valueAt(i); 16154 childInfo.removedForAllUsers = mPackages.get( 16155 childInfo.removedPackage) == null; 16156 } 16157 } 16158 } 16159 } 16160 } 16161 } 16162 } 16163 16164 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16165 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16166 final @ScanFlags int scanFlags, UserHandle user, 16167 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16168 int installReason) { 16169 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16170 + ", old=" + deletedPackage); 16171 16172 final boolean disabledSystem; 16173 16174 // Remove existing system package 16175 removePackageLI(deletedPackage, true); 16176 16177 synchronized (mPackages) { 16178 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16179 } 16180 if (!disabledSystem) { 16181 // We didn't need to disable the .apk as a current system package, 16182 // which means we are replacing another update that is already 16183 // installed. We need to make sure to delete the older one's .apk. 16184 res.removedInfo.args = createInstallArgsForExisting(0, 16185 deletedPackage.applicationInfo.getCodePath(), 16186 deletedPackage.applicationInfo.getResourcePath(), 16187 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16188 } else { 16189 res.removedInfo.args = null; 16190 } 16191 16192 // Successfully disabled the old package. Now proceed with re-installation 16193 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16194 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16195 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16196 16197 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16198 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16199 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16200 16201 PackageParser.Package newPackage = null; 16202 try { 16203 // Add the package to the internal data structures 16204 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16205 16206 // Set the update and install times 16207 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16208 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16209 System.currentTimeMillis()); 16210 16211 // Update the package dynamic state if succeeded 16212 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16213 // Now that the install succeeded make sure we remove data 16214 // directories for any child package the update removed. 16215 final int deletedChildCount = (deletedPackage.childPackages != null) 16216 ? deletedPackage.childPackages.size() : 0; 16217 final int newChildCount = (newPackage.childPackages != null) 16218 ? newPackage.childPackages.size() : 0; 16219 for (int i = 0; i < deletedChildCount; i++) { 16220 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16221 boolean childPackageDeleted = true; 16222 for (int j = 0; j < newChildCount; j++) { 16223 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16224 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16225 childPackageDeleted = false; 16226 break; 16227 } 16228 } 16229 if (childPackageDeleted) { 16230 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16231 deletedChildPkg.packageName); 16232 if (ps != null && res.removedInfo.removedChildPackages != null) { 16233 PackageRemovedInfo removedChildRes = res.removedInfo 16234 .removedChildPackages.get(deletedChildPkg.packageName); 16235 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16236 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16237 } 16238 } 16239 } 16240 16241 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16242 installReason); 16243 prepareAppDataAfterInstallLIF(newPackage); 16244 16245 mDexManager.notifyPackageUpdated(newPackage.packageName, 16246 newPackage.baseCodePath, newPackage.splitCodePaths); 16247 } 16248 } catch (PackageManagerException e) { 16249 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16250 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16251 } 16252 16253 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16254 // Re installation failed. Restore old information 16255 // Remove new pkg information 16256 if (newPackage != null) { 16257 removeInstalledPackageLI(newPackage, true); 16258 } 16259 // Add back the old system package 16260 try { 16261 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16262 } catch (PackageManagerException e) { 16263 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16264 } 16265 16266 synchronized (mPackages) { 16267 if (disabledSystem) { 16268 enableSystemPackageLPw(deletedPackage); 16269 } 16270 16271 // Ensure the installer package name up to date 16272 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16273 16274 // Update permissions for restored package 16275 mPermissionManager.updatePermissions( 16276 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16277 mPermissionCallback); 16278 16279 mSettings.writeLPr(); 16280 } 16281 16282 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16283 + " after failed upgrade"); 16284 } 16285 } 16286 16287 /** 16288 * Checks whether the parent or any of the child packages have a change shared 16289 * user. For a package to be a valid update the shred users of the parent and 16290 * the children should match. We may later support changing child shared users. 16291 * @param oldPkg The updated package. 16292 * @param newPkg The update package. 16293 * @return The shared user that change between the versions. 16294 */ 16295 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16296 PackageParser.Package newPkg) { 16297 // Check parent shared user 16298 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16299 return newPkg.packageName; 16300 } 16301 // Check child shared users 16302 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16303 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16304 for (int i = 0; i < newChildCount; i++) { 16305 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16306 // If this child was present, did it have the same shared user? 16307 for (int j = 0; j < oldChildCount; j++) { 16308 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16309 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16310 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16311 return newChildPkg.packageName; 16312 } 16313 } 16314 } 16315 return null; 16316 } 16317 16318 private void removeNativeBinariesLI(PackageSetting ps) { 16319 // Remove the lib path for the parent package 16320 if (ps != null) { 16321 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16322 // Remove the lib path for the child packages 16323 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16324 for (int i = 0; i < childCount; i++) { 16325 PackageSetting childPs = null; 16326 synchronized (mPackages) { 16327 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16328 } 16329 if (childPs != null) { 16330 NativeLibraryHelper.removeNativeBinariesLI(childPs 16331 .legacyNativeLibraryPathString); 16332 } 16333 } 16334 } 16335 } 16336 16337 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16338 // Enable the parent package 16339 mSettings.enableSystemPackageLPw(pkg.packageName); 16340 // Enable the child packages 16341 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16342 for (int i = 0; i < childCount; i++) { 16343 PackageParser.Package childPkg = pkg.childPackages.get(i); 16344 mSettings.enableSystemPackageLPw(childPkg.packageName); 16345 } 16346 } 16347 16348 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16349 PackageParser.Package newPkg) { 16350 // Disable the parent package (parent always replaced) 16351 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16352 // Disable the child packages 16353 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16354 for (int i = 0; i < childCount; i++) { 16355 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16356 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16357 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16358 } 16359 return disabled; 16360 } 16361 16362 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16363 String installerPackageName) { 16364 // Enable the parent package 16365 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16366 // Enable the child packages 16367 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16368 for (int i = 0; i < childCount; i++) { 16369 PackageParser.Package childPkg = pkg.childPackages.get(i); 16370 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16371 } 16372 } 16373 16374 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16375 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16376 // Update the parent package setting 16377 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16378 res, user, installReason); 16379 // Update the child packages setting 16380 final int childCount = (newPackage.childPackages != null) 16381 ? newPackage.childPackages.size() : 0; 16382 for (int i = 0; i < childCount; i++) { 16383 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16384 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16385 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16386 childRes.origUsers, childRes, user, installReason); 16387 } 16388 } 16389 16390 private void updateSettingsInternalLI(PackageParser.Package pkg, 16391 String installerPackageName, int[] allUsers, int[] installedForUsers, 16392 PackageInstalledInfo res, UserHandle user, int installReason) { 16393 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16394 16395 String pkgName = pkg.packageName; 16396 synchronized (mPackages) { 16397 //write settings. the installStatus will be incomplete at this stage. 16398 //note that the new package setting would have already been 16399 //added to mPackages. It hasn't been persisted yet. 16400 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16401 // TODO: Remove this write? It's also written at the end of this method 16402 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16403 mSettings.writeLPr(); 16404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16405 } 16406 16407 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16408 synchronized (mPackages) { 16409// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16410 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16411 mPermissionCallback); 16412 // For system-bundled packages, we assume that installing an upgraded version 16413 // of the package implies that the user actually wants to run that new code, 16414 // so we enable the package. 16415 PackageSetting ps = mSettings.mPackages.get(pkgName); 16416 final int userId = user.getIdentifier(); 16417 if (ps != null) { 16418 if (isSystemApp(pkg)) { 16419 if (DEBUG_INSTALL) { 16420 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16421 } 16422 // Enable system package for requested users 16423 if (res.origUsers != null) { 16424 for (int origUserId : res.origUsers) { 16425 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16426 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16427 origUserId, installerPackageName); 16428 } 16429 } 16430 } 16431 // Also convey the prior install/uninstall state 16432 if (allUsers != null && installedForUsers != null) { 16433 for (int currentUserId : allUsers) { 16434 final boolean installed = ArrayUtils.contains( 16435 installedForUsers, currentUserId); 16436 if (DEBUG_INSTALL) { 16437 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16438 } 16439 ps.setInstalled(installed, currentUserId); 16440 } 16441 // these install state changes will be persisted in the 16442 // upcoming call to mSettings.writeLPr(). 16443 } 16444 } 16445 // It's implied that when a user requests installation, they want the app to be 16446 // installed and enabled. 16447 if (userId != UserHandle.USER_ALL) { 16448 ps.setInstalled(true, userId); 16449 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16450 } 16451 16452 // When replacing an existing package, preserve the original install reason for all 16453 // users that had the package installed before. 16454 final Set<Integer> previousUserIds = new ArraySet<>(); 16455 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16456 final int installReasonCount = res.removedInfo.installReasons.size(); 16457 for (int i = 0; i < installReasonCount; i++) { 16458 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16459 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16460 ps.setInstallReason(previousInstallReason, previousUserId); 16461 previousUserIds.add(previousUserId); 16462 } 16463 } 16464 16465 // Set install reason for users that are having the package newly installed. 16466 if (userId == UserHandle.USER_ALL) { 16467 for (int currentUserId : sUserManager.getUserIds()) { 16468 if (!previousUserIds.contains(currentUserId)) { 16469 ps.setInstallReason(installReason, currentUserId); 16470 } 16471 } 16472 } else if (!previousUserIds.contains(userId)) { 16473 ps.setInstallReason(installReason, userId); 16474 } 16475 mSettings.writeKernelMappingLPr(ps); 16476 } 16477 res.name = pkgName; 16478 res.uid = pkg.applicationInfo.uid; 16479 res.pkg = pkg; 16480 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16481 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16482 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16483 //to update install status 16484 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16485 mSettings.writeLPr(); 16486 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16487 } 16488 16489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16490 } 16491 16492 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16493 try { 16494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16495 installPackageLI(args, res); 16496 } finally { 16497 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16498 } 16499 } 16500 16501 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16502 final int installFlags = args.installFlags; 16503 final String installerPackageName = args.installerPackageName; 16504 final String volumeUuid = args.volumeUuid; 16505 final File tmpPackageFile = new File(args.getCodePath()); 16506 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16507 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16508 || (args.volumeUuid != null)); 16509 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16510 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16511 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16512 final boolean virtualPreload = 16513 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16514 boolean replace = false; 16515 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16516 if (args.move != null) { 16517 // moving a complete application; perform an initial scan on the new install location 16518 scanFlags |= SCAN_INITIAL; 16519 } 16520 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16521 scanFlags |= SCAN_DONT_KILL_APP; 16522 } 16523 if (instantApp) { 16524 scanFlags |= SCAN_AS_INSTANT_APP; 16525 } 16526 if (fullApp) { 16527 scanFlags |= SCAN_AS_FULL_APP; 16528 } 16529 if (virtualPreload) { 16530 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16531 } 16532 16533 // Result object to be returned 16534 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16535 res.installerPackageName = installerPackageName; 16536 16537 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16538 16539 // Sanity check 16540 if (instantApp && (forwardLocked || onExternal)) { 16541 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16542 + " external=" + onExternal); 16543 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16544 return; 16545 } 16546 16547 // Retrieve PackageSettings and parse package 16548 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16549 | PackageParser.PARSE_ENFORCE_CODE 16550 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16551 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16552 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16553 PackageParser pp = new PackageParser(); 16554 pp.setSeparateProcesses(mSeparateProcesses); 16555 pp.setDisplayMetrics(mMetrics); 16556 pp.setCallback(mPackageParserCallback); 16557 16558 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16559 final PackageParser.Package pkg; 16560 try { 16561 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16562 DexMetadataHelper.validatePackageDexMetadata(pkg); 16563 } catch (PackageParserException e) { 16564 res.setError("Failed parse during installPackageLI", e); 16565 return; 16566 } finally { 16567 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16568 } 16569 16570 // Instant apps have several additional install-time checks. 16571 if (instantApp) { 16572 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16573 Slog.w(TAG, 16574 "Instant app package " + pkg.packageName + " does not target at least O"); 16575 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16576 "Instant app package must target at least O"); 16577 return; 16578 } 16579 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16580 Slog.w(TAG, "Instant app package " + pkg.packageName 16581 + " does not target targetSandboxVersion 2"); 16582 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16583 "Instant app package must use targetSandboxVersion 2"); 16584 return; 16585 } 16586 if (pkg.mSharedUserId != null) { 16587 Slog.w(TAG, "Instant app package " + pkg.packageName 16588 + " may not declare sharedUserId."); 16589 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16590 "Instant app package may not declare a sharedUserId"); 16591 return; 16592 } 16593 } 16594 16595 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16596 // Static shared libraries have synthetic package names 16597 renameStaticSharedLibraryPackage(pkg); 16598 16599 // No static shared libs on external storage 16600 if (onExternal) { 16601 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16602 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16603 "Packages declaring static-shared libs cannot be updated"); 16604 return; 16605 } 16606 } 16607 16608 // If we are installing a clustered package add results for the children 16609 if (pkg.childPackages != null) { 16610 synchronized (mPackages) { 16611 final int childCount = pkg.childPackages.size(); 16612 for (int i = 0; i < childCount; i++) { 16613 PackageParser.Package childPkg = pkg.childPackages.get(i); 16614 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16615 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16616 childRes.pkg = childPkg; 16617 childRes.name = childPkg.packageName; 16618 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16619 if (childPs != null) { 16620 childRes.origUsers = childPs.queryInstalledUsers( 16621 sUserManager.getUserIds(), true); 16622 } 16623 if ((mPackages.containsKey(childPkg.packageName))) { 16624 childRes.removedInfo = new PackageRemovedInfo(this); 16625 childRes.removedInfo.removedPackage = childPkg.packageName; 16626 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16627 } 16628 if (res.addedChildPackages == null) { 16629 res.addedChildPackages = new ArrayMap<>(); 16630 } 16631 res.addedChildPackages.put(childPkg.packageName, childRes); 16632 } 16633 } 16634 } 16635 16636 // If package doesn't declare API override, mark that we have an install 16637 // time CPU ABI override. 16638 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16639 pkg.cpuAbiOverride = args.abiOverride; 16640 } 16641 16642 String pkgName = res.name = pkg.packageName; 16643 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16644 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16645 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16646 return; 16647 } 16648 } 16649 16650 try { 16651 // either use what we've been given or parse directly from the APK 16652 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16653 pkg.setSigningDetails(args.signingDetails); 16654 } else { 16655 PackageParser.collectCertificates(pkg, parseFlags); 16656 } 16657 } catch (PackageParserException e) { 16658 res.setError("Failed collect during installPackageLI", e); 16659 return; 16660 } 16661 16662 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16663 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16664 Slog.w(TAG, "Instant app package " + pkg.packageName 16665 + " is not signed with at least APK Signature Scheme v2"); 16666 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16667 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16668 return; 16669 } 16670 16671 // Get rid of all references to package scan path via parser. 16672 pp = null; 16673 String oldCodePath = null; 16674 boolean systemApp = false; 16675 synchronized (mPackages) { 16676 // Check if installing already existing package 16677 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16678 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16679 if (pkg.mOriginalPackages != null 16680 && pkg.mOriginalPackages.contains(oldName) 16681 && mPackages.containsKey(oldName)) { 16682 // This package is derived from an original package, 16683 // and this device has been updating from that original 16684 // name. We must continue using the original name, so 16685 // rename the new package here. 16686 pkg.setPackageName(oldName); 16687 pkgName = pkg.packageName; 16688 replace = true; 16689 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16690 + oldName + " pkgName=" + pkgName); 16691 } else if (mPackages.containsKey(pkgName)) { 16692 // This package, under its official name, already exists 16693 // on the device; we should replace it. 16694 replace = true; 16695 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16696 } 16697 16698 // Child packages are installed through the parent package 16699 if (pkg.parentPackage != null) { 16700 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16701 "Package " + pkg.packageName + " is child of package " 16702 + pkg.parentPackage.parentPackage + ". Child packages " 16703 + "can be updated only through the parent package."); 16704 return; 16705 } 16706 16707 if (replace) { 16708 // Prevent apps opting out from runtime permissions 16709 PackageParser.Package oldPackage = mPackages.get(pkgName); 16710 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16711 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16712 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16713 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16714 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16715 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16716 + " doesn't support runtime permissions but the old" 16717 + " target SDK " + oldTargetSdk + " does."); 16718 return; 16719 } 16720 // Prevent persistent apps from being updated 16721 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16722 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16723 "Package " + oldPackage.packageName + " is a persistent app. " 16724 + "Persistent apps are not updateable."); 16725 return; 16726 } 16727 // Prevent apps from downgrading their targetSandbox. 16728 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16729 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16730 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16731 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16732 "Package " + pkg.packageName + " new target sandbox " 16733 + newTargetSandbox + " is incompatible with the previous value of" 16734 + oldTargetSandbox + "."); 16735 return; 16736 } 16737 16738 // Prevent installing of child packages 16739 if (oldPackage.parentPackage != null) { 16740 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16741 "Package " + pkg.packageName + " is child of package " 16742 + oldPackage.parentPackage + ". Child packages " 16743 + "can be updated only through the parent package."); 16744 return; 16745 } 16746 } 16747 } 16748 16749 PackageSetting ps = mSettings.mPackages.get(pkgName); 16750 if (ps != null) { 16751 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16752 16753 // Static shared libs have same package with different versions where 16754 // we internally use a synthetic package name to allow multiple versions 16755 // of the same package, therefore we need to compare signatures against 16756 // the package setting for the latest library version. 16757 PackageSetting signatureCheckPs = ps; 16758 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16759 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16760 if (libraryEntry != null) { 16761 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16762 } 16763 } 16764 16765 // Quick sanity check that we're signed correctly if updating; 16766 // we'll check this again later when scanning, but we want to 16767 // bail early here before tripping over redefined permissions. 16768 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16769 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16770 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16771 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16772 + pkg.packageName + " upgrade keys do not match the " 16773 + "previously installed version"); 16774 return; 16775 } 16776 } else { 16777 try { 16778 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16779 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16780 // We don't care about disabledPkgSetting on install for now. 16781 final boolean compatMatch = verifySignatures( 16782 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16783 compareRecover); 16784 // The new KeySets will be re-added later in the scanning process. 16785 if (compatMatch) { 16786 synchronized (mPackages) { 16787 ksms.removeAppKeySetDataLPw(pkg.packageName); 16788 } 16789 } 16790 } catch (PackageManagerException e) { 16791 res.setError(e.error, e.getMessage()); 16792 return; 16793 } 16794 } 16795 16796 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16797 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16798 systemApp = (ps.pkg.applicationInfo.flags & 16799 ApplicationInfo.FLAG_SYSTEM) != 0; 16800 } 16801 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16802 } 16803 16804 int N = pkg.permissions.size(); 16805 for (int i = N-1; i >= 0; i--) { 16806 final PackageParser.Permission perm = pkg.permissions.get(i); 16807 final BasePermission bp = 16808 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16809 16810 // Don't allow anyone but the system to define ephemeral permissions. 16811 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16812 && !systemApp) { 16813 Slog.w(TAG, "Non-System package " + pkg.packageName 16814 + " attempting to delcare ephemeral permission " 16815 + perm.info.name + "; Removing ephemeral."); 16816 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16817 } 16818 16819 // Check whether the newly-scanned package wants to define an already-defined perm 16820 if (bp != null) { 16821 // If the defining package is signed with our cert, it's okay. This 16822 // also includes the "updating the same package" case, of course. 16823 // "updating same package" could also involve key-rotation. 16824 final boolean sigsOk; 16825 final String sourcePackageName = bp.getSourcePackageName(); 16826 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16827 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16828 if (sourcePackageName.equals(pkg.packageName) 16829 && (ksms.shouldCheckUpgradeKeySetLocked( 16830 sourcePackageSetting, scanFlags))) { 16831 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16832 } else { 16833 sigsOk = compareSignatures( 16834 sourcePackageSetting.signatures.mSigningDetails.signatures, 16835 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 16836 } 16837 if (!sigsOk) { 16838 // If the owning package is the system itself, we log but allow 16839 // install to proceed; we fail the install on all other permission 16840 // redefinitions. 16841 if (!sourcePackageName.equals("android")) { 16842 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16843 + pkg.packageName + " attempting to redeclare permission " 16844 + perm.info.name + " already owned by " + sourcePackageName); 16845 res.origPermission = perm.info.name; 16846 res.origPackage = sourcePackageName; 16847 return; 16848 } else { 16849 Slog.w(TAG, "Package " + pkg.packageName 16850 + " attempting to redeclare system permission " 16851 + perm.info.name + "; ignoring new declaration"); 16852 pkg.permissions.remove(i); 16853 } 16854 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16855 // Prevent apps to change protection level to dangerous from any other 16856 // type as this would allow a privilege escalation where an app adds a 16857 // normal/signature permission in other app's group and later redefines 16858 // it as dangerous leading to the group auto-grant. 16859 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16860 == PermissionInfo.PROTECTION_DANGEROUS) { 16861 if (bp != null && !bp.isRuntime()) { 16862 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16863 + "non-runtime permission " + perm.info.name 16864 + " to runtime; keeping old protection level"); 16865 perm.info.protectionLevel = bp.getProtectionLevel(); 16866 } 16867 } 16868 } 16869 } 16870 } 16871 } 16872 16873 if (systemApp) { 16874 if (onExternal) { 16875 // Abort update; system app can't be replaced with app on sdcard 16876 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16877 "Cannot install updates to system apps on sdcard"); 16878 return; 16879 } else if (instantApp) { 16880 // Abort update; system app can't be replaced with an instant app 16881 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16882 "Cannot update a system app with an instant app"); 16883 return; 16884 } 16885 } 16886 16887 if (args.move != null) { 16888 // We did an in-place move, so dex is ready to roll 16889 scanFlags |= SCAN_NO_DEX; 16890 scanFlags |= SCAN_MOVE; 16891 16892 synchronized (mPackages) { 16893 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16894 if (ps == null) { 16895 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16896 "Missing settings for moved package " + pkgName); 16897 } 16898 16899 // We moved the entire application as-is, so bring over the 16900 // previously derived ABI information. 16901 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16902 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16903 } 16904 16905 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16906 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16907 scanFlags |= SCAN_NO_DEX; 16908 16909 try { 16910 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16911 args.abiOverride : pkg.cpuAbiOverride); 16912 final boolean extractNativeLibs = !pkg.isLibrary(); 16913 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 16914 } catch (PackageManagerException pme) { 16915 Slog.e(TAG, "Error deriving application ABI", pme); 16916 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16917 return; 16918 } 16919 16920 // Shared libraries for the package need to be updated. 16921 synchronized (mPackages) { 16922 try { 16923 updateSharedLibrariesLPr(pkg, null); 16924 } catch (PackageManagerException e) { 16925 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16926 } 16927 } 16928 } 16929 16930 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16931 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16932 return; 16933 } 16934 16935 if (!instantApp) { 16936 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16937 } else { 16938 if (DEBUG_DOMAIN_VERIFICATION) { 16939 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16940 } 16941 } 16942 16943 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16944 "installPackageLI")) { 16945 if (replace) { 16946 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16947 // Static libs have a synthetic package name containing the version 16948 // and cannot be updated as an update would get a new package name, 16949 // unless this is the exact same version code which is useful for 16950 // development. 16951 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16952 if (existingPkg != null && 16953 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 16954 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16955 + "static-shared libs cannot be updated"); 16956 return; 16957 } 16958 } 16959 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 16960 installerPackageName, res, args.installReason); 16961 } else { 16962 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16963 args.user, installerPackageName, volumeUuid, res, args.installReason); 16964 } 16965 } 16966 16967 // Check whether we need to dexopt the app. 16968 // 16969 // NOTE: it is IMPORTANT to call dexopt: 16970 // - after doRename which will sync the package data from PackageParser.Package and its 16971 // corresponding ApplicationInfo. 16972 // - after installNewPackageLIF or replacePackageLIF which will update result with the 16973 // uid of the application (pkg.applicationInfo.uid). 16974 // This update happens in place! 16975 // 16976 // We only need to dexopt if the package meets ALL of the following conditions: 16977 // 1) it is not forward locked. 16978 // 2) it is not on on an external ASEC container. 16979 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16980 // 16981 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16982 // complete, so we skip this step during installation. Instead, we'll take extra time 16983 // the first time the instant app starts. It's preferred to do it this way to provide 16984 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16985 // middle of running an instant app. The default behaviour can be overridden 16986 // via gservices. 16987 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 16988 && !forwardLocked 16989 && !pkg.applicationInfo.isExternalAsec() 16990 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16991 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16992 16993 if (performDexopt) { 16994 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16995 // Do not run PackageDexOptimizer through the local performDexOpt 16996 // method because `pkg` may not be in `mPackages` yet. 16997 // 16998 // Also, don't fail application installs if the dexopt step fails. 16999 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17000 REASON_INSTALL, 17001 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17002 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17003 null /* instructionSets */, 17004 getOrCreateCompilerPackageStats(pkg), 17005 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17006 dexoptOptions); 17007 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17008 } 17009 17010 // Notify BackgroundDexOptService that the package has been changed. 17011 // If this is an update of a package which used to fail to compile, 17012 // BackgroundDexOptService will remove it from its blacklist. 17013 // TODO: Layering violation 17014 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17015 17016 synchronized (mPackages) { 17017 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17018 if (ps != null) { 17019 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17020 ps.setUpdateAvailable(false /*updateAvailable*/); 17021 } 17022 17023 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17024 for (int i = 0; i < childCount; i++) { 17025 PackageParser.Package childPkg = pkg.childPackages.get(i); 17026 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17027 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17028 if (childPs != null) { 17029 childRes.newUsers = childPs.queryInstalledUsers( 17030 sUserManager.getUserIds(), true); 17031 } 17032 } 17033 17034 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17035 updateSequenceNumberLP(ps, res.newUsers); 17036 updateInstantAppInstallerLocked(pkgName); 17037 } 17038 } 17039 } 17040 17041 private void startIntentFilterVerifications(int userId, boolean replacing, 17042 PackageParser.Package pkg) { 17043 if (mIntentFilterVerifierComponent == null) { 17044 Slog.w(TAG, "No IntentFilter verification will not be done as " 17045 + "there is no IntentFilterVerifier available!"); 17046 return; 17047 } 17048 17049 final int verifierUid = getPackageUid( 17050 mIntentFilterVerifierComponent.getPackageName(), 17051 MATCH_DEBUG_TRIAGED_MISSING, 17052 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17053 17054 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17055 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17056 mHandler.sendMessage(msg); 17057 17058 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17059 for (int i = 0; i < childCount; i++) { 17060 PackageParser.Package childPkg = pkg.childPackages.get(i); 17061 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17062 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17063 mHandler.sendMessage(msg); 17064 } 17065 } 17066 17067 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17068 PackageParser.Package pkg) { 17069 int size = pkg.activities.size(); 17070 if (size == 0) { 17071 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17072 "No activity, so no need to verify any IntentFilter!"); 17073 return; 17074 } 17075 17076 final boolean hasDomainURLs = hasDomainURLs(pkg); 17077 if (!hasDomainURLs) { 17078 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17079 "No domain URLs, so no need to verify any IntentFilter!"); 17080 return; 17081 } 17082 17083 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17084 + " if any IntentFilter from the " + size 17085 + " Activities needs verification ..."); 17086 17087 int count = 0; 17088 final String packageName = pkg.packageName; 17089 17090 synchronized (mPackages) { 17091 // If this is a new install and we see that we've already run verification for this 17092 // package, we have nothing to do: it means the state was restored from backup. 17093 if (!replacing) { 17094 IntentFilterVerificationInfo ivi = 17095 mSettings.getIntentFilterVerificationLPr(packageName); 17096 if (ivi != null) { 17097 if (DEBUG_DOMAIN_VERIFICATION) { 17098 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17099 + ivi.getStatusString()); 17100 } 17101 return; 17102 } 17103 } 17104 17105 // If any filters need to be verified, then all need to be. 17106 boolean needToVerify = false; 17107 for (PackageParser.Activity a : pkg.activities) { 17108 for (ActivityIntentInfo filter : a.intents) { 17109 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17110 if (DEBUG_DOMAIN_VERIFICATION) { 17111 Slog.d(TAG, 17112 "Intent filter needs verification, so processing all filters"); 17113 } 17114 needToVerify = true; 17115 break; 17116 } 17117 } 17118 } 17119 17120 if (needToVerify) { 17121 final int verificationId = mIntentFilterVerificationToken++; 17122 for (PackageParser.Activity a : pkg.activities) { 17123 for (ActivityIntentInfo filter : a.intents) { 17124 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17125 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17126 "Verification needed for IntentFilter:" + filter.toString()); 17127 mIntentFilterVerifier.addOneIntentFilterVerification( 17128 verifierUid, userId, verificationId, filter, packageName); 17129 count++; 17130 } 17131 } 17132 } 17133 } 17134 } 17135 17136 if (count > 0) { 17137 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17138 + " IntentFilter verification" + (count > 1 ? "s" : "") 17139 + " for userId:" + userId); 17140 mIntentFilterVerifier.startVerifications(userId); 17141 } else { 17142 if (DEBUG_DOMAIN_VERIFICATION) { 17143 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17144 } 17145 } 17146 } 17147 17148 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17149 final ComponentName cn = filter.activity.getComponentName(); 17150 final String packageName = cn.getPackageName(); 17151 17152 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17153 packageName); 17154 if (ivi == null) { 17155 return true; 17156 } 17157 int status = ivi.getStatus(); 17158 switch (status) { 17159 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17161 return true; 17162 17163 default: 17164 // Nothing to do 17165 return false; 17166 } 17167 } 17168 17169 private static boolean isMultiArch(ApplicationInfo info) { 17170 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17171 } 17172 17173 private static boolean isExternal(PackageParser.Package pkg) { 17174 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17175 } 17176 17177 private static boolean isExternal(PackageSetting ps) { 17178 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17179 } 17180 17181 private static boolean isSystemApp(PackageParser.Package pkg) { 17182 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17183 } 17184 17185 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17186 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17187 } 17188 17189 private static boolean isOemApp(PackageParser.Package pkg) { 17190 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17191 } 17192 17193 private static boolean isVendorApp(PackageParser.Package pkg) { 17194 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17195 } 17196 17197 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17198 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17199 } 17200 17201 private static boolean isSystemApp(PackageSetting ps) { 17202 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17203 } 17204 17205 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17206 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17207 } 17208 17209 private int packageFlagsToInstallFlags(PackageSetting ps) { 17210 int installFlags = 0; 17211 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17212 // This existing package was an external ASEC install when we have 17213 // the external flag without a UUID 17214 installFlags |= PackageManager.INSTALL_EXTERNAL; 17215 } 17216 if (ps.isForwardLocked()) { 17217 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17218 } 17219 return installFlags; 17220 } 17221 17222 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17223 if (isExternal(pkg)) { 17224 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17225 return mSettings.getExternalVersion(); 17226 } else { 17227 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17228 } 17229 } else { 17230 return mSettings.getInternalVersion(); 17231 } 17232 } 17233 17234 private void deleteTempPackageFiles() { 17235 final FilenameFilter filter = new FilenameFilter() { 17236 public boolean accept(File dir, String name) { 17237 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17238 } 17239 }; 17240 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17241 file.delete(); 17242 } 17243 } 17244 17245 @Override 17246 public void deletePackageAsUser(String packageName, int versionCode, 17247 IPackageDeleteObserver observer, int userId, int flags) { 17248 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17249 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17250 } 17251 17252 @Override 17253 public void deletePackageVersioned(VersionedPackage versionedPackage, 17254 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17255 final int callingUid = Binder.getCallingUid(); 17256 mContext.enforceCallingOrSelfPermission( 17257 android.Manifest.permission.DELETE_PACKAGES, null); 17258 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17259 Preconditions.checkNotNull(versionedPackage); 17260 Preconditions.checkNotNull(observer); 17261 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17262 PackageManager.VERSION_CODE_HIGHEST, 17263 Long.MAX_VALUE, "versionCode must be >= -1"); 17264 17265 final String packageName = versionedPackage.getPackageName(); 17266 final long versionCode = versionedPackage.getLongVersionCode(); 17267 final String internalPackageName; 17268 synchronized (mPackages) { 17269 // Normalize package name to handle renamed packages and static libs 17270 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17271 } 17272 17273 final int uid = Binder.getCallingUid(); 17274 if (!isOrphaned(internalPackageName) 17275 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17276 try { 17277 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17278 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17279 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17280 observer.onUserActionRequired(intent); 17281 } catch (RemoteException re) { 17282 } 17283 return; 17284 } 17285 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17286 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17287 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17288 mContext.enforceCallingOrSelfPermission( 17289 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17290 "deletePackage for user " + userId); 17291 } 17292 17293 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17294 try { 17295 observer.onPackageDeleted(packageName, 17296 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17297 } catch (RemoteException re) { 17298 } 17299 return; 17300 } 17301 17302 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17303 try { 17304 observer.onPackageDeleted(packageName, 17305 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17306 } catch (RemoteException re) { 17307 } 17308 return; 17309 } 17310 17311 if (DEBUG_REMOVE) { 17312 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17313 + " deleteAllUsers: " + deleteAllUsers + " version=" 17314 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17315 ? "VERSION_CODE_HIGHEST" : versionCode)); 17316 } 17317 // Queue up an async operation since the package deletion may take a little while. 17318 mHandler.post(new Runnable() { 17319 public void run() { 17320 mHandler.removeCallbacks(this); 17321 int returnCode; 17322 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17323 boolean doDeletePackage = true; 17324 if (ps != null) { 17325 final boolean targetIsInstantApp = 17326 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17327 doDeletePackage = !targetIsInstantApp 17328 || canViewInstantApps; 17329 } 17330 if (doDeletePackage) { 17331 if (!deleteAllUsers) { 17332 returnCode = deletePackageX(internalPackageName, versionCode, 17333 userId, deleteFlags); 17334 } else { 17335 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17336 internalPackageName, users); 17337 // If nobody is blocking uninstall, proceed with delete for all users 17338 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17339 returnCode = deletePackageX(internalPackageName, versionCode, 17340 userId, deleteFlags); 17341 } else { 17342 // Otherwise uninstall individually for users with blockUninstalls=false 17343 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17344 for (int userId : users) { 17345 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17346 returnCode = deletePackageX(internalPackageName, versionCode, 17347 userId, userFlags); 17348 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17349 Slog.w(TAG, "Package delete failed for user " + userId 17350 + ", returnCode " + returnCode); 17351 } 17352 } 17353 } 17354 // The app has only been marked uninstalled for certain users. 17355 // We still need to report that delete was blocked 17356 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17357 } 17358 } 17359 } else { 17360 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17361 } 17362 try { 17363 observer.onPackageDeleted(packageName, returnCode, null); 17364 } catch (RemoteException e) { 17365 Log.i(TAG, "Observer no longer exists."); 17366 } //end catch 17367 } //end run 17368 }); 17369 } 17370 17371 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17372 if (pkg.staticSharedLibName != null) { 17373 return pkg.manifestPackageName; 17374 } 17375 return pkg.packageName; 17376 } 17377 17378 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17379 // Handle renamed packages 17380 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17381 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17382 17383 // Is this a static library? 17384 LongSparseArray<SharedLibraryEntry> versionedLib = 17385 mStaticLibsByDeclaringPackage.get(packageName); 17386 if (versionedLib == null || versionedLib.size() <= 0) { 17387 return packageName; 17388 } 17389 17390 // Figure out which lib versions the caller can see 17391 LongSparseLongArray versionsCallerCanSee = null; 17392 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17393 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17394 && callingAppId != Process.ROOT_UID) { 17395 versionsCallerCanSee = new LongSparseLongArray(); 17396 String libName = versionedLib.valueAt(0).info.getName(); 17397 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17398 if (uidPackages != null) { 17399 for (String uidPackage : uidPackages) { 17400 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17401 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17402 if (libIdx >= 0) { 17403 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17404 versionsCallerCanSee.append(libVersion, libVersion); 17405 } 17406 } 17407 } 17408 } 17409 17410 // Caller can see nothing - done 17411 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17412 return packageName; 17413 } 17414 17415 // Find the version the caller can see and the app version code 17416 SharedLibraryEntry highestVersion = null; 17417 final int versionCount = versionedLib.size(); 17418 for (int i = 0; i < versionCount; i++) { 17419 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17420 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17421 libEntry.info.getLongVersion()) < 0) { 17422 continue; 17423 } 17424 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17425 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17426 if (libVersionCode == versionCode) { 17427 return libEntry.apk; 17428 } 17429 } else if (highestVersion == null) { 17430 highestVersion = libEntry; 17431 } else if (libVersionCode > highestVersion.info 17432 .getDeclaringPackage().getLongVersionCode()) { 17433 highestVersion = libEntry; 17434 } 17435 } 17436 17437 if (highestVersion != null) { 17438 return highestVersion.apk; 17439 } 17440 17441 return packageName; 17442 } 17443 17444 boolean isCallerVerifier(int callingUid) { 17445 final int callingUserId = UserHandle.getUserId(callingUid); 17446 return mRequiredVerifierPackage != null && 17447 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17448 } 17449 17450 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17451 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17452 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17453 return true; 17454 } 17455 final int callingUserId = UserHandle.getUserId(callingUid); 17456 // If the caller installed the pkgName, then allow it to silently uninstall. 17457 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17458 return true; 17459 } 17460 17461 // Allow package verifier to silently uninstall. 17462 if (mRequiredVerifierPackage != null && 17463 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17464 return true; 17465 } 17466 17467 // Allow package uninstaller to silently uninstall. 17468 if (mRequiredUninstallerPackage != null && 17469 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17470 return true; 17471 } 17472 17473 // Allow storage manager to silently uninstall. 17474 if (mStorageManagerPackage != null && 17475 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17476 return true; 17477 } 17478 17479 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17480 // uninstall for device owner provisioning. 17481 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17482 == PERMISSION_GRANTED) { 17483 return true; 17484 } 17485 17486 return false; 17487 } 17488 17489 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17490 int[] result = EMPTY_INT_ARRAY; 17491 for (int userId : userIds) { 17492 if (getBlockUninstallForUser(packageName, userId)) { 17493 result = ArrayUtils.appendInt(result, userId); 17494 } 17495 } 17496 return result; 17497 } 17498 17499 @Override 17500 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17501 final int callingUid = Binder.getCallingUid(); 17502 if (getInstantAppPackageName(callingUid) != null 17503 && !isCallerSameApp(packageName, callingUid)) { 17504 return false; 17505 } 17506 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17507 } 17508 17509 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17510 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17511 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17512 try { 17513 if (dpm != null) { 17514 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17515 /* callingUserOnly =*/ false); 17516 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17517 : deviceOwnerComponentName.getPackageName(); 17518 // Does the package contains the device owner? 17519 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17520 // this check is probably not needed, since DO should be registered as a device 17521 // admin on some user too. (Original bug for this: b/17657954) 17522 if (packageName.equals(deviceOwnerPackageName)) { 17523 return true; 17524 } 17525 // Does it contain a device admin for any user? 17526 int[] users; 17527 if (userId == UserHandle.USER_ALL) { 17528 users = sUserManager.getUserIds(); 17529 } else { 17530 users = new int[]{userId}; 17531 } 17532 for (int i = 0; i < users.length; ++i) { 17533 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17534 return true; 17535 } 17536 } 17537 } 17538 } catch (RemoteException e) { 17539 } 17540 return false; 17541 } 17542 17543 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17544 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17545 } 17546 17547 /** 17548 * This method is an internal method that could be get invoked either 17549 * to delete an installed package or to clean up a failed installation. 17550 * After deleting an installed package, a broadcast is sent to notify any 17551 * listeners that the package has been removed. For cleaning up a failed 17552 * installation, the broadcast is not necessary since the package's 17553 * installation wouldn't have sent the initial broadcast either 17554 * The key steps in deleting a package are 17555 * deleting the package information in internal structures like mPackages, 17556 * deleting the packages base directories through installd 17557 * updating mSettings to reflect current status 17558 * persisting settings for later use 17559 * sending a broadcast if necessary 17560 */ 17561 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17562 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17563 final boolean res; 17564 17565 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17566 ? UserHandle.USER_ALL : userId; 17567 17568 if (isPackageDeviceAdmin(packageName, removeUser)) { 17569 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17570 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17571 } 17572 17573 PackageSetting uninstalledPs = null; 17574 PackageParser.Package pkg = null; 17575 17576 // for the uninstall-updates case and restricted profiles, remember the per- 17577 // user handle installed state 17578 int[] allUsers; 17579 synchronized (mPackages) { 17580 uninstalledPs = mSettings.mPackages.get(packageName); 17581 if (uninstalledPs == null) { 17582 Slog.w(TAG, "Not removing non-existent package " + packageName); 17583 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17584 } 17585 17586 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17587 && uninstalledPs.versionCode != versionCode) { 17588 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17589 + uninstalledPs.versionCode + " != " + versionCode); 17590 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17591 } 17592 17593 // Static shared libs can be declared by any package, so let us not 17594 // allow removing a package if it provides a lib others depend on. 17595 pkg = mPackages.get(packageName); 17596 17597 allUsers = sUserManager.getUserIds(); 17598 17599 if (pkg != null && pkg.staticSharedLibName != null) { 17600 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17601 pkg.staticSharedLibVersion); 17602 if (libEntry != null) { 17603 for (int currUserId : allUsers) { 17604 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17605 continue; 17606 } 17607 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17608 libEntry.info, 0, currUserId); 17609 if (!ArrayUtils.isEmpty(libClientPackages)) { 17610 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17611 + " hosting lib " + libEntry.info.getName() + " version " 17612 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17613 + " for user " + currUserId); 17614 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17615 } 17616 } 17617 } 17618 } 17619 17620 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17621 } 17622 17623 final int freezeUser; 17624 if (isUpdatedSystemApp(uninstalledPs) 17625 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17626 // We're downgrading a system app, which will apply to all users, so 17627 // freeze them all during the downgrade 17628 freezeUser = UserHandle.USER_ALL; 17629 } else { 17630 freezeUser = removeUser; 17631 } 17632 17633 synchronized (mInstallLock) { 17634 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17635 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17636 deleteFlags, "deletePackageX")) { 17637 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17638 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17639 } 17640 synchronized (mPackages) { 17641 if (res) { 17642 if (pkg != null) { 17643 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17644 } 17645 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17646 updateInstantAppInstallerLocked(packageName); 17647 } 17648 } 17649 } 17650 17651 if (res) { 17652 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17653 info.sendPackageRemovedBroadcasts(killApp); 17654 info.sendSystemPackageUpdatedBroadcasts(); 17655 info.sendSystemPackageAppearedBroadcasts(); 17656 } 17657 // Force a gc here. 17658 Runtime.getRuntime().gc(); 17659 // Delete the resources here after sending the broadcast to let 17660 // other processes clean up before deleting resources. 17661 if (info.args != null) { 17662 synchronized (mInstallLock) { 17663 info.args.doPostDeleteLI(true); 17664 } 17665 } 17666 17667 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17668 } 17669 17670 static class PackageRemovedInfo { 17671 final PackageSender packageSender; 17672 String removedPackage; 17673 String installerPackageName; 17674 int uid = -1; 17675 int removedAppId = -1; 17676 int[] origUsers; 17677 int[] removedUsers = null; 17678 int[] broadcastUsers = null; 17679 int[] instantUserIds = null; 17680 SparseArray<Integer> installReasons; 17681 boolean isRemovedPackageSystemUpdate = false; 17682 boolean isUpdate; 17683 boolean dataRemoved; 17684 boolean removedForAllUsers; 17685 boolean isStaticSharedLib; 17686 // Clean up resources deleted packages. 17687 InstallArgs args = null; 17688 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17689 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17690 17691 PackageRemovedInfo(PackageSender packageSender) { 17692 this.packageSender = packageSender; 17693 } 17694 17695 void sendPackageRemovedBroadcasts(boolean killApp) { 17696 sendPackageRemovedBroadcastInternal(killApp); 17697 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17698 for (int i = 0; i < childCount; i++) { 17699 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17700 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17701 } 17702 } 17703 17704 void sendSystemPackageUpdatedBroadcasts() { 17705 if (isRemovedPackageSystemUpdate) { 17706 sendSystemPackageUpdatedBroadcastsInternal(); 17707 final int childCount = (removedChildPackages != null) 17708 ? removedChildPackages.size() : 0; 17709 for (int i = 0; i < childCount; i++) { 17710 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17711 if (childInfo.isRemovedPackageSystemUpdate) { 17712 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17713 } 17714 } 17715 } 17716 } 17717 17718 void sendSystemPackageAppearedBroadcasts() { 17719 final int packageCount = (appearedChildPackages != null) 17720 ? appearedChildPackages.size() : 0; 17721 for (int i = 0; i < packageCount; i++) { 17722 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17723 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17724 true /*sendBootCompleted*/, false /*startReceiver*/, 17725 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17726 } 17727 } 17728 17729 private void sendSystemPackageUpdatedBroadcastsInternal() { 17730 Bundle extras = new Bundle(2); 17731 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17732 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17733 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17734 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17735 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17736 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17737 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17738 null, null, 0, removedPackage, null, null, null); 17739 if (installerPackageName != null) { 17740 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17741 removedPackage, extras, 0 /*flags*/, 17742 installerPackageName, null, null, null); 17743 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17744 removedPackage, extras, 0 /*flags*/, 17745 installerPackageName, null, null, null); 17746 } 17747 } 17748 17749 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17750 // Don't send static shared library removal broadcasts as these 17751 // libs are visible only the the apps that depend on them an one 17752 // cannot remove the library if it has a dependency. 17753 if (isStaticSharedLib) { 17754 return; 17755 } 17756 Bundle extras = new Bundle(2); 17757 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17758 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17759 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17760 if (isUpdate || isRemovedPackageSystemUpdate) { 17761 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17762 } 17763 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17764 if (removedPackage != null) { 17765 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17766 removedPackage, extras, 0, null /*targetPackage*/, null, 17767 broadcastUsers, instantUserIds); 17768 if (installerPackageName != null) { 17769 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17770 removedPackage, extras, 0 /*flags*/, 17771 installerPackageName, null, broadcastUsers, instantUserIds); 17772 } 17773 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17774 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17775 removedPackage, extras, 17776 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17777 null, null, broadcastUsers, instantUserIds); 17778 packageSender.notifyPackageRemoved(removedPackage); 17779 } 17780 } 17781 if (removedAppId >= 0) { 17782 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17783 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17784 null, null, broadcastUsers, instantUserIds); 17785 } 17786 } 17787 17788 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17789 removedUsers = userIds; 17790 if (removedUsers == null) { 17791 broadcastUsers = null; 17792 return; 17793 } 17794 17795 broadcastUsers = EMPTY_INT_ARRAY; 17796 instantUserIds = EMPTY_INT_ARRAY; 17797 for (int i = userIds.length - 1; i >= 0; --i) { 17798 final int userId = userIds[i]; 17799 if (deletedPackageSetting.getInstantApp(userId)) { 17800 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 17801 } else { 17802 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17803 } 17804 } 17805 } 17806 } 17807 17808 /* 17809 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17810 * flag is not set, the data directory is removed as well. 17811 * make sure this flag is set for partially installed apps. If not its meaningless to 17812 * delete a partially installed application. 17813 */ 17814 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17815 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17816 String packageName = ps.name; 17817 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17818 // Retrieve object to delete permissions for shared user later on 17819 final PackageParser.Package deletedPkg; 17820 final PackageSetting deletedPs; 17821 // reader 17822 synchronized (mPackages) { 17823 deletedPkg = mPackages.get(packageName); 17824 deletedPs = mSettings.mPackages.get(packageName); 17825 if (outInfo != null) { 17826 outInfo.removedPackage = packageName; 17827 outInfo.installerPackageName = ps.installerPackageName; 17828 outInfo.isStaticSharedLib = deletedPkg != null 17829 && deletedPkg.staticSharedLibName != null; 17830 outInfo.populateUsers(deletedPs == null ? null 17831 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17832 } 17833 } 17834 17835 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17836 17837 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17838 final PackageParser.Package resolvedPkg; 17839 if (deletedPkg != null) { 17840 resolvedPkg = deletedPkg; 17841 } else { 17842 // We don't have a parsed package when it lives on an ejected 17843 // adopted storage device, so fake something together 17844 resolvedPkg = new PackageParser.Package(ps.name); 17845 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17846 } 17847 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17848 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17849 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17850 if (outInfo != null) { 17851 outInfo.dataRemoved = true; 17852 } 17853 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17854 } 17855 17856 int removedAppId = -1; 17857 17858 // writer 17859 synchronized (mPackages) { 17860 boolean installedStateChanged = false; 17861 if (deletedPs != null) { 17862 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17863 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17864 clearDefaultBrowserIfNeeded(packageName); 17865 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17866 removedAppId = mSettings.removePackageLPw(packageName); 17867 if (outInfo != null) { 17868 outInfo.removedAppId = removedAppId; 17869 } 17870 mPermissionManager.updatePermissions( 17871 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17872 if (deletedPs.sharedUser != null) { 17873 // Remove permissions associated with package. Since runtime 17874 // permissions are per user we have to kill the removed package 17875 // or packages running under the shared user of the removed 17876 // package if revoking the permissions requested only by the removed 17877 // package is successful and this causes a change in gids. 17878 for (int userId : UserManagerService.getInstance().getUserIds()) { 17879 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17880 userId); 17881 if (userIdToKill == UserHandle.USER_ALL 17882 || userIdToKill >= UserHandle.USER_SYSTEM) { 17883 // If gids changed for this user, kill all affected packages. 17884 mHandler.post(new Runnable() { 17885 @Override 17886 public void run() { 17887 // This has to happen with no lock held. 17888 killApplication(deletedPs.name, deletedPs.appId, 17889 KILL_APP_REASON_GIDS_CHANGED); 17890 } 17891 }); 17892 break; 17893 } 17894 } 17895 } 17896 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17897 } 17898 // make sure to preserve per-user disabled state if this removal was just 17899 // a downgrade of a system app to the factory package 17900 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17901 if (DEBUG_REMOVE) { 17902 Slog.d(TAG, "Propagating install state across downgrade"); 17903 } 17904 for (int userId : allUserHandles) { 17905 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17906 if (DEBUG_REMOVE) { 17907 Slog.d(TAG, " user " + userId + " => " + installed); 17908 } 17909 if (installed != ps.getInstalled(userId)) { 17910 installedStateChanged = true; 17911 } 17912 ps.setInstalled(installed, userId); 17913 } 17914 } 17915 } 17916 // can downgrade to reader 17917 if (writeSettings) { 17918 // Save settings now 17919 mSettings.writeLPr(); 17920 } 17921 if (installedStateChanged) { 17922 mSettings.writeKernelMappingLPr(ps); 17923 } 17924 } 17925 if (removedAppId != -1) { 17926 // A user ID was deleted here. Go through all users and remove it 17927 // from KeyStore. 17928 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17929 } 17930 } 17931 17932 static boolean locationIsPrivileged(String path) { 17933 try { 17934 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 17935 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 17936 return path.startsWith(privilegedAppDir.getCanonicalPath()) 17937 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 17938 } catch (IOException e) { 17939 Slog.e(TAG, "Unable to access code path " + path); 17940 } 17941 return false; 17942 } 17943 17944 static boolean locationIsOem(String path) { 17945 try { 17946 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 17947 } catch (IOException e) { 17948 Slog.e(TAG, "Unable to access code path " + path); 17949 } 17950 return false; 17951 } 17952 17953 static boolean locationIsVendor(String path) { 17954 try { 17955 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 17956 } catch (IOException e) { 17957 Slog.e(TAG, "Unable to access code path " + path); 17958 } 17959 return false; 17960 } 17961 17962 /* 17963 * Tries to delete system package. 17964 */ 17965 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17966 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17967 boolean writeSettings) { 17968 if (deletedPs.parentPackageName != null) { 17969 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17970 return false; 17971 } 17972 17973 final boolean applyUserRestrictions 17974 = (allUserHandles != null) && (outInfo.origUsers != null); 17975 final PackageSetting disabledPs; 17976 // Confirm if the system package has been updated 17977 // An updated system app can be deleted. This will also have to restore 17978 // the system pkg from system partition 17979 // reader 17980 synchronized (mPackages) { 17981 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17982 } 17983 17984 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17985 + " disabledPs=" + disabledPs); 17986 17987 if (disabledPs == null) { 17988 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17989 return false; 17990 } else if (DEBUG_REMOVE) { 17991 Slog.d(TAG, "Deleting system pkg from data partition"); 17992 } 17993 17994 if (DEBUG_REMOVE) { 17995 if (applyUserRestrictions) { 17996 Slog.d(TAG, "Remembering install states:"); 17997 for (int userId : allUserHandles) { 17998 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17999 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18000 } 18001 } 18002 } 18003 18004 // Delete the updated package 18005 outInfo.isRemovedPackageSystemUpdate = true; 18006 if (outInfo.removedChildPackages != null) { 18007 final int childCount = (deletedPs.childPackageNames != null) 18008 ? deletedPs.childPackageNames.size() : 0; 18009 for (int i = 0; i < childCount; i++) { 18010 String childPackageName = deletedPs.childPackageNames.get(i); 18011 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18012 .contains(childPackageName)) { 18013 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18014 childPackageName); 18015 if (childInfo != null) { 18016 childInfo.isRemovedPackageSystemUpdate = true; 18017 } 18018 } 18019 } 18020 } 18021 18022 if (disabledPs.versionCode < deletedPs.versionCode) { 18023 // Delete data for downgrades 18024 flags &= ~PackageManager.DELETE_KEEP_DATA; 18025 } else { 18026 // Preserve data by setting flag 18027 flags |= PackageManager.DELETE_KEEP_DATA; 18028 } 18029 18030 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18031 outInfo, writeSettings, disabledPs.pkg); 18032 if (!ret) { 18033 return false; 18034 } 18035 18036 // writer 18037 synchronized (mPackages) { 18038 // NOTE: The system package always needs to be enabled; even if it's for 18039 // a compressed stub. If we don't, installing the system package fails 18040 // during scan [scanning checks the disabled packages]. We will reverse 18041 // this later, after we've "installed" the stub. 18042 // Reinstate the old system package 18043 enableSystemPackageLPw(disabledPs.pkg); 18044 // Remove any native libraries from the upgraded package. 18045 removeNativeBinariesLI(deletedPs); 18046 } 18047 18048 // Install the system package 18049 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18050 try { 18051 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18052 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18053 } catch (PackageManagerException e) { 18054 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18055 + e.getMessage()); 18056 return false; 18057 } finally { 18058 if (disabledPs.pkg.isStub) { 18059 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18060 } 18061 } 18062 return true; 18063 } 18064 18065 /** 18066 * Installs a package that's already on the system partition. 18067 */ 18068 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18069 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18070 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18071 throws PackageManagerException { 18072 @ParseFlags int parseFlags = 18073 mDefParseFlags 18074 | PackageParser.PARSE_MUST_BE_APK 18075 | PackageParser.PARSE_IS_SYSTEM_DIR; 18076 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18077 if (isPrivileged || locationIsPrivileged(codePathString)) { 18078 scanFlags |= SCAN_AS_PRIVILEGED; 18079 } 18080 if (locationIsOem(codePathString)) { 18081 scanFlags |= SCAN_AS_OEM; 18082 } 18083 if (locationIsVendor(codePathString)) { 18084 scanFlags |= SCAN_AS_VENDOR; 18085 } 18086 18087 final File codePath = new File(codePathString); 18088 final PackageParser.Package pkg = 18089 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18090 18091 try { 18092 // update shared libraries for the newly re-installed system package 18093 updateSharedLibrariesLPr(pkg, null); 18094 } catch (PackageManagerException e) { 18095 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18096 } 18097 18098 prepareAppDataAfterInstallLIF(pkg); 18099 18100 // writer 18101 synchronized (mPackages) { 18102 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18103 18104 // Propagate the permissions state as we do not want to drop on the floor 18105 // runtime permissions. The update permissions method below will take 18106 // care of removing obsolete permissions and grant install permissions. 18107 if (origPermissionState != null) { 18108 ps.getPermissionsState().copyFrom(origPermissionState); 18109 } 18110 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18111 mPermissionCallback); 18112 18113 final boolean applyUserRestrictions 18114 = (allUserHandles != null) && (origUserHandles != null); 18115 if (applyUserRestrictions) { 18116 boolean installedStateChanged = false; 18117 if (DEBUG_REMOVE) { 18118 Slog.d(TAG, "Propagating install state across reinstall"); 18119 } 18120 for (int userId : allUserHandles) { 18121 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18122 if (DEBUG_REMOVE) { 18123 Slog.d(TAG, " user " + userId + " => " + installed); 18124 } 18125 if (installed != ps.getInstalled(userId)) { 18126 installedStateChanged = true; 18127 } 18128 ps.setInstalled(installed, userId); 18129 18130 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18131 } 18132 // Regardless of writeSettings we need to ensure that this restriction 18133 // state propagation is persisted 18134 mSettings.writeAllUsersPackageRestrictionsLPr(); 18135 if (installedStateChanged) { 18136 mSettings.writeKernelMappingLPr(ps); 18137 } 18138 } 18139 // can downgrade to reader here 18140 if (writeSettings) { 18141 mSettings.writeLPr(); 18142 } 18143 } 18144 return pkg; 18145 } 18146 18147 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18148 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18149 PackageRemovedInfo outInfo, boolean writeSettings, 18150 PackageParser.Package replacingPackage) { 18151 synchronized (mPackages) { 18152 if (outInfo != null) { 18153 outInfo.uid = ps.appId; 18154 } 18155 18156 if (outInfo != null && outInfo.removedChildPackages != null) { 18157 final int childCount = (ps.childPackageNames != null) 18158 ? ps.childPackageNames.size() : 0; 18159 for (int i = 0; i < childCount; i++) { 18160 String childPackageName = ps.childPackageNames.get(i); 18161 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18162 if (childPs == null) { 18163 return false; 18164 } 18165 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18166 childPackageName); 18167 if (childInfo != null) { 18168 childInfo.uid = childPs.appId; 18169 } 18170 } 18171 } 18172 } 18173 18174 // Delete package data from internal structures and also remove data if flag is set 18175 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18176 18177 // Delete the child packages data 18178 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18179 for (int i = 0; i < childCount; i++) { 18180 PackageSetting childPs; 18181 synchronized (mPackages) { 18182 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18183 } 18184 if (childPs != null) { 18185 PackageRemovedInfo childOutInfo = (outInfo != null 18186 && outInfo.removedChildPackages != null) 18187 ? outInfo.removedChildPackages.get(childPs.name) : null; 18188 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18189 && (replacingPackage != null 18190 && !replacingPackage.hasChildPackage(childPs.name)) 18191 ? flags & ~DELETE_KEEP_DATA : flags; 18192 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18193 deleteFlags, writeSettings); 18194 } 18195 } 18196 18197 // Delete application code and resources only for parent packages 18198 if (ps.parentPackageName == null) { 18199 if (deleteCodeAndResources && (outInfo != null)) { 18200 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18201 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18202 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18203 } 18204 } 18205 18206 return true; 18207 } 18208 18209 @Override 18210 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18211 int userId) { 18212 mContext.enforceCallingOrSelfPermission( 18213 android.Manifest.permission.DELETE_PACKAGES, null); 18214 synchronized (mPackages) { 18215 // Cannot block uninstall of static shared libs as they are 18216 // considered a part of the using app (emulating static linking). 18217 // Also static libs are installed always on internal storage. 18218 PackageParser.Package pkg = mPackages.get(packageName); 18219 if (pkg != null && pkg.staticSharedLibName != null) { 18220 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18221 + " providing static shared library: " + pkg.staticSharedLibName); 18222 return false; 18223 } 18224 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18225 mSettings.writePackageRestrictionsLPr(userId); 18226 } 18227 return true; 18228 } 18229 18230 @Override 18231 public boolean getBlockUninstallForUser(String packageName, int userId) { 18232 synchronized (mPackages) { 18233 final PackageSetting ps = mSettings.mPackages.get(packageName); 18234 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18235 return false; 18236 } 18237 return mSettings.getBlockUninstallLPr(userId, packageName); 18238 } 18239 } 18240 18241 @Override 18242 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18243 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18244 synchronized (mPackages) { 18245 PackageSetting ps = mSettings.mPackages.get(packageName); 18246 if (ps == null) { 18247 Log.w(TAG, "Package doesn't exist: " + packageName); 18248 return false; 18249 } 18250 if (systemUserApp) { 18251 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18252 } else { 18253 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18254 } 18255 mSettings.writeLPr(); 18256 } 18257 return true; 18258 } 18259 18260 /* 18261 * This method handles package deletion in general 18262 */ 18263 private boolean deletePackageLIF(String packageName, UserHandle user, 18264 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18265 PackageRemovedInfo outInfo, boolean writeSettings, 18266 PackageParser.Package replacingPackage) { 18267 if (packageName == null) { 18268 Slog.w(TAG, "Attempt to delete null packageName."); 18269 return false; 18270 } 18271 18272 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18273 18274 PackageSetting ps; 18275 synchronized (mPackages) { 18276 ps = mSettings.mPackages.get(packageName); 18277 if (ps == null) { 18278 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18279 return false; 18280 } 18281 18282 if (ps.parentPackageName != null && (!isSystemApp(ps) 18283 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18284 if (DEBUG_REMOVE) { 18285 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18286 + ((user == null) ? UserHandle.USER_ALL : user)); 18287 } 18288 final int removedUserId = (user != null) ? user.getIdentifier() 18289 : UserHandle.USER_ALL; 18290 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18291 return false; 18292 } 18293 markPackageUninstalledForUserLPw(ps, user); 18294 scheduleWritePackageRestrictionsLocked(user); 18295 return true; 18296 } 18297 } 18298 18299 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18300 && user.getIdentifier() != UserHandle.USER_ALL)) { 18301 // The caller is asking that the package only be deleted for a single 18302 // user. To do this, we just mark its uninstalled state and delete 18303 // its data. If this is a system app, we only allow this to happen if 18304 // they have set the special DELETE_SYSTEM_APP which requests different 18305 // semantics than normal for uninstalling system apps. 18306 markPackageUninstalledForUserLPw(ps, user); 18307 18308 if (!isSystemApp(ps)) { 18309 // Do not uninstall the APK if an app should be cached 18310 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18311 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18312 // Other user still have this package installed, so all 18313 // we need to do is clear this user's data and save that 18314 // it is uninstalled. 18315 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18316 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18317 return false; 18318 } 18319 scheduleWritePackageRestrictionsLocked(user); 18320 return true; 18321 } else { 18322 // We need to set it back to 'installed' so the uninstall 18323 // broadcasts will be sent correctly. 18324 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18325 ps.setInstalled(true, user.getIdentifier()); 18326 mSettings.writeKernelMappingLPr(ps); 18327 } 18328 } else { 18329 // This is a system app, so we assume that the 18330 // other users still have this package installed, so all 18331 // we need to do is clear this user's data and save that 18332 // it is uninstalled. 18333 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18334 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18335 return false; 18336 } 18337 scheduleWritePackageRestrictionsLocked(user); 18338 return true; 18339 } 18340 } 18341 18342 // If we are deleting a composite package for all users, keep track 18343 // of result for each child. 18344 if (ps.childPackageNames != null && outInfo != null) { 18345 synchronized (mPackages) { 18346 final int childCount = ps.childPackageNames.size(); 18347 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18348 for (int i = 0; i < childCount; i++) { 18349 String childPackageName = ps.childPackageNames.get(i); 18350 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18351 childInfo.removedPackage = childPackageName; 18352 childInfo.installerPackageName = ps.installerPackageName; 18353 outInfo.removedChildPackages.put(childPackageName, childInfo); 18354 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18355 if (childPs != null) { 18356 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18357 } 18358 } 18359 } 18360 } 18361 18362 boolean ret = false; 18363 if (isSystemApp(ps)) { 18364 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18365 // When an updated system application is deleted we delete the existing resources 18366 // as well and fall back to existing code in system partition 18367 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18368 } else { 18369 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18370 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18371 outInfo, writeSettings, replacingPackage); 18372 } 18373 18374 // Take a note whether we deleted the package for all users 18375 if (outInfo != null) { 18376 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18377 if (outInfo.removedChildPackages != null) { 18378 synchronized (mPackages) { 18379 final int childCount = outInfo.removedChildPackages.size(); 18380 for (int i = 0; i < childCount; i++) { 18381 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18382 if (childInfo != null) { 18383 childInfo.removedForAllUsers = mPackages.get( 18384 childInfo.removedPackage) == null; 18385 } 18386 } 18387 } 18388 } 18389 // If we uninstalled an update to a system app there may be some 18390 // child packages that appeared as they are declared in the system 18391 // app but were not declared in the update. 18392 if (isSystemApp(ps)) { 18393 synchronized (mPackages) { 18394 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18395 final int childCount = (updatedPs.childPackageNames != null) 18396 ? updatedPs.childPackageNames.size() : 0; 18397 for (int i = 0; i < childCount; i++) { 18398 String childPackageName = updatedPs.childPackageNames.get(i); 18399 if (outInfo.removedChildPackages == null 18400 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18401 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18402 if (childPs == null) { 18403 continue; 18404 } 18405 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18406 installRes.name = childPackageName; 18407 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18408 installRes.pkg = mPackages.get(childPackageName); 18409 installRes.uid = childPs.pkg.applicationInfo.uid; 18410 if (outInfo.appearedChildPackages == null) { 18411 outInfo.appearedChildPackages = new ArrayMap<>(); 18412 } 18413 outInfo.appearedChildPackages.put(childPackageName, installRes); 18414 } 18415 } 18416 } 18417 } 18418 } 18419 18420 return ret; 18421 } 18422 18423 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18424 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18425 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18426 for (int nextUserId : userIds) { 18427 if (DEBUG_REMOVE) { 18428 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18429 } 18430 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18431 false /*installed*/, 18432 true /*stopped*/, 18433 true /*notLaunched*/, 18434 false /*hidden*/, 18435 false /*suspended*/, 18436 false /*instantApp*/, 18437 false /*virtualPreload*/, 18438 null /*lastDisableAppCaller*/, 18439 null /*enabledComponents*/, 18440 null /*disabledComponents*/, 18441 ps.readUserState(nextUserId).domainVerificationStatus, 18442 0, PackageManager.INSTALL_REASON_UNKNOWN, 18443 null /*harmfulAppWarning*/); 18444 } 18445 mSettings.writeKernelMappingLPr(ps); 18446 } 18447 18448 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18449 PackageRemovedInfo outInfo) { 18450 final PackageParser.Package pkg; 18451 synchronized (mPackages) { 18452 pkg = mPackages.get(ps.name); 18453 } 18454 18455 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18456 : new int[] {userId}; 18457 for (int nextUserId : userIds) { 18458 if (DEBUG_REMOVE) { 18459 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18460 + nextUserId); 18461 } 18462 18463 destroyAppDataLIF(pkg, userId, 18464 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18465 destroyAppProfilesLIF(pkg, userId); 18466 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18467 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18468 schedulePackageCleaning(ps.name, nextUserId, false); 18469 synchronized (mPackages) { 18470 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18471 scheduleWritePackageRestrictionsLocked(nextUserId); 18472 } 18473 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18474 } 18475 } 18476 18477 if (outInfo != null) { 18478 outInfo.removedPackage = ps.name; 18479 outInfo.installerPackageName = ps.installerPackageName; 18480 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18481 outInfo.removedAppId = ps.appId; 18482 outInfo.removedUsers = userIds; 18483 outInfo.broadcastUsers = userIds; 18484 } 18485 18486 return true; 18487 } 18488 18489 private final class ClearStorageConnection implements ServiceConnection { 18490 IMediaContainerService mContainerService; 18491 18492 @Override 18493 public void onServiceConnected(ComponentName name, IBinder service) { 18494 synchronized (this) { 18495 mContainerService = IMediaContainerService.Stub 18496 .asInterface(Binder.allowBlocking(service)); 18497 notifyAll(); 18498 } 18499 } 18500 18501 @Override 18502 public void onServiceDisconnected(ComponentName name) { 18503 } 18504 } 18505 18506 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18507 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18508 18509 final boolean mounted; 18510 if (Environment.isExternalStorageEmulated()) { 18511 mounted = true; 18512 } else { 18513 final String status = Environment.getExternalStorageState(); 18514 18515 mounted = status.equals(Environment.MEDIA_MOUNTED) 18516 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18517 } 18518 18519 if (!mounted) { 18520 return; 18521 } 18522 18523 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18524 int[] users; 18525 if (userId == UserHandle.USER_ALL) { 18526 users = sUserManager.getUserIds(); 18527 } else { 18528 users = new int[] { userId }; 18529 } 18530 final ClearStorageConnection conn = new ClearStorageConnection(); 18531 if (mContext.bindServiceAsUser( 18532 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18533 try { 18534 for (int curUser : users) { 18535 long timeout = SystemClock.uptimeMillis() + 5000; 18536 synchronized (conn) { 18537 long now; 18538 while (conn.mContainerService == null && 18539 (now = SystemClock.uptimeMillis()) < timeout) { 18540 try { 18541 conn.wait(timeout - now); 18542 } catch (InterruptedException e) { 18543 } 18544 } 18545 } 18546 if (conn.mContainerService == null) { 18547 return; 18548 } 18549 18550 final UserEnvironment userEnv = new UserEnvironment(curUser); 18551 clearDirectory(conn.mContainerService, 18552 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18553 if (allData) { 18554 clearDirectory(conn.mContainerService, 18555 userEnv.buildExternalStorageAppDataDirs(packageName)); 18556 clearDirectory(conn.mContainerService, 18557 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18558 } 18559 } 18560 } finally { 18561 mContext.unbindService(conn); 18562 } 18563 } 18564 } 18565 18566 @Override 18567 public void clearApplicationProfileData(String packageName) { 18568 enforceSystemOrRoot("Only the system can clear all profile data"); 18569 18570 final PackageParser.Package pkg; 18571 synchronized (mPackages) { 18572 pkg = mPackages.get(packageName); 18573 } 18574 18575 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18576 synchronized (mInstallLock) { 18577 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18578 } 18579 } 18580 } 18581 18582 @Override 18583 public void clearApplicationUserData(final String packageName, 18584 final IPackageDataObserver observer, final int userId) { 18585 mContext.enforceCallingOrSelfPermission( 18586 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18587 18588 final int callingUid = Binder.getCallingUid(); 18589 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18590 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18591 18592 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18593 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18594 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18595 throw new SecurityException("Cannot clear data for a protected package: " 18596 + packageName); 18597 } 18598 // Queue up an async operation since the package deletion may take a little while. 18599 mHandler.post(new Runnable() { 18600 public void run() { 18601 mHandler.removeCallbacks(this); 18602 final boolean succeeded; 18603 if (!filterApp) { 18604 try (PackageFreezer freezer = freezePackage(packageName, 18605 "clearApplicationUserData")) { 18606 synchronized (mInstallLock) { 18607 succeeded = clearApplicationUserDataLIF(packageName, userId); 18608 } 18609 clearExternalStorageDataSync(packageName, userId, true); 18610 synchronized (mPackages) { 18611 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18612 packageName, userId); 18613 } 18614 } 18615 if (succeeded) { 18616 // invoke DeviceStorageMonitor's update method to clear any notifications 18617 DeviceStorageMonitorInternal dsm = LocalServices 18618 .getService(DeviceStorageMonitorInternal.class); 18619 if (dsm != null) { 18620 dsm.checkMemory(); 18621 } 18622 } 18623 } else { 18624 succeeded = false; 18625 } 18626 if (observer != null) { 18627 try { 18628 observer.onRemoveCompleted(packageName, succeeded); 18629 } catch (RemoteException e) { 18630 Log.i(TAG, "Observer no longer exists."); 18631 } 18632 } //end if observer 18633 } //end run 18634 }); 18635 } 18636 18637 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18638 if (packageName == null) { 18639 Slog.w(TAG, "Attempt to delete null packageName."); 18640 return false; 18641 } 18642 18643 // Try finding details about the requested package 18644 PackageParser.Package pkg; 18645 synchronized (mPackages) { 18646 pkg = mPackages.get(packageName); 18647 if (pkg == null) { 18648 final PackageSetting ps = mSettings.mPackages.get(packageName); 18649 if (ps != null) { 18650 pkg = ps.pkg; 18651 } 18652 } 18653 18654 if (pkg == null) { 18655 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18656 return false; 18657 } 18658 18659 PackageSetting ps = (PackageSetting) pkg.mExtras; 18660 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18661 } 18662 18663 clearAppDataLIF(pkg, userId, 18664 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18665 18666 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18667 removeKeystoreDataIfNeeded(userId, appId); 18668 18669 UserManagerInternal umInternal = getUserManagerInternal(); 18670 final int flags; 18671 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18672 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18673 } else if (umInternal.isUserRunning(userId)) { 18674 flags = StorageManager.FLAG_STORAGE_DE; 18675 } else { 18676 flags = 0; 18677 } 18678 prepareAppDataContentsLIF(pkg, userId, flags); 18679 18680 return true; 18681 } 18682 18683 /** 18684 * Reverts user permission state changes (permissions and flags) in 18685 * all packages for a given user. 18686 * 18687 * @param userId The device user for which to do a reset. 18688 */ 18689 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18690 final int packageCount = mPackages.size(); 18691 for (int i = 0; i < packageCount; i++) { 18692 PackageParser.Package pkg = mPackages.valueAt(i); 18693 PackageSetting ps = (PackageSetting) pkg.mExtras; 18694 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18695 } 18696 } 18697 18698 private void resetNetworkPolicies(int userId) { 18699 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18700 } 18701 18702 /** 18703 * Reverts user permission state changes (permissions and flags). 18704 * 18705 * @param ps The package for which to reset. 18706 * @param userId The device user for which to do a reset. 18707 */ 18708 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18709 final PackageSetting ps, final int userId) { 18710 if (ps.pkg == null) { 18711 return; 18712 } 18713 18714 // These are flags that can change base on user actions. 18715 final int userSettableMask = FLAG_PERMISSION_USER_SET 18716 | FLAG_PERMISSION_USER_FIXED 18717 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18718 | FLAG_PERMISSION_REVIEW_REQUIRED; 18719 18720 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18721 | FLAG_PERMISSION_POLICY_FIXED; 18722 18723 boolean writeInstallPermissions = false; 18724 boolean writeRuntimePermissions = false; 18725 18726 final int permissionCount = ps.pkg.requestedPermissions.size(); 18727 for (int i = 0; i < permissionCount; i++) { 18728 final String permName = ps.pkg.requestedPermissions.get(i); 18729 final BasePermission bp = 18730 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18731 if (bp == null) { 18732 continue; 18733 } 18734 18735 // If shared user we just reset the state to which only this app contributed. 18736 if (ps.sharedUser != null) { 18737 boolean used = false; 18738 final int packageCount = ps.sharedUser.packages.size(); 18739 for (int j = 0; j < packageCount; j++) { 18740 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18741 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18742 && pkg.pkg.requestedPermissions.contains(permName)) { 18743 used = true; 18744 break; 18745 } 18746 } 18747 if (used) { 18748 continue; 18749 } 18750 } 18751 18752 final PermissionsState permissionsState = ps.getPermissionsState(); 18753 18754 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18755 18756 // Always clear the user settable flags. 18757 final boolean hasInstallState = 18758 permissionsState.getInstallPermissionState(permName) != null; 18759 // If permission review is enabled and this is a legacy app, mark the 18760 // permission as requiring a review as this is the initial state. 18761 int flags = 0; 18762 if (mSettings.mPermissions.mPermissionReviewRequired 18763 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18764 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18765 } 18766 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18767 if (hasInstallState) { 18768 writeInstallPermissions = true; 18769 } else { 18770 writeRuntimePermissions = true; 18771 } 18772 } 18773 18774 // Below is only runtime permission handling. 18775 if (!bp.isRuntime()) { 18776 continue; 18777 } 18778 18779 // Never clobber system or policy. 18780 if ((oldFlags & policyOrSystemFlags) != 0) { 18781 continue; 18782 } 18783 18784 // If this permission was granted by default, make sure it is. 18785 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18786 if (permissionsState.grantRuntimePermission(bp, userId) 18787 != PERMISSION_OPERATION_FAILURE) { 18788 writeRuntimePermissions = true; 18789 } 18790 // If permission review is enabled the permissions for a legacy apps 18791 // are represented as constantly granted runtime ones, so don't revoke. 18792 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18793 // Otherwise, reset the permission. 18794 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18795 switch (revokeResult) { 18796 case PERMISSION_OPERATION_SUCCESS: 18797 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18798 writeRuntimePermissions = true; 18799 final int appId = ps.appId; 18800 mHandler.post(new Runnable() { 18801 @Override 18802 public void run() { 18803 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18804 } 18805 }); 18806 } break; 18807 } 18808 } 18809 } 18810 18811 // Synchronously write as we are taking permissions away. 18812 if (writeRuntimePermissions) { 18813 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18814 } 18815 18816 // Synchronously write as we are taking permissions away. 18817 if (writeInstallPermissions) { 18818 mSettings.writeLPr(); 18819 } 18820 } 18821 18822 /** 18823 * Remove entries from the keystore daemon. Will only remove it if the 18824 * {@code appId} is valid. 18825 */ 18826 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18827 if (appId < 0) { 18828 return; 18829 } 18830 18831 final KeyStore keyStore = KeyStore.getInstance(); 18832 if (keyStore != null) { 18833 if (userId == UserHandle.USER_ALL) { 18834 for (final int individual : sUserManager.getUserIds()) { 18835 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18836 } 18837 } else { 18838 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18839 } 18840 } else { 18841 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18842 } 18843 } 18844 18845 @Override 18846 public void deleteApplicationCacheFiles(final String packageName, 18847 final IPackageDataObserver observer) { 18848 final int userId = UserHandle.getCallingUserId(); 18849 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18850 } 18851 18852 @Override 18853 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18854 final IPackageDataObserver observer) { 18855 final int callingUid = Binder.getCallingUid(); 18856 mContext.enforceCallingOrSelfPermission( 18857 android.Manifest.permission.DELETE_CACHE_FILES, null); 18858 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18859 /* requireFullPermission= */ true, /* checkShell= */ false, 18860 "delete application cache files"); 18861 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18862 android.Manifest.permission.ACCESS_INSTANT_APPS); 18863 18864 final PackageParser.Package pkg; 18865 synchronized (mPackages) { 18866 pkg = mPackages.get(packageName); 18867 } 18868 18869 // Queue up an async operation since the package deletion may take a little while. 18870 mHandler.post(new Runnable() { 18871 public void run() { 18872 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18873 boolean doClearData = true; 18874 if (ps != null) { 18875 final boolean targetIsInstantApp = 18876 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18877 doClearData = !targetIsInstantApp 18878 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18879 } 18880 if (doClearData) { 18881 synchronized (mInstallLock) { 18882 final int flags = StorageManager.FLAG_STORAGE_DE 18883 | StorageManager.FLAG_STORAGE_CE; 18884 // We're only clearing cache files, so we don't care if the 18885 // app is unfrozen and still able to run 18886 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18887 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18888 } 18889 clearExternalStorageDataSync(packageName, userId, false); 18890 } 18891 if (observer != null) { 18892 try { 18893 observer.onRemoveCompleted(packageName, true); 18894 } catch (RemoteException e) { 18895 Log.i(TAG, "Observer no longer exists."); 18896 } 18897 } 18898 } 18899 }); 18900 } 18901 18902 @Override 18903 public void getPackageSizeInfo(final String packageName, int userHandle, 18904 final IPackageStatsObserver observer) { 18905 throw new UnsupportedOperationException( 18906 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18907 } 18908 18909 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18910 final PackageSetting ps; 18911 synchronized (mPackages) { 18912 ps = mSettings.mPackages.get(packageName); 18913 if (ps == null) { 18914 Slog.w(TAG, "Failed to find settings for " + packageName); 18915 return false; 18916 } 18917 } 18918 18919 final String[] packageNames = { packageName }; 18920 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18921 final String[] codePaths = { ps.codePathString }; 18922 18923 try { 18924 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18925 ps.appId, ceDataInodes, codePaths, stats); 18926 18927 // For now, ignore code size of packages on system partition 18928 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18929 stats.codeSize = 0; 18930 } 18931 18932 // External clients expect these to be tracked separately 18933 stats.dataSize -= stats.cacheSize; 18934 18935 } catch (InstallerException e) { 18936 Slog.w(TAG, String.valueOf(e)); 18937 return false; 18938 } 18939 18940 return true; 18941 } 18942 18943 private int getUidTargetSdkVersionLockedLPr(int uid) { 18944 Object obj = mSettings.getUserIdLPr(uid); 18945 if (obj instanceof SharedUserSetting) { 18946 final SharedUserSetting sus = (SharedUserSetting) obj; 18947 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18948 final Iterator<PackageSetting> it = sus.packages.iterator(); 18949 while (it.hasNext()) { 18950 final PackageSetting ps = it.next(); 18951 if (ps.pkg != null) { 18952 int v = ps.pkg.applicationInfo.targetSdkVersion; 18953 if (v < vers) vers = v; 18954 } 18955 } 18956 return vers; 18957 } else if (obj instanceof PackageSetting) { 18958 final PackageSetting ps = (PackageSetting) obj; 18959 if (ps.pkg != null) { 18960 return ps.pkg.applicationInfo.targetSdkVersion; 18961 } 18962 } 18963 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18964 } 18965 18966 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 18967 final PackageParser.Package p = mPackages.get(packageName); 18968 if (p != null) { 18969 return p.applicationInfo.targetSdkVersion; 18970 } 18971 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18972 } 18973 18974 @Override 18975 public void addPreferredActivity(IntentFilter filter, int match, 18976 ComponentName[] set, ComponentName activity, int userId) { 18977 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18978 "Adding preferred"); 18979 } 18980 18981 private void addPreferredActivityInternal(IntentFilter filter, int match, 18982 ComponentName[] set, ComponentName activity, boolean always, int userId, 18983 String opname) { 18984 // writer 18985 int callingUid = Binder.getCallingUid(); 18986 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18987 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18988 if (filter.countActions() == 0) { 18989 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18990 return; 18991 } 18992 synchronized (mPackages) { 18993 if (mContext.checkCallingOrSelfPermission( 18994 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18995 != PackageManager.PERMISSION_GRANTED) { 18996 if (getUidTargetSdkVersionLockedLPr(callingUid) 18997 < Build.VERSION_CODES.FROYO) { 18998 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18999 + callingUid); 19000 return; 19001 } 19002 mContext.enforceCallingOrSelfPermission( 19003 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19004 } 19005 19006 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19007 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19008 + userId + ":"); 19009 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19010 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19011 scheduleWritePackageRestrictionsLocked(userId); 19012 postPreferredActivityChangedBroadcast(userId); 19013 } 19014 } 19015 19016 private void postPreferredActivityChangedBroadcast(int userId) { 19017 mHandler.post(() -> { 19018 final IActivityManager am = ActivityManager.getService(); 19019 if (am == null) { 19020 return; 19021 } 19022 19023 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19024 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19025 try { 19026 am.broadcastIntent(null, intent, null, null, 19027 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19028 null, false, false, userId); 19029 } catch (RemoteException e) { 19030 } 19031 }); 19032 } 19033 19034 @Override 19035 public void replacePreferredActivity(IntentFilter filter, int match, 19036 ComponentName[] set, ComponentName activity, int userId) { 19037 if (filter.countActions() != 1) { 19038 throw new IllegalArgumentException( 19039 "replacePreferredActivity expects filter to have only 1 action."); 19040 } 19041 if (filter.countDataAuthorities() != 0 19042 || filter.countDataPaths() != 0 19043 || filter.countDataSchemes() > 1 19044 || filter.countDataTypes() != 0) { 19045 throw new IllegalArgumentException( 19046 "replacePreferredActivity expects filter to have no data authorities, " + 19047 "paths, or types; and at most one scheme."); 19048 } 19049 19050 final int callingUid = Binder.getCallingUid(); 19051 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19052 true /* requireFullPermission */, false /* checkShell */, 19053 "replace preferred activity"); 19054 synchronized (mPackages) { 19055 if (mContext.checkCallingOrSelfPermission( 19056 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19057 != PackageManager.PERMISSION_GRANTED) { 19058 if (getUidTargetSdkVersionLockedLPr(callingUid) 19059 < Build.VERSION_CODES.FROYO) { 19060 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19061 + Binder.getCallingUid()); 19062 return; 19063 } 19064 mContext.enforceCallingOrSelfPermission( 19065 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19066 } 19067 19068 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19069 if (pir != null) { 19070 // Get all of the existing entries that exactly match this filter. 19071 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19072 if (existing != null && existing.size() == 1) { 19073 PreferredActivity cur = existing.get(0); 19074 if (DEBUG_PREFERRED) { 19075 Slog.i(TAG, "Checking replace of preferred:"); 19076 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19077 if (!cur.mPref.mAlways) { 19078 Slog.i(TAG, " -- CUR; not mAlways!"); 19079 } else { 19080 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19081 Slog.i(TAG, " -- CUR: mSet=" 19082 + Arrays.toString(cur.mPref.mSetComponents)); 19083 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19084 Slog.i(TAG, " -- NEW: mMatch=" 19085 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19086 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19087 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19088 } 19089 } 19090 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19091 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19092 && cur.mPref.sameSet(set)) { 19093 // Setting the preferred activity to what it happens to be already 19094 if (DEBUG_PREFERRED) { 19095 Slog.i(TAG, "Replacing with same preferred activity " 19096 + cur.mPref.mShortComponent + " for user " 19097 + userId + ":"); 19098 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19099 } 19100 return; 19101 } 19102 } 19103 19104 if (existing != null) { 19105 if (DEBUG_PREFERRED) { 19106 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19107 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19108 } 19109 for (int i = 0; i < existing.size(); i++) { 19110 PreferredActivity pa = existing.get(i); 19111 if (DEBUG_PREFERRED) { 19112 Slog.i(TAG, "Removing existing preferred activity " 19113 + pa.mPref.mComponent + ":"); 19114 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19115 } 19116 pir.removeFilter(pa); 19117 } 19118 } 19119 } 19120 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19121 "Replacing preferred"); 19122 } 19123 } 19124 19125 @Override 19126 public void clearPackagePreferredActivities(String packageName) { 19127 final int callingUid = Binder.getCallingUid(); 19128 if (getInstantAppPackageName(callingUid) != null) { 19129 return; 19130 } 19131 // writer 19132 synchronized (mPackages) { 19133 PackageParser.Package pkg = mPackages.get(packageName); 19134 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19135 if (mContext.checkCallingOrSelfPermission( 19136 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19137 != PackageManager.PERMISSION_GRANTED) { 19138 if (getUidTargetSdkVersionLockedLPr(callingUid) 19139 < Build.VERSION_CODES.FROYO) { 19140 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19141 + callingUid); 19142 return; 19143 } 19144 mContext.enforceCallingOrSelfPermission( 19145 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19146 } 19147 } 19148 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19149 if (ps != null 19150 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19151 return; 19152 } 19153 int user = UserHandle.getCallingUserId(); 19154 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19155 scheduleWritePackageRestrictionsLocked(user); 19156 } 19157 } 19158 } 19159 19160 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19161 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19162 ArrayList<PreferredActivity> removed = null; 19163 boolean changed = false; 19164 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19165 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19166 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19167 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19168 continue; 19169 } 19170 Iterator<PreferredActivity> it = pir.filterIterator(); 19171 while (it.hasNext()) { 19172 PreferredActivity pa = it.next(); 19173 // Mark entry for removal only if it matches the package name 19174 // and the entry is of type "always". 19175 if (packageName == null || 19176 (pa.mPref.mComponent.getPackageName().equals(packageName) 19177 && pa.mPref.mAlways)) { 19178 if (removed == null) { 19179 removed = new ArrayList<PreferredActivity>(); 19180 } 19181 removed.add(pa); 19182 } 19183 } 19184 if (removed != null) { 19185 for (int j=0; j<removed.size(); j++) { 19186 PreferredActivity pa = removed.get(j); 19187 pir.removeFilter(pa); 19188 } 19189 changed = true; 19190 } 19191 } 19192 if (changed) { 19193 postPreferredActivityChangedBroadcast(userId); 19194 } 19195 return changed; 19196 } 19197 19198 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19199 private void clearIntentFilterVerificationsLPw(int userId) { 19200 final int packageCount = mPackages.size(); 19201 for (int i = 0; i < packageCount; i++) { 19202 PackageParser.Package pkg = mPackages.valueAt(i); 19203 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19204 } 19205 } 19206 19207 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19208 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19209 if (userId == UserHandle.USER_ALL) { 19210 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19211 sUserManager.getUserIds())) { 19212 for (int oneUserId : sUserManager.getUserIds()) { 19213 scheduleWritePackageRestrictionsLocked(oneUserId); 19214 } 19215 } 19216 } else { 19217 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19218 scheduleWritePackageRestrictionsLocked(userId); 19219 } 19220 } 19221 } 19222 19223 /** Clears state for all users, and touches intent filter verification policy */ 19224 void clearDefaultBrowserIfNeeded(String packageName) { 19225 for (int oneUserId : sUserManager.getUserIds()) { 19226 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19227 } 19228 } 19229 19230 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19231 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19232 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19233 if (packageName.equals(defaultBrowserPackageName)) { 19234 setDefaultBrowserPackageName(null, userId); 19235 } 19236 } 19237 } 19238 19239 @Override 19240 public void resetApplicationPreferences(int userId) { 19241 mContext.enforceCallingOrSelfPermission( 19242 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19243 final long identity = Binder.clearCallingIdentity(); 19244 // writer 19245 try { 19246 synchronized (mPackages) { 19247 clearPackagePreferredActivitiesLPw(null, userId); 19248 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19249 // TODO: We have to reset the default SMS and Phone. This requires 19250 // significant refactoring to keep all default apps in the package 19251 // manager (cleaner but more work) or have the services provide 19252 // callbacks to the package manager to request a default app reset. 19253 applyFactoryDefaultBrowserLPw(userId); 19254 clearIntentFilterVerificationsLPw(userId); 19255 primeDomainVerificationsLPw(userId); 19256 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19257 scheduleWritePackageRestrictionsLocked(userId); 19258 } 19259 resetNetworkPolicies(userId); 19260 } finally { 19261 Binder.restoreCallingIdentity(identity); 19262 } 19263 } 19264 19265 @Override 19266 public int getPreferredActivities(List<IntentFilter> outFilters, 19267 List<ComponentName> outActivities, String packageName) { 19268 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19269 return 0; 19270 } 19271 int num = 0; 19272 final int userId = UserHandle.getCallingUserId(); 19273 // reader 19274 synchronized (mPackages) { 19275 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19276 if (pir != null) { 19277 final Iterator<PreferredActivity> it = pir.filterIterator(); 19278 while (it.hasNext()) { 19279 final PreferredActivity pa = it.next(); 19280 if (packageName == null 19281 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19282 && pa.mPref.mAlways)) { 19283 if (outFilters != null) { 19284 outFilters.add(new IntentFilter(pa)); 19285 } 19286 if (outActivities != null) { 19287 outActivities.add(pa.mPref.mComponent); 19288 } 19289 } 19290 } 19291 } 19292 } 19293 19294 return num; 19295 } 19296 19297 @Override 19298 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19299 int userId) { 19300 int callingUid = Binder.getCallingUid(); 19301 if (callingUid != Process.SYSTEM_UID) { 19302 throw new SecurityException( 19303 "addPersistentPreferredActivity can only be run by the system"); 19304 } 19305 if (filter.countActions() == 0) { 19306 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19307 return; 19308 } 19309 synchronized (mPackages) { 19310 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19311 ":"); 19312 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19313 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19314 new PersistentPreferredActivity(filter, activity)); 19315 scheduleWritePackageRestrictionsLocked(userId); 19316 postPreferredActivityChangedBroadcast(userId); 19317 } 19318 } 19319 19320 @Override 19321 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19322 int callingUid = Binder.getCallingUid(); 19323 if (callingUid != Process.SYSTEM_UID) { 19324 throw new SecurityException( 19325 "clearPackagePersistentPreferredActivities can only be run by the system"); 19326 } 19327 ArrayList<PersistentPreferredActivity> removed = null; 19328 boolean changed = false; 19329 synchronized (mPackages) { 19330 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19331 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19332 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19333 .valueAt(i); 19334 if (userId != thisUserId) { 19335 continue; 19336 } 19337 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19338 while (it.hasNext()) { 19339 PersistentPreferredActivity ppa = it.next(); 19340 // Mark entry for removal only if it matches the package name. 19341 if (ppa.mComponent.getPackageName().equals(packageName)) { 19342 if (removed == null) { 19343 removed = new ArrayList<PersistentPreferredActivity>(); 19344 } 19345 removed.add(ppa); 19346 } 19347 } 19348 if (removed != null) { 19349 for (int j=0; j<removed.size(); j++) { 19350 PersistentPreferredActivity ppa = removed.get(j); 19351 ppir.removeFilter(ppa); 19352 } 19353 changed = true; 19354 } 19355 } 19356 19357 if (changed) { 19358 scheduleWritePackageRestrictionsLocked(userId); 19359 postPreferredActivityChangedBroadcast(userId); 19360 } 19361 } 19362 } 19363 19364 /** 19365 * Common machinery for picking apart a restored XML blob and passing 19366 * it to a caller-supplied functor to be applied to the running system. 19367 */ 19368 private void restoreFromXml(XmlPullParser parser, int userId, 19369 String expectedStartTag, BlobXmlRestorer functor) 19370 throws IOException, XmlPullParserException { 19371 int type; 19372 while ((type = parser.next()) != XmlPullParser.START_TAG 19373 && type != XmlPullParser.END_DOCUMENT) { 19374 } 19375 if (type != XmlPullParser.START_TAG) { 19376 // oops didn't find a start tag?! 19377 if (DEBUG_BACKUP) { 19378 Slog.e(TAG, "Didn't find start tag during restore"); 19379 } 19380 return; 19381 } 19382Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19383 // this is supposed to be TAG_PREFERRED_BACKUP 19384 if (!expectedStartTag.equals(parser.getName())) { 19385 if (DEBUG_BACKUP) { 19386 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19387 } 19388 return; 19389 } 19390 19391 // skip interfering stuff, then we're aligned with the backing implementation 19392 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19393Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19394 functor.apply(parser, userId); 19395 } 19396 19397 private interface BlobXmlRestorer { 19398 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19399 } 19400 19401 /** 19402 * Non-Binder method, support for the backup/restore mechanism: write the 19403 * full set of preferred activities in its canonical XML format. Returns the 19404 * XML output as a byte array, or null if there is none. 19405 */ 19406 @Override 19407 public byte[] getPreferredActivityBackup(int userId) { 19408 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19409 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19410 } 19411 19412 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19413 try { 19414 final XmlSerializer serializer = new FastXmlSerializer(); 19415 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19416 serializer.startDocument(null, true); 19417 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19418 19419 synchronized (mPackages) { 19420 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19421 } 19422 19423 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19424 serializer.endDocument(); 19425 serializer.flush(); 19426 } catch (Exception e) { 19427 if (DEBUG_BACKUP) { 19428 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19429 } 19430 return null; 19431 } 19432 19433 return dataStream.toByteArray(); 19434 } 19435 19436 @Override 19437 public void restorePreferredActivities(byte[] backup, int userId) { 19438 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19439 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19440 } 19441 19442 try { 19443 final XmlPullParser parser = Xml.newPullParser(); 19444 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19445 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19446 new BlobXmlRestorer() { 19447 @Override 19448 public void apply(XmlPullParser parser, int userId) 19449 throws XmlPullParserException, IOException { 19450 synchronized (mPackages) { 19451 mSettings.readPreferredActivitiesLPw(parser, userId); 19452 } 19453 } 19454 } ); 19455 } catch (Exception e) { 19456 if (DEBUG_BACKUP) { 19457 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19458 } 19459 } 19460 } 19461 19462 /** 19463 * Non-Binder method, support for the backup/restore mechanism: write the 19464 * default browser (etc) settings in its canonical XML format. Returns the default 19465 * browser XML representation as a byte array, or null if there is none. 19466 */ 19467 @Override 19468 public byte[] getDefaultAppsBackup(int userId) { 19469 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19470 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19471 } 19472 19473 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19474 try { 19475 final XmlSerializer serializer = new FastXmlSerializer(); 19476 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19477 serializer.startDocument(null, true); 19478 serializer.startTag(null, TAG_DEFAULT_APPS); 19479 19480 synchronized (mPackages) { 19481 mSettings.writeDefaultAppsLPr(serializer, userId); 19482 } 19483 19484 serializer.endTag(null, TAG_DEFAULT_APPS); 19485 serializer.endDocument(); 19486 serializer.flush(); 19487 } catch (Exception e) { 19488 if (DEBUG_BACKUP) { 19489 Slog.e(TAG, "Unable to write default apps for backup", e); 19490 } 19491 return null; 19492 } 19493 19494 return dataStream.toByteArray(); 19495 } 19496 19497 @Override 19498 public void restoreDefaultApps(byte[] backup, int userId) { 19499 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19500 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19501 } 19502 19503 try { 19504 final XmlPullParser parser = Xml.newPullParser(); 19505 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19506 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19507 new BlobXmlRestorer() { 19508 @Override 19509 public void apply(XmlPullParser parser, int userId) 19510 throws XmlPullParserException, IOException { 19511 synchronized (mPackages) { 19512 mSettings.readDefaultAppsLPw(parser, userId); 19513 } 19514 } 19515 } ); 19516 } catch (Exception e) { 19517 if (DEBUG_BACKUP) { 19518 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19519 } 19520 } 19521 } 19522 19523 @Override 19524 public byte[] getIntentFilterVerificationBackup(int userId) { 19525 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19526 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19527 } 19528 19529 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19530 try { 19531 final XmlSerializer serializer = new FastXmlSerializer(); 19532 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19533 serializer.startDocument(null, true); 19534 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19535 19536 synchronized (mPackages) { 19537 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19538 } 19539 19540 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19541 serializer.endDocument(); 19542 serializer.flush(); 19543 } catch (Exception e) { 19544 if (DEBUG_BACKUP) { 19545 Slog.e(TAG, "Unable to write default apps for backup", e); 19546 } 19547 return null; 19548 } 19549 19550 return dataStream.toByteArray(); 19551 } 19552 19553 @Override 19554 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19555 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19556 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19557 } 19558 19559 try { 19560 final XmlPullParser parser = Xml.newPullParser(); 19561 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19562 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19563 new BlobXmlRestorer() { 19564 @Override 19565 public void apply(XmlPullParser parser, int userId) 19566 throws XmlPullParserException, IOException { 19567 synchronized (mPackages) { 19568 mSettings.readAllDomainVerificationsLPr(parser, userId); 19569 mSettings.writeLPr(); 19570 } 19571 } 19572 } ); 19573 } catch (Exception e) { 19574 if (DEBUG_BACKUP) { 19575 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19576 } 19577 } 19578 } 19579 19580 @Override 19581 public byte[] getPermissionGrantBackup(int userId) { 19582 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19583 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19584 } 19585 19586 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19587 try { 19588 final XmlSerializer serializer = new FastXmlSerializer(); 19589 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19590 serializer.startDocument(null, true); 19591 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19592 19593 synchronized (mPackages) { 19594 serializeRuntimePermissionGrantsLPr(serializer, userId); 19595 } 19596 19597 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19598 serializer.endDocument(); 19599 serializer.flush(); 19600 } catch (Exception e) { 19601 if (DEBUG_BACKUP) { 19602 Slog.e(TAG, "Unable to write default apps for backup", e); 19603 } 19604 return null; 19605 } 19606 19607 return dataStream.toByteArray(); 19608 } 19609 19610 @Override 19611 public void restorePermissionGrants(byte[] backup, int userId) { 19612 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19613 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19614 } 19615 19616 try { 19617 final XmlPullParser parser = Xml.newPullParser(); 19618 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19619 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19620 new BlobXmlRestorer() { 19621 @Override 19622 public void apply(XmlPullParser parser, int userId) 19623 throws XmlPullParserException, IOException { 19624 synchronized (mPackages) { 19625 processRestoredPermissionGrantsLPr(parser, userId); 19626 } 19627 } 19628 } ); 19629 } catch (Exception e) { 19630 if (DEBUG_BACKUP) { 19631 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19632 } 19633 } 19634 } 19635 19636 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19637 throws IOException { 19638 serializer.startTag(null, TAG_ALL_GRANTS); 19639 19640 final int N = mSettings.mPackages.size(); 19641 for (int i = 0; i < N; i++) { 19642 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19643 boolean pkgGrantsKnown = false; 19644 19645 PermissionsState packagePerms = ps.getPermissionsState(); 19646 19647 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19648 final int grantFlags = state.getFlags(); 19649 // only look at grants that are not system/policy fixed 19650 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19651 final boolean isGranted = state.isGranted(); 19652 // And only back up the user-twiddled state bits 19653 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19654 final String packageName = mSettings.mPackages.keyAt(i); 19655 if (!pkgGrantsKnown) { 19656 serializer.startTag(null, TAG_GRANT); 19657 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19658 pkgGrantsKnown = true; 19659 } 19660 19661 final boolean userSet = 19662 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19663 final boolean userFixed = 19664 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19665 final boolean revoke = 19666 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19667 19668 serializer.startTag(null, TAG_PERMISSION); 19669 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19670 if (isGranted) { 19671 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19672 } 19673 if (userSet) { 19674 serializer.attribute(null, ATTR_USER_SET, "true"); 19675 } 19676 if (userFixed) { 19677 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19678 } 19679 if (revoke) { 19680 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19681 } 19682 serializer.endTag(null, TAG_PERMISSION); 19683 } 19684 } 19685 } 19686 19687 if (pkgGrantsKnown) { 19688 serializer.endTag(null, TAG_GRANT); 19689 } 19690 } 19691 19692 serializer.endTag(null, TAG_ALL_GRANTS); 19693 } 19694 19695 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19696 throws XmlPullParserException, IOException { 19697 String pkgName = null; 19698 int outerDepth = parser.getDepth(); 19699 int type; 19700 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19701 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19702 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19703 continue; 19704 } 19705 19706 final String tagName = parser.getName(); 19707 if (tagName.equals(TAG_GRANT)) { 19708 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19709 if (DEBUG_BACKUP) { 19710 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19711 } 19712 } else if (tagName.equals(TAG_PERMISSION)) { 19713 19714 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19715 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19716 19717 int newFlagSet = 0; 19718 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19719 newFlagSet |= FLAG_PERMISSION_USER_SET; 19720 } 19721 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19722 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19723 } 19724 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19725 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19726 } 19727 if (DEBUG_BACKUP) { 19728 Slog.v(TAG, " + Restoring grant:" 19729 + " pkg=" + pkgName 19730 + " perm=" + permName 19731 + " granted=" + isGranted 19732 + " bits=0x" + Integer.toHexString(newFlagSet)); 19733 } 19734 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19735 if (ps != null) { 19736 // Already installed so we apply the grant immediately 19737 if (DEBUG_BACKUP) { 19738 Slog.v(TAG, " + already installed; applying"); 19739 } 19740 PermissionsState perms = ps.getPermissionsState(); 19741 BasePermission bp = 19742 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19743 if (bp != null) { 19744 if (isGranted) { 19745 perms.grantRuntimePermission(bp, userId); 19746 } 19747 if (newFlagSet != 0) { 19748 perms.updatePermissionFlags( 19749 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19750 } 19751 } 19752 } else { 19753 // Need to wait for post-restore install to apply the grant 19754 if (DEBUG_BACKUP) { 19755 Slog.v(TAG, " - not yet installed; saving for later"); 19756 } 19757 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19758 isGranted, newFlagSet, userId); 19759 } 19760 } else { 19761 PackageManagerService.reportSettingsProblem(Log.WARN, 19762 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19763 XmlUtils.skipCurrentTag(parser); 19764 } 19765 } 19766 19767 scheduleWriteSettingsLocked(); 19768 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19769 } 19770 19771 @Override 19772 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19773 int sourceUserId, int targetUserId, int flags) { 19774 mContext.enforceCallingOrSelfPermission( 19775 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19776 int callingUid = Binder.getCallingUid(); 19777 enforceOwnerRights(ownerPackage, callingUid); 19778 PackageManagerServiceUtils.enforceShellRestriction( 19779 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19780 if (intentFilter.countActions() == 0) { 19781 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19782 return; 19783 } 19784 synchronized (mPackages) { 19785 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19786 ownerPackage, targetUserId, flags); 19787 CrossProfileIntentResolver resolver = 19788 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19789 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19790 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19791 if (existing != null) { 19792 int size = existing.size(); 19793 for (int i = 0; i < size; i++) { 19794 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19795 return; 19796 } 19797 } 19798 } 19799 resolver.addFilter(newFilter); 19800 scheduleWritePackageRestrictionsLocked(sourceUserId); 19801 } 19802 } 19803 19804 @Override 19805 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19806 mContext.enforceCallingOrSelfPermission( 19807 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19808 final int callingUid = Binder.getCallingUid(); 19809 enforceOwnerRights(ownerPackage, callingUid); 19810 PackageManagerServiceUtils.enforceShellRestriction( 19811 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19812 synchronized (mPackages) { 19813 CrossProfileIntentResolver resolver = 19814 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19815 ArraySet<CrossProfileIntentFilter> set = 19816 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19817 for (CrossProfileIntentFilter filter : set) { 19818 if (filter.getOwnerPackage().equals(ownerPackage)) { 19819 resolver.removeFilter(filter); 19820 } 19821 } 19822 scheduleWritePackageRestrictionsLocked(sourceUserId); 19823 } 19824 } 19825 19826 // Enforcing that callingUid is owning pkg on userId 19827 private void enforceOwnerRights(String pkg, int callingUid) { 19828 // The system owns everything. 19829 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19830 return; 19831 } 19832 final int callingUserId = UserHandle.getUserId(callingUid); 19833 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19834 if (pi == null) { 19835 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19836 + callingUserId); 19837 } 19838 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19839 throw new SecurityException("Calling uid " + callingUid 19840 + " does not own package " + pkg); 19841 } 19842 } 19843 19844 @Override 19845 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19846 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19847 return null; 19848 } 19849 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19850 } 19851 19852 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19853 UserManagerService ums = UserManagerService.getInstance(); 19854 if (ums != null) { 19855 final UserInfo parent = ums.getProfileParent(userId); 19856 final int launcherUid = (parent != null) ? parent.id : userId; 19857 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19858 if (launcherComponent != null) { 19859 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19860 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19861 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19862 .setPackage(launcherComponent.getPackageName()); 19863 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19864 } 19865 } 19866 } 19867 19868 /** 19869 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19870 * then reports the most likely home activity or null if there are more than one. 19871 */ 19872 private ComponentName getDefaultHomeActivity(int userId) { 19873 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19874 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19875 if (cn != null) { 19876 return cn; 19877 } 19878 19879 // Find the launcher with the highest priority and return that component if there are no 19880 // other home activity with the same priority. 19881 int lastPriority = Integer.MIN_VALUE; 19882 ComponentName lastComponent = null; 19883 final int size = allHomeCandidates.size(); 19884 for (int i = 0; i < size; i++) { 19885 final ResolveInfo ri = allHomeCandidates.get(i); 19886 if (ri.priority > lastPriority) { 19887 lastComponent = ri.activityInfo.getComponentName(); 19888 lastPriority = ri.priority; 19889 } else if (ri.priority == lastPriority) { 19890 // Two components found with same priority. 19891 lastComponent = null; 19892 } 19893 } 19894 return lastComponent; 19895 } 19896 19897 private Intent getHomeIntent() { 19898 Intent intent = new Intent(Intent.ACTION_MAIN); 19899 intent.addCategory(Intent.CATEGORY_HOME); 19900 intent.addCategory(Intent.CATEGORY_DEFAULT); 19901 return intent; 19902 } 19903 19904 private IntentFilter getHomeFilter() { 19905 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19906 filter.addCategory(Intent.CATEGORY_HOME); 19907 filter.addCategory(Intent.CATEGORY_DEFAULT); 19908 return filter; 19909 } 19910 19911 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19912 int userId) { 19913 Intent intent = getHomeIntent(); 19914 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19915 PackageManager.GET_META_DATA, userId); 19916 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19917 true, false, false, userId); 19918 19919 allHomeCandidates.clear(); 19920 if (list != null) { 19921 for (ResolveInfo ri : list) { 19922 allHomeCandidates.add(ri); 19923 } 19924 } 19925 return (preferred == null || preferred.activityInfo == null) 19926 ? null 19927 : new ComponentName(preferred.activityInfo.packageName, 19928 preferred.activityInfo.name); 19929 } 19930 19931 @Override 19932 public void setHomeActivity(ComponentName comp, int userId) { 19933 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19934 return; 19935 } 19936 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19937 getHomeActivitiesAsUser(homeActivities, userId); 19938 19939 boolean found = false; 19940 19941 final int size = homeActivities.size(); 19942 final ComponentName[] set = new ComponentName[size]; 19943 for (int i = 0; i < size; i++) { 19944 final ResolveInfo candidate = homeActivities.get(i); 19945 final ActivityInfo info = candidate.activityInfo; 19946 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19947 set[i] = activityName; 19948 if (!found && activityName.equals(comp)) { 19949 found = true; 19950 } 19951 } 19952 if (!found) { 19953 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19954 + userId); 19955 } 19956 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19957 set, comp, userId); 19958 } 19959 19960 private @Nullable String getSetupWizardPackageName() { 19961 final Intent intent = new Intent(Intent.ACTION_MAIN); 19962 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19963 19964 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19965 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19966 | MATCH_DISABLED_COMPONENTS, 19967 UserHandle.myUserId()); 19968 if (matches.size() == 1) { 19969 return matches.get(0).getComponentInfo().packageName; 19970 } else { 19971 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19972 + ": matches=" + matches); 19973 return null; 19974 } 19975 } 19976 19977 private @Nullable String getStorageManagerPackageName() { 19978 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19979 19980 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19981 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19982 | MATCH_DISABLED_COMPONENTS, 19983 UserHandle.myUserId()); 19984 if (matches.size() == 1) { 19985 return matches.get(0).getComponentInfo().packageName; 19986 } else { 19987 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19988 + matches.size() + ": matches=" + matches); 19989 return null; 19990 } 19991 } 19992 19993 @Override 19994 public void setApplicationEnabledSetting(String appPackageName, 19995 int newState, int flags, int userId, String callingPackage) { 19996 if (!sUserManager.exists(userId)) return; 19997 if (callingPackage == null) { 19998 callingPackage = Integer.toString(Binder.getCallingUid()); 19999 } 20000 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20001 } 20002 20003 @Override 20004 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20005 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20006 synchronized (mPackages) { 20007 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20008 if (pkgSetting != null) { 20009 pkgSetting.setUpdateAvailable(updateAvailable); 20010 } 20011 } 20012 } 20013 20014 @Override 20015 public void setComponentEnabledSetting(ComponentName componentName, 20016 int newState, int flags, int userId) { 20017 if (!sUserManager.exists(userId)) return; 20018 setEnabledSetting(componentName.getPackageName(), 20019 componentName.getClassName(), newState, flags, userId, null); 20020 } 20021 20022 private void setEnabledSetting(final String packageName, String className, int newState, 20023 final int flags, int userId, String callingPackage) { 20024 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20025 || newState == COMPONENT_ENABLED_STATE_ENABLED 20026 || newState == COMPONENT_ENABLED_STATE_DISABLED 20027 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20028 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20029 throw new IllegalArgumentException("Invalid new component state: " 20030 + newState); 20031 } 20032 PackageSetting pkgSetting; 20033 final int callingUid = Binder.getCallingUid(); 20034 final int permission; 20035 if (callingUid == Process.SYSTEM_UID) { 20036 permission = PackageManager.PERMISSION_GRANTED; 20037 } else { 20038 permission = mContext.checkCallingOrSelfPermission( 20039 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20040 } 20041 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20042 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20043 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20044 boolean sendNow = false; 20045 boolean isApp = (className == null); 20046 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20047 String componentName = isApp ? packageName : className; 20048 int packageUid = -1; 20049 ArrayList<String> components; 20050 20051 // reader 20052 synchronized (mPackages) { 20053 pkgSetting = mSettings.mPackages.get(packageName); 20054 if (pkgSetting == null) { 20055 if (!isCallerInstantApp) { 20056 if (className == null) { 20057 throw new IllegalArgumentException("Unknown package: " + packageName); 20058 } 20059 throw new IllegalArgumentException( 20060 "Unknown component: " + packageName + "/" + className); 20061 } else { 20062 // throw SecurityException to prevent leaking package information 20063 throw new SecurityException( 20064 "Attempt to change component state; " 20065 + "pid=" + Binder.getCallingPid() 20066 + ", uid=" + callingUid 20067 + (className == null 20068 ? ", package=" + packageName 20069 : ", component=" + packageName + "/" + className)); 20070 } 20071 } 20072 } 20073 20074 // Limit who can change which apps 20075 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20076 // Don't allow apps that don't have permission to modify other apps 20077 if (!allowedByPermission 20078 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20079 throw new SecurityException( 20080 "Attempt to change component state; " 20081 + "pid=" + Binder.getCallingPid() 20082 + ", uid=" + callingUid 20083 + (className == null 20084 ? ", package=" + packageName 20085 : ", component=" + packageName + "/" + className)); 20086 } 20087 // Don't allow changing protected packages. 20088 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20089 throw new SecurityException("Cannot disable a protected package: " + packageName); 20090 } 20091 } 20092 20093 synchronized (mPackages) { 20094 if (callingUid == Process.SHELL_UID 20095 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20096 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20097 // unless it is a test package. 20098 int oldState = pkgSetting.getEnabled(userId); 20099 if (className == null 20100 && 20101 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20102 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20103 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20104 && 20105 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20106 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20107 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20108 // ok 20109 } else { 20110 throw new SecurityException( 20111 "Shell cannot change component state for " + packageName + "/" 20112 + className + " to " + newState); 20113 } 20114 } 20115 } 20116 if (className == null) { 20117 // We're dealing with an application/package level state change 20118 synchronized (mPackages) { 20119 if (pkgSetting.getEnabled(userId) == newState) { 20120 // Nothing to do 20121 return; 20122 } 20123 } 20124 // If we're enabling a system stub, there's a little more work to do. 20125 // Prior to enabling the package, we need to decompress the APK(s) to the 20126 // data partition and then replace the version on the system partition. 20127 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20128 final boolean isSystemStub = deletedPkg.isStub 20129 && deletedPkg.isSystem(); 20130 if (isSystemStub 20131 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20132 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20133 final File codePath = decompressPackage(deletedPkg); 20134 if (codePath == null) { 20135 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20136 return; 20137 } 20138 // TODO remove direct parsing of the package object during internal cleanup 20139 // of scan package 20140 // We need to call parse directly here for no other reason than we need 20141 // the new package in order to disable the old one [we use the information 20142 // for some internal optimization to optionally create a new package setting 20143 // object on replace]. However, we can't get the package from the scan 20144 // because the scan modifies live structures and we need to remove the 20145 // old [system] package from the system before a scan can be attempted. 20146 // Once scan is indempotent we can remove this parse and use the package 20147 // object we scanned, prior to adding it to package settings. 20148 final PackageParser pp = new PackageParser(); 20149 pp.setSeparateProcesses(mSeparateProcesses); 20150 pp.setDisplayMetrics(mMetrics); 20151 pp.setCallback(mPackageParserCallback); 20152 final PackageParser.Package tmpPkg; 20153 try { 20154 final @ParseFlags int parseFlags = mDefParseFlags 20155 | PackageParser.PARSE_MUST_BE_APK 20156 | PackageParser.PARSE_IS_SYSTEM_DIR; 20157 tmpPkg = pp.parsePackage(codePath, parseFlags); 20158 } catch (PackageParserException e) { 20159 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20160 return; 20161 } 20162 synchronized (mInstallLock) { 20163 // Disable the stub and remove any package entries 20164 removePackageLI(deletedPkg, true); 20165 synchronized (mPackages) { 20166 disableSystemPackageLPw(deletedPkg, tmpPkg); 20167 } 20168 final PackageParser.Package pkg; 20169 try (PackageFreezer freezer = 20170 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20171 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20172 | PackageParser.PARSE_ENFORCE_CODE; 20173 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20174 0 /*currentTime*/, null /*user*/); 20175 prepareAppDataAfterInstallLIF(pkg); 20176 synchronized (mPackages) { 20177 try { 20178 updateSharedLibrariesLPr(pkg, null); 20179 } catch (PackageManagerException e) { 20180 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20181 } 20182 mPermissionManager.updatePermissions( 20183 pkg.packageName, pkg, true, mPackages.values(), 20184 mPermissionCallback); 20185 mSettings.writeLPr(); 20186 } 20187 } catch (PackageManagerException e) { 20188 // Whoops! Something went wrong; try to roll back to the stub 20189 Slog.w(TAG, "Failed to install compressed system package:" 20190 + pkgSetting.name, e); 20191 // Remove the failed install 20192 removeCodePathLI(codePath); 20193 20194 // Install the system package 20195 try (PackageFreezer freezer = 20196 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20197 synchronized (mPackages) { 20198 // NOTE: The system package always needs to be enabled; even 20199 // if it's for a compressed stub. If we don't, installing the 20200 // system package fails during scan [scanning checks the disabled 20201 // packages]. We will reverse this later, after we've "installed" 20202 // the stub. 20203 // This leaves us in a fragile state; the stub should never be 20204 // enabled, so, cross your fingers and hope nothing goes wrong 20205 // until we can disable the package later. 20206 enableSystemPackageLPw(deletedPkg); 20207 } 20208 installPackageFromSystemLIF(deletedPkg.codePath, 20209 false /*isPrivileged*/, null /*allUserHandles*/, 20210 null /*origUserHandles*/, null /*origPermissionsState*/, 20211 true /*writeSettings*/); 20212 } catch (PackageManagerException pme) { 20213 Slog.w(TAG, "Failed to restore system package:" 20214 + deletedPkg.packageName, pme); 20215 } finally { 20216 synchronized (mPackages) { 20217 mSettings.disableSystemPackageLPw( 20218 deletedPkg.packageName, true /*replaced*/); 20219 mSettings.writeLPr(); 20220 } 20221 } 20222 return; 20223 } 20224 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20225 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20226 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20227 mDexManager.notifyPackageUpdated(pkg.packageName, 20228 pkg.baseCodePath, pkg.splitCodePaths); 20229 } 20230 } 20231 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20232 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20233 // Don't care about who enables an app. 20234 callingPackage = null; 20235 } 20236 synchronized (mPackages) { 20237 pkgSetting.setEnabled(newState, userId, callingPackage); 20238 } 20239 } else { 20240 synchronized (mPackages) { 20241 // We're dealing with a component level state change 20242 // First, verify that this is a valid class name. 20243 PackageParser.Package pkg = pkgSetting.pkg; 20244 if (pkg == null || !pkg.hasComponentClassName(className)) { 20245 if (pkg != null && 20246 pkg.applicationInfo.targetSdkVersion >= 20247 Build.VERSION_CODES.JELLY_BEAN) { 20248 throw new IllegalArgumentException("Component class " + className 20249 + " does not exist in " + packageName); 20250 } else { 20251 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20252 + className + " does not exist in " + packageName); 20253 } 20254 } 20255 switch (newState) { 20256 case COMPONENT_ENABLED_STATE_ENABLED: 20257 if (!pkgSetting.enableComponentLPw(className, userId)) { 20258 return; 20259 } 20260 break; 20261 case COMPONENT_ENABLED_STATE_DISABLED: 20262 if (!pkgSetting.disableComponentLPw(className, userId)) { 20263 return; 20264 } 20265 break; 20266 case COMPONENT_ENABLED_STATE_DEFAULT: 20267 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20268 return; 20269 } 20270 break; 20271 default: 20272 Slog.e(TAG, "Invalid new component state: " + newState); 20273 return; 20274 } 20275 } 20276 } 20277 synchronized (mPackages) { 20278 scheduleWritePackageRestrictionsLocked(userId); 20279 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20280 final long callingId = Binder.clearCallingIdentity(); 20281 try { 20282 updateInstantAppInstallerLocked(packageName); 20283 } finally { 20284 Binder.restoreCallingIdentity(callingId); 20285 } 20286 components = mPendingBroadcasts.get(userId, packageName); 20287 final boolean newPackage = components == null; 20288 if (newPackage) { 20289 components = new ArrayList<String>(); 20290 } 20291 if (!components.contains(componentName)) { 20292 components.add(componentName); 20293 } 20294 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20295 sendNow = true; 20296 // Purge entry from pending broadcast list if another one exists already 20297 // since we are sending one right away. 20298 mPendingBroadcasts.remove(userId, packageName); 20299 } else { 20300 if (newPackage) { 20301 mPendingBroadcasts.put(userId, packageName, components); 20302 } 20303 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20304 // Schedule a message 20305 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20306 } 20307 } 20308 } 20309 20310 long callingId = Binder.clearCallingIdentity(); 20311 try { 20312 if (sendNow) { 20313 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20314 sendPackageChangedBroadcast(packageName, 20315 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20316 } 20317 } finally { 20318 Binder.restoreCallingIdentity(callingId); 20319 } 20320 } 20321 20322 @Override 20323 public void flushPackageRestrictionsAsUser(int userId) { 20324 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20325 return; 20326 } 20327 if (!sUserManager.exists(userId)) { 20328 return; 20329 } 20330 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20331 false /* checkShell */, "flushPackageRestrictions"); 20332 synchronized (mPackages) { 20333 mSettings.writePackageRestrictionsLPr(userId); 20334 mDirtyUsers.remove(userId); 20335 if (mDirtyUsers.isEmpty()) { 20336 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20337 } 20338 } 20339 } 20340 20341 private void sendPackageChangedBroadcast(String packageName, 20342 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20343 if (DEBUG_INSTALL) 20344 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20345 + componentNames); 20346 Bundle extras = new Bundle(4); 20347 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20348 String nameList[] = new String[componentNames.size()]; 20349 componentNames.toArray(nameList); 20350 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20351 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20352 extras.putInt(Intent.EXTRA_UID, packageUid); 20353 // If this is not reporting a change of the overall package, then only send it 20354 // to registered receivers. We don't want to launch a swath of apps for every 20355 // little component state change. 20356 final int flags = !componentNames.contains(packageName) 20357 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20358 final int userId = UserHandle.getUserId(packageUid); 20359 final boolean isInstantApp = isInstantApp(packageName, userId); 20360 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20361 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20362 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20363 userIds, instantUserIds); 20364 } 20365 20366 @Override 20367 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20368 if (!sUserManager.exists(userId)) return; 20369 final int callingUid = Binder.getCallingUid(); 20370 if (getInstantAppPackageName(callingUid) != null) { 20371 return; 20372 } 20373 final int permission = mContext.checkCallingOrSelfPermission( 20374 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20375 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20376 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20377 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20378 // writer 20379 synchronized (mPackages) { 20380 final PackageSetting ps = mSettings.mPackages.get(packageName); 20381 if (!filterAppAccessLPr(ps, callingUid, userId) 20382 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20383 allowedByPermission, callingUid, userId)) { 20384 scheduleWritePackageRestrictionsLocked(userId); 20385 } 20386 } 20387 } 20388 20389 @Override 20390 public String getInstallerPackageName(String packageName) { 20391 final int callingUid = Binder.getCallingUid(); 20392 if (getInstantAppPackageName(callingUid) != null) { 20393 return null; 20394 } 20395 // reader 20396 synchronized (mPackages) { 20397 final PackageSetting ps = mSettings.mPackages.get(packageName); 20398 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20399 return null; 20400 } 20401 return mSettings.getInstallerPackageNameLPr(packageName); 20402 } 20403 } 20404 20405 public boolean isOrphaned(String packageName) { 20406 // reader 20407 synchronized (mPackages) { 20408 return mSettings.isOrphaned(packageName); 20409 } 20410 } 20411 20412 @Override 20413 public int getApplicationEnabledSetting(String packageName, int userId) { 20414 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20415 int callingUid = Binder.getCallingUid(); 20416 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20417 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20418 // reader 20419 synchronized (mPackages) { 20420 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20421 return COMPONENT_ENABLED_STATE_DISABLED; 20422 } 20423 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20424 } 20425 } 20426 20427 @Override 20428 public int getComponentEnabledSetting(ComponentName component, int userId) { 20429 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20430 int callingUid = Binder.getCallingUid(); 20431 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20432 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20433 synchronized (mPackages) { 20434 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20435 component, TYPE_UNKNOWN, userId)) { 20436 return COMPONENT_ENABLED_STATE_DISABLED; 20437 } 20438 return mSettings.getComponentEnabledSettingLPr(component, userId); 20439 } 20440 } 20441 20442 @Override 20443 public void enterSafeMode() { 20444 enforceSystemOrRoot("Only the system can request entering safe mode"); 20445 20446 if (!mSystemReady) { 20447 mSafeMode = true; 20448 } 20449 } 20450 20451 @Override 20452 public void systemReady() { 20453 enforceSystemOrRoot("Only the system can claim the system is ready"); 20454 20455 mSystemReady = true; 20456 final ContentResolver resolver = mContext.getContentResolver(); 20457 ContentObserver co = new ContentObserver(mHandler) { 20458 @Override 20459 public void onChange(boolean selfChange) { 20460 mEphemeralAppsDisabled = 20461 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20462 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20463 } 20464 }; 20465 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20466 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20467 false, co, UserHandle.USER_SYSTEM); 20468 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20469 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20470 co.onChange(true); 20471 20472 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20473 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20474 // it is done. 20475 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20476 @Override 20477 public void onChange(boolean selfChange) { 20478 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20479 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20480 oobEnabled == 1 ? "true" : "false"); 20481 } 20482 }; 20483 mContext.getContentResolver().registerContentObserver( 20484 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20485 UserHandle.USER_SYSTEM); 20486 // At boot, restore the value from the setting, which persists across reboot. 20487 privAppOobObserver.onChange(true); 20488 20489 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20490 // disabled after already being started. 20491 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20492 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20493 20494 // Read the compatibilty setting when the system is ready. 20495 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20496 mContext.getContentResolver(), 20497 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20498 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20499 if (DEBUG_SETTINGS) { 20500 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20501 } 20502 20503 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20504 20505 synchronized (mPackages) { 20506 // Verify that all of the preferred activity components actually 20507 // exist. It is possible for applications to be updated and at 20508 // that point remove a previously declared activity component that 20509 // had been set as a preferred activity. We try to clean this up 20510 // the next time we encounter that preferred activity, but it is 20511 // possible for the user flow to never be able to return to that 20512 // situation so here we do a sanity check to make sure we haven't 20513 // left any junk around. 20514 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20515 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20516 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20517 removed.clear(); 20518 for (PreferredActivity pa : pir.filterSet()) { 20519 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20520 removed.add(pa); 20521 } 20522 } 20523 if (removed.size() > 0) { 20524 for (int r=0; r<removed.size(); r++) { 20525 PreferredActivity pa = removed.get(r); 20526 Slog.w(TAG, "Removing dangling preferred activity: " 20527 + pa.mPref.mComponent); 20528 pir.removeFilter(pa); 20529 } 20530 mSettings.writePackageRestrictionsLPr( 20531 mSettings.mPreferredActivities.keyAt(i)); 20532 } 20533 } 20534 20535 for (int userId : UserManagerService.getInstance().getUserIds()) { 20536 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20537 grantPermissionsUserIds = ArrayUtils.appendInt( 20538 grantPermissionsUserIds, userId); 20539 } 20540 } 20541 } 20542 sUserManager.systemReady(); 20543 // If we upgraded grant all default permissions before kicking off. 20544 for (int userId : grantPermissionsUserIds) { 20545 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20546 } 20547 20548 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20549 // If we did not grant default permissions, we preload from this the 20550 // default permission exceptions lazily to ensure we don't hit the 20551 // disk on a new user creation. 20552 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20553 } 20554 20555 // Now that we've scanned all packages, and granted any default 20556 // permissions, ensure permissions are updated. Beware of dragons if you 20557 // try optimizing this. 20558 synchronized (mPackages) { 20559 mPermissionManager.updateAllPermissions( 20560 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20561 mPermissionCallback); 20562 } 20563 20564 // Kick off any messages waiting for system ready 20565 if (mPostSystemReadyMessages != null) { 20566 for (Message msg : mPostSystemReadyMessages) { 20567 msg.sendToTarget(); 20568 } 20569 mPostSystemReadyMessages = null; 20570 } 20571 20572 // Watch for external volumes that come and go over time 20573 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20574 storage.registerListener(mStorageListener); 20575 20576 mInstallerService.systemReady(); 20577 mPackageDexOptimizer.systemReady(); 20578 20579 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20580 StorageManagerInternal.class); 20581 StorageManagerInternal.addExternalStoragePolicy( 20582 new StorageManagerInternal.ExternalStorageMountPolicy() { 20583 @Override 20584 public int getMountMode(int uid, String packageName) { 20585 if (Process.isIsolated(uid)) { 20586 return Zygote.MOUNT_EXTERNAL_NONE; 20587 } 20588 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20589 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20590 } 20591 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20592 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20593 } 20594 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20595 return Zygote.MOUNT_EXTERNAL_READ; 20596 } 20597 return Zygote.MOUNT_EXTERNAL_WRITE; 20598 } 20599 20600 @Override 20601 public boolean hasExternalStorage(int uid, String packageName) { 20602 return true; 20603 } 20604 }); 20605 20606 // Now that we're mostly running, clean up stale users and apps 20607 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20608 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20609 20610 mPermissionManager.systemReady(); 20611 } 20612 20613 public void waitForAppDataPrepared() { 20614 if (mPrepareAppDataFuture == null) { 20615 return; 20616 } 20617 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20618 mPrepareAppDataFuture = null; 20619 } 20620 20621 @Override 20622 public boolean isSafeMode() { 20623 // allow instant applications 20624 return mSafeMode; 20625 } 20626 20627 @Override 20628 public boolean hasSystemUidErrors() { 20629 // allow instant applications 20630 return mHasSystemUidErrors; 20631 } 20632 20633 static String arrayToString(int[] array) { 20634 StringBuffer buf = new StringBuffer(128); 20635 buf.append('['); 20636 if (array != null) { 20637 for (int i=0; i<array.length; i++) { 20638 if (i > 0) buf.append(", "); 20639 buf.append(array[i]); 20640 } 20641 } 20642 buf.append(']'); 20643 return buf.toString(); 20644 } 20645 20646 @Override 20647 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20648 FileDescriptor err, String[] args, ShellCallback callback, 20649 ResultReceiver resultReceiver) { 20650 (new PackageManagerShellCommand(this)).exec( 20651 this, in, out, err, args, callback, resultReceiver); 20652 } 20653 20654 @Override 20655 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20656 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20657 20658 DumpState dumpState = new DumpState(); 20659 boolean fullPreferred = false; 20660 boolean checkin = false; 20661 20662 String packageName = null; 20663 ArraySet<String> permissionNames = null; 20664 20665 int opti = 0; 20666 while (opti < args.length) { 20667 String opt = args[opti]; 20668 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20669 break; 20670 } 20671 opti++; 20672 20673 if ("-a".equals(opt)) { 20674 // Right now we only know how to print all. 20675 } else if ("-h".equals(opt)) { 20676 pw.println("Package manager dump options:"); 20677 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20678 pw.println(" --checkin: dump for a checkin"); 20679 pw.println(" -f: print details of intent filters"); 20680 pw.println(" -h: print this help"); 20681 pw.println(" cmd may be one of:"); 20682 pw.println(" l[ibraries]: list known shared libraries"); 20683 pw.println(" f[eatures]: list device features"); 20684 pw.println(" k[eysets]: print known keysets"); 20685 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20686 pw.println(" perm[issions]: dump permissions"); 20687 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20688 pw.println(" pref[erred]: print preferred package settings"); 20689 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20690 pw.println(" prov[iders]: dump content providers"); 20691 pw.println(" p[ackages]: dump installed packages"); 20692 pw.println(" s[hared-users]: dump shared user IDs"); 20693 pw.println(" m[essages]: print collected runtime messages"); 20694 pw.println(" v[erifiers]: print package verifier info"); 20695 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20696 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20697 pw.println(" version: print database version info"); 20698 pw.println(" write: write current settings now"); 20699 pw.println(" installs: details about install sessions"); 20700 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20701 pw.println(" dexopt: dump dexopt state"); 20702 pw.println(" compiler-stats: dump compiler statistics"); 20703 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20704 pw.println(" service-permissions: dump permissions required by services"); 20705 pw.println(" <package.name>: info about given package"); 20706 return; 20707 } else if ("--checkin".equals(opt)) { 20708 checkin = true; 20709 } else if ("-f".equals(opt)) { 20710 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20711 } else if ("--proto".equals(opt)) { 20712 dumpProto(fd); 20713 return; 20714 } else { 20715 pw.println("Unknown argument: " + opt + "; use -h for help"); 20716 } 20717 } 20718 20719 // Is the caller requesting to dump a particular piece of data? 20720 if (opti < args.length) { 20721 String cmd = args[opti]; 20722 opti++; 20723 // Is this a package name? 20724 if ("android".equals(cmd) || cmd.contains(".")) { 20725 packageName = cmd; 20726 // When dumping a single package, we always dump all of its 20727 // filter information since the amount of data will be reasonable. 20728 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20729 } else if ("check-permission".equals(cmd)) { 20730 if (opti >= args.length) { 20731 pw.println("Error: check-permission missing permission argument"); 20732 return; 20733 } 20734 String perm = args[opti]; 20735 opti++; 20736 if (opti >= args.length) { 20737 pw.println("Error: check-permission missing package argument"); 20738 return; 20739 } 20740 20741 String pkg = args[opti]; 20742 opti++; 20743 int user = UserHandle.getUserId(Binder.getCallingUid()); 20744 if (opti < args.length) { 20745 try { 20746 user = Integer.parseInt(args[opti]); 20747 } catch (NumberFormatException e) { 20748 pw.println("Error: check-permission user argument is not a number: " 20749 + args[opti]); 20750 return; 20751 } 20752 } 20753 20754 // Normalize package name to handle renamed packages and static libs 20755 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20756 20757 pw.println(checkPermission(perm, pkg, user)); 20758 return; 20759 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20760 dumpState.setDump(DumpState.DUMP_LIBS); 20761 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20762 dumpState.setDump(DumpState.DUMP_FEATURES); 20763 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20764 if (opti >= args.length) { 20765 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20766 | DumpState.DUMP_SERVICE_RESOLVERS 20767 | DumpState.DUMP_RECEIVER_RESOLVERS 20768 | DumpState.DUMP_CONTENT_RESOLVERS); 20769 } else { 20770 while (opti < args.length) { 20771 String name = args[opti]; 20772 if ("a".equals(name) || "activity".equals(name)) { 20773 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20774 } else if ("s".equals(name) || "service".equals(name)) { 20775 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20776 } else if ("r".equals(name) || "receiver".equals(name)) { 20777 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20778 } else if ("c".equals(name) || "content".equals(name)) { 20779 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20780 } else { 20781 pw.println("Error: unknown resolver table type: " + name); 20782 return; 20783 } 20784 opti++; 20785 } 20786 } 20787 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20788 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20789 } else if ("permission".equals(cmd)) { 20790 if (opti >= args.length) { 20791 pw.println("Error: permission requires permission name"); 20792 return; 20793 } 20794 permissionNames = new ArraySet<>(); 20795 while (opti < args.length) { 20796 permissionNames.add(args[opti]); 20797 opti++; 20798 } 20799 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20800 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20801 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20802 dumpState.setDump(DumpState.DUMP_PREFERRED); 20803 } else if ("preferred-xml".equals(cmd)) { 20804 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20805 if (opti < args.length && "--full".equals(args[opti])) { 20806 fullPreferred = true; 20807 opti++; 20808 } 20809 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20810 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20811 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20812 dumpState.setDump(DumpState.DUMP_PACKAGES); 20813 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20814 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20815 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20816 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20817 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20818 dumpState.setDump(DumpState.DUMP_MESSAGES); 20819 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20820 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20821 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20822 || "intent-filter-verifiers".equals(cmd)) { 20823 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20824 } else if ("version".equals(cmd)) { 20825 dumpState.setDump(DumpState.DUMP_VERSION); 20826 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20827 dumpState.setDump(DumpState.DUMP_KEYSETS); 20828 } else if ("installs".equals(cmd)) { 20829 dumpState.setDump(DumpState.DUMP_INSTALLS); 20830 } else if ("frozen".equals(cmd)) { 20831 dumpState.setDump(DumpState.DUMP_FROZEN); 20832 } else if ("volumes".equals(cmd)) { 20833 dumpState.setDump(DumpState.DUMP_VOLUMES); 20834 } else if ("dexopt".equals(cmd)) { 20835 dumpState.setDump(DumpState.DUMP_DEXOPT); 20836 } else if ("compiler-stats".equals(cmd)) { 20837 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20838 } else if ("changes".equals(cmd)) { 20839 dumpState.setDump(DumpState.DUMP_CHANGES); 20840 } else if ("service-permissions".equals(cmd)) { 20841 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 20842 } else if ("write".equals(cmd)) { 20843 synchronized (mPackages) { 20844 mSettings.writeLPr(); 20845 pw.println("Settings written."); 20846 return; 20847 } 20848 } 20849 } 20850 20851 if (checkin) { 20852 pw.println("vers,1"); 20853 } 20854 20855 // reader 20856 synchronized (mPackages) { 20857 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20858 if (!checkin) { 20859 if (dumpState.onTitlePrinted()) 20860 pw.println(); 20861 pw.println("Database versions:"); 20862 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20863 } 20864 } 20865 20866 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20867 if (!checkin) { 20868 if (dumpState.onTitlePrinted()) 20869 pw.println(); 20870 pw.println("Verifiers:"); 20871 pw.print(" Required: "); 20872 pw.print(mRequiredVerifierPackage); 20873 pw.print(" (uid="); 20874 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20875 UserHandle.USER_SYSTEM)); 20876 pw.println(")"); 20877 } else if (mRequiredVerifierPackage != null) { 20878 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20879 pw.print(","); 20880 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20881 UserHandle.USER_SYSTEM)); 20882 } 20883 } 20884 20885 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20886 packageName == null) { 20887 if (mIntentFilterVerifierComponent != null) { 20888 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20889 if (!checkin) { 20890 if (dumpState.onTitlePrinted()) 20891 pw.println(); 20892 pw.println("Intent Filter Verifier:"); 20893 pw.print(" Using: "); 20894 pw.print(verifierPackageName); 20895 pw.print(" (uid="); 20896 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20897 UserHandle.USER_SYSTEM)); 20898 pw.println(")"); 20899 } else if (verifierPackageName != null) { 20900 pw.print("ifv,"); pw.print(verifierPackageName); 20901 pw.print(","); 20902 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20903 UserHandle.USER_SYSTEM)); 20904 } 20905 } else { 20906 pw.println(); 20907 pw.println("No Intent Filter Verifier available!"); 20908 } 20909 } 20910 20911 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20912 boolean printedHeader = false; 20913 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20914 while (it.hasNext()) { 20915 String libName = it.next(); 20916 LongSparseArray<SharedLibraryEntry> versionedLib 20917 = mSharedLibraries.get(libName); 20918 if (versionedLib == null) { 20919 continue; 20920 } 20921 final int versionCount = versionedLib.size(); 20922 for (int i = 0; i < versionCount; i++) { 20923 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20924 if (!checkin) { 20925 if (!printedHeader) { 20926 if (dumpState.onTitlePrinted()) 20927 pw.println(); 20928 pw.println("Libraries:"); 20929 printedHeader = true; 20930 } 20931 pw.print(" "); 20932 } else { 20933 pw.print("lib,"); 20934 } 20935 pw.print(libEntry.info.getName()); 20936 if (libEntry.info.isStatic()) { 20937 pw.print(" version=" + libEntry.info.getLongVersion()); 20938 } 20939 if (!checkin) { 20940 pw.print(" -> "); 20941 } 20942 if (libEntry.path != null) { 20943 pw.print(" (jar) "); 20944 pw.print(libEntry.path); 20945 } else { 20946 pw.print(" (apk) "); 20947 pw.print(libEntry.apk); 20948 } 20949 pw.println(); 20950 } 20951 } 20952 } 20953 20954 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20955 if (dumpState.onTitlePrinted()) 20956 pw.println(); 20957 if (!checkin) { 20958 pw.println("Features:"); 20959 } 20960 20961 synchronized (mAvailableFeatures) { 20962 for (FeatureInfo feat : mAvailableFeatures.values()) { 20963 if (checkin) { 20964 pw.print("feat,"); 20965 pw.print(feat.name); 20966 pw.print(","); 20967 pw.println(feat.version); 20968 } else { 20969 pw.print(" "); 20970 pw.print(feat.name); 20971 if (feat.version > 0) { 20972 pw.print(" version="); 20973 pw.print(feat.version); 20974 } 20975 pw.println(); 20976 } 20977 } 20978 } 20979 } 20980 20981 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20982 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20983 : "Activity Resolver Table:", " ", packageName, 20984 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20985 dumpState.setTitlePrinted(true); 20986 } 20987 } 20988 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20989 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20990 : "Receiver Resolver Table:", " ", packageName, 20991 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20992 dumpState.setTitlePrinted(true); 20993 } 20994 } 20995 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20996 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20997 : "Service Resolver Table:", " ", packageName, 20998 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20999 dumpState.setTitlePrinted(true); 21000 } 21001 } 21002 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21003 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21004 : "Provider Resolver Table:", " ", packageName, 21005 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21006 dumpState.setTitlePrinted(true); 21007 } 21008 } 21009 21010 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21011 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21012 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21013 int user = mSettings.mPreferredActivities.keyAt(i); 21014 if (pir.dump(pw, 21015 dumpState.getTitlePrinted() 21016 ? "\nPreferred Activities User " + user + ":" 21017 : "Preferred Activities User " + user + ":", " ", 21018 packageName, true, false)) { 21019 dumpState.setTitlePrinted(true); 21020 } 21021 } 21022 } 21023 21024 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21025 pw.flush(); 21026 FileOutputStream fout = new FileOutputStream(fd); 21027 BufferedOutputStream str = new BufferedOutputStream(fout); 21028 XmlSerializer serializer = new FastXmlSerializer(); 21029 try { 21030 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21031 serializer.startDocument(null, true); 21032 serializer.setFeature( 21033 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21034 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21035 serializer.endDocument(); 21036 serializer.flush(); 21037 } catch (IllegalArgumentException e) { 21038 pw.println("Failed writing: " + e); 21039 } catch (IllegalStateException e) { 21040 pw.println("Failed writing: " + e); 21041 } catch (IOException e) { 21042 pw.println("Failed writing: " + e); 21043 } 21044 } 21045 21046 if (!checkin 21047 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21048 && packageName == null) { 21049 pw.println(); 21050 int count = mSettings.mPackages.size(); 21051 if (count == 0) { 21052 pw.println("No applications!"); 21053 pw.println(); 21054 } else { 21055 final String prefix = " "; 21056 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21057 if (allPackageSettings.size() == 0) { 21058 pw.println("No domain preferred apps!"); 21059 pw.println(); 21060 } else { 21061 pw.println("App verification status:"); 21062 pw.println(); 21063 count = 0; 21064 for (PackageSetting ps : allPackageSettings) { 21065 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21066 if (ivi == null || ivi.getPackageName() == null) continue; 21067 pw.println(prefix + "Package: " + ivi.getPackageName()); 21068 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21069 pw.println(prefix + "Status: " + ivi.getStatusString()); 21070 pw.println(); 21071 count++; 21072 } 21073 if (count == 0) { 21074 pw.println(prefix + "No app verification established."); 21075 pw.println(); 21076 } 21077 for (int userId : sUserManager.getUserIds()) { 21078 pw.println("App linkages for user " + userId + ":"); 21079 pw.println(); 21080 count = 0; 21081 for (PackageSetting ps : allPackageSettings) { 21082 final long status = ps.getDomainVerificationStatusForUser(userId); 21083 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21084 && !DEBUG_DOMAIN_VERIFICATION) { 21085 continue; 21086 } 21087 pw.println(prefix + "Package: " + ps.name); 21088 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21089 String statusStr = IntentFilterVerificationInfo. 21090 getStatusStringFromValue(status); 21091 pw.println(prefix + "Status: " + statusStr); 21092 pw.println(); 21093 count++; 21094 } 21095 if (count == 0) { 21096 pw.println(prefix + "No configured app linkages."); 21097 pw.println(); 21098 } 21099 } 21100 } 21101 } 21102 } 21103 21104 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21105 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21106 } 21107 21108 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21109 boolean printedSomething = false; 21110 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21111 if (packageName != null && !packageName.equals(p.info.packageName)) { 21112 continue; 21113 } 21114 if (!printedSomething) { 21115 if (dumpState.onTitlePrinted()) 21116 pw.println(); 21117 pw.println("Registered ContentProviders:"); 21118 printedSomething = true; 21119 } 21120 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21121 pw.print(" "); pw.println(p.toString()); 21122 } 21123 printedSomething = false; 21124 for (Map.Entry<String, PackageParser.Provider> entry : 21125 mProvidersByAuthority.entrySet()) { 21126 PackageParser.Provider p = entry.getValue(); 21127 if (packageName != null && !packageName.equals(p.info.packageName)) { 21128 continue; 21129 } 21130 if (!printedSomething) { 21131 if (dumpState.onTitlePrinted()) 21132 pw.println(); 21133 pw.println("ContentProvider Authorities:"); 21134 printedSomething = true; 21135 } 21136 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21137 pw.print(" "); pw.println(p.toString()); 21138 if (p.info != null && p.info.applicationInfo != null) { 21139 final String appInfo = p.info.applicationInfo.toString(); 21140 pw.print(" applicationInfo="); pw.println(appInfo); 21141 } 21142 } 21143 } 21144 21145 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21146 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21147 } 21148 21149 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21150 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21151 } 21152 21153 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21154 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21155 } 21156 21157 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21158 if (dumpState.onTitlePrinted()) pw.println(); 21159 pw.println("Package Changes:"); 21160 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21161 final int K = mChangedPackages.size(); 21162 for (int i = 0; i < K; i++) { 21163 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21164 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21165 final int N = changes.size(); 21166 if (N == 0) { 21167 pw.print(" "); pw.println("No packages changed"); 21168 } else { 21169 for (int j = 0; j < N; j++) { 21170 final String pkgName = changes.valueAt(j); 21171 final int sequenceNumber = changes.keyAt(j); 21172 pw.print(" "); 21173 pw.print("seq="); 21174 pw.print(sequenceNumber); 21175 pw.print(", package="); 21176 pw.println(pkgName); 21177 } 21178 } 21179 } 21180 } 21181 21182 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21183 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21184 } 21185 21186 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21187 // XXX should handle packageName != null by dumping only install data that 21188 // the given package is involved with. 21189 if (dumpState.onTitlePrinted()) pw.println(); 21190 21191 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21192 ipw.println(); 21193 ipw.println("Frozen packages:"); 21194 ipw.increaseIndent(); 21195 if (mFrozenPackages.size() == 0) { 21196 ipw.println("(none)"); 21197 } else { 21198 for (int i = 0; i < mFrozenPackages.size(); i++) { 21199 ipw.println(mFrozenPackages.valueAt(i)); 21200 } 21201 } 21202 ipw.decreaseIndent(); 21203 } 21204 21205 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21206 if (dumpState.onTitlePrinted()) pw.println(); 21207 21208 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21209 ipw.println(); 21210 ipw.println("Loaded volumes:"); 21211 ipw.increaseIndent(); 21212 if (mLoadedVolumes.size() == 0) { 21213 ipw.println("(none)"); 21214 } else { 21215 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21216 ipw.println(mLoadedVolumes.valueAt(i)); 21217 } 21218 } 21219 ipw.decreaseIndent(); 21220 } 21221 21222 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21223 && packageName == null) { 21224 if (dumpState.onTitlePrinted()) pw.println(); 21225 pw.println("Service permissions:"); 21226 21227 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21228 while (filterIterator.hasNext()) { 21229 final ServiceIntentInfo info = filterIterator.next(); 21230 final ServiceInfo serviceInfo = info.service.info; 21231 final String permission = serviceInfo.permission; 21232 if (permission != null) { 21233 pw.print(" "); 21234 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21235 pw.print(": "); 21236 pw.println(permission); 21237 } 21238 } 21239 } 21240 21241 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21242 if (dumpState.onTitlePrinted()) pw.println(); 21243 dumpDexoptStateLPr(pw, packageName); 21244 } 21245 21246 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21247 if (dumpState.onTitlePrinted()) pw.println(); 21248 dumpCompilerStatsLPr(pw, packageName); 21249 } 21250 21251 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21252 if (dumpState.onTitlePrinted()) pw.println(); 21253 mSettings.dumpReadMessagesLPr(pw, dumpState); 21254 21255 pw.println(); 21256 pw.println("Package warning messages:"); 21257 dumpCriticalInfo(pw, null); 21258 } 21259 21260 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21261 dumpCriticalInfo(pw, "msg,"); 21262 } 21263 } 21264 21265 // PackageInstaller should be called outside of mPackages lock 21266 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21267 // XXX should handle packageName != null by dumping only install data that 21268 // the given package is involved with. 21269 if (dumpState.onTitlePrinted()) pw.println(); 21270 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21271 } 21272 } 21273 21274 private void dumpProto(FileDescriptor fd) { 21275 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21276 21277 synchronized (mPackages) { 21278 final long requiredVerifierPackageToken = 21279 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21280 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21281 proto.write( 21282 PackageServiceDumpProto.PackageShortProto.UID, 21283 getPackageUid( 21284 mRequiredVerifierPackage, 21285 MATCH_DEBUG_TRIAGED_MISSING, 21286 UserHandle.USER_SYSTEM)); 21287 proto.end(requiredVerifierPackageToken); 21288 21289 if (mIntentFilterVerifierComponent != null) { 21290 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21291 final long verifierPackageToken = 21292 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21293 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21294 proto.write( 21295 PackageServiceDumpProto.PackageShortProto.UID, 21296 getPackageUid( 21297 verifierPackageName, 21298 MATCH_DEBUG_TRIAGED_MISSING, 21299 UserHandle.USER_SYSTEM)); 21300 proto.end(verifierPackageToken); 21301 } 21302 21303 dumpSharedLibrariesProto(proto); 21304 dumpFeaturesProto(proto); 21305 mSettings.dumpPackagesProto(proto); 21306 mSettings.dumpSharedUsersProto(proto); 21307 dumpCriticalInfo(proto); 21308 } 21309 proto.flush(); 21310 } 21311 21312 private void dumpFeaturesProto(ProtoOutputStream proto) { 21313 synchronized (mAvailableFeatures) { 21314 final int count = mAvailableFeatures.size(); 21315 for (int i = 0; i < count; i++) { 21316 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21317 } 21318 } 21319 } 21320 21321 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21322 final int count = mSharedLibraries.size(); 21323 for (int i = 0; i < count; i++) { 21324 final String libName = mSharedLibraries.keyAt(i); 21325 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21326 if (versionedLib == null) { 21327 continue; 21328 } 21329 final int versionCount = versionedLib.size(); 21330 for (int j = 0; j < versionCount; j++) { 21331 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21332 final long sharedLibraryToken = 21333 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21334 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21335 final boolean isJar = (libEntry.path != null); 21336 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21337 if (isJar) { 21338 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21339 } else { 21340 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21341 } 21342 proto.end(sharedLibraryToken); 21343 } 21344 } 21345 } 21346 21347 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21348 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21349 ipw.println(); 21350 ipw.println("Dexopt state:"); 21351 ipw.increaseIndent(); 21352 Collection<PackageParser.Package> packages = null; 21353 if (packageName != null) { 21354 PackageParser.Package targetPackage = mPackages.get(packageName); 21355 if (targetPackage != null) { 21356 packages = Collections.singletonList(targetPackage); 21357 } else { 21358 ipw.println("Unable to find package: " + packageName); 21359 return; 21360 } 21361 } else { 21362 packages = mPackages.values(); 21363 } 21364 21365 for (PackageParser.Package pkg : packages) { 21366 ipw.println("[" + pkg.packageName + "]"); 21367 ipw.increaseIndent(); 21368 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21369 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21370 ipw.decreaseIndent(); 21371 } 21372 } 21373 21374 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21375 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21376 ipw.println(); 21377 ipw.println("Compiler stats:"); 21378 ipw.increaseIndent(); 21379 Collection<PackageParser.Package> packages = null; 21380 if (packageName != null) { 21381 PackageParser.Package targetPackage = mPackages.get(packageName); 21382 if (targetPackage != null) { 21383 packages = Collections.singletonList(targetPackage); 21384 } else { 21385 ipw.println("Unable to find package: " + packageName); 21386 return; 21387 } 21388 } else { 21389 packages = mPackages.values(); 21390 } 21391 21392 for (PackageParser.Package pkg : packages) { 21393 ipw.println("[" + pkg.packageName + "]"); 21394 ipw.increaseIndent(); 21395 21396 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21397 if (stats == null) { 21398 ipw.println("(No recorded stats)"); 21399 } else { 21400 stats.dump(ipw); 21401 } 21402 ipw.decreaseIndent(); 21403 } 21404 } 21405 21406 private String dumpDomainString(String packageName) { 21407 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21408 .getList(); 21409 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21410 21411 ArraySet<String> result = new ArraySet<>(); 21412 if (iviList.size() > 0) { 21413 for (IntentFilterVerificationInfo ivi : iviList) { 21414 for (String host : ivi.getDomains()) { 21415 result.add(host); 21416 } 21417 } 21418 } 21419 if (filters != null && filters.size() > 0) { 21420 for (IntentFilter filter : filters) { 21421 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21422 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21423 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21424 result.addAll(filter.getHostsList()); 21425 } 21426 } 21427 } 21428 21429 StringBuilder sb = new StringBuilder(result.size() * 16); 21430 for (String domain : result) { 21431 if (sb.length() > 0) sb.append(" "); 21432 sb.append(domain); 21433 } 21434 return sb.toString(); 21435 } 21436 21437 // ------- apps on sdcard specific code ------- 21438 static final boolean DEBUG_SD_INSTALL = false; 21439 21440 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21441 21442 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21443 21444 private boolean mMediaMounted = false; 21445 21446 static String getEncryptKey() { 21447 try { 21448 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21449 SD_ENCRYPTION_KEYSTORE_NAME); 21450 if (sdEncKey == null) { 21451 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21452 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21453 if (sdEncKey == null) { 21454 Slog.e(TAG, "Failed to create encryption keys"); 21455 return null; 21456 } 21457 } 21458 return sdEncKey; 21459 } catch (NoSuchAlgorithmException nsae) { 21460 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21461 return null; 21462 } catch (IOException ioe) { 21463 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21464 return null; 21465 } 21466 } 21467 21468 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21469 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21470 final int size = infos.size(); 21471 final String[] packageNames = new String[size]; 21472 final int[] packageUids = new int[size]; 21473 for (int i = 0; i < size; i++) { 21474 final ApplicationInfo info = infos.get(i); 21475 packageNames[i] = info.packageName; 21476 packageUids[i] = info.uid; 21477 } 21478 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21479 finishedReceiver); 21480 } 21481 21482 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21483 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21484 sendResourcesChangedBroadcast(mediaStatus, replacing, 21485 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21486 } 21487 21488 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21489 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21490 int size = pkgList.length; 21491 if (size > 0) { 21492 // Send broadcasts here 21493 Bundle extras = new Bundle(); 21494 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21495 if (uidArr != null) { 21496 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21497 } 21498 if (replacing) { 21499 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21500 } 21501 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21502 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21503 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21504 } 21505 } 21506 21507 private void loadPrivatePackages(final VolumeInfo vol) { 21508 mHandler.post(new Runnable() { 21509 @Override 21510 public void run() { 21511 loadPrivatePackagesInner(vol); 21512 } 21513 }); 21514 } 21515 21516 private void loadPrivatePackagesInner(VolumeInfo vol) { 21517 final String volumeUuid = vol.fsUuid; 21518 if (TextUtils.isEmpty(volumeUuid)) { 21519 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21520 return; 21521 } 21522 21523 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21524 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21525 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21526 21527 final VersionInfo ver; 21528 final List<PackageSetting> packages; 21529 synchronized (mPackages) { 21530 ver = mSettings.findOrCreateVersion(volumeUuid); 21531 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21532 } 21533 21534 for (PackageSetting ps : packages) { 21535 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21536 synchronized (mInstallLock) { 21537 final PackageParser.Package pkg; 21538 try { 21539 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21540 loaded.add(pkg.applicationInfo); 21541 21542 } catch (PackageManagerException e) { 21543 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21544 } 21545 21546 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21547 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21548 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21549 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21550 } 21551 } 21552 } 21553 21554 // Reconcile app data for all started/unlocked users 21555 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21556 final UserManager um = mContext.getSystemService(UserManager.class); 21557 UserManagerInternal umInternal = getUserManagerInternal(); 21558 for (UserInfo user : um.getUsers()) { 21559 final int flags; 21560 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21561 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21562 } else if (umInternal.isUserRunning(user.id)) { 21563 flags = StorageManager.FLAG_STORAGE_DE; 21564 } else { 21565 continue; 21566 } 21567 21568 try { 21569 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21570 synchronized (mInstallLock) { 21571 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21572 } 21573 } catch (IllegalStateException e) { 21574 // Device was probably ejected, and we'll process that event momentarily 21575 Slog.w(TAG, "Failed to prepare storage: " + e); 21576 } 21577 } 21578 21579 synchronized (mPackages) { 21580 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21581 if (sdkUpdated) { 21582 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21583 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21584 } 21585 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21586 mPermissionCallback); 21587 21588 // Yay, everything is now upgraded 21589 ver.forceCurrent(); 21590 21591 mSettings.writeLPr(); 21592 } 21593 21594 for (PackageFreezer freezer : freezers) { 21595 freezer.close(); 21596 } 21597 21598 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21599 sendResourcesChangedBroadcast(true, false, loaded, null); 21600 mLoadedVolumes.add(vol.getId()); 21601 } 21602 21603 private void unloadPrivatePackages(final VolumeInfo vol) { 21604 mHandler.post(new Runnable() { 21605 @Override 21606 public void run() { 21607 unloadPrivatePackagesInner(vol); 21608 } 21609 }); 21610 } 21611 21612 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21613 final String volumeUuid = vol.fsUuid; 21614 if (TextUtils.isEmpty(volumeUuid)) { 21615 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21616 return; 21617 } 21618 21619 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21620 synchronized (mInstallLock) { 21621 synchronized (mPackages) { 21622 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21623 for (PackageSetting ps : packages) { 21624 if (ps.pkg == null) continue; 21625 21626 final ApplicationInfo info = ps.pkg.applicationInfo; 21627 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21628 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21629 21630 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21631 "unloadPrivatePackagesInner")) { 21632 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21633 false, null)) { 21634 unloaded.add(info); 21635 } else { 21636 Slog.w(TAG, "Failed to unload " + ps.codePath); 21637 } 21638 } 21639 21640 // Try very hard to release any references to this package 21641 // so we don't risk the system server being killed due to 21642 // open FDs 21643 AttributeCache.instance().removePackage(ps.name); 21644 } 21645 21646 mSettings.writeLPr(); 21647 } 21648 } 21649 21650 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21651 sendResourcesChangedBroadcast(false, false, unloaded, null); 21652 mLoadedVolumes.remove(vol.getId()); 21653 21654 // Try very hard to release any references to this path so we don't risk 21655 // the system server being killed due to open FDs 21656 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21657 21658 for (int i = 0; i < 3; i++) { 21659 System.gc(); 21660 System.runFinalization(); 21661 } 21662 } 21663 21664 private void assertPackageKnown(String volumeUuid, String packageName) 21665 throws PackageManagerException { 21666 synchronized (mPackages) { 21667 // Normalize package name to handle renamed packages 21668 packageName = normalizePackageNameLPr(packageName); 21669 21670 final PackageSetting ps = mSettings.mPackages.get(packageName); 21671 if (ps == null) { 21672 throw new PackageManagerException("Package " + packageName + " is unknown"); 21673 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21674 throw new PackageManagerException( 21675 "Package " + packageName + " found on unknown volume " + volumeUuid 21676 + "; expected volume " + ps.volumeUuid); 21677 } 21678 } 21679 } 21680 21681 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21682 throws PackageManagerException { 21683 synchronized (mPackages) { 21684 // Normalize package name to handle renamed packages 21685 packageName = normalizePackageNameLPr(packageName); 21686 21687 final PackageSetting ps = mSettings.mPackages.get(packageName); 21688 if (ps == null) { 21689 throw new PackageManagerException("Package " + packageName + " is unknown"); 21690 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21691 throw new PackageManagerException( 21692 "Package " + packageName + " found on unknown volume " + volumeUuid 21693 + "; expected volume " + ps.volumeUuid); 21694 } else if (!ps.getInstalled(userId)) { 21695 throw new PackageManagerException( 21696 "Package " + packageName + " not installed for user " + userId); 21697 } 21698 } 21699 } 21700 21701 private List<String> collectAbsoluteCodePaths() { 21702 synchronized (mPackages) { 21703 List<String> codePaths = new ArrayList<>(); 21704 final int packageCount = mSettings.mPackages.size(); 21705 for (int i = 0; i < packageCount; i++) { 21706 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21707 codePaths.add(ps.codePath.getAbsolutePath()); 21708 } 21709 return codePaths; 21710 } 21711 } 21712 21713 /** 21714 * Examine all apps present on given mounted volume, and destroy apps that 21715 * aren't expected, either due to uninstallation or reinstallation on 21716 * another volume. 21717 */ 21718 private void reconcileApps(String volumeUuid) { 21719 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21720 List<File> filesToDelete = null; 21721 21722 final File[] files = FileUtils.listFilesOrEmpty( 21723 Environment.getDataAppDirectory(volumeUuid)); 21724 for (File file : files) { 21725 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21726 && !PackageInstallerService.isStageName(file.getName()); 21727 if (!isPackage) { 21728 // Ignore entries which are not packages 21729 continue; 21730 } 21731 21732 String absolutePath = file.getAbsolutePath(); 21733 21734 boolean pathValid = false; 21735 final int absoluteCodePathCount = absoluteCodePaths.size(); 21736 for (int i = 0; i < absoluteCodePathCount; i++) { 21737 String absoluteCodePath = absoluteCodePaths.get(i); 21738 if (absolutePath.startsWith(absoluteCodePath)) { 21739 pathValid = true; 21740 break; 21741 } 21742 } 21743 21744 if (!pathValid) { 21745 if (filesToDelete == null) { 21746 filesToDelete = new ArrayList<>(); 21747 } 21748 filesToDelete.add(file); 21749 } 21750 } 21751 21752 if (filesToDelete != null) { 21753 final int fileToDeleteCount = filesToDelete.size(); 21754 for (int i = 0; i < fileToDeleteCount; i++) { 21755 File fileToDelete = filesToDelete.get(i); 21756 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21757 synchronized (mInstallLock) { 21758 removeCodePathLI(fileToDelete); 21759 } 21760 } 21761 } 21762 } 21763 21764 /** 21765 * Reconcile all app data for the given user. 21766 * <p> 21767 * Verifies that directories exist and that ownership and labeling is 21768 * correct for all installed apps on all mounted volumes. 21769 */ 21770 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21771 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21772 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21773 final String volumeUuid = vol.getFsUuid(); 21774 synchronized (mInstallLock) { 21775 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21776 } 21777 } 21778 } 21779 21780 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21781 boolean migrateAppData) { 21782 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21783 } 21784 21785 /** 21786 * Reconcile all app data on given mounted volume. 21787 * <p> 21788 * Destroys app data that isn't expected, either due to uninstallation or 21789 * reinstallation on another volume. 21790 * <p> 21791 * Verifies that directories exist and that ownership and labeling is 21792 * correct for all installed apps. 21793 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21794 */ 21795 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21796 boolean migrateAppData, boolean onlyCoreApps) { 21797 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21798 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21799 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21800 21801 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21802 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21803 21804 // First look for stale data that doesn't belong, and check if things 21805 // have changed since we did our last restorecon 21806 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21807 if (StorageManager.isFileEncryptedNativeOrEmulated() 21808 && !StorageManager.isUserKeyUnlocked(userId)) { 21809 throw new RuntimeException( 21810 "Yikes, someone asked us to reconcile CE storage while " + userId 21811 + " was still locked; this would have caused massive data loss!"); 21812 } 21813 21814 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21815 for (File file : files) { 21816 final String packageName = file.getName(); 21817 try { 21818 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21819 } catch (PackageManagerException e) { 21820 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21821 try { 21822 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21823 StorageManager.FLAG_STORAGE_CE, 0); 21824 } catch (InstallerException e2) { 21825 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21826 } 21827 } 21828 } 21829 } 21830 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21831 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21832 for (File file : files) { 21833 final String packageName = file.getName(); 21834 try { 21835 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21836 } catch (PackageManagerException e) { 21837 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21838 try { 21839 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21840 StorageManager.FLAG_STORAGE_DE, 0); 21841 } catch (InstallerException e2) { 21842 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21843 } 21844 } 21845 } 21846 } 21847 21848 // Ensure that data directories are ready to roll for all packages 21849 // installed for this volume and user 21850 final List<PackageSetting> packages; 21851 synchronized (mPackages) { 21852 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21853 } 21854 int preparedCount = 0; 21855 for (PackageSetting ps : packages) { 21856 final String packageName = ps.name; 21857 if (ps.pkg == null) { 21858 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21859 // TODO: might be due to legacy ASEC apps; we should circle back 21860 // and reconcile again once they're scanned 21861 continue; 21862 } 21863 // Skip non-core apps if requested 21864 if (onlyCoreApps && !ps.pkg.coreApp) { 21865 result.add(packageName); 21866 continue; 21867 } 21868 21869 if (ps.getInstalled(userId)) { 21870 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21871 preparedCount++; 21872 } 21873 } 21874 21875 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21876 return result; 21877 } 21878 21879 /** 21880 * Prepare app data for the given app just after it was installed or 21881 * upgraded. This method carefully only touches users that it's installed 21882 * for, and it forces a restorecon to handle any seinfo changes. 21883 * <p> 21884 * Verifies that directories exist and that ownership and labeling is 21885 * correct for all installed apps. If there is an ownership mismatch, it 21886 * will try recovering system apps by wiping data; third-party app data is 21887 * left intact. 21888 * <p> 21889 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21890 */ 21891 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21892 final PackageSetting ps; 21893 synchronized (mPackages) { 21894 ps = mSettings.mPackages.get(pkg.packageName); 21895 mSettings.writeKernelMappingLPr(ps); 21896 } 21897 21898 final UserManager um = mContext.getSystemService(UserManager.class); 21899 UserManagerInternal umInternal = getUserManagerInternal(); 21900 for (UserInfo user : um.getUsers()) { 21901 final int flags; 21902 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21903 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21904 } else if (umInternal.isUserRunning(user.id)) { 21905 flags = StorageManager.FLAG_STORAGE_DE; 21906 } else { 21907 continue; 21908 } 21909 21910 if (ps.getInstalled(user.id)) { 21911 // TODO: when user data is locked, mark that we're still dirty 21912 prepareAppDataLIF(pkg, user.id, flags); 21913 } 21914 } 21915 } 21916 21917 /** 21918 * Prepare app data for the given app. 21919 * <p> 21920 * Verifies that directories exist and that ownership and labeling is 21921 * correct for all installed apps. If there is an ownership mismatch, this 21922 * will try recovering system apps by wiping data; third-party app data is 21923 * left intact. 21924 */ 21925 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21926 if (pkg == null) { 21927 Slog.wtf(TAG, "Package was null!", new Throwable()); 21928 return; 21929 } 21930 prepareAppDataLeafLIF(pkg, userId, flags); 21931 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21932 for (int i = 0; i < childCount; i++) { 21933 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21934 } 21935 } 21936 21937 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21938 boolean maybeMigrateAppData) { 21939 prepareAppDataLIF(pkg, userId, flags); 21940 21941 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21942 // We may have just shuffled around app data directories, so 21943 // prepare them one more time 21944 prepareAppDataLIF(pkg, userId, flags); 21945 } 21946 } 21947 21948 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21949 if (DEBUG_APP_DATA) { 21950 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21951 + Integer.toHexString(flags)); 21952 } 21953 21954 final String volumeUuid = pkg.volumeUuid; 21955 final String packageName = pkg.packageName; 21956 final ApplicationInfo app = pkg.applicationInfo; 21957 final int appId = UserHandle.getAppId(app.uid); 21958 21959 Preconditions.checkNotNull(app.seInfo); 21960 21961 long ceDataInode = -1; 21962 try { 21963 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21964 appId, app.seInfo, app.targetSdkVersion); 21965 } catch (InstallerException e) { 21966 if (app.isSystemApp()) { 21967 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21968 + ", but trying to recover: " + e); 21969 destroyAppDataLeafLIF(pkg, userId, flags); 21970 try { 21971 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21972 appId, app.seInfo, app.targetSdkVersion); 21973 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21974 } catch (InstallerException e2) { 21975 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21976 } 21977 } else { 21978 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21979 } 21980 } 21981 21982 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21983 // TODO: mark this structure as dirty so we persist it! 21984 synchronized (mPackages) { 21985 final PackageSetting ps = mSettings.mPackages.get(packageName); 21986 if (ps != null) { 21987 ps.setCeDataInode(ceDataInode, userId); 21988 } 21989 } 21990 } 21991 21992 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21993 } 21994 21995 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21996 if (pkg == null) { 21997 Slog.wtf(TAG, "Package was null!", new Throwable()); 21998 return; 21999 } 22000 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22001 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22002 for (int i = 0; i < childCount; i++) { 22003 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22004 } 22005 } 22006 22007 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22008 final String volumeUuid = pkg.volumeUuid; 22009 final String packageName = pkg.packageName; 22010 final ApplicationInfo app = pkg.applicationInfo; 22011 22012 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22013 // Create a native library symlink only if we have native libraries 22014 // and if the native libraries are 32 bit libraries. We do not provide 22015 // this symlink for 64 bit libraries. 22016 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22017 final String nativeLibPath = app.nativeLibraryDir; 22018 try { 22019 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22020 nativeLibPath, userId); 22021 } catch (InstallerException e) { 22022 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22023 } 22024 } 22025 } 22026 } 22027 22028 /** 22029 * For system apps on non-FBE devices, this method migrates any existing 22030 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22031 * requested by the app. 22032 */ 22033 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22034 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22035 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22036 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22037 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22038 try { 22039 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22040 storageTarget); 22041 } catch (InstallerException e) { 22042 logCriticalInfo(Log.WARN, 22043 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22044 } 22045 return true; 22046 } else { 22047 return false; 22048 } 22049 } 22050 22051 public PackageFreezer freezePackage(String packageName, String killReason) { 22052 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22053 } 22054 22055 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22056 return new PackageFreezer(packageName, userId, killReason); 22057 } 22058 22059 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22060 String killReason) { 22061 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22062 } 22063 22064 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22065 String killReason) { 22066 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22067 return new PackageFreezer(); 22068 } else { 22069 return freezePackage(packageName, userId, killReason); 22070 } 22071 } 22072 22073 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22074 String killReason) { 22075 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22076 } 22077 22078 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22079 String killReason) { 22080 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22081 return new PackageFreezer(); 22082 } else { 22083 return freezePackage(packageName, userId, killReason); 22084 } 22085 } 22086 22087 /** 22088 * Class that freezes and kills the given package upon creation, and 22089 * unfreezes it upon closing. This is typically used when doing surgery on 22090 * app code/data to prevent the app from running while you're working. 22091 */ 22092 private class PackageFreezer implements AutoCloseable { 22093 private final String mPackageName; 22094 private final PackageFreezer[] mChildren; 22095 22096 private final boolean mWeFroze; 22097 22098 private final AtomicBoolean mClosed = new AtomicBoolean(); 22099 private final CloseGuard mCloseGuard = CloseGuard.get(); 22100 22101 /** 22102 * Create and return a stub freezer that doesn't actually do anything, 22103 * typically used when someone requested 22104 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22105 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22106 */ 22107 public PackageFreezer() { 22108 mPackageName = null; 22109 mChildren = null; 22110 mWeFroze = false; 22111 mCloseGuard.open("close"); 22112 } 22113 22114 public PackageFreezer(String packageName, int userId, String killReason) { 22115 synchronized (mPackages) { 22116 mPackageName = packageName; 22117 mWeFroze = mFrozenPackages.add(mPackageName); 22118 22119 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22120 if (ps != null) { 22121 killApplication(ps.name, ps.appId, userId, killReason); 22122 } 22123 22124 final PackageParser.Package p = mPackages.get(packageName); 22125 if (p != null && p.childPackages != null) { 22126 final int N = p.childPackages.size(); 22127 mChildren = new PackageFreezer[N]; 22128 for (int i = 0; i < N; i++) { 22129 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22130 userId, killReason); 22131 } 22132 } else { 22133 mChildren = null; 22134 } 22135 } 22136 mCloseGuard.open("close"); 22137 } 22138 22139 @Override 22140 protected void finalize() throws Throwable { 22141 try { 22142 if (mCloseGuard != null) { 22143 mCloseGuard.warnIfOpen(); 22144 } 22145 22146 close(); 22147 } finally { 22148 super.finalize(); 22149 } 22150 } 22151 22152 @Override 22153 public void close() { 22154 mCloseGuard.close(); 22155 if (mClosed.compareAndSet(false, true)) { 22156 synchronized (mPackages) { 22157 if (mWeFroze) { 22158 mFrozenPackages.remove(mPackageName); 22159 } 22160 22161 if (mChildren != null) { 22162 for (PackageFreezer freezer : mChildren) { 22163 freezer.close(); 22164 } 22165 } 22166 } 22167 } 22168 } 22169 } 22170 22171 /** 22172 * Verify that given package is currently frozen. 22173 */ 22174 private void checkPackageFrozen(String packageName) { 22175 synchronized (mPackages) { 22176 if (!mFrozenPackages.contains(packageName)) { 22177 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22178 } 22179 } 22180 } 22181 22182 @Override 22183 public int movePackage(final String packageName, final String volumeUuid) { 22184 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22185 22186 final int callingUid = Binder.getCallingUid(); 22187 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22188 final int moveId = mNextMoveId.getAndIncrement(); 22189 mHandler.post(new Runnable() { 22190 @Override 22191 public void run() { 22192 try { 22193 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22194 } catch (PackageManagerException e) { 22195 Slog.w(TAG, "Failed to move " + packageName, e); 22196 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22197 } 22198 } 22199 }); 22200 return moveId; 22201 } 22202 22203 private void movePackageInternal(final String packageName, final String volumeUuid, 22204 final int moveId, final int callingUid, UserHandle user) 22205 throws PackageManagerException { 22206 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22207 final PackageManager pm = mContext.getPackageManager(); 22208 22209 final boolean currentAsec; 22210 final String currentVolumeUuid; 22211 final File codeFile; 22212 final String installerPackageName; 22213 final String packageAbiOverride; 22214 final int appId; 22215 final String seinfo; 22216 final String label; 22217 final int targetSdkVersion; 22218 final PackageFreezer freezer; 22219 final int[] installedUserIds; 22220 22221 // reader 22222 synchronized (mPackages) { 22223 final PackageParser.Package pkg = mPackages.get(packageName); 22224 final PackageSetting ps = mSettings.mPackages.get(packageName); 22225 if (pkg == null 22226 || ps == null 22227 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22228 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22229 } 22230 if (pkg.applicationInfo.isSystemApp()) { 22231 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22232 "Cannot move system application"); 22233 } 22234 22235 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22236 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22237 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22238 if (isInternalStorage && !allow3rdPartyOnInternal) { 22239 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22240 "3rd party apps are not allowed on internal storage"); 22241 } 22242 22243 if (pkg.applicationInfo.isExternalAsec()) { 22244 currentAsec = true; 22245 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22246 } else if (pkg.applicationInfo.isForwardLocked()) { 22247 currentAsec = true; 22248 currentVolumeUuid = "forward_locked"; 22249 } else { 22250 currentAsec = false; 22251 currentVolumeUuid = ps.volumeUuid; 22252 22253 final File probe = new File(pkg.codePath); 22254 final File probeOat = new File(probe, "oat"); 22255 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22256 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22257 "Move only supported for modern cluster style installs"); 22258 } 22259 } 22260 22261 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22262 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22263 "Package already moved to " + volumeUuid); 22264 } 22265 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22266 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22267 "Device admin cannot be moved"); 22268 } 22269 22270 if (mFrozenPackages.contains(packageName)) { 22271 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22272 "Failed to move already frozen package"); 22273 } 22274 22275 codeFile = new File(pkg.codePath); 22276 installerPackageName = ps.installerPackageName; 22277 packageAbiOverride = ps.cpuAbiOverrideString; 22278 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22279 seinfo = pkg.applicationInfo.seInfo; 22280 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22281 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22282 freezer = freezePackage(packageName, "movePackageInternal"); 22283 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22284 } 22285 22286 final Bundle extras = new Bundle(); 22287 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22288 extras.putString(Intent.EXTRA_TITLE, label); 22289 mMoveCallbacks.notifyCreated(moveId, extras); 22290 22291 int installFlags; 22292 final boolean moveCompleteApp; 22293 final File measurePath; 22294 22295 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22296 installFlags = INSTALL_INTERNAL; 22297 moveCompleteApp = !currentAsec; 22298 measurePath = Environment.getDataAppDirectory(volumeUuid); 22299 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22300 installFlags = INSTALL_EXTERNAL; 22301 moveCompleteApp = false; 22302 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22303 } else { 22304 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22305 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22306 || !volume.isMountedWritable()) { 22307 freezer.close(); 22308 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22309 "Move location not mounted private volume"); 22310 } 22311 22312 Preconditions.checkState(!currentAsec); 22313 22314 installFlags = INSTALL_INTERNAL; 22315 moveCompleteApp = true; 22316 measurePath = Environment.getDataAppDirectory(volumeUuid); 22317 } 22318 22319 // If we're moving app data around, we need all the users unlocked 22320 if (moveCompleteApp) { 22321 for (int userId : installedUserIds) { 22322 if (StorageManager.isFileEncryptedNativeOrEmulated() 22323 && !StorageManager.isUserKeyUnlocked(userId)) { 22324 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22325 "User " + userId + " must be unlocked"); 22326 } 22327 } 22328 } 22329 22330 final PackageStats stats = new PackageStats(null, -1); 22331 synchronized (mInstaller) { 22332 for (int userId : installedUserIds) { 22333 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22334 freezer.close(); 22335 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22336 "Failed to measure package size"); 22337 } 22338 } 22339 } 22340 22341 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22342 + stats.dataSize); 22343 22344 final long startFreeBytes = measurePath.getUsableSpace(); 22345 final long sizeBytes; 22346 if (moveCompleteApp) { 22347 sizeBytes = stats.codeSize + stats.dataSize; 22348 } else { 22349 sizeBytes = stats.codeSize; 22350 } 22351 22352 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22353 freezer.close(); 22354 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22355 "Not enough free space to move"); 22356 } 22357 22358 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22359 22360 final CountDownLatch installedLatch = new CountDownLatch(1); 22361 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22362 @Override 22363 public void onUserActionRequired(Intent intent) throws RemoteException { 22364 throw new IllegalStateException(); 22365 } 22366 22367 @Override 22368 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22369 Bundle extras) throws RemoteException { 22370 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22371 + PackageManager.installStatusToString(returnCode, msg)); 22372 22373 installedLatch.countDown(); 22374 freezer.close(); 22375 22376 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22377 switch (status) { 22378 case PackageInstaller.STATUS_SUCCESS: 22379 mMoveCallbacks.notifyStatusChanged(moveId, 22380 PackageManager.MOVE_SUCCEEDED); 22381 break; 22382 case PackageInstaller.STATUS_FAILURE_STORAGE: 22383 mMoveCallbacks.notifyStatusChanged(moveId, 22384 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22385 break; 22386 default: 22387 mMoveCallbacks.notifyStatusChanged(moveId, 22388 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22389 break; 22390 } 22391 } 22392 }; 22393 22394 final MoveInfo move; 22395 if (moveCompleteApp) { 22396 // Kick off a thread to report progress estimates 22397 new Thread() { 22398 @Override 22399 public void run() { 22400 while (true) { 22401 try { 22402 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22403 break; 22404 } 22405 } catch (InterruptedException ignored) { 22406 } 22407 22408 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22409 final int progress = 10 + (int) MathUtils.constrain( 22410 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22411 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22412 } 22413 } 22414 }.start(); 22415 22416 final String dataAppName = codeFile.getName(); 22417 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22418 dataAppName, appId, seinfo, targetSdkVersion); 22419 } else { 22420 move = null; 22421 } 22422 22423 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22424 22425 final Message msg = mHandler.obtainMessage(INIT_COPY); 22426 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22427 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22428 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22429 packageAbiOverride, null /*grantedPermissions*/, 22430 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22431 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22432 msg.obj = params; 22433 22434 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22435 System.identityHashCode(msg.obj)); 22436 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22437 System.identityHashCode(msg.obj)); 22438 22439 mHandler.sendMessage(msg); 22440 } 22441 22442 @Override 22443 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22445 22446 final int realMoveId = mNextMoveId.getAndIncrement(); 22447 final Bundle extras = new Bundle(); 22448 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22449 mMoveCallbacks.notifyCreated(realMoveId, extras); 22450 22451 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22452 @Override 22453 public void onCreated(int moveId, Bundle extras) { 22454 // Ignored 22455 } 22456 22457 @Override 22458 public void onStatusChanged(int moveId, int status, long estMillis) { 22459 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22460 } 22461 }; 22462 22463 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22464 storage.setPrimaryStorageUuid(volumeUuid, callback); 22465 return realMoveId; 22466 } 22467 22468 @Override 22469 public int getMoveStatus(int moveId) { 22470 mContext.enforceCallingOrSelfPermission( 22471 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22472 return mMoveCallbacks.mLastStatus.get(moveId); 22473 } 22474 22475 @Override 22476 public void registerMoveCallback(IPackageMoveObserver callback) { 22477 mContext.enforceCallingOrSelfPermission( 22478 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22479 mMoveCallbacks.register(callback); 22480 } 22481 22482 @Override 22483 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22484 mContext.enforceCallingOrSelfPermission( 22485 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22486 mMoveCallbacks.unregister(callback); 22487 } 22488 22489 @Override 22490 public boolean setInstallLocation(int loc) { 22491 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22492 null); 22493 if (getInstallLocation() == loc) { 22494 return true; 22495 } 22496 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22497 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22498 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22499 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22500 return true; 22501 } 22502 return false; 22503 } 22504 22505 @Override 22506 public int getInstallLocation() { 22507 // allow instant app access 22508 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22509 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22510 PackageHelper.APP_INSTALL_AUTO); 22511 } 22512 22513 /** Called by UserManagerService */ 22514 void cleanUpUser(UserManagerService userManager, int userHandle) { 22515 synchronized (mPackages) { 22516 mDirtyUsers.remove(userHandle); 22517 mUserNeedsBadging.delete(userHandle); 22518 mSettings.removeUserLPw(userHandle); 22519 mPendingBroadcasts.remove(userHandle); 22520 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22521 removeUnusedPackagesLPw(userManager, userHandle); 22522 } 22523 } 22524 22525 /** 22526 * We're removing userHandle and would like to remove any downloaded packages 22527 * that are no longer in use by any other user. 22528 * @param userHandle the user being removed 22529 */ 22530 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22531 final boolean DEBUG_CLEAN_APKS = false; 22532 int [] users = userManager.getUserIds(); 22533 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22534 while (psit.hasNext()) { 22535 PackageSetting ps = psit.next(); 22536 if (ps.pkg == null) { 22537 continue; 22538 } 22539 final String packageName = ps.pkg.packageName; 22540 // Skip over if system app 22541 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22542 continue; 22543 } 22544 if (DEBUG_CLEAN_APKS) { 22545 Slog.i(TAG, "Checking package " + packageName); 22546 } 22547 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22548 if (keep) { 22549 if (DEBUG_CLEAN_APKS) { 22550 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22551 } 22552 } else { 22553 for (int i = 0; i < users.length; i++) { 22554 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22555 keep = true; 22556 if (DEBUG_CLEAN_APKS) { 22557 Slog.i(TAG, " Keeping package " + packageName + " for user " 22558 + users[i]); 22559 } 22560 break; 22561 } 22562 } 22563 } 22564 if (!keep) { 22565 if (DEBUG_CLEAN_APKS) { 22566 Slog.i(TAG, " Removing package " + packageName); 22567 } 22568 mHandler.post(new Runnable() { 22569 public void run() { 22570 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22571 userHandle, 0); 22572 } //end run 22573 }); 22574 } 22575 } 22576 } 22577 22578 /** Called by UserManagerService */ 22579 void createNewUser(int userId, String[] disallowedPackages) { 22580 synchronized (mInstallLock) { 22581 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22582 } 22583 synchronized (mPackages) { 22584 scheduleWritePackageRestrictionsLocked(userId); 22585 scheduleWritePackageListLocked(userId); 22586 applyFactoryDefaultBrowserLPw(userId); 22587 primeDomainVerificationsLPw(userId); 22588 } 22589 } 22590 22591 void onNewUserCreated(final int userId) { 22592 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22593 synchronized(mPackages) { 22594 // If permission review for legacy apps is required, we represent 22595 // dagerous permissions for such apps as always granted runtime 22596 // permissions to keep per user flag state whether review is needed. 22597 // Hence, if a new user is added we have to propagate dangerous 22598 // permission grants for these legacy apps. 22599 if (mSettings.mPermissions.mPermissionReviewRequired) { 22600// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22601 mPermissionManager.updateAllPermissions( 22602 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22603 mPermissionCallback); 22604 } 22605 } 22606 } 22607 22608 @Override 22609 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22610 mContext.enforceCallingOrSelfPermission( 22611 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22612 "Only package verification agents can read the verifier device identity"); 22613 22614 synchronized (mPackages) { 22615 return mSettings.getVerifierDeviceIdentityLPw(); 22616 } 22617 } 22618 22619 @Override 22620 public void setPermissionEnforced(String permission, boolean enforced) { 22621 // TODO: Now that we no longer change GID for storage, this should to away. 22622 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22623 "setPermissionEnforced"); 22624 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22625 synchronized (mPackages) { 22626 if (mSettings.mReadExternalStorageEnforced == null 22627 || mSettings.mReadExternalStorageEnforced != enforced) { 22628 mSettings.mReadExternalStorageEnforced = 22629 enforced ? Boolean.TRUE : Boolean.FALSE; 22630 mSettings.writeLPr(); 22631 } 22632 } 22633 // kill any non-foreground processes so we restart them and 22634 // grant/revoke the GID. 22635 final IActivityManager am = ActivityManager.getService(); 22636 if (am != null) { 22637 final long token = Binder.clearCallingIdentity(); 22638 try { 22639 am.killProcessesBelowForeground("setPermissionEnforcement"); 22640 } catch (RemoteException e) { 22641 } finally { 22642 Binder.restoreCallingIdentity(token); 22643 } 22644 } 22645 } else { 22646 throw new IllegalArgumentException("No selective enforcement for " + permission); 22647 } 22648 } 22649 22650 @Override 22651 @Deprecated 22652 public boolean isPermissionEnforced(String permission) { 22653 // allow instant applications 22654 return true; 22655 } 22656 22657 @Override 22658 public boolean isStorageLow() { 22659 // allow instant applications 22660 final long token = Binder.clearCallingIdentity(); 22661 try { 22662 final DeviceStorageMonitorInternal 22663 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22664 if (dsm != null) { 22665 return dsm.isMemoryLow(); 22666 } else { 22667 return false; 22668 } 22669 } finally { 22670 Binder.restoreCallingIdentity(token); 22671 } 22672 } 22673 22674 @Override 22675 public IPackageInstaller getPackageInstaller() { 22676 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22677 return null; 22678 } 22679 return mInstallerService; 22680 } 22681 22682 @Override 22683 public IArtManager getArtManager() { 22684 return mArtManagerService; 22685 } 22686 22687 private boolean userNeedsBadging(int userId) { 22688 int index = mUserNeedsBadging.indexOfKey(userId); 22689 if (index < 0) { 22690 final UserInfo userInfo; 22691 final long token = Binder.clearCallingIdentity(); 22692 try { 22693 userInfo = sUserManager.getUserInfo(userId); 22694 } finally { 22695 Binder.restoreCallingIdentity(token); 22696 } 22697 final boolean b; 22698 if (userInfo != null && userInfo.isManagedProfile()) { 22699 b = true; 22700 } else { 22701 b = false; 22702 } 22703 mUserNeedsBadging.put(userId, b); 22704 return b; 22705 } 22706 return mUserNeedsBadging.valueAt(index); 22707 } 22708 22709 @Override 22710 public KeySet getKeySetByAlias(String packageName, String alias) { 22711 if (packageName == null || alias == null) { 22712 return null; 22713 } 22714 synchronized(mPackages) { 22715 final PackageParser.Package pkg = mPackages.get(packageName); 22716 if (pkg == null) { 22717 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22718 throw new IllegalArgumentException("Unknown package: " + packageName); 22719 } 22720 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22721 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22722 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22723 throw new IllegalArgumentException("Unknown package: " + packageName); 22724 } 22725 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22726 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22727 } 22728 } 22729 22730 @Override 22731 public KeySet getSigningKeySet(String packageName) { 22732 if (packageName == null) { 22733 return null; 22734 } 22735 synchronized(mPackages) { 22736 final int callingUid = Binder.getCallingUid(); 22737 final int callingUserId = UserHandle.getUserId(callingUid); 22738 final PackageParser.Package pkg = mPackages.get(packageName); 22739 if (pkg == null) { 22740 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22741 throw new IllegalArgumentException("Unknown package: " + packageName); 22742 } 22743 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22744 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22745 // filter and pretend the package doesn't exist 22746 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22747 + ", uid:" + callingUid); 22748 throw new IllegalArgumentException("Unknown package: " + packageName); 22749 } 22750 if (pkg.applicationInfo.uid != callingUid 22751 && Process.SYSTEM_UID != callingUid) { 22752 throw new SecurityException("May not access signing KeySet of other apps."); 22753 } 22754 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22755 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22756 } 22757 } 22758 22759 @Override 22760 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22761 final int callingUid = Binder.getCallingUid(); 22762 if (getInstantAppPackageName(callingUid) != null) { 22763 return false; 22764 } 22765 if (packageName == null || ks == null) { 22766 return false; 22767 } 22768 synchronized(mPackages) { 22769 final PackageParser.Package pkg = mPackages.get(packageName); 22770 if (pkg == null 22771 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22772 UserHandle.getUserId(callingUid))) { 22773 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22774 throw new IllegalArgumentException("Unknown package: " + packageName); 22775 } 22776 IBinder ksh = ks.getToken(); 22777 if (ksh instanceof KeySetHandle) { 22778 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22779 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22780 } 22781 return false; 22782 } 22783 } 22784 22785 @Override 22786 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22787 final int callingUid = Binder.getCallingUid(); 22788 if (getInstantAppPackageName(callingUid) != null) { 22789 return false; 22790 } 22791 if (packageName == null || ks == null) { 22792 return false; 22793 } 22794 synchronized(mPackages) { 22795 final PackageParser.Package pkg = mPackages.get(packageName); 22796 if (pkg == null 22797 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22798 UserHandle.getUserId(callingUid))) { 22799 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22800 throw new IllegalArgumentException("Unknown package: " + packageName); 22801 } 22802 IBinder ksh = ks.getToken(); 22803 if (ksh instanceof KeySetHandle) { 22804 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22805 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22806 } 22807 return false; 22808 } 22809 } 22810 22811 private void deletePackageIfUnusedLPr(final String packageName) { 22812 PackageSetting ps = mSettings.mPackages.get(packageName); 22813 if (ps == null) { 22814 return; 22815 } 22816 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22817 // TODO Implement atomic delete if package is unused 22818 // It is currently possible that the package will be deleted even if it is installed 22819 // after this method returns. 22820 mHandler.post(new Runnable() { 22821 public void run() { 22822 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22823 0, PackageManager.DELETE_ALL_USERS); 22824 } 22825 }); 22826 } 22827 } 22828 22829 /** 22830 * Check and throw if the given before/after packages would be considered a 22831 * downgrade. 22832 */ 22833 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22834 throws PackageManagerException { 22835 if (after.getLongVersionCode() < before.getLongVersionCode()) { 22836 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22837 "Update version code " + after.versionCode + " is older than current " 22838 + before.getLongVersionCode()); 22839 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 22840 if (after.baseRevisionCode < before.baseRevisionCode) { 22841 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22842 "Update base revision code " + after.baseRevisionCode 22843 + " is older than current " + before.baseRevisionCode); 22844 } 22845 22846 if (!ArrayUtils.isEmpty(after.splitNames)) { 22847 for (int i = 0; i < after.splitNames.length; i++) { 22848 final String splitName = after.splitNames[i]; 22849 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22850 if (j != -1) { 22851 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22852 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22853 "Update split " + splitName + " revision code " 22854 + after.splitRevisionCodes[i] + " is older than current " 22855 + before.splitRevisionCodes[j]); 22856 } 22857 } 22858 } 22859 } 22860 } 22861 } 22862 22863 private static class MoveCallbacks extends Handler { 22864 private static final int MSG_CREATED = 1; 22865 private static final int MSG_STATUS_CHANGED = 2; 22866 22867 private final RemoteCallbackList<IPackageMoveObserver> 22868 mCallbacks = new RemoteCallbackList<>(); 22869 22870 private final SparseIntArray mLastStatus = new SparseIntArray(); 22871 22872 public MoveCallbacks(Looper looper) { 22873 super(looper); 22874 } 22875 22876 public void register(IPackageMoveObserver callback) { 22877 mCallbacks.register(callback); 22878 } 22879 22880 public void unregister(IPackageMoveObserver callback) { 22881 mCallbacks.unregister(callback); 22882 } 22883 22884 @Override 22885 public void handleMessage(Message msg) { 22886 final SomeArgs args = (SomeArgs) msg.obj; 22887 final int n = mCallbacks.beginBroadcast(); 22888 for (int i = 0; i < n; i++) { 22889 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22890 try { 22891 invokeCallback(callback, msg.what, args); 22892 } catch (RemoteException ignored) { 22893 } 22894 } 22895 mCallbacks.finishBroadcast(); 22896 args.recycle(); 22897 } 22898 22899 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22900 throws RemoteException { 22901 switch (what) { 22902 case MSG_CREATED: { 22903 callback.onCreated(args.argi1, (Bundle) args.arg2); 22904 break; 22905 } 22906 case MSG_STATUS_CHANGED: { 22907 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22908 break; 22909 } 22910 } 22911 } 22912 22913 private void notifyCreated(int moveId, Bundle extras) { 22914 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22915 22916 final SomeArgs args = SomeArgs.obtain(); 22917 args.argi1 = moveId; 22918 args.arg2 = extras; 22919 obtainMessage(MSG_CREATED, args).sendToTarget(); 22920 } 22921 22922 private void notifyStatusChanged(int moveId, int status) { 22923 notifyStatusChanged(moveId, status, -1); 22924 } 22925 22926 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22927 Slog.v(TAG, "Move " + moveId + " status " + status); 22928 22929 final SomeArgs args = SomeArgs.obtain(); 22930 args.argi1 = moveId; 22931 args.argi2 = status; 22932 args.arg3 = estMillis; 22933 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22934 22935 synchronized (mLastStatus) { 22936 mLastStatus.put(moveId, status); 22937 } 22938 } 22939 } 22940 22941 private final static class OnPermissionChangeListeners extends Handler { 22942 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22943 22944 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22945 new RemoteCallbackList<>(); 22946 22947 public OnPermissionChangeListeners(Looper looper) { 22948 super(looper); 22949 } 22950 22951 @Override 22952 public void handleMessage(Message msg) { 22953 switch (msg.what) { 22954 case MSG_ON_PERMISSIONS_CHANGED: { 22955 final int uid = msg.arg1; 22956 handleOnPermissionsChanged(uid); 22957 } break; 22958 } 22959 } 22960 22961 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22962 mPermissionListeners.register(listener); 22963 22964 } 22965 22966 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22967 mPermissionListeners.unregister(listener); 22968 } 22969 22970 public void onPermissionsChanged(int uid) { 22971 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22972 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22973 } 22974 } 22975 22976 private void handleOnPermissionsChanged(int uid) { 22977 final int count = mPermissionListeners.beginBroadcast(); 22978 try { 22979 for (int i = 0; i < count; i++) { 22980 IOnPermissionsChangeListener callback = mPermissionListeners 22981 .getBroadcastItem(i); 22982 try { 22983 callback.onPermissionsChanged(uid); 22984 } catch (RemoteException e) { 22985 Log.e(TAG, "Permission listener is dead", e); 22986 } 22987 } 22988 } finally { 22989 mPermissionListeners.finishBroadcast(); 22990 } 22991 } 22992 } 22993 22994 private class PackageManagerNative extends IPackageManagerNative.Stub { 22995 @Override 22996 public String[] getNamesForUids(int[] uids) throws RemoteException { 22997 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22998 // massage results so they can be parsed by the native binder 22999 for (int i = results.length - 1; i >= 0; --i) { 23000 if (results[i] == null) { 23001 results[i] = ""; 23002 } 23003 } 23004 return results; 23005 } 23006 23007 // NB: this differentiates between preloads and sideloads 23008 @Override 23009 public String getInstallerForPackage(String packageName) throws RemoteException { 23010 final String installerName = getInstallerPackageName(packageName); 23011 if (!TextUtils.isEmpty(installerName)) { 23012 return installerName; 23013 } 23014 // differentiate between preload and sideload 23015 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23016 ApplicationInfo appInfo = getApplicationInfo(packageName, 23017 /*flags*/ 0, 23018 /*userId*/ callingUser); 23019 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23020 return "preload"; 23021 } 23022 return ""; 23023 } 23024 23025 @Override 23026 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23027 try { 23028 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23029 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23030 if (pInfo != null) { 23031 return pInfo.getLongVersionCode(); 23032 } 23033 } catch (Exception e) { 23034 } 23035 return 0; 23036 } 23037 } 23038 23039 private class PackageManagerInternalImpl extends PackageManagerInternal { 23040 @Override 23041 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23042 int flagValues, int userId) { 23043 PackageManagerService.this.updatePermissionFlags( 23044 permName, packageName, flagMask, flagValues, userId); 23045 } 23046 23047 @Override 23048 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23049 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23050 } 23051 23052 @Override 23053 public boolean isInstantApp(String packageName, int userId) { 23054 return PackageManagerService.this.isInstantApp(packageName, userId); 23055 } 23056 23057 @Override 23058 public String getInstantAppPackageName(int uid) { 23059 return PackageManagerService.this.getInstantAppPackageName(uid); 23060 } 23061 23062 @Override 23063 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23064 synchronized (mPackages) { 23065 return PackageManagerService.this.filterAppAccessLPr( 23066 (PackageSetting) pkg.mExtras, callingUid, userId); 23067 } 23068 } 23069 23070 @Override 23071 public PackageParser.Package getPackage(String packageName) { 23072 synchronized (mPackages) { 23073 packageName = resolveInternalPackageNameLPr( 23074 packageName, PackageManager.VERSION_CODE_HIGHEST); 23075 return mPackages.get(packageName); 23076 } 23077 } 23078 23079 @Override 23080 public PackageList getPackageList(PackageListObserver observer) { 23081 synchronized (mPackages) { 23082 final int N = mPackages.size(); 23083 final ArrayList<String> list = new ArrayList<>(N); 23084 for (int i = 0; i < N; i++) { 23085 list.add(mPackages.keyAt(i)); 23086 } 23087 final PackageList packageList = new PackageList(list, observer); 23088 if (observer != null) { 23089 mPackageListObservers.add(packageList); 23090 } 23091 return packageList; 23092 } 23093 } 23094 23095 @Override 23096 public void removePackageListObserver(PackageListObserver observer) { 23097 synchronized (mPackages) { 23098 mPackageListObservers.remove(observer); 23099 } 23100 } 23101 23102 @Override 23103 public PackageParser.Package getDisabledPackage(String packageName) { 23104 synchronized (mPackages) { 23105 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23106 return (ps != null) ? ps.pkg : null; 23107 } 23108 } 23109 23110 @Override 23111 public String getKnownPackageName(int knownPackage, int userId) { 23112 switch(knownPackage) { 23113 case PackageManagerInternal.PACKAGE_BROWSER: 23114 return getDefaultBrowserPackageName(userId); 23115 case PackageManagerInternal.PACKAGE_INSTALLER: 23116 return mRequiredInstallerPackage; 23117 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23118 return mSetupWizardPackage; 23119 case PackageManagerInternal.PACKAGE_SYSTEM: 23120 return "android"; 23121 case PackageManagerInternal.PACKAGE_VERIFIER: 23122 return mRequiredVerifierPackage; 23123 } 23124 return null; 23125 } 23126 23127 @Override 23128 public boolean isResolveActivityComponent(ComponentInfo component) { 23129 return mResolveActivity.packageName.equals(component.packageName) 23130 && mResolveActivity.name.equals(component.name); 23131 } 23132 23133 @Override 23134 public void setLocationPackagesProvider(PackagesProvider provider) { 23135 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23136 } 23137 23138 @Override 23139 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23140 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23141 } 23142 23143 @Override 23144 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23145 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23146 } 23147 23148 @Override 23149 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23150 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23151 } 23152 23153 @Override 23154 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23155 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23156 } 23157 23158 @Override 23159 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23160 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23161 } 23162 23163 @Override 23164 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23165 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23166 } 23167 23168 @Override 23169 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23170 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23171 } 23172 23173 @Override 23174 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23175 synchronized (mPackages) { 23176 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23177 } 23178 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23179 } 23180 23181 @Override 23182 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23183 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23184 packageName, userId); 23185 } 23186 23187 @Override 23188 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23189 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23190 packageName, userId); 23191 } 23192 23193 @Override 23194 public void setKeepUninstalledPackages(final List<String> packageList) { 23195 Preconditions.checkNotNull(packageList); 23196 List<String> removedFromList = null; 23197 synchronized (mPackages) { 23198 if (mKeepUninstalledPackages != null) { 23199 final int packagesCount = mKeepUninstalledPackages.size(); 23200 for (int i = 0; i < packagesCount; i++) { 23201 String oldPackage = mKeepUninstalledPackages.get(i); 23202 if (packageList != null && packageList.contains(oldPackage)) { 23203 continue; 23204 } 23205 if (removedFromList == null) { 23206 removedFromList = new ArrayList<>(); 23207 } 23208 removedFromList.add(oldPackage); 23209 } 23210 } 23211 mKeepUninstalledPackages = new ArrayList<>(packageList); 23212 if (removedFromList != null) { 23213 final int removedCount = removedFromList.size(); 23214 for (int i = 0; i < removedCount; i++) { 23215 deletePackageIfUnusedLPr(removedFromList.get(i)); 23216 } 23217 } 23218 } 23219 } 23220 23221 @Override 23222 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23223 synchronized (mPackages) { 23224 return mPermissionManager.isPermissionsReviewRequired( 23225 mPackages.get(packageName), userId); 23226 } 23227 } 23228 23229 @Override 23230 public PackageInfo getPackageInfo( 23231 String packageName, int flags, int filterCallingUid, int userId) { 23232 return PackageManagerService.this 23233 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23234 flags, filterCallingUid, userId); 23235 } 23236 23237 @Override 23238 public int getPackageUid(String packageName, int flags, int userId) { 23239 return PackageManagerService.this 23240 .getPackageUid(packageName, flags, userId); 23241 } 23242 23243 @Override 23244 public ApplicationInfo getApplicationInfo( 23245 String packageName, int flags, int filterCallingUid, int userId) { 23246 return PackageManagerService.this 23247 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23248 } 23249 23250 @Override 23251 public ActivityInfo getActivityInfo( 23252 ComponentName component, int flags, int filterCallingUid, int userId) { 23253 return PackageManagerService.this 23254 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23255 } 23256 23257 @Override 23258 public List<ResolveInfo> queryIntentActivities( 23259 Intent intent, int flags, int filterCallingUid, int userId) { 23260 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23261 return PackageManagerService.this 23262 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23263 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23264 } 23265 23266 @Override 23267 public List<ResolveInfo> queryIntentServices( 23268 Intent intent, int flags, int callingUid, int userId) { 23269 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23270 return PackageManagerService.this 23271 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23272 false); 23273 } 23274 23275 @Override 23276 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23277 int userId) { 23278 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23279 } 23280 23281 @Override 23282 public void setDeviceAndProfileOwnerPackages( 23283 int deviceOwnerUserId, String deviceOwnerPackage, 23284 SparseArray<String> profileOwnerPackages) { 23285 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23286 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23287 } 23288 23289 @Override 23290 public boolean isPackageDataProtected(int userId, String packageName) { 23291 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23292 } 23293 23294 @Override 23295 public boolean isPackageEphemeral(int userId, String packageName) { 23296 synchronized (mPackages) { 23297 final PackageSetting ps = mSettings.mPackages.get(packageName); 23298 return ps != null ? ps.getInstantApp(userId) : false; 23299 } 23300 } 23301 23302 @Override 23303 public boolean wasPackageEverLaunched(String packageName, int userId) { 23304 synchronized (mPackages) { 23305 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23306 } 23307 } 23308 23309 @Override 23310 public void grantRuntimePermission(String packageName, String permName, int userId, 23311 boolean overridePolicy) { 23312 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23313 permName, packageName, overridePolicy, getCallingUid(), userId, 23314 mPermissionCallback); 23315 } 23316 23317 @Override 23318 public void revokeRuntimePermission(String packageName, String permName, int userId, 23319 boolean overridePolicy) { 23320 mPermissionManager.revokeRuntimePermission( 23321 permName, packageName, overridePolicy, getCallingUid(), userId, 23322 mPermissionCallback); 23323 } 23324 23325 @Override 23326 public String getNameForUid(int uid) { 23327 return PackageManagerService.this.getNameForUid(uid); 23328 } 23329 23330 @Override 23331 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23332 Intent origIntent, String resolvedType, String callingPackage, 23333 Bundle verificationBundle, int userId) { 23334 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23335 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23336 userId); 23337 } 23338 23339 @Override 23340 public void grantEphemeralAccess(int userId, Intent intent, 23341 int targetAppId, int ephemeralAppId) { 23342 synchronized (mPackages) { 23343 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23344 targetAppId, ephemeralAppId); 23345 } 23346 } 23347 23348 @Override 23349 public boolean isInstantAppInstallerComponent(ComponentName component) { 23350 synchronized (mPackages) { 23351 return mInstantAppInstallerActivity != null 23352 && mInstantAppInstallerActivity.getComponentName().equals(component); 23353 } 23354 } 23355 23356 @Override 23357 public void pruneInstantApps() { 23358 mInstantAppRegistry.pruneInstantApps(); 23359 } 23360 23361 @Override 23362 public String getSetupWizardPackageName() { 23363 return mSetupWizardPackage; 23364 } 23365 23366 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23367 if (policy != null) { 23368 mExternalSourcesPolicy = policy; 23369 } 23370 } 23371 23372 @Override 23373 public boolean isPackagePersistent(String packageName) { 23374 synchronized (mPackages) { 23375 PackageParser.Package pkg = mPackages.get(packageName); 23376 return pkg != null 23377 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23378 | ApplicationInfo.FLAG_PERSISTENT)) == 23379 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23380 : false; 23381 } 23382 } 23383 23384 @Override 23385 public boolean isLegacySystemApp(Package pkg) { 23386 synchronized (mPackages) { 23387 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23388 return mPromoteSystemApps 23389 && ps.isSystem() 23390 && mExistingSystemPackages.contains(ps.name); 23391 } 23392 } 23393 23394 @Override 23395 public List<PackageInfo> getOverlayPackages(int userId) { 23396 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23397 synchronized (mPackages) { 23398 for (PackageParser.Package p : mPackages.values()) { 23399 if (p.mOverlayTarget != null) { 23400 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23401 if (pkg != null) { 23402 overlayPackages.add(pkg); 23403 } 23404 } 23405 } 23406 } 23407 return overlayPackages; 23408 } 23409 23410 @Override 23411 public List<String> getTargetPackageNames(int userId) { 23412 List<String> targetPackages = new ArrayList<>(); 23413 synchronized (mPackages) { 23414 for (PackageParser.Package p : mPackages.values()) { 23415 if (p.mOverlayTarget == null) { 23416 targetPackages.add(p.packageName); 23417 } 23418 } 23419 } 23420 return targetPackages; 23421 } 23422 23423 @Override 23424 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23425 @Nullable List<String> overlayPackageNames) { 23426 synchronized (mPackages) { 23427 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23428 Slog.e(TAG, "failed to find package " + targetPackageName); 23429 return false; 23430 } 23431 ArrayList<String> overlayPaths = null; 23432 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23433 final int N = overlayPackageNames.size(); 23434 overlayPaths = new ArrayList<>(N); 23435 for (int i = 0; i < N; i++) { 23436 final String packageName = overlayPackageNames.get(i); 23437 final PackageParser.Package pkg = mPackages.get(packageName); 23438 if (pkg == null) { 23439 Slog.e(TAG, "failed to find package " + packageName); 23440 return false; 23441 } 23442 overlayPaths.add(pkg.baseCodePath); 23443 } 23444 } 23445 23446 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23447 ps.setOverlayPaths(overlayPaths, userId); 23448 return true; 23449 } 23450 } 23451 23452 @Override 23453 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23454 int flags, int userId, boolean resolveForStart) { 23455 return resolveIntentInternal( 23456 intent, resolvedType, flags, userId, resolveForStart); 23457 } 23458 23459 @Override 23460 public ResolveInfo resolveService(Intent intent, String resolvedType, 23461 int flags, int userId, int callingUid) { 23462 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23463 } 23464 23465 @Override 23466 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23467 return PackageManagerService.this.resolveContentProviderInternal( 23468 name, flags, userId); 23469 } 23470 23471 @Override 23472 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23473 synchronized (mPackages) { 23474 mIsolatedOwners.put(isolatedUid, ownerUid); 23475 } 23476 } 23477 23478 @Override 23479 public void removeIsolatedUid(int isolatedUid) { 23480 synchronized (mPackages) { 23481 mIsolatedOwners.delete(isolatedUid); 23482 } 23483 } 23484 23485 @Override 23486 public int getUidTargetSdkVersion(int uid) { 23487 synchronized (mPackages) { 23488 return getUidTargetSdkVersionLockedLPr(uid); 23489 } 23490 } 23491 23492 @Override 23493 public int getPackageTargetSdkVersion(String packageName) { 23494 synchronized (mPackages) { 23495 return getPackageTargetSdkVersionLockedLPr(packageName); 23496 } 23497 } 23498 23499 @Override 23500 public boolean canAccessInstantApps(int callingUid, int userId) { 23501 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23502 } 23503 23504 @Override 23505 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23506 synchronized (mPackages) { 23507 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23508 } 23509 } 23510 23511 @Override 23512 public void notifyPackageUse(String packageName, int reason) { 23513 synchronized (mPackages) { 23514 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23515 } 23516 } 23517 } 23518 23519 @Override 23520 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23521 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23522 synchronized (mPackages) { 23523 final long identity = Binder.clearCallingIdentity(); 23524 try { 23525 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23526 packageNames, userId); 23527 } finally { 23528 Binder.restoreCallingIdentity(identity); 23529 } 23530 } 23531 } 23532 23533 @Override 23534 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23535 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23536 synchronized (mPackages) { 23537 final long identity = Binder.clearCallingIdentity(); 23538 try { 23539 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23540 packageNames, userId); 23541 } finally { 23542 Binder.restoreCallingIdentity(identity); 23543 } 23544 } 23545 } 23546 23547 private static void enforceSystemOrPhoneCaller(String tag) { 23548 int callingUid = Binder.getCallingUid(); 23549 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23550 throw new SecurityException( 23551 "Cannot call " + tag + " from UID " + callingUid); 23552 } 23553 } 23554 23555 boolean isHistoricalPackageUsageAvailable() { 23556 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23557 } 23558 23559 /** 23560 * Return a <b>copy</b> of the collection of packages known to the package manager. 23561 * @return A copy of the values of mPackages. 23562 */ 23563 Collection<PackageParser.Package> getPackages() { 23564 synchronized (mPackages) { 23565 return new ArrayList<>(mPackages.values()); 23566 } 23567 } 23568 23569 /** 23570 * Logs process start information (including base APK hash) to the security log. 23571 * @hide 23572 */ 23573 @Override 23574 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23575 String apkFile, int pid) { 23576 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23577 return; 23578 } 23579 if (!SecurityLog.isLoggingEnabled()) { 23580 return; 23581 } 23582 Bundle data = new Bundle(); 23583 data.putLong("startTimestamp", System.currentTimeMillis()); 23584 data.putString("processName", processName); 23585 data.putInt("uid", uid); 23586 data.putString("seinfo", seinfo); 23587 data.putString("apkFile", apkFile); 23588 data.putInt("pid", pid); 23589 Message msg = mProcessLoggingHandler.obtainMessage( 23590 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23591 msg.setData(data); 23592 mProcessLoggingHandler.sendMessage(msg); 23593 } 23594 23595 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23596 return mCompilerStats.getPackageStats(pkgName); 23597 } 23598 23599 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23600 return getOrCreateCompilerPackageStats(pkg.packageName); 23601 } 23602 23603 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23604 return mCompilerStats.getOrCreatePackageStats(pkgName); 23605 } 23606 23607 public void deleteCompilerPackageStats(String pkgName) { 23608 mCompilerStats.deletePackageStats(pkgName); 23609 } 23610 23611 @Override 23612 public int getInstallReason(String packageName, int userId) { 23613 final int callingUid = Binder.getCallingUid(); 23614 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23615 true /* requireFullPermission */, false /* checkShell */, 23616 "get install reason"); 23617 synchronized (mPackages) { 23618 final PackageSetting ps = mSettings.mPackages.get(packageName); 23619 if (filterAppAccessLPr(ps, callingUid, userId)) { 23620 return PackageManager.INSTALL_REASON_UNKNOWN; 23621 } 23622 if (ps != null) { 23623 return ps.getInstallReason(userId); 23624 } 23625 } 23626 return PackageManager.INSTALL_REASON_UNKNOWN; 23627 } 23628 23629 @Override 23630 public boolean canRequestPackageInstalls(String packageName, int userId) { 23631 return canRequestPackageInstallsInternal(packageName, 0, userId, 23632 true /* throwIfPermNotDeclared*/); 23633 } 23634 23635 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23636 boolean throwIfPermNotDeclared) { 23637 int callingUid = Binder.getCallingUid(); 23638 int uid = getPackageUid(packageName, 0, userId); 23639 if (callingUid != uid && callingUid != Process.ROOT_UID 23640 && callingUid != Process.SYSTEM_UID) { 23641 throw new SecurityException( 23642 "Caller uid " + callingUid + " does not own package " + packageName); 23643 } 23644 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23645 if (info == null) { 23646 return false; 23647 } 23648 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23649 return false; 23650 } 23651 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23652 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23653 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23654 if (throwIfPermNotDeclared) { 23655 throw new SecurityException("Need to declare " + appOpPermission 23656 + " to call this api"); 23657 } else { 23658 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23659 return false; 23660 } 23661 } 23662 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23663 return false; 23664 } 23665 if (mExternalSourcesPolicy != null) { 23666 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23667 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23668 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23669 } 23670 } 23671 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23672 } 23673 23674 @Override 23675 public ComponentName getInstantAppResolverSettingsComponent() { 23676 return mInstantAppResolverSettingsComponent; 23677 } 23678 23679 @Override 23680 public ComponentName getInstantAppInstallerComponent() { 23681 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23682 return null; 23683 } 23684 return mInstantAppInstallerActivity == null 23685 ? null : mInstantAppInstallerActivity.getComponentName(); 23686 } 23687 23688 @Override 23689 public String getInstantAppAndroidId(String packageName, int userId) { 23690 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23691 "getInstantAppAndroidId"); 23692 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23693 true /* requireFullPermission */, false /* checkShell */, 23694 "getInstantAppAndroidId"); 23695 // Make sure the target is an Instant App. 23696 if (!isInstantApp(packageName, userId)) { 23697 return null; 23698 } 23699 synchronized (mPackages) { 23700 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23701 } 23702 } 23703 23704 boolean canHaveOatDir(String packageName) { 23705 synchronized (mPackages) { 23706 PackageParser.Package p = mPackages.get(packageName); 23707 if (p == null) { 23708 return false; 23709 } 23710 return p.canHaveOatDir(); 23711 } 23712 } 23713 23714 private String getOatDir(PackageParser.Package pkg) { 23715 if (!pkg.canHaveOatDir()) { 23716 return null; 23717 } 23718 File codePath = new File(pkg.codePath); 23719 if (codePath.isDirectory()) { 23720 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23721 } 23722 return null; 23723 } 23724 23725 void deleteOatArtifactsOfPackage(String packageName) { 23726 final String[] instructionSets; 23727 final List<String> codePaths; 23728 final String oatDir; 23729 final PackageParser.Package pkg; 23730 synchronized (mPackages) { 23731 pkg = mPackages.get(packageName); 23732 } 23733 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23734 codePaths = pkg.getAllCodePaths(); 23735 oatDir = getOatDir(pkg); 23736 23737 for (String codePath : codePaths) { 23738 for (String isa : instructionSets) { 23739 try { 23740 mInstaller.deleteOdex(codePath, isa, oatDir); 23741 } catch (InstallerException e) { 23742 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23743 } 23744 } 23745 } 23746 } 23747 23748 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23749 Set<String> unusedPackages = new HashSet<>(); 23750 long currentTimeInMillis = System.currentTimeMillis(); 23751 synchronized (mPackages) { 23752 for (PackageParser.Package pkg : mPackages.values()) { 23753 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23754 if (ps == null) { 23755 continue; 23756 } 23757 PackageDexUsage.PackageUseInfo packageUseInfo = 23758 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23759 if (PackageManagerServiceUtils 23760 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23761 downgradeTimeThresholdMillis, packageUseInfo, 23762 pkg.getLatestPackageUseTimeInMills(), 23763 pkg.getLatestForegroundPackageUseTimeInMills())) { 23764 unusedPackages.add(pkg.packageName); 23765 } 23766 } 23767 } 23768 return unusedPackages; 23769 } 23770 23771 @Override 23772 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 23773 int userId) { 23774 final int callingUid = Binder.getCallingUid(); 23775 final int callingAppId = UserHandle.getAppId(callingUid); 23776 23777 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23778 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 23779 23780 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23781 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23782 throw new SecurityException("Caller must have the " 23783 + SET_HARMFUL_APP_WARNINGS + " permission."); 23784 } 23785 23786 synchronized(mPackages) { 23787 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 23788 scheduleWritePackageRestrictionsLocked(userId); 23789 } 23790 } 23791 23792 @Nullable 23793 @Override 23794 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 23795 final int callingUid = Binder.getCallingUid(); 23796 final int callingAppId = UserHandle.getAppId(callingUid); 23797 23798 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23799 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 23800 23801 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23802 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23803 throw new SecurityException("Caller must have the " 23804 + SET_HARMFUL_APP_WARNINGS + " permission."); 23805 } 23806 23807 synchronized(mPackages) { 23808 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 23809 } 23810 } 23811} 23812 23813interface PackageSender { 23814 /** 23815 * @param userIds User IDs where the action occurred on a full application 23816 * @param instantUserIds User IDs where the action occurred on an instant application 23817 */ 23818 void sendPackageBroadcast(final String action, final String pkg, 23819 final Bundle extras, final int flags, final String targetPkg, 23820 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 23821 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23822 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 23823 void notifyPackageAdded(String packageName); 23824 void notifyPackageRemoved(String packageName); 23825} 23826