PackageManagerService.java revision cccad1971e4f04db7c8db8b0a9d6afd95937fc5e
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 26import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 115 116import android.Manifest; 117import android.annotation.IntDef; 118import android.annotation.NonNull; 119import android.annotation.Nullable; 120import android.app.ActivityManager; 121import android.app.ActivityManagerInternal; 122import android.app.AppOpsManager; 123import android.app.IActivityManager; 124import android.app.ResourcesManager; 125import android.app.admin.IDevicePolicyManager; 126import android.app.admin.SecurityLog; 127import android.app.backup.IBackupManager; 128import android.content.BroadcastReceiver; 129import android.content.ComponentName; 130import android.content.ContentResolver; 131import android.content.Context; 132import android.content.IIntentReceiver; 133import android.content.Intent; 134import android.content.IntentFilter; 135import android.content.IntentSender; 136import android.content.IntentSender.SendIntentException; 137import android.content.ServiceConnection; 138import android.content.pm.ActivityInfo; 139import android.content.pm.ApplicationInfo; 140import android.content.pm.AppsQueryHelper; 141import android.content.pm.AuxiliaryResolveInfo; 142import android.content.pm.ChangedPackages; 143import android.content.pm.ComponentInfo; 144import android.content.pm.FallbackCategoryProvider; 145import android.content.pm.FeatureInfo; 146import android.content.pm.IDexModuleRegisterCallback; 147import android.content.pm.IOnPermissionsChangeListener; 148import android.content.pm.IPackageDataObserver; 149import android.content.pm.IPackageDeleteObserver; 150import android.content.pm.IPackageDeleteObserver2; 151import android.content.pm.IPackageInstallObserver2; 152import android.content.pm.IPackageInstaller; 153import android.content.pm.IPackageManager; 154import android.content.pm.IPackageManagerNative; 155import android.content.pm.IPackageMoveObserver; 156import android.content.pm.IPackageStatsObserver; 157import android.content.pm.InstantAppInfo; 158import android.content.pm.InstantAppRequest; 159import android.content.pm.InstantAppResolveInfo; 160import android.content.pm.InstrumentationInfo; 161import android.content.pm.IntentFilterVerificationInfo; 162import android.content.pm.KeySet; 163import android.content.pm.PackageCleanItem; 164import android.content.pm.PackageInfo; 165import android.content.pm.PackageInfoLite; 166import android.content.pm.PackageInstaller; 167import android.content.pm.PackageList; 168import android.content.pm.PackageManager; 169import android.content.pm.PackageManagerInternal; 170import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 171import android.content.pm.PackageManagerInternal.PackageListObserver; 172import android.content.pm.PackageParser; 173import android.content.pm.PackageParser.ActivityIntentInfo; 174import android.content.pm.PackageParser.Package; 175import android.content.pm.PackageParser.PackageLite; 176import android.content.pm.PackageParser.PackageParserException; 177import android.content.pm.PackageParser.ParseFlags; 178import android.content.pm.PackageParser.ServiceIntentInfo; 179import android.content.pm.PackageParser.SigningDetails; 180import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 181import android.content.pm.PackageStats; 182import android.content.pm.PackageUserState; 183import android.content.pm.ParceledListSlice; 184import android.content.pm.PermissionGroupInfo; 185import android.content.pm.PermissionInfo; 186import android.content.pm.ProviderInfo; 187import android.content.pm.ResolveInfo; 188import android.content.pm.ServiceInfo; 189import android.content.pm.SharedLibraryInfo; 190import android.content.pm.Signature; 191import android.content.pm.UserInfo; 192import android.content.pm.VerifierDeviceIdentity; 193import android.content.pm.VerifierInfo; 194import android.content.pm.VersionedPackage; 195import android.content.pm.dex.ArtManager; 196import android.content.pm.dex.DexMetadataHelper; 197import android.content.pm.dex.IArtManager; 198import android.content.res.Resources; 199import android.database.ContentObserver; 200import android.graphics.Bitmap; 201import android.hardware.display.DisplayManager; 202import android.net.Uri; 203import android.os.Binder; 204import android.os.Build; 205import android.os.Bundle; 206import android.os.Debug; 207import android.os.Environment; 208import android.os.Environment.UserEnvironment; 209import android.os.FileUtils; 210import android.os.Handler; 211import android.os.IBinder; 212import android.os.Looper; 213import android.os.Message; 214import android.os.Parcel; 215import android.os.ParcelFileDescriptor; 216import android.os.PatternMatcher; 217import android.os.Process; 218import android.os.RemoteCallbackList; 219import android.os.RemoteException; 220import android.os.ResultReceiver; 221import android.os.SELinux; 222import android.os.ServiceManager; 223import android.os.ShellCallback; 224import android.os.SystemClock; 225import android.os.SystemProperties; 226import android.os.Trace; 227import android.os.UserHandle; 228import android.os.UserManager; 229import android.os.UserManagerInternal; 230import android.os.storage.IStorageManager; 231import android.os.storage.StorageEventListener; 232import android.os.storage.StorageManager; 233import android.os.storage.StorageManagerInternal; 234import android.os.storage.VolumeInfo; 235import android.os.storage.VolumeRecord; 236import android.provider.Settings.Global; 237import android.provider.Settings.Secure; 238import android.security.KeyStore; 239import android.security.SystemKeyStore; 240import android.service.pm.PackageServiceDumpProto; 241import android.service.textclassifier.TextClassifierService; 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.ByteStringUtils; 250import android.util.DisplayMetrics; 251import android.util.EventLog; 252import android.util.ExceptionUtils; 253import android.util.Log; 254import android.util.LogPrinter; 255import android.util.LongSparseArray; 256import android.util.LongSparseLongArray; 257import android.util.MathUtils; 258import android.util.PackageUtils; 259import android.util.Pair; 260import android.util.PrintStreamPrinter; 261import android.util.Slog; 262import android.util.SparseArray; 263import android.util.SparseBooleanArray; 264import android.util.SparseIntArray; 265import android.util.TimingsTraceLog; 266import android.util.Xml; 267import android.util.jar.StrictJarFile; 268import android.util.proto.ProtoOutputStream; 269import android.view.Display; 270 271import com.android.internal.R; 272import com.android.internal.annotations.GuardedBy; 273import com.android.internal.app.IMediaContainerService; 274import com.android.internal.app.ResolverActivity; 275import com.android.internal.content.NativeLibraryHelper; 276import com.android.internal.content.PackageHelper; 277import com.android.internal.logging.MetricsLogger; 278import com.android.internal.os.IParcelFileDescriptorFactory; 279import com.android.internal.os.SomeArgs; 280import com.android.internal.os.Zygote; 281import com.android.internal.telephony.CarrierAppUtils; 282import com.android.internal.util.ArrayUtils; 283import com.android.internal.util.ConcurrentUtils; 284import com.android.internal.util.DumpUtils; 285import com.android.internal.util.FastXmlSerializer; 286import com.android.internal.util.IndentingPrintWriter; 287import com.android.internal.util.Preconditions; 288import com.android.internal.util.XmlUtils; 289import com.android.server.AttributeCache; 290import com.android.server.DeviceIdleController; 291import com.android.server.EventLogTags; 292import com.android.server.FgThread; 293import com.android.server.IntentResolver; 294import com.android.server.LocalServices; 295import com.android.server.LockGuard; 296import com.android.server.ServiceThread; 297import com.android.server.SystemConfig; 298import com.android.server.SystemServerInitThreadPool; 299import com.android.server.Watchdog; 300import com.android.server.net.NetworkPolicyManagerInternal; 301import com.android.server.pm.Installer.InstallerException; 302import com.android.server.pm.Settings.DatabaseVersion; 303import com.android.server.pm.Settings.VersionInfo; 304import com.android.server.pm.dex.ArtManagerService; 305import com.android.server.pm.dex.DexLogger; 306import com.android.server.pm.dex.DexManager; 307import com.android.server.pm.dex.DexoptOptions; 308import com.android.server.pm.dex.PackageDexUsage; 309import com.android.server.pm.permission.BasePermission; 310import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 311import com.android.server.pm.permission.PermissionManagerService; 312import com.android.server.pm.permission.PermissionManagerInternal; 313import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 314import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 315import com.android.server.pm.permission.PermissionsState; 316import com.android.server.pm.permission.PermissionsState.PermissionState; 317import com.android.server.security.VerityUtils; 318import com.android.server.storage.DeviceStorageMonitorInternal; 319 320import dalvik.system.CloseGuard; 321import dalvik.system.VMRuntime; 322 323import libcore.io.IoUtils; 324 325import org.xmlpull.v1.XmlPullParser; 326import org.xmlpull.v1.XmlPullParserException; 327import org.xmlpull.v1.XmlSerializer; 328 329import java.io.BufferedOutputStream; 330import java.io.ByteArrayInputStream; 331import java.io.ByteArrayOutputStream; 332import java.io.File; 333import java.io.FileDescriptor; 334import java.io.FileInputStream; 335import java.io.FileOutputStream; 336import java.io.FilenameFilter; 337import java.io.IOException; 338import java.io.PrintWriter; 339import java.lang.annotation.Retention; 340import java.lang.annotation.RetentionPolicy; 341import java.nio.charset.StandardCharsets; 342import java.security.DigestException; 343import java.security.DigestInputStream; 344import java.security.MessageDigest; 345import java.security.NoSuchAlgorithmException; 346import java.security.PublicKey; 347import java.security.SecureRandom; 348import java.security.cert.CertificateException; 349import java.util.ArrayList; 350import java.util.Arrays; 351import java.util.Collection; 352import java.util.Collections; 353import java.util.Comparator; 354import java.util.HashMap; 355import java.util.HashSet; 356import java.util.Iterator; 357import java.util.LinkedHashSet; 358import java.util.List; 359import java.util.Map; 360import java.util.Objects; 361import java.util.Set; 362import java.util.concurrent.CountDownLatch; 363import java.util.concurrent.Future; 364import java.util.concurrent.TimeUnit; 365import java.util.concurrent.atomic.AtomicBoolean; 366import java.util.concurrent.atomic.AtomicInteger; 367 368/** 369 * Keep track of all those APKs everywhere. 370 * <p> 371 * Internally there are two important locks: 372 * <ul> 373 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 374 * and other related state. It is a fine-grained lock that should only be held 375 * momentarily, as it's one of the most contended locks in the system. 376 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 377 * operations typically involve heavy lifting of application data on disk. Since 378 * {@code installd} is single-threaded, and it's operations can often be slow, 379 * this lock should never be acquired while already holding {@link #mPackages}. 380 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 381 * holding {@link #mInstallLock}. 382 * </ul> 383 * Many internal methods rely on the caller to hold the appropriate locks, and 384 * this contract is expressed through method name suffixes: 385 * <ul> 386 * <li>fooLI(): the caller must hold {@link #mInstallLock} 387 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 388 * being modified must be frozen 389 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 390 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 391 * </ul> 392 * <p> 393 * Because this class is very central to the platform's security; please run all 394 * CTS and unit tests whenever making modifications: 395 * 396 * <pre> 397 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 398 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 399 * </pre> 400 */ 401public class PackageManagerService extends IPackageManager.Stub 402 implements PackageSender { 403 static final String TAG = "PackageManager"; 404 public static final boolean DEBUG_SETTINGS = false; 405 static final boolean DEBUG_PREFERRED = false; 406 static final boolean DEBUG_UPGRADE = false; 407 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 408 private static final boolean DEBUG_BACKUP = false; 409 public static final boolean DEBUG_INSTALL = false; 410 public static final boolean DEBUG_REMOVE = false; 411 private static final boolean DEBUG_BROADCASTS = false; 412 private static final boolean DEBUG_SHOW_INFO = false; 413 private static final boolean DEBUG_PACKAGE_INFO = false; 414 private static final boolean DEBUG_INTENT_MATCHING = false; 415 public static final boolean DEBUG_PACKAGE_SCANNING = false; 416 private static final boolean DEBUG_VERIFY = false; 417 private static final boolean DEBUG_FILTERS = false; 418 public static final boolean DEBUG_PERMISSIONS = false; 419 private static final boolean DEBUG_SHARED_LIBRARIES = false; 420 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 421 422 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 423 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 424 // user, but by default initialize to this. 425 public static final boolean DEBUG_DEXOPT = false; 426 427 private static final boolean DEBUG_ABI_SELECTION = false; 428 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 429 private static final boolean DEBUG_TRIAGED_MISSING = false; 430 private static final boolean DEBUG_APP_DATA = false; 431 432 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 433 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 434 435 private static final boolean HIDE_EPHEMERAL_APIS = false; 436 437 private static final boolean ENABLE_FREE_CACHE_V2 = 438 SystemProperties.getBoolean("fw.free_cache_v2", true); 439 440 private static final int RADIO_UID = Process.PHONE_UID; 441 private static final int LOG_UID = Process.LOG_UID; 442 private static final int NFC_UID = Process.NFC_UID; 443 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 444 private static final int SHELL_UID = Process.SHELL_UID; 445 private static final int SE_UID = Process.SE_UID; 446 447 // Suffix used during package installation when copying/moving 448 // package apks to install directory. 449 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 450 451 static final int SCAN_NO_DEX = 1<<0; 452 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 453 static final int SCAN_NEW_INSTALL = 1<<2; 454 static final int SCAN_UPDATE_TIME = 1<<3; 455 static final int SCAN_BOOTING = 1<<4; 456 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 457 static final int SCAN_REQUIRE_KNOWN = 1<<7; 458 static final int SCAN_MOVE = 1<<8; 459 static final int SCAN_INITIAL = 1<<9; 460 static final int SCAN_CHECK_ONLY = 1<<10; 461 static final int SCAN_DONT_KILL_APP = 1<<11; 462 static final int SCAN_IGNORE_FROZEN = 1<<12; 463 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 464 static final int SCAN_AS_INSTANT_APP = 1<<14; 465 static final int SCAN_AS_FULL_APP = 1<<15; 466 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 467 static final int SCAN_AS_SYSTEM = 1<<17; 468 static final int SCAN_AS_PRIVILEGED = 1<<18; 469 static final int SCAN_AS_OEM = 1<<19; 470 static final int SCAN_AS_VENDOR = 1<<20; 471 static final int SCAN_AS_PRODUCT = 1<<21; 472 473 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 474 SCAN_NO_DEX, 475 SCAN_UPDATE_SIGNATURE, 476 SCAN_NEW_INSTALL, 477 SCAN_UPDATE_TIME, 478 SCAN_BOOTING, 479 SCAN_DELETE_DATA_ON_FAILURES, 480 SCAN_REQUIRE_KNOWN, 481 SCAN_MOVE, 482 SCAN_INITIAL, 483 SCAN_CHECK_ONLY, 484 SCAN_DONT_KILL_APP, 485 SCAN_IGNORE_FROZEN, 486 SCAN_FIRST_BOOT_OR_UPGRADE, 487 SCAN_AS_INSTANT_APP, 488 SCAN_AS_FULL_APP, 489 SCAN_AS_VIRTUAL_PRELOAD, 490 }) 491 @Retention(RetentionPolicy.SOURCE) 492 public @interface ScanFlags {} 493 494 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 495 /** Extension of the compressed packages */ 496 public final static String COMPRESSED_EXTENSION = ".gz"; 497 /** Suffix of stub packages on the system partition */ 498 public final static String STUB_SUFFIX = "-Stub"; 499 500 private static final int[] EMPTY_INT_ARRAY = new int[0]; 501 502 private static final int TYPE_UNKNOWN = 0; 503 private static final int TYPE_ACTIVITY = 1; 504 private static final int TYPE_RECEIVER = 2; 505 private static final int TYPE_SERVICE = 3; 506 private static final int TYPE_PROVIDER = 4; 507 @IntDef(prefix = { "TYPE_" }, value = { 508 TYPE_UNKNOWN, 509 TYPE_ACTIVITY, 510 TYPE_RECEIVER, 511 TYPE_SERVICE, 512 TYPE_PROVIDER, 513 }) 514 @Retention(RetentionPolicy.SOURCE) 515 public @interface ComponentType {} 516 517 /** 518 * Timeout (in milliseconds) after which the watchdog should declare that 519 * our handler thread is wedged. The usual default for such things is one 520 * minute but we sometimes do very lengthy I/O operations on this thread, 521 * such as installing multi-gigabyte applications, so ours needs to be longer. 522 */ 523 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 524 525 /** 526 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 527 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 528 * settings entry if available, otherwise we use the hardcoded default. If it's been 529 * more than this long since the last fstrim, we force one during the boot sequence. 530 * 531 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 532 * one gets run at the next available charging+idle time. This final mandatory 533 * no-fstrim check kicks in only of the other scheduling criteria is never met. 534 */ 535 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 536 537 /** 538 * Whether verification is enabled by default. 539 */ 540 private static final boolean DEFAULT_VERIFY_ENABLE = true; 541 542 /** 543 * The default maximum time to wait for the verification agent to return in 544 * milliseconds. 545 */ 546 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 547 548 /** 549 * The default response for package verification timeout. 550 * 551 * This can be either PackageManager.VERIFICATION_ALLOW or 552 * PackageManager.VERIFICATION_REJECT. 553 */ 554 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 555 556 public static final String PLATFORM_PACKAGE_NAME = "android"; 557 558 public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 559 560 public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 561 DEFAULT_CONTAINER_PACKAGE, 562 "com.android.defcontainer.DefaultContainerService"); 563 564 private static final String KILL_APP_REASON_GIDS_CHANGED = 565 "permission grant or revoke changed gids"; 566 567 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 568 "permissions revoked"; 569 570 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 571 572 private static final String PACKAGE_SCHEME = "package"; 573 574 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 575 576 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 577 578 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 579 580 /** Canonical intent used to identify what counts as a "web browser" app */ 581 private static final Intent sBrowserIntent; 582 static { 583 sBrowserIntent = new Intent(); 584 sBrowserIntent.setAction(Intent.ACTION_VIEW); 585 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 586 sBrowserIntent.setData(Uri.parse("http:")); 587 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 588 } 589 590 /** 591 * The set of all protected actions [i.e. those actions for which a high priority 592 * intent filter is disallowed]. 593 */ 594 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 595 static { 596 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 597 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 598 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 599 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 600 } 601 602 // Compilation reasons. 603 public static final int REASON_UNKNOWN = -1; 604 public static final int REASON_FIRST_BOOT = 0; 605 public static final int REASON_BOOT = 1; 606 public static final int REASON_INSTALL = 2; 607 public static final int REASON_BACKGROUND_DEXOPT = 3; 608 public static final int REASON_AB_OTA = 4; 609 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 610 public static final int REASON_SHARED = 6; 611 612 public static final int REASON_LAST = REASON_SHARED; 613 614 /** 615 * Version number for the package parser cache. Increment this whenever the format or 616 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 617 */ 618 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 619 620 /** 621 * Whether the package parser cache is enabled. 622 */ 623 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 624 625 /** 626 * Permissions required in order to receive instant application lifecycle broadcasts. 627 */ 628 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 629 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 630 631 final ServiceThread mHandlerThread; 632 633 final PackageHandler mHandler; 634 635 private final ProcessLoggingHandler mProcessLoggingHandler; 636 637 /** 638 * Messages for {@link #mHandler} that need to wait for system ready before 639 * being dispatched. 640 */ 641 private ArrayList<Message> mPostSystemReadyMessages; 642 643 final int mSdkVersion = Build.VERSION.SDK_INT; 644 645 final Context mContext; 646 final boolean mFactoryTest; 647 final boolean mOnlyCore; 648 final DisplayMetrics mMetrics; 649 final int mDefParseFlags; 650 final String[] mSeparateProcesses; 651 final boolean mIsUpgrade; 652 final boolean mIsPreNUpgrade; 653 final boolean mIsPreNMR1Upgrade; 654 655 // Have we told the Activity Manager to whitelist the default container service by uid yet? 656 @GuardedBy("mPackages") 657 boolean mDefaultContainerWhitelisted = false; 658 659 @GuardedBy("mPackages") 660 private boolean mDexOptDialogShown; 661 662 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 663 // LOCK HELD. Can be called with mInstallLock held. 664 @GuardedBy("mInstallLock") 665 final Installer mInstaller; 666 667 /** Directory where installed applications are stored */ 668 private static final File sAppInstallDir = 669 new File(Environment.getDataDirectory(), "app"); 670 /** Directory where installed application's 32-bit native libraries are copied. */ 671 private static final File sAppLib32InstallDir = 672 new File(Environment.getDataDirectory(), "app-lib"); 673 /** Directory where code and non-resource assets of forward-locked applications are stored */ 674 private static final File sDrmAppPrivateInstallDir = 675 new File(Environment.getDataDirectory(), "app-private"); 676 677 // ---------------------------------------------------------------- 678 679 // Lock for state used when installing and doing other long running 680 // operations. Methods that must be called with this lock held have 681 // the suffix "LI". 682 final Object mInstallLock = new Object(); 683 684 // ---------------------------------------------------------------- 685 686 // Keys are String (package name), values are Package. This also serves 687 // as the lock for the global state. Methods that must be called with 688 // this lock held have the prefix "LP". 689 @GuardedBy("mPackages") 690 final ArrayMap<String, PackageParser.Package> mPackages = 691 new ArrayMap<String, PackageParser.Package>(); 692 693 final ArrayMap<String, Set<String>> mKnownCodebase = 694 new ArrayMap<String, Set<String>>(); 695 696 // Keys are isolated uids and values are the uid of the application 697 // that created the isolated proccess. 698 @GuardedBy("mPackages") 699 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 700 701 /** 702 * Tracks new system packages [received in an OTA] that we expect to 703 * find updated user-installed versions. Keys are package name, values 704 * are package location. 705 */ 706 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 707 /** 708 * Tracks high priority intent filters for protected actions. During boot, certain 709 * filter actions are protected and should never be allowed to have a high priority 710 * intent filter for them. However, there is one, and only one exception -- the 711 * setup wizard. It must be able to define a high priority intent filter for these 712 * actions to ensure there are no escapes from the wizard. We need to delay processing 713 * of these during boot as we need to look at all of the system packages in order 714 * to know which component is the setup wizard. 715 */ 716 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 717 /** 718 * Whether or not processing protected filters should be deferred. 719 */ 720 private boolean mDeferProtectedFilters = true; 721 722 /** 723 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 724 */ 725 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 726 /** 727 * Whether or not system app permissions should be promoted from install to runtime. 728 */ 729 boolean mPromoteSystemApps; 730 731 @GuardedBy("mPackages") 732 final Settings mSettings; 733 734 /** 735 * Set of package names that are currently "frozen", which means active 736 * surgery is being done on the code/data for that package. The platform 737 * will refuse to launch frozen packages to avoid race conditions. 738 * 739 * @see PackageFreezer 740 */ 741 @GuardedBy("mPackages") 742 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 743 744 final ProtectedPackages mProtectedPackages; 745 746 @GuardedBy("mLoadedVolumes") 747 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 748 749 boolean mFirstBoot; 750 751 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 752 753 @GuardedBy("mAvailableFeatures") 754 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 755 756 private final InstantAppRegistry mInstantAppRegistry; 757 758 @GuardedBy("mPackages") 759 int mChangedPackagesSequenceNumber; 760 /** 761 * List of changed [installed, removed or updated] packages. 762 * mapping from user id -> sequence number -> package name 763 */ 764 @GuardedBy("mPackages") 765 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 766 /** 767 * The sequence number of the last change to a package. 768 * mapping from user id -> package name -> sequence number 769 */ 770 @GuardedBy("mPackages") 771 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 772 773 @GuardedBy("mPackages") 774 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 775 776 class PackageParserCallback implements PackageParser.Callback { 777 @Override public final boolean hasFeature(String feature) { 778 return PackageManagerService.this.hasSystemFeature(feature, 0); 779 } 780 781 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 782 Collection<PackageParser.Package> allPackages, String targetPackageName) { 783 List<PackageParser.Package> overlayPackages = null; 784 for (PackageParser.Package p : allPackages) { 785 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 786 if (overlayPackages == null) { 787 overlayPackages = new ArrayList<PackageParser.Package>(); 788 } 789 overlayPackages.add(p); 790 } 791 } 792 if (overlayPackages != null) { 793 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 794 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 795 return p1.mOverlayPriority - p2.mOverlayPriority; 796 } 797 }; 798 Collections.sort(overlayPackages, cmp); 799 } 800 return overlayPackages; 801 } 802 803 @GuardedBy("mInstallLock") 804 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 805 String targetPackageName, String targetPath) { 806 if ("android".equals(targetPackageName)) { 807 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 808 // native AssetManager. 809 return null; 810 } 811 List<PackageParser.Package> overlayPackages = 812 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 813 if (overlayPackages == null || overlayPackages.isEmpty()) { 814 return null; 815 } 816 List<String> overlayPathList = null; 817 for (PackageParser.Package overlayPackage : overlayPackages) { 818 if (targetPath == null) { 819 if (overlayPathList == null) { 820 overlayPathList = new ArrayList<String>(); 821 } 822 overlayPathList.add(overlayPackage.baseCodePath); 823 continue; 824 } 825 826 try { 827 // Creates idmaps for system to parse correctly the Android manifest of the 828 // target package. 829 // 830 // OverlayManagerService will update each of them with a correct gid from its 831 // target package app id. 832 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 833 UserHandle.getSharedAppGid( 834 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 835 if (overlayPathList == null) { 836 overlayPathList = new ArrayList<String>(); 837 } 838 overlayPathList.add(overlayPackage.baseCodePath); 839 } catch (InstallerException e) { 840 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 841 overlayPackage.baseCodePath); 842 } 843 } 844 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 845 } 846 847 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 848 synchronized (mPackages) { 849 return getStaticOverlayPathsLocked( 850 mPackages.values(), targetPackageName, targetPath); 851 } 852 } 853 854 @Override public final String[] getOverlayApks(String targetPackageName) { 855 return getStaticOverlayPaths(targetPackageName, null); 856 } 857 858 @Override public final String[] getOverlayPaths(String targetPackageName, 859 String targetPath) { 860 return getStaticOverlayPaths(targetPackageName, targetPath); 861 } 862 } 863 864 class ParallelPackageParserCallback extends PackageParserCallback { 865 List<PackageParser.Package> mOverlayPackages = null; 866 867 void findStaticOverlayPackages() { 868 synchronized (mPackages) { 869 for (PackageParser.Package p : mPackages.values()) { 870 if (p.mOverlayIsStatic) { 871 if (mOverlayPackages == null) { 872 mOverlayPackages = new ArrayList<PackageParser.Package>(); 873 } 874 mOverlayPackages.add(p); 875 } 876 } 877 } 878 } 879 880 @Override 881 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 882 // We can trust mOverlayPackages without holding mPackages because package uninstall 883 // can't happen while running parallel parsing. 884 // Moreover holding mPackages on each parsing thread causes dead-lock. 885 return mOverlayPackages == null ? null : 886 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 887 } 888 } 889 890 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 891 final ParallelPackageParserCallback mParallelPackageParserCallback = 892 new ParallelPackageParserCallback(); 893 894 public static final class SharedLibraryEntry { 895 public final @Nullable String path; 896 public final @Nullable String apk; 897 public final @NonNull SharedLibraryInfo info; 898 899 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 900 String declaringPackageName, long declaringPackageVersionCode) { 901 path = _path; 902 apk = _apk; 903 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 904 declaringPackageName, declaringPackageVersionCode), null); 905 } 906 } 907 908 // Currently known shared libraries. 909 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 910 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 911 new ArrayMap<>(); 912 913 // All available activities, for your resolving pleasure. 914 final ActivityIntentResolver mActivities = 915 new ActivityIntentResolver(); 916 917 // All available receivers, for your resolving pleasure. 918 final ActivityIntentResolver mReceivers = 919 new ActivityIntentResolver(); 920 921 // All available services, for your resolving pleasure. 922 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 923 924 // All available providers, for your resolving pleasure. 925 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 926 927 // Mapping from provider base names (first directory in content URI codePath) 928 // to the provider information. 929 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 930 new ArrayMap<String, PackageParser.Provider>(); 931 932 // Mapping from instrumentation class names to info about them. 933 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 934 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 935 936 // Packages whose data we have transfered into another package, thus 937 // should no longer exist. 938 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 939 940 // Broadcast actions that are only available to the system. 941 @GuardedBy("mProtectedBroadcasts") 942 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 943 944 /** List of packages waiting for verification. */ 945 final SparseArray<PackageVerificationState> mPendingVerification 946 = new SparseArray<PackageVerificationState>(); 947 948 final PackageInstallerService mInstallerService; 949 950 final ArtManagerService mArtManagerService; 951 952 private final PackageDexOptimizer mPackageDexOptimizer; 953 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 954 // is used by other apps). 955 private final DexManager mDexManager; 956 957 private AtomicInteger mNextMoveId = new AtomicInteger(); 958 private final MoveCallbacks mMoveCallbacks; 959 960 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 961 962 // Cache of users who need badging. 963 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 964 965 /** Token for keys in mPendingVerification. */ 966 private int mPendingVerificationToken = 0; 967 968 volatile boolean mSystemReady; 969 volatile boolean mSafeMode; 970 volatile boolean mHasSystemUidErrors; 971 private volatile boolean mWebInstantAppsDisabled; 972 973 ApplicationInfo mAndroidApplication; 974 final ActivityInfo mResolveActivity = new ActivityInfo(); 975 final ResolveInfo mResolveInfo = new ResolveInfo(); 976 ComponentName mResolveComponentName; 977 PackageParser.Package mPlatformPackage; 978 ComponentName mCustomResolverComponentName; 979 980 boolean mResolverReplaced = false; 981 982 private final @Nullable ComponentName mIntentFilterVerifierComponent; 983 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 984 985 private int mIntentFilterVerificationToken = 0; 986 987 /** The service connection to the ephemeral resolver */ 988 final InstantAppResolverConnection mInstantAppResolverConnection; 989 /** Component used to show resolver settings for Instant Apps */ 990 final ComponentName mInstantAppResolverSettingsComponent; 991 992 /** Activity used to install instant applications */ 993 ActivityInfo mInstantAppInstallerActivity; 994 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 995 996 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 997 = new SparseArray<IntentFilterVerificationState>(); 998 999 // TODO remove this and go through mPermissonManager directly 1000 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1001 private final PermissionManagerInternal mPermissionManager; 1002 1003 // List of packages names to keep cached, even if they are uninstalled for all users 1004 private List<String> mKeepUninstalledPackages; 1005 1006 private UserManagerInternal mUserManagerInternal; 1007 private ActivityManagerInternal mActivityManagerInternal; 1008 1009 private DeviceIdleController.LocalService mDeviceIdleController; 1010 1011 private File mCacheDir; 1012 1013 private Future<?> mPrepareAppDataFuture; 1014 1015 private static class IFVerificationParams { 1016 PackageParser.Package pkg; 1017 boolean replacing; 1018 int userId; 1019 int verifierUid; 1020 1021 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1022 int _userId, int _verifierUid) { 1023 pkg = _pkg; 1024 replacing = _replacing; 1025 userId = _userId; 1026 replacing = _replacing; 1027 verifierUid = _verifierUid; 1028 } 1029 } 1030 1031 private interface IntentFilterVerifier<T extends IntentFilter> { 1032 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1033 T filter, String packageName); 1034 void startVerifications(int userId); 1035 void receiveVerificationResponse(int verificationId); 1036 } 1037 1038 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1039 private Context mContext; 1040 private ComponentName mIntentFilterVerifierComponent; 1041 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1042 1043 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1044 mContext = context; 1045 mIntentFilterVerifierComponent = verifierComponent; 1046 } 1047 1048 private String getDefaultScheme() { 1049 return IntentFilter.SCHEME_HTTPS; 1050 } 1051 1052 @Override 1053 public void startVerifications(int userId) { 1054 // Launch verifications requests 1055 int count = mCurrentIntentFilterVerifications.size(); 1056 for (int n=0; n<count; n++) { 1057 int verificationId = mCurrentIntentFilterVerifications.get(n); 1058 final IntentFilterVerificationState ivs = 1059 mIntentFilterVerificationStates.get(verificationId); 1060 1061 String packageName = ivs.getPackageName(); 1062 1063 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1064 final int filterCount = filters.size(); 1065 ArraySet<String> domainsSet = new ArraySet<>(); 1066 for (int m=0; m<filterCount; m++) { 1067 PackageParser.ActivityIntentInfo filter = filters.get(m); 1068 domainsSet.addAll(filter.getHostsList()); 1069 } 1070 synchronized (mPackages) { 1071 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1072 packageName, domainsSet) != null) { 1073 scheduleWriteSettingsLocked(); 1074 } 1075 } 1076 sendVerificationRequest(verificationId, ivs); 1077 } 1078 mCurrentIntentFilterVerifications.clear(); 1079 } 1080 1081 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1082 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1083 verificationIntent.putExtra( 1084 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1085 verificationId); 1086 verificationIntent.putExtra( 1087 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1088 getDefaultScheme()); 1089 verificationIntent.putExtra( 1090 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1091 ivs.getHostsString()); 1092 verificationIntent.putExtra( 1093 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1094 ivs.getPackageName()); 1095 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1096 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1097 1098 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1099 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1100 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1101 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1102 1103 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1104 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1105 "Sending IntentFilter verification broadcast"); 1106 } 1107 1108 public void receiveVerificationResponse(int verificationId) { 1109 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1110 1111 final boolean verified = ivs.isVerified(); 1112 1113 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1114 final int count = filters.size(); 1115 if (DEBUG_DOMAIN_VERIFICATION) { 1116 Slog.i(TAG, "Received verification response " + verificationId 1117 + " for " + count + " filters, verified=" + verified); 1118 } 1119 for (int n=0; n<count; n++) { 1120 PackageParser.ActivityIntentInfo filter = filters.get(n); 1121 filter.setVerified(verified); 1122 1123 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1124 + " verified with result:" + verified + " and hosts:" 1125 + ivs.getHostsString()); 1126 } 1127 1128 mIntentFilterVerificationStates.remove(verificationId); 1129 1130 final String packageName = ivs.getPackageName(); 1131 IntentFilterVerificationInfo ivi = null; 1132 1133 synchronized (mPackages) { 1134 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1135 } 1136 if (ivi == null) { 1137 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1138 + verificationId + " packageName:" + packageName); 1139 return; 1140 } 1141 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1142 "Updating IntentFilterVerificationInfo for package " + packageName 1143 +" verificationId:" + verificationId); 1144 1145 synchronized (mPackages) { 1146 if (verified) { 1147 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1148 } else { 1149 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1150 } 1151 scheduleWriteSettingsLocked(); 1152 1153 final int userId = ivs.getUserId(); 1154 if (userId != UserHandle.USER_ALL) { 1155 final int userStatus = 1156 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1157 1158 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1159 boolean needUpdate = false; 1160 1161 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1162 // already been set by the User thru the Disambiguation dialog 1163 switch (userStatus) { 1164 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1165 if (verified) { 1166 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1167 } else { 1168 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1169 } 1170 needUpdate = true; 1171 break; 1172 1173 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1174 if (verified) { 1175 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1176 needUpdate = true; 1177 } 1178 break; 1179 1180 default: 1181 // Nothing to do 1182 } 1183 1184 if (needUpdate) { 1185 mSettings.updateIntentFilterVerificationStatusLPw( 1186 packageName, updatedStatus, userId); 1187 scheduleWritePackageRestrictionsLocked(userId); 1188 } 1189 } 1190 } 1191 } 1192 1193 @Override 1194 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1195 ActivityIntentInfo filter, String packageName) { 1196 if (!hasValidDomains(filter)) { 1197 return false; 1198 } 1199 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1200 if (ivs == null) { 1201 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1202 packageName); 1203 } 1204 if (DEBUG_DOMAIN_VERIFICATION) { 1205 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1206 } 1207 ivs.addFilter(filter); 1208 return true; 1209 } 1210 1211 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1212 int userId, int verificationId, String packageName) { 1213 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1214 verifierUid, userId, packageName); 1215 ivs.setPendingState(); 1216 synchronized (mPackages) { 1217 mIntentFilterVerificationStates.append(verificationId, ivs); 1218 mCurrentIntentFilterVerifications.add(verificationId); 1219 } 1220 return ivs; 1221 } 1222 } 1223 1224 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1225 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1226 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1227 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1228 } 1229 1230 // Set of pending broadcasts for aggregating enable/disable of components. 1231 static class PendingPackageBroadcasts { 1232 // for each user id, a map of <package name -> components within that package> 1233 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1234 1235 public PendingPackageBroadcasts() { 1236 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1237 } 1238 1239 public ArrayList<String> get(int userId, String packageName) { 1240 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1241 return packages.get(packageName); 1242 } 1243 1244 public void put(int userId, String packageName, ArrayList<String> components) { 1245 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1246 packages.put(packageName, components); 1247 } 1248 1249 public void remove(int userId, String packageName) { 1250 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1251 if (packages != null) { 1252 packages.remove(packageName); 1253 } 1254 } 1255 1256 public void remove(int userId) { 1257 mUidMap.remove(userId); 1258 } 1259 1260 public int userIdCount() { 1261 return mUidMap.size(); 1262 } 1263 1264 public int userIdAt(int n) { 1265 return mUidMap.keyAt(n); 1266 } 1267 1268 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1269 return mUidMap.get(userId); 1270 } 1271 1272 public int size() { 1273 // total number of pending broadcast entries across all userIds 1274 int num = 0; 1275 for (int i = 0; i< mUidMap.size(); i++) { 1276 num += mUidMap.valueAt(i).size(); 1277 } 1278 return num; 1279 } 1280 1281 public void clear() { 1282 mUidMap.clear(); 1283 } 1284 1285 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1286 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1287 if (map == null) { 1288 map = new ArrayMap<String, ArrayList<String>>(); 1289 mUidMap.put(userId, map); 1290 } 1291 return map; 1292 } 1293 } 1294 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1295 1296 // Service Connection to remote media container service to copy 1297 // package uri's from external media onto secure containers 1298 // or internal storage. 1299 private IMediaContainerService mContainerService = null; 1300 1301 static final int SEND_PENDING_BROADCAST = 1; 1302 static final int MCS_BOUND = 3; 1303 static final int END_COPY = 4; 1304 static final int INIT_COPY = 5; 1305 static final int MCS_UNBIND = 6; 1306 static final int START_CLEANING_PACKAGE = 7; 1307 static final int FIND_INSTALL_LOC = 8; 1308 static final int POST_INSTALL = 9; 1309 static final int MCS_RECONNECT = 10; 1310 static final int MCS_GIVE_UP = 11; 1311 static final int WRITE_SETTINGS = 13; 1312 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1313 static final int PACKAGE_VERIFIED = 15; 1314 static final int CHECK_PENDING_VERIFICATION = 16; 1315 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1316 static final int INTENT_FILTER_VERIFIED = 18; 1317 static final int WRITE_PACKAGE_LIST = 19; 1318 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1319 1320 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1321 1322 // Delay time in millisecs 1323 static final int BROADCAST_DELAY = 10 * 1000; 1324 1325 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1326 2 * 60 * 60 * 1000L; /* two hours */ 1327 1328 static UserManagerService sUserManager; 1329 1330 // Stores a list of users whose package restrictions file needs to be updated 1331 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1332 1333 final private DefaultContainerConnection mDefContainerConn = 1334 new DefaultContainerConnection(); 1335 class DefaultContainerConnection implements ServiceConnection { 1336 public void onServiceConnected(ComponentName name, IBinder service) { 1337 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1338 final IMediaContainerService imcs = IMediaContainerService.Stub 1339 .asInterface(Binder.allowBlocking(service)); 1340 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1341 } 1342 1343 public void onServiceDisconnected(ComponentName name) { 1344 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1345 } 1346 } 1347 1348 // Recordkeeping of restore-after-install operations that are currently in flight 1349 // between the Package Manager and the Backup Manager 1350 static class PostInstallData { 1351 public InstallArgs args; 1352 public PackageInstalledInfo res; 1353 1354 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1355 args = _a; 1356 res = _r; 1357 } 1358 } 1359 1360 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1361 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1362 1363 // XML tags for backup/restore of various bits of state 1364 private static final String TAG_PREFERRED_BACKUP = "pa"; 1365 private static final String TAG_DEFAULT_APPS = "da"; 1366 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1367 1368 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1369 private static final String TAG_ALL_GRANTS = "rt-grants"; 1370 private static final String TAG_GRANT = "grant"; 1371 private static final String ATTR_PACKAGE_NAME = "pkg"; 1372 1373 private static final String TAG_PERMISSION = "perm"; 1374 private static final String ATTR_PERMISSION_NAME = "name"; 1375 private static final String ATTR_IS_GRANTED = "g"; 1376 private static final String ATTR_USER_SET = "set"; 1377 private static final String ATTR_USER_FIXED = "fixed"; 1378 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1379 1380 // System/policy permission grants are not backed up 1381 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1382 FLAG_PERMISSION_POLICY_FIXED 1383 | FLAG_PERMISSION_SYSTEM_FIXED 1384 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1385 1386 // And we back up these user-adjusted states 1387 private static final int USER_RUNTIME_GRANT_MASK = 1388 FLAG_PERMISSION_USER_SET 1389 | FLAG_PERMISSION_USER_FIXED 1390 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1391 1392 final @Nullable String mRequiredVerifierPackage; 1393 final @NonNull String mRequiredInstallerPackage; 1394 final @NonNull String mRequiredUninstallerPackage; 1395 final @Nullable String mSetupWizardPackage; 1396 final @Nullable String mStorageManagerPackage; 1397 final @Nullable String mSystemTextClassifierPackage; 1398 final @NonNull String mServicesSystemSharedLibraryPackageName; 1399 final @NonNull String mSharedSystemSharedLibraryPackageName; 1400 1401 private final PackageUsage mPackageUsage = new PackageUsage(); 1402 private final CompilerStats mCompilerStats = new CompilerStats(); 1403 1404 class PackageHandler extends Handler { 1405 private boolean mBound = false; 1406 final ArrayList<HandlerParams> mPendingInstalls = 1407 new ArrayList<HandlerParams>(); 1408 1409 private boolean connectToService() { 1410 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1411 " DefaultContainerService"); 1412 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1415 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1416 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1417 mBound = true; 1418 return true; 1419 } 1420 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1421 return false; 1422 } 1423 1424 private void disconnectService() { 1425 mContainerService = null; 1426 mBound = false; 1427 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1428 mContext.unbindService(mDefContainerConn); 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1430 } 1431 1432 PackageHandler(Looper looper) { 1433 super(looper); 1434 } 1435 1436 public void handleMessage(Message msg) { 1437 try { 1438 doHandleMessage(msg); 1439 } finally { 1440 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1441 } 1442 } 1443 1444 void doHandleMessage(Message msg) { 1445 switch (msg.what) { 1446 case INIT_COPY: { 1447 HandlerParams params = (HandlerParams) msg.obj; 1448 int idx = mPendingInstalls.size(); 1449 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1450 // If a bind was already initiated we dont really 1451 // need to do anything. The pending install 1452 // will be processed later on. 1453 if (!mBound) { 1454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1455 System.identityHashCode(mHandler)); 1456 // If this is the only one pending we might 1457 // have to bind to the service again. 1458 if (!connectToService()) { 1459 Slog.e(TAG, "Failed to bind to media container service"); 1460 params.serviceError(); 1461 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1462 System.identityHashCode(mHandler)); 1463 if (params.traceMethod != null) { 1464 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1465 params.traceCookie); 1466 } 1467 return; 1468 } else { 1469 // Once we bind to the service, the first 1470 // pending request will be processed. 1471 mPendingInstalls.add(idx, params); 1472 } 1473 } else { 1474 mPendingInstalls.add(idx, params); 1475 // Already bound to the service. Just make 1476 // sure we trigger off processing the first request. 1477 if (idx == 0) { 1478 mHandler.sendEmptyMessage(MCS_BOUND); 1479 } 1480 } 1481 break; 1482 } 1483 case MCS_BOUND: { 1484 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1485 if (msg.obj != null) { 1486 mContainerService = (IMediaContainerService) msg.obj; 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1488 System.identityHashCode(mHandler)); 1489 } 1490 if (mContainerService == null) { 1491 if (!mBound) { 1492 // Something seriously wrong since we are not bound and we are not 1493 // waiting for connection. Bail out. 1494 Slog.e(TAG, "Cannot bind to media container service"); 1495 for (HandlerParams params : mPendingInstalls) { 1496 // Indicate service bind error 1497 params.serviceError(); 1498 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1499 System.identityHashCode(params)); 1500 if (params.traceMethod != null) { 1501 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1502 params.traceMethod, params.traceCookie); 1503 } 1504 return; 1505 } 1506 mPendingInstalls.clear(); 1507 } else { 1508 Slog.w(TAG, "Waiting to connect to media container service"); 1509 } 1510 } else if (mPendingInstalls.size() > 0) { 1511 HandlerParams params = mPendingInstalls.get(0); 1512 if (params != null) { 1513 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1514 System.identityHashCode(params)); 1515 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1516 if (params.startCopy()) { 1517 // We are done... look for more work or to 1518 // go idle. 1519 if (DEBUG_SD_INSTALL) Log.i(TAG, 1520 "Checking for more work or unbind..."); 1521 // Delete pending install 1522 if (mPendingInstalls.size() > 0) { 1523 mPendingInstalls.remove(0); 1524 } 1525 if (mPendingInstalls.size() == 0) { 1526 if (mBound) { 1527 if (DEBUG_SD_INSTALL) Log.i(TAG, 1528 "Posting delayed MCS_UNBIND"); 1529 removeMessages(MCS_UNBIND); 1530 Message ubmsg = obtainMessage(MCS_UNBIND); 1531 // Unbind after a little delay, to avoid 1532 // continual thrashing. 1533 sendMessageDelayed(ubmsg, 10000); 1534 } 1535 } else { 1536 // There are more pending requests in queue. 1537 // Just post MCS_BOUND message to trigger processing 1538 // of next pending install. 1539 if (DEBUG_SD_INSTALL) Log.i(TAG, 1540 "Posting MCS_BOUND for next work"); 1541 mHandler.sendEmptyMessage(MCS_BOUND); 1542 } 1543 } 1544 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1545 } 1546 } else { 1547 // Should never happen ideally. 1548 Slog.w(TAG, "Empty queue"); 1549 } 1550 break; 1551 } 1552 case MCS_RECONNECT: { 1553 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1554 if (mPendingInstalls.size() > 0) { 1555 if (mBound) { 1556 disconnectService(); 1557 } 1558 if (!connectToService()) { 1559 Slog.e(TAG, "Failed to bind to media container service"); 1560 for (HandlerParams params : mPendingInstalls) { 1561 // Indicate service bind error 1562 params.serviceError(); 1563 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1564 System.identityHashCode(params)); 1565 } 1566 mPendingInstalls.clear(); 1567 } 1568 } 1569 break; 1570 } 1571 case MCS_UNBIND: { 1572 // If there is no actual work left, then time to unbind. 1573 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1574 1575 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1576 if (mBound) { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1578 1579 disconnectService(); 1580 } 1581 } else if (mPendingInstalls.size() > 0) { 1582 // There are more pending requests in queue. 1583 // Just post MCS_BOUND message to trigger processing 1584 // of next pending install. 1585 mHandler.sendEmptyMessage(MCS_BOUND); 1586 } 1587 1588 break; 1589 } 1590 case MCS_GIVE_UP: { 1591 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1592 HandlerParams params = mPendingInstalls.remove(0); 1593 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1594 System.identityHashCode(params)); 1595 break; 1596 } 1597 case SEND_PENDING_BROADCAST: { 1598 String packages[]; 1599 ArrayList<String> components[]; 1600 int size = 0; 1601 int uids[]; 1602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1603 synchronized (mPackages) { 1604 if (mPendingBroadcasts == null) { 1605 return; 1606 } 1607 size = mPendingBroadcasts.size(); 1608 if (size <= 0) { 1609 // Nothing to be done. Just return 1610 return; 1611 } 1612 packages = new String[size]; 1613 components = new ArrayList[size]; 1614 uids = new int[size]; 1615 int i = 0; // filling out the above arrays 1616 1617 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1618 int packageUserId = mPendingBroadcasts.userIdAt(n); 1619 Iterator<Map.Entry<String, ArrayList<String>>> it 1620 = mPendingBroadcasts.packagesForUserId(packageUserId) 1621 .entrySet().iterator(); 1622 while (it.hasNext() && i < size) { 1623 Map.Entry<String, ArrayList<String>> ent = it.next(); 1624 packages[i] = ent.getKey(); 1625 components[i] = ent.getValue(); 1626 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1627 uids[i] = (ps != null) 1628 ? UserHandle.getUid(packageUserId, ps.appId) 1629 : -1; 1630 i++; 1631 } 1632 } 1633 size = i; 1634 mPendingBroadcasts.clear(); 1635 } 1636 // Send broadcasts 1637 for (int i = 0; i < size; i++) { 1638 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1639 } 1640 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1641 break; 1642 } 1643 case START_CLEANING_PACKAGE: { 1644 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1645 final String packageName = (String)msg.obj; 1646 final int userId = msg.arg1; 1647 final boolean andCode = msg.arg2 != 0; 1648 synchronized (mPackages) { 1649 if (userId == UserHandle.USER_ALL) { 1650 int[] users = sUserManager.getUserIds(); 1651 for (int user : users) { 1652 mSettings.addPackageToCleanLPw( 1653 new PackageCleanItem(user, packageName, andCode)); 1654 } 1655 } else { 1656 mSettings.addPackageToCleanLPw( 1657 new PackageCleanItem(userId, packageName, andCode)); 1658 } 1659 } 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1661 startCleaningPackages(); 1662 } break; 1663 case POST_INSTALL: { 1664 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1665 1666 PostInstallData data = mRunningInstalls.get(msg.arg1); 1667 final boolean didRestore = (msg.arg2 != 0); 1668 mRunningInstalls.delete(msg.arg1); 1669 1670 if (data != null) { 1671 InstallArgs args = data.args; 1672 PackageInstalledInfo parentRes = data.res; 1673 1674 final boolean grantPermissions = (args.installFlags 1675 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1676 final boolean killApp = (args.installFlags 1677 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1678 final boolean virtualPreload = ((args.installFlags 1679 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1680 final String[] grantedPermissions = args.installGrantPermissions; 1681 1682 // Handle the parent package 1683 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1684 virtualPreload, grantedPermissions, didRestore, 1685 args.installerPackageName, args.observer); 1686 1687 // Handle the child packages 1688 final int childCount = (parentRes.addedChildPackages != null) 1689 ? parentRes.addedChildPackages.size() : 0; 1690 for (int i = 0; i < childCount; i++) { 1691 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1692 handlePackagePostInstall(childRes, grantPermissions, killApp, 1693 virtualPreload, grantedPermissions, false /*didRestore*/, 1694 args.installerPackageName, args.observer); 1695 } 1696 1697 // Log tracing if needed 1698 if (args.traceMethod != null) { 1699 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1700 args.traceCookie); 1701 } 1702 } else { 1703 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1704 } 1705 1706 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1707 } break; 1708 case WRITE_SETTINGS: { 1709 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1710 synchronized (mPackages) { 1711 removeMessages(WRITE_SETTINGS); 1712 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1713 mSettings.writeLPr(); 1714 mDirtyUsers.clear(); 1715 } 1716 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1717 } break; 1718 case WRITE_PACKAGE_RESTRICTIONS: { 1719 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1720 synchronized (mPackages) { 1721 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1722 for (int userId : mDirtyUsers) { 1723 mSettings.writePackageRestrictionsLPr(userId); 1724 } 1725 mDirtyUsers.clear(); 1726 } 1727 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1728 } break; 1729 case WRITE_PACKAGE_LIST: { 1730 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1731 synchronized (mPackages) { 1732 removeMessages(WRITE_PACKAGE_LIST); 1733 mSettings.writePackageListLPr(msg.arg1); 1734 } 1735 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1736 } break; 1737 case CHECK_PENDING_VERIFICATION: { 1738 final int verificationId = msg.arg1; 1739 final PackageVerificationState state = mPendingVerification.get(verificationId); 1740 1741 if ((state != null) && !state.timeoutExtended()) { 1742 final InstallArgs args = state.getInstallArgs(); 1743 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1744 1745 Slog.i(TAG, "Verification timed out for " + originUri); 1746 mPendingVerification.remove(verificationId); 1747 1748 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1749 1750 final UserHandle user = args.getUser(); 1751 if (getDefaultVerificationResponse(user) 1752 == PackageManager.VERIFICATION_ALLOW) { 1753 Slog.i(TAG, "Continuing with installation of " + originUri); 1754 state.setVerifierResponse(Binder.getCallingUid(), 1755 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1756 broadcastPackageVerified(verificationId, originUri, 1757 PackageManager.VERIFICATION_ALLOW, user); 1758 try { 1759 ret = args.copyApk(mContainerService, true); 1760 } catch (RemoteException e) { 1761 Slog.e(TAG, "Could not contact the ContainerService"); 1762 } 1763 } else { 1764 broadcastPackageVerified(verificationId, originUri, 1765 PackageManager.VERIFICATION_REJECT, user); 1766 } 1767 1768 Trace.asyncTraceEnd( 1769 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1770 1771 processPendingInstall(args, ret); 1772 mHandler.sendEmptyMessage(MCS_UNBIND); 1773 } 1774 break; 1775 } 1776 case PACKAGE_VERIFIED: { 1777 final int verificationId = msg.arg1; 1778 1779 final PackageVerificationState state = mPendingVerification.get(verificationId); 1780 if (state == null) { 1781 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1782 break; 1783 } 1784 1785 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1786 1787 state.setVerifierResponse(response.callerUid, response.code); 1788 1789 if (state.isVerificationComplete()) { 1790 mPendingVerification.remove(verificationId); 1791 1792 final InstallArgs args = state.getInstallArgs(); 1793 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1794 1795 int ret; 1796 if (state.isInstallAllowed()) { 1797 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1798 broadcastPackageVerified(verificationId, originUri, 1799 response.code, state.getInstallArgs().getUser()); 1800 try { 1801 ret = args.copyApk(mContainerService, true); 1802 } catch (RemoteException e) { 1803 Slog.e(TAG, "Could not contact the ContainerService"); 1804 } 1805 } else { 1806 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1807 } 1808 1809 Trace.asyncTraceEnd( 1810 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1811 1812 processPendingInstall(args, ret); 1813 mHandler.sendEmptyMessage(MCS_UNBIND); 1814 } 1815 1816 break; 1817 } 1818 case START_INTENT_FILTER_VERIFICATIONS: { 1819 IFVerificationParams params = (IFVerificationParams) msg.obj; 1820 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1821 params.replacing, params.pkg); 1822 break; 1823 } 1824 case INTENT_FILTER_VERIFIED: { 1825 final int verificationId = msg.arg1; 1826 1827 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1828 verificationId); 1829 if (state == null) { 1830 Slog.w(TAG, "Invalid IntentFilter verification token " 1831 + verificationId + " received"); 1832 break; 1833 } 1834 1835 final int userId = state.getUserId(); 1836 1837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1838 "Processing IntentFilter verification with token:" 1839 + verificationId + " and userId:" + userId); 1840 1841 final IntentFilterVerificationResponse response = 1842 (IntentFilterVerificationResponse) msg.obj; 1843 1844 state.setVerifierResponse(response.callerUid, response.code); 1845 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1847 "IntentFilter verification with token:" + verificationId 1848 + " and userId:" + userId 1849 + " is settings verifier response with response code:" 1850 + response.code); 1851 1852 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1854 + response.getFailedDomainsString()); 1855 } 1856 1857 if (state.isVerificationComplete()) { 1858 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1859 } else { 1860 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1861 "IntentFilter verification with token:" + verificationId 1862 + " was not said to be complete"); 1863 } 1864 1865 break; 1866 } 1867 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1868 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1869 mInstantAppResolverConnection, 1870 (InstantAppRequest) msg.obj, 1871 mInstantAppInstallerActivity, 1872 mHandler); 1873 } 1874 } 1875 } 1876 } 1877 1878 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1879 @Override 1880 public void onGidsChanged(int appId, int userId) { 1881 mHandler.post(new Runnable() { 1882 @Override 1883 public void run() { 1884 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1885 } 1886 }); 1887 } 1888 @Override 1889 public void onPermissionGranted(int uid, int userId) { 1890 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1891 1892 // Not critical; if this is lost, the application has to request again. 1893 synchronized (mPackages) { 1894 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1895 } 1896 } 1897 @Override 1898 public void onInstallPermissionGranted() { 1899 synchronized (mPackages) { 1900 scheduleWriteSettingsLocked(); 1901 } 1902 } 1903 @Override 1904 public void onPermissionRevoked(int uid, int userId) { 1905 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1906 1907 synchronized (mPackages) { 1908 // Critical; after this call the application should never have the permission 1909 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1910 } 1911 1912 final int appId = UserHandle.getAppId(uid); 1913 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1914 } 1915 @Override 1916 public void onInstallPermissionRevoked() { 1917 synchronized (mPackages) { 1918 scheduleWriteSettingsLocked(); 1919 } 1920 } 1921 @Override 1922 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1923 synchronized (mPackages) { 1924 for (int userId : updatedUserIds) { 1925 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1926 } 1927 } 1928 } 1929 @Override 1930 public void onInstallPermissionUpdated() { 1931 synchronized (mPackages) { 1932 scheduleWriteSettingsLocked(); 1933 } 1934 } 1935 @Override 1936 public void onPermissionRemoved() { 1937 synchronized (mPackages) { 1938 mSettings.writeLPr(); 1939 } 1940 } 1941 }; 1942 1943 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1944 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1945 boolean launchedForRestore, String installerPackage, 1946 IPackageInstallObserver2 installObserver) { 1947 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1948 // Send the removed broadcasts 1949 if (res.removedInfo != null) { 1950 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1951 } 1952 1953 // Now that we successfully installed the package, grant runtime 1954 // permissions if requested before broadcasting the install. Also 1955 // for legacy apps in permission review mode we clear the permission 1956 // review flag which is used to emulate runtime permissions for 1957 // legacy apps. 1958 if (grantPermissions) { 1959 final int callingUid = Binder.getCallingUid(); 1960 mPermissionManager.grantRequestedRuntimePermissions( 1961 res.pkg, res.newUsers, grantedPermissions, callingUid, 1962 mPermissionCallback); 1963 } 1964 1965 final boolean update = res.removedInfo != null 1966 && res.removedInfo.removedPackage != null; 1967 final String installerPackageName = 1968 res.installerPackageName != null 1969 ? res.installerPackageName 1970 : res.removedInfo != null 1971 ? res.removedInfo.installerPackageName 1972 : null; 1973 1974 // If this is the first time we have child packages for a disabled privileged 1975 // app that had no children, we grant requested runtime permissions to the new 1976 // children if the parent on the system image had them already granted. 1977 if (res.pkg.parentPackage != null) { 1978 final int callingUid = Binder.getCallingUid(); 1979 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1980 res.pkg, callingUid, mPermissionCallback); 1981 } 1982 1983 synchronized (mPackages) { 1984 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1985 } 1986 1987 final String packageName = res.pkg.applicationInfo.packageName; 1988 1989 // Determine the set of users who are adding this package for 1990 // the first time vs. those who are seeing an update. 1991 int[] firstUserIds = EMPTY_INT_ARRAY; 1992 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1993 int[] updateUserIds = EMPTY_INT_ARRAY; 1994 int[] instantUserIds = EMPTY_INT_ARRAY; 1995 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1996 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1997 for (int newUser : res.newUsers) { 1998 final boolean isInstantApp = ps.getInstantApp(newUser); 1999 if (allNewUsers) { 2000 if (isInstantApp) { 2001 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2002 } else { 2003 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2004 } 2005 continue; 2006 } 2007 boolean isNew = true; 2008 for (int origUser : res.origUsers) { 2009 if (origUser == newUser) { 2010 isNew = false; 2011 break; 2012 } 2013 } 2014 if (isNew) { 2015 if (isInstantApp) { 2016 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2017 } else { 2018 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2019 } 2020 } else { 2021 if (isInstantApp) { 2022 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2023 } else { 2024 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2025 } 2026 } 2027 } 2028 2029 // Send installed broadcasts if the package is not a static shared lib. 2030 if (res.pkg.staticSharedLibName == null) { 2031 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2032 2033 // Send added for users that see the package for the first time 2034 // sendPackageAddedForNewUsers also deals with system apps 2035 int appId = UserHandle.getAppId(res.uid); 2036 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2037 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2038 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2039 2040 // Send added for users that don't see the package for the first time 2041 Bundle extras = new Bundle(1); 2042 extras.putInt(Intent.EXTRA_UID, res.uid); 2043 if (update) { 2044 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2045 } 2046 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2047 extras, 0 /*flags*/, 2048 null /*targetPackage*/, null /*finishedReceiver*/, 2049 updateUserIds, instantUserIds); 2050 if (installerPackageName != null) { 2051 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2052 extras, 0 /*flags*/, 2053 installerPackageName, null /*finishedReceiver*/, 2054 updateUserIds, instantUserIds); 2055 } 2056 2057 // Send replaced for users that don't see the package for the first time 2058 if (update) { 2059 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2060 packageName, extras, 0 /*flags*/, 2061 null /*targetPackage*/, null /*finishedReceiver*/, 2062 updateUserIds, instantUserIds); 2063 if (installerPackageName != null) { 2064 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2065 extras, 0 /*flags*/, 2066 installerPackageName, null /*finishedReceiver*/, 2067 updateUserIds, instantUserIds); 2068 } 2069 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2070 null /*package*/, null /*extras*/, 0 /*flags*/, 2071 packageName /*targetPackage*/, 2072 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2073 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2074 // First-install and we did a restore, so we're responsible for the 2075 // first-launch broadcast. 2076 if (DEBUG_BACKUP) { 2077 Slog.i(TAG, "Post-restore of " + packageName 2078 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2079 } 2080 sendFirstLaunchBroadcast(packageName, installerPackage, 2081 firstUserIds, firstInstantUserIds); 2082 } 2083 2084 // Send broadcast package appeared if forward locked/external for all users 2085 // treat asec-hosted packages like removable media on upgrade 2086 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2087 if (DEBUG_INSTALL) { 2088 Slog.i(TAG, "upgrading pkg " + res.pkg 2089 + " is ASEC-hosted -> AVAILABLE"); 2090 } 2091 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2092 ArrayList<String> pkgList = new ArrayList<>(1); 2093 pkgList.add(packageName); 2094 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2095 } 2096 } 2097 2098 // Work that needs to happen on first install within each user 2099 if (firstUserIds != null && firstUserIds.length > 0) { 2100 synchronized (mPackages) { 2101 for (int userId : firstUserIds) { 2102 // If this app is a browser and it's newly-installed for some 2103 // users, clear any default-browser state in those users. The 2104 // app's nature doesn't depend on the user, so we can just check 2105 // its browser nature in any user and generalize. 2106 if (packageIsBrowser(packageName, userId)) { 2107 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2108 } 2109 2110 // We may also need to apply pending (restored) runtime 2111 // permission grants within these users. 2112 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2113 } 2114 } 2115 } 2116 2117 if (allNewUsers && !update) { 2118 notifyPackageAdded(packageName); 2119 } 2120 2121 // Log current value of "unknown sources" setting 2122 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2123 getUnknownSourcesSettings()); 2124 2125 // Remove the replaced package's older resources safely now 2126 // We delete after a gc for applications on sdcard. 2127 if (res.removedInfo != null && res.removedInfo.args != null) { 2128 Runtime.getRuntime().gc(); 2129 synchronized (mInstallLock) { 2130 res.removedInfo.args.doPostDeleteLI(true); 2131 } 2132 } else { 2133 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2134 // and not block here. 2135 VMRuntime.getRuntime().requestConcurrentGC(); 2136 } 2137 2138 // Notify DexManager that the package was installed for new users. 2139 // The updated users should already be indexed and the package code paths 2140 // should not change. 2141 // Don't notify the manager for ephemeral apps as they are not expected to 2142 // survive long enough to benefit of background optimizations. 2143 for (int userId : firstUserIds) { 2144 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2145 // There's a race currently where some install events may interleave with an uninstall. 2146 // This can lead to package info being null (b/36642664). 2147 if (info != null) { 2148 mDexManager.notifyPackageInstalled(info, userId); 2149 } 2150 } 2151 } 2152 2153 // If someone is watching installs - notify them 2154 if (installObserver != null) { 2155 try { 2156 Bundle extras = extrasForInstallResult(res); 2157 installObserver.onPackageInstalled(res.name, res.returnCode, 2158 res.returnMsg, extras); 2159 } catch (RemoteException e) { 2160 Slog.i(TAG, "Observer no longer exists."); 2161 } 2162 } 2163 } 2164 2165 private StorageEventListener mStorageListener = new StorageEventListener() { 2166 @Override 2167 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2168 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2169 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2170 final String volumeUuid = vol.getFsUuid(); 2171 2172 // Clean up any users or apps that were removed or recreated 2173 // while this volume was missing 2174 sUserManager.reconcileUsers(volumeUuid); 2175 reconcileApps(volumeUuid); 2176 2177 // Clean up any install sessions that expired or were 2178 // cancelled while this volume was missing 2179 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2180 2181 loadPrivatePackages(vol); 2182 2183 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2184 unloadPrivatePackages(vol); 2185 } 2186 } 2187 } 2188 2189 @Override 2190 public void onVolumeForgotten(String fsUuid) { 2191 if (TextUtils.isEmpty(fsUuid)) { 2192 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2193 return; 2194 } 2195 2196 // Remove any apps installed on the forgotten volume 2197 synchronized (mPackages) { 2198 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2199 for (PackageSetting ps : packages) { 2200 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2201 deletePackageVersioned(new VersionedPackage(ps.name, 2202 PackageManager.VERSION_CODE_HIGHEST), 2203 new LegacyPackageDeleteObserver(null).getBinder(), 2204 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2205 // Try very hard to release any references to this package 2206 // so we don't risk the system server being killed due to 2207 // open FDs 2208 AttributeCache.instance().removePackage(ps.name); 2209 } 2210 2211 mSettings.onVolumeForgotten(fsUuid); 2212 mSettings.writeLPr(); 2213 } 2214 } 2215 }; 2216 2217 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2218 Bundle extras = null; 2219 switch (res.returnCode) { 2220 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2221 extras = new Bundle(); 2222 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2223 res.origPermission); 2224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2225 res.origPackage); 2226 break; 2227 } 2228 case PackageManager.INSTALL_SUCCEEDED: { 2229 extras = new Bundle(); 2230 extras.putBoolean(Intent.EXTRA_REPLACING, 2231 res.removedInfo != null && res.removedInfo.removedPackage != null); 2232 break; 2233 } 2234 } 2235 return extras; 2236 } 2237 2238 void scheduleWriteSettingsLocked() { 2239 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2240 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2241 } 2242 } 2243 2244 void scheduleWritePackageListLocked(int userId) { 2245 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2246 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2247 msg.arg1 = userId; 2248 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2249 } 2250 } 2251 2252 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2253 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2254 scheduleWritePackageRestrictionsLocked(userId); 2255 } 2256 2257 void scheduleWritePackageRestrictionsLocked(int userId) { 2258 final int[] userIds = (userId == UserHandle.USER_ALL) 2259 ? sUserManager.getUserIds() : new int[]{userId}; 2260 for (int nextUserId : userIds) { 2261 if (!sUserManager.exists(nextUserId)) return; 2262 mDirtyUsers.add(nextUserId); 2263 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2264 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2265 } 2266 } 2267 } 2268 2269 public static PackageManagerService main(Context context, Installer installer, 2270 boolean factoryTest, boolean onlyCore) { 2271 // Self-check for initial settings. 2272 PackageManagerServiceCompilerMapping.checkProperties(); 2273 2274 PackageManagerService m = new PackageManagerService(context, installer, 2275 factoryTest, onlyCore); 2276 m.enableSystemUserPackages(); 2277 ServiceManager.addService("package", m); 2278 final PackageManagerNative pmn = m.new PackageManagerNative(); 2279 ServiceManager.addService("package_native", pmn); 2280 return m; 2281 } 2282 2283 private void enableSystemUserPackages() { 2284 if (!UserManager.isSplitSystemUser()) { 2285 return; 2286 } 2287 // For system user, enable apps based on the following conditions: 2288 // - app is whitelisted or belong to one of these groups: 2289 // -- system app which has no launcher icons 2290 // -- system app which has INTERACT_ACROSS_USERS permission 2291 // -- system IME app 2292 // - app is not in the blacklist 2293 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2294 Set<String> enableApps = new ArraySet<>(); 2295 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2296 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2297 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2298 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2299 enableApps.addAll(wlApps); 2300 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2301 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2302 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2303 enableApps.removeAll(blApps); 2304 Log.i(TAG, "Applications installed for system user: " + enableApps); 2305 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2306 UserHandle.SYSTEM); 2307 final int allAppsSize = allAps.size(); 2308 synchronized (mPackages) { 2309 for (int i = 0; i < allAppsSize; i++) { 2310 String pName = allAps.get(i); 2311 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2312 // Should not happen, but we shouldn't be failing if it does 2313 if (pkgSetting == null) { 2314 continue; 2315 } 2316 boolean install = enableApps.contains(pName); 2317 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2318 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2319 + " for system user"); 2320 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2321 } 2322 } 2323 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2324 } 2325 } 2326 2327 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2328 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2329 Context.DISPLAY_SERVICE); 2330 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2331 } 2332 2333 /** 2334 * Requests that files preopted on a secondary system partition be copied to the data partition 2335 * if possible. Note that the actual copying of the files is accomplished by init for security 2336 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2337 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2338 */ 2339 private static void requestCopyPreoptedFiles() { 2340 final int WAIT_TIME_MS = 100; 2341 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2342 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2343 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2344 // We will wait for up to 100 seconds. 2345 final long timeStart = SystemClock.uptimeMillis(); 2346 final long timeEnd = timeStart + 100 * 1000; 2347 long timeNow = timeStart; 2348 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2349 try { 2350 Thread.sleep(WAIT_TIME_MS); 2351 } catch (InterruptedException e) { 2352 // Do nothing 2353 } 2354 timeNow = SystemClock.uptimeMillis(); 2355 if (timeNow > timeEnd) { 2356 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2357 Slog.wtf(TAG, "cppreopt did not finish!"); 2358 break; 2359 } 2360 } 2361 2362 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2363 } 2364 } 2365 2366 public PackageManagerService(Context context, Installer installer, 2367 boolean factoryTest, boolean onlyCore) { 2368 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2369 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2370 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2371 SystemClock.uptimeMillis()); 2372 2373 if (mSdkVersion <= 0) { 2374 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2375 } 2376 2377 mContext = context; 2378 2379 mFactoryTest = factoryTest; 2380 mOnlyCore = onlyCore; 2381 mMetrics = new DisplayMetrics(); 2382 mInstaller = installer; 2383 2384 // Create sub-components that provide services / data. Order here is important. 2385 synchronized (mInstallLock) { 2386 synchronized (mPackages) { 2387 // Expose private service for system components to use. 2388 LocalServices.addService( 2389 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2390 sUserManager = new UserManagerService(context, this, 2391 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2392 mPermissionManager = PermissionManagerService.create(context, 2393 new DefaultPermissionGrantedCallback() { 2394 @Override 2395 public void onDefaultRuntimePermissionsGranted(int userId) { 2396 synchronized(mPackages) { 2397 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2398 } 2399 } 2400 }, mPackages /*externalLock*/); 2401 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2402 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2403 } 2404 } 2405 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2406 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2407 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2408 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2409 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2410 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2411 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2412 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2413 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2414 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2415 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2416 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2417 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2418 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2419 2420 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2421 if (separateProcesses != null && separateProcesses.length() > 0) { 2422 if ("*".equals(separateProcesses)) { 2423 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2424 mSeparateProcesses = null; 2425 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2426 } else { 2427 mDefParseFlags = 0; 2428 mSeparateProcesses = separateProcesses.split(","); 2429 Slog.w(TAG, "Running with debug.separate_processes: " 2430 + separateProcesses); 2431 } 2432 } else { 2433 mDefParseFlags = 0; 2434 mSeparateProcesses = null; 2435 } 2436 2437 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2438 "*dexopt*"); 2439 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2440 installer, mInstallLock); 2441 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2442 dexManagerListener); 2443 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2444 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2445 2446 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2447 FgThread.get().getLooper()); 2448 2449 getDefaultDisplayMetrics(context, mMetrics); 2450 2451 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2452 SystemConfig systemConfig = SystemConfig.getInstance(); 2453 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2455 2456 mProtectedPackages = new ProtectedPackages(mContext); 2457 2458 synchronized (mInstallLock) { 2459 // writer 2460 synchronized (mPackages) { 2461 mHandlerThread = new ServiceThread(TAG, 2462 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2463 mHandlerThread.start(); 2464 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2465 mProcessLoggingHandler = new ProcessLoggingHandler(); 2466 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2467 mInstantAppRegistry = new InstantAppRegistry(this); 2468 2469 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2470 final int builtInLibCount = libConfig.size(); 2471 for (int i = 0; i < builtInLibCount; i++) { 2472 String name = libConfig.keyAt(i); 2473 String path = libConfig.valueAt(i); 2474 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2475 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2476 } 2477 2478 SELinuxMMAC.readInstallPolicy(); 2479 2480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2481 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2483 2484 // Clean up orphaned packages for which the code path doesn't exist 2485 // and they are an update to a system app - caused by bug/32321269 2486 final int packageSettingCount = mSettings.mPackages.size(); 2487 for (int i = packageSettingCount - 1; i >= 0; i--) { 2488 PackageSetting ps = mSettings.mPackages.valueAt(i); 2489 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2490 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2491 mSettings.mPackages.removeAt(i); 2492 mSettings.enableSystemPackageLPw(ps.name); 2493 } 2494 } 2495 2496 if (mFirstBoot) { 2497 requestCopyPreoptedFiles(); 2498 } 2499 2500 String customResolverActivity = Resources.getSystem().getString( 2501 R.string.config_customResolverActivity); 2502 if (TextUtils.isEmpty(customResolverActivity)) { 2503 customResolverActivity = null; 2504 } else { 2505 mCustomResolverComponentName = ComponentName.unflattenFromString( 2506 customResolverActivity); 2507 } 2508 2509 long startTime = SystemClock.uptimeMillis(); 2510 2511 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2512 startTime); 2513 2514 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2515 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2516 2517 if (bootClassPath == null) { 2518 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2519 } 2520 2521 if (systemServerClassPath == null) { 2522 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2523 } 2524 2525 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2526 2527 final VersionInfo ver = mSettings.getInternalVersion(); 2528 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2529 if (mIsUpgrade) { 2530 logCriticalInfo(Log.INFO, 2531 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2532 } 2533 2534 // when upgrading from pre-M, promote system app permissions from install to runtime 2535 mPromoteSystemApps = 2536 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2537 2538 // When upgrading from pre-N, we need to handle package extraction like first boot, 2539 // as there is no profiling data available. 2540 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2541 2542 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2543 2544 // save off the names of pre-existing system packages prior to scanning; we don't 2545 // want to automatically grant runtime permissions for new system apps 2546 if (mPromoteSystemApps) { 2547 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2548 while (pkgSettingIter.hasNext()) { 2549 PackageSetting ps = pkgSettingIter.next(); 2550 if (isSystemApp(ps)) { 2551 mExistingSystemPackages.add(ps.name); 2552 } 2553 } 2554 } 2555 2556 mCacheDir = preparePackageParserCache(mIsUpgrade); 2557 2558 // Set flag to monitor and not change apk file paths when 2559 // scanning install directories. 2560 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2561 2562 if (mIsUpgrade || mFirstBoot) { 2563 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2564 } 2565 2566 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2567 // For security and version matching reason, only consider 2568 // overlay packages if they reside in the right directory. 2569 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2570 mDefParseFlags 2571 | PackageParser.PARSE_IS_SYSTEM_DIR, 2572 scanFlags 2573 | SCAN_AS_SYSTEM 2574 | SCAN_AS_VENDOR, 2575 0); 2576 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2577 mDefParseFlags 2578 | PackageParser.PARSE_IS_SYSTEM_DIR, 2579 scanFlags 2580 | SCAN_AS_SYSTEM 2581 | SCAN_AS_PRODUCT, 2582 0); 2583 2584 mParallelPackageParserCallback.findStaticOverlayPackages(); 2585 2586 // Find base frameworks (resource packages without code). 2587 scanDirTracedLI(frameworkDir, 2588 mDefParseFlags 2589 | PackageParser.PARSE_IS_SYSTEM_DIR, 2590 scanFlags 2591 | SCAN_NO_DEX 2592 | SCAN_AS_SYSTEM 2593 | SCAN_AS_PRIVILEGED, 2594 0); 2595 2596 // Collect privileged system packages. 2597 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2598 scanDirTracedLI(privilegedAppDir, 2599 mDefParseFlags 2600 | PackageParser.PARSE_IS_SYSTEM_DIR, 2601 scanFlags 2602 | SCAN_AS_SYSTEM 2603 | SCAN_AS_PRIVILEGED, 2604 0); 2605 2606 // Collect ordinary system packages. 2607 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2608 scanDirTracedLI(systemAppDir, 2609 mDefParseFlags 2610 | PackageParser.PARSE_IS_SYSTEM_DIR, 2611 scanFlags 2612 | SCAN_AS_SYSTEM, 2613 0); 2614 2615 // Collect privileged vendor packages. 2616 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2617 try { 2618 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2619 } catch (IOException e) { 2620 // failed to look up canonical path, continue with original one 2621 } 2622 scanDirTracedLI(privilegedVendorAppDir, 2623 mDefParseFlags 2624 | PackageParser.PARSE_IS_SYSTEM_DIR, 2625 scanFlags 2626 | SCAN_AS_SYSTEM 2627 | SCAN_AS_VENDOR 2628 | SCAN_AS_PRIVILEGED, 2629 0); 2630 2631 // Collect ordinary vendor packages. 2632 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2633 try { 2634 vendorAppDir = vendorAppDir.getCanonicalFile(); 2635 } catch (IOException e) { 2636 // failed to look up canonical path, continue with original one 2637 } 2638 scanDirTracedLI(vendorAppDir, 2639 mDefParseFlags 2640 | PackageParser.PARSE_IS_SYSTEM_DIR, 2641 scanFlags 2642 | SCAN_AS_SYSTEM 2643 | SCAN_AS_VENDOR, 2644 0); 2645 2646 // Collect privileged odm packages. /odm is another vendor partition 2647 // other than /vendor. 2648 File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), 2649 "priv-app"); 2650 try { 2651 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile(); 2652 } catch (IOException e) { 2653 // failed to look up canonical path, continue with original one 2654 } 2655 scanDirTracedLI(privilegedOdmAppDir, 2656 mDefParseFlags 2657 | PackageParser.PARSE_IS_SYSTEM_DIR, 2658 scanFlags 2659 | SCAN_AS_SYSTEM 2660 | SCAN_AS_VENDOR 2661 | SCAN_AS_PRIVILEGED, 2662 0); 2663 2664 // Collect ordinary odm packages. /odm is another vendor partition 2665 // other than /vendor. 2666 File odmAppDir = new File(Environment.getOdmDirectory(), "app"); 2667 try { 2668 odmAppDir = odmAppDir.getCanonicalFile(); 2669 } catch (IOException e) { 2670 // failed to look up canonical path, continue with original one 2671 } 2672 scanDirTracedLI(odmAppDir, 2673 mDefParseFlags 2674 | PackageParser.PARSE_IS_SYSTEM_DIR, 2675 scanFlags 2676 | SCAN_AS_SYSTEM 2677 | SCAN_AS_VENDOR, 2678 0); 2679 2680 // Collect all OEM packages. 2681 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2682 scanDirTracedLI(oemAppDir, 2683 mDefParseFlags 2684 | PackageParser.PARSE_IS_SYSTEM_DIR, 2685 scanFlags 2686 | SCAN_AS_SYSTEM 2687 | SCAN_AS_OEM, 2688 0); 2689 2690 // Collected privileged product packages. 2691 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2692 try { 2693 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2694 } catch (IOException e) { 2695 // failed to look up canonical path, continue with original one 2696 } 2697 scanDirTracedLI(privilegedProductAppDir, 2698 mDefParseFlags 2699 | PackageParser.PARSE_IS_SYSTEM_DIR, 2700 scanFlags 2701 | SCAN_AS_SYSTEM 2702 | SCAN_AS_PRODUCT 2703 | SCAN_AS_PRIVILEGED, 2704 0); 2705 2706 // Collect ordinary product packages. 2707 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2708 try { 2709 productAppDir = productAppDir.getCanonicalFile(); 2710 } catch (IOException e) { 2711 // failed to look up canonical path, continue with original one 2712 } 2713 scanDirTracedLI(productAppDir, 2714 mDefParseFlags 2715 | PackageParser.PARSE_IS_SYSTEM_DIR, 2716 scanFlags 2717 | SCAN_AS_SYSTEM 2718 | SCAN_AS_PRODUCT, 2719 0); 2720 2721 // Prune any system packages that no longer exist. 2722 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2723 // Stub packages must either be replaced with full versions in the /data 2724 // partition or be disabled. 2725 final List<String> stubSystemApps = new ArrayList<>(); 2726 if (!mOnlyCore) { 2727 // do this first before mucking with mPackages for the "expecting better" case 2728 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2729 while (pkgIterator.hasNext()) { 2730 final PackageParser.Package pkg = pkgIterator.next(); 2731 if (pkg.isStub) { 2732 stubSystemApps.add(pkg.packageName); 2733 } 2734 } 2735 2736 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2737 while (psit.hasNext()) { 2738 PackageSetting ps = psit.next(); 2739 2740 /* 2741 * If this is not a system app, it can't be a 2742 * disable system app. 2743 */ 2744 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2745 continue; 2746 } 2747 2748 /* 2749 * If the package is scanned, it's not erased. 2750 */ 2751 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2752 if (scannedPkg != null) { 2753 /* 2754 * If the system app is both scanned and in the 2755 * disabled packages list, then it must have been 2756 * added via OTA. Remove it from the currently 2757 * scanned package so the previously user-installed 2758 * application can be scanned. 2759 */ 2760 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2761 logCriticalInfo(Log.WARN, 2762 "Expecting better updated system app for " + ps.name 2763 + "; removing system app. Last known" 2764 + " codePath=" + ps.codePathString 2765 + ", versionCode=" + ps.versionCode 2766 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2767 removePackageLI(scannedPkg, true); 2768 mExpectingBetter.put(ps.name, ps.codePath); 2769 } 2770 2771 continue; 2772 } 2773 2774 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2775 psit.remove(); 2776 logCriticalInfo(Log.WARN, "System package " + ps.name 2777 + " no longer exists; it's data will be wiped"); 2778 // Actual deletion of code and data will be handled by later 2779 // reconciliation step 2780 } else { 2781 // we still have a disabled system package, but, it still might have 2782 // been removed. check the code path still exists and check there's 2783 // still a package. the latter can happen if an OTA keeps the same 2784 // code path, but, changes the package name. 2785 final PackageSetting disabledPs = 2786 mSettings.getDisabledSystemPkgLPr(ps.name); 2787 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2788 || disabledPs.pkg == null) { 2789 possiblyDeletedUpdatedSystemApps.add(ps.name); 2790 } 2791 } 2792 } 2793 } 2794 2795 //delete tmp files 2796 deleteTempPackageFiles(); 2797 2798 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2799 2800 // Remove any shared userIDs that have no associated packages 2801 mSettings.pruneSharedUsersLPw(); 2802 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2803 final int systemPackagesCount = mPackages.size(); 2804 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2805 + " ms, packageCount: " + systemPackagesCount 2806 + " , timePerPackage: " 2807 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2808 + " , cached: " + cachedSystemApps); 2809 if (mIsUpgrade && systemPackagesCount > 0) { 2810 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2811 ((int) systemScanTime) / systemPackagesCount); 2812 } 2813 if (!mOnlyCore) { 2814 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2815 SystemClock.uptimeMillis()); 2816 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2817 2818 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2819 | PackageParser.PARSE_FORWARD_LOCK, 2820 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2821 2822 // Remove disable package settings for updated system apps that were 2823 // removed via an OTA. If the update is no longer present, remove the 2824 // app completely. Otherwise, revoke their system privileges. 2825 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2826 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2827 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2828 final String msg; 2829 if (deletedPkg == null) { 2830 // should have found an update, but, we didn't; remove everything 2831 msg = "Updated system package " + deletedAppName 2832 + " no longer exists; removing its data"; 2833 // Actual deletion of code and data will be handled by later 2834 // reconciliation step 2835 } else { 2836 // found an update; revoke system privileges 2837 msg = "Updated system package + " + deletedAppName 2838 + " no longer exists; revoking system privileges"; 2839 2840 // Don't do anything if a stub is removed from the system image. If 2841 // we were to remove the uncompressed version from the /data partition, 2842 // this is where it'd be done. 2843 2844 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2845 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2846 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2847 } 2848 logCriticalInfo(Log.WARN, msg); 2849 } 2850 2851 /* 2852 * Make sure all system apps that we expected to appear on 2853 * the userdata partition actually showed up. If they never 2854 * appeared, crawl back and revive the system version. 2855 */ 2856 for (int i = 0; i < mExpectingBetter.size(); i++) { 2857 final String packageName = mExpectingBetter.keyAt(i); 2858 if (!mPackages.containsKey(packageName)) { 2859 final File scanFile = mExpectingBetter.valueAt(i); 2860 2861 logCriticalInfo(Log.WARN, "Expected better " + packageName 2862 + " but never showed up; reverting to system"); 2863 2864 final @ParseFlags int reparseFlags; 2865 final @ScanFlags int rescanFlags; 2866 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2867 reparseFlags = 2868 mDefParseFlags | 2869 PackageParser.PARSE_IS_SYSTEM_DIR; 2870 rescanFlags = 2871 scanFlags 2872 | SCAN_AS_SYSTEM 2873 | SCAN_AS_PRIVILEGED; 2874 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2875 reparseFlags = 2876 mDefParseFlags | 2877 PackageParser.PARSE_IS_SYSTEM_DIR; 2878 rescanFlags = 2879 scanFlags 2880 | SCAN_AS_SYSTEM; 2881 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile) 2882 || FileUtils.contains(privilegedOdmAppDir, scanFile)) { 2883 reparseFlags = 2884 mDefParseFlags | 2885 PackageParser.PARSE_IS_SYSTEM_DIR; 2886 rescanFlags = 2887 scanFlags 2888 | SCAN_AS_SYSTEM 2889 | SCAN_AS_VENDOR 2890 | SCAN_AS_PRIVILEGED; 2891 } else if (FileUtils.contains(vendorAppDir, scanFile) 2892 || FileUtils.contains(odmAppDir, scanFile)) { 2893 reparseFlags = 2894 mDefParseFlags | 2895 PackageParser.PARSE_IS_SYSTEM_DIR; 2896 rescanFlags = 2897 scanFlags 2898 | SCAN_AS_SYSTEM 2899 | SCAN_AS_VENDOR; 2900 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2901 reparseFlags = 2902 mDefParseFlags | 2903 PackageParser.PARSE_IS_SYSTEM_DIR; 2904 rescanFlags = 2905 scanFlags 2906 | SCAN_AS_SYSTEM 2907 | SCAN_AS_OEM; 2908 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2909 reparseFlags = 2910 mDefParseFlags | 2911 PackageParser.PARSE_IS_SYSTEM_DIR; 2912 rescanFlags = 2913 scanFlags 2914 | SCAN_AS_SYSTEM 2915 | SCAN_AS_PRODUCT 2916 | SCAN_AS_PRIVILEGED; 2917 } else if (FileUtils.contains(productAppDir, scanFile)) { 2918 reparseFlags = 2919 mDefParseFlags | 2920 PackageParser.PARSE_IS_SYSTEM_DIR; 2921 rescanFlags = 2922 scanFlags 2923 | SCAN_AS_SYSTEM 2924 | SCAN_AS_PRODUCT; 2925 } else { 2926 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2927 continue; 2928 } 2929 2930 mSettings.enableSystemPackageLPw(packageName); 2931 2932 try { 2933 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2934 } catch (PackageManagerException e) { 2935 Slog.e(TAG, "Failed to parse original system package: " 2936 + e.getMessage()); 2937 } 2938 } 2939 } 2940 2941 // Uncompress and install any stubbed system applications. 2942 // This must be done last to ensure all stubs are replaced or disabled. 2943 decompressSystemApplications(stubSystemApps, scanFlags); 2944 2945 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2946 - cachedSystemApps; 2947 2948 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2949 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2950 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2951 + " ms, packageCount: " + dataPackagesCount 2952 + " , timePerPackage: " 2953 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2954 + " , cached: " + cachedNonSystemApps); 2955 if (mIsUpgrade && dataPackagesCount > 0) { 2956 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2957 ((int) dataScanTime) / dataPackagesCount); 2958 } 2959 } 2960 mExpectingBetter.clear(); 2961 2962 // Resolve the storage manager. 2963 mStorageManagerPackage = getStorageManagerPackageName(); 2964 2965 // Resolve protected action filters. Only the setup wizard is allowed to 2966 // have a high priority filter for these actions. 2967 mSetupWizardPackage = getSetupWizardPackageName(); 2968 if (mProtectedFilters.size() > 0) { 2969 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2970 Slog.i(TAG, "No setup wizard;" 2971 + " All protected intents capped to priority 0"); 2972 } 2973 for (ActivityIntentInfo filter : mProtectedFilters) { 2974 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2975 if (DEBUG_FILTERS) { 2976 Slog.i(TAG, "Found setup wizard;" 2977 + " allow priority " + filter.getPriority() + ";" 2978 + " package: " + filter.activity.info.packageName 2979 + " activity: " + filter.activity.className 2980 + " priority: " + filter.getPriority()); 2981 } 2982 // skip setup wizard; allow it to keep the high priority filter 2983 continue; 2984 } 2985 if (DEBUG_FILTERS) { 2986 Slog.i(TAG, "Protected action; cap priority to 0;" 2987 + " package: " + filter.activity.info.packageName 2988 + " activity: " + filter.activity.className 2989 + " origPrio: " + filter.getPriority()); 2990 } 2991 filter.setPriority(0); 2992 } 2993 } 2994 2995 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 2996 2997 mDeferProtectedFilters = false; 2998 mProtectedFilters.clear(); 2999 3000 // Now that we know all of the shared libraries, update all clients to have 3001 // the correct library paths. 3002 updateAllSharedLibrariesLPw(null); 3003 3004 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3005 // NOTE: We ignore potential failures here during a system scan (like 3006 // the rest of the commands above) because there's precious little we 3007 // can do about it. A settings error is reported, though. 3008 final List<String> changedAbiCodePath = 3009 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 3010 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3011 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3012 final String codePathString = changedAbiCodePath.get(i); 3013 try { 3014 mInstaller.rmdex(codePathString, 3015 getDexCodeInstructionSet(getPreferredInstructionSet())); 3016 } catch (InstallerException ignored) { 3017 } 3018 } 3019 } 3020 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3021 // SELinux domain. 3022 setting.fixSeInfoLocked(); 3023 } 3024 3025 // Now that we know all the packages we are keeping, 3026 // read and update their last usage times. 3027 mPackageUsage.read(mPackages); 3028 mCompilerStats.read(); 3029 3030 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3031 SystemClock.uptimeMillis()); 3032 Slog.i(TAG, "Time to scan packages: " 3033 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3034 + " seconds"); 3035 3036 // If the platform SDK has changed since the last time we booted, 3037 // we need to re-grant app permission to catch any new ones that 3038 // appear. This is really a hack, and means that apps can in some 3039 // cases get permissions that the user didn't initially explicitly 3040 // allow... it would be nice to have some better way to handle 3041 // this situation. 3042 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3043 if (sdkUpdated) { 3044 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3045 + mSdkVersion + "; regranting permissions for internal storage"); 3046 } 3047 mPermissionManager.updateAllPermissions( 3048 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3049 mPermissionCallback); 3050 ver.sdkVersion = mSdkVersion; 3051 3052 // If this is the first boot or an update from pre-M, and it is a normal 3053 // boot, then we need to initialize the default preferred apps across 3054 // all defined users. 3055 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3056 for (UserInfo user : sUserManager.getUsers(true)) { 3057 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3058 applyFactoryDefaultBrowserLPw(user.id); 3059 primeDomainVerificationsLPw(user.id); 3060 } 3061 } 3062 3063 // Prepare storage for system user really early during boot, 3064 // since core system apps like SettingsProvider and SystemUI 3065 // can't wait for user to start 3066 final int storageFlags; 3067 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3068 storageFlags = StorageManager.FLAG_STORAGE_DE; 3069 } else { 3070 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3071 } 3072 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3073 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3074 true /* onlyCoreApps */); 3075 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3076 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3077 Trace.TRACE_TAG_PACKAGE_MANAGER); 3078 traceLog.traceBegin("AppDataFixup"); 3079 try { 3080 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3081 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3082 } catch (InstallerException e) { 3083 Slog.w(TAG, "Trouble fixing GIDs", e); 3084 } 3085 traceLog.traceEnd(); 3086 3087 traceLog.traceBegin("AppDataPrepare"); 3088 if (deferPackages == null || deferPackages.isEmpty()) { 3089 return; 3090 } 3091 int count = 0; 3092 for (String pkgName : deferPackages) { 3093 PackageParser.Package pkg = null; 3094 synchronized (mPackages) { 3095 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3096 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3097 pkg = ps.pkg; 3098 } 3099 } 3100 if (pkg != null) { 3101 synchronized (mInstallLock) { 3102 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3103 true /* maybeMigrateAppData */); 3104 } 3105 count++; 3106 } 3107 } 3108 traceLog.traceEnd(); 3109 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3110 }, "prepareAppData"); 3111 3112 // If this is first boot after an OTA, and a normal boot, then 3113 // we need to clear code cache directories. 3114 // Note that we do *not* clear the application profiles. These remain valid 3115 // across OTAs and are used to drive profile verification (post OTA) and 3116 // profile compilation (without waiting to collect a fresh set of profiles). 3117 if (mIsUpgrade && !onlyCore) { 3118 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3119 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3120 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3121 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3122 // No apps are running this early, so no need to freeze 3123 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3124 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3125 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3126 } 3127 } 3128 ver.fingerprint = Build.FINGERPRINT; 3129 } 3130 3131 checkDefaultBrowser(); 3132 3133 // clear only after permissions and other defaults have been updated 3134 mExistingSystemPackages.clear(); 3135 mPromoteSystemApps = false; 3136 3137 // All the changes are done during package scanning. 3138 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3139 3140 // can downgrade to reader 3141 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3142 mSettings.writeLPr(); 3143 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3144 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3145 SystemClock.uptimeMillis()); 3146 3147 if (!mOnlyCore) { 3148 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3149 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3150 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3151 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3152 if (mIntentFilterVerifierComponent != null) { 3153 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3154 mIntentFilterVerifierComponent); 3155 } else { 3156 mIntentFilterVerifier = null; 3157 } 3158 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3159 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3160 SharedLibraryInfo.VERSION_UNDEFINED); 3161 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3162 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3163 SharedLibraryInfo.VERSION_UNDEFINED); 3164 } else { 3165 mRequiredVerifierPackage = null; 3166 mRequiredInstallerPackage = null; 3167 mRequiredUninstallerPackage = null; 3168 mIntentFilterVerifierComponent = null; 3169 mIntentFilterVerifier = null; 3170 mServicesSystemSharedLibraryPackageName = null; 3171 mSharedSystemSharedLibraryPackageName = null; 3172 } 3173 3174 mInstallerService = new PackageInstallerService(context, this); 3175 final Pair<ComponentName, String> instantAppResolverComponent = 3176 getInstantAppResolverLPr(); 3177 if (instantAppResolverComponent != null) { 3178 if (DEBUG_INSTANT) { 3179 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3180 } 3181 mInstantAppResolverConnection = new InstantAppResolverConnection( 3182 mContext, instantAppResolverComponent.first, 3183 instantAppResolverComponent.second); 3184 mInstantAppResolverSettingsComponent = 3185 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3186 } else { 3187 mInstantAppResolverConnection = null; 3188 mInstantAppResolverSettingsComponent = null; 3189 } 3190 updateInstantAppInstallerLocked(null); 3191 3192 // Read and update the usage of dex files. 3193 // Do this at the end of PM init so that all the packages have their 3194 // data directory reconciled. 3195 // At this point we know the code paths of the packages, so we can validate 3196 // the disk file and build the internal cache. 3197 // The usage file is expected to be small so loading and verifying it 3198 // should take a fairly small time compare to the other activities (e.g. package 3199 // scanning). 3200 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3201 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3202 for (int userId : currentUserIds) { 3203 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3204 } 3205 mDexManager.load(userPackages); 3206 if (mIsUpgrade) { 3207 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3208 (int) (SystemClock.uptimeMillis() - startTime)); 3209 } 3210 } // synchronized (mPackages) 3211 } // synchronized (mInstallLock) 3212 3213 // Now after opening every single application zip, make sure they 3214 // are all flushed. Not really needed, but keeps things nice and 3215 // tidy. 3216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3217 Runtime.getRuntime().gc(); 3218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3219 3220 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3221 FallbackCategoryProvider.loadFallbacks(); 3222 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3223 3224 // The initial scanning above does many calls into installd while 3225 // holding the mPackages lock, but we're mostly interested in yelling 3226 // once we have a booted system. 3227 mInstaller.setWarnIfHeld(mPackages); 3228 3229 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3230 } 3231 3232 /** 3233 * Uncompress and install stub applications. 3234 * <p>In order to save space on the system partition, some applications are shipped in a 3235 * compressed form. In addition the compressed bits for the full application, the 3236 * system image contains a tiny stub comprised of only the Android manifest. 3237 * <p>During the first boot, attempt to uncompress and install the full application. If 3238 * the application can't be installed for any reason, disable the stub and prevent 3239 * uncompressing the full application during future boots. 3240 * <p>In order to forcefully attempt an installation of a full application, go to app 3241 * settings and enable the application. 3242 */ 3243 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3244 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3245 final String pkgName = stubSystemApps.get(i); 3246 // skip if the system package is already disabled 3247 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3248 stubSystemApps.remove(i); 3249 continue; 3250 } 3251 // skip if the package isn't installed (?!); this should never happen 3252 final PackageParser.Package pkg = mPackages.get(pkgName); 3253 if (pkg == null) { 3254 stubSystemApps.remove(i); 3255 continue; 3256 } 3257 // skip if the package has been disabled by the user 3258 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3259 if (ps != null) { 3260 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3261 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3262 stubSystemApps.remove(i); 3263 continue; 3264 } 3265 } 3266 3267 if (DEBUG_COMPRESSION) { 3268 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3269 } 3270 3271 // uncompress the binary to its eventual destination on /data 3272 final File scanFile = decompressPackage(pkg); 3273 if (scanFile == null) { 3274 continue; 3275 } 3276 3277 // install the package to replace the stub on /system 3278 try { 3279 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3280 removePackageLI(pkg, true /*chatty*/); 3281 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3282 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3283 UserHandle.USER_SYSTEM, "android"); 3284 stubSystemApps.remove(i); 3285 continue; 3286 } catch (PackageManagerException e) { 3287 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3288 } 3289 3290 // any failed attempt to install the package will be cleaned up later 3291 } 3292 3293 // disable any stub still left; these failed to install the full application 3294 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3295 final String pkgName = stubSystemApps.get(i); 3296 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3297 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3298 UserHandle.USER_SYSTEM, "android"); 3299 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3300 } 3301 } 3302 3303 /** 3304 * Decompresses the given package on the system image onto 3305 * the /data partition. 3306 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3307 */ 3308 private File decompressPackage(PackageParser.Package pkg) { 3309 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3310 if (compressedFiles == null || compressedFiles.length == 0) { 3311 if (DEBUG_COMPRESSION) { 3312 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3313 } 3314 return null; 3315 } 3316 final File dstCodePath = 3317 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3318 int ret = PackageManager.INSTALL_SUCCEEDED; 3319 try { 3320 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3321 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3322 for (File srcFile : compressedFiles) { 3323 final String srcFileName = srcFile.getName(); 3324 final String dstFileName = srcFileName.substring( 3325 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3326 final File dstFile = new File(dstCodePath, dstFileName); 3327 ret = decompressFile(srcFile, dstFile); 3328 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3329 logCriticalInfo(Log.ERROR, "Failed to decompress" 3330 + "; pkg: " + pkg.packageName 3331 + ", file: " + dstFileName); 3332 break; 3333 } 3334 } 3335 } catch (ErrnoException e) { 3336 logCriticalInfo(Log.ERROR, "Failed to decompress" 3337 + "; pkg: " + pkg.packageName 3338 + ", err: " + e.errno); 3339 } 3340 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3341 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3342 NativeLibraryHelper.Handle handle = null; 3343 try { 3344 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3345 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3346 null /*abiOverride*/); 3347 } catch (IOException e) { 3348 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3349 + "; pkg: " + pkg.packageName); 3350 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3351 } finally { 3352 IoUtils.closeQuietly(handle); 3353 } 3354 } 3355 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3356 if (dstCodePath == null || !dstCodePath.exists()) { 3357 return null; 3358 } 3359 removeCodePathLI(dstCodePath); 3360 return null; 3361 } 3362 3363 return dstCodePath; 3364 } 3365 3366 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3367 // we're only interested in updating the installer appliction when 1) it's not 3368 // already set or 2) the modified package is the installer 3369 if (mInstantAppInstallerActivity != null 3370 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3371 .equals(modifiedPackage)) { 3372 return; 3373 } 3374 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3375 } 3376 3377 private static File preparePackageParserCache(boolean isUpgrade) { 3378 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3379 return null; 3380 } 3381 3382 // Disable package parsing on eng builds to allow for faster incremental development. 3383 if (Build.IS_ENG) { 3384 return null; 3385 } 3386 3387 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3388 Slog.i(TAG, "Disabling package parser cache due to system property."); 3389 return null; 3390 } 3391 3392 // The base directory for the package parser cache lives under /data/system/. 3393 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3394 "package_cache"); 3395 if (cacheBaseDir == null) { 3396 return null; 3397 } 3398 3399 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3400 // This also serves to "GC" unused entries when the package cache version changes (which 3401 // can only happen during upgrades). 3402 if (isUpgrade) { 3403 FileUtils.deleteContents(cacheBaseDir); 3404 } 3405 3406 3407 // Return the versioned package cache directory. This is something like 3408 // "/data/system/package_cache/1" 3409 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3410 3411 if (cacheDir == null) { 3412 // Something went wrong. Attempt to delete everything and return. 3413 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3414 FileUtils.deleteContentsAndDir(cacheBaseDir); 3415 return null; 3416 } 3417 3418 // The following is a workaround to aid development on non-numbered userdebug 3419 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3420 // the system partition is newer. 3421 // 3422 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3423 // that starts with "eng." to signify that this is an engineering build and not 3424 // destined for release. 3425 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3426 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3427 3428 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3429 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3430 // in general and should not be used for production changes. In this specific case, 3431 // we know that they will work. 3432 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3433 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3434 FileUtils.deleteContents(cacheBaseDir); 3435 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3436 } 3437 } 3438 3439 return cacheDir; 3440 } 3441 3442 @Override 3443 public boolean isFirstBoot() { 3444 // allow instant applications 3445 return mFirstBoot; 3446 } 3447 3448 @Override 3449 public boolean isOnlyCoreApps() { 3450 // allow instant applications 3451 return mOnlyCore; 3452 } 3453 3454 @Override 3455 public boolean isUpgrade() { 3456 // allow instant applications 3457 // The system property allows testing ota flow when upgraded to the same image. 3458 return mIsUpgrade || SystemProperties.getBoolean( 3459 "persist.pm.mock-upgrade", false /* default */); 3460 } 3461 3462 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3463 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3464 3465 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3466 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3467 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3468 if (matches.size() == 1) { 3469 return matches.get(0).getComponentInfo().packageName; 3470 } else if (matches.size() == 0) { 3471 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3472 return null; 3473 } 3474 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3475 } 3476 3477 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3478 synchronized (mPackages) { 3479 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3480 if (libraryEntry == null) { 3481 throw new IllegalStateException("Missing required shared library:" + name); 3482 } 3483 return libraryEntry.apk; 3484 } 3485 } 3486 3487 private @NonNull String getRequiredInstallerLPr() { 3488 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3489 intent.addCategory(Intent.CATEGORY_DEFAULT); 3490 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3491 3492 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3493 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3494 UserHandle.USER_SYSTEM); 3495 if (matches.size() == 1) { 3496 ResolveInfo resolveInfo = matches.get(0); 3497 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3498 throw new RuntimeException("The installer must be a privileged app"); 3499 } 3500 return matches.get(0).getComponentInfo().packageName; 3501 } else { 3502 throw new RuntimeException("There must be exactly one installer; found " + matches); 3503 } 3504 } 3505 3506 private @NonNull String getRequiredUninstallerLPr() { 3507 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3508 intent.addCategory(Intent.CATEGORY_DEFAULT); 3509 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3510 3511 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3512 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3513 UserHandle.USER_SYSTEM); 3514 if (resolveInfo == null || 3515 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3516 throw new RuntimeException("There must be exactly one uninstaller; found " 3517 + resolveInfo); 3518 } 3519 return resolveInfo.getComponentInfo().packageName; 3520 } 3521 3522 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3523 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3524 3525 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3526 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3527 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3528 ResolveInfo best = null; 3529 final int N = matches.size(); 3530 for (int i = 0; i < N; i++) { 3531 final ResolveInfo cur = matches.get(i); 3532 final String packageName = cur.getComponentInfo().packageName; 3533 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3534 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3535 continue; 3536 } 3537 3538 if (best == null || cur.priority > best.priority) { 3539 best = cur; 3540 } 3541 } 3542 3543 if (best != null) { 3544 return best.getComponentInfo().getComponentName(); 3545 } 3546 Slog.w(TAG, "Intent filter verifier not found"); 3547 return null; 3548 } 3549 3550 @Override 3551 public @Nullable ComponentName getInstantAppResolverComponent() { 3552 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3553 return null; 3554 } 3555 synchronized (mPackages) { 3556 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3557 if (instantAppResolver == null) { 3558 return null; 3559 } 3560 return instantAppResolver.first; 3561 } 3562 } 3563 3564 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3565 final String[] packageArray = 3566 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3567 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3568 if (DEBUG_INSTANT) { 3569 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3570 } 3571 return null; 3572 } 3573 3574 final int callingUid = Binder.getCallingUid(); 3575 final int resolveFlags = 3576 MATCH_DIRECT_BOOT_AWARE 3577 | MATCH_DIRECT_BOOT_UNAWARE 3578 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3579 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3580 final Intent resolverIntent = new Intent(actionName); 3581 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3582 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3583 final int N = resolvers.size(); 3584 if (N == 0) { 3585 if (DEBUG_INSTANT) { 3586 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3587 } 3588 return null; 3589 } 3590 3591 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3592 for (int i = 0; i < N; i++) { 3593 final ResolveInfo info = resolvers.get(i); 3594 3595 if (info.serviceInfo == null) { 3596 continue; 3597 } 3598 3599 final String packageName = info.serviceInfo.packageName; 3600 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3601 if (DEBUG_INSTANT) { 3602 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3603 + " pkg: " + packageName + ", info:" + info); 3604 } 3605 continue; 3606 } 3607 3608 if (DEBUG_INSTANT) { 3609 Slog.v(TAG, "Ephemeral resolver found;" 3610 + " pkg: " + packageName + ", info:" + info); 3611 } 3612 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3613 } 3614 if (DEBUG_INSTANT) { 3615 Slog.v(TAG, "Ephemeral resolver NOT found"); 3616 } 3617 return null; 3618 } 3619 3620 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3621 String[] orderedActions = Build.IS_ENG 3622 ? new String[]{ 3623 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3624 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3625 : new String[]{ 3626 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3627 3628 final int resolveFlags = 3629 MATCH_DIRECT_BOOT_AWARE 3630 | MATCH_DIRECT_BOOT_UNAWARE 3631 | Intent.FLAG_IGNORE_EPHEMERAL 3632 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3633 final Intent intent = new Intent(); 3634 intent.addCategory(Intent.CATEGORY_DEFAULT); 3635 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3636 List<ResolveInfo> matches = null; 3637 for (String action : orderedActions) { 3638 intent.setAction(action); 3639 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3640 resolveFlags, UserHandle.USER_SYSTEM); 3641 if (matches.isEmpty()) { 3642 if (DEBUG_INSTANT) { 3643 Slog.d(TAG, "Instant App installer not found with " + action); 3644 } 3645 } else { 3646 break; 3647 } 3648 } 3649 Iterator<ResolveInfo> iter = matches.iterator(); 3650 while (iter.hasNext()) { 3651 final ResolveInfo rInfo = iter.next(); 3652 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3653 if (ps != null) { 3654 final PermissionsState permissionsState = ps.getPermissionsState(); 3655 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3656 || Build.IS_ENG) { 3657 continue; 3658 } 3659 } 3660 iter.remove(); 3661 } 3662 if (matches.size() == 0) { 3663 return null; 3664 } else if (matches.size() == 1) { 3665 return (ActivityInfo) matches.get(0).getComponentInfo(); 3666 } else { 3667 throw new RuntimeException( 3668 "There must be at most one ephemeral installer; found " + matches); 3669 } 3670 } 3671 3672 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3673 @NonNull ComponentName resolver) { 3674 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3675 .addCategory(Intent.CATEGORY_DEFAULT) 3676 .setPackage(resolver.getPackageName()); 3677 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3678 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3679 UserHandle.USER_SYSTEM); 3680 if (matches.isEmpty()) { 3681 return null; 3682 } 3683 return matches.get(0).getComponentInfo().getComponentName(); 3684 } 3685 3686 private void primeDomainVerificationsLPw(int userId) { 3687 if (DEBUG_DOMAIN_VERIFICATION) { 3688 Slog.d(TAG, "Priming domain verifications in user " + userId); 3689 } 3690 3691 SystemConfig systemConfig = SystemConfig.getInstance(); 3692 ArraySet<String> packages = systemConfig.getLinkedApps(); 3693 3694 for (String packageName : packages) { 3695 PackageParser.Package pkg = mPackages.get(packageName); 3696 if (pkg != null) { 3697 if (!pkg.isSystem()) { 3698 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3699 continue; 3700 } 3701 3702 ArraySet<String> domains = null; 3703 for (PackageParser.Activity a : pkg.activities) { 3704 for (ActivityIntentInfo filter : a.intents) { 3705 if (hasValidDomains(filter)) { 3706 if (domains == null) { 3707 domains = new ArraySet<String>(); 3708 } 3709 domains.addAll(filter.getHostsList()); 3710 } 3711 } 3712 } 3713 3714 if (domains != null && domains.size() > 0) { 3715 if (DEBUG_DOMAIN_VERIFICATION) { 3716 Slog.v(TAG, " + " + packageName); 3717 } 3718 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3719 // state w.r.t. the formal app-linkage "no verification attempted" state; 3720 // and then 'always' in the per-user state actually used for intent resolution. 3721 final IntentFilterVerificationInfo ivi; 3722 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3723 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3724 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3725 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3726 } else { 3727 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3728 + "' does not handle web links"); 3729 } 3730 } else { 3731 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3732 } 3733 } 3734 3735 scheduleWritePackageRestrictionsLocked(userId); 3736 scheduleWriteSettingsLocked(); 3737 } 3738 3739 private void applyFactoryDefaultBrowserLPw(int userId) { 3740 // The default browser app's package name is stored in a string resource, 3741 // with a product-specific overlay used for vendor customization. 3742 String browserPkg = mContext.getResources().getString( 3743 com.android.internal.R.string.default_browser); 3744 if (!TextUtils.isEmpty(browserPkg)) { 3745 // non-empty string => required to be a known package 3746 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3747 if (ps == null) { 3748 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3749 browserPkg = null; 3750 } else { 3751 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3752 } 3753 } 3754 3755 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3756 // default. If there's more than one, just leave everything alone. 3757 if (browserPkg == null) { 3758 calculateDefaultBrowserLPw(userId); 3759 } 3760 } 3761 3762 private void calculateDefaultBrowserLPw(int userId) { 3763 List<String> allBrowsers = resolveAllBrowserApps(userId); 3764 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3765 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3766 } 3767 3768 private List<String> resolveAllBrowserApps(int userId) { 3769 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3770 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3771 PackageManager.MATCH_ALL, userId); 3772 3773 final int count = list.size(); 3774 List<String> result = new ArrayList<String>(count); 3775 for (int i=0; i<count; i++) { 3776 ResolveInfo info = list.get(i); 3777 if (info.activityInfo == null 3778 || !info.handleAllWebDataURI 3779 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3780 || result.contains(info.activityInfo.packageName)) { 3781 continue; 3782 } 3783 result.add(info.activityInfo.packageName); 3784 } 3785 3786 return result; 3787 } 3788 3789 private boolean packageIsBrowser(String packageName, int userId) { 3790 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3791 PackageManager.MATCH_ALL, userId); 3792 final int N = list.size(); 3793 for (int i = 0; i < N; i++) { 3794 ResolveInfo info = list.get(i); 3795 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3796 return true; 3797 } 3798 } 3799 return false; 3800 } 3801 3802 private void checkDefaultBrowser() { 3803 final int myUserId = UserHandle.myUserId(); 3804 final String packageName = getDefaultBrowserPackageName(myUserId); 3805 if (packageName != null) { 3806 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3807 if (info == null) { 3808 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3809 synchronized (mPackages) { 3810 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3811 } 3812 } 3813 } 3814 } 3815 3816 @Override 3817 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3818 throws RemoteException { 3819 try { 3820 return super.onTransact(code, data, reply, flags); 3821 } catch (RuntimeException e) { 3822 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3823 Slog.wtf(TAG, "Package Manager Crash", e); 3824 } 3825 throw e; 3826 } 3827 } 3828 3829 static int[] appendInts(int[] cur, int[] add) { 3830 if (add == null) return cur; 3831 if (cur == null) return add; 3832 final int N = add.length; 3833 for (int i=0; i<N; i++) { 3834 cur = appendInt(cur, add[i]); 3835 } 3836 return cur; 3837 } 3838 3839 /** 3840 * Returns whether or not a full application can see an instant application. 3841 * <p> 3842 * Currently, there are three cases in which this can occur: 3843 * <ol> 3844 * <li>The calling application is a "special" process. Special processes 3845 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3846 * <li>The calling application has the permission 3847 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3848 * <li>The calling application is the default launcher on the 3849 * system partition.</li> 3850 * </ol> 3851 */ 3852 private boolean canViewInstantApps(int callingUid, int userId) { 3853 if (callingUid < Process.FIRST_APPLICATION_UID) { 3854 return true; 3855 } 3856 if (mContext.checkCallingOrSelfPermission( 3857 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3858 return true; 3859 } 3860 if (mContext.checkCallingOrSelfPermission( 3861 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3862 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3863 if (homeComponent != null 3864 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3865 return true; 3866 } 3867 } 3868 return false; 3869 } 3870 3871 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3872 if (!sUserManager.exists(userId)) return null; 3873 if (ps == null) { 3874 return null; 3875 } 3876 final int callingUid = Binder.getCallingUid(); 3877 // Filter out ephemeral app metadata: 3878 // * The system/shell/root can see metadata for any app 3879 // * An installed app can see metadata for 1) other installed apps 3880 // and 2) ephemeral apps that have explicitly interacted with it 3881 // * Ephemeral apps can only see their own data and exposed installed apps 3882 // * Holding a signature permission allows seeing instant apps 3883 if (filterAppAccessLPr(ps, callingUid, userId)) { 3884 return null; 3885 } 3886 3887 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3888 && ps.isSystem()) { 3889 flags |= MATCH_ANY_USER; 3890 } 3891 3892 final PackageUserState state = ps.readUserState(userId); 3893 PackageParser.Package p = ps.pkg; 3894 if (p != null) { 3895 final PermissionsState permissionsState = ps.getPermissionsState(); 3896 3897 // Compute GIDs only if requested 3898 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3899 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3900 // Compute granted permissions only if package has requested permissions 3901 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3902 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3903 3904 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3905 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3906 3907 if (packageInfo == null) { 3908 return null; 3909 } 3910 3911 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3912 resolveExternalPackageNameLPr(p); 3913 3914 return packageInfo; 3915 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 3916 PackageInfo pi = new PackageInfo(); 3917 pi.packageName = ps.name; 3918 pi.setLongVersionCode(ps.versionCode); 3919 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 3920 pi.firstInstallTime = ps.firstInstallTime; 3921 pi.lastUpdateTime = ps.lastUpdateTime; 3922 3923 ApplicationInfo ai = new ApplicationInfo(); 3924 ai.packageName = ps.name; 3925 ai.uid = UserHandle.getUid(userId, ps.appId); 3926 ai.primaryCpuAbi = ps.primaryCpuAbiString; 3927 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 3928 ai.versionCode = ps.versionCode; 3929 ai.flags = ps.pkgFlags; 3930 ai.privateFlags = ps.pkgPrivateFlags; 3931 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 3932 3933 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 3934 + ps.name + "]. Provides a minimum info."); 3935 return pi; 3936 } else { 3937 return null; 3938 } 3939 } 3940 3941 @Override 3942 public void checkPackageStartable(String packageName, int userId) { 3943 final int callingUid = Binder.getCallingUid(); 3944 if (getInstantAppPackageName(callingUid) != null) { 3945 throw new SecurityException("Instant applications don't have access to this method"); 3946 } 3947 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3948 synchronized (mPackages) { 3949 final PackageSetting ps = mSettings.mPackages.get(packageName); 3950 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3951 throw new SecurityException("Package " + packageName + " was not found!"); 3952 } 3953 3954 if (!ps.getInstalled(userId)) { 3955 throw new SecurityException( 3956 "Package " + packageName + " was not installed for user " + userId + "!"); 3957 } 3958 3959 if (mSafeMode && !ps.isSystem()) { 3960 throw new SecurityException("Package " + packageName + " not a system app!"); 3961 } 3962 3963 if (mFrozenPackages.contains(packageName)) { 3964 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3965 } 3966 3967 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3968 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3969 } 3970 } 3971 } 3972 3973 @Override 3974 public boolean isPackageAvailable(String packageName, int userId) { 3975 if (!sUserManager.exists(userId)) return false; 3976 final int callingUid = Binder.getCallingUid(); 3977 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3978 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3979 synchronized (mPackages) { 3980 PackageParser.Package p = mPackages.get(packageName); 3981 if (p != null) { 3982 final PackageSetting ps = (PackageSetting) p.mExtras; 3983 if (filterAppAccessLPr(ps, callingUid, userId)) { 3984 return false; 3985 } 3986 if (ps != null) { 3987 final PackageUserState state = ps.readUserState(userId); 3988 if (state != null) { 3989 return PackageParser.isAvailable(state); 3990 } 3991 } 3992 } 3993 } 3994 return false; 3995 } 3996 3997 @Override 3998 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3999 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4000 flags, Binder.getCallingUid(), userId); 4001 } 4002 4003 @Override 4004 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4005 int flags, int userId) { 4006 return getPackageInfoInternal(versionedPackage.getPackageName(), 4007 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4008 } 4009 4010 /** 4011 * Important: The provided filterCallingUid is used exclusively to filter out packages 4012 * that can be seen based on user state. It's typically the original caller uid prior 4013 * to clearing. Because it can only be provided by trusted code, it's value can be 4014 * trusted and will be used as-is; unlike userId which will be validated by this method. 4015 */ 4016 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4017 int flags, int filterCallingUid, int userId) { 4018 if (!sUserManager.exists(userId)) return null; 4019 flags = updateFlagsForPackage(flags, userId, packageName); 4020 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4021 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4022 4023 // reader 4024 synchronized (mPackages) { 4025 // Normalize package name to handle renamed packages and static libs 4026 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4027 4028 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4029 if (matchFactoryOnly) { 4030 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4031 if (ps != null) { 4032 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4033 return null; 4034 } 4035 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4036 return null; 4037 } 4038 return generatePackageInfo(ps, flags, userId); 4039 } 4040 } 4041 4042 PackageParser.Package p = mPackages.get(packageName); 4043 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4044 return null; 4045 } 4046 if (DEBUG_PACKAGE_INFO) 4047 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4048 if (p != null) { 4049 final PackageSetting ps = (PackageSetting) p.mExtras; 4050 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4051 return null; 4052 } 4053 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4054 return null; 4055 } 4056 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4057 } 4058 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4059 final PackageSetting ps = mSettings.mPackages.get(packageName); 4060 if (ps == null) return null; 4061 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4062 return null; 4063 } 4064 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4065 return null; 4066 } 4067 return generatePackageInfo(ps, flags, userId); 4068 } 4069 } 4070 return null; 4071 } 4072 4073 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4074 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4075 return true; 4076 } 4077 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4078 return true; 4079 } 4080 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4081 return true; 4082 } 4083 return false; 4084 } 4085 4086 private boolean isComponentVisibleToInstantApp( 4087 @Nullable ComponentName component, @ComponentType int type) { 4088 if (type == TYPE_ACTIVITY) { 4089 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4090 if (activity == null) { 4091 return false; 4092 } 4093 final boolean visibleToInstantApp = 4094 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4095 final boolean explicitlyVisibleToInstantApp = 4096 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4097 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4098 } else if (type == TYPE_RECEIVER) { 4099 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4100 if (activity == null) { 4101 return false; 4102 } 4103 final boolean visibleToInstantApp = 4104 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4105 final boolean explicitlyVisibleToInstantApp = 4106 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4107 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4108 } else if (type == TYPE_SERVICE) { 4109 final PackageParser.Service service = mServices.mServices.get(component); 4110 return service != null 4111 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4112 : false; 4113 } else if (type == TYPE_PROVIDER) { 4114 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4115 return provider != null 4116 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4117 : false; 4118 } else if (type == TYPE_UNKNOWN) { 4119 return isComponentVisibleToInstantApp(component); 4120 } 4121 return false; 4122 } 4123 4124 /** 4125 * Returns whether or not access to the application should be filtered. 4126 * <p> 4127 * Access may be limited based upon whether the calling or target applications 4128 * are instant applications. 4129 * 4130 * @see #canAccessInstantApps(int) 4131 */ 4132 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4133 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4134 // if we're in an isolated process, get the real calling UID 4135 if (Process.isIsolated(callingUid)) { 4136 callingUid = mIsolatedOwners.get(callingUid); 4137 } 4138 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4139 final boolean callerIsInstantApp = instantAppPkgName != null; 4140 if (ps == null) { 4141 if (callerIsInstantApp) { 4142 // pretend the application exists, but, needs to be filtered 4143 return true; 4144 } 4145 return false; 4146 } 4147 // if the target and caller are the same application, don't filter 4148 if (isCallerSameApp(ps.name, callingUid)) { 4149 return false; 4150 } 4151 if (callerIsInstantApp) { 4152 // both caller and target are both instant, but, different applications, filter 4153 if (ps.getInstantApp(userId)) { 4154 return true; 4155 } 4156 // request for a specific component; if it hasn't been explicitly exposed through 4157 // property or instrumentation target, filter 4158 if (component != null) { 4159 final PackageParser.Instrumentation instrumentation = 4160 mInstrumentation.get(component); 4161 if (instrumentation != null 4162 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4163 return false; 4164 } 4165 return !isComponentVisibleToInstantApp(component, componentType); 4166 } 4167 // request for application; if no components have been explicitly exposed, filter 4168 return !ps.pkg.visibleToInstantApps; 4169 } 4170 if (ps.getInstantApp(userId)) { 4171 // caller can see all components of all instant applications, don't filter 4172 if (canViewInstantApps(callingUid, userId)) { 4173 return false; 4174 } 4175 // request for a specific instant application component, filter 4176 if (component != null) { 4177 return true; 4178 } 4179 // request for an instant application; if the caller hasn't been granted access, filter 4180 return !mInstantAppRegistry.isInstantAccessGranted( 4181 userId, UserHandle.getAppId(callingUid), ps.appId); 4182 } 4183 return false; 4184 } 4185 4186 /** 4187 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4188 */ 4189 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4190 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4191 } 4192 4193 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4194 int flags) { 4195 // Callers can access only the libs they depend on, otherwise they need to explicitly 4196 // ask for the shared libraries given the caller is allowed to access all static libs. 4197 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4198 // System/shell/root get to see all static libs 4199 final int appId = UserHandle.getAppId(uid); 4200 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4201 || appId == Process.ROOT_UID) { 4202 return false; 4203 } 4204 } 4205 4206 // No package means no static lib as it is always on internal storage 4207 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4208 return false; 4209 } 4210 4211 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4212 ps.pkg.staticSharedLibVersion); 4213 if (libEntry == null) { 4214 return false; 4215 } 4216 4217 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4218 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4219 if (uidPackageNames == null) { 4220 return true; 4221 } 4222 4223 for (String uidPackageName : uidPackageNames) { 4224 if (ps.name.equals(uidPackageName)) { 4225 return false; 4226 } 4227 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4228 if (uidPs != null) { 4229 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4230 libEntry.info.getName()); 4231 if (index < 0) { 4232 continue; 4233 } 4234 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4235 return false; 4236 } 4237 } 4238 } 4239 return true; 4240 } 4241 4242 @Override 4243 public String[] currentToCanonicalPackageNames(String[] names) { 4244 final int callingUid = Binder.getCallingUid(); 4245 if (getInstantAppPackageName(callingUid) != null) { 4246 return names; 4247 } 4248 final String[] out = new String[names.length]; 4249 // reader 4250 synchronized (mPackages) { 4251 final int callingUserId = UserHandle.getUserId(callingUid); 4252 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4253 for (int i=names.length-1; i>=0; i--) { 4254 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4255 boolean translateName = false; 4256 if (ps != null && ps.realName != null) { 4257 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4258 translateName = !targetIsInstantApp 4259 || canViewInstantApps 4260 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4261 UserHandle.getAppId(callingUid), ps.appId); 4262 } 4263 out[i] = translateName ? ps.realName : names[i]; 4264 } 4265 } 4266 return out; 4267 } 4268 4269 @Override 4270 public String[] canonicalToCurrentPackageNames(String[] names) { 4271 final int callingUid = Binder.getCallingUid(); 4272 if (getInstantAppPackageName(callingUid) != null) { 4273 return names; 4274 } 4275 final String[] out = new String[names.length]; 4276 // reader 4277 synchronized (mPackages) { 4278 final int callingUserId = UserHandle.getUserId(callingUid); 4279 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4280 for (int i=names.length-1; i>=0; i--) { 4281 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4282 boolean translateName = false; 4283 if (cur != null) { 4284 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4285 final boolean targetIsInstantApp = 4286 ps != null && ps.getInstantApp(callingUserId); 4287 translateName = !targetIsInstantApp 4288 || canViewInstantApps 4289 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4290 UserHandle.getAppId(callingUid), ps.appId); 4291 } 4292 out[i] = translateName ? cur : names[i]; 4293 } 4294 } 4295 return out; 4296 } 4297 4298 @Override 4299 public int getPackageUid(String packageName, int flags, int userId) { 4300 if (!sUserManager.exists(userId)) return -1; 4301 final int callingUid = Binder.getCallingUid(); 4302 flags = updateFlagsForPackage(flags, userId, packageName); 4303 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4304 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4305 4306 // reader 4307 synchronized (mPackages) { 4308 final PackageParser.Package p = mPackages.get(packageName); 4309 if (p != null && p.isMatch(flags)) { 4310 PackageSetting ps = (PackageSetting) p.mExtras; 4311 if (filterAppAccessLPr(ps, callingUid, userId)) { 4312 return -1; 4313 } 4314 return UserHandle.getUid(userId, p.applicationInfo.uid); 4315 } 4316 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4317 final PackageSetting ps = mSettings.mPackages.get(packageName); 4318 if (ps != null && ps.isMatch(flags) 4319 && !filterAppAccessLPr(ps, callingUid, userId)) { 4320 return UserHandle.getUid(userId, ps.appId); 4321 } 4322 } 4323 } 4324 4325 return -1; 4326 } 4327 4328 @Override 4329 public int[] getPackageGids(String packageName, int flags, int userId) { 4330 if (!sUserManager.exists(userId)) return null; 4331 final int callingUid = Binder.getCallingUid(); 4332 flags = updateFlagsForPackage(flags, userId, packageName); 4333 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4334 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4335 4336 // reader 4337 synchronized (mPackages) { 4338 final PackageParser.Package p = mPackages.get(packageName); 4339 if (p != null && p.isMatch(flags)) { 4340 PackageSetting ps = (PackageSetting) p.mExtras; 4341 if (filterAppAccessLPr(ps, callingUid, userId)) { 4342 return null; 4343 } 4344 // TODO: Shouldn't this be checking for package installed state for userId and 4345 // return null? 4346 return ps.getPermissionsState().computeGids(userId); 4347 } 4348 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4349 final PackageSetting ps = mSettings.mPackages.get(packageName); 4350 if (ps != null && ps.isMatch(flags) 4351 && !filterAppAccessLPr(ps, callingUid, userId)) { 4352 return ps.getPermissionsState().computeGids(userId); 4353 } 4354 } 4355 } 4356 4357 return null; 4358 } 4359 4360 @Override 4361 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4362 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4363 } 4364 4365 @Override 4366 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4367 int flags) { 4368 final List<PermissionInfo> permissionList = 4369 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4370 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4371 } 4372 4373 @Override 4374 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4375 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4376 } 4377 4378 @Override 4379 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4380 final List<PermissionGroupInfo> permissionList = 4381 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4382 return (permissionList == null) 4383 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4384 } 4385 4386 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4387 int filterCallingUid, int userId) { 4388 if (!sUserManager.exists(userId)) return null; 4389 PackageSetting ps = mSettings.mPackages.get(packageName); 4390 if (ps != null) { 4391 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4392 return null; 4393 } 4394 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4395 return null; 4396 } 4397 if (ps.pkg == null) { 4398 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4399 if (pInfo != null) { 4400 return pInfo.applicationInfo; 4401 } 4402 return null; 4403 } 4404 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4405 ps.readUserState(userId), userId); 4406 if (ai != null) { 4407 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4408 } 4409 return ai; 4410 } 4411 return null; 4412 } 4413 4414 @Override 4415 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4416 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4417 } 4418 4419 /** 4420 * Important: The provided filterCallingUid is used exclusively to filter out applications 4421 * that can be seen based on user state. It's typically the original caller uid prior 4422 * to clearing. Because it can only be provided by trusted code, it's value can be 4423 * trusted and will be used as-is; unlike userId which will be validated by this method. 4424 */ 4425 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4426 int filterCallingUid, int userId) { 4427 if (!sUserManager.exists(userId)) return null; 4428 flags = updateFlagsForApplication(flags, userId, packageName); 4429 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4430 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4431 4432 // writer 4433 synchronized (mPackages) { 4434 // Normalize package name to handle renamed packages and static libs 4435 packageName = resolveInternalPackageNameLPr(packageName, 4436 PackageManager.VERSION_CODE_HIGHEST); 4437 4438 PackageParser.Package p = mPackages.get(packageName); 4439 if (DEBUG_PACKAGE_INFO) Log.v( 4440 TAG, "getApplicationInfo " + packageName 4441 + ": " + p); 4442 if (p != null) { 4443 PackageSetting ps = mSettings.mPackages.get(packageName); 4444 if (ps == null) return null; 4445 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4446 return null; 4447 } 4448 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4449 return null; 4450 } 4451 // Note: isEnabledLP() does not apply here - always return info 4452 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4453 p, flags, ps.readUserState(userId), userId); 4454 if (ai != null) { 4455 ai.packageName = resolveExternalPackageNameLPr(p); 4456 } 4457 return ai; 4458 } 4459 if ("android".equals(packageName)||"system".equals(packageName)) { 4460 return mAndroidApplication; 4461 } 4462 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4463 // Already generates the external package name 4464 return generateApplicationInfoFromSettingsLPw(packageName, 4465 flags, filterCallingUid, userId); 4466 } 4467 } 4468 return null; 4469 } 4470 4471 private String normalizePackageNameLPr(String packageName) { 4472 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4473 return normalizedPackageName != null ? normalizedPackageName : packageName; 4474 } 4475 4476 @Override 4477 public void deletePreloadsFileCache() { 4478 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4479 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4480 } 4481 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4482 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4483 FileUtils.deleteContents(dir); 4484 } 4485 4486 @Override 4487 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4488 final int storageFlags, final IPackageDataObserver observer) { 4489 mContext.enforceCallingOrSelfPermission( 4490 android.Manifest.permission.CLEAR_APP_CACHE, null); 4491 mHandler.post(() -> { 4492 boolean success = false; 4493 try { 4494 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4495 success = true; 4496 } catch (IOException e) { 4497 Slog.w(TAG, e); 4498 } 4499 if (observer != null) { 4500 try { 4501 observer.onRemoveCompleted(null, success); 4502 } catch (RemoteException e) { 4503 Slog.w(TAG, e); 4504 } 4505 } 4506 }); 4507 } 4508 4509 @Override 4510 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4511 final int storageFlags, final IntentSender pi) { 4512 mContext.enforceCallingOrSelfPermission( 4513 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4514 mHandler.post(() -> { 4515 boolean success = false; 4516 try { 4517 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4518 success = true; 4519 } catch (IOException e) { 4520 Slog.w(TAG, e); 4521 } 4522 if (pi != null) { 4523 try { 4524 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4525 } catch (SendIntentException e) { 4526 Slog.w(TAG, e); 4527 } 4528 } 4529 }); 4530 } 4531 4532 /** 4533 * Blocking call to clear various types of cached data across the system 4534 * until the requested bytes are available. 4535 */ 4536 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4537 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4538 final File file = storage.findPathForUuid(volumeUuid); 4539 if (file.getUsableSpace() >= bytes) return; 4540 4541 if (ENABLE_FREE_CACHE_V2) { 4542 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4543 volumeUuid); 4544 final boolean aggressive = (storageFlags 4545 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4546 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4547 4548 // 1. Pre-flight to determine if we have any chance to succeed 4549 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4550 if (internalVolume && (aggressive || SystemProperties 4551 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4552 deletePreloadsFileCache(); 4553 if (file.getUsableSpace() >= bytes) return; 4554 } 4555 4556 // 3. Consider parsed APK data (aggressive only) 4557 if (internalVolume && aggressive) { 4558 FileUtils.deleteContents(mCacheDir); 4559 if (file.getUsableSpace() >= bytes) return; 4560 } 4561 4562 // 4. Consider cached app data (above quotas) 4563 try { 4564 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4565 Installer.FLAG_FREE_CACHE_V2); 4566 } catch (InstallerException ignored) { 4567 } 4568 if (file.getUsableSpace() >= bytes) return; 4569 4570 // 5. Consider shared libraries with refcount=0 and age>min cache period 4571 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4572 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4573 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4574 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4575 return; 4576 } 4577 4578 // 6. Consider dexopt output (aggressive only) 4579 // TODO: Implement 4580 4581 // 7. Consider installed instant apps unused longer than min cache period 4582 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4583 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4584 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4585 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4586 return; 4587 } 4588 4589 // 8. Consider cached app data (below quotas) 4590 try { 4591 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4592 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4593 } catch (InstallerException ignored) { 4594 } 4595 if (file.getUsableSpace() >= bytes) return; 4596 4597 // 9. Consider DropBox entries 4598 // TODO: Implement 4599 4600 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4601 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4602 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4603 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4604 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4605 return; 4606 } 4607 } else { 4608 try { 4609 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4610 } catch (InstallerException ignored) { 4611 } 4612 if (file.getUsableSpace() >= bytes) return; 4613 } 4614 4615 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4616 } 4617 4618 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4619 throws IOException { 4620 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4621 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4622 4623 List<VersionedPackage> packagesToDelete = null; 4624 final long now = System.currentTimeMillis(); 4625 4626 synchronized (mPackages) { 4627 final int[] allUsers = sUserManager.getUserIds(); 4628 final int libCount = mSharedLibraries.size(); 4629 for (int i = 0; i < libCount; i++) { 4630 final LongSparseArray<SharedLibraryEntry> versionedLib 4631 = mSharedLibraries.valueAt(i); 4632 if (versionedLib == null) { 4633 continue; 4634 } 4635 final int versionCount = versionedLib.size(); 4636 for (int j = 0; j < versionCount; j++) { 4637 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4638 // Skip packages that are not static shared libs. 4639 if (!libInfo.isStatic()) { 4640 break; 4641 } 4642 // Important: We skip static shared libs used for some user since 4643 // in such a case we need to keep the APK on the device. The check for 4644 // a lib being used for any user is performed by the uninstall call. 4645 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4646 // Resolve the package name - we use synthetic package names internally 4647 final String internalPackageName = resolveInternalPackageNameLPr( 4648 declaringPackage.getPackageName(), 4649 declaringPackage.getLongVersionCode()); 4650 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4651 // Skip unused static shared libs cached less than the min period 4652 // to prevent pruning a lib needed by a subsequently installed package. 4653 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4654 continue; 4655 } 4656 if (packagesToDelete == null) { 4657 packagesToDelete = new ArrayList<>(); 4658 } 4659 packagesToDelete.add(new VersionedPackage(internalPackageName, 4660 declaringPackage.getLongVersionCode())); 4661 } 4662 } 4663 } 4664 4665 if (packagesToDelete != null) { 4666 final int packageCount = packagesToDelete.size(); 4667 for (int i = 0; i < packageCount; i++) { 4668 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4669 // Delete the package synchronously (will fail of the lib used for any user). 4670 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4671 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4672 == PackageManager.DELETE_SUCCEEDED) { 4673 if (volume.getUsableSpace() >= neededSpace) { 4674 return true; 4675 } 4676 } 4677 } 4678 } 4679 4680 return false; 4681 } 4682 4683 /** 4684 * Update given flags based on encryption status of current user. 4685 */ 4686 private int updateFlags(int flags, int userId) { 4687 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4688 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4689 // Caller expressed an explicit opinion about what encryption 4690 // aware/unaware components they want to see, so fall through and 4691 // give them what they want 4692 } else { 4693 // Caller expressed no opinion, so match based on user state 4694 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4695 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4696 } else { 4697 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4698 } 4699 } 4700 return flags; 4701 } 4702 4703 private UserManagerInternal getUserManagerInternal() { 4704 if (mUserManagerInternal == null) { 4705 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4706 } 4707 return mUserManagerInternal; 4708 } 4709 4710 private ActivityManagerInternal getActivityManagerInternal() { 4711 if (mActivityManagerInternal == null) { 4712 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4713 } 4714 return mActivityManagerInternal; 4715 } 4716 4717 4718 private DeviceIdleController.LocalService getDeviceIdleController() { 4719 if (mDeviceIdleController == null) { 4720 mDeviceIdleController = 4721 LocalServices.getService(DeviceIdleController.LocalService.class); 4722 } 4723 return mDeviceIdleController; 4724 } 4725 4726 /** 4727 * Update given flags when being used to request {@link PackageInfo}. 4728 */ 4729 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4730 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4731 boolean triaged = true; 4732 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4733 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4734 // Caller is asking for component details, so they'd better be 4735 // asking for specific encryption matching behavior, or be triaged 4736 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4737 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4738 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4739 triaged = false; 4740 } 4741 } 4742 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4743 | PackageManager.MATCH_SYSTEM_ONLY 4744 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4745 triaged = false; 4746 } 4747 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4748 mPermissionManager.enforceCrossUserPermission( 4749 Binder.getCallingUid(), userId, false, false, 4750 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4751 + Debug.getCallers(5)); 4752 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4753 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4754 // If the caller wants all packages and has a restricted profile associated with it, 4755 // then match all users. This is to make sure that launchers that need to access work 4756 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4757 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4758 flags |= PackageManager.MATCH_ANY_USER; 4759 } 4760 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4761 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4762 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4763 } 4764 return updateFlags(flags, userId); 4765 } 4766 4767 /** 4768 * Update given flags when being used to request {@link ApplicationInfo}. 4769 */ 4770 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4771 return updateFlagsForPackage(flags, userId, cookie); 4772 } 4773 4774 /** 4775 * Update given flags when being used to request {@link ComponentInfo}. 4776 */ 4777 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4778 if (cookie instanceof Intent) { 4779 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4780 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4781 } 4782 } 4783 4784 boolean triaged = true; 4785 // Caller is asking for component details, so they'd better be 4786 // asking for specific encryption matching behavior, or be triaged 4787 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4788 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4789 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4790 triaged = false; 4791 } 4792 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4793 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4794 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4795 } 4796 4797 return updateFlags(flags, userId); 4798 } 4799 4800 /** 4801 * Update given intent when being used to request {@link ResolveInfo}. 4802 */ 4803 private Intent updateIntentForResolve(Intent intent) { 4804 if (intent.getSelector() != null) { 4805 intent = intent.getSelector(); 4806 } 4807 if (DEBUG_PREFERRED) { 4808 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4809 } 4810 return intent; 4811 } 4812 4813 /** 4814 * Update given flags when being used to request {@link ResolveInfo}. 4815 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4816 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4817 * flag set. However, this flag is only honoured in three circumstances: 4818 * <ul> 4819 * <li>when called from a system process</li> 4820 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4821 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4822 * action and a {@code android.intent.category.BROWSABLE} category</li> 4823 * </ul> 4824 */ 4825 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4826 return updateFlagsForResolve(flags, userId, intent, callingUid, 4827 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4828 } 4829 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4830 boolean wantInstantApps) { 4831 return updateFlagsForResolve(flags, userId, intent, callingUid, 4832 wantInstantApps, false /*onlyExposedExplicitly*/); 4833 } 4834 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4835 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4836 // Safe mode means we shouldn't match any third-party components 4837 if (mSafeMode) { 4838 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4839 } 4840 if (getInstantAppPackageName(callingUid) != null) { 4841 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4842 if (onlyExposedExplicitly) { 4843 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4844 } 4845 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4846 flags |= PackageManager.MATCH_INSTANT; 4847 } else { 4848 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4849 final boolean allowMatchInstant = wantInstantApps 4850 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4851 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4852 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4853 if (!allowMatchInstant) { 4854 flags &= ~PackageManager.MATCH_INSTANT; 4855 } 4856 } 4857 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4858 } 4859 4860 @Override 4861 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4862 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4863 } 4864 4865 /** 4866 * Important: The provided filterCallingUid is used exclusively to filter out activities 4867 * that can be seen based on user state. It's typically the original caller uid prior 4868 * to clearing. Because it can only be provided by trusted code, it's value can be 4869 * trusted and will be used as-is; unlike userId which will be validated by this method. 4870 */ 4871 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4872 int filterCallingUid, int userId) { 4873 if (!sUserManager.exists(userId)) return null; 4874 flags = updateFlagsForComponent(flags, userId, component); 4875 4876 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4877 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4878 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4879 } 4880 4881 synchronized (mPackages) { 4882 PackageParser.Activity a = mActivities.mActivities.get(component); 4883 4884 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4885 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4886 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4887 if (ps == null) return null; 4888 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4889 return null; 4890 } 4891 return PackageParser.generateActivityInfo( 4892 a, flags, ps.readUserState(userId), userId); 4893 } 4894 if (mResolveComponentName.equals(component)) { 4895 return PackageParser.generateActivityInfo( 4896 mResolveActivity, flags, new PackageUserState(), userId); 4897 } 4898 } 4899 return null; 4900 } 4901 4902 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4903 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4904 return false; 4905 } 4906 final long token = Binder.clearCallingIdentity(); 4907 try { 4908 final int callingUserId = UserHandle.getUserId(callingUid); 4909 if (ActivityManager.getCurrentUser() != callingUserId) { 4910 return false; 4911 } 4912 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4913 } finally { 4914 Binder.restoreCallingIdentity(token); 4915 } 4916 } 4917 4918 @Override 4919 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4920 String resolvedType) { 4921 synchronized (mPackages) { 4922 if (component.equals(mResolveComponentName)) { 4923 // The resolver supports EVERYTHING! 4924 return true; 4925 } 4926 final int callingUid = Binder.getCallingUid(); 4927 final int callingUserId = UserHandle.getUserId(callingUid); 4928 PackageParser.Activity a = mActivities.mActivities.get(component); 4929 if (a == null) { 4930 return false; 4931 } 4932 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4933 if (ps == null) { 4934 return false; 4935 } 4936 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4937 return false; 4938 } 4939 for (int i=0; i<a.intents.size(); i++) { 4940 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4941 intent.getData(), intent.getCategories(), TAG) >= 0) { 4942 return true; 4943 } 4944 } 4945 return false; 4946 } 4947 } 4948 4949 @Override 4950 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4951 if (!sUserManager.exists(userId)) return null; 4952 final int callingUid = Binder.getCallingUid(); 4953 flags = updateFlagsForComponent(flags, userId, component); 4954 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4955 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4956 synchronized (mPackages) { 4957 PackageParser.Activity a = mReceivers.mActivities.get(component); 4958 if (DEBUG_PACKAGE_INFO) Log.v( 4959 TAG, "getReceiverInfo " + component + ": " + a); 4960 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4961 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4962 if (ps == null) return null; 4963 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4964 return null; 4965 } 4966 return PackageParser.generateActivityInfo( 4967 a, flags, ps.readUserState(userId), userId); 4968 } 4969 } 4970 return null; 4971 } 4972 4973 @Override 4974 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4975 int flags, int userId) { 4976 if (!sUserManager.exists(userId)) return null; 4977 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4978 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4979 return null; 4980 } 4981 4982 flags = updateFlagsForPackage(flags, userId, null); 4983 4984 final boolean canSeeStaticLibraries = 4985 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4986 == PERMISSION_GRANTED 4987 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4988 == PERMISSION_GRANTED 4989 || canRequestPackageInstallsInternal(packageName, 4990 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4991 false /* throwIfPermNotDeclared*/) 4992 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4993 == PERMISSION_GRANTED; 4994 4995 synchronized (mPackages) { 4996 List<SharedLibraryInfo> result = null; 4997 4998 final int libCount = mSharedLibraries.size(); 4999 for (int i = 0; i < libCount; i++) { 5000 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5001 if (versionedLib == null) { 5002 continue; 5003 } 5004 5005 final int versionCount = versionedLib.size(); 5006 for (int j = 0; j < versionCount; j++) { 5007 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 5008 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5009 break; 5010 } 5011 final long identity = Binder.clearCallingIdentity(); 5012 try { 5013 PackageInfo packageInfo = getPackageInfoVersioned( 5014 libInfo.getDeclaringPackage(), flags 5015 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5016 if (packageInfo == null) { 5017 continue; 5018 } 5019 } finally { 5020 Binder.restoreCallingIdentity(identity); 5021 } 5022 5023 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 5024 libInfo.getLongVersion(), libInfo.getType(), 5025 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 5026 flags, userId)); 5027 5028 if (result == null) { 5029 result = new ArrayList<>(); 5030 } 5031 result.add(resLibInfo); 5032 } 5033 } 5034 5035 return result != null ? new ParceledListSlice<>(result) : null; 5036 } 5037 } 5038 5039 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5040 SharedLibraryInfo libInfo, int flags, int userId) { 5041 List<VersionedPackage> versionedPackages = null; 5042 final int packageCount = mSettings.mPackages.size(); 5043 for (int i = 0; i < packageCount; i++) { 5044 PackageSetting ps = mSettings.mPackages.valueAt(i); 5045 5046 if (ps == null) { 5047 continue; 5048 } 5049 5050 if (!ps.getUserState().get(userId).isAvailable(flags)) { 5051 continue; 5052 } 5053 5054 final String libName = libInfo.getName(); 5055 if (libInfo.isStatic()) { 5056 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5057 if (libIdx < 0) { 5058 continue; 5059 } 5060 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5061 continue; 5062 } 5063 if (versionedPackages == null) { 5064 versionedPackages = new ArrayList<>(); 5065 } 5066 // If the dependent is a static shared lib, use the public package name 5067 String dependentPackageName = ps.name; 5068 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5069 dependentPackageName = ps.pkg.manifestPackageName; 5070 } 5071 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5072 } else if (ps.pkg != null) { 5073 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5074 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5075 if (versionedPackages == null) { 5076 versionedPackages = new ArrayList<>(); 5077 } 5078 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5079 } 5080 } 5081 } 5082 5083 return versionedPackages; 5084 } 5085 5086 @Override 5087 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5088 if (!sUserManager.exists(userId)) return null; 5089 final int callingUid = Binder.getCallingUid(); 5090 flags = updateFlagsForComponent(flags, userId, component); 5091 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5092 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5093 synchronized (mPackages) { 5094 PackageParser.Service s = mServices.mServices.get(component); 5095 if (DEBUG_PACKAGE_INFO) Log.v( 5096 TAG, "getServiceInfo " + component + ": " + s); 5097 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5098 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5099 if (ps == null) return null; 5100 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5101 return null; 5102 } 5103 return PackageParser.generateServiceInfo( 5104 s, flags, ps.readUserState(userId), userId); 5105 } 5106 } 5107 return null; 5108 } 5109 5110 @Override 5111 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5112 if (!sUserManager.exists(userId)) return null; 5113 final int callingUid = Binder.getCallingUid(); 5114 flags = updateFlagsForComponent(flags, userId, component); 5115 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5116 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5117 synchronized (mPackages) { 5118 PackageParser.Provider p = mProviders.mProviders.get(component); 5119 if (DEBUG_PACKAGE_INFO) Log.v( 5120 TAG, "getProviderInfo " + component + ": " + p); 5121 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5122 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5123 if (ps == null) return null; 5124 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5125 return null; 5126 } 5127 return PackageParser.generateProviderInfo( 5128 p, flags, ps.readUserState(userId), userId); 5129 } 5130 } 5131 return null; 5132 } 5133 5134 @Override 5135 public String[] getSystemSharedLibraryNames() { 5136 // allow instant applications 5137 synchronized (mPackages) { 5138 Set<String> libs = null; 5139 final int libCount = mSharedLibraries.size(); 5140 for (int i = 0; i < libCount; i++) { 5141 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5142 if (versionedLib == null) { 5143 continue; 5144 } 5145 final int versionCount = versionedLib.size(); 5146 for (int j = 0; j < versionCount; j++) { 5147 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5148 if (!libEntry.info.isStatic()) { 5149 if (libs == null) { 5150 libs = new ArraySet<>(); 5151 } 5152 libs.add(libEntry.info.getName()); 5153 break; 5154 } 5155 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5156 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5157 UserHandle.getUserId(Binder.getCallingUid()), 5158 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5159 if (libs == null) { 5160 libs = new ArraySet<>(); 5161 } 5162 libs.add(libEntry.info.getName()); 5163 break; 5164 } 5165 } 5166 } 5167 5168 if (libs != null) { 5169 String[] libsArray = new String[libs.size()]; 5170 libs.toArray(libsArray); 5171 return libsArray; 5172 } 5173 5174 return null; 5175 } 5176 } 5177 5178 @Override 5179 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5180 // allow instant applications 5181 synchronized (mPackages) { 5182 return mServicesSystemSharedLibraryPackageName; 5183 } 5184 } 5185 5186 @Override 5187 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5188 // allow instant applications 5189 synchronized (mPackages) { 5190 return mSharedSystemSharedLibraryPackageName; 5191 } 5192 } 5193 5194 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5195 for (int i = userList.length - 1; i >= 0; --i) { 5196 final int userId = userList[i]; 5197 // don't add instant app to the list of updates 5198 if (pkgSetting.getInstantApp(userId)) { 5199 continue; 5200 } 5201 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5202 if (changedPackages == null) { 5203 changedPackages = new SparseArray<>(); 5204 mChangedPackages.put(userId, changedPackages); 5205 } 5206 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5207 if (sequenceNumbers == null) { 5208 sequenceNumbers = new HashMap<>(); 5209 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5210 } 5211 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5212 if (sequenceNumber != null) { 5213 changedPackages.remove(sequenceNumber); 5214 } 5215 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5216 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5217 } 5218 mChangedPackagesSequenceNumber++; 5219 } 5220 5221 @Override 5222 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5223 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5224 return null; 5225 } 5226 synchronized (mPackages) { 5227 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5228 return null; 5229 } 5230 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5231 if (changedPackages == null) { 5232 return null; 5233 } 5234 final List<String> packageNames = 5235 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5236 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5237 final String packageName = changedPackages.get(i); 5238 if (packageName != null) { 5239 packageNames.add(packageName); 5240 } 5241 } 5242 return packageNames.isEmpty() 5243 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5244 } 5245 } 5246 5247 @Override 5248 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5249 // allow instant applications 5250 ArrayList<FeatureInfo> res; 5251 synchronized (mAvailableFeatures) { 5252 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5253 res.addAll(mAvailableFeatures.values()); 5254 } 5255 final FeatureInfo fi = new FeatureInfo(); 5256 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5257 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5258 res.add(fi); 5259 5260 return new ParceledListSlice<>(res); 5261 } 5262 5263 @Override 5264 public boolean hasSystemFeature(String name, int version) { 5265 // allow instant applications 5266 synchronized (mAvailableFeatures) { 5267 final FeatureInfo feat = mAvailableFeatures.get(name); 5268 if (feat == null) { 5269 return false; 5270 } else { 5271 return feat.version >= version; 5272 } 5273 } 5274 } 5275 5276 @Override 5277 public int checkPermission(String permName, String pkgName, int userId) { 5278 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5279 } 5280 5281 @Override 5282 public int checkUidPermission(String permName, int uid) { 5283 synchronized (mPackages) { 5284 final String[] packageNames = getPackagesForUid(uid); 5285 final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0) 5286 ? mPackages.get(packageNames[0]) 5287 : null; 5288 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5289 } 5290 } 5291 5292 @Override 5293 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5294 if (UserHandle.getCallingUserId() != userId) { 5295 mContext.enforceCallingPermission( 5296 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5297 "isPermissionRevokedByPolicy for user " + userId); 5298 } 5299 5300 if (checkPermission(permission, packageName, userId) 5301 == PackageManager.PERMISSION_GRANTED) { 5302 return false; 5303 } 5304 5305 final int callingUid = Binder.getCallingUid(); 5306 if (getInstantAppPackageName(callingUid) != null) { 5307 if (!isCallerSameApp(packageName, callingUid)) { 5308 return false; 5309 } 5310 } else { 5311 if (isInstantApp(packageName, userId)) { 5312 return false; 5313 } 5314 } 5315 5316 final long identity = Binder.clearCallingIdentity(); 5317 try { 5318 final int flags = getPermissionFlags(permission, packageName, userId); 5319 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5320 } finally { 5321 Binder.restoreCallingIdentity(identity); 5322 } 5323 } 5324 5325 @Override 5326 public String getPermissionControllerPackageName() { 5327 synchronized (mPackages) { 5328 return mRequiredInstallerPackage; 5329 } 5330 } 5331 5332 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5333 return mPermissionManager.addDynamicPermission( 5334 info, async, getCallingUid(), new PermissionCallback() { 5335 @Override 5336 public void onPermissionChanged() { 5337 if (!async) { 5338 mSettings.writeLPr(); 5339 } else { 5340 scheduleWriteSettingsLocked(); 5341 } 5342 } 5343 }); 5344 } 5345 5346 @Override 5347 public boolean addPermission(PermissionInfo info) { 5348 synchronized (mPackages) { 5349 return addDynamicPermission(info, false); 5350 } 5351 } 5352 5353 @Override 5354 public boolean addPermissionAsync(PermissionInfo info) { 5355 synchronized (mPackages) { 5356 return addDynamicPermission(info, true); 5357 } 5358 } 5359 5360 @Override 5361 public void removePermission(String permName) { 5362 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5363 } 5364 5365 @Override 5366 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5367 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5368 getCallingUid(), userId, mPermissionCallback); 5369 } 5370 5371 @Override 5372 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5373 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5374 getCallingUid(), userId, mPermissionCallback); 5375 } 5376 5377 @Override 5378 public void resetRuntimePermissions() { 5379 mContext.enforceCallingOrSelfPermission( 5380 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5381 "revokeRuntimePermission"); 5382 5383 int callingUid = Binder.getCallingUid(); 5384 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5385 mContext.enforceCallingOrSelfPermission( 5386 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5387 "resetRuntimePermissions"); 5388 } 5389 5390 synchronized (mPackages) { 5391 mPermissionManager.updateAllPermissions( 5392 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5393 mPermissionCallback); 5394 for (int userId : UserManagerService.getInstance().getUserIds()) { 5395 final int packageCount = mPackages.size(); 5396 for (int i = 0; i < packageCount; i++) { 5397 PackageParser.Package pkg = mPackages.valueAt(i); 5398 if (!(pkg.mExtras instanceof PackageSetting)) { 5399 continue; 5400 } 5401 PackageSetting ps = (PackageSetting) pkg.mExtras; 5402 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5403 } 5404 } 5405 } 5406 } 5407 5408 @Override 5409 public int getPermissionFlags(String permName, String packageName, int userId) { 5410 return mPermissionManager.getPermissionFlags( 5411 permName, packageName, getCallingUid(), userId); 5412 } 5413 5414 @Override 5415 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5416 int flagValues, int userId) { 5417 mPermissionManager.updatePermissionFlags( 5418 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5419 mPermissionCallback); 5420 } 5421 5422 /** 5423 * Update the permission flags for all packages and runtime permissions of a user in order 5424 * to allow device or profile owner to remove POLICY_FIXED. 5425 */ 5426 @Override 5427 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5428 synchronized (mPackages) { 5429 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5430 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5431 mPermissionCallback); 5432 if (changed) { 5433 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5434 } 5435 } 5436 } 5437 5438 @Override 5439 public boolean shouldShowRequestPermissionRationale(String permissionName, 5440 String packageName, int userId) { 5441 if (UserHandle.getCallingUserId() != userId) { 5442 mContext.enforceCallingPermission( 5443 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5444 "canShowRequestPermissionRationale for user " + userId); 5445 } 5446 5447 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5448 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5449 return false; 5450 } 5451 5452 if (checkPermission(permissionName, packageName, userId) 5453 == PackageManager.PERMISSION_GRANTED) { 5454 return false; 5455 } 5456 5457 final int flags; 5458 5459 final long identity = Binder.clearCallingIdentity(); 5460 try { 5461 flags = getPermissionFlags(permissionName, 5462 packageName, userId); 5463 } finally { 5464 Binder.restoreCallingIdentity(identity); 5465 } 5466 5467 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5468 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5469 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5470 5471 if ((flags & fixedFlags) != 0) { 5472 return false; 5473 } 5474 5475 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5476 } 5477 5478 @Override 5479 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5480 mContext.enforceCallingOrSelfPermission( 5481 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5482 "addOnPermissionsChangeListener"); 5483 5484 synchronized (mPackages) { 5485 mOnPermissionChangeListeners.addListenerLocked(listener); 5486 } 5487 } 5488 5489 @Override 5490 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5491 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5492 throw new SecurityException("Instant applications don't have access to this method"); 5493 } 5494 synchronized (mPackages) { 5495 mOnPermissionChangeListeners.removeListenerLocked(listener); 5496 } 5497 } 5498 5499 @Override 5500 public boolean isProtectedBroadcast(String actionName) { 5501 // allow instant applications 5502 synchronized (mProtectedBroadcasts) { 5503 if (mProtectedBroadcasts.contains(actionName)) { 5504 return true; 5505 } else if (actionName != null) { 5506 // TODO: remove these terrible hacks 5507 if (actionName.startsWith("android.net.netmon.lingerExpired") 5508 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5509 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5510 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5511 return true; 5512 } 5513 } 5514 } 5515 return false; 5516 } 5517 5518 @Override 5519 public int checkSignatures(String pkg1, String pkg2) { 5520 synchronized (mPackages) { 5521 final PackageParser.Package p1 = mPackages.get(pkg1); 5522 final PackageParser.Package p2 = mPackages.get(pkg2); 5523 if (p1 == null || p1.mExtras == null 5524 || p2 == null || p2.mExtras == null) { 5525 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5526 } 5527 final int callingUid = Binder.getCallingUid(); 5528 final int callingUserId = UserHandle.getUserId(callingUid); 5529 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5530 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5531 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5532 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5533 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5534 } 5535 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5536 } 5537 } 5538 5539 @Override 5540 public int checkUidSignatures(int uid1, int uid2) { 5541 final int callingUid = Binder.getCallingUid(); 5542 final int callingUserId = UserHandle.getUserId(callingUid); 5543 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5544 // Map to base uids. 5545 uid1 = UserHandle.getAppId(uid1); 5546 uid2 = UserHandle.getAppId(uid2); 5547 // reader 5548 synchronized (mPackages) { 5549 Signature[] s1; 5550 Signature[] s2; 5551 Object obj = mSettings.getUserIdLPr(uid1); 5552 if (obj != null) { 5553 if (obj instanceof SharedUserSetting) { 5554 if (isCallerInstantApp) { 5555 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5556 } 5557 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5558 } else if (obj instanceof PackageSetting) { 5559 final PackageSetting ps = (PackageSetting) obj; 5560 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5561 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5562 } 5563 s1 = ps.signatures.mSigningDetails.signatures; 5564 } else { 5565 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5566 } 5567 } else { 5568 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5569 } 5570 obj = mSettings.getUserIdLPr(uid2); 5571 if (obj != null) { 5572 if (obj instanceof SharedUserSetting) { 5573 if (isCallerInstantApp) { 5574 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5575 } 5576 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5577 } else if (obj instanceof PackageSetting) { 5578 final PackageSetting ps = (PackageSetting) obj; 5579 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5580 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5581 } 5582 s2 = ps.signatures.mSigningDetails.signatures; 5583 } else { 5584 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5585 } 5586 } else { 5587 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5588 } 5589 return compareSignatures(s1, s2); 5590 } 5591 } 5592 5593 @Override 5594 public boolean hasSigningCertificate( 5595 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5596 5597 synchronized (mPackages) { 5598 final PackageParser.Package p = mPackages.get(packageName); 5599 if (p == null || p.mExtras == null) { 5600 return false; 5601 } 5602 final int callingUid = Binder.getCallingUid(); 5603 final int callingUserId = UserHandle.getUserId(callingUid); 5604 final PackageSetting ps = (PackageSetting) p.mExtras; 5605 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5606 return false; 5607 } 5608 switch (type) { 5609 case CERT_INPUT_RAW_X509: 5610 return p.mSigningDetails.hasCertificate(certificate); 5611 case CERT_INPUT_SHA256: 5612 return p.mSigningDetails.hasSha256Certificate(certificate); 5613 default: 5614 return false; 5615 } 5616 } 5617 } 5618 5619 @Override 5620 public boolean hasUidSigningCertificate( 5621 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5622 final int callingUid = Binder.getCallingUid(); 5623 final int callingUserId = UserHandle.getUserId(callingUid); 5624 // Map to base uids. 5625 uid = UserHandle.getAppId(uid); 5626 // reader 5627 synchronized (mPackages) { 5628 final PackageParser.SigningDetails signingDetails; 5629 final Object obj = mSettings.getUserIdLPr(uid); 5630 if (obj != null) { 5631 if (obj instanceof SharedUserSetting) { 5632 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5633 if (isCallerInstantApp) { 5634 return false; 5635 } 5636 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5637 } else if (obj instanceof PackageSetting) { 5638 final PackageSetting ps = (PackageSetting) obj; 5639 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5640 return false; 5641 } 5642 signingDetails = ps.signatures.mSigningDetails; 5643 } else { 5644 return false; 5645 } 5646 } else { 5647 return false; 5648 } 5649 switch (type) { 5650 case CERT_INPUT_RAW_X509: 5651 return signingDetails.hasCertificate(certificate); 5652 case CERT_INPUT_SHA256: 5653 return signingDetails.hasSha256Certificate(certificate); 5654 default: 5655 return false; 5656 } 5657 } 5658 } 5659 5660 /** 5661 * This method should typically only be used when granting or revoking 5662 * permissions, since the app may immediately restart after this call. 5663 * <p> 5664 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5665 * guard your work against the app being relaunched. 5666 */ 5667 private void killUid(int appId, int userId, String reason) { 5668 final long identity = Binder.clearCallingIdentity(); 5669 try { 5670 IActivityManager am = ActivityManager.getService(); 5671 if (am != null) { 5672 try { 5673 am.killUid(appId, userId, reason); 5674 } catch (RemoteException e) { 5675 /* ignore - same process */ 5676 } 5677 } 5678 } finally { 5679 Binder.restoreCallingIdentity(identity); 5680 } 5681 } 5682 5683 /** 5684 * If the database version for this type of package (internal storage or 5685 * external storage) is less than the version where package signatures 5686 * were updated, return true. 5687 */ 5688 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5689 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5690 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5691 } 5692 5693 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5694 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5695 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5696 } 5697 5698 @Override 5699 public List<String> getAllPackages() { 5700 final int callingUid = Binder.getCallingUid(); 5701 final int callingUserId = UserHandle.getUserId(callingUid); 5702 synchronized (mPackages) { 5703 if (canViewInstantApps(callingUid, callingUserId)) { 5704 return new ArrayList<String>(mPackages.keySet()); 5705 } 5706 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5707 final List<String> result = new ArrayList<>(); 5708 if (instantAppPkgName != null) { 5709 // caller is an instant application; filter unexposed applications 5710 for (PackageParser.Package pkg : mPackages.values()) { 5711 if (!pkg.visibleToInstantApps) { 5712 continue; 5713 } 5714 result.add(pkg.packageName); 5715 } 5716 } else { 5717 // caller is a normal application; filter instant applications 5718 for (PackageParser.Package pkg : mPackages.values()) { 5719 final PackageSetting ps = 5720 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5721 if (ps != null 5722 && ps.getInstantApp(callingUserId) 5723 && !mInstantAppRegistry.isInstantAccessGranted( 5724 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5725 continue; 5726 } 5727 result.add(pkg.packageName); 5728 } 5729 } 5730 return result; 5731 } 5732 } 5733 5734 @Override 5735 public String[] getPackagesForUid(int uid) { 5736 final int callingUid = Binder.getCallingUid(); 5737 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5738 final int userId = UserHandle.getUserId(uid); 5739 uid = UserHandle.getAppId(uid); 5740 // reader 5741 synchronized (mPackages) { 5742 Object obj = mSettings.getUserIdLPr(uid); 5743 if (obj instanceof SharedUserSetting) { 5744 if (isCallerInstantApp) { 5745 return null; 5746 } 5747 final SharedUserSetting sus = (SharedUserSetting) obj; 5748 final int N = sus.packages.size(); 5749 String[] res = new String[N]; 5750 final Iterator<PackageSetting> it = sus.packages.iterator(); 5751 int i = 0; 5752 while (it.hasNext()) { 5753 PackageSetting ps = it.next(); 5754 if (ps.getInstalled(userId)) { 5755 res[i++] = ps.name; 5756 } else { 5757 res = ArrayUtils.removeElement(String.class, res, res[i]); 5758 } 5759 } 5760 return res; 5761 } else if (obj instanceof PackageSetting) { 5762 final PackageSetting ps = (PackageSetting) obj; 5763 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5764 return new String[]{ps.name}; 5765 } 5766 } 5767 } 5768 return null; 5769 } 5770 5771 @Override 5772 public String getNameForUid(int uid) { 5773 final int callingUid = Binder.getCallingUid(); 5774 if (getInstantAppPackageName(callingUid) != null) { 5775 return null; 5776 } 5777 synchronized (mPackages) { 5778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5779 if (obj instanceof SharedUserSetting) { 5780 final SharedUserSetting sus = (SharedUserSetting) obj; 5781 return sus.name + ":" + sus.userId; 5782 } else if (obj instanceof PackageSetting) { 5783 final PackageSetting ps = (PackageSetting) obj; 5784 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5785 return null; 5786 } 5787 return ps.name; 5788 } 5789 return null; 5790 } 5791 } 5792 5793 @Override 5794 public String[] getNamesForUids(int[] uids) { 5795 if (uids == null || uids.length == 0) { 5796 return null; 5797 } 5798 final int callingUid = Binder.getCallingUid(); 5799 if (getInstantAppPackageName(callingUid) != null) { 5800 return null; 5801 } 5802 final String[] names = new String[uids.length]; 5803 synchronized (mPackages) { 5804 for (int i = uids.length - 1; i >= 0; i--) { 5805 final int uid = uids[i]; 5806 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5807 if (obj instanceof SharedUserSetting) { 5808 final SharedUserSetting sus = (SharedUserSetting) obj; 5809 names[i] = "shared:" + sus.name; 5810 } else if (obj instanceof PackageSetting) { 5811 final PackageSetting ps = (PackageSetting) obj; 5812 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5813 names[i] = null; 5814 } else { 5815 names[i] = ps.name; 5816 } 5817 } else { 5818 names[i] = null; 5819 } 5820 } 5821 } 5822 return names; 5823 } 5824 5825 @Override 5826 public int getUidForSharedUser(String sharedUserName) { 5827 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5828 return -1; 5829 } 5830 if (sharedUserName == null) { 5831 return -1; 5832 } 5833 // reader 5834 synchronized (mPackages) { 5835 SharedUserSetting suid; 5836 try { 5837 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5838 if (suid != null) { 5839 return suid.userId; 5840 } 5841 } catch (PackageManagerException ignore) { 5842 // can't happen, but, still need to catch it 5843 } 5844 return -1; 5845 } 5846 } 5847 5848 @Override 5849 public int getFlagsForUid(int uid) { 5850 final int callingUid = Binder.getCallingUid(); 5851 if (getInstantAppPackageName(callingUid) != null) { 5852 return 0; 5853 } 5854 synchronized (mPackages) { 5855 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5856 if (obj instanceof SharedUserSetting) { 5857 final SharedUserSetting sus = (SharedUserSetting) obj; 5858 return sus.pkgFlags; 5859 } else if (obj instanceof PackageSetting) { 5860 final PackageSetting ps = (PackageSetting) obj; 5861 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5862 return 0; 5863 } 5864 return ps.pkgFlags; 5865 } 5866 } 5867 return 0; 5868 } 5869 5870 @Override 5871 public int getPrivateFlagsForUid(int uid) { 5872 final int callingUid = Binder.getCallingUid(); 5873 if (getInstantAppPackageName(callingUid) != null) { 5874 return 0; 5875 } 5876 synchronized (mPackages) { 5877 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5878 if (obj instanceof SharedUserSetting) { 5879 final SharedUserSetting sus = (SharedUserSetting) obj; 5880 return sus.pkgPrivateFlags; 5881 } else if (obj instanceof PackageSetting) { 5882 final PackageSetting ps = (PackageSetting) obj; 5883 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5884 return 0; 5885 } 5886 return ps.pkgPrivateFlags; 5887 } 5888 } 5889 return 0; 5890 } 5891 5892 @Override 5893 public boolean isUidPrivileged(int uid) { 5894 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5895 return false; 5896 } 5897 uid = UserHandle.getAppId(uid); 5898 // reader 5899 synchronized (mPackages) { 5900 Object obj = mSettings.getUserIdLPr(uid); 5901 if (obj instanceof SharedUserSetting) { 5902 final SharedUserSetting sus = (SharedUserSetting) obj; 5903 final Iterator<PackageSetting> it = sus.packages.iterator(); 5904 while (it.hasNext()) { 5905 if (it.next().isPrivileged()) { 5906 return true; 5907 } 5908 } 5909 } else if (obj instanceof PackageSetting) { 5910 final PackageSetting ps = (PackageSetting) obj; 5911 return ps.isPrivileged(); 5912 } 5913 } 5914 return false; 5915 } 5916 5917 @Override 5918 public String[] getAppOpPermissionPackages(String permName) { 5919 return mPermissionManager.getAppOpPermissionPackages(permName); 5920 } 5921 5922 @Override 5923 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5924 int flags, int userId) { 5925 return resolveIntentInternal( 5926 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5927 } 5928 5929 /** 5930 * Normally instant apps can only be resolved when they're visible to the caller. 5931 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5932 * since we need to allow the system to start any installed application. 5933 */ 5934 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5935 int flags, int userId, boolean resolveForStart) { 5936 try { 5937 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5938 5939 if (!sUserManager.exists(userId)) return null; 5940 final int callingUid = Binder.getCallingUid(); 5941 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5942 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5943 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5944 5945 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5946 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5947 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5948 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5949 5950 final ResolveInfo bestChoice = 5951 chooseBestActivity(intent, resolvedType, flags, query, userId); 5952 return bestChoice; 5953 } finally { 5954 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5955 } 5956 } 5957 5958 @Override 5959 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5960 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5961 throw new SecurityException( 5962 "findPersistentPreferredActivity can only be run by the system"); 5963 } 5964 if (!sUserManager.exists(userId)) { 5965 return null; 5966 } 5967 final int callingUid = Binder.getCallingUid(); 5968 intent = updateIntentForResolve(intent); 5969 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5970 final int flags = updateFlagsForResolve( 5971 0, userId, intent, callingUid, false /*includeInstantApps*/); 5972 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5973 userId); 5974 synchronized (mPackages) { 5975 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5976 userId); 5977 } 5978 } 5979 5980 @Override 5981 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5982 IntentFilter filter, int match, ComponentName activity) { 5983 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5984 return; 5985 } 5986 final int userId = UserHandle.getCallingUserId(); 5987 if (DEBUG_PREFERRED) { 5988 Log.v(TAG, "setLastChosenActivity intent=" + intent 5989 + " resolvedType=" + resolvedType 5990 + " flags=" + flags 5991 + " filter=" + filter 5992 + " match=" + match 5993 + " activity=" + activity); 5994 filter.dump(new PrintStreamPrinter(System.out), " "); 5995 } 5996 intent.setComponent(null); 5997 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5998 userId); 5999 // Find any earlier preferred or last chosen entries and nuke them 6000 findPreferredActivity(intent, resolvedType, 6001 flags, query, 0, false, true, false, userId); 6002 // Add the new activity as the last chosen for this filter 6003 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6004 "Setting last chosen"); 6005 } 6006 6007 @Override 6008 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6009 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6010 return null; 6011 } 6012 final int userId = UserHandle.getCallingUserId(); 6013 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6014 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6015 userId); 6016 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6017 false, false, false, userId); 6018 } 6019 6020 /** 6021 * Returns whether or not instant apps have been disabled remotely. 6022 */ 6023 private boolean areWebInstantAppsDisabled() { 6024 return mWebInstantAppsDisabled; 6025 } 6026 6027 private boolean isInstantAppResolutionAllowed( 6028 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6029 boolean skipPackageCheck) { 6030 if (mInstantAppResolverConnection == null) { 6031 return false; 6032 } 6033 if (mInstantAppInstallerActivity == null) { 6034 return false; 6035 } 6036 if (intent.getComponent() != null) { 6037 return false; 6038 } 6039 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6040 return false; 6041 } 6042 if (!skipPackageCheck && intent.getPackage() != null) { 6043 return false; 6044 } 6045 if (!intent.isWebIntent()) { 6046 // for non web intents, we should not resolve externally if an app already exists to 6047 // handle it or if the caller didn't explicitly request it. 6048 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6049 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6050 return false; 6051 } 6052 } else { 6053 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6054 return false; 6055 } else if (areWebInstantAppsDisabled()) { 6056 return false; 6057 } 6058 } 6059 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6060 // Or if there's already an ephemeral app installed that handles the action 6061 synchronized (mPackages) { 6062 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6063 for (int n = 0; n < count; n++) { 6064 final ResolveInfo info = resolvedActivities.get(n); 6065 final String packageName = info.activityInfo.packageName; 6066 final PackageSetting ps = mSettings.mPackages.get(packageName); 6067 if (ps != null) { 6068 // only check domain verification status if the app is not a browser 6069 if (!info.handleAllWebDataURI) { 6070 // Try to get the status from User settings first 6071 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6072 final int status = (int) (packedStatus >> 32); 6073 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6074 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6075 if (DEBUG_INSTANT) { 6076 Slog.v(TAG, "DENY instant app;" 6077 + " pkg: " + packageName + ", status: " + status); 6078 } 6079 return false; 6080 } 6081 } 6082 if (ps.getInstantApp(userId)) { 6083 if (DEBUG_INSTANT) { 6084 Slog.v(TAG, "DENY instant app installed;" 6085 + " pkg: " + packageName); 6086 } 6087 return false; 6088 } 6089 } 6090 } 6091 } 6092 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6093 return true; 6094 } 6095 6096 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6097 Intent origIntent, String resolvedType, String callingPackage, 6098 Bundle verificationBundle, int userId) { 6099 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6100 new InstantAppRequest(responseObj, origIntent, resolvedType, 6101 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6102 mHandler.sendMessage(msg); 6103 } 6104 6105 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6106 int flags, List<ResolveInfo> query, int userId) { 6107 if (query != null) { 6108 final int N = query.size(); 6109 if (N == 1) { 6110 return query.get(0); 6111 } else if (N > 1) { 6112 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6113 // If there is more than one activity with the same priority, 6114 // then let the user decide between them. 6115 ResolveInfo r0 = query.get(0); 6116 ResolveInfo r1 = query.get(1); 6117 if (DEBUG_INTENT_MATCHING || debug) { 6118 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6119 + r1.activityInfo.name + "=" + r1.priority); 6120 } 6121 // If the first activity has a higher priority, or a different 6122 // default, then it is always desirable to pick it. 6123 if (r0.priority != r1.priority 6124 || r0.preferredOrder != r1.preferredOrder 6125 || r0.isDefault != r1.isDefault) { 6126 return query.get(0); 6127 } 6128 // If we have saved a preference for a preferred activity for 6129 // this Intent, use that. 6130 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6131 flags, query, r0.priority, true, false, debug, userId); 6132 if (ri != null) { 6133 return ri; 6134 } 6135 // If we have an ephemeral app, use it 6136 for (int i = 0; i < N; i++) { 6137 ri = query.get(i); 6138 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6139 final String packageName = ri.activityInfo.packageName; 6140 final PackageSetting ps = mSettings.mPackages.get(packageName); 6141 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6142 final int status = (int)(packedStatus >> 32); 6143 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6144 return ri; 6145 } 6146 } 6147 } 6148 ri = new ResolveInfo(mResolveInfo); 6149 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6150 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6151 // If all of the options come from the same package, show the application's 6152 // label and icon instead of the generic resolver's. 6153 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6154 // and then throw away the ResolveInfo itself, meaning that the caller loses 6155 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6156 // a fallback for this case; we only set the target package's resources on 6157 // the ResolveInfo, not the ActivityInfo. 6158 final String intentPackage = intent.getPackage(); 6159 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6160 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6161 ri.resolvePackageName = intentPackage; 6162 if (userNeedsBadging(userId)) { 6163 ri.noResourceId = true; 6164 } else { 6165 ri.icon = appi.icon; 6166 } 6167 ri.iconResourceId = appi.icon; 6168 ri.labelRes = appi.labelRes; 6169 } 6170 ri.activityInfo.applicationInfo = new ApplicationInfo( 6171 ri.activityInfo.applicationInfo); 6172 if (userId != 0) { 6173 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6174 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6175 } 6176 // Make sure that the resolver is displayable in car mode 6177 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6178 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6179 return ri; 6180 } 6181 } 6182 return null; 6183 } 6184 6185 /** 6186 * Return true if the given list is not empty and all of its contents have 6187 * an activityInfo with the given package name. 6188 */ 6189 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6190 if (ArrayUtils.isEmpty(list)) { 6191 return false; 6192 } 6193 for (int i = 0, N = list.size(); i < N; i++) { 6194 final ResolveInfo ri = list.get(i); 6195 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6196 if (ai == null || !packageName.equals(ai.packageName)) { 6197 return false; 6198 } 6199 } 6200 return true; 6201 } 6202 6203 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6204 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6205 final int N = query.size(); 6206 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6207 .get(userId); 6208 // Get the list of persistent preferred activities that handle the intent 6209 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6210 List<PersistentPreferredActivity> pprefs = ppir != null 6211 ? ppir.queryIntent(intent, resolvedType, 6212 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6213 userId) 6214 : null; 6215 if (pprefs != null && pprefs.size() > 0) { 6216 final int M = pprefs.size(); 6217 for (int i=0; i<M; i++) { 6218 final PersistentPreferredActivity ppa = pprefs.get(i); 6219 if (DEBUG_PREFERRED || debug) { 6220 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6221 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6222 + "\n component=" + ppa.mComponent); 6223 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6224 } 6225 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6226 flags | MATCH_DISABLED_COMPONENTS, userId); 6227 if (DEBUG_PREFERRED || debug) { 6228 Slog.v(TAG, "Found persistent preferred activity:"); 6229 if (ai != null) { 6230 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6231 } else { 6232 Slog.v(TAG, " null"); 6233 } 6234 } 6235 if (ai == null) { 6236 // This previously registered persistent preferred activity 6237 // component is no longer known. Ignore it and do NOT remove it. 6238 continue; 6239 } 6240 for (int j=0; j<N; j++) { 6241 final ResolveInfo ri = query.get(j); 6242 if (!ri.activityInfo.applicationInfo.packageName 6243 .equals(ai.applicationInfo.packageName)) { 6244 continue; 6245 } 6246 if (!ri.activityInfo.name.equals(ai.name)) { 6247 continue; 6248 } 6249 // Found a persistent preference that can handle the intent. 6250 if (DEBUG_PREFERRED || debug) { 6251 Slog.v(TAG, "Returning persistent preferred activity: " + 6252 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6253 } 6254 return ri; 6255 } 6256 } 6257 } 6258 return null; 6259 } 6260 6261 // TODO: handle preferred activities missing while user has amnesia 6262 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6263 List<ResolveInfo> query, int priority, boolean always, 6264 boolean removeMatches, boolean debug, int userId) { 6265 if (!sUserManager.exists(userId)) return null; 6266 final int callingUid = Binder.getCallingUid(); 6267 flags = updateFlagsForResolve( 6268 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6269 intent = updateIntentForResolve(intent); 6270 // writer 6271 synchronized (mPackages) { 6272 // Try to find a matching persistent preferred activity. 6273 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6274 debug, userId); 6275 6276 // If a persistent preferred activity matched, use it. 6277 if (pri != null) { 6278 return pri; 6279 } 6280 6281 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6282 // Get the list of preferred activities that handle the intent 6283 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6284 List<PreferredActivity> prefs = pir != null 6285 ? pir.queryIntent(intent, resolvedType, 6286 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6287 userId) 6288 : null; 6289 if (prefs != null && prefs.size() > 0) { 6290 boolean changed = false; 6291 try { 6292 // First figure out how good the original match set is. 6293 // We will only allow preferred activities that came 6294 // from the same match quality. 6295 int match = 0; 6296 6297 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6298 6299 final int N = query.size(); 6300 for (int j=0; j<N; j++) { 6301 final ResolveInfo ri = query.get(j); 6302 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6303 + ": 0x" + Integer.toHexString(match)); 6304 if (ri.match > match) { 6305 match = ri.match; 6306 } 6307 } 6308 6309 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6310 + Integer.toHexString(match)); 6311 6312 match &= IntentFilter.MATCH_CATEGORY_MASK; 6313 final int M = prefs.size(); 6314 for (int i=0; i<M; i++) { 6315 final PreferredActivity pa = prefs.get(i); 6316 if (DEBUG_PREFERRED || debug) { 6317 Slog.v(TAG, "Checking PreferredActivity ds=" 6318 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6319 + "\n component=" + pa.mPref.mComponent); 6320 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6321 } 6322 if (pa.mPref.mMatch != match) { 6323 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6324 + Integer.toHexString(pa.mPref.mMatch)); 6325 continue; 6326 } 6327 // If it's not an "always" type preferred activity and that's what we're 6328 // looking for, skip it. 6329 if (always && !pa.mPref.mAlways) { 6330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6331 continue; 6332 } 6333 final ActivityInfo ai = getActivityInfo( 6334 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6335 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6336 userId); 6337 if (DEBUG_PREFERRED || debug) { 6338 Slog.v(TAG, "Found preferred activity:"); 6339 if (ai != null) { 6340 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6341 } else { 6342 Slog.v(TAG, " null"); 6343 } 6344 } 6345 if (ai == null) { 6346 // This previously registered preferred activity 6347 // component is no longer known. Most likely an update 6348 // to the app was installed and in the new version this 6349 // component no longer exists. Clean it up by removing 6350 // it from the preferred activities list, and skip it. 6351 Slog.w(TAG, "Removing dangling preferred activity: " 6352 + pa.mPref.mComponent); 6353 pir.removeFilter(pa); 6354 changed = true; 6355 continue; 6356 } 6357 for (int j=0; j<N; j++) { 6358 final ResolveInfo ri = query.get(j); 6359 if (!ri.activityInfo.applicationInfo.packageName 6360 .equals(ai.applicationInfo.packageName)) { 6361 continue; 6362 } 6363 if (!ri.activityInfo.name.equals(ai.name)) { 6364 continue; 6365 } 6366 6367 if (removeMatches) { 6368 pir.removeFilter(pa); 6369 changed = true; 6370 if (DEBUG_PREFERRED) { 6371 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6372 } 6373 break; 6374 } 6375 6376 // Okay we found a previously set preferred or last chosen app. 6377 // If the result set is different from when this 6378 // was created, and is not a subset of the preferred set, we need to 6379 // clear it and re-ask the user their preference, if we're looking for 6380 // an "always" type entry. 6381 if (always && !pa.mPref.sameSet(query)) { 6382 if (pa.mPref.isSuperset(query)) { 6383 // some components of the set are no longer present in 6384 // the query, but the preferred activity can still be reused 6385 if (DEBUG_PREFERRED) { 6386 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6387 + " still valid as only non-preferred components" 6388 + " were removed for " + intent + " type " 6389 + resolvedType); 6390 } 6391 // remove obsolete components and re-add the up-to-date filter 6392 PreferredActivity freshPa = new PreferredActivity(pa, 6393 pa.mPref.mMatch, 6394 pa.mPref.discardObsoleteComponents(query), 6395 pa.mPref.mComponent, 6396 pa.mPref.mAlways); 6397 pir.removeFilter(pa); 6398 pir.addFilter(freshPa); 6399 changed = true; 6400 } else { 6401 Slog.i(TAG, 6402 "Result set changed, dropping preferred activity for " 6403 + intent + " type " + resolvedType); 6404 if (DEBUG_PREFERRED) { 6405 Slog.v(TAG, "Removing preferred activity since set changed " 6406 + pa.mPref.mComponent); 6407 } 6408 pir.removeFilter(pa); 6409 // Re-add the filter as a "last chosen" entry (!always) 6410 PreferredActivity lastChosen = new PreferredActivity( 6411 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6412 pir.addFilter(lastChosen); 6413 changed = true; 6414 return null; 6415 } 6416 } 6417 6418 // Yay! Either the set matched or we're looking for the last chosen 6419 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6420 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6421 return ri; 6422 } 6423 } 6424 } finally { 6425 if (changed) { 6426 if (DEBUG_PREFERRED) { 6427 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6428 } 6429 scheduleWritePackageRestrictionsLocked(userId); 6430 } 6431 } 6432 } 6433 } 6434 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6435 return null; 6436 } 6437 6438 /* 6439 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6440 */ 6441 @Override 6442 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6443 int targetUserId) { 6444 mContext.enforceCallingOrSelfPermission( 6445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6446 List<CrossProfileIntentFilter> matches = 6447 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6448 if (matches != null) { 6449 int size = matches.size(); 6450 for (int i = 0; i < size; i++) { 6451 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6452 } 6453 } 6454 if (intent.hasWebURI()) { 6455 // cross-profile app linking works only towards the parent. 6456 final int callingUid = Binder.getCallingUid(); 6457 final UserInfo parent = getProfileParent(sourceUserId); 6458 synchronized(mPackages) { 6459 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6460 false /*includeInstantApps*/); 6461 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6462 intent, resolvedType, flags, sourceUserId, parent.id); 6463 return xpDomainInfo != null; 6464 } 6465 } 6466 return false; 6467 } 6468 6469 private UserInfo getProfileParent(int userId) { 6470 final long identity = Binder.clearCallingIdentity(); 6471 try { 6472 return sUserManager.getProfileParent(userId); 6473 } finally { 6474 Binder.restoreCallingIdentity(identity); 6475 } 6476 } 6477 6478 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6479 String resolvedType, int userId) { 6480 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6481 if (resolver != null) { 6482 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6483 } 6484 return null; 6485 } 6486 6487 @Override 6488 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6489 String resolvedType, int flags, int userId) { 6490 try { 6491 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6492 6493 return new ParceledListSlice<>( 6494 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6495 } finally { 6496 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6497 } 6498 } 6499 6500 /** 6501 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6502 * instant, returns {@code null}. 6503 */ 6504 private String getInstantAppPackageName(int callingUid) { 6505 synchronized (mPackages) { 6506 // If the caller is an isolated app use the owner's uid for the lookup. 6507 if (Process.isIsolated(callingUid)) { 6508 callingUid = mIsolatedOwners.get(callingUid); 6509 } 6510 final int appId = UserHandle.getAppId(callingUid); 6511 final Object obj = mSettings.getUserIdLPr(appId); 6512 if (obj instanceof PackageSetting) { 6513 final PackageSetting ps = (PackageSetting) obj; 6514 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6515 return isInstantApp ? ps.pkg.packageName : null; 6516 } 6517 } 6518 return null; 6519 } 6520 6521 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6522 String resolvedType, int flags, int userId) { 6523 return queryIntentActivitiesInternal( 6524 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6525 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6526 } 6527 6528 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6529 String resolvedType, int flags, int filterCallingUid, int userId, 6530 boolean resolveForStart, boolean allowDynamicSplits) { 6531 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6532 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6533 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6534 false /* requireFullPermission */, false /* checkShell */, 6535 "query intent activities"); 6536 final String pkgName = intent.getPackage(); 6537 ComponentName comp = intent.getComponent(); 6538 if (comp == null) { 6539 if (intent.getSelector() != null) { 6540 intent = intent.getSelector(); 6541 comp = intent.getComponent(); 6542 } 6543 } 6544 6545 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6546 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6547 if (comp != null) { 6548 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6549 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6550 if (ai != null) { 6551 // When specifying an explicit component, we prevent the activity from being 6552 // used when either 1) the calling package is normal and the activity is within 6553 // an ephemeral application or 2) the calling package is ephemeral and the 6554 // activity is not visible to ephemeral applications. 6555 final boolean matchInstantApp = 6556 (flags & PackageManager.MATCH_INSTANT) != 0; 6557 final boolean matchVisibleToInstantAppOnly = 6558 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6559 final boolean matchExplicitlyVisibleOnly = 6560 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6561 final boolean isCallerInstantApp = 6562 instantAppPkgName != null; 6563 final boolean isTargetSameInstantApp = 6564 comp.getPackageName().equals(instantAppPkgName); 6565 final boolean isTargetInstantApp = 6566 (ai.applicationInfo.privateFlags 6567 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6568 final boolean isTargetVisibleToInstantApp = 6569 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6570 final boolean isTargetExplicitlyVisibleToInstantApp = 6571 isTargetVisibleToInstantApp 6572 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6573 final boolean isTargetHiddenFromInstantApp = 6574 !isTargetVisibleToInstantApp 6575 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6576 final boolean blockResolution = 6577 !isTargetSameInstantApp 6578 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6579 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6580 && isTargetHiddenFromInstantApp)); 6581 if (!blockResolution) { 6582 final ResolveInfo ri = new ResolveInfo(); 6583 ri.activityInfo = ai; 6584 list.add(ri); 6585 } 6586 } 6587 return applyPostResolutionFilter( 6588 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6589 } 6590 6591 // reader 6592 boolean sortResult = false; 6593 boolean addInstant = false; 6594 List<ResolveInfo> result; 6595 synchronized (mPackages) { 6596 if (pkgName == null) { 6597 List<CrossProfileIntentFilter> matchingFilters = 6598 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6599 // Check for results that need to skip the current profile. 6600 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6601 resolvedType, flags, userId); 6602 if (xpResolveInfo != null) { 6603 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6604 xpResult.add(xpResolveInfo); 6605 return applyPostResolutionFilter( 6606 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6607 allowDynamicSplits, filterCallingUid, userId, intent); 6608 } 6609 6610 // Check for results in the current profile. 6611 result = filterIfNotSystemUser(mActivities.queryIntent( 6612 intent, resolvedType, flags, userId), userId); 6613 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 6614 false /*skipPackageCheck*/); 6615 // Check for cross profile results. 6616 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6617 xpResolveInfo = queryCrossProfileIntents( 6618 matchingFilters, intent, resolvedType, flags, userId, 6619 hasNonNegativePriorityResult); 6620 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6621 boolean isVisibleToUser = filterIfNotSystemUser( 6622 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6623 if (isVisibleToUser) { 6624 result.add(xpResolveInfo); 6625 sortResult = true; 6626 } 6627 } 6628 if (intent.hasWebURI()) { 6629 CrossProfileDomainInfo xpDomainInfo = null; 6630 final UserInfo parent = getProfileParent(userId); 6631 if (parent != null) { 6632 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6633 flags, userId, parent.id); 6634 } 6635 if (xpDomainInfo != null) { 6636 if (xpResolveInfo != null) { 6637 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6638 // in the result. 6639 result.remove(xpResolveInfo); 6640 } 6641 if (result.size() == 0 && !addInstant) { 6642 // No result in current profile, but found candidate in parent user. 6643 // And we are not going to add emphemeral app, so we can return the 6644 // result straight away. 6645 result.add(xpDomainInfo.resolveInfo); 6646 return applyPostResolutionFilter(result, instantAppPkgName, 6647 allowDynamicSplits, filterCallingUid, userId, intent); 6648 } 6649 } else if (result.size() <= 1 && !addInstant) { 6650 // No result in parent user and <= 1 result in current profile, and we 6651 // are not going to add emphemeral app, so we can return the result without 6652 // further processing. 6653 return applyPostResolutionFilter(result, instantAppPkgName, 6654 allowDynamicSplits, filterCallingUid, userId, intent); 6655 } 6656 // We have more than one candidate (combining results from current and parent 6657 // profile), so we need filtering and sorting. 6658 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6659 intent, flags, result, xpDomainInfo, userId); 6660 sortResult = true; 6661 } 6662 } else { 6663 final PackageParser.Package pkg = mPackages.get(pkgName); 6664 result = null; 6665 if (pkg != null) { 6666 result = filterIfNotSystemUser( 6667 mActivities.queryIntentForPackage( 6668 intent, resolvedType, flags, pkg.activities, userId), 6669 userId); 6670 } 6671 if (result == null || result.size() == 0) { 6672 // the caller wants to resolve for a particular package; however, there 6673 // were no installed results, so, try to find an ephemeral result 6674 addInstant = isInstantAppResolutionAllowed( 6675 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6676 if (result == null) { 6677 result = new ArrayList<>(); 6678 } 6679 } 6680 } 6681 } 6682 if (addInstant) { 6683 result = maybeAddInstantAppInstaller( 6684 result, intent, resolvedType, flags, userId, resolveForStart); 6685 } 6686 if (sortResult) { 6687 Collections.sort(result, mResolvePrioritySorter); 6688 } 6689 return applyPostResolutionFilter( 6690 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6691 } 6692 6693 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6694 String resolvedType, int flags, int userId, boolean resolveForStart) { 6695 // first, check to see if we've got an instant app already installed 6696 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6697 ResolveInfo localInstantApp = null; 6698 boolean blockResolution = false; 6699 if (!alreadyResolvedLocally) { 6700 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6701 flags 6702 | PackageManager.GET_RESOLVED_FILTER 6703 | PackageManager.MATCH_INSTANT 6704 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6705 userId); 6706 for (int i = instantApps.size() - 1; i >= 0; --i) { 6707 final ResolveInfo info = instantApps.get(i); 6708 final String packageName = info.activityInfo.packageName; 6709 final PackageSetting ps = mSettings.mPackages.get(packageName); 6710 if (ps.getInstantApp(userId)) { 6711 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6712 final int status = (int)(packedStatus >> 32); 6713 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6714 // there's a local instant application installed, but, the user has 6715 // chosen to never use it; skip resolution and don't acknowledge 6716 // an instant application is even available 6717 if (DEBUG_INSTANT) { 6718 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6719 } 6720 blockResolution = true; 6721 break; 6722 } else { 6723 // we have a locally installed instant application; skip resolution 6724 // but acknowledge there's an instant application available 6725 if (DEBUG_INSTANT) { 6726 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6727 } 6728 localInstantApp = info; 6729 break; 6730 } 6731 } 6732 } 6733 } 6734 // no app installed, let's see if one's available 6735 AuxiliaryResolveInfo auxiliaryResponse = null; 6736 if (!blockResolution) { 6737 if (localInstantApp == null) { 6738 // we don't have an instant app locally, resolve externally 6739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6740 final InstantAppRequest requestObject = new InstantAppRequest( 6741 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6742 null /*callingPackage*/, userId, null /*verificationBundle*/, 6743 resolveForStart); 6744 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6745 mInstantAppResolverConnection, requestObject); 6746 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6747 } else { 6748 // we have an instant application locally, but, we can't admit that since 6749 // callers shouldn't be able to determine prior browsing. create a dummy 6750 // auxiliary response so the downstream code behaves as if there's an 6751 // instant application available externally. when it comes time to start 6752 // the instant application, we'll do the right thing. 6753 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6754 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6755 ai.packageName, ai.versionCode, null /* splitName */); 6756 } 6757 } 6758 if (intent.isWebIntent() && auxiliaryResponse == null) { 6759 return result; 6760 } 6761 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6762 if (ps == null 6763 || ps.getUserState().get(userId) == null 6764 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 6765 return result; 6766 } 6767 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6768 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6769 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6770 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6771 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6772 // add a non-generic filter 6773 ephemeralInstaller.filter = new IntentFilter(); 6774 if (intent.getAction() != null) { 6775 ephemeralInstaller.filter.addAction(intent.getAction()); 6776 } 6777 if (intent.getData() != null && intent.getData().getPath() != null) { 6778 ephemeralInstaller.filter.addDataPath( 6779 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6780 } 6781 ephemeralInstaller.isInstantAppAvailable = true; 6782 // make sure this resolver is the default 6783 ephemeralInstaller.isDefault = true; 6784 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6785 if (DEBUG_INSTANT) { 6786 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6787 } 6788 6789 result.add(ephemeralInstaller); 6790 return result; 6791 } 6792 6793 private static class CrossProfileDomainInfo { 6794 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6795 ResolveInfo resolveInfo; 6796 /* Best domain verification status of the activities found in the other profile */ 6797 int bestDomainVerificationStatus; 6798 } 6799 6800 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6801 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6802 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6803 sourceUserId)) { 6804 return null; 6805 } 6806 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6807 resolvedType, flags, parentUserId); 6808 6809 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6810 return null; 6811 } 6812 CrossProfileDomainInfo result = null; 6813 int size = resultTargetUser.size(); 6814 for (int i = 0; i < size; i++) { 6815 ResolveInfo riTargetUser = resultTargetUser.get(i); 6816 // Intent filter verification is only for filters that specify a host. So don't return 6817 // those that handle all web uris. 6818 if (riTargetUser.handleAllWebDataURI) { 6819 continue; 6820 } 6821 String packageName = riTargetUser.activityInfo.packageName; 6822 PackageSetting ps = mSettings.mPackages.get(packageName); 6823 if (ps == null) { 6824 continue; 6825 } 6826 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6827 int status = (int)(verificationState >> 32); 6828 if (result == null) { 6829 result = new CrossProfileDomainInfo(); 6830 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6831 sourceUserId, parentUserId); 6832 result.bestDomainVerificationStatus = status; 6833 } else { 6834 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6835 result.bestDomainVerificationStatus); 6836 } 6837 } 6838 // Don't consider matches with status NEVER across profiles. 6839 if (result != null && result.bestDomainVerificationStatus 6840 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6841 return null; 6842 } 6843 return result; 6844 } 6845 6846 /** 6847 * Verification statuses are ordered from the worse to the best, except for 6848 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6849 */ 6850 private int bestDomainVerificationStatus(int status1, int status2) { 6851 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6852 return status2; 6853 } 6854 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6855 return status1; 6856 } 6857 return (int) MathUtils.max(status1, status2); 6858 } 6859 6860 private boolean isUserEnabled(int userId) { 6861 long callingId = Binder.clearCallingIdentity(); 6862 try { 6863 UserInfo userInfo = sUserManager.getUserInfo(userId); 6864 return userInfo != null && userInfo.isEnabled(); 6865 } finally { 6866 Binder.restoreCallingIdentity(callingId); 6867 } 6868 } 6869 6870 /** 6871 * Filter out activities with systemUserOnly flag set, when current user is not System. 6872 * 6873 * @return filtered list 6874 */ 6875 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6876 if (userId == UserHandle.USER_SYSTEM) { 6877 return resolveInfos; 6878 } 6879 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6880 ResolveInfo info = resolveInfos.get(i); 6881 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6882 resolveInfos.remove(i); 6883 } 6884 } 6885 return resolveInfos; 6886 } 6887 6888 /** 6889 * Filters out ephemeral activities. 6890 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6891 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6892 * 6893 * @param resolveInfos The pre-filtered list of resolved activities 6894 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6895 * is performed. 6896 * @param intent 6897 * @return A filtered list of resolved activities. 6898 */ 6899 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6900 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId, 6901 Intent intent) { 6902 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(); 6903 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6904 final ResolveInfo info = resolveInfos.get(i); 6905 // remove locally resolved instant app web results when disabled 6906 if (info.isInstantAppAvailable && blockInstant) { 6907 resolveInfos.remove(i); 6908 continue; 6909 } 6910 // allow activities that are defined in the provided package 6911 if (allowDynamicSplits 6912 && info.activityInfo != null 6913 && info.activityInfo.splitName != null 6914 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6915 info.activityInfo.splitName)) { 6916 if (mInstantAppInstallerActivity == null) { 6917 if (DEBUG_INSTALL) { 6918 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6919 } 6920 resolveInfos.remove(i); 6921 continue; 6922 } 6923 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 6924 resolveInfos.remove(i); 6925 continue; 6926 } 6927 // requested activity is defined in a split that hasn't been installed yet. 6928 // add the installer to the resolve list 6929 if (DEBUG_INSTALL) { 6930 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6931 } 6932 final ResolveInfo installerInfo = new ResolveInfo( 6933 mInstantAppInstallerInfo); 6934 final ComponentName installFailureActivity = findInstallFailureActivity( 6935 info.activityInfo.packageName, filterCallingUid, userId); 6936 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6937 installFailureActivity, 6938 info.activityInfo.packageName, 6939 info.activityInfo.applicationInfo.versionCode, 6940 info.activityInfo.splitName); 6941 // add a non-generic filter 6942 installerInfo.filter = new IntentFilter(); 6943 6944 // This resolve info may appear in the chooser UI, so let us make it 6945 // look as the one it replaces as far as the user is concerned which 6946 // requires loading the correct label and icon for the resolve info. 6947 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6948 installerInfo.labelRes = info.resolveLabelResId(); 6949 installerInfo.icon = info.resolveIconResId(); 6950 installerInfo.isInstantAppAvailable = true; 6951 resolveInfos.set(i, installerInfo); 6952 continue; 6953 } 6954 // caller is a full app, don't need to apply any other filtering 6955 if (ephemeralPkgName == null) { 6956 continue; 6957 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6958 // caller is same app; don't need to apply any other filtering 6959 continue; 6960 } 6961 // allow activities that have been explicitly exposed to ephemeral apps 6962 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6963 if (!isEphemeralApp 6964 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6965 continue; 6966 } 6967 resolveInfos.remove(i); 6968 } 6969 return resolveInfos; 6970 } 6971 6972 /** 6973 * Returns the activity component that can handle install failures. 6974 * <p>By default, the instant application installer handles failures. However, an 6975 * application may want to handle failures on its own. Applications do this by 6976 * creating an activity with an intent filter that handles the action 6977 * {@link Intent#ACTION_INSTALL_FAILURE}. 6978 */ 6979 private @Nullable ComponentName findInstallFailureActivity( 6980 String packageName, int filterCallingUid, int userId) { 6981 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6982 failureActivityIntent.setPackage(packageName); 6983 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6984 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6985 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6986 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6987 final int NR = result.size(); 6988 if (NR > 0) { 6989 for (int i = 0; i < NR; i++) { 6990 final ResolveInfo info = result.get(i); 6991 if (info.activityInfo.splitName != null) { 6992 continue; 6993 } 6994 return new ComponentName(packageName, info.activityInfo.name); 6995 } 6996 } 6997 return null; 6998 } 6999 7000 /** 7001 * @param resolveInfos list of resolve infos in descending priority order 7002 * @return if the list contains a resolve info with non-negative priority 7003 */ 7004 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7005 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7006 } 7007 7008 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7009 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7010 int userId) { 7011 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7012 7013 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7014 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7015 candidates.size()); 7016 } 7017 7018 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7019 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7020 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7021 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7022 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7023 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7024 7025 synchronized (mPackages) { 7026 final int count = candidates.size(); 7027 // First, try to use linked apps. Partition the candidates into four lists: 7028 // one for the final results, one for the "do not use ever", one for "undefined status" 7029 // and finally one for "browser app type". 7030 for (int n=0; n<count; n++) { 7031 ResolveInfo info = candidates.get(n); 7032 String packageName = info.activityInfo.packageName; 7033 PackageSetting ps = mSettings.mPackages.get(packageName); 7034 if (ps != null) { 7035 // Add to the special match all list (Browser use case) 7036 if (info.handleAllWebDataURI) { 7037 matchAllList.add(info); 7038 continue; 7039 } 7040 // Try to get the status from User settings first 7041 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7042 int status = (int)(packedStatus >> 32); 7043 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7044 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7045 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7046 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7047 + " : linkgen=" + linkGeneration); 7048 } 7049 // Use link-enabled generation as preferredOrder, i.e. 7050 // prefer newly-enabled over earlier-enabled. 7051 info.preferredOrder = linkGeneration; 7052 alwaysList.add(info); 7053 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7054 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7055 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7056 } 7057 neverList.add(info); 7058 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7059 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7060 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7061 } 7062 alwaysAskList.add(info); 7063 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7064 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7065 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7066 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7067 } 7068 undefinedList.add(info); 7069 } 7070 } 7071 } 7072 7073 // We'll want to include browser possibilities in a few cases 7074 boolean includeBrowser = false; 7075 7076 // First try to add the "always" resolution(s) for the current user, if any 7077 if (alwaysList.size() > 0) { 7078 result.addAll(alwaysList); 7079 } else { 7080 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7081 result.addAll(undefinedList); 7082 // Maybe add one for the other profile. 7083 if (xpDomainInfo != null && ( 7084 xpDomainInfo.bestDomainVerificationStatus 7085 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7086 result.add(xpDomainInfo.resolveInfo); 7087 } 7088 includeBrowser = true; 7089 } 7090 7091 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7092 // If there were 'always' entries their preferred order has been set, so we also 7093 // back that off to make the alternatives equivalent 7094 if (alwaysAskList.size() > 0) { 7095 for (ResolveInfo i : result) { 7096 i.preferredOrder = 0; 7097 } 7098 result.addAll(alwaysAskList); 7099 includeBrowser = true; 7100 } 7101 7102 if (includeBrowser) { 7103 // Also add browsers (all of them or only the default one) 7104 if (DEBUG_DOMAIN_VERIFICATION) { 7105 Slog.v(TAG, " ...including browsers in candidate set"); 7106 } 7107 if ((matchFlags & MATCH_ALL) != 0) { 7108 result.addAll(matchAllList); 7109 } else { 7110 // Browser/generic handling case. If there's a default browser, go straight 7111 // to that (but only if there is no other higher-priority match). 7112 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7113 int maxMatchPrio = 0; 7114 ResolveInfo defaultBrowserMatch = null; 7115 final int numCandidates = matchAllList.size(); 7116 for (int n = 0; n < numCandidates; n++) { 7117 ResolveInfo info = matchAllList.get(n); 7118 // track the highest overall match priority... 7119 if (info.priority > maxMatchPrio) { 7120 maxMatchPrio = info.priority; 7121 } 7122 // ...and the highest-priority default browser match 7123 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7124 if (defaultBrowserMatch == null 7125 || (defaultBrowserMatch.priority < info.priority)) { 7126 if (debug) { 7127 Slog.v(TAG, "Considering default browser match " + info); 7128 } 7129 defaultBrowserMatch = info; 7130 } 7131 } 7132 } 7133 if (defaultBrowserMatch != null 7134 && defaultBrowserMatch.priority >= maxMatchPrio 7135 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7136 { 7137 if (debug) { 7138 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7139 } 7140 result.add(defaultBrowserMatch); 7141 } else { 7142 result.addAll(matchAllList); 7143 } 7144 } 7145 7146 // If there is nothing selected, add all candidates and remove the ones that the user 7147 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7148 if (result.size() == 0) { 7149 result.addAll(candidates); 7150 result.removeAll(neverList); 7151 } 7152 } 7153 } 7154 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7155 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7156 result.size()); 7157 for (ResolveInfo info : result) { 7158 Slog.v(TAG, " + " + info.activityInfo); 7159 } 7160 } 7161 return result; 7162 } 7163 7164 // Returns a packed value as a long: 7165 // 7166 // high 'int'-sized word: link status: undefined/ask/never/always. 7167 // low 'int'-sized word: relative priority among 'always' results. 7168 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7169 long result = ps.getDomainVerificationStatusForUser(userId); 7170 // if none available, get the master status 7171 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7172 if (ps.getIntentFilterVerificationInfo() != null) { 7173 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7174 } 7175 } 7176 return result; 7177 } 7178 7179 private ResolveInfo querySkipCurrentProfileIntents( 7180 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7181 int flags, int sourceUserId) { 7182 if (matchingFilters != null) { 7183 int size = matchingFilters.size(); 7184 for (int i = 0; i < size; i ++) { 7185 CrossProfileIntentFilter filter = matchingFilters.get(i); 7186 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7187 // Checking if there are activities in the target user that can handle the 7188 // intent. 7189 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7190 resolvedType, flags, sourceUserId); 7191 if (resolveInfo != null) { 7192 return resolveInfo; 7193 } 7194 } 7195 } 7196 } 7197 return null; 7198 } 7199 7200 // Return matching ResolveInfo in target user if any. 7201 private ResolveInfo queryCrossProfileIntents( 7202 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7203 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7204 if (matchingFilters != null) { 7205 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7206 // match the same intent. For performance reasons, it is better not to 7207 // run queryIntent twice for the same userId 7208 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7209 int size = matchingFilters.size(); 7210 for (int i = 0; i < size; i++) { 7211 CrossProfileIntentFilter filter = matchingFilters.get(i); 7212 int targetUserId = filter.getTargetUserId(); 7213 boolean skipCurrentProfile = 7214 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7215 boolean skipCurrentProfileIfNoMatchFound = 7216 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7217 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7218 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7219 // Checking if there are activities in the target user that can handle the 7220 // intent. 7221 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7222 resolvedType, flags, sourceUserId); 7223 if (resolveInfo != null) return resolveInfo; 7224 alreadyTriedUserIds.put(targetUserId, true); 7225 } 7226 } 7227 } 7228 return null; 7229 } 7230 7231 /** 7232 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7233 * will forward the intent to the filter's target user. 7234 * Otherwise, returns null. 7235 */ 7236 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7237 String resolvedType, int flags, int sourceUserId) { 7238 int targetUserId = filter.getTargetUserId(); 7239 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7240 resolvedType, flags, targetUserId); 7241 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7242 // If all the matches in the target profile are suspended, return null. 7243 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7244 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7245 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7246 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7247 targetUserId); 7248 } 7249 } 7250 } 7251 return null; 7252 } 7253 7254 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7255 int sourceUserId, int targetUserId) { 7256 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7257 long ident = Binder.clearCallingIdentity(); 7258 boolean targetIsProfile; 7259 try { 7260 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7261 } finally { 7262 Binder.restoreCallingIdentity(ident); 7263 } 7264 String className; 7265 if (targetIsProfile) { 7266 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7267 } else { 7268 className = FORWARD_INTENT_TO_PARENT; 7269 } 7270 ComponentName forwardingActivityComponentName = new ComponentName( 7271 mAndroidApplication.packageName, className); 7272 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7273 sourceUserId); 7274 if (!targetIsProfile) { 7275 forwardingActivityInfo.showUserIcon = targetUserId; 7276 forwardingResolveInfo.noResourceId = true; 7277 } 7278 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7279 forwardingResolveInfo.priority = 0; 7280 forwardingResolveInfo.preferredOrder = 0; 7281 forwardingResolveInfo.match = 0; 7282 forwardingResolveInfo.isDefault = true; 7283 forwardingResolveInfo.filter = filter; 7284 forwardingResolveInfo.targetUserId = targetUserId; 7285 return forwardingResolveInfo; 7286 } 7287 7288 @Override 7289 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7290 Intent[] specifics, String[] specificTypes, Intent intent, 7291 String resolvedType, int flags, int userId) { 7292 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7293 specificTypes, intent, resolvedType, flags, userId)); 7294 } 7295 7296 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7297 Intent[] specifics, String[] specificTypes, Intent intent, 7298 String resolvedType, int flags, int userId) { 7299 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7300 final int callingUid = Binder.getCallingUid(); 7301 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7302 false /*includeInstantApps*/); 7303 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7304 false /*requireFullPermission*/, false /*checkShell*/, 7305 "query intent activity options"); 7306 final String resultsAction = intent.getAction(); 7307 7308 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7309 | PackageManager.GET_RESOLVED_FILTER, userId); 7310 7311 if (DEBUG_INTENT_MATCHING) { 7312 Log.v(TAG, "Query " + intent + ": " + results); 7313 } 7314 7315 int specificsPos = 0; 7316 int N; 7317 7318 // todo: note that the algorithm used here is O(N^2). This 7319 // isn't a problem in our current environment, but if we start running 7320 // into situations where we have more than 5 or 10 matches then this 7321 // should probably be changed to something smarter... 7322 7323 // First we go through and resolve each of the specific items 7324 // that were supplied, taking care of removing any corresponding 7325 // duplicate items in the generic resolve list. 7326 if (specifics != null) { 7327 for (int i=0; i<specifics.length; i++) { 7328 final Intent sintent = specifics[i]; 7329 if (sintent == null) { 7330 continue; 7331 } 7332 7333 if (DEBUG_INTENT_MATCHING) { 7334 Log.v(TAG, "Specific #" + i + ": " + sintent); 7335 } 7336 7337 String action = sintent.getAction(); 7338 if (resultsAction != null && resultsAction.equals(action)) { 7339 // If this action was explicitly requested, then don't 7340 // remove things that have it. 7341 action = null; 7342 } 7343 7344 ResolveInfo ri = null; 7345 ActivityInfo ai = null; 7346 7347 ComponentName comp = sintent.getComponent(); 7348 if (comp == null) { 7349 ri = resolveIntent( 7350 sintent, 7351 specificTypes != null ? specificTypes[i] : null, 7352 flags, userId); 7353 if (ri == null) { 7354 continue; 7355 } 7356 if (ri == mResolveInfo) { 7357 // ACK! Must do something better with this. 7358 } 7359 ai = ri.activityInfo; 7360 comp = new ComponentName(ai.applicationInfo.packageName, 7361 ai.name); 7362 } else { 7363 ai = getActivityInfo(comp, flags, userId); 7364 if (ai == null) { 7365 continue; 7366 } 7367 } 7368 7369 // Look for any generic query activities that are duplicates 7370 // of this specific one, and remove them from the results. 7371 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7372 N = results.size(); 7373 int j; 7374 for (j=specificsPos; j<N; j++) { 7375 ResolveInfo sri = results.get(j); 7376 if ((sri.activityInfo.name.equals(comp.getClassName()) 7377 && sri.activityInfo.applicationInfo.packageName.equals( 7378 comp.getPackageName())) 7379 || (action != null && sri.filter.matchAction(action))) { 7380 results.remove(j); 7381 if (DEBUG_INTENT_MATCHING) Log.v( 7382 TAG, "Removing duplicate item from " + j 7383 + " due to specific " + specificsPos); 7384 if (ri == null) { 7385 ri = sri; 7386 } 7387 j--; 7388 N--; 7389 } 7390 } 7391 7392 // Add this specific item to its proper place. 7393 if (ri == null) { 7394 ri = new ResolveInfo(); 7395 ri.activityInfo = ai; 7396 } 7397 results.add(specificsPos, ri); 7398 ri.specificIndex = i; 7399 specificsPos++; 7400 } 7401 } 7402 7403 // Now we go through the remaining generic results and remove any 7404 // duplicate actions that are found here. 7405 N = results.size(); 7406 for (int i=specificsPos; i<N-1; i++) { 7407 final ResolveInfo rii = results.get(i); 7408 if (rii.filter == null) { 7409 continue; 7410 } 7411 7412 // Iterate over all of the actions of this result's intent 7413 // filter... typically this should be just one. 7414 final Iterator<String> it = rii.filter.actionsIterator(); 7415 if (it == null) { 7416 continue; 7417 } 7418 while (it.hasNext()) { 7419 final String action = it.next(); 7420 if (resultsAction != null && resultsAction.equals(action)) { 7421 // If this action was explicitly requested, then don't 7422 // remove things that have it. 7423 continue; 7424 } 7425 for (int j=i+1; j<N; j++) { 7426 final ResolveInfo rij = results.get(j); 7427 if (rij.filter != null && rij.filter.hasAction(action)) { 7428 results.remove(j); 7429 if (DEBUG_INTENT_MATCHING) Log.v( 7430 TAG, "Removing duplicate item from " + j 7431 + " due to action " + action + " at " + i); 7432 j--; 7433 N--; 7434 } 7435 } 7436 } 7437 7438 // If the caller didn't request filter information, drop it now 7439 // so we don't have to marshall/unmarshall it. 7440 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7441 rii.filter = null; 7442 } 7443 } 7444 7445 // Filter out the caller activity if so requested. 7446 if (caller != null) { 7447 N = results.size(); 7448 for (int i=0; i<N; i++) { 7449 ActivityInfo ainfo = results.get(i).activityInfo; 7450 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7451 && caller.getClassName().equals(ainfo.name)) { 7452 results.remove(i); 7453 break; 7454 } 7455 } 7456 } 7457 7458 // If the caller didn't request filter information, 7459 // drop them now so we don't have to 7460 // marshall/unmarshall it. 7461 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7462 N = results.size(); 7463 for (int i=0; i<N; i++) { 7464 results.get(i).filter = null; 7465 } 7466 } 7467 7468 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7469 return results; 7470 } 7471 7472 @Override 7473 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7474 String resolvedType, int flags, int userId) { 7475 return new ParceledListSlice<>( 7476 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7477 false /*allowDynamicSplits*/)); 7478 } 7479 7480 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7481 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7482 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7483 final int callingUid = Binder.getCallingUid(); 7484 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7485 false /*requireFullPermission*/, false /*checkShell*/, 7486 "query intent receivers"); 7487 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7488 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7489 false /*includeInstantApps*/); 7490 ComponentName comp = intent.getComponent(); 7491 if (comp == null) { 7492 if (intent.getSelector() != null) { 7493 intent = intent.getSelector(); 7494 comp = intent.getComponent(); 7495 } 7496 } 7497 if (comp != null) { 7498 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7499 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7500 if (ai != null) { 7501 // When specifying an explicit component, we prevent the activity from being 7502 // used when either 1) the calling package is normal and the activity is within 7503 // an instant application or 2) the calling package is ephemeral and the 7504 // activity is not visible to instant applications. 7505 final boolean matchInstantApp = 7506 (flags & PackageManager.MATCH_INSTANT) != 0; 7507 final boolean matchVisibleToInstantAppOnly = 7508 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7509 final boolean matchExplicitlyVisibleOnly = 7510 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7511 final boolean isCallerInstantApp = 7512 instantAppPkgName != null; 7513 final boolean isTargetSameInstantApp = 7514 comp.getPackageName().equals(instantAppPkgName); 7515 final boolean isTargetInstantApp = 7516 (ai.applicationInfo.privateFlags 7517 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7518 final boolean isTargetVisibleToInstantApp = 7519 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7520 final boolean isTargetExplicitlyVisibleToInstantApp = 7521 isTargetVisibleToInstantApp 7522 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7523 final boolean isTargetHiddenFromInstantApp = 7524 !isTargetVisibleToInstantApp 7525 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7526 final boolean blockResolution = 7527 !isTargetSameInstantApp 7528 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7529 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7530 && isTargetHiddenFromInstantApp)); 7531 if (!blockResolution) { 7532 ResolveInfo ri = new ResolveInfo(); 7533 ri.activityInfo = ai; 7534 list.add(ri); 7535 } 7536 } 7537 return applyPostResolutionFilter( 7538 list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7539 } 7540 7541 // reader 7542 synchronized (mPackages) { 7543 String pkgName = intent.getPackage(); 7544 if (pkgName == null) { 7545 final List<ResolveInfo> result = 7546 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7547 return applyPostResolutionFilter( 7548 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7549 } 7550 final PackageParser.Package pkg = mPackages.get(pkgName); 7551 if (pkg != null) { 7552 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7553 intent, resolvedType, flags, pkg.receivers, userId); 7554 return applyPostResolutionFilter( 7555 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7556 } 7557 return Collections.emptyList(); 7558 } 7559 } 7560 7561 @Override 7562 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7563 final int callingUid = Binder.getCallingUid(); 7564 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7565 } 7566 7567 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7568 int userId, int callingUid) { 7569 if (!sUserManager.exists(userId)) return null; 7570 flags = updateFlagsForResolve( 7571 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7572 List<ResolveInfo> query = queryIntentServicesInternal( 7573 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7574 if (query != null) { 7575 if (query.size() >= 1) { 7576 // If there is more than one service with the same priority, 7577 // just arbitrarily pick the first one. 7578 return query.get(0); 7579 } 7580 } 7581 return null; 7582 } 7583 7584 @Override 7585 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7586 String resolvedType, int flags, int userId) { 7587 final int callingUid = Binder.getCallingUid(); 7588 return new ParceledListSlice<>(queryIntentServicesInternal( 7589 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7590 } 7591 7592 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7593 String resolvedType, int flags, int userId, int callingUid, 7594 boolean includeInstantApps) { 7595 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7596 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7597 false /*requireFullPermission*/, false /*checkShell*/, 7598 "query intent receivers"); 7599 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7600 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7601 ComponentName comp = intent.getComponent(); 7602 if (comp == null) { 7603 if (intent.getSelector() != null) { 7604 intent = intent.getSelector(); 7605 comp = intent.getComponent(); 7606 } 7607 } 7608 if (comp != null) { 7609 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7610 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7611 if (si != null) { 7612 // When specifying an explicit component, we prevent the service from being 7613 // used when either 1) the service is in an instant application and the 7614 // caller is not the same instant application or 2) the calling package is 7615 // ephemeral and the activity is not visible to ephemeral applications. 7616 final boolean matchInstantApp = 7617 (flags & PackageManager.MATCH_INSTANT) != 0; 7618 final boolean matchVisibleToInstantAppOnly = 7619 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7620 final boolean isCallerInstantApp = 7621 instantAppPkgName != null; 7622 final boolean isTargetSameInstantApp = 7623 comp.getPackageName().equals(instantAppPkgName); 7624 final boolean isTargetInstantApp = 7625 (si.applicationInfo.privateFlags 7626 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7627 final boolean isTargetHiddenFromInstantApp = 7628 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7629 final boolean blockResolution = 7630 !isTargetSameInstantApp 7631 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7632 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7633 && isTargetHiddenFromInstantApp)); 7634 if (!blockResolution) { 7635 final ResolveInfo ri = new ResolveInfo(); 7636 ri.serviceInfo = si; 7637 list.add(ri); 7638 } 7639 } 7640 return list; 7641 } 7642 7643 // reader 7644 synchronized (mPackages) { 7645 String pkgName = intent.getPackage(); 7646 if (pkgName == null) { 7647 return applyPostServiceResolutionFilter( 7648 mServices.queryIntent(intent, resolvedType, flags, userId), 7649 instantAppPkgName); 7650 } 7651 final PackageParser.Package pkg = mPackages.get(pkgName); 7652 if (pkg != null) { 7653 return applyPostServiceResolutionFilter( 7654 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7655 userId), 7656 instantAppPkgName); 7657 } 7658 return Collections.emptyList(); 7659 } 7660 } 7661 7662 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7663 String instantAppPkgName) { 7664 if (instantAppPkgName == null) { 7665 return resolveInfos; 7666 } 7667 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7668 final ResolveInfo info = resolveInfos.get(i); 7669 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7670 // allow services that are defined in the provided package 7671 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7672 if (info.serviceInfo.splitName != null 7673 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7674 info.serviceInfo.splitName)) { 7675 // requested service is defined in a split that hasn't been installed yet. 7676 // add the installer to the resolve list 7677 if (DEBUG_INSTANT) { 7678 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7679 } 7680 final ResolveInfo installerInfo = new ResolveInfo( 7681 mInstantAppInstallerInfo); 7682 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7683 null /* installFailureActivity */, 7684 info.serviceInfo.packageName, 7685 info.serviceInfo.applicationInfo.versionCode, 7686 info.serviceInfo.splitName); 7687 // add a non-generic filter 7688 installerInfo.filter = new IntentFilter(); 7689 // load resources from the correct package 7690 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7691 resolveInfos.set(i, installerInfo); 7692 } 7693 continue; 7694 } 7695 // allow services that have been explicitly exposed to ephemeral apps 7696 if (!isEphemeralApp 7697 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7698 continue; 7699 } 7700 resolveInfos.remove(i); 7701 } 7702 return resolveInfos; 7703 } 7704 7705 @Override 7706 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7707 String resolvedType, int flags, int userId) { 7708 return new ParceledListSlice<>( 7709 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7710 } 7711 7712 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7713 Intent intent, String resolvedType, int flags, int userId) { 7714 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7715 final int callingUid = Binder.getCallingUid(); 7716 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7717 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7718 false /*includeInstantApps*/); 7719 ComponentName comp = intent.getComponent(); 7720 if (comp == null) { 7721 if (intent.getSelector() != null) { 7722 intent = intent.getSelector(); 7723 comp = intent.getComponent(); 7724 } 7725 } 7726 if (comp != null) { 7727 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7728 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7729 if (pi != null) { 7730 // When specifying an explicit component, we prevent the provider from being 7731 // used when either 1) the provider is in an instant application and the 7732 // caller is not the same instant application or 2) the calling package is an 7733 // instant application and the provider is not visible to instant applications. 7734 final boolean matchInstantApp = 7735 (flags & PackageManager.MATCH_INSTANT) != 0; 7736 final boolean matchVisibleToInstantAppOnly = 7737 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7738 final boolean isCallerInstantApp = 7739 instantAppPkgName != null; 7740 final boolean isTargetSameInstantApp = 7741 comp.getPackageName().equals(instantAppPkgName); 7742 final boolean isTargetInstantApp = 7743 (pi.applicationInfo.privateFlags 7744 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7745 final boolean isTargetHiddenFromInstantApp = 7746 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7747 final boolean blockResolution = 7748 !isTargetSameInstantApp 7749 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7750 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7751 && isTargetHiddenFromInstantApp)); 7752 if (!blockResolution) { 7753 final ResolveInfo ri = new ResolveInfo(); 7754 ri.providerInfo = pi; 7755 list.add(ri); 7756 } 7757 } 7758 return list; 7759 } 7760 7761 // reader 7762 synchronized (mPackages) { 7763 String pkgName = intent.getPackage(); 7764 if (pkgName == null) { 7765 return applyPostContentProviderResolutionFilter( 7766 mProviders.queryIntent(intent, resolvedType, flags, userId), 7767 instantAppPkgName); 7768 } 7769 final PackageParser.Package pkg = mPackages.get(pkgName); 7770 if (pkg != null) { 7771 return applyPostContentProviderResolutionFilter( 7772 mProviders.queryIntentForPackage( 7773 intent, resolvedType, flags, pkg.providers, userId), 7774 instantAppPkgName); 7775 } 7776 return Collections.emptyList(); 7777 } 7778 } 7779 7780 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7781 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7782 if (instantAppPkgName == null) { 7783 return resolveInfos; 7784 } 7785 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7786 final ResolveInfo info = resolveInfos.get(i); 7787 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7788 // allow providers that are defined in the provided package 7789 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7790 if (info.providerInfo.splitName != null 7791 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7792 info.providerInfo.splitName)) { 7793 // requested provider is defined in a split that hasn't been installed yet. 7794 // add the installer to the resolve list 7795 if (DEBUG_INSTANT) { 7796 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7797 } 7798 final ResolveInfo installerInfo = new ResolveInfo( 7799 mInstantAppInstallerInfo); 7800 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7801 null /*failureActivity*/, 7802 info.providerInfo.packageName, 7803 info.providerInfo.applicationInfo.versionCode, 7804 info.providerInfo.splitName); 7805 // add a non-generic filter 7806 installerInfo.filter = new IntentFilter(); 7807 // load resources from the correct package 7808 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7809 resolveInfos.set(i, installerInfo); 7810 } 7811 continue; 7812 } 7813 // allow providers that have been explicitly exposed to instant applications 7814 if (!isEphemeralApp 7815 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7816 continue; 7817 } 7818 resolveInfos.remove(i); 7819 } 7820 return resolveInfos; 7821 } 7822 7823 @Override 7824 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7825 final int callingUid = Binder.getCallingUid(); 7826 if (getInstantAppPackageName(callingUid) != null) { 7827 return ParceledListSlice.emptyList(); 7828 } 7829 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7830 flags = updateFlagsForPackage(flags, userId, null); 7831 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7832 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7833 true /* requireFullPermission */, false /* checkShell */, 7834 "get installed packages"); 7835 7836 // writer 7837 synchronized (mPackages) { 7838 ArrayList<PackageInfo> list; 7839 if (listUninstalled) { 7840 list = new ArrayList<>(mSettings.mPackages.size()); 7841 for (PackageSetting ps : mSettings.mPackages.values()) { 7842 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7843 continue; 7844 } 7845 if (filterAppAccessLPr(ps, callingUid, userId)) { 7846 continue; 7847 } 7848 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7849 if (pi != null) { 7850 list.add(pi); 7851 } 7852 } 7853 } else { 7854 list = new ArrayList<>(mPackages.size()); 7855 for (PackageParser.Package p : mPackages.values()) { 7856 final PackageSetting ps = (PackageSetting) p.mExtras; 7857 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7858 continue; 7859 } 7860 if (filterAppAccessLPr(ps, callingUid, userId)) { 7861 continue; 7862 } 7863 final PackageInfo pi = generatePackageInfo((PackageSetting) 7864 p.mExtras, flags, userId); 7865 if (pi != null) { 7866 list.add(pi); 7867 } 7868 } 7869 } 7870 7871 return new ParceledListSlice<>(list); 7872 } 7873 } 7874 7875 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7876 String[] permissions, boolean[] tmp, int flags, int userId) { 7877 int numMatch = 0; 7878 final PermissionsState permissionsState = ps.getPermissionsState(); 7879 for (int i=0; i<permissions.length; i++) { 7880 final String permission = permissions[i]; 7881 if (permissionsState.hasPermission(permission, userId)) { 7882 tmp[i] = true; 7883 numMatch++; 7884 } else { 7885 tmp[i] = false; 7886 } 7887 } 7888 if (numMatch == 0) { 7889 return; 7890 } 7891 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7892 7893 // The above might return null in cases of uninstalled apps or install-state 7894 // skew across users/profiles. 7895 if (pi != null) { 7896 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7897 if (numMatch == permissions.length) { 7898 pi.requestedPermissions = permissions; 7899 } else { 7900 pi.requestedPermissions = new String[numMatch]; 7901 numMatch = 0; 7902 for (int i=0; i<permissions.length; i++) { 7903 if (tmp[i]) { 7904 pi.requestedPermissions[numMatch] = permissions[i]; 7905 numMatch++; 7906 } 7907 } 7908 } 7909 } 7910 list.add(pi); 7911 } 7912 } 7913 7914 @Override 7915 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7916 String[] permissions, int flags, int userId) { 7917 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7918 flags = updateFlagsForPackage(flags, userId, permissions); 7919 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7920 true /* requireFullPermission */, false /* checkShell */, 7921 "get packages holding permissions"); 7922 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7923 7924 // writer 7925 synchronized (mPackages) { 7926 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7927 boolean[] tmpBools = new boolean[permissions.length]; 7928 if (listUninstalled) { 7929 for (PackageSetting ps : mSettings.mPackages.values()) { 7930 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7931 userId); 7932 } 7933 } else { 7934 for (PackageParser.Package pkg : mPackages.values()) { 7935 PackageSetting ps = (PackageSetting)pkg.mExtras; 7936 if (ps != null) { 7937 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7938 userId); 7939 } 7940 } 7941 } 7942 7943 return new ParceledListSlice<PackageInfo>(list); 7944 } 7945 } 7946 7947 @Override 7948 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7949 final int callingUid = Binder.getCallingUid(); 7950 if (getInstantAppPackageName(callingUid) != null) { 7951 return ParceledListSlice.emptyList(); 7952 } 7953 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7954 flags = updateFlagsForApplication(flags, userId, null); 7955 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7956 7957 // writer 7958 synchronized (mPackages) { 7959 ArrayList<ApplicationInfo> list; 7960 if (listUninstalled) { 7961 list = new ArrayList<>(mSettings.mPackages.size()); 7962 for (PackageSetting ps : mSettings.mPackages.values()) { 7963 ApplicationInfo ai; 7964 int effectiveFlags = flags; 7965 if (ps.isSystem()) { 7966 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7967 } 7968 if (ps.pkg != null) { 7969 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7970 continue; 7971 } 7972 if (filterAppAccessLPr(ps, callingUid, userId)) { 7973 continue; 7974 } 7975 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7976 ps.readUserState(userId), userId); 7977 if (ai != null) { 7978 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7979 } 7980 } else { 7981 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7982 // and already converts to externally visible package name 7983 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7984 callingUid, effectiveFlags, userId); 7985 } 7986 if (ai != null) { 7987 list.add(ai); 7988 } 7989 } 7990 } else { 7991 list = new ArrayList<>(mPackages.size()); 7992 for (PackageParser.Package p : mPackages.values()) { 7993 if (p.mExtras != null) { 7994 PackageSetting ps = (PackageSetting) p.mExtras; 7995 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7996 continue; 7997 } 7998 if (filterAppAccessLPr(ps, callingUid, userId)) { 7999 continue; 8000 } 8001 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8002 ps.readUserState(userId), userId); 8003 if (ai != null) { 8004 ai.packageName = resolveExternalPackageNameLPr(p); 8005 list.add(ai); 8006 } 8007 } 8008 } 8009 } 8010 8011 return new ParceledListSlice<>(list); 8012 } 8013 } 8014 8015 @Override 8016 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8017 if (HIDE_EPHEMERAL_APIS) { 8018 return null; 8019 } 8020 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8021 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8022 "getEphemeralApplications"); 8023 } 8024 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8025 true /* requireFullPermission */, false /* checkShell */, 8026 "getEphemeralApplications"); 8027 synchronized (mPackages) { 8028 List<InstantAppInfo> instantApps = mInstantAppRegistry 8029 .getInstantAppsLPr(userId); 8030 if (instantApps != null) { 8031 return new ParceledListSlice<>(instantApps); 8032 } 8033 } 8034 return null; 8035 } 8036 8037 @Override 8038 public boolean isInstantApp(String packageName, int userId) { 8039 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8040 true /* requireFullPermission */, false /* checkShell */, 8041 "isInstantApp"); 8042 if (HIDE_EPHEMERAL_APIS) { 8043 return false; 8044 } 8045 8046 synchronized (mPackages) { 8047 int callingUid = Binder.getCallingUid(); 8048 if (Process.isIsolated(callingUid)) { 8049 callingUid = mIsolatedOwners.get(callingUid); 8050 } 8051 final PackageSetting ps = mSettings.mPackages.get(packageName); 8052 PackageParser.Package pkg = mPackages.get(packageName); 8053 final boolean returnAllowed = 8054 ps != null 8055 && (isCallerSameApp(packageName, callingUid) 8056 || canViewInstantApps(callingUid, userId) 8057 || mInstantAppRegistry.isInstantAccessGranted( 8058 userId, UserHandle.getAppId(callingUid), ps.appId)); 8059 if (returnAllowed) { 8060 return ps.getInstantApp(userId); 8061 } 8062 } 8063 return false; 8064 } 8065 8066 @Override 8067 public byte[] getInstantAppCookie(String packageName, int userId) { 8068 if (HIDE_EPHEMERAL_APIS) { 8069 return null; 8070 } 8071 8072 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8073 true /* requireFullPermission */, false /* checkShell */, 8074 "getInstantAppCookie"); 8075 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8076 return null; 8077 } 8078 synchronized (mPackages) { 8079 return mInstantAppRegistry.getInstantAppCookieLPw( 8080 packageName, userId); 8081 } 8082 } 8083 8084 @Override 8085 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8086 if (HIDE_EPHEMERAL_APIS) { 8087 return true; 8088 } 8089 8090 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8091 true /* requireFullPermission */, true /* checkShell */, 8092 "setInstantAppCookie"); 8093 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8094 return false; 8095 } 8096 synchronized (mPackages) { 8097 return mInstantAppRegistry.setInstantAppCookieLPw( 8098 packageName, cookie, userId); 8099 } 8100 } 8101 8102 @Override 8103 public Bitmap getInstantAppIcon(String packageName, int userId) { 8104 if (HIDE_EPHEMERAL_APIS) { 8105 return null; 8106 } 8107 8108 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8109 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8110 "getInstantAppIcon"); 8111 } 8112 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8113 true /* requireFullPermission */, false /* checkShell */, 8114 "getInstantAppIcon"); 8115 8116 synchronized (mPackages) { 8117 return mInstantAppRegistry.getInstantAppIconLPw( 8118 packageName, userId); 8119 } 8120 } 8121 8122 private boolean isCallerSameApp(String packageName, int uid) { 8123 PackageParser.Package pkg = mPackages.get(packageName); 8124 return pkg != null 8125 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8126 } 8127 8128 @Override 8129 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8130 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8131 return ParceledListSlice.emptyList(); 8132 } 8133 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8134 } 8135 8136 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8137 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8138 8139 // reader 8140 synchronized (mPackages) { 8141 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8142 final int userId = UserHandle.getCallingUserId(); 8143 while (i.hasNext()) { 8144 final PackageParser.Package p = i.next(); 8145 if (p.applicationInfo == null) continue; 8146 8147 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8148 && !p.applicationInfo.isDirectBootAware(); 8149 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8150 && p.applicationInfo.isDirectBootAware(); 8151 8152 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8153 && (!mSafeMode || isSystemApp(p)) 8154 && (matchesUnaware || matchesAware)) { 8155 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8156 if (ps != null) { 8157 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8158 ps.readUserState(userId), userId); 8159 if (ai != null) { 8160 finalList.add(ai); 8161 } 8162 } 8163 } 8164 } 8165 } 8166 8167 return finalList; 8168 } 8169 8170 @Override 8171 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8172 return resolveContentProviderInternal(name, flags, userId); 8173 } 8174 8175 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8176 if (!sUserManager.exists(userId)) return null; 8177 flags = updateFlagsForComponent(flags, userId, name); 8178 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8179 // reader 8180 synchronized (mPackages) { 8181 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8182 PackageSetting ps = provider != null 8183 ? mSettings.mPackages.get(provider.owner.packageName) 8184 : null; 8185 if (ps != null) { 8186 final boolean isInstantApp = ps.getInstantApp(userId); 8187 // normal application; filter out instant application provider 8188 if (instantAppPkgName == null && isInstantApp) { 8189 return null; 8190 } 8191 // instant application; filter out other instant applications 8192 if (instantAppPkgName != null 8193 && isInstantApp 8194 && !provider.owner.packageName.equals(instantAppPkgName)) { 8195 return null; 8196 } 8197 // instant application; filter out non-exposed provider 8198 if (instantAppPkgName != null 8199 && !isInstantApp 8200 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8201 return null; 8202 } 8203 // provider not enabled 8204 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8205 return null; 8206 } 8207 return PackageParser.generateProviderInfo( 8208 provider, flags, ps.readUserState(userId), userId); 8209 } 8210 return null; 8211 } 8212 } 8213 8214 /** 8215 * @deprecated 8216 */ 8217 @Deprecated 8218 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8219 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8220 return; 8221 } 8222 // reader 8223 synchronized (mPackages) { 8224 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8225 .entrySet().iterator(); 8226 final int userId = UserHandle.getCallingUserId(); 8227 while (i.hasNext()) { 8228 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8229 PackageParser.Provider p = entry.getValue(); 8230 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8231 8232 if (ps != null && p.syncable 8233 && (!mSafeMode || (p.info.applicationInfo.flags 8234 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8235 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8236 ps.readUserState(userId), userId); 8237 if (info != null) { 8238 outNames.add(entry.getKey()); 8239 outInfo.add(info); 8240 } 8241 } 8242 } 8243 } 8244 } 8245 8246 @Override 8247 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8248 int uid, int flags, String metaDataKey) { 8249 final int callingUid = Binder.getCallingUid(); 8250 final int userId = processName != null ? UserHandle.getUserId(uid) 8251 : UserHandle.getCallingUserId(); 8252 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8253 flags = updateFlagsForComponent(flags, userId, processName); 8254 ArrayList<ProviderInfo> finalList = null; 8255 // reader 8256 synchronized (mPackages) { 8257 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8258 while (i.hasNext()) { 8259 final PackageParser.Provider p = i.next(); 8260 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8261 if (ps != null && p.info.authority != null 8262 && (processName == null 8263 || (p.info.processName.equals(processName) 8264 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8265 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8266 8267 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8268 // parameter. 8269 if (metaDataKey != null 8270 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8271 continue; 8272 } 8273 final ComponentName component = 8274 new ComponentName(p.info.packageName, p.info.name); 8275 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8276 continue; 8277 } 8278 if (finalList == null) { 8279 finalList = new ArrayList<ProviderInfo>(3); 8280 } 8281 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8282 ps.readUserState(userId), userId); 8283 if (info != null) { 8284 finalList.add(info); 8285 } 8286 } 8287 } 8288 } 8289 8290 if (finalList != null) { 8291 Collections.sort(finalList, mProviderInitOrderSorter); 8292 return new ParceledListSlice<ProviderInfo>(finalList); 8293 } 8294 8295 return ParceledListSlice.emptyList(); 8296 } 8297 8298 @Override 8299 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8300 // reader 8301 synchronized (mPackages) { 8302 final int callingUid = Binder.getCallingUid(); 8303 final int callingUserId = UserHandle.getUserId(callingUid); 8304 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8305 if (ps == null) return null; 8306 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8307 return null; 8308 } 8309 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8310 return PackageParser.generateInstrumentationInfo(i, flags); 8311 } 8312 } 8313 8314 @Override 8315 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8316 String targetPackage, int flags) { 8317 final int callingUid = Binder.getCallingUid(); 8318 final int callingUserId = UserHandle.getUserId(callingUid); 8319 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8320 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8321 return ParceledListSlice.emptyList(); 8322 } 8323 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8324 } 8325 8326 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8327 int flags) { 8328 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8329 8330 // reader 8331 synchronized (mPackages) { 8332 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8333 while (i.hasNext()) { 8334 final PackageParser.Instrumentation p = i.next(); 8335 if (targetPackage == null 8336 || targetPackage.equals(p.info.targetPackage)) { 8337 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8338 flags); 8339 if (ii != null) { 8340 finalList.add(ii); 8341 } 8342 } 8343 } 8344 } 8345 8346 return finalList; 8347 } 8348 8349 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8350 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8351 try { 8352 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8353 } finally { 8354 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8355 } 8356 } 8357 8358 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8359 final File[] files = scanDir.listFiles(); 8360 if (ArrayUtils.isEmpty(files)) { 8361 Log.d(TAG, "No files in app dir " + scanDir); 8362 return; 8363 } 8364 8365 if (DEBUG_PACKAGE_SCANNING) { 8366 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8367 + " flags=0x" + Integer.toHexString(parseFlags)); 8368 } 8369 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8370 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8371 mParallelPackageParserCallback)) { 8372 // Submit files for parsing in parallel 8373 int fileCount = 0; 8374 for (File file : files) { 8375 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8376 && !PackageInstallerService.isStageName(file.getName()); 8377 if (!isPackage) { 8378 // Ignore entries which are not packages 8379 continue; 8380 } 8381 parallelPackageParser.submit(file, parseFlags); 8382 fileCount++; 8383 } 8384 8385 // Process results one by one 8386 for (; fileCount > 0; fileCount--) { 8387 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8388 Throwable throwable = parseResult.throwable; 8389 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8390 8391 if (throwable == null) { 8392 // TODO(toddke): move lower in the scan chain 8393 // Static shared libraries have synthetic package names 8394 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8395 renameStaticSharedLibraryPackage(parseResult.pkg); 8396 } 8397 try { 8398 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8399 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8400 currentTime, null); 8401 } 8402 } catch (PackageManagerException e) { 8403 errorCode = e.error; 8404 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8405 } 8406 } else if (throwable instanceof PackageParser.PackageParserException) { 8407 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8408 throwable; 8409 errorCode = e.error; 8410 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8411 } else { 8412 throw new IllegalStateException("Unexpected exception occurred while parsing " 8413 + parseResult.scanFile, throwable); 8414 } 8415 8416 // Delete invalid userdata apps 8417 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8418 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8419 logCriticalInfo(Log.WARN, 8420 "Deleting invalid package at " + parseResult.scanFile); 8421 removeCodePathLI(parseResult.scanFile); 8422 } 8423 } 8424 } 8425 } 8426 8427 public static void reportSettingsProblem(int priority, String msg) { 8428 logCriticalInfo(priority, msg); 8429 } 8430 8431 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8432 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 8433 // When upgrading from pre-N MR1, verify the package time stamp using the package 8434 // directory and not the APK file. 8435 final long lastModifiedTime = mIsPreNMR1Upgrade 8436 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8437 if (ps != null && !forceCollect 8438 && ps.codePathString.equals(pkg.codePath) 8439 && ps.timeStamp == lastModifiedTime 8440 && !isCompatSignatureUpdateNeeded(pkg) 8441 && !isRecoverSignatureUpdateNeeded(pkg)) { 8442 if (ps.signatures.mSigningDetails.signatures != null 8443 && ps.signatures.mSigningDetails.signatures.length != 0 8444 && ps.signatures.mSigningDetails.signatureSchemeVersion 8445 != SignatureSchemeVersion.UNKNOWN) { 8446 // Optimization: reuse the existing cached signing data 8447 // if the package appears to be unchanged. 8448 pkg.mSigningDetails = 8449 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8450 return; 8451 } 8452 8453 Slog.w(TAG, "PackageSetting for " + ps.name 8454 + " is missing signatures. Collecting certs again to recover them."); 8455 } else { 8456 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8457 (forceCollect ? " (forced)" : "")); 8458 } 8459 8460 try { 8461 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8462 PackageParser.collectCertificates(pkg, skipVerify); 8463 } catch (PackageParserException e) { 8464 throw PackageManagerException.from(e); 8465 } finally { 8466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8467 } 8468 } 8469 8470 /** 8471 * Traces a package scan. 8472 * @see #scanPackageLI(File, int, int, long, UserHandle) 8473 */ 8474 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8475 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8476 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8477 try { 8478 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8479 } finally { 8480 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8481 } 8482 } 8483 8484 /** 8485 * Scans a package and returns the newly parsed package. 8486 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8487 */ 8488 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8489 long currentTime, UserHandle user) throws PackageManagerException { 8490 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8491 PackageParser pp = new PackageParser(); 8492 pp.setSeparateProcesses(mSeparateProcesses); 8493 pp.setOnlyCoreApps(mOnlyCore); 8494 pp.setDisplayMetrics(mMetrics); 8495 pp.setCallback(mPackageParserCallback); 8496 8497 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8498 final PackageParser.Package pkg; 8499 try { 8500 pkg = pp.parsePackage(scanFile, parseFlags); 8501 } catch (PackageParserException e) { 8502 throw PackageManagerException.from(e); 8503 } finally { 8504 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8505 } 8506 8507 // Static shared libraries have synthetic package names 8508 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8509 renameStaticSharedLibraryPackage(pkg); 8510 } 8511 8512 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8513 } 8514 8515 /** 8516 * Scans a package and returns the newly parsed package. 8517 * @throws PackageManagerException on a parse error. 8518 */ 8519 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8520 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8521 @Nullable UserHandle user) 8522 throws PackageManagerException { 8523 // If the package has children and this is the first dive in the function 8524 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8525 // packages (parent and children) would be successfully scanned before the 8526 // actual scan since scanning mutates internal state and we want to atomically 8527 // install the package and its children. 8528 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8529 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8530 scanFlags |= SCAN_CHECK_ONLY; 8531 } 8532 } else { 8533 scanFlags &= ~SCAN_CHECK_ONLY; 8534 } 8535 8536 // Scan the parent 8537 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8538 scanFlags, currentTime, user); 8539 8540 // Scan the children 8541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8542 for (int i = 0; i < childCount; i++) { 8543 PackageParser.Package childPackage = pkg.childPackages.get(i); 8544 addForInitLI(childPackage, parseFlags, scanFlags, 8545 currentTime, user); 8546 } 8547 8548 8549 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8550 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8551 } 8552 8553 return scannedPkg; 8554 } 8555 8556 /** 8557 * Returns if full apk verification can be skipped for the whole package, including the splits. 8558 */ 8559 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8560 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8561 return false; 8562 } 8563 // TODO: Allow base and splits to be verified individually. 8564 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8565 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8566 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8567 return false; 8568 } 8569 } 8570 } 8571 return true; 8572 } 8573 8574 /** 8575 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8576 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8577 * match one in a trusted source, and should be done separately. 8578 */ 8579 private boolean canSkipFullApkVerification(String apkPath) { 8580 byte[] rootHashObserved = null; 8581 try { 8582 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8583 if (rootHashObserved == null) { 8584 return false; // APK does not contain Merkle tree root hash. 8585 } 8586 synchronized (mInstallLock) { 8587 // Returns whether the observed root hash matches what kernel has. 8588 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8589 return true; 8590 } 8591 } catch (InstallerException | IOException | DigestException | 8592 NoSuchAlgorithmException e) { 8593 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8594 } 8595 return false; 8596 } 8597 8598 /** 8599 * Adds a new package to the internal data structures during platform initialization. 8600 * <p>After adding, the package is known to the system and available for querying. 8601 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8602 * etc...], additional checks are performed. Basic verification [such as ensuring 8603 * matching signatures, checking version codes, etc...] occurs if the package is 8604 * identical to a previously known package. If the package fails a signature check, 8605 * the version installed on /data will be removed. If the version of the new package 8606 * is less than or equal than the version on /data, it will be ignored. 8607 * <p>Regardless of the package location, the results are applied to the internal 8608 * structures and the package is made available to the rest of the system. 8609 * <p>NOTE: The return value should be removed. It's the passed in package object. 8610 */ 8611 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8612 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8613 @Nullable UserHandle user) 8614 throws PackageManagerException { 8615 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8616 final String renamedPkgName; 8617 final PackageSetting disabledPkgSetting; 8618 final boolean isSystemPkgUpdated; 8619 final boolean pkgAlreadyExists; 8620 PackageSetting pkgSetting; 8621 8622 // NOTE: installPackageLI() has the same code to setup the package's 8623 // application info. This probably should be done lower in the call 8624 // stack [such as scanPackageOnly()]. However, we verify the application 8625 // info prior to that [in scanPackageNew()] and thus have to setup 8626 // the application info early. 8627 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8628 pkg.setApplicationInfoCodePath(pkg.codePath); 8629 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8630 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8631 pkg.setApplicationInfoResourcePath(pkg.codePath); 8632 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8633 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8634 8635 synchronized (mPackages) { 8636 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8637 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8638 if (realPkgName != null) { 8639 ensurePackageRenamed(pkg, renamedPkgName); 8640 } 8641 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8642 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8643 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8644 pkgAlreadyExists = pkgSetting != null; 8645 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8646 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8647 isSystemPkgUpdated = disabledPkgSetting != null; 8648 8649 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8650 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8651 } 8652 8653 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8654 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8655 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8656 : null; 8657 if (DEBUG_PACKAGE_SCANNING 8658 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8659 && sharedUserSetting != null) { 8660 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8661 + " (uid=" + sharedUserSetting.userId + "):" 8662 + " packages=" + sharedUserSetting.packages); 8663 } 8664 8665 if (scanSystemPartition) { 8666 // Potentially prune child packages. If the application on the /system 8667 // partition has been updated via OTA, but, is still disabled by a 8668 // version on /data, cycle through all of its children packages and 8669 // remove children that are no longer defined. 8670 if (isSystemPkgUpdated) { 8671 final int scannedChildCount = (pkg.childPackages != null) 8672 ? pkg.childPackages.size() : 0; 8673 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8674 ? disabledPkgSetting.childPackageNames.size() : 0; 8675 for (int i = 0; i < disabledChildCount; i++) { 8676 String disabledChildPackageName = 8677 disabledPkgSetting.childPackageNames.get(i); 8678 boolean disabledPackageAvailable = false; 8679 for (int j = 0; j < scannedChildCount; j++) { 8680 PackageParser.Package childPkg = pkg.childPackages.get(j); 8681 if (childPkg.packageName.equals(disabledChildPackageName)) { 8682 disabledPackageAvailable = true; 8683 break; 8684 } 8685 } 8686 if (!disabledPackageAvailable) { 8687 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8688 } 8689 } 8690 // we're updating the disabled package, so, scan it as the package setting 8691 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8692 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8693 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8694 (pkg == mPlatformPackage), user); 8695 applyPolicy(pkg, parseFlags, scanFlags); 8696 scanPackageOnlyLI(request, mFactoryTest, -1L); 8697 } 8698 } 8699 } 8700 8701 final boolean newPkgChangedPaths = 8702 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8703 final boolean newPkgVersionGreater = 8704 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8705 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8706 && newPkgChangedPaths && newPkgVersionGreater; 8707 if (isSystemPkgBetter) { 8708 // The version of the application on /system is greater than the version on 8709 // /data. Switch back to the application on /system. 8710 // It's safe to assume the application on /system will correctly scan. If not, 8711 // there won't be a working copy of the application. 8712 synchronized (mPackages) { 8713 // just remove the loaded entries from package lists 8714 mPackages.remove(pkgSetting.name); 8715 } 8716 8717 logCriticalInfo(Log.WARN, 8718 "System package updated;" 8719 + " name: " + pkgSetting.name 8720 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8721 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8722 8723 final InstallArgs args = createInstallArgsForExisting( 8724 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8725 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8726 args.cleanUpResourcesLI(); 8727 synchronized (mPackages) { 8728 mSettings.enableSystemPackageLPw(pkgSetting.name); 8729 } 8730 } 8731 8732 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8733 // The version of the application on the /system partition is less than or 8734 // equal to the version on the /data partition. Throw an exception and use 8735 // the application already installed on the /data partition. 8736 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8737 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8738 + " better than this " + pkg.getLongVersionCode()); 8739 } 8740 8741 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8742 // force re-collecting certificate. 8743 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8744 disabledPkgSetting); 8745 // Full APK verification can be skipped during certificate collection, only if the file is 8746 // in verified partition, or can be verified on access (when apk verity is enabled). In both 8747 // cases, only data in Signing Block is verified instead of the whole file. 8748 final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) || 8749 (forceCollect && canSkipFullPackageVerification(pkg)); 8750 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 8751 8752 boolean shouldHideSystemApp = false; 8753 // A new application appeared on /system, but, we already have a copy of 8754 // the application installed on /data. 8755 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8756 && !pkgSetting.isSystem()) { 8757 8758 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 8759 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 8760 logCriticalInfo(Log.WARN, 8761 "System package signature mismatch;" 8762 + " name: " + pkgSetting.name); 8763 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8764 "scanPackageInternalLI")) { 8765 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8766 } 8767 pkgSetting = null; 8768 } else if (newPkgVersionGreater) { 8769 // The application on /system is newer than the application on /data. 8770 // Simply remove the application on /data [keeping application data] 8771 // and replace it with the version on /system. 8772 logCriticalInfo(Log.WARN, 8773 "System package enabled;" 8774 + " name: " + pkgSetting.name 8775 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8776 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8777 InstallArgs args = createInstallArgsForExisting( 8778 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8779 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8780 synchronized (mInstallLock) { 8781 args.cleanUpResourcesLI(); 8782 } 8783 } else { 8784 // The application on /system is older than the application on /data. Hide 8785 // the application on /system and the version on /data will be scanned later 8786 // and re-added like an update. 8787 shouldHideSystemApp = true; 8788 logCriticalInfo(Log.INFO, 8789 "System package disabled;" 8790 + " name: " + pkgSetting.name 8791 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8792 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8793 } 8794 } 8795 8796 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8797 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8798 8799 if (shouldHideSystemApp) { 8800 synchronized (mPackages) { 8801 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8802 } 8803 } 8804 return scannedPkg; 8805 } 8806 8807 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8808 // Derive the new package synthetic package name 8809 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8810 + pkg.staticSharedLibVersion); 8811 } 8812 8813 private static String fixProcessName(String defProcessName, 8814 String processName) { 8815 if (processName == null) { 8816 return defProcessName; 8817 } 8818 return processName; 8819 } 8820 8821 /** 8822 * Enforces that only the system UID or root's UID can call a method exposed 8823 * via Binder. 8824 * 8825 * @param message used as message if SecurityException is thrown 8826 * @throws SecurityException if the caller is not system or root 8827 */ 8828 private static final void enforceSystemOrRoot(String message) { 8829 final int uid = Binder.getCallingUid(); 8830 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8831 throw new SecurityException(message); 8832 } 8833 } 8834 8835 @Override 8836 public void performFstrimIfNeeded() { 8837 enforceSystemOrRoot("Only the system can request fstrim"); 8838 8839 // Before everything else, see whether we need to fstrim. 8840 try { 8841 IStorageManager sm = PackageHelper.getStorageManager(); 8842 if (sm != null) { 8843 boolean doTrim = false; 8844 final long interval = android.provider.Settings.Global.getLong( 8845 mContext.getContentResolver(), 8846 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8847 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8848 if (interval > 0) { 8849 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8850 if (timeSinceLast > interval) { 8851 doTrim = true; 8852 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8853 + "; running immediately"); 8854 } 8855 } 8856 if (doTrim) { 8857 final boolean dexOptDialogShown; 8858 synchronized (mPackages) { 8859 dexOptDialogShown = mDexOptDialogShown; 8860 } 8861 if (!isFirstBoot() && dexOptDialogShown) { 8862 try { 8863 ActivityManager.getService().showBootMessage( 8864 mContext.getResources().getString( 8865 R.string.android_upgrading_fstrim), true); 8866 } catch (RemoteException e) { 8867 } 8868 } 8869 sm.runMaintenance(); 8870 } 8871 } else { 8872 Slog.e(TAG, "storageManager service unavailable!"); 8873 } 8874 } catch (RemoteException e) { 8875 // Can't happen; StorageManagerService is local 8876 } 8877 } 8878 8879 @Override 8880 public void updatePackagesIfNeeded() { 8881 enforceSystemOrRoot("Only the system can request package update"); 8882 8883 // We need to re-extract after an OTA. 8884 boolean causeUpgrade = isUpgrade(); 8885 8886 // First boot or factory reset. 8887 // Note: we also handle devices that are upgrading to N right now as if it is their 8888 // first boot, as they do not have profile data. 8889 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8890 8891 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8892 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8893 8894 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8895 return; 8896 } 8897 8898 List<PackageParser.Package> pkgs; 8899 synchronized (mPackages) { 8900 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8901 } 8902 8903 final long startTime = System.nanoTime(); 8904 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8905 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 8906 false /* bootComplete */); 8907 8908 final int elapsedTimeSeconds = 8909 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8910 8911 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8912 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8913 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8914 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8915 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8916 } 8917 8918 /* 8919 * Return the prebuilt profile path given a package base code path. 8920 */ 8921 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8922 return pkg.baseCodePath + ".prof"; 8923 } 8924 8925 /** 8926 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8927 * containing statistics about the invocation. The array consists of three elements, 8928 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8929 * and {@code numberOfPackagesFailed}. 8930 */ 8931 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8932 final int compilationReason, boolean bootComplete) { 8933 8934 int numberOfPackagesVisited = 0; 8935 int numberOfPackagesOptimized = 0; 8936 int numberOfPackagesSkipped = 0; 8937 int numberOfPackagesFailed = 0; 8938 final int numberOfPackagesToDexopt = pkgs.size(); 8939 8940 for (PackageParser.Package pkg : pkgs) { 8941 numberOfPackagesVisited++; 8942 8943 boolean useProfileForDexopt = false; 8944 8945 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8946 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8947 // that are already compiled. 8948 File profileFile = new File(getPrebuildProfilePath(pkg)); 8949 // Copy profile if it exists. 8950 if (profileFile.exists()) { 8951 try { 8952 // We could also do this lazily before calling dexopt in 8953 // PackageDexOptimizer to prevent this happening on first boot. The issue 8954 // is that we don't have a good way to say "do this only once". 8955 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8956 pkg.applicationInfo.uid, pkg.packageName, 8957 ArtManager.getProfileName(null))) { 8958 Log.e(TAG, "Installer failed to copy system profile!"); 8959 } else { 8960 // Disabled as this causes speed-profile compilation during first boot 8961 // even if things are already compiled. 8962 // useProfileForDexopt = true; 8963 } 8964 } catch (Exception e) { 8965 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8966 e); 8967 } 8968 } else { 8969 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8970 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8971 // minimize the number off apps being speed-profile compiled during first boot. 8972 // The other paths will not change the filter. 8973 if (disabledPs != null && disabledPs.pkg.isStub) { 8974 // The package is the stub one, remove the stub suffix to get the normal 8975 // package and APK names. 8976 String systemProfilePath = 8977 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8978 profileFile = new File(systemProfilePath); 8979 // If we have a profile for a compressed APK, copy it to the reference 8980 // location. 8981 // Note that copying the profile here will cause it to override the 8982 // reference profile every OTA even though the existing reference profile 8983 // may have more data. We can't copy during decompression since the 8984 // directories are not set up at that point. 8985 if (profileFile.exists()) { 8986 try { 8987 // We could also do this lazily before calling dexopt in 8988 // PackageDexOptimizer to prevent this happening on first boot. The 8989 // issue is that we don't have a good way to say "do this only 8990 // once". 8991 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8992 pkg.applicationInfo.uid, pkg.packageName, 8993 ArtManager.getProfileName(null))) { 8994 Log.e(TAG, "Failed to copy system profile for stub package!"); 8995 } else { 8996 useProfileForDexopt = true; 8997 } 8998 } catch (Exception e) { 8999 Log.e(TAG, "Failed to copy profile " + 9000 profileFile.getAbsolutePath() + " ", e); 9001 } 9002 } 9003 } 9004 } 9005 } 9006 9007 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9008 if (DEBUG_DEXOPT) { 9009 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9010 } 9011 numberOfPackagesSkipped++; 9012 continue; 9013 } 9014 9015 if (DEBUG_DEXOPT) { 9016 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9017 numberOfPackagesToDexopt + ": " + pkg.packageName); 9018 } 9019 9020 if (showDialog) { 9021 try { 9022 ActivityManager.getService().showBootMessage( 9023 mContext.getResources().getString(R.string.android_upgrading_apk, 9024 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9025 } catch (RemoteException e) { 9026 } 9027 synchronized (mPackages) { 9028 mDexOptDialogShown = true; 9029 } 9030 } 9031 9032 int pkgCompilationReason = compilationReason; 9033 if (useProfileForDexopt) { 9034 // Use background dexopt mode to try and use the profile. Note that this does not 9035 // guarantee usage of the profile. 9036 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9037 } 9038 9039 // checkProfiles is false to avoid merging profiles during boot which 9040 // might interfere with background compilation (b/28612421). 9041 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9042 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9043 // trade-off worth doing to save boot time work. 9044 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9045 if (compilationReason == REASON_FIRST_BOOT) { 9046 // TODO: This doesn't cover the upgrade case, we should check for this too. 9047 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9048 } 9049 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9050 pkg.packageName, 9051 pkgCompilationReason, 9052 dexoptFlags)); 9053 9054 switch (primaryDexOptStaus) { 9055 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9056 numberOfPackagesOptimized++; 9057 break; 9058 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9059 numberOfPackagesSkipped++; 9060 break; 9061 case PackageDexOptimizer.DEX_OPT_FAILED: 9062 numberOfPackagesFailed++; 9063 break; 9064 default: 9065 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9066 break; 9067 } 9068 } 9069 9070 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9071 numberOfPackagesFailed }; 9072 } 9073 9074 @Override 9075 public void notifyPackageUse(String packageName, int reason) { 9076 synchronized (mPackages) { 9077 final int callingUid = Binder.getCallingUid(); 9078 final int callingUserId = UserHandle.getUserId(callingUid); 9079 if (getInstantAppPackageName(callingUid) != null) { 9080 if (!isCallerSameApp(packageName, callingUid)) { 9081 return; 9082 } 9083 } else { 9084 if (isInstantApp(packageName, callingUserId)) { 9085 return; 9086 } 9087 } 9088 notifyPackageUseLocked(packageName, reason); 9089 } 9090 } 9091 9092 @GuardedBy("mPackages") 9093 private void notifyPackageUseLocked(String packageName, int reason) { 9094 final PackageParser.Package p = mPackages.get(packageName); 9095 if (p == null) { 9096 return; 9097 } 9098 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9099 } 9100 9101 @Override 9102 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9103 List<String> classPaths, String loaderIsa) { 9104 int userId = UserHandle.getCallingUserId(); 9105 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9106 if (ai == null) { 9107 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9108 + loadingPackageName + ", user=" + userId); 9109 return; 9110 } 9111 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9112 } 9113 9114 @Override 9115 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9116 IDexModuleRegisterCallback callback) { 9117 int userId = UserHandle.getCallingUserId(); 9118 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9119 DexManager.RegisterDexModuleResult result; 9120 if (ai == null) { 9121 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9122 " calling user. package=" + packageName + ", user=" + userId); 9123 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9124 } else { 9125 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9126 } 9127 9128 if (callback != null) { 9129 mHandler.post(() -> { 9130 try { 9131 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9132 } catch (RemoteException e) { 9133 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9134 } 9135 }); 9136 } 9137 } 9138 9139 /** 9140 * Ask the package manager to perform a dex-opt with the given compiler filter. 9141 * 9142 * Note: exposed only for the shell command to allow moving packages explicitly to a 9143 * definite state. 9144 */ 9145 @Override 9146 public boolean performDexOptMode(String packageName, 9147 boolean checkProfiles, String targetCompilerFilter, boolean force, 9148 boolean bootComplete, String splitName) { 9149 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9150 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9151 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9152 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9153 targetCompilerFilter, splitName, flags)); 9154 } 9155 9156 /** 9157 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9158 * secondary dex files belonging to the given package. 9159 * 9160 * Note: exposed only for the shell command to allow moving packages explicitly to a 9161 * definite state. 9162 */ 9163 @Override 9164 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9165 boolean force) { 9166 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9167 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9168 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9169 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9170 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9171 } 9172 9173 /*package*/ boolean performDexOpt(DexoptOptions options) { 9174 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9175 return false; 9176 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9177 return false; 9178 } 9179 9180 if (options.isDexoptOnlySecondaryDex()) { 9181 return mDexManager.dexoptSecondaryDex(options); 9182 } else { 9183 int dexoptStatus = performDexOptWithStatus(options); 9184 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9185 } 9186 } 9187 9188 /** 9189 * Perform dexopt on the given package and return one of following result: 9190 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9191 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9192 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9193 */ 9194 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9195 return performDexOptTraced(options); 9196 } 9197 9198 private int performDexOptTraced(DexoptOptions options) { 9199 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9200 try { 9201 return performDexOptInternal(options); 9202 } finally { 9203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9204 } 9205 } 9206 9207 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9208 // if the package can now be considered up to date for the given filter. 9209 private int performDexOptInternal(DexoptOptions options) { 9210 PackageParser.Package p; 9211 synchronized (mPackages) { 9212 p = mPackages.get(options.getPackageName()); 9213 if (p == null) { 9214 // Package could not be found. Report failure. 9215 return PackageDexOptimizer.DEX_OPT_FAILED; 9216 } 9217 mPackageUsage.maybeWriteAsync(mPackages); 9218 mCompilerStats.maybeWriteAsync(); 9219 } 9220 long callingId = Binder.clearCallingIdentity(); 9221 try { 9222 synchronized (mInstallLock) { 9223 return performDexOptInternalWithDependenciesLI(p, options); 9224 } 9225 } finally { 9226 Binder.restoreCallingIdentity(callingId); 9227 } 9228 } 9229 9230 public ArraySet<String> getOptimizablePackages() { 9231 ArraySet<String> pkgs = new ArraySet<String>(); 9232 synchronized (mPackages) { 9233 for (PackageParser.Package p : mPackages.values()) { 9234 if (PackageDexOptimizer.canOptimizePackage(p)) { 9235 pkgs.add(p.packageName); 9236 } 9237 } 9238 } 9239 return pkgs; 9240 } 9241 9242 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9243 DexoptOptions options) { 9244 // Select the dex optimizer based on the force parameter. 9245 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9246 // allocate an object here. 9247 PackageDexOptimizer pdo = options.isForce() 9248 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9249 : mPackageDexOptimizer; 9250 9251 // Dexopt all dependencies first. Note: we ignore the return value and march on 9252 // on errors. 9253 // Note that we are going to call performDexOpt on those libraries as many times as 9254 // they are referenced in packages. When we do a batch of performDexOpt (for example 9255 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9256 // and the first package that uses the library will dexopt it. The 9257 // others will see that the compiled code for the library is up to date. 9258 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9259 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9260 if (!deps.isEmpty()) { 9261 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9262 options.getCompilationReason(), options.getCompilerFilter(), 9263 options.getSplitName(), 9264 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9265 for (PackageParser.Package depPackage : deps) { 9266 // TODO: Analyze and investigate if we (should) profile libraries. 9267 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9268 getOrCreateCompilerPackageStats(depPackage), 9269 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9270 } 9271 } 9272 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9273 getOrCreateCompilerPackageStats(p), 9274 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9275 } 9276 9277 /** 9278 * Reconcile the information we have about the secondary dex files belonging to 9279 * {@code packagName} and the actual dex files. For all dex files that were 9280 * deleted, update the internal records and delete the generated oat files. 9281 */ 9282 @Override 9283 public void reconcileSecondaryDexFiles(String packageName) { 9284 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9285 return; 9286 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9287 return; 9288 } 9289 mDexManager.reconcileSecondaryDexFiles(packageName); 9290 } 9291 9292 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9293 // a reference there. 9294 /*package*/ DexManager getDexManager() { 9295 return mDexManager; 9296 } 9297 9298 /** 9299 * Execute the background dexopt job immediately. 9300 */ 9301 @Override 9302 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9303 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9304 return false; 9305 } 9306 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9307 } 9308 9309 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9310 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9311 || p.usesStaticLibraries != null) { 9312 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9313 Set<String> collectedNames = new HashSet<>(); 9314 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9315 9316 retValue.remove(p); 9317 9318 return retValue; 9319 } else { 9320 return Collections.emptyList(); 9321 } 9322 } 9323 9324 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9325 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9326 if (!collectedNames.contains(p.packageName)) { 9327 collectedNames.add(p.packageName); 9328 collected.add(p); 9329 9330 if (p.usesLibraries != null) { 9331 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9332 null, collected, collectedNames); 9333 } 9334 if (p.usesOptionalLibraries != null) { 9335 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9336 null, collected, collectedNames); 9337 } 9338 if (p.usesStaticLibraries != null) { 9339 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9340 p.usesStaticLibrariesVersions, collected, collectedNames); 9341 } 9342 } 9343 } 9344 9345 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9346 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9347 final int libNameCount = libs.size(); 9348 for (int i = 0; i < libNameCount; i++) { 9349 String libName = libs.get(i); 9350 long version = (versions != null && versions.length == libNameCount) 9351 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9352 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9353 if (libPkg != null) { 9354 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9355 } 9356 } 9357 } 9358 9359 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9360 synchronized (mPackages) { 9361 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9362 if (libEntry != null) { 9363 return mPackages.get(libEntry.apk); 9364 } 9365 return null; 9366 } 9367 } 9368 9369 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9370 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9371 if (versionedLib == null) { 9372 return null; 9373 } 9374 return versionedLib.get(version); 9375 } 9376 9377 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9378 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9379 pkg.staticSharedLibName); 9380 if (versionedLib == null) { 9381 return null; 9382 } 9383 long previousLibVersion = -1; 9384 final int versionCount = versionedLib.size(); 9385 for (int i = 0; i < versionCount; i++) { 9386 final long libVersion = versionedLib.keyAt(i); 9387 if (libVersion < pkg.staticSharedLibVersion) { 9388 previousLibVersion = Math.max(previousLibVersion, libVersion); 9389 } 9390 } 9391 if (previousLibVersion >= 0) { 9392 return versionedLib.get(previousLibVersion); 9393 } 9394 return null; 9395 } 9396 9397 public void shutdown() { 9398 mPackageUsage.writeNow(mPackages); 9399 mCompilerStats.writeNow(); 9400 mDexManager.writePackageDexUsageNow(); 9401 } 9402 9403 @Override 9404 public void dumpProfiles(String packageName) { 9405 PackageParser.Package pkg; 9406 synchronized (mPackages) { 9407 pkg = mPackages.get(packageName); 9408 if (pkg == null) { 9409 throw new IllegalArgumentException("Unknown package: " + packageName); 9410 } 9411 } 9412 /* Only the shell, root, or the app user should be able to dump profiles. */ 9413 int callingUid = Binder.getCallingUid(); 9414 if (callingUid != Process.SHELL_UID && 9415 callingUid != Process.ROOT_UID && 9416 callingUid != pkg.applicationInfo.uid) { 9417 throw new SecurityException("dumpProfiles"); 9418 } 9419 9420 synchronized (mInstallLock) { 9421 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9422 mArtManagerService.dumpProfiles(pkg); 9423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9424 } 9425 } 9426 9427 @Override 9428 public void forceDexOpt(String packageName) { 9429 enforceSystemOrRoot("forceDexOpt"); 9430 9431 PackageParser.Package pkg; 9432 synchronized (mPackages) { 9433 pkg = mPackages.get(packageName); 9434 if (pkg == null) { 9435 throw new IllegalArgumentException("Unknown package: " + packageName); 9436 } 9437 } 9438 9439 synchronized (mInstallLock) { 9440 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9441 9442 // Whoever is calling forceDexOpt wants a compiled package. 9443 // Don't use profiles since that may cause compilation to be skipped. 9444 final int res = performDexOptInternalWithDependenciesLI( 9445 pkg, 9446 new DexoptOptions(packageName, 9447 getDefaultCompilerFilter(), 9448 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9449 9450 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9451 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9452 throw new IllegalStateException("Failed to dexopt: " + res); 9453 } 9454 } 9455 } 9456 9457 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9458 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9459 Slog.w(TAG, "Unable to update from " + oldPkg.name 9460 + " to " + newPkg.packageName 9461 + ": old package not in system partition"); 9462 return false; 9463 } else if (mPackages.get(oldPkg.name) != null) { 9464 Slog.w(TAG, "Unable to update from " + oldPkg.name 9465 + " to " + newPkg.packageName 9466 + ": old package still exists"); 9467 return false; 9468 } 9469 return true; 9470 } 9471 9472 void removeCodePathLI(File codePath) { 9473 if (codePath.isDirectory()) { 9474 try { 9475 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9476 } catch (InstallerException e) { 9477 Slog.w(TAG, "Failed to remove code path", e); 9478 } 9479 } else { 9480 codePath.delete(); 9481 } 9482 } 9483 9484 private int[] resolveUserIds(int userId) { 9485 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9486 } 9487 9488 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9489 if (pkg == null) { 9490 Slog.wtf(TAG, "Package was null!", new Throwable()); 9491 return; 9492 } 9493 clearAppDataLeafLIF(pkg, userId, flags); 9494 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9495 for (int i = 0; i < childCount; i++) { 9496 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9497 } 9498 9499 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9500 } 9501 9502 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9503 final PackageSetting ps; 9504 synchronized (mPackages) { 9505 ps = mSettings.mPackages.get(pkg.packageName); 9506 } 9507 for (int realUserId : resolveUserIds(userId)) { 9508 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9509 try { 9510 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9511 ceDataInode); 9512 } catch (InstallerException e) { 9513 Slog.w(TAG, String.valueOf(e)); 9514 } 9515 } 9516 } 9517 9518 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9519 if (pkg == null) { 9520 Slog.wtf(TAG, "Package was null!", new Throwable()); 9521 return; 9522 } 9523 destroyAppDataLeafLIF(pkg, userId, flags); 9524 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9525 for (int i = 0; i < childCount; i++) { 9526 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9527 } 9528 } 9529 9530 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9531 final PackageSetting ps; 9532 synchronized (mPackages) { 9533 ps = mSettings.mPackages.get(pkg.packageName); 9534 } 9535 for (int realUserId : resolveUserIds(userId)) { 9536 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9537 try { 9538 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9539 ceDataInode); 9540 } catch (InstallerException e) { 9541 Slog.w(TAG, String.valueOf(e)); 9542 } 9543 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9544 } 9545 } 9546 9547 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9548 if (pkg == null) { 9549 Slog.wtf(TAG, "Package was null!", new Throwable()); 9550 return; 9551 } 9552 destroyAppProfilesLeafLIF(pkg); 9553 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9554 for (int i = 0; i < childCount; i++) { 9555 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9556 } 9557 } 9558 9559 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9560 try { 9561 mInstaller.destroyAppProfiles(pkg.packageName); 9562 } catch (InstallerException e) { 9563 Slog.w(TAG, String.valueOf(e)); 9564 } 9565 } 9566 9567 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9568 if (pkg == null) { 9569 Slog.wtf(TAG, "Package was null!", new Throwable()); 9570 return; 9571 } 9572 mArtManagerService.clearAppProfiles(pkg); 9573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9574 for (int i = 0; i < childCount; i++) { 9575 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9576 } 9577 } 9578 9579 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9580 long lastUpdateTime) { 9581 // Set parent install/update time 9582 PackageSetting ps = (PackageSetting) pkg.mExtras; 9583 if (ps != null) { 9584 ps.firstInstallTime = firstInstallTime; 9585 ps.lastUpdateTime = lastUpdateTime; 9586 } 9587 // Set children install/update time 9588 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9589 for (int i = 0; i < childCount; i++) { 9590 PackageParser.Package childPkg = pkg.childPackages.get(i); 9591 ps = (PackageSetting) childPkg.mExtras; 9592 if (ps != null) { 9593 ps.firstInstallTime = firstInstallTime; 9594 ps.lastUpdateTime = lastUpdateTime; 9595 } 9596 } 9597 } 9598 9599 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9600 SharedLibraryEntry file, 9601 PackageParser.Package changingLib) { 9602 if (file.path != null) { 9603 usesLibraryFiles.add(file.path); 9604 return; 9605 } 9606 PackageParser.Package p = mPackages.get(file.apk); 9607 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9608 // If we are doing this while in the middle of updating a library apk, 9609 // then we need to make sure to use that new apk for determining the 9610 // dependencies here. (We haven't yet finished committing the new apk 9611 // to the package manager state.) 9612 if (p == null || p.packageName.equals(changingLib.packageName)) { 9613 p = changingLib; 9614 } 9615 } 9616 if (p != null) { 9617 usesLibraryFiles.addAll(p.getAllCodePaths()); 9618 if (p.usesLibraryFiles != null) { 9619 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9620 } 9621 } 9622 } 9623 9624 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9625 PackageParser.Package changingLib) throws PackageManagerException { 9626 if (pkg == null) { 9627 return; 9628 } 9629 // The collection used here must maintain the order of addition (so 9630 // that libraries are searched in the correct order) and must have no 9631 // duplicates. 9632 Set<String> usesLibraryFiles = null; 9633 if (pkg.usesLibraries != null) { 9634 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9635 null, null, pkg.packageName, changingLib, true, 9636 pkg.applicationInfo.targetSdkVersion, null); 9637 } 9638 if (pkg.usesStaticLibraries != null) { 9639 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9640 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9641 pkg.packageName, changingLib, true, 9642 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9643 } 9644 if (pkg.usesOptionalLibraries != null) { 9645 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9646 null, null, pkg.packageName, changingLib, false, 9647 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9648 } 9649 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9650 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9651 } else { 9652 pkg.usesLibraryFiles = null; 9653 } 9654 } 9655 9656 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9657 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9658 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9659 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9660 throws PackageManagerException { 9661 final int libCount = requestedLibraries.size(); 9662 for (int i = 0; i < libCount; i++) { 9663 final String libName = requestedLibraries.get(i); 9664 final long libVersion = requiredVersions != null ? requiredVersions[i] 9665 : SharedLibraryInfo.VERSION_UNDEFINED; 9666 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9667 if (libEntry == null) { 9668 if (required) { 9669 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9670 "Package " + packageName + " requires unavailable shared library " 9671 + libName + "; failing!"); 9672 } else if (DEBUG_SHARED_LIBRARIES) { 9673 Slog.i(TAG, "Package " + packageName 9674 + " desires unavailable shared library " 9675 + libName + "; ignoring!"); 9676 } 9677 } else { 9678 if (requiredVersions != null && requiredCertDigests != null) { 9679 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9680 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9681 "Package " + packageName + " requires unavailable static shared" 9682 + " library " + libName + " version " 9683 + libEntry.info.getLongVersion() + "; failing!"); 9684 } 9685 9686 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9687 if (libPkg == null) { 9688 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9689 "Package " + packageName + " requires unavailable static shared" 9690 + " library; failing!"); 9691 } 9692 9693 final String[] expectedCertDigests = requiredCertDigests[i]; 9694 9695 9696 if (expectedCertDigests.length > 1) { 9697 9698 // For apps targeting O MR1 we require explicit enumeration of all certs. 9699 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9700 ? PackageUtils.computeSignaturesSha256Digests( 9701 libPkg.mSigningDetails.signatures) 9702 : PackageUtils.computeSignaturesSha256Digests( 9703 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9704 9705 // Take a shortcut if sizes don't match. Note that if an app doesn't 9706 // target O we don't parse the "additional-certificate" tags similarly 9707 // how we only consider all certs only for apps targeting O (see above). 9708 // Therefore, the size check is safe to make. 9709 if (expectedCertDigests.length != libCertDigests.length) { 9710 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9711 "Package " + packageName + " requires differently signed" + 9712 " static shared library; failing!"); 9713 } 9714 9715 // Use a predictable order as signature order may vary 9716 Arrays.sort(libCertDigests); 9717 Arrays.sort(expectedCertDigests); 9718 9719 final int certCount = libCertDigests.length; 9720 for (int j = 0; j < certCount; j++) { 9721 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9722 throw new PackageManagerException( 9723 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9724 "Package " + packageName + " requires differently signed" + 9725 " static shared library; failing!"); 9726 } 9727 } 9728 } else { 9729 9730 // lib signing cert could have rotated beyond the one expected, check to see 9731 // if the new one has been blessed by the old 9732 if (!libPkg.mSigningDetails.hasSha256Certificate( 9733 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 9734 throw new PackageManagerException( 9735 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9736 "Package " + packageName + " requires differently signed" + 9737 " static shared library; failing!"); 9738 } 9739 } 9740 } 9741 9742 if (outUsedLibraries == null) { 9743 // Use LinkedHashSet to preserve the order of files added to 9744 // usesLibraryFiles while eliminating duplicates. 9745 outUsedLibraries = new LinkedHashSet<>(); 9746 } 9747 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9748 } 9749 } 9750 return outUsedLibraries; 9751 } 9752 9753 private static boolean hasString(List<String> list, List<String> which) { 9754 if (list == null) { 9755 return false; 9756 } 9757 for (int i=list.size()-1; i>=0; i--) { 9758 for (int j=which.size()-1; j>=0; j--) { 9759 if (which.get(j).equals(list.get(i))) { 9760 return true; 9761 } 9762 } 9763 } 9764 return false; 9765 } 9766 9767 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9768 PackageParser.Package changingPkg) { 9769 ArrayList<PackageParser.Package> res = null; 9770 for (PackageParser.Package pkg : mPackages.values()) { 9771 if (changingPkg != null 9772 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9773 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9774 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9775 changingPkg.staticSharedLibName)) { 9776 return null; 9777 } 9778 if (res == null) { 9779 res = new ArrayList<>(); 9780 } 9781 res.add(pkg); 9782 try { 9783 updateSharedLibrariesLPr(pkg, changingPkg); 9784 } catch (PackageManagerException e) { 9785 // If a system app update or an app and a required lib missing we 9786 // delete the package and for updated system apps keep the data as 9787 // it is better for the user to reinstall than to be in an limbo 9788 // state. Also libs disappearing under an app should never happen 9789 // - just in case. 9790 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9791 final int flags = pkg.isUpdatedSystemApp() 9792 ? PackageManager.DELETE_KEEP_DATA : 0; 9793 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9794 flags , null, true, null); 9795 } 9796 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9797 } 9798 } 9799 return res; 9800 } 9801 9802 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9803 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9804 @Nullable UserHandle user) throws PackageManagerException { 9805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9806 // If the package has children and this is the first dive in the function 9807 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9808 // whether all packages (parent and children) would be successfully scanned 9809 // before the actual scan since scanning mutates internal state and we want 9810 // to atomically install the package and its children. 9811 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9812 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9813 scanFlags |= SCAN_CHECK_ONLY; 9814 } 9815 } else { 9816 scanFlags &= ~SCAN_CHECK_ONLY; 9817 } 9818 9819 final PackageParser.Package scannedPkg; 9820 try { 9821 // Scan the parent 9822 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9823 // Scan the children 9824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9825 for (int i = 0; i < childCount; i++) { 9826 PackageParser.Package childPkg = pkg.childPackages.get(i); 9827 scanPackageNewLI(childPkg, parseFlags, 9828 scanFlags, currentTime, user); 9829 } 9830 } finally { 9831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9832 } 9833 9834 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9835 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9836 } 9837 9838 return scannedPkg; 9839 } 9840 9841 /** The result of a package scan. */ 9842 private static class ScanResult { 9843 /** Whether or not the package scan was successful */ 9844 public final boolean success; 9845 /** 9846 * The final package settings. This may be the same object passed in 9847 * the {@link ScanRequest}, but, with modified values. 9848 */ 9849 @Nullable public final PackageSetting pkgSetting; 9850 /** ABI code paths that have changed in the package scan */ 9851 @Nullable public final List<String> changedAbiCodePath; 9852 public ScanResult( 9853 boolean success, 9854 @Nullable PackageSetting pkgSetting, 9855 @Nullable List<String> changedAbiCodePath) { 9856 this.success = success; 9857 this.pkgSetting = pkgSetting; 9858 this.changedAbiCodePath = changedAbiCodePath; 9859 } 9860 } 9861 9862 /** A package to be scanned */ 9863 private static class ScanRequest { 9864 /** The parsed package */ 9865 @NonNull public final PackageParser.Package pkg; 9866 /** Shared user settings, if the package has a shared user */ 9867 @Nullable public final SharedUserSetting sharedUserSetting; 9868 /** 9869 * Package settings of the currently installed version. 9870 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9871 * during scan. 9872 */ 9873 @Nullable public final PackageSetting pkgSetting; 9874 /** A copy of the settings for the currently installed version */ 9875 @Nullable public final PackageSetting oldPkgSetting; 9876 /** Package settings for the disabled version on the /system partition */ 9877 @Nullable public final PackageSetting disabledPkgSetting; 9878 /** Package settings for the installed version under its original package name */ 9879 @Nullable public final PackageSetting originalPkgSetting; 9880 /** The real package name of a renamed application */ 9881 @Nullable public final String realPkgName; 9882 public final @ParseFlags int parseFlags; 9883 public final @ScanFlags int scanFlags; 9884 /** The user for which the package is being scanned */ 9885 @Nullable public final UserHandle user; 9886 /** Whether or not the platform package is being scanned */ 9887 public final boolean isPlatformPackage; 9888 public ScanRequest( 9889 @NonNull PackageParser.Package pkg, 9890 @Nullable SharedUserSetting sharedUserSetting, 9891 @Nullable PackageSetting pkgSetting, 9892 @Nullable PackageSetting disabledPkgSetting, 9893 @Nullable PackageSetting originalPkgSetting, 9894 @Nullable String realPkgName, 9895 @ParseFlags int parseFlags, 9896 @ScanFlags int scanFlags, 9897 boolean isPlatformPackage, 9898 @Nullable UserHandle user) { 9899 this.pkg = pkg; 9900 this.pkgSetting = pkgSetting; 9901 this.sharedUserSetting = sharedUserSetting; 9902 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9903 this.disabledPkgSetting = disabledPkgSetting; 9904 this.originalPkgSetting = originalPkgSetting; 9905 this.realPkgName = realPkgName; 9906 this.parseFlags = parseFlags; 9907 this.scanFlags = scanFlags; 9908 this.isPlatformPackage = isPlatformPackage; 9909 this.user = user; 9910 } 9911 } 9912 9913 /** 9914 * Returns the actual scan flags depending upon the state of the other settings. 9915 * <p>Updated system applications will not have the following flags set 9916 * by default and need to be adjusted after the fact: 9917 * <ul> 9918 * <li>{@link #SCAN_AS_SYSTEM}</li> 9919 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9920 * <li>{@link #SCAN_AS_OEM}</li> 9921 * <li>{@link #SCAN_AS_VENDOR}</li> 9922 * <li>{@link #SCAN_AS_PRODUCT}</li> 9923 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9924 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9925 * </ul> 9926 */ 9927 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9928 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9929 PackageParser.Package pkg) { 9930 if (disabledPkgSetting != null) { 9931 // updated system application, must at least have SCAN_AS_SYSTEM 9932 scanFlags |= SCAN_AS_SYSTEM; 9933 if ((disabledPkgSetting.pkgPrivateFlags 9934 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9935 scanFlags |= SCAN_AS_PRIVILEGED; 9936 } 9937 if ((disabledPkgSetting.pkgPrivateFlags 9938 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9939 scanFlags |= SCAN_AS_OEM; 9940 } 9941 if ((disabledPkgSetting.pkgPrivateFlags 9942 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9943 scanFlags |= SCAN_AS_VENDOR; 9944 } 9945 if ((disabledPkgSetting.pkgPrivateFlags 9946 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9947 scanFlags |= SCAN_AS_PRODUCT; 9948 } 9949 } 9950 if (pkgSetting != null) { 9951 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9952 if (pkgSetting.getInstantApp(userId)) { 9953 scanFlags |= SCAN_AS_INSTANT_APP; 9954 } 9955 if (pkgSetting.getVirtulalPreload(userId)) { 9956 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9957 } 9958 } 9959 9960 // Scan as privileged apps that share a user with a priv-app. 9961 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9962 && (pkg.mSharedUserId != null)) { 9963 SharedUserSetting sharedUserSetting = null; 9964 try { 9965 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9966 } catch (PackageManagerException ignore) {} 9967 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9968 // Exempt SharedUsers signed with the platform key. 9969 // TODO(b/72378145) Fix this exemption. Force signature apps 9970 // to whitelist their privileged permissions just like other 9971 // priv-apps. 9972 synchronized (mPackages) { 9973 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9974 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9975 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9976 scanFlags |= SCAN_AS_PRIVILEGED; 9977 } 9978 } 9979 } 9980 } 9981 9982 return scanFlags; 9983 } 9984 9985 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 9986 // the results / removing app data needs to be moved up a level to the callers of this 9987 // method. Also, we need to solve the problem of potentially creating a new shared user 9988 // setting. That can probably be done later and patch things up after the fact. 9989 @GuardedBy("mInstallLock") 9990 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9991 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9992 @Nullable UserHandle user) throws PackageManagerException { 9993 9994 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9995 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9996 if (realPkgName != null) { 9997 ensurePackageRenamed(pkg, renamedPkgName); 9998 } 9999 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10000 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10001 final PackageSetting disabledPkgSetting = 10002 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10003 10004 if (mTransferedPackages.contains(pkg.packageName)) { 10005 Slog.w(TAG, "Package " + pkg.packageName 10006 + " was transferred to another, but its .apk remains"); 10007 } 10008 10009 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10010 synchronized (mPackages) { 10011 applyPolicy(pkg, parseFlags, scanFlags); 10012 assertPackageIsValid(pkg, parseFlags, scanFlags); 10013 10014 SharedUserSetting sharedUserSetting = null; 10015 if (pkg.mSharedUserId != null) { 10016 // SIDE EFFECTS; may potentially allocate a new shared user 10017 sharedUserSetting = mSettings.getSharedUserLPw( 10018 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10019 if (DEBUG_PACKAGE_SCANNING) { 10020 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10021 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10022 + " (uid=" + sharedUserSetting.userId + "):" 10023 + " packages=" + sharedUserSetting.packages); 10024 } 10025 } 10026 10027 boolean scanSucceeded = false; 10028 try { 10029 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10030 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10031 (pkg == mPlatformPackage), user); 10032 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10033 if (result.success) { 10034 commitScanResultsLocked(request, result); 10035 } 10036 scanSucceeded = true; 10037 } finally { 10038 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10039 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10040 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10041 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10042 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10043 } 10044 } 10045 } 10046 return pkg; 10047 } 10048 10049 /** 10050 * Commits the package scan and modifies system state. 10051 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10052 * of committing the package, leaving the system in an inconsistent state. 10053 * This needs to be fixed so, once we get to this point, no errors are 10054 * possible and the system is not left in an inconsistent state. 10055 */ 10056 @GuardedBy("mPackages") 10057 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10058 throws PackageManagerException { 10059 final PackageParser.Package pkg = request.pkg; 10060 final @ParseFlags int parseFlags = request.parseFlags; 10061 final @ScanFlags int scanFlags = request.scanFlags; 10062 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10063 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10064 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10065 final UserHandle user = request.user; 10066 final String realPkgName = request.realPkgName; 10067 final PackageSetting pkgSetting = result.pkgSetting; 10068 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10069 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10070 10071 if (newPkgSettingCreated) { 10072 if (originalPkgSetting != null) { 10073 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10074 } 10075 // THROWS: when we can't allocate a user id. add call to check if there's 10076 // enough space to ensure we won't throw; otherwise, don't modify state 10077 mSettings.addUserToSettingLPw(pkgSetting); 10078 10079 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10080 mTransferedPackages.add(originalPkgSetting.name); 10081 } 10082 } 10083 // TODO(toddke): Consider a method specifically for modifying the Package object 10084 // post scan; or, moving this stuff out of the Package object since it has nothing 10085 // to do with the package on disk. 10086 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10087 // for creating the application ID. If we did this earlier, we would be saving the 10088 // correct ID. 10089 pkg.applicationInfo.uid = pkgSetting.appId; 10090 10091 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10092 10093 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10094 mTransferedPackages.add(pkg.packageName); 10095 } 10096 10097 // THROWS: when requested libraries that can't be found. it only changes 10098 // the state of the passed in pkg object, so, move to the top of the method 10099 // and allow it to abort 10100 if ((scanFlags & SCAN_BOOTING) == 0 10101 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10102 // Check all shared libraries and map to their actual file path. 10103 // We only do this here for apps not on a system dir, because those 10104 // are the only ones that can fail an install due to this. We 10105 // will take care of the system apps by updating all of their 10106 // library paths after the scan is done. Also during the initial 10107 // scan don't update any libs as we do this wholesale after all 10108 // apps are scanned to avoid dependency based scanning. 10109 updateSharedLibrariesLPr(pkg, null); 10110 } 10111 10112 // All versions of a static shared library are referenced with the same 10113 // package name. Internally, we use a synthetic package name to allow 10114 // multiple versions of the same shared library to be installed. So, 10115 // we need to generate the synthetic package name of the latest shared 10116 // library in order to compare signatures. 10117 PackageSetting signatureCheckPs = pkgSetting; 10118 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10119 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10120 if (libraryEntry != null) { 10121 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10122 } 10123 } 10124 10125 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10126 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10127 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10128 // We just determined the app is signed correctly, so bring 10129 // over the latest parsed certs. 10130 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10131 } else { 10132 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10133 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10134 "Package " + pkg.packageName + " upgrade keys do not match the " 10135 + "previously installed version"); 10136 } else { 10137 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10138 String msg = "System package " + pkg.packageName 10139 + " signature changed; retaining data."; 10140 reportSettingsProblem(Log.WARN, msg); 10141 } 10142 } 10143 } else { 10144 try { 10145 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10146 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10147 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10148 pkg.mSigningDetails, compareCompat, compareRecover); 10149 // The new KeySets will be re-added later in the scanning process. 10150 if (compatMatch) { 10151 synchronized (mPackages) { 10152 ksms.removeAppKeySetDataLPw(pkg.packageName); 10153 } 10154 } 10155 // We just determined the app is signed correctly, so bring 10156 // over the latest parsed certs. 10157 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10158 10159 10160 // if this is is a sharedUser, check to see if the new package is signed by a newer 10161 // signing certificate than the existing one, and if so, copy over the new details 10162 if (signatureCheckPs.sharedUser != null 10163 && pkg.mSigningDetails.hasAncestor( 10164 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 10165 signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails; 10166 } 10167 } catch (PackageManagerException e) { 10168 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10169 throw e; 10170 } 10171 // The signature has changed, but this package is in the system 10172 // image... let's recover! 10173 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10174 // However... if this package is part of a shared user, but it 10175 // doesn't match the signature of the shared user, let's fail. 10176 // What this means is that you can't change the signatures 10177 // associated with an overall shared user, which doesn't seem all 10178 // that unreasonable. 10179 if (signatureCheckPs.sharedUser != null) { 10180 if (compareSignatures( 10181 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10182 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10183 throw new PackageManagerException( 10184 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10185 "Signature mismatch for shared user: " 10186 + pkgSetting.sharedUser); 10187 } 10188 } 10189 // File a report about this. 10190 String msg = "System package " + pkg.packageName 10191 + " signature changed; retaining data."; 10192 reportSettingsProblem(Log.WARN, msg); 10193 } catch (IllegalArgumentException e) { 10194 10195 // should never happen: certs matched when checking, but not when comparing 10196 // old to new for sharedUser 10197 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10198 "Signing certificates comparison made on incomparable signing details" 10199 + " but somehow passed verifySignatures!"); 10200 } 10201 } 10202 10203 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10204 // This package wants to adopt ownership of permissions from 10205 // another package. 10206 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10207 final String origName = pkg.mAdoptPermissions.get(i); 10208 final PackageSetting orig = mSettings.getPackageLPr(origName); 10209 if (orig != null) { 10210 if (verifyPackageUpdateLPr(orig, pkg)) { 10211 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10212 + pkg.packageName); 10213 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10214 } 10215 } 10216 } 10217 } 10218 10219 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10220 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10221 final String codePathString = changedAbiCodePath.get(i); 10222 try { 10223 mInstaller.rmdex(codePathString, 10224 getDexCodeInstructionSet(getPreferredInstructionSet())); 10225 } catch (InstallerException ignored) { 10226 } 10227 } 10228 } 10229 10230 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10231 if (oldPkgSetting != null) { 10232 synchronized (mPackages) { 10233 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10234 } 10235 } 10236 } else { 10237 final int userId = user == null ? 0 : user.getIdentifier(); 10238 // Modify state for the given package setting 10239 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10240 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10241 if (pkgSetting.getInstantApp(userId)) { 10242 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10243 } 10244 } 10245 } 10246 10247 /** 10248 * Returns the "real" name of the package. 10249 * <p>This may differ from the package's actual name if the application has already 10250 * been installed under one of this package's original names. 10251 */ 10252 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10253 @Nullable String renamedPkgName) { 10254 if (isPackageRenamed(pkg, renamedPkgName)) { 10255 return pkg.mRealPackage; 10256 } 10257 return null; 10258 } 10259 10260 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10261 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10262 @Nullable String renamedPkgName) { 10263 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10264 } 10265 10266 /** 10267 * Returns the original package setting. 10268 * <p>A package can migrate its name during an update. In this scenario, a package 10269 * designates a set of names that it considers as one of its original names. 10270 * <p>An original package must be signed identically and it must have the same 10271 * shared user [if any]. 10272 */ 10273 @GuardedBy("mPackages") 10274 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10275 @Nullable String renamedPkgName) { 10276 if (!isPackageRenamed(pkg, renamedPkgName)) { 10277 return null; 10278 } 10279 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10280 final PackageSetting originalPs = 10281 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10282 if (originalPs != null) { 10283 // the package is already installed under its original name... 10284 // but, should we use it? 10285 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10286 // the new package is incompatible with the original 10287 continue; 10288 } else if (originalPs.sharedUser != null) { 10289 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10290 // the shared user id is incompatible with the original 10291 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10292 + " to " + pkg.packageName + ": old uid " 10293 + originalPs.sharedUser.name 10294 + " differs from " + pkg.mSharedUserId); 10295 continue; 10296 } 10297 // TODO: Add case when shared user id is added [b/28144775] 10298 } else { 10299 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10300 + pkg.packageName + " to old name " + originalPs.name); 10301 } 10302 return originalPs; 10303 } 10304 } 10305 return null; 10306 } 10307 10308 /** 10309 * Renames the package if it was installed under a different name. 10310 * <p>When we've already installed the package under an original name, update 10311 * the new package so we can continue to have the old name. 10312 */ 10313 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10314 @NonNull String renamedPackageName) { 10315 if (pkg.mOriginalPackages == null 10316 || !pkg.mOriginalPackages.contains(renamedPackageName) 10317 || pkg.packageName.equals(renamedPackageName)) { 10318 return; 10319 } 10320 pkg.setPackageName(renamedPackageName); 10321 } 10322 10323 /** 10324 * Just scans the package without any side effects. 10325 * <p>Not entirely true at the moment. There is still one side effect -- this 10326 * method potentially modifies a live {@link PackageSetting} object representing 10327 * the package being scanned. This will be resolved in the future. 10328 * 10329 * @param request Information about the package to be scanned 10330 * @param isUnderFactoryTest Whether or not the device is under factory test 10331 * @param currentTime The current time, in millis 10332 * @return The results of the scan 10333 */ 10334 @GuardedBy("mInstallLock") 10335 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10336 boolean isUnderFactoryTest, long currentTime) 10337 throws PackageManagerException { 10338 final PackageParser.Package pkg = request.pkg; 10339 PackageSetting pkgSetting = request.pkgSetting; 10340 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10341 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10342 final @ParseFlags int parseFlags = request.parseFlags; 10343 final @ScanFlags int scanFlags = request.scanFlags; 10344 final String realPkgName = request.realPkgName; 10345 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10346 final UserHandle user = request.user; 10347 final boolean isPlatformPackage = request.isPlatformPackage; 10348 10349 List<String> changedAbiCodePath = null; 10350 10351 if (DEBUG_PACKAGE_SCANNING) { 10352 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10353 Log.d(TAG, "Scanning package " + pkg.packageName); 10354 } 10355 10356 if (Build.IS_DEBUGGABLE && 10357 pkg.isPrivileged() && 10358 !SystemProperties.getBoolean(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, true)) { 10359 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10360 } 10361 10362 // Initialize package source and resource directories 10363 final File scanFile = new File(pkg.codePath); 10364 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10365 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10366 10367 // We keep references to the derived CPU Abis from settings in oder to reuse 10368 // them in the case where we're not upgrading or booting for the first time. 10369 String primaryCpuAbiFromSettings = null; 10370 String secondaryCpuAbiFromSettings = null; 10371 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10372 10373 if (!needToDeriveAbi) { 10374 if (pkgSetting != null) { 10375 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10376 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10377 } else { 10378 // Re-scanning a system package after uninstalling updates; need to derive ABI 10379 needToDeriveAbi = true; 10380 } 10381 } 10382 10383 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10384 PackageManagerService.reportSettingsProblem(Log.WARN, 10385 "Package " + pkg.packageName + " shared user changed from " 10386 + (pkgSetting.sharedUser != null 10387 ? pkgSetting.sharedUser.name : "<nothing>") 10388 + " to " 10389 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10390 + "; replacing with new"); 10391 pkgSetting = null; 10392 } 10393 10394 String[] usesStaticLibraries = null; 10395 if (pkg.usesStaticLibraries != null) { 10396 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10397 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10398 } 10399 final boolean createNewPackage = (pkgSetting == null); 10400 if (createNewPackage) { 10401 final String parentPackageName = (pkg.parentPackage != null) 10402 ? pkg.parentPackage.packageName : null; 10403 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10404 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10405 // REMOVE SharedUserSetting from method; update in a separate call 10406 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10407 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10408 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10409 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10410 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10411 user, true /*allowInstall*/, instantApp, virtualPreload, 10412 parentPackageName, pkg.getChildPackageNames(), 10413 UserManagerService.getInstance(), usesStaticLibraries, 10414 pkg.usesStaticLibrariesVersions); 10415 } else { 10416 // REMOVE SharedUserSetting from method; update in a separate call. 10417 // 10418 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10419 // secondaryCpuAbi are not known at this point so we always update them 10420 // to null here, only to reset them at a later point. 10421 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10422 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10423 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10424 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10425 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10426 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10427 } 10428 if (createNewPackage && originalPkgSetting != null) { 10429 // This is the initial transition from the original package, so, 10430 // fix up the new package's name now. We must do this after looking 10431 // up the package under its new name, so getPackageLP takes care of 10432 // fiddling things correctly. 10433 pkg.setPackageName(originalPkgSetting.name); 10434 10435 // File a report about this. 10436 String msg = "New package " + pkgSetting.realName 10437 + " renamed to replace old package " + pkgSetting.name; 10438 reportSettingsProblem(Log.WARN, msg); 10439 } 10440 10441 if (disabledPkgSetting != null) { 10442 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10443 } 10444 10445 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 10446 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 10447 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 10448 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 10449 // least restrictive selinux domain. 10450 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 10451 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 10452 // ensures that all packages continue to run in the same selinux domain. 10453 final int targetSdkVersion = 10454 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 10455 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 10456 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10457 // They currently can be if the sharedUser apps are signed with the platform key. 10458 final boolean isPrivileged = (sharedUserSetting != null) ? 10459 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 10460 10461 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 10462 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 10463 10464 pkg.mExtras = pkgSetting; 10465 pkg.applicationInfo.processName = fixProcessName( 10466 pkg.applicationInfo.packageName, 10467 pkg.applicationInfo.processName); 10468 10469 if (!isPlatformPackage) { 10470 // Get all of our default paths setup 10471 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10472 } 10473 10474 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10475 10476 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10477 if (needToDeriveAbi) { 10478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10479 final boolean extractNativeLibs = !pkg.isLibrary(); 10480 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10481 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10482 10483 // Some system apps still use directory structure for native libraries 10484 // in which case we might end up not detecting abi solely based on apk 10485 // structure. Try to detect abi based on directory structure. 10486 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10487 pkg.applicationInfo.primaryCpuAbi == null) { 10488 setBundledAppAbisAndRoots(pkg, pkgSetting); 10489 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10490 } 10491 } else { 10492 // This is not a first boot or an upgrade, don't bother deriving the 10493 // ABI during the scan. Instead, trust the value that was stored in the 10494 // package setting. 10495 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10496 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10497 10498 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10499 10500 if (DEBUG_ABI_SELECTION) { 10501 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10502 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10503 pkg.applicationInfo.secondaryCpuAbi); 10504 } 10505 } 10506 } else { 10507 if ((scanFlags & SCAN_MOVE) != 0) { 10508 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10509 // but we already have this packages package info in the PackageSetting. We just 10510 // use that and derive the native library path based on the new codepath. 10511 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10512 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10513 } 10514 10515 // Set native library paths again. For moves, the path will be updated based on the 10516 // ABIs we've determined above. For non-moves, the path will be updated based on the 10517 // ABIs we determined during compilation, but the path will depend on the final 10518 // package path (after the rename away from the stage path). 10519 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10520 } 10521 10522 // This is a special case for the "system" package, where the ABI is 10523 // dictated by the zygote configuration (and init.rc). We should keep track 10524 // of this ABI so that we can deal with "normal" applications that run under 10525 // the same UID correctly. 10526 if (isPlatformPackage) { 10527 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10528 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10529 } 10530 10531 // If there's a mismatch between the abi-override in the package setting 10532 // and the abiOverride specified for the install. Warn about this because we 10533 // would've already compiled the app without taking the package setting into 10534 // account. 10535 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10536 if (cpuAbiOverride == null && pkg.packageName != null) { 10537 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10538 " for package " + pkg.packageName); 10539 } 10540 } 10541 10542 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10543 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10544 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10545 10546 // Copy the derived override back to the parsed package, so that we can 10547 // update the package settings accordingly. 10548 pkg.cpuAbiOverride = cpuAbiOverride; 10549 10550 if (DEBUG_ABI_SELECTION) { 10551 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10552 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10553 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10554 } 10555 10556 // Push the derived path down into PackageSettings so we know what to 10557 // clean up at uninstall time. 10558 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10559 10560 if (DEBUG_ABI_SELECTION) { 10561 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10562 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10563 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10564 } 10565 10566 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10567 // We don't do this here during boot because we can do it all 10568 // at once after scanning all existing packages. 10569 // 10570 // We also do this *before* we perform dexopt on this package, so that 10571 // we can avoid redundant dexopts, and also to make sure we've got the 10572 // code and package path correct. 10573 changedAbiCodePath = 10574 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10575 } 10576 10577 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10578 android.Manifest.permission.FACTORY_TEST)) { 10579 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10580 } 10581 10582 if (isSystemApp(pkg)) { 10583 pkgSetting.isOrphaned = true; 10584 } 10585 10586 // Take care of first install / last update times. 10587 final long scanFileTime = getLastModifiedTime(pkg); 10588 if (currentTime != 0) { 10589 if (pkgSetting.firstInstallTime == 0) { 10590 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10591 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10592 pkgSetting.lastUpdateTime = currentTime; 10593 } 10594 } else if (pkgSetting.firstInstallTime == 0) { 10595 // We need *something*. Take time time stamp of the file. 10596 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10597 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10598 if (scanFileTime != pkgSetting.timeStamp) { 10599 // A package on the system image has changed; consider this 10600 // to be an update. 10601 pkgSetting.lastUpdateTime = scanFileTime; 10602 } 10603 } 10604 pkgSetting.setTimeStamp(scanFileTime); 10605 10606 pkgSetting.pkg = pkg; 10607 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10608 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10609 pkgSetting.versionCode = pkg.getLongVersionCode(); 10610 } 10611 // Update volume if needed 10612 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10613 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10614 Slog.i(PackageManagerService.TAG, 10615 "Update" + (pkgSetting.isSystem() ? " system" : "") 10616 + " package " + pkg.packageName 10617 + " volume from " + pkgSetting.volumeUuid 10618 + " to " + volumeUuid); 10619 pkgSetting.volumeUuid = volumeUuid; 10620 } 10621 10622 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10623 } 10624 10625 /** 10626 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10627 */ 10628 private static boolean apkHasCode(String fileName) { 10629 StrictJarFile jarFile = null; 10630 try { 10631 jarFile = new StrictJarFile(fileName, 10632 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10633 return jarFile.findEntry("classes.dex") != null; 10634 } catch (IOException ignore) { 10635 } finally { 10636 try { 10637 if (jarFile != null) { 10638 jarFile.close(); 10639 } 10640 } catch (IOException ignore) {} 10641 } 10642 return false; 10643 } 10644 10645 /** 10646 * Enforces code policy for the package. This ensures that if an APK has 10647 * declared hasCode="true" in its manifest that the APK actually contains 10648 * code. 10649 * 10650 * @throws PackageManagerException If bytecode could not be found when it should exist 10651 */ 10652 private static void assertCodePolicy(PackageParser.Package pkg) 10653 throws PackageManagerException { 10654 final boolean shouldHaveCode = 10655 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10656 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10657 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10658 "Package " + pkg.baseCodePath + " code is missing"); 10659 } 10660 10661 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10662 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10663 final boolean splitShouldHaveCode = 10664 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10665 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10666 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10667 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10668 } 10669 } 10670 } 10671 } 10672 10673 /** 10674 * Applies policy to the parsed package based upon the given policy flags. 10675 * Ensures the package is in a good state. 10676 * <p> 10677 * Implementation detail: This method must NOT have any side effect. It would 10678 * ideally be static, but, it requires locks to read system state. 10679 */ 10680 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10681 final @ScanFlags int scanFlags) { 10682 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10683 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10684 if (pkg.applicationInfo.isDirectBootAware()) { 10685 // we're direct boot aware; set for all components 10686 for (PackageParser.Service s : pkg.services) { 10687 s.info.encryptionAware = s.info.directBootAware = true; 10688 } 10689 for (PackageParser.Provider p : pkg.providers) { 10690 p.info.encryptionAware = p.info.directBootAware = true; 10691 } 10692 for (PackageParser.Activity a : pkg.activities) { 10693 a.info.encryptionAware = a.info.directBootAware = true; 10694 } 10695 for (PackageParser.Activity r : pkg.receivers) { 10696 r.info.encryptionAware = r.info.directBootAware = true; 10697 } 10698 } 10699 if (compressedFileExists(pkg.codePath)) { 10700 pkg.isStub = true; 10701 } 10702 } else { 10703 // non system apps can't be flagged as core 10704 pkg.coreApp = false; 10705 // clear flags not applicable to regular apps 10706 pkg.applicationInfo.flags &= 10707 ~ApplicationInfo.FLAG_PERSISTENT; 10708 pkg.applicationInfo.privateFlags &= 10709 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10710 pkg.applicationInfo.privateFlags &= 10711 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10712 // cap permission priorities 10713 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10714 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10715 pkg.permissionGroups.get(i).info.priority = 0; 10716 } 10717 } 10718 } 10719 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10720 // clear protected broadcasts 10721 pkg.protectedBroadcasts = null; 10722 // ignore export request for single user receivers 10723 if (pkg.receivers != null) { 10724 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10725 final PackageParser.Activity receiver = pkg.receivers.get(i); 10726 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10727 receiver.info.exported = false; 10728 } 10729 } 10730 } 10731 // ignore export request for single user services 10732 if (pkg.services != null) { 10733 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10734 final PackageParser.Service service = pkg.services.get(i); 10735 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10736 service.info.exported = false; 10737 } 10738 } 10739 } 10740 // ignore export request for single user providers 10741 if (pkg.providers != null) { 10742 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10743 final PackageParser.Provider provider = pkg.providers.get(i); 10744 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10745 provider.info.exported = false; 10746 } 10747 } 10748 } 10749 } 10750 10751 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10752 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10753 } 10754 10755 if ((scanFlags & SCAN_AS_OEM) != 0) { 10756 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10757 } 10758 10759 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10760 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10761 } 10762 10763 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10764 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10765 } 10766 10767 if (!isSystemApp(pkg)) { 10768 // Only system apps can use these features. 10769 pkg.mOriginalPackages = null; 10770 pkg.mRealPackage = null; 10771 pkg.mAdoptPermissions = null; 10772 } 10773 } 10774 10775 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10776 throws PackageManagerException { 10777 if (object == null) { 10778 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10779 } 10780 return object; 10781 } 10782 10783 /** 10784 * Asserts the parsed package is valid according to the given policy. If the 10785 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10786 * <p> 10787 * Implementation detail: This method must NOT have any side effects. It would 10788 * ideally be static, but, it requires locks to read system state. 10789 * 10790 * @throws PackageManagerException If the package fails any of the validation checks 10791 */ 10792 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10793 final @ScanFlags int scanFlags) 10794 throws PackageManagerException { 10795 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10796 assertCodePolicy(pkg); 10797 } 10798 10799 if (pkg.applicationInfo.getCodePath() == null || 10800 pkg.applicationInfo.getResourcePath() == null) { 10801 // Bail out. The resource and code paths haven't been set. 10802 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10803 "Code and resource paths haven't been set correctly"); 10804 } 10805 10806 // Make sure we're not adding any bogus keyset info 10807 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10808 ksms.assertScannedPackageValid(pkg); 10809 10810 synchronized (mPackages) { 10811 // The special "android" package can only be defined once 10812 if (pkg.packageName.equals("android")) { 10813 if (mAndroidApplication != null) { 10814 Slog.w(TAG, "*************************************************"); 10815 Slog.w(TAG, "Core android package being redefined. Skipping."); 10816 Slog.w(TAG, " codePath=" + pkg.codePath); 10817 Slog.w(TAG, "*************************************************"); 10818 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10819 "Core android package being redefined. Skipping."); 10820 } 10821 } 10822 10823 // A package name must be unique; don't allow duplicates 10824 if (mPackages.containsKey(pkg.packageName)) { 10825 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10826 "Application package " + pkg.packageName 10827 + " already installed. Skipping duplicate."); 10828 } 10829 10830 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10831 // Static libs have a synthetic package name containing the version 10832 // but we still want the base name to be unique. 10833 if (mPackages.containsKey(pkg.manifestPackageName)) { 10834 throw new PackageManagerException( 10835 "Duplicate static shared lib provider package"); 10836 } 10837 10838 // Static shared libraries should have at least O target SDK 10839 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10840 throw new PackageManagerException( 10841 "Packages declaring static-shared libs must target O SDK or higher"); 10842 } 10843 10844 // Package declaring static a shared lib cannot be instant apps 10845 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10846 throw new PackageManagerException( 10847 "Packages declaring static-shared libs cannot be instant apps"); 10848 } 10849 10850 // Package declaring static a shared lib cannot be renamed since the package 10851 // name is synthetic and apps can't code around package manager internals. 10852 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10853 throw new PackageManagerException( 10854 "Packages declaring static-shared libs cannot be renamed"); 10855 } 10856 10857 // Package declaring static a shared lib cannot declare child packages 10858 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10859 throw new PackageManagerException( 10860 "Packages declaring static-shared libs cannot have child packages"); 10861 } 10862 10863 // Package declaring static a shared lib cannot declare dynamic libs 10864 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10865 throw new PackageManagerException( 10866 "Packages declaring static-shared libs cannot declare dynamic libs"); 10867 } 10868 10869 // Package declaring static a shared lib cannot declare shared users 10870 if (pkg.mSharedUserId != null) { 10871 throw new PackageManagerException( 10872 "Packages declaring static-shared libs cannot declare shared users"); 10873 } 10874 10875 // Static shared libs cannot declare activities 10876 if (!pkg.activities.isEmpty()) { 10877 throw new PackageManagerException( 10878 "Static shared libs cannot declare activities"); 10879 } 10880 10881 // Static shared libs cannot declare services 10882 if (!pkg.services.isEmpty()) { 10883 throw new PackageManagerException( 10884 "Static shared libs cannot declare services"); 10885 } 10886 10887 // Static shared libs cannot declare providers 10888 if (!pkg.providers.isEmpty()) { 10889 throw new PackageManagerException( 10890 "Static shared libs cannot declare content providers"); 10891 } 10892 10893 // Static shared libs cannot declare receivers 10894 if (!pkg.receivers.isEmpty()) { 10895 throw new PackageManagerException( 10896 "Static shared libs cannot declare broadcast receivers"); 10897 } 10898 10899 // Static shared libs cannot declare permission groups 10900 if (!pkg.permissionGroups.isEmpty()) { 10901 throw new PackageManagerException( 10902 "Static shared libs cannot declare permission groups"); 10903 } 10904 10905 // Static shared libs cannot declare permissions 10906 if (!pkg.permissions.isEmpty()) { 10907 throw new PackageManagerException( 10908 "Static shared libs cannot declare permissions"); 10909 } 10910 10911 // Static shared libs cannot declare protected broadcasts 10912 if (pkg.protectedBroadcasts != null) { 10913 throw new PackageManagerException( 10914 "Static shared libs cannot declare protected broadcasts"); 10915 } 10916 10917 // Static shared libs cannot be overlay targets 10918 if (pkg.mOverlayTarget != null) { 10919 throw new PackageManagerException( 10920 "Static shared libs cannot be overlay targets"); 10921 } 10922 10923 // The version codes must be ordered as lib versions 10924 long minVersionCode = Long.MIN_VALUE; 10925 long maxVersionCode = Long.MAX_VALUE; 10926 10927 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10928 pkg.staticSharedLibName); 10929 if (versionedLib != null) { 10930 final int versionCount = versionedLib.size(); 10931 for (int i = 0; i < versionCount; i++) { 10932 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10933 final long libVersionCode = libInfo.getDeclaringPackage() 10934 .getLongVersionCode(); 10935 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10936 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10937 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10938 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10939 } else { 10940 minVersionCode = maxVersionCode = libVersionCode; 10941 break; 10942 } 10943 } 10944 } 10945 if (pkg.getLongVersionCode() < minVersionCode 10946 || pkg.getLongVersionCode() > maxVersionCode) { 10947 throw new PackageManagerException("Static shared" 10948 + " lib version codes must be ordered as lib versions"); 10949 } 10950 } 10951 10952 // Only privileged apps and updated privileged apps can add child packages. 10953 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10954 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10955 throw new PackageManagerException("Only privileged apps can add child " 10956 + "packages. Ignoring package " + pkg.packageName); 10957 } 10958 final int childCount = pkg.childPackages.size(); 10959 for (int i = 0; i < childCount; i++) { 10960 PackageParser.Package childPkg = pkg.childPackages.get(i); 10961 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10962 childPkg.packageName)) { 10963 throw new PackageManagerException("Can't override child of " 10964 + "another disabled app. Ignoring package " + pkg.packageName); 10965 } 10966 } 10967 } 10968 10969 // If we're only installing presumed-existing packages, require that the 10970 // scanned APK is both already known and at the path previously established 10971 // for it. Previously unknown packages we pick up normally, but if we have an 10972 // a priori expectation about this package's install presence, enforce it. 10973 // With a singular exception for new system packages. When an OTA contains 10974 // a new system package, we allow the codepath to change from a system location 10975 // to the user-installed location. If we don't allow this change, any newer, 10976 // user-installed version of the application will be ignored. 10977 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10978 if (mExpectingBetter.containsKey(pkg.packageName)) { 10979 logCriticalInfo(Log.WARN, 10980 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10981 } else { 10982 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10983 if (known != null) { 10984 if (DEBUG_PACKAGE_SCANNING) { 10985 Log.d(TAG, "Examining " + pkg.codePath 10986 + " and requiring known paths " + known.codePathString 10987 + " & " + known.resourcePathString); 10988 } 10989 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10990 || !pkg.applicationInfo.getResourcePath().equals( 10991 known.resourcePathString)) { 10992 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10993 "Application package " + pkg.packageName 10994 + " found at " + pkg.applicationInfo.getCodePath() 10995 + " but expected at " + known.codePathString 10996 + "; ignoring."); 10997 } 10998 } else { 10999 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11000 "Application package " + pkg.packageName 11001 + " not found; ignoring."); 11002 } 11003 } 11004 } 11005 11006 // Verify that this new package doesn't have any content providers 11007 // that conflict with existing packages. Only do this if the 11008 // package isn't already installed, since we don't want to break 11009 // things that are installed. 11010 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11011 final int N = pkg.providers.size(); 11012 int i; 11013 for (i=0; i<N; i++) { 11014 PackageParser.Provider p = pkg.providers.get(i); 11015 if (p.info.authority != null) { 11016 String names[] = p.info.authority.split(";"); 11017 for (int j = 0; j < names.length; j++) { 11018 if (mProvidersByAuthority.containsKey(names[j])) { 11019 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11020 final String otherPackageName = 11021 ((other != null && other.getComponentName() != null) ? 11022 other.getComponentName().getPackageName() : "?"); 11023 throw new PackageManagerException( 11024 INSTALL_FAILED_CONFLICTING_PROVIDER, 11025 "Can't install because provider name " + names[j] 11026 + " (in package " + pkg.applicationInfo.packageName 11027 + ") is already used by " + otherPackageName); 11028 } 11029 } 11030 } 11031 } 11032 } 11033 11034 // Verify that packages sharing a user with a privileged app are marked as privileged. 11035 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11036 SharedUserSetting sharedUserSetting = null; 11037 try { 11038 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11039 } catch (PackageManagerException ignore) {} 11040 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11041 // Exempt SharedUsers signed with the platform key. 11042 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11043 if ((platformPkgSetting.signatures.mSigningDetails 11044 != PackageParser.SigningDetails.UNKNOWN) 11045 && (compareSignatures( 11046 platformPkgSetting.signatures.mSigningDetails.signatures, 11047 pkg.mSigningDetails.signatures) 11048 != PackageManager.SIGNATURE_MATCH)) { 11049 throw new PackageManagerException("Apps that share a user with a " + 11050 "privileged app must themselves be marked as privileged. " + 11051 pkg.packageName + " shares privileged user " + 11052 pkg.mSharedUserId + "."); 11053 } 11054 } 11055 } 11056 11057 // Apply policies specific for runtime resource overlays (RROs). 11058 if (pkg.mOverlayTarget != null) { 11059 // System overlays have some restrictions on their use of the 'static' state. 11060 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11061 // We are scanning a system overlay. This can be the first scan of the 11062 // system/vendor/oem partition, or an update to the system overlay. 11063 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11064 // This must be an update to a system overlay. 11065 final PackageSetting previousPkg = assertNotNull( 11066 mSettings.getPackageLPr(pkg.packageName), 11067 "previous package state not present"); 11068 11069 // Static overlays cannot be updated. 11070 if (previousPkg.pkg.mOverlayIsStatic) { 11071 throw new PackageManagerException("Overlay " + pkg.packageName + 11072 " is static and cannot be upgraded."); 11073 // Non-static overlays cannot be converted to static overlays. 11074 } else if (pkg.mOverlayIsStatic) { 11075 throw new PackageManagerException("Overlay " + pkg.packageName + 11076 " cannot be upgraded into a static overlay."); 11077 } 11078 } 11079 } else { 11080 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11081 if (pkg.mOverlayIsStatic) { 11082 throw new PackageManagerException("Overlay " + pkg.packageName + 11083 " is static but not pre-installed."); 11084 } 11085 11086 // The only case where we allow installation of a non-system overlay is when 11087 // its signature is signed with the platform certificate. 11088 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11089 if ((platformPkgSetting.signatures.mSigningDetails 11090 != PackageParser.SigningDetails.UNKNOWN) 11091 && (compareSignatures( 11092 platformPkgSetting.signatures.mSigningDetails.signatures, 11093 pkg.mSigningDetails.signatures) 11094 != PackageManager.SIGNATURE_MATCH)) { 11095 throw new PackageManagerException("Overlay " + pkg.packageName + 11096 " must be signed with the platform certificate."); 11097 } 11098 } 11099 } 11100 } 11101 } 11102 11103 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11104 int type, String declaringPackageName, long declaringVersionCode) { 11105 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11106 if (versionedLib == null) { 11107 versionedLib = new LongSparseArray<>(); 11108 mSharedLibraries.put(name, versionedLib); 11109 if (type == SharedLibraryInfo.TYPE_STATIC) { 11110 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11111 } 11112 } else if (versionedLib.indexOfKey(version) >= 0) { 11113 return false; 11114 } 11115 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11116 version, type, declaringPackageName, declaringVersionCode); 11117 versionedLib.put(version, libEntry); 11118 return true; 11119 } 11120 11121 private boolean removeSharedLibraryLPw(String name, long version) { 11122 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11123 if (versionedLib == null) { 11124 return false; 11125 } 11126 final int libIdx = versionedLib.indexOfKey(version); 11127 if (libIdx < 0) { 11128 return false; 11129 } 11130 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11131 versionedLib.remove(version); 11132 if (versionedLib.size() <= 0) { 11133 mSharedLibraries.remove(name); 11134 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11135 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11136 .getPackageName()); 11137 } 11138 } 11139 return true; 11140 } 11141 11142 /** 11143 * Adds a scanned package to the system. When this method is finished, the package will 11144 * be available for query, resolution, etc... 11145 */ 11146 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11147 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11148 final String pkgName = pkg.packageName; 11149 if (mCustomResolverComponentName != null && 11150 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11151 setUpCustomResolverActivity(pkg); 11152 } 11153 11154 if (pkg.packageName.equals("android")) { 11155 synchronized (mPackages) { 11156 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11157 // Set up information for our fall-back user intent resolution activity. 11158 mPlatformPackage = pkg; 11159 pkg.mVersionCode = mSdkVersion; 11160 pkg.mVersionCodeMajor = 0; 11161 mAndroidApplication = pkg.applicationInfo; 11162 if (!mResolverReplaced) { 11163 mResolveActivity.applicationInfo = mAndroidApplication; 11164 mResolveActivity.name = ResolverActivity.class.getName(); 11165 mResolveActivity.packageName = mAndroidApplication.packageName; 11166 mResolveActivity.processName = "system:ui"; 11167 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11168 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11169 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11170 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11171 mResolveActivity.exported = true; 11172 mResolveActivity.enabled = true; 11173 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11174 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11175 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11176 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11177 | ActivityInfo.CONFIG_ORIENTATION 11178 | ActivityInfo.CONFIG_KEYBOARD 11179 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11180 mResolveInfo.activityInfo = mResolveActivity; 11181 mResolveInfo.priority = 0; 11182 mResolveInfo.preferredOrder = 0; 11183 mResolveInfo.match = 0; 11184 mResolveComponentName = new ComponentName( 11185 mAndroidApplication.packageName, mResolveActivity.name); 11186 } 11187 } 11188 } 11189 } 11190 11191 ArrayList<PackageParser.Package> clientLibPkgs = null; 11192 // writer 11193 synchronized (mPackages) { 11194 boolean hasStaticSharedLibs = false; 11195 11196 // Any app can add new static shared libraries 11197 if (pkg.staticSharedLibName != null) { 11198 // Static shared libs don't allow renaming as they have synthetic package 11199 // names to allow install of multiple versions, so use name from manifest. 11200 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11201 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11202 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11203 hasStaticSharedLibs = true; 11204 } else { 11205 Slog.w(TAG, "Package " + pkg.packageName + " library " 11206 + pkg.staticSharedLibName + " already exists; skipping"); 11207 } 11208 // Static shared libs cannot be updated once installed since they 11209 // use synthetic package name which includes the version code, so 11210 // not need to update other packages's shared lib dependencies. 11211 } 11212 11213 if (!hasStaticSharedLibs 11214 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11215 // Only system apps can add new dynamic shared libraries. 11216 if (pkg.libraryNames != null) { 11217 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11218 String name = pkg.libraryNames.get(i); 11219 boolean allowed = false; 11220 if (pkg.isUpdatedSystemApp()) { 11221 // New library entries can only be added through the 11222 // system image. This is important to get rid of a lot 11223 // of nasty edge cases: for example if we allowed a non- 11224 // system update of the app to add a library, then uninstalling 11225 // the update would make the library go away, and assumptions 11226 // we made such as through app install filtering would now 11227 // have allowed apps on the device which aren't compatible 11228 // with it. Better to just have the restriction here, be 11229 // conservative, and create many fewer cases that can negatively 11230 // impact the user experience. 11231 final PackageSetting sysPs = mSettings 11232 .getDisabledSystemPkgLPr(pkg.packageName); 11233 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11234 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11235 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11236 allowed = true; 11237 break; 11238 } 11239 } 11240 } 11241 } else { 11242 allowed = true; 11243 } 11244 if (allowed) { 11245 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11246 SharedLibraryInfo.VERSION_UNDEFINED, 11247 SharedLibraryInfo.TYPE_DYNAMIC, 11248 pkg.packageName, pkg.getLongVersionCode())) { 11249 Slog.w(TAG, "Package " + pkg.packageName + " library " 11250 + name + " already exists; skipping"); 11251 } 11252 } else { 11253 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11254 + name + " that is not declared on system image; skipping"); 11255 } 11256 } 11257 11258 if ((scanFlags & SCAN_BOOTING) == 0) { 11259 // If we are not booting, we need to update any applications 11260 // that are clients of our shared library. If we are booting, 11261 // this will all be done once the scan is complete. 11262 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11263 } 11264 } 11265 } 11266 } 11267 11268 if ((scanFlags & SCAN_BOOTING) != 0) { 11269 // No apps can run during boot scan, so they don't need to be frozen 11270 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11271 // Caller asked to not kill app, so it's probably not frozen 11272 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11273 // Caller asked us to ignore frozen check for some reason; they 11274 // probably didn't know the package name 11275 } else { 11276 // We're doing major surgery on this package, so it better be frozen 11277 // right now to keep it from launching 11278 checkPackageFrozen(pkgName); 11279 } 11280 11281 // Also need to kill any apps that are dependent on the library. 11282 if (clientLibPkgs != null) { 11283 for (int i=0; i<clientLibPkgs.size(); i++) { 11284 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11285 killApplication(clientPkg.applicationInfo.packageName, 11286 clientPkg.applicationInfo.uid, "update lib"); 11287 } 11288 } 11289 11290 // writer 11291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11292 11293 synchronized (mPackages) { 11294 // We don't expect installation to fail beyond this point 11295 11296 // Add the new setting to mSettings 11297 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11298 // Add the new setting to mPackages 11299 mPackages.put(pkg.applicationInfo.packageName, pkg); 11300 // Make sure we don't accidentally delete its data. 11301 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11302 while (iter.hasNext()) { 11303 PackageCleanItem item = iter.next(); 11304 if (pkgName.equals(item.packageName)) { 11305 iter.remove(); 11306 } 11307 } 11308 11309 // Add the package's KeySets to the global KeySetManagerService 11310 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11311 ksms.addScannedPackageLPw(pkg); 11312 11313 int N = pkg.providers.size(); 11314 StringBuilder r = null; 11315 int i; 11316 for (i=0; i<N; i++) { 11317 PackageParser.Provider p = pkg.providers.get(i); 11318 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11319 p.info.processName); 11320 mProviders.addProvider(p); 11321 p.syncable = p.info.isSyncable; 11322 if (p.info.authority != null) { 11323 String names[] = p.info.authority.split(";"); 11324 p.info.authority = null; 11325 for (int j = 0; j < names.length; j++) { 11326 if (j == 1 && p.syncable) { 11327 // We only want the first authority for a provider to possibly be 11328 // syncable, so if we already added this provider using a different 11329 // authority clear the syncable flag. We copy the provider before 11330 // changing it because the mProviders object contains a reference 11331 // to a provider that we don't want to change. 11332 // Only do this for the second authority since the resulting provider 11333 // object can be the same for all future authorities for this provider. 11334 p = new PackageParser.Provider(p); 11335 p.syncable = false; 11336 } 11337 if (!mProvidersByAuthority.containsKey(names[j])) { 11338 mProvidersByAuthority.put(names[j], p); 11339 if (p.info.authority == null) { 11340 p.info.authority = names[j]; 11341 } else { 11342 p.info.authority = p.info.authority + ";" + names[j]; 11343 } 11344 if (DEBUG_PACKAGE_SCANNING) { 11345 if (chatty) 11346 Log.d(TAG, "Registered content provider: " + names[j] 11347 + ", className = " + p.info.name + ", isSyncable = " 11348 + p.info.isSyncable); 11349 } 11350 } else { 11351 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11352 Slog.w(TAG, "Skipping provider name " + names[j] + 11353 " (in package " + pkg.applicationInfo.packageName + 11354 "): name already used by " 11355 + ((other != null && other.getComponentName() != null) 11356 ? other.getComponentName().getPackageName() : "?")); 11357 } 11358 } 11359 } 11360 if (chatty) { 11361 if (r == null) { 11362 r = new StringBuilder(256); 11363 } else { 11364 r.append(' '); 11365 } 11366 r.append(p.info.name); 11367 } 11368 } 11369 if (r != null) { 11370 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11371 } 11372 11373 N = pkg.services.size(); 11374 r = null; 11375 for (i=0; i<N; i++) { 11376 PackageParser.Service s = pkg.services.get(i); 11377 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11378 s.info.processName); 11379 mServices.addService(s); 11380 if (chatty) { 11381 if (r == null) { 11382 r = new StringBuilder(256); 11383 } else { 11384 r.append(' '); 11385 } 11386 r.append(s.info.name); 11387 } 11388 } 11389 if (r != null) { 11390 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11391 } 11392 11393 N = pkg.receivers.size(); 11394 r = null; 11395 for (i=0; i<N; i++) { 11396 PackageParser.Activity a = pkg.receivers.get(i); 11397 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11398 a.info.processName); 11399 mReceivers.addActivity(a, "receiver"); 11400 if (chatty) { 11401 if (r == null) { 11402 r = new StringBuilder(256); 11403 } else { 11404 r.append(' '); 11405 } 11406 r.append(a.info.name); 11407 } 11408 } 11409 if (r != null) { 11410 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11411 } 11412 11413 N = pkg.activities.size(); 11414 r = null; 11415 for (i=0; i<N; i++) { 11416 PackageParser.Activity a = pkg.activities.get(i); 11417 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11418 a.info.processName); 11419 mActivities.addActivity(a, "activity"); 11420 if (chatty) { 11421 if (r == null) { 11422 r = new StringBuilder(256); 11423 } else { 11424 r.append(' '); 11425 } 11426 r.append(a.info.name); 11427 } 11428 } 11429 if (r != null) { 11430 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11431 } 11432 11433 // Don't allow ephemeral applications to define new permissions groups. 11434 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11435 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11436 + " ignored: instant apps cannot define new permission groups."); 11437 } else { 11438 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11439 } 11440 11441 // Don't allow ephemeral applications to define new permissions. 11442 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11443 Slog.w(TAG, "Permissions from package " + pkg.packageName 11444 + " ignored: instant apps cannot define new permissions."); 11445 } else { 11446 mPermissionManager.addAllPermissions(pkg, chatty); 11447 } 11448 11449 N = pkg.instrumentation.size(); 11450 r = null; 11451 for (i=0; i<N; i++) { 11452 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11453 a.info.packageName = pkg.applicationInfo.packageName; 11454 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11455 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11456 a.info.splitNames = pkg.splitNames; 11457 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11458 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11459 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11460 a.info.dataDir = pkg.applicationInfo.dataDir; 11461 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11462 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11463 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11464 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11465 mInstrumentation.put(a.getComponentName(), a); 11466 if (chatty) { 11467 if (r == null) { 11468 r = new StringBuilder(256); 11469 } else { 11470 r.append(' '); 11471 } 11472 r.append(a.info.name); 11473 } 11474 } 11475 if (r != null) { 11476 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11477 } 11478 11479 if (pkg.protectedBroadcasts != null) { 11480 N = pkg.protectedBroadcasts.size(); 11481 synchronized (mProtectedBroadcasts) { 11482 for (i = 0; i < N; i++) { 11483 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11484 } 11485 } 11486 } 11487 } 11488 11489 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11490 } 11491 11492 /** 11493 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11494 * is derived purely on the basis of the contents of {@code scanFile} and 11495 * {@code cpuAbiOverride}. 11496 * 11497 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11498 */ 11499 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11500 boolean extractLibs) 11501 throws PackageManagerException { 11502 // Give ourselves some initial paths; we'll come back for another 11503 // pass once we've determined ABI below. 11504 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11505 11506 // We would never need to extract libs for forward-locked and external packages, 11507 // since the container service will do it for us. We shouldn't attempt to 11508 // extract libs from system app when it was not updated. 11509 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11510 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11511 extractLibs = false; 11512 } 11513 11514 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11515 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11516 11517 NativeLibraryHelper.Handle handle = null; 11518 try { 11519 handle = NativeLibraryHelper.Handle.create(pkg); 11520 // TODO(multiArch): This can be null for apps that didn't go through the 11521 // usual installation process. We can calculate it again, like we 11522 // do during install time. 11523 // 11524 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11525 // unnecessary. 11526 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11527 11528 // Null out the abis so that they can be recalculated. 11529 pkg.applicationInfo.primaryCpuAbi = null; 11530 pkg.applicationInfo.secondaryCpuAbi = null; 11531 if (isMultiArch(pkg.applicationInfo)) { 11532 // Warn if we've set an abiOverride for multi-lib packages.. 11533 // By definition, we need to copy both 32 and 64 bit libraries for 11534 // such packages. 11535 if (pkg.cpuAbiOverride != null 11536 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11537 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11538 } 11539 11540 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11541 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11542 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11543 if (extractLibs) { 11544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11545 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11546 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11547 useIsaSpecificSubdirs); 11548 } else { 11549 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11550 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11551 } 11552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11553 } 11554 11555 // Shared library native code should be in the APK zip aligned 11556 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11557 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11558 "Shared library native lib extraction not supported"); 11559 } 11560 11561 maybeThrowExceptionForMultiArchCopy( 11562 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11563 11564 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11565 if (extractLibs) { 11566 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11567 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11568 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11569 useIsaSpecificSubdirs); 11570 } else { 11571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11572 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11573 } 11574 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11575 } 11576 11577 maybeThrowExceptionForMultiArchCopy( 11578 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11579 11580 if (abi64 >= 0) { 11581 // Shared library native libs should be in the APK zip aligned 11582 if (extractLibs && pkg.isLibrary()) { 11583 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11584 "Shared library native lib extraction not supported"); 11585 } 11586 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11587 } 11588 11589 if (abi32 >= 0) { 11590 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11591 if (abi64 >= 0) { 11592 if (pkg.use32bitAbi) { 11593 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11594 pkg.applicationInfo.primaryCpuAbi = abi; 11595 } else { 11596 pkg.applicationInfo.secondaryCpuAbi = abi; 11597 } 11598 } else { 11599 pkg.applicationInfo.primaryCpuAbi = abi; 11600 } 11601 } 11602 } else { 11603 String[] abiList = (cpuAbiOverride != null) ? 11604 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11605 11606 // Enable gross and lame hacks for apps that are built with old 11607 // SDK tools. We must scan their APKs for renderscript bitcode and 11608 // not launch them if it's present. Don't bother checking on devices 11609 // that don't have 64 bit support. 11610 boolean needsRenderScriptOverride = false; 11611 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11612 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11613 abiList = Build.SUPPORTED_32_BIT_ABIS; 11614 needsRenderScriptOverride = true; 11615 } 11616 11617 final int copyRet; 11618 if (extractLibs) { 11619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11620 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11621 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11622 } else { 11623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11624 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11625 } 11626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11627 11628 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11629 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11630 "Error unpackaging native libs for app, errorCode=" + copyRet); 11631 } 11632 11633 if (copyRet >= 0) { 11634 // Shared libraries that have native libs must be multi-architecture 11635 if (pkg.isLibrary()) { 11636 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11637 "Shared library with native libs must be multiarch"); 11638 } 11639 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11640 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11641 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11642 } else if (needsRenderScriptOverride) { 11643 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11644 } 11645 } 11646 } catch (IOException ioe) { 11647 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11648 } finally { 11649 IoUtils.closeQuietly(handle); 11650 } 11651 11652 // Now that we've calculated the ABIs and determined if it's an internal app, 11653 // we will go ahead and populate the nativeLibraryPath. 11654 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11655 } 11656 11657 /** 11658 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11659 * i.e, so that all packages can be run inside a single process if required. 11660 * 11661 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11662 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11663 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11664 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11665 * updating a package that belongs to a shared user. 11666 * 11667 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11668 * adds unnecessary complexity. 11669 */ 11670 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11671 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11672 List<String> changedAbiCodePath = null; 11673 String requiredInstructionSet = null; 11674 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11675 requiredInstructionSet = VMRuntime.getInstructionSet( 11676 scannedPackage.applicationInfo.primaryCpuAbi); 11677 } 11678 11679 PackageSetting requirer = null; 11680 for (PackageSetting ps : packagesForUser) { 11681 // If packagesForUser contains scannedPackage, we skip it. This will happen 11682 // when scannedPackage is an update of an existing package. Without this check, 11683 // we will never be able to change the ABI of any package belonging to a shared 11684 // user, even if it's compatible with other packages. 11685 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11686 if (ps.primaryCpuAbiString == null) { 11687 continue; 11688 } 11689 11690 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11691 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11692 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11693 // this but there's not much we can do. 11694 String errorMessage = "Instruction set mismatch, " 11695 + ((requirer == null) ? "[caller]" : requirer) 11696 + " requires " + requiredInstructionSet + " whereas " + ps 11697 + " requires " + instructionSet; 11698 Slog.w(TAG, errorMessage); 11699 } 11700 11701 if (requiredInstructionSet == null) { 11702 requiredInstructionSet = instructionSet; 11703 requirer = ps; 11704 } 11705 } 11706 } 11707 11708 if (requiredInstructionSet != null) { 11709 String adjustedAbi; 11710 if (requirer != null) { 11711 // requirer != null implies that either scannedPackage was null or that scannedPackage 11712 // did not require an ABI, in which case we have to adjust scannedPackage to match 11713 // the ABI of the set (which is the same as requirer's ABI) 11714 adjustedAbi = requirer.primaryCpuAbiString; 11715 if (scannedPackage != null) { 11716 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11717 } 11718 } else { 11719 // requirer == null implies that we're updating all ABIs in the set to 11720 // match scannedPackage. 11721 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11722 } 11723 11724 for (PackageSetting ps : packagesForUser) { 11725 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11726 if (ps.primaryCpuAbiString != null) { 11727 continue; 11728 } 11729 11730 ps.primaryCpuAbiString = adjustedAbi; 11731 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11732 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11733 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11734 if (DEBUG_ABI_SELECTION) { 11735 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11736 + " (requirer=" 11737 + (requirer != null ? requirer.pkg : "null") 11738 + ", scannedPackage=" 11739 + (scannedPackage != null ? scannedPackage : "null") 11740 + ")"); 11741 } 11742 if (changedAbiCodePath == null) { 11743 changedAbiCodePath = new ArrayList<>(); 11744 } 11745 changedAbiCodePath.add(ps.codePathString); 11746 } 11747 } 11748 } 11749 } 11750 return changedAbiCodePath; 11751 } 11752 11753 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11754 synchronized (mPackages) { 11755 mResolverReplaced = true; 11756 // Set up information for custom user intent resolution activity. 11757 mResolveActivity.applicationInfo = pkg.applicationInfo; 11758 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11759 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11760 mResolveActivity.processName = pkg.applicationInfo.packageName; 11761 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11762 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11763 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11764 mResolveActivity.theme = 0; 11765 mResolveActivity.exported = true; 11766 mResolveActivity.enabled = true; 11767 mResolveInfo.activityInfo = mResolveActivity; 11768 mResolveInfo.priority = 0; 11769 mResolveInfo.preferredOrder = 0; 11770 mResolveInfo.match = 0; 11771 mResolveComponentName = mCustomResolverComponentName; 11772 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11773 mResolveComponentName); 11774 } 11775 } 11776 11777 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11778 if (installerActivity == null) { 11779 if (DEBUG_INSTANT) { 11780 Slog.d(TAG, "Clear ephemeral installer activity"); 11781 } 11782 mInstantAppInstallerActivity = null; 11783 return; 11784 } 11785 11786 if (DEBUG_INSTANT) { 11787 Slog.d(TAG, "Set ephemeral installer activity: " 11788 + installerActivity.getComponentName()); 11789 } 11790 // Set up information for ephemeral installer activity 11791 mInstantAppInstallerActivity = installerActivity; 11792 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11793 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11794 mInstantAppInstallerActivity.exported = true; 11795 mInstantAppInstallerActivity.enabled = true; 11796 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11797 mInstantAppInstallerInfo.priority = 1; 11798 mInstantAppInstallerInfo.preferredOrder = 1; 11799 mInstantAppInstallerInfo.isDefault = true; 11800 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11801 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11802 } 11803 11804 private static String calculateBundledApkRoot(final String codePathString) { 11805 final File codePath = new File(codePathString); 11806 final File codeRoot; 11807 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11808 codeRoot = Environment.getRootDirectory(); 11809 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11810 codeRoot = Environment.getOemDirectory(); 11811 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11812 codeRoot = Environment.getVendorDirectory(); 11813 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 11814 codeRoot = Environment.getOdmDirectory(); 11815 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11816 codeRoot = Environment.getProductDirectory(); 11817 } else { 11818 // Unrecognized code path; take its top real segment as the apk root: 11819 // e.g. /something/app/blah.apk => /something 11820 try { 11821 File f = codePath.getCanonicalFile(); 11822 File parent = f.getParentFile(); // non-null because codePath is a file 11823 File tmp; 11824 while ((tmp = parent.getParentFile()) != null) { 11825 f = parent; 11826 parent = tmp; 11827 } 11828 codeRoot = f; 11829 Slog.w(TAG, "Unrecognized code path " 11830 + codePath + " - using " + codeRoot); 11831 } catch (IOException e) { 11832 // Can't canonicalize the code path -- shenanigans? 11833 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11834 return Environment.getRootDirectory().getPath(); 11835 } 11836 } 11837 return codeRoot.getPath(); 11838 } 11839 11840 /** 11841 * Derive and set the location of native libraries for the given package, 11842 * which varies depending on where and how the package was installed. 11843 */ 11844 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11845 final ApplicationInfo info = pkg.applicationInfo; 11846 final String codePath = pkg.codePath; 11847 final File codeFile = new File(codePath); 11848 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11849 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11850 11851 info.nativeLibraryRootDir = null; 11852 info.nativeLibraryRootRequiresIsa = false; 11853 info.nativeLibraryDir = null; 11854 info.secondaryNativeLibraryDir = null; 11855 11856 if (isApkFile(codeFile)) { 11857 // Monolithic install 11858 if (bundledApp) { 11859 // If "/system/lib64/apkname" exists, assume that is the per-package 11860 // native library directory to use; otherwise use "/system/lib/apkname". 11861 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11862 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11863 getPrimaryInstructionSet(info)); 11864 11865 // This is a bundled system app so choose the path based on the ABI. 11866 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11867 // is just the default path. 11868 final String apkName = deriveCodePathName(codePath); 11869 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11870 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11871 apkName).getAbsolutePath(); 11872 11873 if (info.secondaryCpuAbi != null) { 11874 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11875 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11876 secondaryLibDir, apkName).getAbsolutePath(); 11877 } 11878 } else if (asecApp) { 11879 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11880 .getAbsolutePath(); 11881 } else { 11882 final String apkName = deriveCodePathName(codePath); 11883 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11884 .getAbsolutePath(); 11885 } 11886 11887 info.nativeLibraryRootRequiresIsa = false; 11888 info.nativeLibraryDir = info.nativeLibraryRootDir; 11889 } else { 11890 // Cluster install 11891 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11892 info.nativeLibraryRootRequiresIsa = true; 11893 11894 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11895 getPrimaryInstructionSet(info)).getAbsolutePath(); 11896 11897 if (info.secondaryCpuAbi != null) { 11898 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11899 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11900 } 11901 } 11902 } 11903 11904 /** 11905 * Calculate the abis and roots for a bundled app. These can uniquely 11906 * be determined from the contents of the system partition, i.e whether 11907 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11908 * of this information, and instead assume that the system was built 11909 * sensibly. 11910 */ 11911 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11912 PackageSetting pkgSetting) { 11913 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11914 11915 // If "/system/lib64/apkname" exists, assume that is the per-package 11916 // native library directory to use; otherwise use "/system/lib/apkname". 11917 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11918 setBundledAppAbi(pkg, apkRoot, apkName); 11919 // pkgSetting might be null during rescan following uninstall of updates 11920 // to a bundled app, so accommodate that possibility. The settings in 11921 // that case will be established later from the parsed package. 11922 // 11923 // If the settings aren't null, sync them up with what we've just derived. 11924 // note that apkRoot isn't stored in the package settings. 11925 if (pkgSetting != null) { 11926 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11927 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11928 } 11929 } 11930 11931 /** 11932 * Deduces the ABI of a bundled app and sets the relevant fields on the 11933 * parsed pkg object. 11934 * 11935 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11936 * under which system libraries are installed. 11937 * @param apkName the name of the installed package. 11938 */ 11939 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11940 final File codeFile = new File(pkg.codePath); 11941 11942 final boolean has64BitLibs; 11943 final boolean has32BitLibs; 11944 if (isApkFile(codeFile)) { 11945 // Monolithic install 11946 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11947 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11948 } else { 11949 // Cluster install 11950 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11951 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11952 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11953 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11954 has64BitLibs = (new File(rootDir, isa)).exists(); 11955 } else { 11956 has64BitLibs = false; 11957 } 11958 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11959 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11960 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11961 has32BitLibs = (new File(rootDir, isa)).exists(); 11962 } else { 11963 has32BitLibs = false; 11964 } 11965 } 11966 11967 if (has64BitLibs && !has32BitLibs) { 11968 // The package has 64 bit libs, but not 32 bit libs. Its primary 11969 // ABI should be 64 bit. We can safely assume here that the bundled 11970 // native libraries correspond to the most preferred ABI in the list. 11971 11972 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11973 pkg.applicationInfo.secondaryCpuAbi = null; 11974 } else if (has32BitLibs && !has64BitLibs) { 11975 // The package has 32 bit libs but not 64 bit libs. Its primary 11976 // ABI should be 32 bit. 11977 11978 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11979 pkg.applicationInfo.secondaryCpuAbi = null; 11980 } else if (has32BitLibs && has64BitLibs) { 11981 // The application has both 64 and 32 bit bundled libraries. We check 11982 // here that the app declares multiArch support, and warn if it doesn't. 11983 // 11984 // We will be lenient here and record both ABIs. The primary will be the 11985 // ABI that's higher on the list, i.e, a device that's configured to prefer 11986 // 64 bit apps will see a 64 bit primary ABI, 11987 11988 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11989 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11990 } 11991 11992 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11993 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11994 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11995 } else { 11996 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11997 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11998 } 11999 } else { 12000 pkg.applicationInfo.primaryCpuAbi = null; 12001 pkg.applicationInfo.secondaryCpuAbi = null; 12002 } 12003 } 12004 12005 private void killApplication(String pkgName, int appId, String reason) { 12006 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12007 } 12008 12009 private void killApplication(String pkgName, int appId, int userId, String reason) { 12010 // Request the ActivityManager to kill the process(only for existing packages) 12011 // so that we do not end up in a confused state while the user is still using the older 12012 // version of the application while the new one gets installed. 12013 final long token = Binder.clearCallingIdentity(); 12014 try { 12015 IActivityManager am = ActivityManager.getService(); 12016 if (am != null) { 12017 try { 12018 am.killApplication(pkgName, appId, userId, reason); 12019 } catch (RemoteException e) { 12020 } 12021 } 12022 } finally { 12023 Binder.restoreCallingIdentity(token); 12024 } 12025 } 12026 12027 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12028 // Remove the parent package setting 12029 PackageSetting ps = (PackageSetting) pkg.mExtras; 12030 if (ps != null) { 12031 removePackageLI(ps, chatty); 12032 } 12033 // Remove the child package setting 12034 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12035 for (int i = 0; i < childCount; i++) { 12036 PackageParser.Package childPkg = pkg.childPackages.get(i); 12037 ps = (PackageSetting) childPkg.mExtras; 12038 if (ps != null) { 12039 removePackageLI(ps, chatty); 12040 } 12041 } 12042 } 12043 12044 void removePackageLI(PackageSetting ps, boolean chatty) { 12045 if (DEBUG_INSTALL) { 12046 if (chatty) 12047 Log.d(TAG, "Removing package " + ps.name); 12048 } 12049 12050 // writer 12051 synchronized (mPackages) { 12052 mPackages.remove(ps.name); 12053 final PackageParser.Package pkg = ps.pkg; 12054 if (pkg != null) { 12055 cleanPackageDataStructuresLILPw(pkg, chatty); 12056 } 12057 } 12058 } 12059 12060 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12061 if (DEBUG_INSTALL) { 12062 if (chatty) 12063 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12064 } 12065 12066 // writer 12067 synchronized (mPackages) { 12068 // Remove the parent package 12069 mPackages.remove(pkg.applicationInfo.packageName); 12070 cleanPackageDataStructuresLILPw(pkg, chatty); 12071 12072 // Remove the child packages 12073 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12074 for (int i = 0; i < childCount; i++) { 12075 PackageParser.Package childPkg = pkg.childPackages.get(i); 12076 mPackages.remove(childPkg.applicationInfo.packageName); 12077 cleanPackageDataStructuresLILPw(childPkg, chatty); 12078 } 12079 } 12080 } 12081 12082 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12083 int N = pkg.providers.size(); 12084 StringBuilder r = null; 12085 int i; 12086 for (i=0; i<N; i++) { 12087 PackageParser.Provider p = pkg.providers.get(i); 12088 mProviders.removeProvider(p); 12089 if (p.info.authority == null) { 12090 12091 /* There was another ContentProvider with this authority when 12092 * this app was installed so this authority is null, 12093 * Ignore it as we don't have to unregister the provider. 12094 */ 12095 continue; 12096 } 12097 String names[] = p.info.authority.split(";"); 12098 for (int j = 0; j < names.length; j++) { 12099 if (mProvidersByAuthority.get(names[j]) == p) { 12100 mProvidersByAuthority.remove(names[j]); 12101 if (DEBUG_REMOVE) { 12102 if (chatty) 12103 Log.d(TAG, "Unregistered content provider: " + names[j] 12104 + ", className = " + p.info.name + ", isSyncable = " 12105 + p.info.isSyncable); 12106 } 12107 } 12108 } 12109 if (DEBUG_REMOVE && chatty) { 12110 if (r == null) { 12111 r = new StringBuilder(256); 12112 } else { 12113 r.append(' '); 12114 } 12115 r.append(p.info.name); 12116 } 12117 } 12118 if (r != null) { 12119 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12120 } 12121 12122 N = pkg.services.size(); 12123 r = null; 12124 for (i=0; i<N; i++) { 12125 PackageParser.Service s = pkg.services.get(i); 12126 mServices.removeService(s); 12127 if (chatty) { 12128 if (r == null) { 12129 r = new StringBuilder(256); 12130 } else { 12131 r.append(' '); 12132 } 12133 r.append(s.info.name); 12134 } 12135 } 12136 if (r != null) { 12137 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12138 } 12139 12140 N = pkg.receivers.size(); 12141 r = null; 12142 for (i=0; i<N; i++) { 12143 PackageParser.Activity a = pkg.receivers.get(i); 12144 mReceivers.removeActivity(a, "receiver"); 12145 if (DEBUG_REMOVE && chatty) { 12146 if (r == null) { 12147 r = new StringBuilder(256); 12148 } else { 12149 r.append(' '); 12150 } 12151 r.append(a.info.name); 12152 } 12153 } 12154 if (r != null) { 12155 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12156 } 12157 12158 N = pkg.activities.size(); 12159 r = null; 12160 for (i=0; i<N; i++) { 12161 PackageParser.Activity a = pkg.activities.get(i); 12162 mActivities.removeActivity(a, "activity"); 12163 if (DEBUG_REMOVE && chatty) { 12164 if (r == null) { 12165 r = new StringBuilder(256); 12166 } else { 12167 r.append(' '); 12168 } 12169 r.append(a.info.name); 12170 } 12171 } 12172 if (r != null) { 12173 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12174 } 12175 12176 mPermissionManager.removeAllPermissions(pkg, chatty); 12177 12178 N = pkg.instrumentation.size(); 12179 r = null; 12180 for (i=0; i<N; i++) { 12181 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12182 mInstrumentation.remove(a.getComponentName()); 12183 if (DEBUG_REMOVE && chatty) { 12184 if (r == null) { 12185 r = new StringBuilder(256); 12186 } else { 12187 r.append(' '); 12188 } 12189 r.append(a.info.name); 12190 } 12191 } 12192 if (r != null) { 12193 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12194 } 12195 12196 r = null; 12197 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12198 // Only system apps can hold shared libraries. 12199 if (pkg.libraryNames != null) { 12200 for (i = 0; i < pkg.libraryNames.size(); i++) { 12201 String name = pkg.libraryNames.get(i); 12202 if (removeSharedLibraryLPw(name, 0)) { 12203 if (DEBUG_REMOVE && chatty) { 12204 if (r == null) { 12205 r = new StringBuilder(256); 12206 } else { 12207 r.append(' '); 12208 } 12209 r.append(name); 12210 } 12211 } 12212 } 12213 } 12214 } 12215 12216 r = null; 12217 12218 // Any package can hold static shared libraries. 12219 if (pkg.staticSharedLibName != null) { 12220 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12221 if (DEBUG_REMOVE && chatty) { 12222 if (r == null) { 12223 r = new StringBuilder(256); 12224 } else { 12225 r.append(' '); 12226 } 12227 r.append(pkg.staticSharedLibName); 12228 } 12229 } 12230 } 12231 12232 if (r != null) { 12233 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12234 } 12235 } 12236 12237 12238 final class ActivityIntentResolver 12239 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12240 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12241 boolean defaultOnly, int userId) { 12242 if (!sUserManager.exists(userId)) return null; 12243 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12244 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12245 } 12246 12247 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12248 int userId) { 12249 if (!sUserManager.exists(userId)) return null; 12250 mFlags = flags; 12251 return super.queryIntent(intent, resolvedType, 12252 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12253 userId); 12254 } 12255 12256 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12257 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12258 if (!sUserManager.exists(userId)) return null; 12259 if (packageActivities == null) { 12260 return null; 12261 } 12262 mFlags = flags; 12263 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12264 final int N = packageActivities.size(); 12265 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12266 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12267 12268 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12269 for (int i = 0; i < N; ++i) { 12270 intentFilters = packageActivities.get(i).intents; 12271 if (intentFilters != null && intentFilters.size() > 0) { 12272 PackageParser.ActivityIntentInfo[] array = 12273 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12274 intentFilters.toArray(array); 12275 listCut.add(array); 12276 } 12277 } 12278 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12279 } 12280 12281 /** 12282 * Finds a privileged activity that matches the specified activity names. 12283 */ 12284 private PackageParser.Activity findMatchingActivity( 12285 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12286 for (PackageParser.Activity sysActivity : activityList) { 12287 if (sysActivity.info.name.equals(activityInfo.name)) { 12288 return sysActivity; 12289 } 12290 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12291 return sysActivity; 12292 } 12293 if (sysActivity.info.targetActivity != null) { 12294 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12295 return sysActivity; 12296 } 12297 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12298 return sysActivity; 12299 } 12300 } 12301 } 12302 return null; 12303 } 12304 12305 public class IterGenerator<E> { 12306 public Iterator<E> generate(ActivityIntentInfo info) { 12307 return null; 12308 } 12309 } 12310 12311 public class ActionIterGenerator extends IterGenerator<String> { 12312 @Override 12313 public Iterator<String> generate(ActivityIntentInfo info) { 12314 return info.actionsIterator(); 12315 } 12316 } 12317 12318 public class CategoriesIterGenerator extends IterGenerator<String> { 12319 @Override 12320 public Iterator<String> generate(ActivityIntentInfo info) { 12321 return info.categoriesIterator(); 12322 } 12323 } 12324 12325 public class SchemesIterGenerator extends IterGenerator<String> { 12326 @Override 12327 public Iterator<String> generate(ActivityIntentInfo info) { 12328 return info.schemesIterator(); 12329 } 12330 } 12331 12332 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12333 @Override 12334 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12335 return info.authoritiesIterator(); 12336 } 12337 } 12338 12339 /** 12340 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12341 * MODIFIED. Do not pass in a list that should not be changed. 12342 */ 12343 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12344 IterGenerator<T> generator, Iterator<T> searchIterator) { 12345 // loop through the set of actions; every one must be found in the intent filter 12346 while (searchIterator.hasNext()) { 12347 // we must have at least one filter in the list to consider a match 12348 if (intentList.size() == 0) { 12349 break; 12350 } 12351 12352 final T searchAction = searchIterator.next(); 12353 12354 // loop through the set of intent filters 12355 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12356 while (intentIter.hasNext()) { 12357 final ActivityIntentInfo intentInfo = intentIter.next(); 12358 boolean selectionFound = false; 12359 12360 // loop through the intent filter's selection criteria; at least one 12361 // of them must match the searched criteria 12362 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12363 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12364 final T intentSelection = intentSelectionIter.next(); 12365 if (intentSelection != null && intentSelection.equals(searchAction)) { 12366 selectionFound = true; 12367 break; 12368 } 12369 } 12370 12371 // the selection criteria wasn't found in this filter's set; this filter 12372 // is not a potential match 12373 if (!selectionFound) { 12374 intentIter.remove(); 12375 } 12376 } 12377 } 12378 } 12379 12380 private boolean isProtectedAction(ActivityIntentInfo filter) { 12381 final Iterator<String> actionsIter = filter.actionsIterator(); 12382 while (actionsIter != null && actionsIter.hasNext()) { 12383 final String filterAction = actionsIter.next(); 12384 if (PROTECTED_ACTIONS.contains(filterAction)) { 12385 return true; 12386 } 12387 } 12388 return false; 12389 } 12390 12391 /** 12392 * Adjusts the priority of the given intent filter according to policy. 12393 * <p> 12394 * <ul> 12395 * <li>The priority for non privileged applications is capped to '0'</li> 12396 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12397 * <li>The priority for unbundled updates to privileged applications is capped to the 12398 * priority defined on the system partition</li> 12399 * </ul> 12400 * <p> 12401 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12402 * allowed to obtain any priority on any action. 12403 */ 12404 private void adjustPriority( 12405 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12406 // nothing to do; priority is fine as-is 12407 if (intent.getPriority() <= 0) { 12408 return; 12409 } 12410 12411 final ActivityInfo activityInfo = intent.activity.info; 12412 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12413 12414 final boolean privilegedApp = 12415 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12416 if (!privilegedApp) { 12417 // non-privileged applications can never define a priority >0 12418 if (DEBUG_FILTERS) { 12419 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12420 + " package: " + applicationInfo.packageName 12421 + " activity: " + intent.activity.className 12422 + " origPrio: " + intent.getPriority()); 12423 } 12424 intent.setPriority(0); 12425 return; 12426 } 12427 12428 if (systemActivities == null) { 12429 // the system package is not disabled; we're parsing the system partition 12430 if (isProtectedAction(intent)) { 12431 if (mDeferProtectedFilters) { 12432 // We can't deal with these just yet. No component should ever obtain a 12433 // >0 priority for a protected actions, with ONE exception -- the setup 12434 // wizard. The setup wizard, however, cannot be known until we're able to 12435 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12436 // until all intent filters have been processed. Chicken, meet egg. 12437 // Let the filter temporarily have a high priority and rectify the 12438 // priorities after all system packages have been scanned. 12439 mProtectedFilters.add(intent); 12440 if (DEBUG_FILTERS) { 12441 Slog.i(TAG, "Protected action; save for later;" 12442 + " package: " + applicationInfo.packageName 12443 + " activity: " + intent.activity.className 12444 + " origPrio: " + intent.getPriority()); 12445 } 12446 return; 12447 } else { 12448 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12449 Slog.i(TAG, "No setup wizard;" 12450 + " All protected intents capped to priority 0"); 12451 } 12452 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12453 if (DEBUG_FILTERS) { 12454 Slog.i(TAG, "Found setup wizard;" 12455 + " allow priority " + intent.getPriority() + ";" 12456 + " package: " + intent.activity.info.packageName 12457 + " activity: " + intent.activity.className 12458 + " priority: " + intent.getPriority()); 12459 } 12460 // setup wizard gets whatever it wants 12461 return; 12462 } 12463 if (DEBUG_FILTERS) { 12464 Slog.i(TAG, "Protected action; cap priority to 0;" 12465 + " package: " + intent.activity.info.packageName 12466 + " activity: " + intent.activity.className 12467 + " origPrio: " + intent.getPriority()); 12468 } 12469 intent.setPriority(0); 12470 return; 12471 } 12472 } 12473 // privileged apps on the system image get whatever priority they request 12474 return; 12475 } 12476 12477 // privileged app unbundled update ... try to find the same activity 12478 final PackageParser.Activity foundActivity = 12479 findMatchingActivity(systemActivities, activityInfo); 12480 if (foundActivity == null) { 12481 // this is a new activity; it cannot obtain >0 priority 12482 if (DEBUG_FILTERS) { 12483 Slog.i(TAG, "New activity; cap priority to 0;" 12484 + " package: " + applicationInfo.packageName 12485 + " activity: " + intent.activity.className 12486 + " origPrio: " + intent.getPriority()); 12487 } 12488 intent.setPriority(0); 12489 return; 12490 } 12491 12492 // found activity, now check for filter equivalence 12493 12494 // a shallow copy is enough; we modify the list, not its contents 12495 final List<ActivityIntentInfo> intentListCopy = 12496 new ArrayList<>(foundActivity.intents); 12497 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12498 12499 // find matching action subsets 12500 final Iterator<String> actionsIterator = intent.actionsIterator(); 12501 if (actionsIterator != null) { 12502 getIntentListSubset( 12503 intentListCopy, new ActionIterGenerator(), actionsIterator); 12504 if (intentListCopy.size() == 0) { 12505 // no more intents to match; we're not equivalent 12506 if (DEBUG_FILTERS) { 12507 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12508 + " package: " + applicationInfo.packageName 12509 + " activity: " + intent.activity.className 12510 + " origPrio: " + intent.getPriority()); 12511 } 12512 intent.setPriority(0); 12513 return; 12514 } 12515 } 12516 12517 // find matching category subsets 12518 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12519 if (categoriesIterator != null) { 12520 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12521 categoriesIterator); 12522 if (intentListCopy.size() == 0) { 12523 // no more intents to match; we're not equivalent 12524 if (DEBUG_FILTERS) { 12525 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12526 + " package: " + applicationInfo.packageName 12527 + " activity: " + intent.activity.className 12528 + " origPrio: " + intent.getPriority()); 12529 } 12530 intent.setPriority(0); 12531 return; 12532 } 12533 } 12534 12535 // find matching schemes subsets 12536 final Iterator<String> schemesIterator = intent.schemesIterator(); 12537 if (schemesIterator != null) { 12538 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12539 schemesIterator); 12540 if (intentListCopy.size() == 0) { 12541 // no more intents to match; we're not equivalent 12542 if (DEBUG_FILTERS) { 12543 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12544 + " package: " + applicationInfo.packageName 12545 + " activity: " + intent.activity.className 12546 + " origPrio: " + intent.getPriority()); 12547 } 12548 intent.setPriority(0); 12549 return; 12550 } 12551 } 12552 12553 // find matching authorities subsets 12554 final Iterator<IntentFilter.AuthorityEntry> 12555 authoritiesIterator = intent.authoritiesIterator(); 12556 if (authoritiesIterator != null) { 12557 getIntentListSubset(intentListCopy, 12558 new AuthoritiesIterGenerator(), 12559 authoritiesIterator); 12560 if (intentListCopy.size() == 0) { 12561 // no more intents to match; we're not equivalent 12562 if (DEBUG_FILTERS) { 12563 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12564 + " package: " + applicationInfo.packageName 12565 + " activity: " + intent.activity.className 12566 + " origPrio: " + intent.getPriority()); 12567 } 12568 intent.setPriority(0); 12569 return; 12570 } 12571 } 12572 12573 // we found matching filter(s); app gets the max priority of all intents 12574 int cappedPriority = 0; 12575 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12576 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12577 } 12578 if (intent.getPriority() > cappedPriority) { 12579 if (DEBUG_FILTERS) { 12580 Slog.i(TAG, "Found matching filter(s);" 12581 + " cap priority to " + cappedPriority + ";" 12582 + " package: " + applicationInfo.packageName 12583 + " activity: " + intent.activity.className 12584 + " origPrio: " + intent.getPriority()); 12585 } 12586 intent.setPriority(cappedPriority); 12587 return; 12588 } 12589 // all this for nothing; the requested priority was <= what was on the system 12590 } 12591 12592 public final void addActivity(PackageParser.Activity a, String type) { 12593 mActivities.put(a.getComponentName(), a); 12594 if (DEBUG_SHOW_INFO) 12595 Log.v( 12596 TAG, " " + type + " " + 12597 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12598 if (DEBUG_SHOW_INFO) 12599 Log.v(TAG, " Class=" + a.info.name); 12600 final int NI = a.intents.size(); 12601 for (int j=0; j<NI; j++) { 12602 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12603 if ("activity".equals(type)) { 12604 final PackageSetting ps = 12605 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12606 final List<PackageParser.Activity> systemActivities = 12607 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12608 adjustPriority(systemActivities, intent); 12609 } 12610 if (DEBUG_SHOW_INFO) { 12611 Log.v(TAG, " IntentFilter:"); 12612 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12613 } 12614 if (!intent.debugCheck()) { 12615 Log.w(TAG, "==> For Activity " + a.info.name); 12616 } 12617 addFilter(intent); 12618 } 12619 } 12620 12621 public final void removeActivity(PackageParser.Activity a, String type) { 12622 mActivities.remove(a.getComponentName()); 12623 if (DEBUG_SHOW_INFO) { 12624 Log.v(TAG, " " + type + " " 12625 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12626 : a.info.name) + ":"); 12627 Log.v(TAG, " Class=" + a.info.name); 12628 } 12629 final int NI = a.intents.size(); 12630 for (int j=0; j<NI; j++) { 12631 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12632 if (DEBUG_SHOW_INFO) { 12633 Log.v(TAG, " IntentFilter:"); 12634 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12635 } 12636 removeFilter(intent); 12637 } 12638 } 12639 12640 @Override 12641 protected boolean allowFilterResult( 12642 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12643 ActivityInfo filterAi = filter.activity.info; 12644 for (int i=dest.size()-1; i>=0; i--) { 12645 ActivityInfo destAi = dest.get(i).activityInfo; 12646 if (destAi.name == filterAi.name 12647 && destAi.packageName == filterAi.packageName) { 12648 return false; 12649 } 12650 } 12651 return true; 12652 } 12653 12654 @Override 12655 protected ActivityIntentInfo[] newArray(int size) { 12656 return new ActivityIntentInfo[size]; 12657 } 12658 12659 @Override 12660 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12661 if (!sUserManager.exists(userId)) return true; 12662 PackageParser.Package p = filter.activity.owner; 12663 if (p != null) { 12664 PackageSetting ps = (PackageSetting)p.mExtras; 12665 if (ps != null) { 12666 // System apps are never considered stopped for purposes of 12667 // filtering, because there may be no way for the user to 12668 // actually re-launch them. 12669 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12670 && ps.getStopped(userId); 12671 } 12672 } 12673 return false; 12674 } 12675 12676 @Override 12677 protected boolean isPackageForFilter(String packageName, 12678 PackageParser.ActivityIntentInfo info) { 12679 return packageName.equals(info.activity.owner.packageName); 12680 } 12681 12682 @Override 12683 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12684 int match, int userId) { 12685 if (!sUserManager.exists(userId)) return null; 12686 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12687 return null; 12688 } 12689 final PackageParser.Activity activity = info.activity; 12690 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12691 if (ps == null) { 12692 return null; 12693 } 12694 final PackageUserState userState = ps.readUserState(userId); 12695 ActivityInfo ai = 12696 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12697 if (ai == null) { 12698 return null; 12699 } 12700 final boolean matchExplicitlyVisibleOnly = 12701 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12702 final boolean matchVisibleToInstantApp = 12703 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12704 final boolean componentVisible = 12705 matchVisibleToInstantApp 12706 && info.isVisibleToInstantApp() 12707 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12708 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12709 // throw out filters that aren't visible to ephemeral apps 12710 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12711 return null; 12712 } 12713 // throw out instant app filters if we're not explicitly requesting them 12714 if (!matchInstantApp && userState.instantApp) { 12715 return null; 12716 } 12717 // throw out instant app filters if updates are available; will trigger 12718 // instant app resolution 12719 if (userState.instantApp && ps.isUpdateAvailable()) { 12720 return null; 12721 } 12722 final ResolveInfo res = new ResolveInfo(); 12723 res.activityInfo = ai; 12724 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12725 res.filter = info; 12726 } 12727 if (info != null) { 12728 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12729 } 12730 res.priority = info.getPriority(); 12731 res.preferredOrder = activity.owner.mPreferredOrder; 12732 //System.out.println("Result: " + res.activityInfo.className + 12733 // " = " + res.priority); 12734 res.match = match; 12735 res.isDefault = info.hasDefault; 12736 res.labelRes = info.labelRes; 12737 res.nonLocalizedLabel = info.nonLocalizedLabel; 12738 if (userNeedsBadging(userId)) { 12739 res.noResourceId = true; 12740 } else { 12741 res.icon = info.icon; 12742 } 12743 res.iconResourceId = info.icon; 12744 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12745 res.isInstantAppAvailable = userState.instantApp; 12746 return res; 12747 } 12748 12749 @Override 12750 protected void sortResults(List<ResolveInfo> results) { 12751 Collections.sort(results, mResolvePrioritySorter); 12752 } 12753 12754 @Override 12755 protected void dumpFilter(PrintWriter out, String prefix, 12756 PackageParser.ActivityIntentInfo filter) { 12757 out.print(prefix); out.print( 12758 Integer.toHexString(System.identityHashCode(filter.activity))); 12759 out.print(' '); 12760 filter.activity.printComponentShortName(out); 12761 out.print(" filter "); 12762 out.println(Integer.toHexString(System.identityHashCode(filter))); 12763 } 12764 12765 @Override 12766 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12767 return filter.activity; 12768 } 12769 12770 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12771 PackageParser.Activity activity = (PackageParser.Activity)label; 12772 out.print(prefix); out.print( 12773 Integer.toHexString(System.identityHashCode(activity))); 12774 out.print(' '); 12775 activity.printComponentShortName(out); 12776 if (count > 1) { 12777 out.print(" ("); out.print(count); out.print(" filters)"); 12778 } 12779 out.println(); 12780 } 12781 12782 // Keys are String (activity class name), values are Activity. 12783 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12784 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12785 private int mFlags; 12786 } 12787 12788 private final class ServiceIntentResolver 12789 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12790 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12791 boolean defaultOnly, int userId) { 12792 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12793 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12794 } 12795 12796 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12797 int userId) { 12798 if (!sUserManager.exists(userId)) return null; 12799 mFlags = flags; 12800 return super.queryIntent(intent, resolvedType, 12801 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12802 userId); 12803 } 12804 12805 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12806 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12807 if (!sUserManager.exists(userId)) return null; 12808 if (packageServices == null) { 12809 return null; 12810 } 12811 mFlags = flags; 12812 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12813 final int N = packageServices.size(); 12814 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12815 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12816 12817 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12818 for (int i = 0; i < N; ++i) { 12819 intentFilters = packageServices.get(i).intents; 12820 if (intentFilters != null && intentFilters.size() > 0) { 12821 PackageParser.ServiceIntentInfo[] array = 12822 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12823 intentFilters.toArray(array); 12824 listCut.add(array); 12825 } 12826 } 12827 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12828 } 12829 12830 public final void addService(PackageParser.Service s) { 12831 mServices.put(s.getComponentName(), s); 12832 if (DEBUG_SHOW_INFO) { 12833 Log.v(TAG, " " 12834 + (s.info.nonLocalizedLabel != null 12835 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12836 Log.v(TAG, " Class=" + s.info.name); 12837 } 12838 final int NI = s.intents.size(); 12839 int j; 12840 for (j=0; j<NI; j++) { 12841 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12842 if (DEBUG_SHOW_INFO) { 12843 Log.v(TAG, " IntentFilter:"); 12844 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12845 } 12846 if (!intent.debugCheck()) { 12847 Log.w(TAG, "==> For Service " + s.info.name); 12848 } 12849 addFilter(intent); 12850 } 12851 } 12852 12853 public final void removeService(PackageParser.Service s) { 12854 mServices.remove(s.getComponentName()); 12855 if (DEBUG_SHOW_INFO) { 12856 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12857 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12858 Log.v(TAG, " Class=" + s.info.name); 12859 } 12860 final int NI = s.intents.size(); 12861 int j; 12862 for (j=0; j<NI; j++) { 12863 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12864 if (DEBUG_SHOW_INFO) { 12865 Log.v(TAG, " IntentFilter:"); 12866 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12867 } 12868 removeFilter(intent); 12869 } 12870 } 12871 12872 @Override 12873 protected boolean allowFilterResult( 12874 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12875 ServiceInfo filterSi = filter.service.info; 12876 for (int i=dest.size()-1; i>=0; i--) { 12877 ServiceInfo destAi = dest.get(i).serviceInfo; 12878 if (destAi.name == filterSi.name 12879 && destAi.packageName == filterSi.packageName) { 12880 return false; 12881 } 12882 } 12883 return true; 12884 } 12885 12886 @Override 12887 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12888 return new PackageParser.ServiceIntentInfo[size]; 12889 } 12890 12891 @Override 12892 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12893 if (!sUserManager.exists(userId)) return true; 12894 PackageParser.Package p = filter.service.owner; 12895 if (p != null) { 12896 PackageSetting ps = (PackageSetting)p.mExtras; 12897 if (ps != null) { 12898 // System apps are never considered stopped for purposes of 12899 // filtering, because there may be no way for the user to 12900 // actually re-launch them. 12901 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12902 && ps.getStopped(userId); 12903 } 12904 } 12905 return false; 12906 } 12907 12908 @Override 12909 protected boolean isPackageForFilter(String packageName, 12910 PackageParser.ServiceIntentInfo info) { 12911 return packageName.equals(info.service.owner.packageName); 12912 } 12913 12914 @Override 12915 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12916 int match, int userId) { 12917 if (!sUserManager.exists(userId)) return null; 12918 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12919 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12920 return null; 12921 } 12922 final PackageParser.Service service = info.service; 12923 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12924 if (ps == null) { 12925 return null; 12926 } 12927 final PackageUserState userState = ps.readUserState(userId); 12928 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12929 userState, userId); 12930 if (si == null) { 12931 return null; 12932 } 12933 final boolean matchVisibleToInstantApp = 12934 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12935 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12936 // throw out filters that aren't visible to ephemeral apps 12937 if (matchVisibleToInstantApp 12938 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12939 return null; 12940 } 12941 // throw out ephemeral filters if we're not explicitly requesting them 12942 if (!isInstantApp && userState.instantApp) { 12943 return null; 12944 } 12945 // throw out instant app filters if updates are available; will trigger 12946 // instant app resolution 12947 if (userState.instantApp && ps.isUpdateAvailable()) { 12948 return null; 12949 } 12950 final ResolveInfo res = new ResolveInfo(); 12951 res.serviceInfo = si; 12952 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12953 res.filter = filter; 12954 } 12955 res.priority = info.getPriority(); 12956 res.preferredOrder = service.owner.mPreferredOrder; 12957 res.match = match; 12958 res.isDefault = info.hasDefault; 12959 res.labelRes = info.labelRes; 12960 res.nonLocalizedLabel = info.nonLocalizedLabel; 12961 res.icon = info.icon; 12962 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12963 return res; 12964 } 12965 12966 @Override 12967 protected void sortResults(List<ResolveInfo> results) { 12968 Collections.sort(results, mResolvePrioritySorter); 12969 } 12970 12971 @Override 12972 protected void dumpFilter(PrintWriter out, String prefix, 12973 PackageParser.ServiceIntentInfo filter) { 12974 out.print(prefix); out.print( 12975 Integer.toHexString(System.identityHashCode(filter.service))); 12976 out.print(' '); 12977 filter.service.printComponentShortName(out); 12978 out.print(" filter "); 12979 out.print(Integer.toHexString(System.identityHashCode(filter))); 12980 if (filter.service.info.permission != null) { 12981 out.print(" permission "); out.println(filter.service.info.permission); 12982 } else { 12983 out.println(); 12984 } 12985 } 12986 12987 @Override 12988 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12989 return filter.service; 12990 } 12991 12992 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12993 PackageParser.Service service = (PackageParser.Service)label; 12994 out.print(prefix); out.print( 12995 Integer.toHexString(System.identityHashCode(service))); 12996 out.print(' '); 12997 service.printComponentShortName(out); 12998 if (count > 1) { 12999 out.print(" ("); out.print(count); out.print(" filters)"); 13000 } 13001 out.println(); 13002 } 13003 13004// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13005// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13006// final List<ResolveInfo> retList = Lists.newArrayList(); 13007// while (i.hasNext()) { 13008// final ResolveInfo resolveInfo = (ResolveInfo) i; 13009// if (isEnabledLP(resolveInfo.serviceInfo)) { 13010// retList.add(resolveInfo); 13011// } 13012// } 13013// return retList; 13014// } 13015 13016 // Keys are String (activity class name), values are Activity. 13017 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13018 = new ArrayMap<ComponentName, PackageParser.Service>(); 13019 private int mFlags; 13020 } 13021 13022 private final class ProviderIntentResolver 13023 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13024 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13025 boolean defaultOnly, int userId) { 13026 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13027 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13028 } 13029 13030 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13031 int userId) { 13032 if (!sUserManager.exists(userId)) 13033 return null; 13034 mFlags = flags; 13035 return super.queryIntent(intent, resolvedType, 13036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13037 userId); 13038 } 13039 13040 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13041 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13042 if (!sUserManager.exists(userId)) 13043 return null; 13044 if (packageProviders == null) { 13045 return null; 13046 } 13047 mFlags = flags; 13048 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13049 final int N = packageProviders.size(); 13050 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13051 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13052 13053 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13054 for (int i = 0; i < N; ++i) { 13055 intentFilters = packageProviders.get(i).intents; 13056 if (intentFilters != null && intentFilters.size() > 0) { 13057 PackageParser.ProviderIntentInfo[] array = 13058 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13059 intentFilters.toArray(array); 13060 listCut.add(array); 13061 } 13062 } 13063 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13064 } 13065 13066 public final void addProvider(PackageParser.Provider p) { 13067 if (mProviders.containsKey(p.getComponentName())) { 13068 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13069 return; 13070 } 13071 13072 mProviders.put(p.getComponentName(), p); 13073 if (DEBUG_SHOW_INFO) { 13074 Log.v(TAG, " " 13075 + (p.info.nonLocalizedLabel != null 13076 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13077 Log.v(TAG, " Class=" + p.info.name); 13078 } 13079 final int NI = p.intents.size(); 13080 int j; 13081 for (j = 0; j < NI; j++) { 13082 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13083 if (DEBUG_SHOW_INFO) { 13084 Log.v(TAG, " IntentFilter:"); 13085 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13086 } 13087 if (!intent.debugCheck()) { 13088 Log.w(TAG, "==> For Provider " + p.info.name); 13089 } 13090 addFilter(intent); 13091 } 13092 } 13093 13094 public final void removeProvider(PackageParser.Provider p) { 13095 mProviders.remove(p.getComponentName()); 13096 if (DEBUG_SHOW_INFO) { 13097 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13098 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13099 Log.v(TAG, " Class=" + p.info.name); 13100 } 13101 final int NI = p.intents.size(); 13102 int j; 13103 for (j = 0; j < NI; j++) { 13104 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13105 if (DEBUG_SHOW_INFO) { 13106 Log.v(TAG, " IntentFilter:"); 13107 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13108 } 13109 removeFilter(intent); 13110 } 13111 } 13112 13113 @Override 13114 protected boolean allowFilterResult( 13115 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13116 ProviderInfo filterPi = filter.provider.info; 13117 for (int i = dest.size() - 1; i >= 0; i--) { 13118 ProviderInfo destPi = dest.get(i).providerInfo; 13119 if (destPi.name == filterPi.name 13120 && destPi.packageName == filterPi.packageName) { 13121 return false; 13122 } 13123 } 13124 return true; 13125 } 13126 13127 @Override 13128 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13129 return new PackageParser.ProviderIntentInfo[size]; 13130 } 13131 13132 @Override 13133 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13134 if (!sUserManager.exists(userId)) 13135 return true; 13136 PackageParser.Package p = filter.provider.owner; 13137 if (p != null) { 13138 PackageSetting ps = (PackageSetting) p.mExtras; 13139 if (ps != null) { 13140 // System apps are never considered stopped for purposes of 13141 // filtering, because there may be no way for the user to 13142 // actually re-launch them. 13143 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13144 && ps.getStopped(userId); 13145 } 13146 } 13147 return false; 13148 } 13149 13150 @Override 13151 protected boolean isPackageForFilter(String packageName, 13152 PackageParser.ProviderIntentInfo info) { 13153 return packageName.equals(info.provider.owner.packageName); 13154 } 13155 13156 @Override 13157 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13158 int match, int userId) { 13159 if (!sUserManager.exists(userId)) 13160 return null; 13161 final PackageParser.ProviderIntentInfo info = filter; 13162 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13163 return null; 13164 } 13165 final PackageParser.Provider provider = info.provider; 13166 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13167 if (ps == null) { 13168 return null; 13169 } 13170 final PackageUserState userState = ps.readUserState(userId); 13171 final boolean matchVisibleToInstantApp = 13172 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13173 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13174 // throw out filters that aren't visible to instant applications 13175 if (matchVisibleToInstantApp 13176 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13177 return null; 13178 } 13179 // throw out instant application filters if we're not explicitly requesting them 13180 if (!isInstantApp && userState.instantApp) { 13181 return null; 13182 } 13183 // throw out instant application filters if updates are available; will trigger 13184 // instant application resolution 13185 if (userState.instantApp && ps.isUpdateAvailable()) { 13186 return null; 13187 } 13188 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13189 userState, userId); 13190 if (pi == null) { 13191 return null; 13192 } 13193 final ResolveInfo res = new ResolveInfo(); 13194 res.providerInfo = pi; 13195 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13196 res.filter = filter; 13197 } 13198 res.priority = info.getPriority(); 13199 res.preferredOrder = provider.owner.mPreferredOrder; 13200 res.match = match; 13201 res.isDefault = info.hasDefault; 13202 res.labelRes = info.labelRes; 13203 res.nonLocalizedLabel = info.nonLocalizedLabel; 13204 res.icon = info.icon; 13205 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13206 return res; 13207 } 13208 13209 @Override 13210 protected void sortResults(List<ResolveInfo> results) { 13211 Collections.sort(results, mResolvePrioritySorter); 13212 } 13213 13214 @Override 13215 protected void dumpFilter(PrintWriter out, String prefix, 13216 PackageParser.ProviderIntentInfo filter) { 13217 out.print(prefix); 13218 out.print( 13219 Integer.toHexString(System.identityHashCode(filter.provider))); 13220 out.print(' '); 13221 filter.provider.printComponentShortName(out); 13222 out.print(" filter "); 13223 out.println(Integer.toHexString(System.identityHashCode(filter))); 13224 } 13225 13226 @Override 13227 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13228 return filter.provider; 13229 } 13230 13231 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13232 PackageParser.Provider provider = (PackageParser.Provider)label; 13233 out.print(prefix); out.print( 13234 Integer.toHexString(System.identityHashCode(provider))); 13235 out.print(' '); 13236 provider.printComponentShortName(out); 13237 if (count > 1) { 13238 out.print(" ("); out.print(count); out.print(" filters)"); 13239 } 13240 out.println(); 13241 } 13242 13243 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13244 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13245 private int mFlags; 13246 } 13247 13248 static final class InstantAppIntentResolver 13249 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13250 AuxiliaryResolveInfo.AuxiliaryFilter> { 13251 /** 13252 * The result that has the highest defined order. Ordering applies on a 13253 * per-package basis. Mapping is from package name to Pair of order and 13254 * EphemeralResolveInfo. 13255 * <p> 13256 * NOTE: This is implemented as a field variable for convenience and efficiency. 13257 * By having a field variable, we're able to track filter ordering as soon as 13258 * a non-zero order is defined. Otherwise, multiple loops across the result set 13259 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13260 * this needs to be contained entirely within {@link #filterResults}. 13261 */ 13262 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13263 13264 @Override 13265 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13266 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13267 } 13268 13269 @Override 13270 protected boolean isPackageForFilter(String packageName, 13271 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13272 return true; 13273 } 13274 13275 @Override 13276 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13277 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13278 if (!sUserManager.exists(userId)) { 13279 return null; 13280 } 13281 final String packageName = responseObj.resolveInfo.getPackageName(); 13282 final Integer order = responseObj.getOrder(); 13283 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13284 mOrderResult.get(packageName); 13285 // ordering is enabled and this item's order isn't high enough 13286 if (lastOrderResult != null && lastOrderResult.first >= order) { 13287 return null; 13288 } 13289 final InstantAppResolveInfo res = responseObj.resolveInfo; 13290 if (order > 0) { 13291 // non-zero order, enable ordering 13292 mOrderResult.put(packageName, new Pair<>(order, res)); 13293 } 13294 return responseObj; 13295 } 13296 13297 @Override 13298 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13299 // only do work if ordering is enabled [most of the time it won't be] 13300 if (mOrderResult.size() == 0) { 13301 return; 13302 } 13303 int resultSize = results.size(); 13304 for (int i = 0; i < resultSize; i++) { 13305 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13306 final String packageName = info.getPackageName(); 13307 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13308 if (savedInfo == null) { 13309 // package doesn't having ordering 13310 continue; 13311 } 13312 if (savedInfo.second == info) { 13313 // circled back to the highest ordered item; remove from order list 13314 mOrderResult.remove(packageName); 13315 if (mOrderResult.size() == 0) { 13316 // no more ordered items 13317 break; 13318 } 13319 continue; 13320 } 13321 // item has a worse order, remove it from the result list 13322 results.remove(i); 13323 resultSize--; 13324 i--; 13325 } 13326 } 13327 } 13328 13329 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13330 new Comparator<ResolveInfo>() { 13331 public int compare(ResolveInfo r1, ResolveInfo r2) { 13332 int v1 = r1.priority; 13333 int v2 = r2.priority; 13334 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13335 if (v1 != v2) { 13336 return (v1 > v2) ? -1 : 1; 13337 } 13338 v1 = r1.preferredOrder; 13339 v2 = r2.preferredOrder; 13340 if (v1 != v2) { 13341 return (v1 > v2) ? -1 : 1; 13342 } 13343 if (r1.isDefault != r2.isDefault) { 13344 return r1.isDefault ? -1 : 1; 13345 } 13346 v1 = r1.match; 13347 v2 = r2.match; 13348 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13349 if (v1 != v2) { 13350 return (v1 > v2) ? -1 : 1; 13351 } 13352 if (r1.system != r2.system) { 13353 return r1.system ? -1 : 1; 13354 } 13355 if (r1.activityInfo != null) { 13356 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13357 } 13358 if (r1.serviceInfo != null) { 13359 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13360 } 13361 if (r1.providerInfo != null) { 13362 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13363 } 13364 return 0; 13365 } 13366 }; 13367 13368 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13369 new Comparator<ProviderInfo>() { 13370 public int compare(ProviderInfo p1, ProviderInfo p2) { 13371 final int v1 = p1.initOrder; 13372 final int v2 = p2.initOrder; 13373 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13374 } 13375 }; 13376 13377 @Override 13378 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13379 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13380 final int[] userIds, int[] instantUserIds) { 13381 mHandler.post(new Runnable() { 13382 @Override 13383 public void run() { 13384 try { 13385 final IActivityManager am = ActivityManager.getService(); 13386 if (am == null) return; 13387 final int[] resolvedUserIds; 13388 if (userIds == null) { 13389 resolvedUserIds = am.getRunningUserIds(); 13390 } else { 13391 resolvedUserIds = userIds; 13392 } 13393 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13394 resolvedUserIds, false); 13395 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13396 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13397 instantUserIds, true); 13398 } 13399 } catch (RemoteException ex) { 13400 } 13401 } 13402 }); 13403 } 13404 13405 @Override 13406 public void notifyPackageAdded(String packageName) { 13407 final PackageListObserver[] observers; 13408 synchronized (mPackages) { 13409 if (mPackageListObservers.size() == 0) { 13410 return; 13411 } 13412 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13413 } 13414 for (int i = observers.length - 1; i >= 0; --i) { 13415 observers[i].onPackageAdded(packageName); 13416 } 13417 } 13418 13419 @Override 13420 public void notifyPackageRemoved(String packageName) { 13421 final PackageListObserver[] observers; 13422 synchronized (mPackages) { 13423 if (mPackageListObservers.size() == 0) { 13424 return; 13425 } 13426 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13427 } 13428 for (int i = observers.length - 1; i >= 0; --i) { 13429 observers[i].onPackageRemoved(packageName); 13430 } 13431 } 13432 13433 /** 13434 * Sends a broadcast for the given action. 13435 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13436 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13437 * the system and applications allowed to see instant applications to receive package 13438 * lifecycle events for instant applications. 13439 */ 13440 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13441 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13442 int[] userIds, boolean isInstantApp) 13443 throws RemoteException { 13444 for (int id : userIds) { 13445 final Intent intent = new Intent(action, 13446 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13447 final String[] requiredPermissions = 13448 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13449 if (extras != null) { 13450 intent.putExtras(extras); 13451 } 13452 if (targetPkg != null) { 13453 intent.setPackage(targetPkg); 13454 } 13455 // Modify the UID when posting to other users 13456 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13457 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13458 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13459 intent.putExtra(Intent.EXTRA_UID, uid); 13460 } 13461 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13462 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13463 if (DEBUG_BROADCASTS) { 13464 RuntimeException here = new RuntimeException("here"); 13465 here.fillInStackTrace(); 13466 Slog.d(TAG, "Sending to user " + id + ": " 13467 + intent.toShortString(false, true, false, false) 13468 + " " + intent.getExtras(), here); 13469 } 13470 am.broadcastIntent(null, intent, null, finishedReceiver, 13471 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13472 null, finishedReceiver != null, false, id); 13473 } 13474 } 13475 13476 /** 13477 * Check if the external storage media is available. This is true if there 13478 * is a mounted external storage medium or if the external storage is 13479 * emulated. 13480 */ 13481 private boolean isExternalMediaAvailable() { 13482 return mMediaMounted || Environment.isExternalStorageEmulated(); 13483 } 13484 13485 @Override 13486 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13487 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13488 return null; 13489 } 13490 if (!isExternalMediaAvailable()) { 13491 // If the external storage is no longer mounted at this point, 13492 // the caller may not have been able to delete all of this 13493 // packages files and can not delete any more. Bail. 13494 return null; 13495 } 13496 synchronized (mPackages) { 13497 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13498 if (lastPackage != null) { 13499 pkgs.remove(lastPackage); 13500 } 13501 if (pkgs.size() > 0) { 13502 return pkgs.get(0); 13503 } 13504 } 13505 return null; 13506 } 13507 13508 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13509 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13510 userId, andCode ? 1 : 0, packageName); 13511 if (mSystemReady) { 13512 msg.sendToTarget(); 13513 } else { 13514 if (mPostSystemReadyMessages == null) { 13515 mPostSystemReadyMessages = new ArrayList<>(); 13516 } 13517 mPostSystemReadyMessages.add(msg); 13518 } 13519 } 13520 13521 void startCleaningPackages() { 13522 // reader 13523 if (!isExternalMediaAvailable()) { 13524 return; 13525 } 13526 synchronized (mPackages) { 13527 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13528 return; 13529 } 13530 } 13531 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13532 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13533 IActivityManager am = ActivityManager.getService(); 13534 if (am != null) { 13535 int dcsUid = -1; 13536 synchronized (mPackages) { 13537 if (!mDefaultContainerWhitelisted) { 13538 mDefaultContainerWhitelisted = true; 13539 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13540 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13541 } 13542 } 13543 try { 13544 if (dcsUid > 0) { 13545 am.backgroundWhitelistUid(dcsUid); 13546 } 13547 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13548 UserHandle.USER_SYSTEM); 13549 } catch (RemoteException e) { 13550 } 13551 } 13552 } 13553 13554 /** 13555 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13556 * it is acting on behalf on an enterprise or the user). 13557 * 13558 * Note that the ordering of the conditionals in this method is important. The checks we perform 13559 * are as follows, in this order: 13560 * 13561 * 1) If the install is being performed by a system app, we can trust the app to have set the 13562 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13563 * what it is. 13564 * 2) If the install is being performed by a device or profile owner app, the install reason 13565 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13566 * set the install reason correctly. If the app targets an older SDK version where install 13567 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13568 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13569 * 3) In all other cases, the install is being performed by a regular app that is neither part 13570 * of the system nor a device or profile owner. We have no reason to believe that this app is 13571 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13572 * set to enterprise policy and if so, change it to unknown instead. 13573 */ 13574 private int fixUpInstallReason(String installerPackageName, int installerUid, 13575 int installReason) { 13576 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13577 == PERMISSION_GRANTED) { 13578 // If the install is being performed by a system app, we trust that app to have set the 13579 // install reason correctly. 13580 return installReason; 13581 } 13582 13583 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13584 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13585 if (dpm != null) { 13586 ComponentName owner = null; 13587 try { 13588 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13589 if (owner == null) { 13590 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13591 } 13592 } catch (RemoteException e) { 13593 } 13594 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13595 // If the install is being performed by a device or profile owner, the install 13596 // reason should be enterprise policy. 13597 return PackageManager.INSTALL_REASON_POLICY; 13598 } 13599 } 13600 13601 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13602 // If the install is being performed by a regular app (i.e. neither system app nor 13603 // device or profile owner), we have no reason to believe that the app is acting on 13604 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13605 // change it to unknown instead. 13606 return PackageManager.INSTALL_REASON_UNKNOWN; 13607 } 13608 13609 // If the install is being performed by a regular app and the install reason was set to any 13610 // value but enterprise policy, leave the install reason unchanged. 13611 return installReason; 13612 } 13613 13614 void installStage(String packageName, File stagedDir, 13615 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13616 String installerPackageName, int installerUid, UserHandle user, 13617 PackageParser.SigningDetails signingDetails) { 13618 if (DEBUG_INSTANT) { 13619 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13620 Slog.d(TAG, "Ephemeral install of " + packageName); 13621 } 13622 } 13623 final VerificationInfo verificationInfo = new VerificationInfo( 13624 sessionParams.originatingUri, sessionParams.referrerUri, 13625 sessionParams.originatingUid, installerUid); 13626 13627 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13628 13629 final Message msg = mHandler.obtainMessage(INIT_COPY); 13630 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13631 sessionParams.installReason); 13632 final InstallParams params = new InstallParams(origin, null, observer, 13633 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13634 verificationInfo, user, sessionParams.abiOverride, 13635 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13636 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13637 msg.obj = params; 13638 13639 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13640 System.identityHashCode(msg.obj)); 13641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13642 System.identityHashCode(msg.obj)); 13643 13644 mHandler.sendMessage(msg); 13645 } 13646 13647 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13648 int userId) { 13649 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13650 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13651 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13652 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13653 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13654 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13655 13656 // Send a session commit broadcast 13657 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13658 info.installReason = pkgSetting.getInstallReason(userId); 13659 info.appPackageName = packageName; 13660 sendSessionCommitBroadcast(info, userId); 13661 } 13662 13663 @Override 13664 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13665 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13666 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13667 return; 13668 } 13669 Bundle extras = new Bundle(1); 13670 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13671 final int uid = UserHandle.getUid( 13672 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13673 extras.putInt(Intent.EXTRA_UID, uid); 13674 13675 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13676 packageName, extras, 0, null, null, userIds, instantUserIds); 13677 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13678 mHandler.post(() -> { 13679 for (int userId : userIds) { 13680 sendBootCompletedBroadcastToSystemApp( 13681 packageName, includeStopped, userId); 13682 } 13683 } 13684 ); 13685 } 13686 } 13687 13688 /** 13689 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13690 * automatically without needing an explicit launch. 13691 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13692 */ 13693 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13694 int userId) { 13695 // If user is not running, the app didn't miss any broadcast 13696 if (!mUserManagerInternal.isUserRunning(userId)) { 13697 return; 13698 } 13699 final IActivityManager am = ActivityManager.getService(); 13700 try { 13701 // Deliver LOCKED_BOOT_COMPLETED first 13702 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13703 .setPackage(packageName); 13704 if (includeStopped) { 13705 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13706 } 13707 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13708 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13709 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13710 13711 // Deliver BOOT_COMPLETED only if user is unlocked 13712 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13713 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13714 if (includeStopped) { 13715 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13716 } 13717 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13718 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13719 } 13720 } catch (RemoteException e) { 13721 throw e.rethrowFromSystemServer(); 13722 } 13723 } 13724 13725 @Override 13726 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13727 int userId) { 13728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13729 PackageSetting pkgSetting; 13730 final int callingUid = Binder.getCallingUid(); 13731 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13732 true /* requireFullPermission */, true /* checkShell */, 13733 "setApplicationHiddenSetting for user " + userId); 13734 13735 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13736 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13737 return false; 13738 } 13739 13740 long callingId = Binder.clearCallingIdentity(); 13741 try { 13742 boolean sendAdded = false; 13743 boolean sendRemoved = false; 13744 // writer 13745 synchronized (mPackages) { 13746 pkgSetting = mSettings.mPackages.get(packageName); 13747 if (pkgSetting == null) { 13748 return false; 13749 } 13750 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13751 return false; 13752 } 13753 // Do not allow "android" is being disabled 13754 if ("android".equals(packageName)) { 13755 Slog.w(TAG, "Cannot hide package: android"); 13756 return false; 13757 } 13758 // Cannot hide static shared libs as they are considered 13759 // a part of the using app (emulating static linking). Also 13760 // static libs are installed always on internal storage. 13761 PackageParser.Package pkg = mPackages.get(packageName); 13762 if (pkg != null && pkg.staticSharedLibName != null) { 13763 Slog.w(TAG, "Cannot hide package: " + packageName 13764 + " providing static shared library: " 13765 + pkg.staticSharedLibName); 13766 return false; 13767 } 13768 // Only allow protected packages to hide themselves. 13769 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13770 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13771 Slog.w(TAG, "Not hiding protected package: " + packageName); 13772 return false; 13773 } 13774 13775 if (pkgSetting.getHidden(userId) != hidden) { 13776 pkgSetting.setHidden(hidden, userId); 13777 mSettings.writePackageRestrictionsLPr(userId); 13778 if (hidden) { 13779 sendRemoved = true; 13780 } else { 13781 sendAdded = true; 13782 } 13783 } 13784 } 13785 if (sendAdded) { 13786 sendPackageAddedForUser(packageName, pkgSetting, userId); 13787 return true; 13788 } 13789 if (sendRemoved) { 13790 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13791 "hiding pkg"); 13792 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13793 return true; 13794 } 13795 } finally { 13796 Binder.restoreCallingIdentity(callingId); 13797 } 13798 return false; 13799 } 13800 13801 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13802 int userId) { 13803 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13804 info.removedPackage = packageName; 13805 info.installerPackageName = pkgSetting.installerPackageName; 13806 info.removedUsers = new int[] {userId}; 13807 info.broadcastUsers = new int[] {userId}; 13808 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13809 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13810 } 13811 13812 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13813 if (pkgList.length > 0) { 13814 Bundle extras = new Bundle(1); 13815 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13816 13817 sendPackageBroadcast( 13818 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13819 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13820 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13821 new int[] {userId}, null); 13822 } 13823 } 13824 13825 /** 13826 * Returns true if application is not found or there was an error. Otherwise it returns 13827 * the hidden state of the package for the given user. 13828 */ 13829 @Override 13830 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13831 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13832 final int callingUid = Binder.getCallingUid(); 13833 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13834 true /* requireFullPermission */, false /* checkShell */, 13835 "getApplicationHidden for user " + userId); 13836 PackageSetting ps; 13837 long callingId = Binder.clearCallingIdentity(); 13838 try { 13839 // writer 13840 synchronized (mPackages) { 13841 ps = mSettings.mPackages.get(packageName); 13842 if (ps == null) { 13843 return true; 13844 } 13845 if (filterAppAccessLPr(ps, callingUid, userId)) { 13846 return true; 13847 } 13848 return ps.getHidden(userId); 13849 } 13850 } finally { 13851 Binder.restoreCallingIdentity(callingId); 13852 } 13853 } 13854 13855 /** 13856 * @hide 13857 */ 13858 @Override 13859 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13860 int installReason) { 13861 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13862 null); 13863 PackageSetting pkgSetting; 13864 final int callingUid = Binder.getCallingUid(); 13865 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13866 true /* requireFullPermission */, true /* checkShell */, 13867 "installExistingPackage for user " + userId); 13868 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13869 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13870 } 13871 13872 long callingId = Binder.clearCallingIdentity(); 13873 try { 13874 boolean installed = false; 13875 final boolean instantApp = 13876 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13877 final boolean fullApp = 13878 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13879 13880 // writer 13881 synchronized (mPackages) { 13882 pkgSetting = mSettings.mPackages.get(packageName); 13883 if (pkgSetting == null) { 13884 return PackageManager.INSTALL_FAILED_INVALID_URI; 13885 } 13886 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13887 // only allow the existing package to be used if it's installed as a full 13888 // application for at least one user 13889 boolean installAllowed = false; 13890 for (int checkUserId : sUserManager.getUserIds()) { 13891 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13892 if (installAllowed) { 13893 break; 13894 } 13895 } 13896 if (!installAllowed) { 13897 return PackageManager.INSTALL_FAILED_INVALID_URI; 13898 } 13899 } 13900 if (!pkgSetting.getInstalled(userId)) { 13901 pkgSetting.setInstalled(true, userId); 13902 pkgSetting.setHidden(false, userId); 13903 pkgSetting.setInstallReason(installReason, userId); 13904 mSettings.writePackageRestrictionsLPr(userId); 13905 mSettings.writeKernelMappingLPr(pkgSetting); 13906 installed = true; 13907 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13908 // upgrade app from instant to full; we don't allow app downgrade 13909 installed = true; 13910 } 13911 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13912 } 13913 13914 if (installed) { 13915 if (pkgSetting.pkg != null) { 13916 synchronized (mInstallLock) { 13917 // We don't need to freeze for a brand new install 13918 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13919 } 13920 } 13921 sendPackageAddedForUser(packageName, pkgSetting, userId); 13922 synchronized (mPackages) { 13923 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13924 } 13925 } 13926 } finally { 13927 Binder.restoreCallingIdentity(callingId); 13928 } 13929 13930 return PackageManager.INSTALL_SUCCEEDED; 13931 } 13932 13933 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13934 boolean instantApp, boolean fullApp) { 13935 // no state specified; do nothing 13936 if (!instantApp && !fullApp) { 13937 return; 13938 } 13939 if (userId != UserHandle.USER_ALL) { 13940 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13941 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13942 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13943 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13944 } 13945 } else { 13946 for (int currentUserId : sUserManager.getUserIds()) { 13947 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13948 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13949 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13950 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13951 } 13952 } 13953 } 13954 } 13955 13956 boolean isUserRestricted(int userId, String restrictionKey) { 13957 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13958 if (restrictions.getBoolean(restrictionKey, false)) { 13959 Log.w(TAG, "User is restricted: " + restrictionKey); 13960 return true; 13961 } 13962 return false; 13963 } 13964 13965 @Override 13966 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13967 int userId) { 13968 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13969 final int callingUid = Binder.getCallingUid(); 13970 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13971 true /* requireFullPermission */, true /* checkShell */, 13972 "setPackagesSuspended for user " + userId); 13973 13974 if (ArrayUtils.isEmpty(packageNames)) { 13975 return packageNames; 13976 } 13977 13978 // List of package names for whom the suspended state has changed. 13979 List<String> changedPackages = new ArrayList<>(packageNames.length); 13980 // List of package names for whom the suspended state is not set as requested in this 13981 // method. 13982 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13983 long callingId = Binder.clearCallingIdentity(); 13984 try { 13985 for (int i = 0; i < packageNames.length; i++) { 13986 String packageName = packageNames[i]; 13987 boolean changed = false; 13988 final int appId; 13989 synchronized (mPackages) { 13990 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13991 if (pkgSetting == null 13992 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13993 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13994 + "\". Skipping suspending/un-suspending."); 13995 unactionedPackages.add(packageName); 13996 continue; 13997 } 13998 appId = pkgSetting.appId; 13999 if (pkgSetting.getSuspended(userId) != suspended) { 14000 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14001 unactionedPackages.add(packageName); 14002 continue; 14003 } 14004 pkgSetting.setSuspended(suspended, userId); 14005 mSettings.writePackageRestrictionsLPr(userId); 14006 changed = true; 14007 changedPackages.add(packageName); 14008 } 14009 } 14010 14011 if (changed && suspended) { 14012 killApplication(packageName, UserHandle.getUid(userId, appId), 14013 "suspending package"); 14014 } 14015 } 14016 } finally { 14017 Binder.restoreCallingIdentity(callingId); 14018 } 14019 14020 if (!changedPackages.isEmpty()) { 14021 sendPackagesSuspendedForUser(changedPackages.toArray( 14022 new String[changedPackages.size()]), userId, suspended); 14023 } 14024 14025 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14026 } 14027 14028 @Override 14029 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14030 final int callingUid = Binder.getCallingUid(); 14031 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14032 true /* requireFullPermission */, false /* checkShell */, 14033 "isPackageSuspendedForUser for user " + userId); 14034 synchronized (mPackages) { 14035 final PackageSetting ps = mSettings.mPackages.get(packageName); 14036 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14037 throw new IllegalArgumentException("Unknown target package: " + packageName); 14038 } 14039 return ps.getSuspended(userId); 14040 } 14041 } 14042 14043 @GuardedBy("mPackages") 14044 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14045 if (isPackageDeviceAdmin(packageName, userId)) { 14046 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14047 + "\": has an active device admin"); 14048 return false; 14049 } 14050 14051 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14052 if (packageName.equals(activeLauncherPackageName)) { 14053 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14054 + "\": contains the active launcher"); 14055 return false; 14056 } 14057 14058 if (packageName.equals(mRequiredInstallerPackage)) { 14059 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14060 + "\": required for package installation"); 14061 return false; 14062 } 14063 14064 if (packageName.equals(mRequiredUninstallerPackage)) { 14065 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14066 + "\": required for package uninstallation"); 14067 return false; 14068 } 14069 14070 if (packageName.equals(mRequiredVerifierPackage)) { 14071 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14072 + "\": required for package verification"); 14073 return false; 14074 } 14075 14076 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14077 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14078 + "\": is the default dialer"); 14079 return false; 14080 } 14081 14082 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14083 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14084 + "\": protected package"); 14085 return false; 14086 } 14087 14088 // Cannot suspend static shared libs as they are considered 14089 // a part of the using app (emulating static linking). Also 14090 // static libs are installed always on internal storage. 14091 PackageParser.Package pkg = mPackages.get(packageName); 14092 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14093 Slog.w(TAG, "Cannot suspend package: " + packageName 14094 + " providing static shared library: " 14095 + pkg.staticSharedLibName); 14096 return false; 14097 } 14098 14099 return true; 14100 } 14101 14102 private String getActiveLauncherPackageName(int userId) { 14103 Intent intent = new Intent(Intent.ACTION_MAIN); 14104 intent.addCategory(Intent.CATEGORY_HOME); 14105 ResolveInfo resolveInfo = resolveIntent( 14106 intent, 14107 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14108 PackageManager.MATCH_DEFAULT_ONLY, 14109 userId); 14110 14111 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14112 } 14113 14114 private String getDefaultDialerPackageName(int userId) { 14115 synchronized (mPackages) { 14116 return mSettings.getDefaultDialerPackageNameLPw(userId); 14117 } 14118 } 14119 14120 @Override 14121 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14122 mContext.enforceCallingOrSelfPermission( 14123 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14124 "Only package verification agents can verify applications"); 14125 14126 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14127 final PackageVerificationResponse response = new PackageVerificationResponse( 14128 verificationCode, Binder.getCallingUid()); 14129 msg.arg1 = id; 14130 msg.obj = response; 14131 mHandler.sendMessage(msg); 14132 } 14133 14134 @Override 14135 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14136 long millisecondsToDelay) { 14137 mContext.enforceCallingOrSelfPermission( 14138 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14139 "Only package verification agents can extend verification timeouts"); 14140 14141 final PackageVerificationState state = mPendingVerification.get(id); 14142 final PackageVerificationResponse response = new PackageVerificationResponse( 14143 verificationCodeAtTimeout, Binder.getCallingUid()); 14144 14145 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14146 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14147 } 14148 if (millisecondsToDelay < 0) { 14149 millisecondsToDelay = 0; 14150 } 14151 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14152 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14153 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14154 } 14155 14156 if ((state != null) && !state.timeoutExtended()) { 14157 state.extendTimeout(); 14158 14159 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14160 msg.arg1 = id; 14161 msg.obj = response; 14162 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14163 } 14164 } 14165 14166 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14167 int verificationCode, UserHandle user) { 14168 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14169 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14170 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14171 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14172 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14173 14174 mContext.sendBroadcastAsUser(intent, user, 14175 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14176 } 14177 14178 private ComponentName matchComponentForVerifier(String packageName, 14179 List<ResolveInfo> receivers) { 14180 ActivityInfo targetReceiver = null; 14181 14182 final int NR = receivers.size(); 14183 for (int i = 0; i < NR; i++) { 14184 final ResolveInfo info = receivers.get(i); 14185 if (info.activityInfo == null) { 14186 continue; 14187 } 14188 14189 if (packageName.equals(info.activityInfo.packageName)) { 14190 targetReceiver = info.activityInfo; 14191 break; 14192 } 14193 } 14194 14195 if (targetReceiver == null) { 14196 return null; 14197 } 14198 14199 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14200 } 14201 14202 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14203 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14204 if (pkgInfo.verifiers.length == 0) { 14205 return null; 14206 } 14207 14208 final int N = pkgInfo.verifiers.length; 14209 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14210 for (int i = 0; i < N; i++) { 14211 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14212 14213 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14214 receivers); 14215 if (comp == null) { 14216 continue; 14217 } 14218 14219 final int verifierUid = getUidForVerifier(verifierInfo); 14220 if (verifierUid == -1) { 14221 continue; 14222 } 14223 14224 if (DEBUG_VERIFY) { 14225 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14226 + " with the correct signature"); 14227 } 14228 sufficientVerifiers.add(comp); 14229 verificationState.addSufficientVerifier(verifierUid); 14230 } 14231 14232 return sufficientVerifiers; 14233 } 14234 14235 private int getUidForVerifier(VerifierInfo verifierInfo) { 14236 synchronized (mPackages) { 14237 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14238 if (pkg == null) { 14239 return -1; 14240 } else if (pkg.mSigningDetails.signatures.length != 1) { 14241 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14242 + " has more than one signature; ignoring"); 14243 return -1; 14244 } 14245 14246 /* 14247 * If the public key of the package's signature does not match 14248 * our expected public key, then this is a different package and 14249 * we should skip. 14250 */ 14251 14252 final byte[] expectedPublicKey; 14253 try { 14254 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14255 final PublicKey publicKey = verifierSig.getPublicKey(); 14256 expectedPublicKey = publicKey.getEncoded(); 14257 } catch (CertificateException e) { 14258 return -1; 14259 } 14260 14261 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14262 14263 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14264 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14265 + " does not have the expected public key; ignoring"); 14266 return -1; 14267 } 14268 14269 return pkg.applicationInfo.uid; 14270 } 14271 } 14272 14273 @Override 14274 public void finishPackageInstall(int token, boolean didLaunch) { 14275 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14276 14277 if (DEBUG_INSTALL) { 14278 Slog.v(TAG, "BM finishing package install for " + token); 14279 } 14280 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14281 14282 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14283 mHandler.sendMessage(msg); 14284 } 14285 14286 /** 14287 * Get the verification agent timeout. Used for both the APK verifier and the 14288 * intent filter verifier. 14289 * 14290 * @return verification timeout in milliseconds 14291 */ 14292 private long getVerificationTimeout() { 14293 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14294 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14295 DEFAULT_VERIFICATION_TIMEOUT); 14296 } 14297 14298 /** 14299 * Get the default verification agent response code. 14300 * 14301 * @return default verification response code 14302 */ 14303 private int getDefaultVerificationResponse(UserHandle user) { 14304 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14305 return PackageManager.VERIFICATION_REJECT; 14306 } 14307 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14308 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14309 DEFAULT_VERIFICATION_RESPONSE); 14310 } 14311 14312 /** 14313 * Check whether or not package verification has been enabled. 14314 * 14315 * @return true if verification should be performed 14316 */ 14317 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14318 if (!DEFAULT_VERIFY_ENABLE) { 14319 return false; 14320 } 14321 14322 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14323 14324 // Check if installing from ADB 14325 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14326 // Do not run verification in a test harness environment 14327 if (ActivityManager.isRunningInTestHarness()) { 14328 return false; 14329 } 14330 if (ensureVerifyAppsEnabled) { 14331 return true; 14332 } 14333 // Check if the developer does not want package verification for ADB installs 14334 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14335 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14336 return false; 14337 } 14338 } else { 14339 // only when not installed from ADB, skip verification for instant apps when 14340 // the installer and verifier are the same. 14341 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14342 if (mInstantAppInstallerActivity != null 14343 && mInstantAppInstallerActivity.packageName.equals( 14344 mRequiredVerifierPackage)) { 14345 try { 14346 mContext.getSystemService(AppOpsManager.class) 14347 .checkPackage(installerUid, mRequiredVerifierPackage); 14348 if (DEBUG_VERIFY) { 14349 Slog.i(TAG, "disable verification for instant app"); 14350 } 14351 return false; 14352 } catch (SecurityException ignore) { } 14353 } 14354 } 14355 } 14356 14357 if (ensureVerifyAppsEnabled) { 14358 return true; 14359 } 14360 14361 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14362 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14363 } 14364 14365 @Override 14366 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14367 throws RemoteException { 14368 mContext.enforceCallingOrSelfPermission( 14369 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14370 "Only intentfilter verification agents can verify applications"); 14371 14372 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14373 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14374 Binder.getCallingUid(), verificationCode, failedDomains); 14375 msg.arg1 = id; 14376 msg.obj = response; 14377 mHandler.sendMessage(msg); 14378 } 14379 14380 @Override 14381 public int getIntentVerificationStatus(String packageName, int userId) { 14382 final int callingUid = Binder.getCallingUid(); 14383 if (UserHandle.getUserId(callingUid) != userId) { 14384 mContext.enforceCallingOrSelfPermission( 14385 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14386 "getIntentVerificationStatus" + userId); 14387 } 14388 if (getInstantAppPackageName(callingUid) != null) { 14389 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14390 } 14391 synchronized (mPackages) { 14392 final PackageSetting ps = mSettings.mPackages.get(packageName); 14393 if (ps == null 14394 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14395 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14396 } 14397 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14398 } 14399 } 14400 14401 @Override 14402 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14403 mContext.enforceCallingOrSelfPermission( 14404 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14405 14406 boolean result = false; 14407 synchronized (mPackages) { 14408 final PackageSetting ps = mSettings.mPackages.get(packageName); 14409 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14410 return false; 14411 } 14412 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14413 } 14414 if (result) { 14415 scheduleWritePackageRestrictionsLocked(userId); 14416 } 14417 return result; 14418 } 14419 14420 @Override 14421 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14422 String packageName) { 14423 final int callingUid = Binder.getCallingUid(); 14424 if (getInstantAppPackageName(callingUid) != null) { 14425 return ParceledListSlice.emptyList(); 14426 } 14427 synchronized (mPackages) { 14428 final PackageSetting ps = mSettings.mPackages.get(packageName); 14429 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14430 return ParceledListSlice.emptyList(); 14431 } 14432 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14433 } 14434 } 14435 14436 @Override 14437 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14438 if (TextUtils.isEmpty(packageName)) { 14439 return ParceledListSlice.emptyList(); 14440 } 14441 final int callingUid = Binder.getCallingUid(); 14442 final int callingUserId = UserHandle.getUserId(callingUid); 14443 synchronized (mPackages) { 14444 PackageParser.Package pkg = mPackages.get(packageName); 14445 if (pkg == null || pkg.activities == null) { 14446 return ParceledListSlice.emptyList(); 14447 } 14448 if (pkg.mExtras == null) { 14449 return ParceledListSlice.emptyList(); 14450 } 14451 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14452 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14453 return ParceledListSlice.emptyList(); 14454 } 14455 final int count = pkg.activities.size(); 14456 ArrayList<IntentFilter> result = new ArrayList<>(); 14457 for (int n=0; n<count; n++) { 14458 PackageParser.Activity activity = pkg.activities.get(n); 14459 if (activity.intents != null && activity.intents.size() > 0) { 14460 result.addAll(activity.intents); 14461 } 14462 } 14463 return new ParceledListSlice<>(result); 14464 } 14465 } 14466 14467 @Override 14468 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14469 mContext.enforceCallingOrSelfPermission( 14470 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14471 if (UserHandle.getCallingUserId() != userId) { 14472 mContext.enforceCallingOrSelfPermission( 14473 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14474 } 14475 14476 synchronized (mPackages) { 14477 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14478 if (packageName != null) { 14479 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14480 packageName, userId); 14481 } 14482 return result; 14483 } 14484 } 14485 14486 @Override 14487 public String getDefaultBrowserPackageName(int userId) { 14488 if (UserHandle.getCallingUserId() != userId) { 14489 mContext.enforceCallingOrSelfPermission( 14490 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14491 } 14492 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14493 return null; 14494 } 14495 synchronized (mPackages) { 14496 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14497 } 14498 } 14499 14500 /** 14501 * Get the "allow unknown sources" setting. 14502 * 14503 * @return the current "allow unknown sources" setting 14504 */ 14505 private int getUnknownSourcesSettings() { 14506 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14507 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14508 -1); 14509 } 14510 14511 @Override 14512 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14513 final int callingUid = Binder.getCallingUid(); 14514 if (getInstantAppPackageName(callingUid) != null) { 14515 return; 14516 } 14517 // writer 14518 synchronized (mPackages) { 14519 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14520 if (targetPackageSetting == null 14521 || filterAppAccessLPr( 14522 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14523 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14524 } 14525 14526 PackageSetting installerPackageSetting; 14527 if (installerPackageName != null) { 14528 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14529 if (installerPackageSetting == null) { 14530 throw new IllegalArgumentException("Unknown installer package: " 14531 + installerPackageName); 14532 } 14533 } else { 14534 installerPackageSetting = null; 14535 } 14536 14537 Signature[] callerSignature; 14538 Object obj = mSettings.getUserIdLPr(callingUid); 14539 if (obj != null) { 14540 if (obj instanceof SharedUserSetting) { 14541 callerSignature = 14542 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14543 } else if (obj instanceof PackageSetting) { 14544 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14545 } else { 14546 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14547 } 14548 } else { 14549 throw new SecurityException("Unknown calling UID: " + callingUid); 14550 } 14551 14552 // Verify: can't set installerPackageName to a package that is 14553 // not signed with the same cert as the caller. 14554 if (installerPackageSetting != null) { 14555 if (compareSignatures(callerSignature, 14556 installerPackageSetting.signatures.mSigningDetails.signatures) 14557 != PackageManager.SIGNATURE_MATCH) { 14558 throw new SecurityException( 14559 "Caller does not have same cert as new installer package " 14560 + installerPackageName); 14561 } 14562 } 14563 14564 // Verify: if target already has an installer package, it must 14565 // be signed with the same cert as the caller. 14566 if (targetPackageSetting.installerPackageName != null) { 14567 PackageSetting setting = mSettings.mPackages.get( 14568 targetPackageSetting.installerPackageName); 14569 // If the currently set package isn't valid, then it's always 14570 // okay to change it. 14571 if (setting != null) { 14572 if (compareSignatures(callerSignature, 14573 setting.signatures.mSigningDetails.signatures) 14574 != PackageManager.SIGNATURE_MATCH) { 14575 throw new SecurityException( 14576 "Caller does not have same cert as old installer package " 14577 + targetPackageSetting.installerPackageName); 14578 } 14579 } 14580 } 14581 14582 // Okay! 14583 targetPackageSetting.installerPackageName = installerPackageName; 14584 if (installerPackageName != null) { 14585 mSettings.mInstallerPackages.add(installerPackageName); 14586 } 14587 scheduleWriteSettingsLocked(); 14588 } 14589 } 14590 14591 @Override 14592 public void setApplicationCategoryHint(String packageName, int categoryHint, 14593 String callerPackageName) { 14594 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14595 throw new SecurityException("Instant applications don't have access to this method"); 14596 } 14597 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14598 callerPackageName); 14599 synchronized (mPackages) { 14600 PackageSetting ps = mSettings.mPackages.get(packageName); 14601 if (ps == null) { 14602 throw new IllegalArgumentException("Unknown target package " + packageName); 14603 } 14604 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14605 throw new IllegalArgumentException("Unknown target package " + packageName); 14606 } 14607 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14608 throw new IllegalArgumentException("Calling package " + callerPackageName 14609 + " is not installer for " + packageName); 14610 } 14611 14612 if (ps.categoryHint != categoryHint) { 14613 ps.categoryHint = categoryHint; 14614 scheduleWriteSettingsLocked(); 14615 } 14616 } 14617 } 14618 14619 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14620 // Queue up an async operation since the package installation may take a little while. 14621 mHandler.post(new Runnable() { 14622 public void run() { 14623 mHandler.removeCallbacks(this); 14624 // Result object to be returned 14625 PackageInstalledInfo res = new PackageInstalledInfo(); 14626 res.setReturnCode(currentStatus); 14627 res.uid = -1; 14628 res.pkg = null; 14629 res.removedInfo = null; 14630 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14631 args.doPreInstall(res.returnCode); 14632 synchronized (mInstallLock) { 14633 installPackageTracedLI(args, res); 14634 } 14635 args.doPostInstall(res.returnCode, res.uid); 14636 } 14637 14638 // A restore should be performed at this point if (a) the install 14639 // succeeded, (b) the operation is not an update, and (c) the new 14640 // package has not opted out of backup participation. 14641 final boolean update = res.removedInfo != null 14642 && res.removedInfo.removedPackage != null; 14643 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14644 boolean doRestore = !update 14645 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14646 14647 // Set up the post-install work request bookkeeping. This will be used 14648 // and cleaned up by the post-install event handling regardless of whether 14649 // there's a restore pass performed. Token values are >= 1. 14650 int token; 14651 if (mNextInstallToken < 0) mNextInstallToken = 1; 14652 token = mNextInstallToken++; 14653 14654 PostInstallData data = new PostInstallData(args, res); 14655 mRunningInstalls.put(token, data); 14656 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14657 14658 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14659 // Pass responsibility to the Backup Manager. It will perform a 14660 // restore if appropriate, then pass responsibility back to the 14661 // Package Manager to run the post-install observer callbacks 14662 // and broadcasts. 14663 IBackupManager bm = IBackupManager.Stub.asInterface( 14664 ServiceManager.getService(Context.BACKUP_SERVICE)); 14665 if (bm != null) { 14666 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14667 + " to BM for possible restore"); 14668 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14669 try { 14670 // TODO: http://b/22388012 14671 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14672 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14673 } else { 14674 doRestore = false; 14675 } 14676 } catch (RemoteException e) { 14677 // can't happen; the backup manager is local 14678 } catch (Exception e) { 14679 Slog.e(TAG, "Exception trying to enqueue restore", e); 14680 doRestore = false; 14681 } 14682 } else { 14683 Slog.e(TAG, "Backup Manager not found!"); 14684 doRestore = false; 14685 } 14686 } 14687 14688 if (!doRestore) { 14689 // No restore possible, or the Backup Manager was mysteriously not 14690 // available -- just fire the post-install work request directly. 14691 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14692 14693 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14694 14695 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14696 mHandler.sendMessage(msg); 14697 } 14698 } 14699 }); 14700 } 14701 14702 /** 14703 * Callback from PackageSettings whenever an app is first transitioned out of the 14704 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14705 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14706 * here whether the app is the target of an ongoing install, and only send the 14707 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14708 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14709 * handling. 14710 */ 14711 void notifyFirstLaunch(final String packageName, final String installerPackage, 14712 final int userId) { 14713 // Serialize this with the rest of the install-process message chain. In the 14714 // restore-at-install case, this Runnable will necessarily run before the 14715 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14716 // are coherent. In the non-restore case, the app has already completed install 14717 // and been launched through some other means, so it is not in a problematic 14718 // state for observers to see the FIRST_LAUNCH signal. 14719 mHandler.post(new Runnable() { 14720 @Override 14721 public void run() { 14722 for (int i = 0; i < mRunningInstalls.size(); i++) { 14723 final PostInstallData data = mRunningInstalls.valueAt(i); 14724 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14725 continue; 14726 } 14727 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14728 // right package; but is it for the right user? 14729 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14730 if (userId == data.res.newUsers[uIndex]) { 14731 if (DEBUG_BACKUP) { 14732 Slog.i(TAG, "Package " + packageName 14733 + " being restored so deferring FIRST_LAUNCH"); 14734 } 14735 return; 14736 } 14737 } 14738 } 14739 } 14740 // didn't find it, so not being restored 14741 if (DEBUG_BACKUP) { 14742 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14743 } 14744 final boolean isInstantApp = isInstantApp(packageName, userId); 14745 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14746 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14747 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14748 } 14749 }); 14750 } 14751 14752 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14753 int[] userIds, int[] instantUserIds) { 14754 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14755 installerPkg, null, userIds, instantUserIds); 14756 } 14757 14758 private abstract class HandlerParams { 14759 private static final int MAX_RETRIES = 4; 14760 14761 /** 14762 * Number of times startCopy() has been attempted and had a non-fatal 14763 * error. 14764 */ 14765 private int mRetries = 0; 14766 14767 /** User handle for the user requesting the information or installation. */ 14768 private final UserHandle mUser; 14769 String traceMethod; 14770 int traceCookie; 14771 14772 HandlerParams(UserHandle user) { 14773 mUser = user; 14774 } 14775 14776 UserHandle getUser() { 14777 return mUser; 14778 } 14779 14780 HandlerParams setTraceMethod(String traceMethod) { 14781 this.traceMethod = traceMethod; 14782 return this; 14783 } 14784 14785 HandlerParams setTraceCookie(int traceCookie) { 14786 this.traceCookie = traceCookie; 14787 return this; 14788 } 14789 14790 final boolean startCopy() { 14791 boolean res; 14792 try { 14793 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14794 14795 if (++mRetries > MAX_RETRIES) { 14796 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14797 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14798 handleServiceError(); 14799 return false; 14800 } else { 14801 handleStartCopy(); 14802 res = true; 14803 } 14804 } catch (RemoteException e) { 14805 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14806 mHandler.sendEmptyMessage(MCS_RECONNECT); 14807 res = false; 14808 } 14809 handleReturnCode(); 14810 return res; 14811 } 14812 14813 final void serviceError() { 14814 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14815 handleServiceError(); 14816 handleReturnCode(); 14817 } 14818 14819 abstract void handleStartCopy() throws RemoteException; 14820 abstract void handleServiceError(); 14821 abstract void handleReturnCode(); 14822 } 14823 14824 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14825 for (File path : paths) { 14826 try { 14827 mcs.clearDirectory(path.getAbsolutePath()); 14828 } catch (RemoteException e) { 14829 } 14830 } 14831 } 14832 14833 static class OriginInfo { 14834 /** 14835 * Location where install is coming from, before it has been 14836 * copied/renamed into place. This could be a single monolithic APK 14837 * file, or a cluster directory. This location may be untrusted. 14838 */ 14839 final File file; 14840 14841 /** 14842 * Flag indicating that {@link #file} or {@link #cid} has already been 14843 * staged, meaning downstream users don't need to defensively copy the 14844 * contents. 14845 */ 14846 final boolean staged; 14847 14848 /** 14849 * Flag indicating that {@link #file} or {@link #cid} is an already 14850 * installed app that is being moved. 14851 */ 14852 final boolean existing; 14853 14854 final String resolvedPath; 14855 final File resolvedFile; 14856 14857 static OriginInfo fromNothing() { 14858 return new OriginInfo(null, false, false); 14859 } 14860 14861 static OriginInfo fromUntrustedFile(File file) { 14862 return new OriginInfo(file, false, false); 14863 } 14864 14865 static OriginInfo fromExistingFile(File file) { 14866 return new OriginInfo(file, false, true); 14867 } 14868 14869 static OriginInfo fromStagedFile(File file) { 14870 return new OriginInfo(file, true, false); 14871 } 14872 14873 private OriginInfo(File file, boolean staged, boolean existing) { 14874 this.file = file; 14875 this.staged = staged; 14876 this.existing = existing; 14877 14878 if (file != null) { 14879 resolvedPath = file.getAbsolutePath(); 14880 resolvedFile = file; 14881 } else { 14882 resolvedPath = null; 14883 resolvedFile = null; 14884 } 14885 } 14886 } 14887 14888 static class MoveInfo { 14889 final int moveId; 14890 final String fromUuid; 14891 final String toUuid; 14892 final String packageName; 14893 final String dataAppName; 14894 final int appId; 14895 final String seinfo; 14896 final int targetSdkVersion; 14897 14898 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14899 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14900 this.moveId = moveId; 14901 this.fromUuid = fromUuid; 14902 this.toUuid = toUuid; 14903 this.packageName = packageName; 14904 this.dataAppName = dataAppName; 14905 this.appId = appId; 14906 this.seinfo = seinfo; 14907 this.targetSdkVersion = targetSdkVersion; 14908 } 14909 } 14910 14911 static class VerificationInfo { 14912 /** A constant used to indicate that a uid value is not present. */ 14913 public static final int NO_UID = -1; 14914 14915 /** URI referencing where the package was downloaded from. */ 14916 final Uri originatingUri; 14917 14918 /** HTTP referrer URI associated with the originatingURI. */ 14919 final Uri referrer; 14920 14921 /** UID of the application that the install request originated from. */ 14922 final int originatingUid; 14923 14924 /** UID of application requesting the install */ 14925 final int installerUid; 14926 14927 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14928 this.originatingUri = originatingUri; 14929 this.referrer = referrer; 14930 this.originatingUid = originatingUid; 14931 this.installerUid = installerUid; 14932 } 14933 } 14934 14935 class InstallParams extends HandlerParams { 14936 final OriginInfo origin; 14937 final MoveInfo move; 14938 final IPackageInstallObserver2 observer; 14939 int installFlags; 14940 final String installerPackageName; 14941 final String volumeUuid; 14942 private InstallArgs mArgs; 14943 private int mRet; 14944 final String packageAbiOverride; 14945 final String[] grantedRuntimePermissions; 14946 final VerificationInfo verificationInfo; 14947 final PackageParser.SigningDetails signingDetails; 14948 final int installReason; 14949 14950 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14951 int installFlags, String installerPackageName, String volumeUuid, 14952 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14953 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14954 super(user); 14955 this.origin = origin; 14956 this.move = move; 14957 this.observer = observer; 14958 this.installFlags = installFlags; 14959 this.installerPackageName = installerPackageName; 14960 this.volumeUuid = volumeUuid; 14961 this.verificationInfo = verificationInfo; 14962 this.packageAbiOverride = packageAbiOverride; 14963 this.grantedRuntimePermissions = grantedPermissions; 14964 this.signingDetails = signingDetails; 14965 this.installReason = installReason; 14966 } 14967 14968 @Override 14969 public String toString() { 14970 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14971 + " file=" + origin.file + "}"; 14972 } 14973 14974 private int installLocationPolicy(PackageInfoLite pkgLite) { 14975 String packageName = pkgLite.packageName; 14976 int installLocation = pkgLite.installLocation; 14977 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14978 // reader 14979 synchronized (mPackages) { 14980 // Currently installed package which the new package is attempting to replace or 14981 // null if no such package is installed. 14982 PackageParser.Package installedPkg = mPackages.get(packageName); 14983 // Package which currently owns the data which the new package will own if installed. 14984 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14985 // will be null whereas dataOwnerPkg will contain information about the package 14986 // which was uninstalled while keeping its data. 14987 PackageParser.Package dataOwnerPkg = installedPkg; 14988 if (dataOwnerPkg == null) { 14989 PackageSetting ps = mSettings.mPackages.get(packageName); 14990 if (ps != null) { 14991 dataOwnerPkg = ps.pkg; 14992 } 14993 } 14994 14995 if (dataOwnerPkg != null) { 14996 // If installed, the package will get access to data left on the device by its 14997 // predecessor. As a security measure, this is permited only if this is not a 14998 // version downgrade or if the predecessor package is marked as debuggable and 14999 // a downgrade is explicitly requested. 15000 // 15001 // On debuggable platform builds, downgrades are permitted even for 15002 // non-debuggable packages to make testing easier. Debuggable platform builds do 15003 // not offer security guarantees and thus it's OK to disable some security 15004 // mechanisms to make debugging/testing easier on those builds. However, even on 15005 // debuggable builds downgrades of packages are permitted only if requested via 15006 // installFlags. This is because we aim to keep the behavior of debuggable 15007 // platform builds as close as possible to the behavior of non-debuggable 15008 // platform builds. 15009 final boolean downgradeRequested = 15010 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15011 final boolean packageDebuggable = 15012 (dataOwnerPkg.applicationInfo.flags 15013 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15014 final boolean downgradePermitted = 15015 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15016 if (!downgradePermitted) { 15017 try { 15018 checkDowngrade(dataOwnerPkg, pkgLite); 15019 } catch (PackageManagerException e) { 15020 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15021 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15022 } 15023 } 15024 } 15025 15026 if (installedPkg != null) { 15027 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15028 // Check for updated system application. 15029 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15030 if (onSd) { 15031 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15032 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15033 } 15034 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15035 } else { 15036 if (onSd) { 15037 // Install flag overrides everything. 15038 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15039 } 15040 // If current upgrade specifies particular preference 15041 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15042 // Application explicitly specified internal. 15043 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15044 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15045 // App explictly prefers external. Let policy decide 15046 } else { 15047 // Prefer previous location 15048 if (isExternal(installedPkg)) { 15049 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15050 } 15051 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15052 } 15053 } 15054 } else { 15055 // Invalid install. Return error code 15056 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15057 } 15058 } 15059 } 15060 // All the special cases have been taken care of. 15061 // Return result based on recommended install location. 15062 if (onSd) { 15063 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15064 } 15065 return pkgLite.recommendedInstallLocation; 15066 } 15067 15068 /* 15069 * Invoke remote method to get package information and install 15070 * location values. Override install location based on default 15071 * policy if needed and then create install arguments based 15072 * on the install location. 15073 */ 15074 public void handleStartCopy() throws RemoteException { 15075 int ret = PackageManager.INSTALL_SUCCEEDED; 15076 15077 // If we're already staged, we've firmly committed to an install location 15078 if (origin.staged) { 15079 if (origin.file != null) { 15080 installFlags |= PackageManager.INSTALL_INTERNAL; 15081 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15082 } else { 15083 throw new IllegalStateException("Invalid stage location"); 15084 } 15085 } 15086 15087 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15088 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15089 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15090 PackageInfoLite pkgLite = null; 15091 15092 if (onInt && onSd) { 15093 // Check if both bits are set. 15094 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15095 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15096 } else if (onSd && ephemeral) { 15097 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15098 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15099 } else { 15100 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15101 packageAbiOverride); 15102 15103 if (DEBUG_INSTANT && ephemeral) { 15104 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15105 } 15106 15107 /* 15108 * If we have too little free space, try to free cache 15109 * before giving up. 15110 */ 15111 if (!origin.staged && pkgLite.recommendedInstallLocation 15112 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15113 // TODO: focus freeing disk space on the target device 15114 final StorageManager storage = StorageManager.from(mContext); 15115 final long lowThreshold = storage.getStorageLowBytes( 15116 Environment.getDataDirectory()); 15117 15118 final long sizeBytes = mContainerService.calculateInstalledSize( 15119 origin.resolvedPath, packageAbiOverride); 15120 15121 try { 15122 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15123 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15124 installFlags, packageAbiOverride); 15125 } catch (InstallerException e) { 15126 Slog.w(TAG, "Failed to free cache", e); 15127 } 15128 15129 /* 15130 * The cache free must have deleted the file we 15131 * downloaded to install. 15132 * 15133 * TODO: fix the "freeCache" call to not delete 15134 * the file we care about. 15135 */ 15136 if (pkgLite.recommendedInstallLocation 15137 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15138 pkgLite.recommendedInstallLocation 15139 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15140 } 15141 } 15142 } 15143 15144 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15145 int loc = pkgLite.recommendedInstallLocation; 15146 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15147 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15148 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15149 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15150 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15151 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15152 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15153 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15154 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15155 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15156 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15157 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15158 } else { 15159 // Override with defaults if needed. 15160 loc = installLocationPolicy(pkgLite); 15161 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15162 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15163 } else if (!onSd && !onInt) { 15164 // Override install location with flags 15165 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15166 // Set the flag to install on external media. 15167 installFlags |= PackageManager.INSTALL_EXTERNAL; 15168 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15169 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15170 if (DEBUG_INSTANT) { 15171 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15172 } 15173 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15174 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15175 |PackageManager.INSTALL_INTERNAL); 15176 } else { 15177 // Make sure the flag for installing on external 15178 // media is unset 15179 installFlags |= PackageManager.INSTALL_INTERNAL; 15180 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15181 } 15182 } 15183 } 15184 } 15185 15186 final InstallArgs args = createInstallArgs(this); 15187 mArgs = args; 15188 15189 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15190 // TODO: http://b/22976637 15191 // Apps installed for "all" users use the device owner to verify the app 15192 UserHandle verifierUser = getUser(); 15193 if (verifierUser == UserHandle.ALL) { 15194 verifierUser = UserHandle.SYSTEM; 15195 } 15196 15197 /* 15198 * Determine if we have any installed package verifiers. If we 15199 * do, then we'll defer to them to verify the packages. 15200 */ 15201 final int requiredUid = mRequiredVerifierPackage == null ? -1 15202 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15203 verifierUser.getIdentifier()); 15204 final int installerUid = 15205 verificationInfo == null ? -1 : verificationInfo.installerUid; 15206 if (!origin.existing && requiredUid != -1 15207 && isVerificationEnabled( 15208 verifierUser.getIdentifier(), installFlags, installerUid)) { 15209 final Intent verification = new Intent( 15210 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15211 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15212 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15213 PACKAGE_MIME_TYPE); 15214 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15215 15216 // Query all live verifiers based on current user state 15217 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15218 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15219 false /*allowDynamicSplits*/); 15220 15221 if (DEBUG_VERIFY) { 15222 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15223 + verification.toString() + " with " + pkgLite.verifiers.length 15224 + " optional verifiers"); 15225 } 15226 15227 final int verificationId = mPendingVerificationToken++; 15228 15229 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15230 15231 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15232 installerPackageName); 15233 15234 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15235 installFlags); 15236 15237 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15238 pkgLite.packageName); 15239 15240 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15241 pkgLite.versionCode); 15242 15243 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15244 pkgLite.getLongVersionCode()); 15245 15246 if (verificationInfo != null) { 15247 if (verificationInfo.originatingUri != null) { 15248 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15249 verificationInfo.originatingUri); 15250 } 15251 if (verificationInfo.referrer != null) { 15252 verification.putExtra(Intent.EXTRA_REFERRER, 15253 verificationInfo.referrer); 15254 } 15255 if (verificationInfo.originatingUid >= 0) { 15256 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15257 verificationInfo.originatingUid); 15258 } 15259 if (verificationInfo.installerUid >= 0) { 15260 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15261 verificationInfo.installerUid); 15262 } 15263 } 15264 15265 final PackageVerificationState verificationState = new PackageVerificationState( 15266 requiredUid, args); 15267 15268 mPendingVerification.append(verificationId, verificationState); 15269 15270 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15271 receivers, verificationState); 15272 15273 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15274 final long idleDuration = getVerificationTimeout(); 15275 15276 /* 15277 * If any sufficient verifiers were listed in the package 15278 * manifest, attempt to ask them. 15279 */ 15280 if (sufficientVerifiers != null) { 15281 final int N = sufficientVerifiers.size(); 15282 if (N == 0) { 15283 Slog.i(TAG, "Additional verifiers required, but none installed."); 15284 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15285 } else { 15286 for (int i = 0; i < N; i++) { 15287 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15288 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15289 verifierComponent.getPackageName(), idleDuration, 15290 verifierUser.getIdentifier(), false, "package verifier"); 15291 15292 final Intent sufficientIntent = new Intent(verification); 15293 sufficientIntent.setComponent(verifierComponent); 15294 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15295 } 15296 } 15297 } 15298 15299 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15300 mRequiredVerifierPackage, receivers); 15301 if (ret == PackageManager.INSTALL_SUCCEEDED 15302 && mRequiredVerifierPackage != null) { 15303 Trace.asyncTraceBegin( 15304 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15305 /* 15306 * Send the intent to the required verification agent, 15307 * but only start the verification timeout after the 15308 * target BroadcastReceivers have run. 15309 */ 15310 verification.setComponent(requiredVerifierComponent); 15311 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15312 mRequiredVerifierPackage, idleDuration, 15313 verifierUser.getIdentifier(), false, "package verifier"); 15314 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15315 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15316 new BroadcastReceiver() { 15317 @Override 15318 public void onReceive(Context context, Intent intent) { 15319 final Message msg = mHandler 15320 .obtainMessage(CHECK_PENDING_VERIFICATION); 15321 msg.arg1 = verificationId; 15322 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15323 } 15324 }, null, 0, null, null); 15325 15326 /* 15327 * We don't want the copy to proceed until verification 15328 * succeeds, so null out this field. 15329 */ 15330 mArgs = null; 15331 } 15332 } else { 15333 /* 15334 * No package verification is enabled, so immediately start 15335 * the remote call to initiate copy using temporary file. 15336 */ 15337 ret = args.copyApk(mContainerService, true); 15338 } 15339 } 15340 15341 mRet = ret; 15342 } 15343 15344 @Override 15345 void handleReturnCode() { 15346 // If mArgs is null, then MCS couldn't be reached. When it 15347 // reconnects, it will try again to install. At that point, this 15348 // will succeed. 15349 if (mArgs != null) { 15350 processPendingInstall(mArgs, mRet); 15351 } 15352 } 15353 15354 @Override 15355 void handleServiceError() { 15356 mArgs = createInstallArgs(this); 15357 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15358 } 15359 } 15360 15361 private InstallArgs createInstallArgs(InstallParams params) { 15362 if (params.move != null) { 15363 return new MoveInstallArgs(params); 15364 } else { 15365 return new FileInstallArgs(params); 15366 } 15367 } 15368 15369 /** 15370 * Create args that describe an existing installed package. Typically used 15371 * when cleaning up old installs, or used as a move source. 15372 */ 15373 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15374 String resourcePath, String[] instructionSets) { 15375 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15376 } 15377 15378 static abstract class InstallArgs { 15379 /** @see InstallParams#origin */ 15380 final OriginInfo origin; 15381 /** @see InstallParams#move */ 15382 final MoveInfo move; 15383 15384 final IPackageInstallObserver2 observer; 15385 // Always refers to PackageManager flags only 15386 final int installFlags; 15387 final String installerPackageName; 15388 final String volumeUuid; 15389 final UserHandle user; 15390 final String abiOverride; 15391 final String[] installGrantPermissions; 15392 /** If non-null, drop an async trace when the install completes */ 15393 final String traceMethod; 15394 final int traceCookie; 15395 final PackageParser.SigningDetails signingDetails; 15396 final int installReason; 15397 15398 // The list of instruction sets supported by this app. This is currently 15399 // only used during the rmdex() phase to clean up resources. We can get rid of this 15400 // if we move dex files under the common app path. 15401 /* nullable */ String[] instructionSets; 15402 15403 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15404 int installFlags, String installerPackageName, String volumeUuid, 15405 UserHandle user, String[] instructionSets, 15406 String abiOverride, String[] installGrantPermissions, 15407 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15408 int installReason) { 15409 this.origin = origin; 15410 this.move = move; 15411 this.installFlags = installFlags; 15412 this.observer = observer; 15413 this.installerPackageName = installerPackageName; 15414 this.volumeUuid = volumeUuid; 15415 this.user = user; 15416 this.instructionSets = instructionSets; 15417 this.abiOverride = abiOverride; 15418 this.installGrantPermissions = installGrantPermissions; 15419 this.traceMethod = traceMethod; 15420 this.traceCookie = traceCookie; 15421 this.signingDetails = signingDetails; 15422 this.installReason = installReason; 15423 } 15424 15425 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15426 abstract int doPreInstall(int status); 15427 15428 /** 15429 * Rename package into final resting place. All paths on the given 15430 * scanned package should be updated to reflect the rename. 15431 */ 15432 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15433 abstract int doPostInstall(int status, int uid); 15434 15435 /** @see PackageSettingBase#codePathString */ 15436 abstract String getCodePath(); 15437 /** @see PackageSettingBase#resourcePathString */ 15438 abstract String getResourcePath(); 15439 15440 // Need installer lock especially for dex file removal. 15441 abstract void cleanUpResourcesLI(); 15442 abstract boolean doPostDeleteLI(boolean delete); 15443 15444 /** 15445 * Called before the source arguments are copied. This is used mostly 15446 * for MoveParams when it needs to read the source file to put it in the 15447 * destination. 15448 */ 15449 int doPreCopy() { 15450 return PackageManager.INSTALL_SUCCEEDED; 15451 } 15452 15453 /** 15454 * Called after the source arguments are copied. This is used mostly for 15455 * MoveParams when it needs to read the source file to put it in the 15456 * destination. 15457 */ 15458 int doPostCopy(int uid) { 15459 return PackageManager.INSTALL_SUCCEEDED; 15460 } 15461 15462 protected boolean isFwdLocked() { 15463 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15464 } 15465 15466 protected boolean isExternalAsec() { 15467 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15468 } 15469 15470 protected boolean isEphemeral() { 15471 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15472 } 15473 15474 UserHandle getUser() { 15475 return user; 15476 } 15477 } 15478 15479 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15480 if (!allCodePaths.isEmpty()) { 15481 if (instructionSets == null) { 15482 throw new IllegalStateException("instructionSet == null"); 15483 } 15484 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15485 for (String codePath : allCodePaths) { 15486 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15487 try { 15488 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15489 } catch (InstallerException ignored) { 15490 } 15491 } 15492 } 15493 } 15494 } 15495 15496 /** 15497 * Logic to handle installation of non-ASEC applications, including copying 15498 * and renaming logic. 15499 */ 15500 class FileInstallArgs extends InstallArgs { 15501 private File codeFile; 15502 private File resourceFile; 15503 15504 // Example topology: 15505 // /data/app/com.example/base.apk 15506 // /data/app/com.example/split_foo.apk 15507 // /data/app/com.example/lib/arm/libfoo.so 15508 // /data/app/com.example/lib/arm64/libfoo.so 15509 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15510 15511 /** New install */ 15512 FileInstallArgs(InstallParams params) { 15513 super(params.origin, params.move, params.observer, params.installFlags, 15514 params.installerPackageName, params.volumeUuid, 15515 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15516 params.grantedRuntimePermissions, 15517 params.traceMethod, params.traceCookie, params.signingDetails, 15518 params.installReason); 15519 if (isFwdLocked()) { 15520 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15521 } 15522 } 15523 15524 /** Existing install */ 15525 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15526 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15527 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15528 PackageManager.INSTALL_REASON_UNKNOWN); 15529 this.codeFile = (codePath != null) ? new File(codePath) : null; 15530 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15531 } 15532 15533 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15535 try { 15536 return doCopyApk(imcs, temp); 15537 } finally { 15538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15539 } 15540 } 15541 15542 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15543 if (origin.staged) { 15544 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15545 codeFile = origin.file; 15546 resourceFile = origin.file; 15547 return PackageManager.INSTALL_SUCCEEDED; 15548 } 15549 15550 try { 15551 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15552 final File tempDir = 15553 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15554 codeFile = tempDir; 15555 resourceFile = tempDir; 15556 } catch (IOException e) { 15557 Slog.w(TAG, "Failed to create copy file: " + e); 15558 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15559 } 15560 15561 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15562 @Override 15563 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15564 if (!FileUtils.isValidExtFilename(name)) { 15565 throw new IllegalArgumentException("Invalid filename: " + name); 15566 } 15567 try { 15568 final File file = new File(codeFile, name); 15569 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15570 O_RDWR | O_CREAT, 0644); 15571 Os.chmod(file.getAbsolutePath(), 0644); 15572 return new ParcelFileDescriptor(fd); 15573 } catch (ErrnoException e) { 15574 throw new RemoteException("Failed to open: " + e.getMessage()); 15575 } 15576 } 15577 }; 15578 15579 int ret = PackageManager.INSTALL_SUCCEEDED; 15580 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15581 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15582 Slog.e(TAG, "Failed to copy package"); 15583 return ret; 15584 } 15585 15586 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15587 NativeLibraryHelper.Handle handle = null; 15588 try { 15589 handle = NativeLibraryHelper.Handle.create(codeFile); 15590 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15591 abiOverride); 15592 } catch (IOException e) { 15593 Slog.e(TAG, "Copying native libraries failed", e); 15594 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15595 } finally { 15596 IoUtils.closeQuietly(handle); 15597 } 15598 15599 return ret; 15600 } 15601 15602 int doPreInstall(int status) { 15603 if (status != PackageManager.INSTALL_SUCCEEDED) { 15604 cleanUp(); 15605 } 15606 return status; 15607 } 15608 15609 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15610 if (status != PackageManager.INSTALL_SUCCEEDED) { 15611 cleanUp(); 15612 return false; 15613 } 15614 15615 final File targetDir = codeFile.getParentFile(); 15616 final File beforeCodeFile = codeFile; 15617 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15618 15619 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15620 try { 15621 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15622 } catch (ErrnoException e) { 15623 Slog.w(TAG, "Failed to rename", e); 15624 return false; 15625 } 15626 15627 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15628 Slog.w(TAG, "Failed to restorecon"); 15629 return false; 15630 } 15631 15632 // Reflect the rename internally 15633 codeFile = afterCodeFile; 15634 resourceFile = afterCodeFile; 15635 15636 // Reflect the rename in scanned details 15637 try { 15638 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15639 } catch (IOException e) { 15640 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15641 return false; 15642 } 15643 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15644 afterCodeFile, pkg.baseCodePath)); 15645 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15646 afterCodeFile, pkg.splitCodePaths)); 15647 15648 // Reflect the rename in app info 15649 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15650 pkg.setApplicationInfoCodePath(pkg.codePath); 15651 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15652 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15653 pkg.setApplicationInfoResourcePath(pkg.codePath); 15654 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15655 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15656 15657 return true; 15658 } 15659 15660 int doPostInstall(int status, int uid) { 15661 if (status != PackageManager.INSTALL_SUCCEEDED) { 15662 cleanUp(); 15663 } 15664 return status; 15665 } 15666 15667 @Override 15668 String getCodePath() { 15669 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15670 } 15671 15672 @Override 15673 String getResourcePath() { 15674 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15675 } 15676 15677 private boolean cleanUp() { 15678 if (codeFile == null || !codeFile.exists()) { 15679 return false; 15680 } 15681 15682 removeCodePathLI(codeFile); 15683 15684 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15685 resourceFile.delete(); 15686 } 15687 15688 return true; 15689 } 15690 15691 void cleanUpResourcesLI() { 15692 // Try enumerating all code paths before deleting 15693 List<String> allCodePaths = Collections.EMPTY_LIST; 15694 if (codeFile != null && codeFile.exists()) { 15695 try { 15696 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15697 allCodePaths = pkg.getAllCodePaths(); 15698 } catch (PackageParserException e) { 15699 // Ignored; we tried our best 15700 } 15701 } 15702 15703 cleanUp(); 15704 removeDexFiles(allCodePaths, instructionSets); 15705 } 15706 15707 boolean doPostDeleteLI(boolean delete) { 15708 // XXX err, shouldn't we respect the delete flag? 15709 cleanUpResourcesLI(); 15710 return true; 15711 } 15712 } 15713 15714 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15715 PackageManagerException { 15716 if (copyRet < 0) { 15717 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15718 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15719 throw new PackageManagerException(copyRet, message); 15720 } 15721 } 15722 } 15723 15724 /** 15725 * Extract the StorageManagerService "container ID" from the full code path of an 15726 * .apk. 15727 */ 15728 static String cidFromCodePath(String fullCodePath) { 15729 int eidx = fullCodePath.lastIndexOf("/"); 15730 String subStr1 = fullCodePath.substring(0, eidx); 15731 int sidx = subStr1.lastIndexOf("/"); 15732 return subStr1.substring(sidx+1, eidx); 15733 } 15734 15735 /** 15736 * Logic to handle movement of existing installed applications. 15737 */ 15738 class MoveInstallArgs extends InstallArgs { 15739 private File codeFile; 15740 private File resourceFile; 15741 15742 /** New install */ 15743 MoveInstallArgs(InstallParams params) { 15744 super(params.origin, params.move, params.observer, params.installFlags, 15745 params.installerPackageName, params.volumeUuid, 15746 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15747 params.grantedRuntimePermissions, 15748 params.traceMethod, params.traceCookie, params.signingDetails, 15749 params.installReason); 15750 } 15751 15752 int copyApk(IMediaContainerService imcs, boolean temp) { 15753 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15754 + move.fromUuid + " to " + move.toUuid); 15755 synchronized (mInstaller) { 15756 try { 15757 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15758 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15759 } catch (InstallerException e) { 15760 Slog.w(TAG, "Failed to move app", e); 15761 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15762 } 15763 } 15764 15765 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15766 resourceFile = codeFile; 15767 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15768 15769 return PackageManager.INSTALL_SUCCEEDED; 15770 } 15771 15772 int doPreInstall(int status) { 15773 if (status != PackageManager.INSTALL_SUCCEEDED) { 15774 cleanUp(move.toUuid); 15775 } 15776 return status; 15777 } 15778 15779 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15780 if (status != PackageManager.INSTALL_SUCCEEDED) { 15781 cleanUp(move.toUuid); 15782 return false; 15783 } 15784 15785 // Reflect the move in app info 15786 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15787 pkg.setApplicationInfoCodePath(pkg.codePath); 15788 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15789 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15790 pkg.setApplicationInfoResourcePath(pkg.codePath); 15791 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15792 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15793 15794 return true; 15795 } 15796 15797 int doPostInstall(int status, int uid) { 15798 if (status == PackageManager.INSTALL_SUCCEEDED) { 15799 cleanUp(move.fromUuid); 15800 } else { 15801 cleanUp(move.toUuid); 15802 } 15803 return status; 15804 } 15805 15806 @Override 15807 String getCodePath() { 15808 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15809 } 15810 15811 @Override 15812 String getResourcePath() { 15813 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15814 } 15815 15816 private boolean cleanUp(String volumeUuid) { 15817 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15818 move.dataAppName); 15819 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15820 final int[] userIds = sUserManager.getUserIds(); 15821 synchronized (mInstallLock) { 15822 // Clean up both app data and code 15823 // All package moves are frozen until finished 15824 for (int userId : userIds) { 15825 try { 15826 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15827 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15828 } catch (InstallerException e) { 15829 Slog.w(TAG, String.valueOf(e)); 15830 } 15831 } 15832 removeCodePathLI(codeFile); 15833 } 15834 return true; 15835 } 15836 15837 void cleanUpResourcesLI() { 15838 throw new UnsupportedOperationException(); 15839 } 15840 15841 boolean doPostDeleteLI(boolean delete) { 15842 throw new UnsupportedOperationException(); 15843 } 15844 } 15845 15846 static String getAsecPackageName(String packageCid) { 15847 int idx = packageCid.lastIndexOf("-"); 15848 if (idx == -1) { 15849 return packageCid; 15850 } 15851 return packageCid.substring(0, idx); 15852 } 15853 15854 // Utility method used to create code paths based on package name and available index. 15855 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15856 String idxStr = ""; 15857 int idx = 1; 15858 // Fall back to default value of idx=1 if prefix is not 15859 // part of oldCodePath 15860 if (oldCodePath != null) { 15861 String subStr = oldCodePath; 15862 // Drop the suffix right away 15863 if (suffix != null && subStr.endsWith(suffix)) { 15864 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15865 } 15866 // If oldCodePath already contains prefix find out the 15867 // ending index to either increment or decrement. 15868 int sidx = subStr.lastIndexOf(prefix); 15869 if (sidx != -1) { 15870 subStr = subStr.substring(sidx + prefix.length()); 15871 if (subStr != null) { 15872 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15873 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15874 } 15875 try { 15876 idx = Integer.parseInt(subStr); 15877 if (idx <= 1) { 15878 idx++; 15879 } else { 15880 idx--; 15881 } 15882 } catch(NumberFormatException e) { 15883 } 15884 } 15885 } 15886 } 15887 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15888 return prefix + idxStr; 15889 } 15890 15891 private File getNextCodePath(File targetDir, String packageName) { 15892 File result; 15893 SecureRandom random = new SecureRandom(); 15894 byte[] bytes = new byte[16]; 15895 do { 15896 random.nextBytes(bytes); 15897 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15898 result = new File(targetDir, packageName + "-" + suffix); 15899 } while (result.exists()); 15900 return result; 15901 } 15902 15903 // Utility method that returns the relative package path with respect 15904 // to the installation directory. Like say for /data/data/com.test-1.apk 15905 // string com.test-1 is returned. 15906 static String deriveCodePathName(String codePath) { 15907 if (codePath == null) { 15908 return null; 15909 } 15910 final File codeFile = new File(codePath); 15911 final String name = codeFile.getName(); 15912 if (codeFile.isDirectory()) { 15913 return name; 15914 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15915 final int lastDot = name.lastIndexOf('.'); 15916 return name.substring(0, lastDot); 15917 } else { 15918 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15919 return null; 15920 } 15921 } 15922 15923 static class PackageInstalledInfo { 15924 String name; 15925 int uid; 15926 // The set of users that originally had this package installed. 15927 int[] origUsers; 15928 // The set of users that now have this package installed. 15929 int[] newUsers; 15930 PackageParser.Package pkg; 15931 int returnCode; 15932 String returnMsg; 15933 String installerPackageName; 15934 PackageRemovedInfo removedInfo; 15935 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15936 15937 public void setError(int code, String msg) { 15938 setReturnCode(code); 15939 setReturnMessage(msg); 15940 Slog.w(TAG, msg); 15941 } 15942 15943 public void setError(String msg, PackageParserException e) { 15944 setReturnCode(e.error); 15945 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15946 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15947 for (int i = 0; i < childCount; i++) { 15948 addedChildPackages.valueAt(i).setError(msg, e); 15949 } 15950 Slog.w(TAG, msg, e); 15951 } 15952 15953 public void setError(String msg, PackageManagerException e) { 15954 returnCode = e.error; 15955 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15956 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15957 for (int i = 0; i < childCount; i++) { 15958 addedChildPackages.valueAt(i).setError(msg, e); 15959 } 15960 Slog.w(TAG, msg, e); 15961 } 15962 15963 public void setReturnCode(int returnCode) { 15964 this.returnCode = returnCode; 15965 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15966 for (int i = 0; i < childCount; i++) { 15967 addedChildPackages.valueAt(i).returnCode = returnCode; 15968 } 15969 } 15970 15971 private void setReturnMessage(String returnMsg) { 15972 this.returnMsg = returnMsg; 15973 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15974 for (int i = 0; i < childCount; i++) { 15975 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15976 } 15977 } 15978 15979 // In some error cases we want to convey more info back to the observer 15980 String origPackage; 15981 String origPermission; 15982 } 15983 15984 /* 15985 * Install a non-existing package. 15986 */ 15987 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15988 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15989 String volumeUuid, PackageInstalledInfo res, int installReason) { 15990 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15991 15992 // Remember this for later, in case we need to rollback this install 15993 String pkgName = pkg.packageName; 15994 15995 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15996 15997 synchronized(mPackages) { 15998 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15999 if (renamedPackage != null) { 16000 // A package with the same name is already installed, though 16001 // it has been renamed to an older name. The package we 16002 // are trying to install should be installed as an update to 16003 // the existing one, but that has not been requested, so bail. 16004 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16005 + " without first uninstalling package running as " 16006 + renamedPackage); 16007 return; 16008 } 16009 if (mPackages.containsKey(pkgName)) { 16010 // Don't allow installation over an existing package with the same name. 16011 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16012 + " without first uninstalling."); 16013 return; 16014 } 16015 } 16016 16017 try { 16018 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 16019 System.currentTimeMillis(), user); 16020 16021 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16022 16023 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16024 prepareAppDataAfterInstallLIF(newPackage); 16025 16026 } else { 16027 // Remove package from internal structures, but keep around any 16028 // data that might have already existed 16029 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16030 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16031 } 16032 } catch (PackageManagerException e) { 16033 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16034 } 16035 16036 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16037 } 16038 16039 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16040 try (DigestInputStream digestStream = 16041 new DigestInputStream(new FileInputStream(file), digest)) { 16042 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16043 } 16044 } 16045 16046 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16047 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16048 PackageInstalledInfo res, int installReason) { 16049 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16050 16051 final PackageParser.Package oldPackage; 16052 final PackageSetting ps; 16053 final String pkgName = pkg.packageName; 16054 final int[] allUsers; 16055 final int[] installedUsers; 16056 16057 synchronized(mPackages) { 16058 oldPackage = mPackages.get(pkgName); 16059 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16060 16061 // don't allow upgrade to target a release SDK from a pre-release SDK 16062 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16063 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16064 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16065 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16066 if (oldTargetsPreRelease 16067 && !newTargetsPreRelease 16068 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16069 Slog.w(TAG, "Can't install package targeting released sdk"); 16070 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16071 return; 16072 } 16073 16074 ps = mSettings.mPackages.get(pkgName); 16075 16076 // verify signatures are valid 16077 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16078 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16079 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16080 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16081 "New package not signed by keys specified by upgrade-keysets: " 16082 + pkgName); 16083 return; 16084 } 16085 } else { 16086 16087 // default to original signature matching 16088 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 16089 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 16090 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16091 "New package has a different signature: " + pkgName); 16092 return; 16093 } 16094 } 16095 16096 // don't allow a system upgrade unless the upgrade hash matches 16097 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16098 byte[] digestBytes = null; 16099 try { 16100 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16101 updateDigest(digest, new File(pkg.baseCodePath)); 16102 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16103 for (String path : pkg.splitCodePaths) { 16104 updateDigest(digest, new File(path)); 16105 } 16106 } 16107 digestBytes = digest.digest(); 16108 } catch (NoSuchAlgorithmException | IOException e) { 16109 res.setError(INSTALL_FAILED_INVALID_APK, 16110 "Could not compute hash: " + pkgName); 16111 return; 16112 } 16113 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16114 res.setError(INSTALL_FAILED_INVALID_APK, 16115 "New package fails restrict-update check: " + pkgName); 16116 return; 16117 } 16118 // retain upgrade restriction 16119 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16120 } 16121 16122 // Check for shared user id changes 16123 String invalidPackageName = 16124 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16125 if (invalidPackageName != null) { 16126 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16127 "Package " + invalidPackageName + " tried to change user " 16128 + oldPackage.mSharedUserId); 16129 return; 16130 } 16131 16132 // check if the new package supports all of the abis which the old package supports 16133 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16134 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16135 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16136 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16137 "Update to package " + pkgName + " doesn't support multi arch"); 16138 return; 16139 } 16140 16141 // In case of rollback, remember per-user/profile install state 16142 allUsers = sUserManager.getUserIds(); 16143 installedUsers = ps.queryInstalledUsers(allUsers, true); 16144 16145 // don't allow an upgrade from full to ephemeral 16146 if (isInstantApp) { 16147 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16148 for (int currentUser : allUsers) { 16149 if (!ps.getInstantApp(currentUser)) { 16150 // can't downgrade from full to instant 16151 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16152 + " for user: " + currentUser); 16153 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16154 return; 16155 } 16156 } 16157 } else if (!ps.getInstantApp(user.getIdentifier())) { 16158 // can't downgrade from full to instant 16159 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16160 + " for user: " + user.getIdentifier()); 16161 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16162 return; 16163 } 16164 } 16165 } 16166 16167 // Update what is removed 16168 res.removedInfo = new PackageRemovedInfo(this); 16169 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16170 res.removedInfo.removedPackage = oldPackage.packageName; 16171 res.removedInfo.installerPackageName = ps.installerPackageName; 16172 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16173 res.removedInfo.isUpdate = true; 16174 res.removedInfo.origUsers = installedUsers; 16175 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16176 for (int i = 0; i < installedUsers.length; i++) { 16177 final int userId = installedUsers[i]; 16178 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16179 } 16180 16181 final int childCount = (oldPackage.childPackages != null) 16182 ? oldPackage.childPackages.size() : 0; 16183 for (int i = 0; i < childCount; i++) { 16184 boolean childPackageUpdated = false; 16185 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16186 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16187 if (res.addedChildPackages != null) { 16188 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16189 if (childRes != null) { 16190 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16191 childRes.removedInfo.removedPackage = childPkg.packageName; 16192 if (childPs != null) { 16193 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16194 } 16195 childRes.removedInfo.isUpdate = true; 16196 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16197 childPackageUpdated = true; 16198 } 16199 } 16200 if (!childPackageUpdated) { 16201 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16202 childRemovedRes.removedPackage = childPkg.packageName; 16203 if (childPs != null) { 16204 childRemovedRes.installerPackageName = childPs.installerPackageName; 16205 } 16206 childRemovedRes.isUpdate = false; 16207 childRemovedRes.dataRemoved = true; 16208 synchronized (mPackages) { 16209 if (childPs != null) { 16210 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16211 } 16212 } 16213 if (res.removedInfo.removedChildPackages == null) { 16214 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16215 } 16216 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16217 } 16218 } 16219 16220 boolean sysPkg = (isSystemApp(oldPackage)); 16221 if (sysPkg) { 16222 // Set the system/privileged/oem/vendor/product flags as needed 16223 final boolean privileged = 16224 (oldPackage.applicationInfo.privateFlags 16225 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16226 final boolean oem = 16227 (oldPackage.applicationInfo.privateFlags 16228 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16229 final boolean vendor = 16230 (oldPackage.applicationInfo.privateFlags 16231 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16232 final boolean product = 16233 (oldPackage.applicationInfo.privateFlags 16234 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16235 final @ParseFlags int systemParseFlags = parseFlags; 16236 final @ScanFlags int systemScanFlags = scanFlags 16237 | SCAN_AS_SYSTEM 16238 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16239 | (oem ? SCAN_AS_OEM : 0) 16240 | (vendor ? SCAN_AS_VENDOR : 0) 16241 | (product ? SCAN_AS_PRODUCT : 0); 16242 16243 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16244 user, allUsers, installerPackageName, res, installReason); 16245 } else { 16246 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16247 user, allUsers, installerPackageName, res, installReason); 16248 } 16249 } 16250 16251 @Override 16252 public List<String> getPreviousCodePaths(String packageName) { 16253 final int callingUid = Binder.getCallingUid(); 16254 final List<String> result = new ArrayList<>(); 16255 if (getInstantAppPackageName(callingUid) != null) { 16256 return result; 16257 } 16258 final PackageSetting ps = mSettings.mPackages.get(packageName); 16259 if (ps != null 16260 && ps.oldCodePaths != null 16261 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16262 result.addAll(ps.oldCodePaths); 16263 } 16264 return result; 16265 } 16266 16267 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16268 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16269 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16270 String installerPackageName, PackageInstalledInfo res, int installReason) { 16271 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16272 + deletedPackage); 16273 16274 String pkgName = deletedPackage.packageName; 16275 boolean deletedPkg = true; 16276 boolean addedPkg = false; 16277 boolean updatedSettings = false; 16278 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16279 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16280 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16281 16282 final long origUpdateTime = (pkg.mExtras != null) 16283 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16284 16285 // First delete the existing package while retaining the data directory 16286 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16287 res.removedInfo, true, pkg)) { 16288 // If the existing package wasn't successfully deleted 16289 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16290 deletedPkg = false; 16291 } else { 16292 // Successfully deleted the old package; proceed with replace. 16293 16294 // If deleted package lived in a container, give users a chance to 16295 // relinquish resources before killing. 16296 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16297 if (DEBUG_INSTALL) { 16298 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16299 } 16300 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16301 final ArrayList<String> pkgList = new ArrayList<String>(1); 16302 pkgList.add(deletedPackage.applicationInfo.packageName); 16303 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16304 } 16305 16306 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16307 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16308 16309 try { 16310 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16311 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16312 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16313 installReason); 16314 16315 // Update the in-memory copy of the previous code paths. 16316 PackageSetting ps = mSettings.mPackages.get(pkgName); 16317 if (!killApp) { 16318 if (ps.oldCodePaths == null) { 16319 ps.oldCodePaths = new ArraySet<>(); 16320 } 16321 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16322 if (deletedPackage.splitCodePaths != null) { 16323 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16324 } 16325 } else { 16326 ps.oldCodePaths = null; 16327 } 16328 if (ps.childPackageNames != null) { 16329 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16330 final String childPkgName = ps.childPackageNames.get(i); 16331 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16332 childPs.oldCodePaths = ps.oldCodePaths; 16333 } 16334 } 16335 // set instant app status, but, only if it's explicitly specified 16336 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16337 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16338 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16339 prepareAppDataAfterInstallLIF(newPackage); 16340 addedPkg = true; 16341 mDexManager.notifyPackageUpdated(newPackage.packageName, 16342 newPackage.baseCodePath, newPackage.splitCodePaths); 16343 } catch (PackageManagerException e) { 16344 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16345 } 16346 } 16347 16348 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16349 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16350 16351 // Revert all internal state mutations and added folders for the failed install 16352 if (addedPkg) { 16353 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16354 res.removedInfo, true, null); 16355 } 16356 16357 // Restore the old package 16358 if (deletedPkg) { 16359 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16360 File restoreFile = new File(deletedPackage.codePath); 16361 // Parse old package 16362 boolean oldExternal = isExternal(deletedPackage); 16363 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16364 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16365 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16366 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16367 try { 16368 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16369 null); 16370 } catch (PackageManagerException e) { 16371 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16372 + e.getMessage()); 16373 return; 16374 } 16375 16376 synchronized (mPackages) { 16377 // Ensure the installer package name up to date 16378 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16379 16380 // Update permissions for restored package 16381 mPermissionManager.updatePermissions( 16382 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16383 mPermissionCallback); 16384 16385 mSettings.writeLPr(); 16386 } 16387 16388 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16389 } 16390 } else { 16391 synchronized (mPackages) { 16392 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16393 if (ps != null) { 16394 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16395 if (res.removedInfo.removedChildPackages != null) { 16396 final int childCount = res.removedInfo.removedChildPackages.size(); 16397 // Iterate in reverse as we may modify the collection 16398 for (int i = childCount - 1; i >= 0; i--) { 16399 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16400 if (res.addedChildPackages.containsKey(childPackageName)) { 16401 res.removedInfo.removedChildPackages.removeAt(i); 16402 } else { 16403 PackageRemovedInfo childInfo = res.removedInfo 16404 .removedChildPackages.valueAt(i); 16405 childInfo.removedForAllUsers = mPackages.get( 16406 childInfo.removedPackage) == null; 16407 } 16408 } 16409 } 16410 } 16411 } 16412 } 16413 } 16414 16415 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16416 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16417 final @ScanFlags int scanFlags, UserHandle user, 16418 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16419 int installReason) { 16420 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16421 + ", old=" + deletedPackage); 16422 16423 final boolean disabledSystem; 16424 16425 // Remove existing system package 16426 removePackageLI(deletedPackage, true); 16427 16428 synchronized (mPackages) { 16429 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16430 } 16431 if (!disabledSystem) { 16432 // We didn't need to disable the .apk as a current system package, 16433 // which means we are replacing another update that is already 16434 // installed. We need to make sure to delete the older one's .apk. 16435 res.removedInfo.args = createInstallArgsForExisting(0, 16436 deletedPackage.applicationInfo.getCodePath(), 16437 deletedPackage.applicationInfo.getResourcePath(), 16438 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16439 } else { 16440 res.removedInfo.args = null; 16441 } 16442 16443 // Successfully disabled the old package. Now proceed with re-installation 16444 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16445 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16446 16447 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16448 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16449 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16450 16451 PackageParser.Package newPackage = null; 16452 try { 16453 // Add the package to the internal data structures 16454 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16455 16456 // Set the update and install times 16457 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16458 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16459 System.currentTimeMillis()); 16460 16461 // Update the package dynamic state if succeeded 16462 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16463 // Now that the install succeeded make sure we remove data 16464 // directories for any child package the update removed. 16465 final int deletedChildCount = (deletedPackage.childPackages != null) 16466 ? deletedPackage.childPackages.size() : 0; 16467 final int newChildCount = (newPackage.childPackages != null) 16468 ? newPackage.childPackages.size() : 0; 16469 for (int i = 0; i < deletedChildCount; i++) { 16470 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16471 boolean childPackageDeleted = true; 16472 for (int j = 0; j < newChildCount; j++) { 16473 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16474 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16475 childPackageDeleted = false; 16476 break; 16477 } 16478 } 16479 if (childPackageDeleted) { 16480 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16481 deletedChildPkg.packageName); 16482 if (ps != null && res.removedInfo.removedChildPackages != null) { 16483 PackageRemovedInfo removedChildRes = res.removedInfo 16484 .removedChildPackages.get(deletedChildPkg.packageName); 16485 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16486 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16487 } 16488 } 16489 } 16490 16491 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16492 installReason); 16493 prepareAppDataAfterInstallLIF(newPackage); 16494 16495 mDexManager.notifyPackageUpdated(newPackage.packageName, 16496 newPackage.baseCodePath, newPackage.splitCodePaths); 16497 } 16498 } catch (PackageManagerException e) { 16499 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16500 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16501 } 16502 16503 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16504 // Re installation failed. Restore old information 16505 // Remove new pkg information 16506 if (newPackage != null) { 16507 removeInstalledPackageLI(newPackage, true); 16508 } 16509 // Add back the old system package 16510 try { 16511 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16512 } catch (PackageManagerException e) { 16513 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16514 } 16515 16516 synchronized (mPackages) { 16517 if (disabledSystem) { 16518 enableSystemPackageLPw(deletedPackage); 16519 } 16520 16521 // Ensure the installer package name up to date 16522 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16523 16524 // Update permissions for restored package 16525 mPermissionManager.updatePermissions( 16526 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16527 mPermissionCallback); 16528 16529 mSettings.writeLPr(); 16530 } 16531 16532 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16533 + " after failed upgrade"); 16534 } 16535 } 16536 16537 /** 16538 * Checks whether the parent or any of the child packages have a change shared 16539 * user. For a package to be a valid update the shred users of the parent and 16540 * the children should match. We may later support changing child shared users. 16541 * @param oldPkg The updated package. 16542 * @param newPkg The update package. 16543 * @return The shared user that change between the versions. 16544 */ 16545 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16546 PackageParser.Package newPkg) { 16547 // Check parent shared user 16548 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16549 return newPkg.packageName; 16550 } 16551 // Check child shared users 16552 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16553 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16554 for (int i = 0; i < newChildCount; i++) { 16555 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16556 // If this child was present, did it have the same shared user? 16557 for (int j = 0; j < oldChildCount; j++) { 16558 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16559 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16560 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16561 return newChildPkg.packageName; 16562 } 16563 } 16564 } 16565 return null; 16566 } 16567 16568 private void removeNativeBinariesLI(PackageSetting ps) { 16569 // Remove the lib path for the parent package 16570 if (ps != null) { 16571 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16572 // Remove the lib path for the child packages 16573 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16574 for (int i = 0; i < childCount; i++) { 16575 PackageSetting childPs = null; 16576 synchronized (mPackages) { 16577 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16578 } 16579 if (childPs != null) { 16580 NativeLibraryHelper.removeNativeBinariesLI(childPs 16581 .legacyNativeLibraryPathString); 16582 } 16583 } 16584 } 16585 } 16586 16587 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16588 // Enable the parent package 16589 mSettings.enableSystemPackageLPw(pkg.packageName); 16590 // Enable the child packages 16591 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16592 for (int i = 0; i < childCount; i++) { 16593 PackageParser.Package childPkg = pkg.childPackages.get(i); 16594 mSettings.enableSystemPackageLPw(childPkg.packageName); 16595 } 16596 } 16597 16598 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16599 PackageParser.Package newPkg) { 16600 // Disable the parent package (parent always replaced) 16601 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16602 // Disable the child packages 16603 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16604 for (int i = 0; i < childCount; i++) { 16605 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16606 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16607 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16608 } 16609 return disabled; 16610 } 16611 16612 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16613 String installerPackageName) { 16614 // Enable the parent package 16615 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16616 // Enable the child packages 16617 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16618 for (int i = 0; i < childCount; i++) { 16619 PackageParser.Package childPkg = pkg.childPackages.get(i); 16620 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16621 } 16622 } 16623 16624 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16625 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16626 // Update the parent package setting 16627 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16628 res, user, installReason); 16629 // Update the child packages setting 16630 final int childCount = (newPackage.childPackages != null) 16631 ? newPackage.childPackages.size() : 0; 16632 for (int i = 0; i < childCount; i++) { 16633 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16634 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16635 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16636 childRes.origUsers, childRes, user, installReason); 16637 } 16638 } 16639 16640 private void updateSettingsInternalLI(PackageParser.Package pkg, 16641 String installerPackageName, int[] allUsers, int[] installedForUsers, 16642 PackageInstalledInfo res, UserHandle user, int installReason) { 16643 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16644 16645 final String pkgName = pkg.packageName; 16646 16647 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16648 synchronized (mPackages) { 16649// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16650 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16651 mPermissionCallback); 16652 // For system-bundled packages, we assume that installing an upgraded version 16653 // of the package implies that the user actually wants to run that new code, 16654 // so we enable the package. 16655 PackageSetting ps = mSettings.mPackages.get(pkgName); 16656 final int userId = user.getIdentifier(); 16657 if (ps != null) { 16658 if (isSystemApp(pkg)) { 16659 if (DEBUG_INSTALL) { 16660 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16661 } 16662 // Enable system package for requested users 16663 if (res.origUsers != null) { 16664 for (int origUserId : res.origUsers) { 16665 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16666 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16667 origUserId, installerPackageName); 16668 } 16669 } 16670 } 16671 // Also convey the prior install/uninstall state 16672 if (allUsers != null && installedForUsers != null) { 16673 for (int currentUserId : allUsers) { 16674 final boolean installed = ArrayUtils.contains( 16675 installedForUsers, currentUserId); 16676 if (DEBUG_INSTALL) { 16677 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16678 } 16679 ps.setInstalled(installed, currentUserId); 16680 } 16681 // these install state changes will be persisted in the 16682 // upcoming call to mSettings.writeLPr(). 16683 } 16684 } 16685 // It's implied that when a user requests installation, they want the app to be 16686 // installed and enabled. 16687 if (userId != UserHandle.USER_ALL) { 16688 ps.setInstalled(true, userId); 16689 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16690 } else { 16691 for (int currentUserId : sUserManager.getUserIds()) { 16692 ps.setInstalled(true, currentUserId); 16693 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId, 16694 installerPackageName); 16695 } 16696 } 16697 16698 // When replacing an existing package, preserve the original install reason for all 16699 // users that had the package installed before. 16700 final Set<Integer> previousUserIds = new ArraySet<>(); 16701 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16702 final int installReasonCount = res.removedInfo.installReasons.size(); 16703 for (int i = 0; i < installReasonCount; i++) { 16704 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16705 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16706 ps.setInstallReason(previousInstallReason, previousUserId); 16707 previousUserIds.add(previousUserId); 16708 } 16709 } 16710 16711 // Set install reason for users that are having the package newly installed. 16712 if (userId == UserHandle.USER_ALL) { 16713 for (int currentUserId : sUserManager.getUserIds()) { 16714 if (!previousUserIds.contains(currentUserId)) { 16715 ps.setInstallReason(installReason, currentUserId); 16716 } 16717 } 16718 } else if (!previousUserIds.contains(userId)) { 16719 ps.setInstallReason(installReason, userId); 16720 } 16721 mSettings.writeKernelMappingLPr(ps); 16722 } 16723 res.name = pkgName; 16724 res.uid = pkg.applicationInfo.uid; 16725 res.pkg = pkg; 16726 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16727 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16728 //to update install status 16729 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16730 mSettings.writeLPr(); 16731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16732 } 16733 16734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16735 } 16736 16737 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16738 try { 16739 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16740 installPackageLI(args, res); 16741 } finally { 16742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16743 } 16744 } 16745 16746 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16747 final int installFlags = args.installFlags; 16748 final String installerPackageName = args.installerPackageName; 16749 final String volumeUuid = args.volumeUuid; 16750 final File tmpPackageFile = new File(args.getCodePath()); 16751 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16752 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16753 || (args.volumeUuid != null)); 16754 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16755 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16756 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16757 final boolean virtualPreload = 16758 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16759 boolean replace = false; 16760 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16761 if (args.move != null) { 16762 // moving a complete application; perform an initial scan on the new install location 16763 scanFlags |= SCAN_INITIAL; 16764 } 16765 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16766 scanFlags |= SCAN_DONT_KILL_APP; 16767 } 16768 if (instantApp) { 16769 scanFlags |= SCAN_AS_INSTANT_APP; 16770 } 16771 if (fullApp) { 16772 scanFlags |= SCAN_AS_FULL_APP; 16773 } 16774 if (virtualPreload) { 16775 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16776 } 16777 16778 // Result object to be returned 16779 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16780 res.installerPackageName = installerPackageName; 16781 16782 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16783 16784 // Sanity check 16785 if (instantApp && (forwardLocked || onExternal)) { 16786 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16787 + " external=" + onExternal); 16788 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16789 return; 16790 } 16791 16792 // Retrieve PackageSettings and parse package 16793 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16794 | PackageParser.PARSE_ENFORCE_CODE 16795 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16796 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16797 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16798 PackageParser pp = new PackageParser(); 16799 pp.setSeparateProcesses(mSeparateProcesses); 16800 pp.setDisplayMetrics(mMetrics); 16801 pp.setCallback(mPackageParserCallback); 16802 16803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16804 final PackageParser.Package pkg; 16805 try { 16806 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16807 DexMetadataHelper.validatePackageDexMetadata(pkg); 16808 } catch (PackageParserException e) { 16809 res.setError("Failed parse during installPackageLI", e); 16810 return; 16811 } finally { 16812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16813 } 16814 16815 // Instant apps have several additional install-time checks. 16816 if (instantApp) { 16817 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16818 Slog.w(TAG, 16819 "Instant app package " + pkg.packageName + " does not target at least O"); 16820 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16821 "Instant app package must target at least O"); 16822 return; 16823 } 16824 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16825 Slog.w(TAG, "Instant app package " + pkg.packageName 16826 + " does not target targetSandboxVersion 2"); 16827 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16828 "Instant app package must use targetSandboxVersion 2"); 16829 return; 16830 } 16831 if (pkg.mSharedUserId != null) { 16832 Slog.w(TAG, "Instant app package " + pkg.packageName 16833 + " may not declare sharedUserId."); 16834 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16835 "Instant app package may not declare a sharedUserId"); 16836 return; 16837 } 16838 } 16839 16840 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16841 // Static shared libraries have synthetic package names 16842 renameStaticSharedLibraryPackage(pkg); 16843 16844 // No static shared libs on external storage 16845 if (onExternal) { 16846 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16847 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16848 "Packages declaring static-shared libs cannot be updated"); 16849 return; 16850 } 16851 } 16852 16853 // If we are installing a clustered package add results for the children 16854 if (pkg.childPackages != null) { 16855 synchronized (mPackages) { 16856 final int childCount = pkg.childPackages.size(); 16857 for (int i = 0; i < childCount; i++) { 16858 PackageParser.Package childPkg = pkg.childPackages.get(i); 16859 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16860 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16861 childRes.pkg = childPkg; 16862 childRes.name = childPkg.packageName; 16863 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16864 if (childPs != null) { 16865 childRes.origUsers = childPs.queryInstalledUsers( 16866 sUserManager.getUserIds(), true); 16867 } 16868 if ((mPackages.containsKey(childPkg.packageName))) { 16869 childRes.removedInfo = new PackageRemovedInfo(this); 16870 childRes.removedInfo.removedPackage = childPkg.packageName; 16871 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16872 } 16873 if (res.addedChildPackages == null) { 16874 res.addedChildPackages = new ArrayMap<>(); 16875 } 16876 res.addedChildPackages.put(childPkg.packageName, childRes); 16877 } 16878 } 16879 } 16880 16881 // If package doesn't declare API override, mark that we have an install 16882 // time CPU ABI override. 16883 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16884 pkg.cpuAbiOverride = args.abiOverride; 16885 } 16886 16887 String pkgName = res.name = pkg.packageName; 16888 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16889 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16890 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16891 return; 16892 } 16893 } 16894 16895 try { 16896 // either use what we've been given or parse directly from the APK 16897 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16898 pkg.setSigningDetails(args.signingDetails); 16899 } else { 16900 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16901 } 16902 } catch (PackageParserException e) { 16903 res.setError("Failed collect during installPackageLI", e); 16904 return; 16905 } 16906 16907 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16908 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16909 Slog.w(TAG, "Instant app package " + pkg.packageName 16910 + " is not signed with at least APK Signature Scheme v2"); 16911 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16912 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16913 return; 16914 } 16915 16916 // Get rid of all references to package scan path via parser. 16917 pp = null; 16918 String oldCodePath = null; 16919 boolean systemApp = false; 16920 synchronized (mPackages) { 16921 // Check if installing already existing package 16922 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16923 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16924 if (pkg.mOriginalPackages != null 16925 && pkg.mOriginalPackages.contains(oldName) 16926 && mPackages.containsKey(oldName)) { 16927 // This package is derived from an original package, 16928 // and this device has been updating from that original 16929 // name. We must continue using the original name, so 16930 // rename the new package here. 16931 pkg.setPackageName(oldName); 16932 pkgName = pkg.packageName; 16933 replace = true; 16934 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16935 + oldName + " pkgName=" + pkgName); 16936 } else if (mPackages.containsKey(pkgName)) { 16937 // This package, under its official name, already exists 16938 // on the device; we should replace it. 16939 replace = true; 16940 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16941 } 16942 16943 // Child packages are installed through the parent package 16944 if (pkg.parentPackage != null) { 16945 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16946 "Package " + pkg.packageName + " is child of package " 16947 + pkg.parentPackage.parentPackage + ". Child packages " 16948 + "can be updated only through the parent package."); 16949 return; 16950 } 16951 16952 if (replace) { 16953 // Prevent apps opting out from runtime permissions 16954 PackageParser.Package oldPackage = mPackages.get(pkgName); 16955 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16956 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16957 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16958 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16959 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16960 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16961 + " doesn't support runtime permissions but the old" 16962 + " target SDK " + oldTargetSdk + " does."); 16963 return; 16964 } 16965 // Prevent persistent apps from being updated 16966 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16967 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16968 "Package " + oldPackage.packageName + " is a persistent app. " 16969 + "Persistent apps are not updateable."); 16970 return; 16971 } 16972 // Prevent apps from downgrading their targetSandbox. 16973 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16974 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16975 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16976 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16977 "Package " + pkg.packageName + " new target sandbox " 16978 + newTargetSandbox + " is incompatible with the previous value of" 16979 + oldTargetSandbox + "."); 16980 return; 16981 } 16982 16983 // Prevent installing of child packages 16984 if (oldPackage.parentPackage != null) { 16985 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16986 "Package " + pkg.packageName + " is child of package " 16987 + oldPackage.parentPackage + ". Child packages " 16988 + "can be updated only through the parent package."); 16989 return; 16990 } 16991 } 16992 } 16993 16994 PackageSetting ps = mSettings.mPackages.get(pkgName); 16995 if (ps != null) { 16996 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16997 16998 // Static shared libs have same package with different versions where 16999 // we internally use a synthetic package name to allow multiple versions 17000 // of the same package, therefore we need to compare signatures against 17001 // the package setting for the latest library version. 17002 PackageSetting signatureCheckPs = ps; 17003 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17004 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17005 if (libraryEntry != null) { 17006 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17007 } 17008 } 17009 17010 // Quick sanity check that we're signed correctly if updating; 17011 // we'll check this again later when scanning, but we want to 17012 // bail early here before tripping over redefined permissions. 17013 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17014 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 17015 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 17016 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17017 + pkg.packageName + " upgrade keys do not match the " 17018 + "previously installed version"); 17019 return; 17020 } 17021 } else { 17022 try { 17023 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17024 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17025 // We don't care about disabledPkgSetting on install for now. 17026 final boolean compatMatch = verifySignatures( 17027 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17028 compareRecover); 17029 // The new KeySets will be re-added later in the scanning process. 17030 if (compatMatch) { 17031 synchronized (mPackages) { 17032 ksms.removeAppKeySetDataLPw(pkg.packageName); 17033 } 17034 } 17035 } catch (PackageManagerException e) { 17036 res.setError(e.error, e.getMessage()); 17037 return; 17038 } 17039 } 17040 17041 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17042 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17043 systemApp = (ps.pkg.applicationInfo.flags & 17044 ApplicationInfo.FLAG_SYSTEM) != 0; 17045 } 17046 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17047 } 17048 17049 int N = pkg.permissions.size(); 17050 for (int i = N-1; i >= 0; i--) { 17051 final PackageParser.Permission perm = pkg.permissions.get(i); 17052 final BasePermission bp = 17053 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17054 17055 // Don't allow anyone but the system to define ephemeral permissions. 17056 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17057 && !systemApp) { 17058 Slog.w(TAG, "Non-System package " + pkg.packageName 17059 + " attempting to delcare ephemeral permission " 17060 + perm.info.name + "; Removing ephemeral."); 17061 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17062 } 17063 17064 // Check whether the newly-scanned package wants to define an already-defined perm 17065 if (bp != null) { 17066 // If the defining package is signed with our cert, it's okay. This 17067 // also includes the "updating the same package" case, of course. 17068 // "updating same package" could also involve key-rotation. 17069 final boolean sigsOk; 17070 final String sourcePackageName = bp.getSourcePackageName(); 17071 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17072 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17073 if (sourcePackageName.equals(pkg.packageName) 17074 && (ksms.shouldCheckUpgradeKeySetLocked( 17075 sourcePackageSetting, scanFlags))) { 17076 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17077 } else { 17078 17079 // in the event of signing certificate rotation, we need to see if the 17080 // package's certificate has rotated from the current one, or if it is an 17081 // older certificate with which the current is ok with sharing permissions 17082 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17083 pkg.mSigningDetails, 17084 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17085 sigsOk = true; 17086 } else if (pkg.mSigningDetails.checkCapability( 17087 sourcePackageSetting.signatures.mSigningDetails, 17088 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17089 17090 // the scanned package checks out, has signing certificate rotation 17091 // history, and is newer; bring it over 17092 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17093 sigsOk = true; 17094 } else { 17095 sigsOk = false; 17096 } 17097 } 17098 if (!sigsOk) { 17099 // If the owning package is the system itself, we log but allow 17100 // install to proceed; we fail the install on all other permission 17101 // redefinitions. 17102 if (!sourcePackageName.equals("android")) { 17103 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17104 + pkg.packageName + " attempting to redeclare permission " 17105 + perm.info.name + " already owned by " + sourcePackageName); 17106 res.origPermission = perm.info.name; 17107 res.origPackage = sourcePackageName; 17108 return; 17109 } else { 17110 Slog.w(TAG, "Package " + pkg.packageName 17111 + " attempting to redeclare system permission " 17112 + perm.info.name + "; ignoring new declaration"); 17113 pkg.permissions.remove(i); 17114 } 17115 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17116 // Prevent apps to change protection level to dangerous from any other 17117 // type as this would allow a privilege escalation where an app adds a 17118 // normal/signature permission in other app's group and later redefines 17119 // it as dangerous leading to the group auto-grant. 17120 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17121 == PermissionInfo.PROTECTION_DANGEROUS) { 17122 if (bp != null && !bp.isRuntime()) { 17123 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17124 + "non-runtime permission " + perm.info.name 17125 + " to runtime; keeping old protection level"); 17126 perm.info.protectionLevel = bp.getProtectionLevel(); 17127 } 17128 } 17129 } 17130 } 17131 } 17132 } 17133 17134 if (systemApp) { 17135 if (onExternal) { 17136 // Abort update; system app can't be replaced with app on sdcard 17137 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17138 "Cannot install updates to system apps on sdcard"); 17139 return; 17140 } else if (instantApp) { 17141 // Abort update; system app can't be replaced with an instant app 17142 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17143 "Cannot update a system app with an instant app"); 17144 return; 17145 } 17146 } 17147 17148 if (args.move != null) { 17149 // We did an in-place move, so dex is ready to roll 17150 scanFlags |= SCAN_NO_DEX; 17151 scanFlags |= SCAN_MOVE; 17152 17153 synchronized (mPackages) { 17154 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17155 if (ps == null) { 17156 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17157 "Missing settings for moved package " + pkgName); 17158 } 17159 17160 // We moved the entire application as-is, so bring over the 17161 // previously derived ABI information. 17162 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17163 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17164 } 17165 17166 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17167 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17168 scanFlags |= SCAN_NO_DEX; 17169 17170 try { 17171 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17172 args.abiOverride : pkg.cpuAbiOverride); 17173 final boolean extractNativeLibs = !pkg.isLibrary(); 17174 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17175 } catch (PackageManagerException pme) { 17176 Slog.e(TAG, "Error deriving application ABI", pme); 17177 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17178 return; 17179 } 17180 17181 // Shared libraries for the package need to be updated. 17182 synchronized (mPackages) { 17183 try { 17184 updateSharedLibrariesLPr(pkg, null); 17185 } catch (PackageManagerException e) { 17186 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17187 } 17188 } 17189 } 17190 17191 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17192 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17193 return; 17194 } 17195 17196 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17197 String apkPath = null; 17198 synchronized (mPackages) { 17199 // Note that if the attacker managed to skip verify setup, for example by tampering 17200 // with the package settings, upon reboot we will do full apk verification when 17201 // verity is not detected. 17202 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17203 if (ps != null && ps.isPrivileged()) { 17204 apkPath = pkg.baseCodePath; 17205 } 17206 } 17207 17208 if (apkPath != null) { 17209 final VerityUtils.SetupResult result = 17210 VerityUtils.generateApkVeritySetupData(apkPath); 17211 if (result.isOk()) { 17212 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17213 FileDescriptor fd = result.getUnownedFileDescriptor(); 17214 try { 17215 final byte[] signedRootHash = VerityUtils.generateFsverityRootHash(apkPath); 17216 mInstaller.installApkVerity(apkPath, fd, result.getContentSize()); 17217 mInstaller.assertFsverityRootHashMatches(apkPath, signedRootHash); 17218 } catch (InstallerException | IOException | DigestException | 17219 NoSuchAlgorithmException e) { 17220 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17221 "Failed to set up verity: " + e); 17222 return; 17223 } finally { 17224 IoUtils.closeQuietly(fd); 17225 } 17226 } else if (result.isFailed()) { 17227 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17228 return; 17229 } else { 17230 // Do nothing if verity is skipped. Will fall back to full apk verification on 17231 // reboot. 17232 } 17233 } 17234 } 17235 17236 if (!instantApp) { 17237 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17238 } else { 17239 if (DEBUG_DOMAIN_VERIFICATION) { 17240 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17241 } 17242 } 17243 17244 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17245 "installPackageLI")) { 17246 if (replace) { 17247 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17248 // Static libs have a synthetic package name containing the version 17249 // and cannot be updated as an update would get a new package name, 17250 // unless this is the exact same version code which is useful for 17251 // development. 17252 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17253 if (existingPkg != null && 17254 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17255 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17256 + "static-shared libs cannot be updated"); 17257 return; 17258 } 17259 } 17260 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17261 installerPackageName, res, args.installReason); 17262 } else { 17263 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17264 args.user, installerPackageName, volumeUuid, res, args.installReason); 17265 } 17266 } 17267 17268 // Prepare the application profiles for the new code paths. 17269 // This needs to be done before invoking dexopt so that any install-time profile 17270 // can be used for optimizations. 17271 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17272 17273 // Check whether we need to dexopt the app. 17274 // 17275 // NOTE: it is IMPORTANT to call dexopt: 17276 // - after doRename which will sync the package data from PackageParser.Package and its 17277 // corresponding ApplicationInfo. 17278 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17279 // uid of the application (pkg.applicationInfo.uid). 17280 // This update happens in place! 17281 // 17282 // We only need to dexopt if the package meets ALL of the following conditions: 17283 // 1) it is not forward locked. 17284 // 2) it is not on on an external ASEC container. 17285 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17286 // 17287 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17288 // complete, so we skip this step during installation. Instead, we'll take extra time 17289 // the first time the instant app starts. It's preferred to do it this way to provide 17290 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17291 // middle of running an instant app. The default behaviour can be overridden 17292 // via gservices. 17293 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17294 && !forwardLocked 17295 && !pkg.applicationInfo.isExternalAsec() 17296 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17297 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17298 17299 if (performDexopt) { 17300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17301 // Do not run PackageDexOptimizer through the local performDexOpt 17302 // method because `pkg` may not be in `mPackages` yet. 17303 // 17304 // Also, don't fail application installs if the dexopt step fails. 17305 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17306 REASON_INSTALL, 17307 DexoptOptions.DEXOPT_BOOT_COMPLETE | 17308 DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17309 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17310 null /* instructionSets */, 17311 getOrCreateCompilerPackageStats(pkg), 17312 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17313 dexoptOptions); 17314 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17315 } 17316 17317 // Notify BackgroundDexOptService that the package has been changed. 17318 // If this is an update of a package which used to fail to compile, 17319 // BackgroundDexOptService will remove it from its blacklist. 17320 // TODO: Layering violation 17321 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17322 17323 synchronized (mPackages) { 17324 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17325 if (ps != null) { 17326 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17327 ps.setUpdateAvailable(false /*updateAvailable*/); 17328 } 17329 17330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17331 for (int i = 0; i < childCount; i++) { 17332 PackageParser.Package childPkg = pkg.childPackages.get(i); 17333 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17334 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17335 if (childPs != null) { 17336 childRes.newUsers = childPs.queryInstalledUsers( 17337 sUserManager.getUserIds(), true); 17338 } 17339 } 17340 17341 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17342 updateSequenceNumberLP(ps, res.newUsers); 17343 updateInstantAppInstallerLocked(pkgName); 17344 } 17345 } 17346 } 17347 17348 private void startIntentFilterVerifications(int userId, boolean replacing, 17349 PackageParser.Package pkg) { 17350 if (mIntentFilterVerifierComponent == null) { 17351 Slog.w(TAG, "No IntentFilter verification will not be done as " 17352 + "there is no IntentFilterVerifier available!"); 17353 return; 17354 } 17355 17356 final int verifierUid = getPackageUid( 17357 mIntentFilterVerifierComponent.getPackageName(), 17358 MATCH_DEBUG_TRIAGED_MISSING, 17359 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17360 17361 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17362 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17363 mHandler.sendMessage(msg); 17364 17365 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17366 for (int i = 0; i < childCount; i++) { 17367 PackageParser.Package childPkg = pkg.childPackages.get(i); 17368 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17369 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17370 mHandler.sendMessage(msg); 17371 } 17372 } 17373 17374 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17375 PackageParser.Package pkg) { 17376 int size = pkg.activities.size(); 17377 if (size == 0) { 17378 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17379 "No activity, so no need to verify any IntentFilter!"); 17380 return; 17381 } 17382 17383 final boolean hasDomainURLs = hasDomainURLs(pkg); 17384 if (!hasDomainURLs) { 17385 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17386 "No domain URLs, so no need to verify any IntentFilter!"); 17387 return; 17388 } 17389 17390 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17391 + " if any IntentFilter from the " + size 17392 + " Activities needs verification ..."); 17393 17394 int count = 0; 17395 final String packageName = pkg.packageName; 17396 17397 synchronized (mPackages) { 17398 // If this is a new install and we see that we've already run verification for this 17399 // package, we have nothing to do: it means the state was restored from backup. 17400 if (!replacing) { 17401 IntentFilterVerificationInfo ivi = 17402 mSettings.getIntentFilterVerificationLPr(packageName); 17403 if (ivi != null) { 17404 if (DEBUG_DOMAIN_VERIFICATION) { 17405 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17406 + ivi.getStatusString()); 17407 } 17408 return; 17409 } 17410 } 17411 17412 // If any filters need to be verified, then all need to be. 17413 boolean needToVerify = false; 17414 for (PackageParser.Activity a : pkg.activities) { 17415 for (ActivityIntentInfo filter : a.intents) { 17416 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17417 if (DEBUG_DOMAIN_VERIFICATION) { 17418 Slog.d(TAG, 17419 "Intent filter needs verification, so processing all filters"); 17420 } 17421 needToVerify = true; 17422 break; 17423 } 17424 } 17425 } 17426 17427 if (needToVerify) { 17428 final int verificationId = mIntentFilterVerificationToken++; 17429 for (PackageParser.Activity a : pkg.activities) { 17430 for (ActivityIntentInfo filter : a.intents) { 17431 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17432 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17433 "Verification needed for IntentFilter:" + filter.toString()); 17434 mIntentFilterVerifier.addOneIntentFilterVerification( 17435 verifierUid, userId, verificationId, filter, packageName); 17436 count++; 17437 } 17438 } 17439 } 17440 } 17441 } 17442 17443 if (count > 0) { 17444 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17445 + " IntentFilter verification" + (count > 1 ? "s" : "") 17446 + " for userId:" + userId); 17447 mIntentFilterVerifier.startVerifications(userId); 17448 } else { 17449 if (DEBUG_DOMAIN_VERIFICATION) { 17450 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17451 } 17452 } 17453 } 17454 17455 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17456 final ComponentName cn = filter.activity.getComponentName(); 17457 final String packageName = cn.getPackageName(); 17458 17459 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17460 packageName); 17461 if (ivi == null) { 17462 return true; 17463 } 17464 int status = ivi.getStatus(); 17465 switch (status) { 17466 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17467 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17468 return true; 17469 17470 default: 17471 // Nothing to do 17472 return false; 17473 } 17474 } 17475 17476 private static boolean isMultiArch(ApplicationInfo info) { 17477 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17478 } 17479 17480 private static boolean isExternal(PackageParser.Package pkg) { 17481 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17482 } 17483 17484 private static boolean isExternal(PackageSetting ps) { 17485 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17486 } 17487 17488 private static boolean isSystemApp(PackageParser.Package pkg) { 17489 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17490 } 17491 17492 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17493 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17494 } 17495 17496 private static boolean isOemApp(PackageParser.Package pkg) { 17497 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17498 } 17499 17500 private static boolean isVendorApp(PackageParser.Package pkg) { 17501 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17502 } 17503 17504 private static boolean isProductApp(PackageParser.Package pkg) { 17505 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17506 } 17507 17508 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17509 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17510 } 17511 17512 private static boolean isSystemApp(PackageSetting ps) { 17513 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17514 } 17515 17516 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17517 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17518 } 17519 17520 private int packageFlagsToInstallFlags(PackageSetting ps) { 17521 int installFlags = 0; 17522 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17523 // This existing package was an external ASEC install when we have 17524 // the external flag without a UUID 17525 installFlags |= PackageManager.INSTALL_EXTERNAL; 17526 } 17527 if (ps.isForwardLocked()) { 17528 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17529 } 17530 return installFlags; 17531 } 17532 17533 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17534 if (isExternal(pkg)) { 17535 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17536 return mSettings.getExternalVersion(); 17537 } else { 17538 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17539 } 17540 } else { 17541 return mSettings.getInternalVersion(); 17542 } 17543 } 17544 17545 private void deleteTempPackageFiles() { 17546 final FilenameFilter filter = new FilenameFilter() { 17547 public boolean accept(File dir, String name) { 17548 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17549 } 17550 }; 17551 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17552 file.delete(); 17553 } 17554 } 17555 17556 @Override 17557 public void deletePackageAsUser(String packageName, int versionCode, 17558 IPackageDeleteObserver observer, int userId, int flags) { 17559 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17560 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17561 } 17562 17563 @Override 17564 public void deletePackageVersioned(VersionedPackage versionedPackage, 17565 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17566 final int callingUid = Binder.getCallingUid(); 17567 mContext.enforceCallingOrSelfPermission( 17568 android.Manifest.permission.DELETE_PACKAGES, null); 17569 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17570 Preconditions.checkNotNull(versionedPackage); 17571 Preconditions.checkNotNull(observer); 17572 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17573 PackageManager.VERSION_CODE_HIGHEST, 17574 Long.MAX_VALUE, "versionCode must be >= -1"); 17575 17576 final String packageName = versionedPackage.getPackageName(); 17577 final long versionCode = versionedPackage.getLongVersionCode(); 17578 final String internalPackageName; 17579 synchronized (mPackages) { 17580 // Normalize package name to handle renamed packages and static libs 17581 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17582 } 17583 17584 final int uid = Binder.getCallingUid(); 17585 if (!isOrphaned(internalPackageName) 17586 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17587 try { 17588 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17589 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17590 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17591 observer.onUserActionRequired(intent); 17592 } catch (RemoteException re) { 17593 } 17594 return; 17595 } 17596 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17597 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17598 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17599 mContext.enforceCallingOrSelfPermission( 17600 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17601 "deletePackage for user " + userId); 17602 } 17603 17604 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17605 try { 17606 observer.onPackageDeleted(packageName, 17607 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17608 } catch (RemoteException re) { 17609 } 17610 return; 17611 } 17612 17613 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17614 try { 17615 observer.onPackageDeleted(packageName, 17616 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17617 } catch (RemoteException re) { 17618 } 17619 return; 17620 } 17621 17622 if (DEBUG_REMOVE) { 17623 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17624 + " deleteAllUsers: " + deleteAllUsers + " version=" 17625 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17626 ? "VERSION_CODE_HIGHEST" : versionCode)); 17627 } 17628 // Queue up an async operation since the package deletion may take a little while. 17629 mHandler.post(new Runnable() { 17630 public void run() { 17631 mHandler.removeCallbacks(this); 17632 int returnCode; 17633 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17634 boolean doDeletePackage = true; 17635 if (ps != null) { 17636 final boolean targetIsInstantApp = 17637 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17638 doDeletePackage = !targetIsInstantApp 17639 || canViewInstantApps; 17640 } 17641 if (doDeletePackage) { 17642 if (!deleteAllUsers) { 17643 returnCode = deletePackageX(internalPackageName, versionCode, 17644 userId, deleteFlags); 17645 } else { 17646 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17647 internalPackageName, users); 17648 // If nobody is blocking uninstall, proceed with delete for all users 17649 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17650 returnCode = deletePackageX(internalPackageName, versionCode, 17651 userId, deleteFlags); 17652 } else { 17653 // Otherwise uninstall individually for users with blockUninstalls=false 17654 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17655 for (int userId : users) { 17656 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17657 returnCode = deletePackageX(internalPackageName, versionCode, 17658 userId, userFlags); 17659 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17660 Slog.w(TAG, "Package delete failed for user " + userId 17661 + ", returnCode " + returnCode); 17662 } 17663 } 17664 } 17665 // The app has only been marked uninstalled for certain users. 17666 // We still need to report that delete was blocked 17667 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17668 } 17669 } 17670 } else { 17671 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17672 } 17673 try { 17674 observer.onPackageDeleted(packageName, returnCode, null); 17675 } catch (RemoteException e) { 17676 Log.i(TAG, "Observer no longer exists."); 17677 } //end catch 17678 } //end run 17679 }); 17680 } 17681 17682 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17683 if (pkg.staticSharedLibName != null) { 17684 return pkg.manifestPackageName; 17685 } 17686 return pkg.packageName; 17687 } 17688 17689 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17690 // Handle renamed packages 17691 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17692 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17693 17694 // Is this a static library? 17695 LongSparseArray<SharedLibraryEntry> versionedLib = 17696 mStaticLibsByDeclaringPackage.get(packageName); 17697 if (versionedLib == null || versionedLib.size() <= 0) { 17698 return packageName; 17699 } 17700 17701 // Figure out which lib versions the caller can see 17702 LongSparseLongArray versionsCallerCanSee = null; 17703 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17704 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17705 && callingAppId != Process.ROOT_UID) { 17706 versionsCallerCanSee = new LongSparseLongArray(); 17707 String libName = versionedLib.valueAt(0).info.getName(); 17708 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17709 if (uidPackages != null) { 17710 for (String uidPackage : uidPackages) { 17711 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17712 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17713 if (libIdx >= 0) { 17714 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17715 versionsCallerCanSee.append(libVersion, libVersion); 17716 } 17717 } 17718 } 17719 } 17720 17721 // Caller can see nothing - done 17722 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17723 return packageName; 17724 } 17725 17726 // Find the version the caller can see and the app version code 17727 SharedLibraryEntry highestVersion = null; 17728 final int versionCount = versionedLib.size(); 17729 for (int i = 0; i < versionCount; i++) { 17730 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17731 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17732 libEntry.info.getLongVersion()) < 0) { 17733 continue; 17734 } 17735 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17736 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17737 if (libVersionCode == versionCode) { 17738 return libEntry.apk; 17739 } 17740 } else if (highestVersion == null) { 17741 highestVersion = libEntry; 17742 } else if (libVersionCode > highestVersion.info 17743 .getDeclaringPackage().getLongVersionCode()) { 17744 highestVersion = libEntry; 17745 } 17746 } 17747 17748 if (highestVersion != null) { 17749 return highestVersion.apk; 17750 } 17751 17752 return packageName; 17753 } 17754 17755 boolean isCallerVerifier(int callingUid) { 17756 final int callingUserId = UserHandle.getUserId(callingUid); 17757 return mRequiredVerifierPackage != null && 17758 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17759 } 17760 17761 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17762 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17763 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17764 return true; 17765 } 17766 final int callingUserId = UserHandle.getUserId(callingUid); 17767 // If the caller installed the pkgName, then allow it to silently uninstall. 17768 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17769 return true; 17770 } 17771 17772 // Allow package verifier to silently uninstall. 17773 if (mRequiredVerifierPackage != null && 17774 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17775 return true; 17776 } 17777 17778 // Allow package uninstaller to silently uninstall. 17779 if (mRequiredUninstallerPackage != null && 17780 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17781 return true; 17782 } 17783 17784 // Allow storage manager to silently uninstall. 17785 if (mStorageManagerPackage != null && 17786 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17787 return true; 17788 } 17789 17790 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17791 // uninstall for device owner provisioning. 17792 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17793 == PERMISSION_GRANTED) { 17794 return true; 17795 } 17796 17797 return false; 17798 } 17799 17800 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17801 int[] result = EMPTY_INT_ARRAY; 17802 for (int userId : userIds) { 17803 if (getBlockUninstallForUser(packageName, userId)) { 17804 result = ArrayUtils.appendInt(result, userId); 17805 } 17806 } 17807 return result; 17808 } 17809 17810 @Override 17811 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17812 final int callingUid = Binder.getCallingUid(); 17813 if (getInstantAppPackageName(callingUid) != null 17814 && !isCallerSameApp(packageName, callingUid)) { 17815 return false; 17816 } 17817 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17818 } 17819 17820 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17821 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17822 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17823 try { 17824 if (dpm != null) { 17825 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17826 /* callingUserOnly =*/ false); 17827 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17828 : deviceOwnerComponentName.getPackageName(); 17829 // Does the package contains the device owner? 17830 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17831 // this check is probably not needed, since DO should be registered as a device 17832 // admin on some user too. (Original bug for this: b/17657954) 17833 if (packageName.equals(deviceOwnerPackageName)) { 17834 return true; 17835 } 17836 // Does it contain a device admin for any user? 17837 int[] users; 17838 if (userId == UserHandle.USER_ALL) { 17839 users = sUserManager.getUserIds(); 17840 } else { 17841 users = new int[]{userId}; 17842 } 17843 for (int i = 0; i < users.length; ++i) { 17844 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17845 return true; 17846 } 17847 } 17848 } 17849 } catch (RemoteException e) { 17850 } 17851 return false; 17852 } 17853 17854 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17855 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17856 } 17857 17858 /** 17859 * This method is an internal method that could be get invoked either 17860 * to delete an installed package or to clean up a failed installation. 17861 * After deleting an installed package, a broadcast is sent to notify any 17862 * listeners that the package has been removed. For cleaning up a failed 17863 * installation, the broadcast is not necessary since the package's 17864 * installation wouldn't have sent the initial broadcast either 17865 * The key steps in deleting a package are 17866 * deleting the package information in internal structures like mPackages, 17867 * deleting the packages base directories through installd 17868 * updating mSettings to reflect current status 17869 * persisting settings for later use 17870 * sending a broadcast if necessary 17871 */ 17872 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17873 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17874 final boolean res; 17875 17876 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17877 ? UserHandle.USER_ALL : userId; 17878 17879 if (isPackageDeviceAdmin(packageName, removeUser)) { 17880 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17881 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17882 } 17883 17884 PackageSetting uninstalledPs = null; 17885 PackageParser.Package pkg = null; 17886 17887 // for the uninstall-updates case and restricted profiles, remember the per- 17888 // user handle installed state 17889 int[] allUsers; 17890 synchronized (mPackages) { 17891 uninstalledPs = mSettings.mPackages.get(packageName); 17892 if (uninstalledPs == null) { 17893 Slog.w(TAG, "Not removing non-existent package " + packageName); 17894 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17895 } 17896 17897 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17898 && uninstalledPs.versionCode != versionCode) { 17899 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17900 + uninstalledPs.versionCode + " != " + versionCode); 17901 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17902 } 17903 17904 // Static shared libs can be declared by any package, so let us not 17905 // allow removing a package if it provides a lib others depend on. 17906 pkg = mPackages.get(packageName); 17907 17908 allUsers = sUserManager.getUserIds(); 17909 17910 if (pkg != null && pkg.staticSharedLibName != null) { 17911 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17912 pkg.staticSharedLibVersion); 17913 if (libEntry != null) { 17914 for (int currUserId : allUsers) { 17915 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17916 continue; 17917 } 17918 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17919 libEntry.info, 0, currUserId); 17920 if (!ArrayUtils.isEmpty(libClientPackages)) { 17921 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17922 + " hosting lib " + libEntry.info.getName() + " version " 17923 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17924 + " for user " + currUserId); 17925 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17926 } 17927 } 17928 } 17929 } 17930 17931 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17932 } 17933 17934 final int freezeUser; 17935 if (isUpdatedSystemApp(uninstalledPs) 17936 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17937 // We're downgrading a system app, which will apply to all users, so 17938 // freeze them all during the downgrade 17939 freezeUser = UserHandle.USER_ALL; 17940 } else { 17941 freezeUser = removeUser; 17942 } 17943 17944 synchronized (mInstallLock) { 17945 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17946 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17947 deleteFlags, "deletePackageX")) { 17948 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17949 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17950 } 17951 synchronized (mPackages) { 17952 if (res) { 17953 if (pkg != null) { 17954 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17955 } 17956 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17957 updateInstantAppInstallerLocked(packageName); 17958 } 17959 } 17960 } 17961 17962 if (res) { 17963 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17964 info.sendPackageRemovedBroadcasts(killApp); 17965 info.sendSystemPackageUpdatedBroadcasts(); 17966 info.sendSystemPackageAppearedBroadcasts(); 17967 } 17968 // Force a gc here. 17969 Runtime.getRuntime().gc(); 17970 // Delete the resources here after sending the broadcast to let 17971 // other processes clean up before deleting resources. 17972 if (info.args != null) { 17973 synchronized (mInstallLock) { 17974 info.args.doPostDeleteLI(true); 17975 } 17976 } 17977 17978 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17979 } 17980 17981 static class PackageRemovedInfo { 17982 final PackageSender packageSender; 17983 String removedPackage; 17984 String installerPackageName; 17985 int uid = -1; 17986 int removedAppId = -1; 17987 int[] origUsers; 17988 int[] removedUsers = null; 17989 int[] broadcastUsers = null; 17990 int[] instantUserIds = null; 17991 SparseArray<Integer> installReasons; 17992 boolean isRemovedPackageSystemUpdate = false; 17993 boolean isUpdate; 17994 boolean dataRemoved; 17995 boolean removedForAllUsers; 17996 boolean isStaticSharedLib; 17997 // Clean up resources deleted packages. 17998 InstallArgs args = null; 17999 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18000 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18001 18002 PackageRemovedInfo(PackageSender packageSender) { 18003 this.packageSender = packageSender; 18004 } 18005 18006 void sendPackageRemovedBroadcasts(boolean killApp) { 18007 sendPackageRemovedBroadcastInternal(killApp); 18008 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18009 for (int i = 0; i < childCount; i++) { 18010 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18011 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18012 } 18013 } 18014 18015 void sendSystemPackageUpdatedBroadcasts() { 18016 if (isRemovedPackageSystemUpdate) { 18017 sendSystemPackageUpdatedBroadcastsInternal(); 18018 final int childCount = (removedChildPackages != null) 18019 ? removedChildPackages.size() : 0; 18020 for (int i = 0; i < childCount; i++) { 18021 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18022 if (childInfo.isRemovedPackageSystemUpdate) { 18023 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18024 } 18025 } 18026 } 18027 } 18028 18029 void sendSystemPackageAppearedBroadcasts() { 18030 final int packageCount = (appearedChildPackages != null) 18031 ? appearedChildPackages.size() : 0; 18032 for (int i = 0; i < packageCount; i++) { 18033 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18034 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18035 true /*sendBootCompleted*/, false /*startReceiver*/, 18036 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18037 } 18038 } 18039 18040 private void sendSystemPackageUpdatedBroadcastsInternal() { 18041 Bundle extras = new Bundle(2); 18042 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18043 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18044 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18045 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18046 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18047 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18048 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18049 null, null, 0, removedPackage, null, null, null); 18050 if (installerPackageName != null) { 18051 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18052 removedPackage, extras, 0 /*flags*/, 18053 installerPackageName, null, null, null); 18054 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18055 removedPackage, extras, 0 /*flags*/, 18056 installerPackageName, null, null, null); 18057 } 18058 } 18059 18060 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18061 // Don't send static shared library removal broadcasts as these 18062 // libs are visible only the the apps that depend on them an one 18063 // cannot remove the library if it has a dependency. 18064 if (isStaticSharedLib) { 18065 return; 18066 } 18067 Bundle extras = new Bundle(2); 18068 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18069 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18070 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18071 if (isUpdate || isRemovedPackageSystemUpdate) { 18072 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18073 } 18074 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18075 if (removedPackage != null) { 18076 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18077 removedPackage, extras, 0, null /*targetPackage*/, null, 18078 broadcastUsers, instantUserIds); 18079 if (installerPackageName != null) { 18080 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18081 removedPackage, extras, 0 /*flags*/, 18082 installerPackageName, null, broadcastUsers, instantUserIds); 18083 } 18084 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18085 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18086 removedPackage, extras, 18087 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18088 null, null, broadcastUsers, instantUserIds); 18089 packageSender.notifyPackageRemoved(removedPackage); 18090 } 18091 } 18092 if (removedAppId >= 0) { 18093 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18094 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18095 null, null, broadcastUsers, instantUserIds); 18096 } 18097 } 18098 18099 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18100 removedUsers = userIds; 18101 if (removedUsers == null) { 18102 broadcastUsers = null; 18103 return; 18104 } 18105 18106 broadcastUsers = EMPTY_INT_ARRAY; 18107 instantUserIds = EMPTY_INT_ARRAY; 18108 for (int i = userIds.length - 1; i >= 0; --i) { 18109 final int userId = userIds[i]; 18110 if (deletedPackageSetting.getInstantApp(userId)) { 18111 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18112 } else { 18113 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18114 } 18115 } 18116 } 18117 } 18118 18119 /* 18120 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18121 * flag is not set, the data directory is removed as well. 18122 * make sure this flag is set for partially installed apps. If not its meaningless to 18123 * delete a partially installed application. 18124 */ 18125 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18126 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18127 String packageName = ps.name; 18128 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18129 // Retrieve object to delete permissions for shared user later on 18130 final PackageParser.Package deletedPkg; 18131 final PackageSetting deletedPs; 18132 // reader 18133 synchronized (mPackages) { 18134 deletedPkg = mPackages.get(packageName); 18135 deletedPs = mSettings.mPackages.get(packageName); 18136 if (outInfo != null) { 18137 outInfo.removedPackage = packageName; 18138 outInfo.installerPackageName = ps.installerPackageName; 18139 outInfo.isStaticSharedLib = deletedPkg != null 18140 && deletedPkg.staticSharedLibName != null; 18141 outInfo.populateUsers(deletedPs == null ? null 18142 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18143 } 18144 } 18145 18146 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18147 18148 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18149 final PackageParser.Package resolvedPkg; 18150 if (deletedPkg != null) { 18151 resolvedPkg = deletedPkg; 18152 } else { 18153 // We don't have a parsed package when it lives on an ejected 18154 // adopted storage device, so fake something together 18155 resolvedPkg = new PackageParser.Package(ps.name); 18156 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18157 } 18158 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18159 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18160 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18161 if (outInfo != null) { 18162 outInfo.dataRemoved = true; 18163 } 18164 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18165 } 18166 18167 int removedAppId = -1; 18168 18169 // writer 18170 synchronized (mPackages) { 18171 boolean installedStateChanged = false; 18172 if (deletedPs != null) { 18173 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18174 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18175 clearDefaultBrowserIfNeeded(packageName); 18176 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18177 removedAppId = mSettings.removePackageLPw(packageName); 18178 if (outInfo != null) { 18179 outInfo.removedAppId = removedAppId; 18180 } 18181 mPermissionManager.updatePermissions( 18182 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18183 if (deletedPs.sharedUser != null) { 18184 // Remove permissions associated with package. Since runtime 18185 // permissions are per user we have to kill the removed package 18186 // or packages running under the shared user of the removed 18187 // package if revoking the permissions requested only by the removed 18188 // package is successful and this causes a change in gids. 18189 for (int userId : UserManagerService.getInstance().getUserIds()) { 18190 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18191 userId); 18192 if (userIdToKill == UserHandle.USER_ALL 18193 || userIdToKill >= UserHandle.USER_SYSTEM) { 18194 // If gids changed for this user, kill all affected packages. 18195 mHandler.post(new Runnable() { 18196 @Override 18197 public void run() { 18198 // This has to happen with no lock held. 18199 killApplication(deletedPs.name, deletedPs.appId, 18200 KILL_APP_REASON_GIDS_CHANGED); 18201 } 18202 }); 18203 break; 18204 } 18205 } 18206 } 18207 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18208 } 18209 // make sure to preserve per-user disabled state if this removal was just 18210 // a downgrade of a system app to the factory package 18211 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18212 if (DEBUG_REMOVE) { 18213 Slog.d(TAG, "Propagating install state across downgrade"); 18214 } 18215 for (int userId : allUserHandles) { 18216 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18217 if (DEBUG_REMOVE) { 18218 Slog.d(TAG, " user " + userId + " => " + installed); 18219 } 18220 if (installed != ps.getInstalled(userId)) { 18221 installedStateChanged = true; 18222 } 18223 ps.setInstalled(installed, userId); 18224 } 18225 } 18226 } 18227 // can downgrade to reader 18228 if (writeSettings) { 18229 // Save settings now 18230 mSettings.writeLPr(); 18231 } 18232 if (installedStateChanged) { 18233 mSettings.writeKernelMappingLPr(ps); 18234 } 18235 } 18236 if (removedAppId != -1) { 18237 // A user ID was deleted here. Go through all users and remove it 18238 // from KeyStore. 18239 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18240 } 18241 } 18242 18243 static boolean locationIsPrivileged(String path) { 18244 try { 18245 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18246 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18247 final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app"); 18248 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18249 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18250 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18251 || path.startsWith(privilegedOdmAppDir.getCanonicalPath()) 18252 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18253 } catch (IOException e) { 18254 Slog.e(TAG, "Unable to access code path " + path); 18255 } 18256 return false; 18257 } 18258 18259 static boolean locationIsOem(String path) { 18260 try { 18261 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18262 } catch (IOException e) { 18263 Slog.e(TAG, "Unable to access code path " + path); 18264 } 18265 return false; 18266 } 18267 18268 static boolean locationIsVendor(String path) { 18269 try { 18270 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()) 18271 || path.startsWith(Environment.getOdmDirectory().getCanonicalPath()); 18272 } catch (IOException e) { 18273 Slog.e(TAG, "Unable to access code path " + path); 18274 } 18275 return false; 18276 } 18277 18278 static boolean locationIsProduct(String path) { 18279 try { 18280 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18281 } catch (IOException e) { 18282 Slog.e(TAG, "Unable to access code path " + path); 18283 } 18284 return false; 18285 } 18286 18287 /* 18288 * Tries to delete system package. 18289 */ 18290 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18291 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18292 boolean writeSettings) { 18293 if (deletedPs.parentPackageName != null) { 18294 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18295 return false; 18296 } 18297 18298 final boolean applyUserRestrictions 18299 = (allUserHandles != null) && (outInfo.origUsers != null); 18300 final PackageSetting disabledPs; 18301 // Confirm if the system package has been updated 18302 // An updated system app can be deleted. This will also have to restore 18303 // the system pkg from system partition 18304 // reader 18305 synchronized (mPackages) { 18306 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18307 } 18308 18309 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18310 + " disabledPs=" + disabledPs); 18311 18312 if (disabledPs == null) { 18313 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18314 return false; 18315 } else if (DEBUG_REMOVE) { 18316 Slog.d(TAG, "Deleting system pkg from data partition"); 18317 } 18318 18319 if (DEBUG_REMOVE) { 18320 if (applyUserRestrictions) { 18321 Slog.d(TAG, "Remembering install states:"); 18322 for (int userId : allUserHandles) { 18323 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18324 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18325 } 18326 } 18327 } 18328 18329 // Delete the updated package 18330 outInfo.isRemovedPackageSystemUpdate = true; 18331 if (outInfo.removedChildPackages != null) { 18332 final int childCount = (deletedPs.childPackageNames != null) 18333 ? deletedPs.childPackageNames.size() : 0; 18334 for (int i = 0; i < childCount; i++) { 18335 String childPackageName = deletedPs.childPackageNames.get(i); 18336 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18337 .contains(childPackageName)) { 18338 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18339 childPackageName); 18340 if (childInfo != null) { 18341 childInfo.isRemovedPackageSystemUpdate = true; 18342 } 18343 } 18344 } 18345 } 18346 18347 if (disabledPs.versionCode < deletedPs.versionCode) { 18348 // Delete data for downgrades 18349 flags &= ~PackageManager.DELETE_KEEP_DATA; 18350 } else { 18351 // Preserve data by setting flag 18352 flags |= PackageManager.DELETE_KEEP_DATA; 18353 } 18354 18355 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18356 outInfo, writeSettings, disabledPs.pkg); 18357 if (!ret) { 18358 return false; 18359 } 18360 18361 // writer 18362 synchronized (mPackages) { 18363 // NOTE: The system package always needs to be enabled; even if it's for 18364 // a compressed stub. If we don't, installing the system package fails 18365 // during scan [scanning checks the disabled packages]. We will reverse 18366 // this later, after we've "installed" the stub. 18367 // Reinstate the old system package 18368 enableSystemPackageLPw(disabledPs.pkg); 18369 // Remove any native libraries from the upgraded package. 18370 removeNativeBinariesLI(deletedPs); 18371 } 18372 18373 // Install the system package 18374 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18375 try { 18376 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18377 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18378 } catch (PackageManagerException e) { 18379 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18380 + e.getMessage()); 18381 return false; 18382 } finally { 18383 if (disabledPs.pkg.isStub) { 18384 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18385 } 18386 } 18387 return true; 18388 } 18389 18390 /** 18391 * Installs a package that's already on the system partition. 18392 */ 18393 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18394 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18395 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18396 throws PackageManagerException { 18397 @ParseFlags int parseFlags = 18398 mDefParseFlags 18399 | PackageParser.PARSE_MUST_BE_APK 18400 | PackageParser.PARSE_IS_SYSTEM_DIR; 18401 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18402 if (isPrivileged || locationIsPrivileged(codePathString)) { 18403 scanFlags |= SCAN_AS_PRIVILEGED; 18404 } 18405 if (locationIsOem(codePathString)) { 18406 scanFlags |= SCAN_AS_OEM; 18407 } 18408 if (locationIsVendor(codePathString)) { 18409 scanFlags |= SCAN_AS_VENDOR; 18410 } 18411 if (locationIsProduct(codePathString)) { 18412 scanFlags |= SCAN_AS_PRODUCT; 18413 } 18414 18415 final File codePath = new File(codePathString); 18416 final PackageParser.Package pkg = 18417 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18418 18419 try { 18420 // update shared libraries for the newly re-installed system package 18421 updateSharedLibrariesLPr(pkg, null); 18422 } catch (PackageManagerException e) { 18423 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18424 } 18425 18426 prepareAppDataAfterInstallLIF(pkg); 18427 18428 // writer 18429 synchronized (mPackages) { 18430 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18431 18432 // Propagate the permissions state as we do not want to drop on the floor 18433 // runtime permissions. The update permissions method below will take 18434 // care of removing obsolete permissions and grant install permissions. 18435 if (origPermissionState != null) { 18436 ps.getPermissionsState().copyFrom(origPermissionState); 18437 } 18438 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18439 mPermissionCallback); 18440 18441 final boolean applyUserRestrictions 18442 = (allUserHandles != null) && (origUserHandles != null); 18443 if (applyUserRestrictions) { 18444 boolean installedStateChanged = false; 18445 if (DEBUG_REMOVE) { 18446 Slog.d(TAG, "Propagating install state across reinstall"); 18447 } 18448 for (int userId : allUserHandles) { 18449 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18450 if (DEBUG_REMOVE) { 18451 Slog.d(TAG, " user " + userId + " => " + installed); 18452 } 18453 if (installed != ps.getInstalled(userId)) { 18454 installedStateChanged = true; 18455 } 18456 ps.setInstalled(installed, userId); 18457 18458 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18459 } 18460 // Regardless of writeSettings we need to ensure that this restriction 18461 // state propagation is persisted 18462 mSettings.writeAllUsersPackageRestrictionsLPr(); 18463 if (installedStateChanged) { 18464 mSettings.writeKernelMappingLPr(ps); 18465 } 18466 } 18467 // can downgrade to reader here 18468 if (writeSettings) { 18469 mSettings.writeLPr(); 18470 } 18471 } 18472 return pkg; 18473 } 18474 18475 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18476 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18477 PackageRemovedInfo outInfo, boolean writeSettings, 18478 PackageParser.Package replacingPackage) { 18479 synchronized (mPackages) { 18480 if (outInfo != null) { 18481 outInfo.uid = ps.appId; 18482 } 18483 18484 if (outInfo != null && outInfo.removedChildPackages != null) { 18485 final int childCount = (ps.childPackageNames != null) 18486 ? ps.childPackageNames.size() : 0; 18487 for (int i = 0; i < childCount; i++) { 18488 String childPackageName = ps.childPackageNames.get(i); 18489 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18490 if (childPs == null) { 18491 return false; 18492 } 18493 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18494 childPackageName); 18495 if (childInfo != null) { 18496 childInfo.uid = childPs.appId; 18497 } 18498 } 18499 } 18500 } 18501 18502 // Delete package data from internal structures and also remove data if flag is set 18503 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18504 18505 // Delete the child packages data 18506 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18507 for (int i = 0; i < childCount; i++) { 18508 PackageSetting childPs; 18509 synchronized (mPackages) { 18510 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18511 } 18512 if (childPs != null) { 18513 PackageRemovedInfo childOutInfo = (outInfo != null 18514 && outInfo.removedChildPackages != null) 18515 ? outInfo.removedChildPackages.get(childPs.name) : null; 18516 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18517 && (replacingPackage != null 18518 && !replacingPackage.hasChildPackage(childPs.name)) 18519 ? flags & ~DELETE_KEEP_DATA : flags; 18520 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18521 deleteFlags, writeSettings); 18522 } 18523 } 18524 18525 // Delete application code and resources only for parent packages 18526 if (ps.parentPackageName == null) { 18527 if (deleteCodeAndResources && (outInfo != null)) { 18528 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18529 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18530 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18531 } 18532 } 18533 18534 return true; 18535 } 18536 18537 @Override 18538 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18539 int userId) { 18540 mContext.enforceCallingOrSelfPermission( 18541 android.Manifest.permission.DELETE_PACKAGES, null); 18542 synchronized (mPackages) { 18543 // Cannot block uninstall of static shared libs as they are 18544 // considered a part of the using app (emulating static linking). 18545 // Also static libs are installed always on internal storage. 18546 PackageParser.Package pkg = mPackages.get(packageName); 18547 if (pkg != null && pkg.staticSharedLibName != null) { 18548 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18549 + " providing static shared library: " + pkg.staticSharedLibName); 18550 return false; 18551 } 18552 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18553 mSettings.writePackageRestrictionsLPr(userId); 18554 } 18555 return true; 18556 } 18557 18558 @Override 18559 public boolean getBlockUninstallForUser(String packageName, int userId) { 18560 synchronized (mPackages) { 18561 final PackageSetting ps = mSettings.mPackages.get(packageName); 18562 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18563 return false; 18564 } 18565 return mSettings.getBlockUninstallLPr(userId, packageName); 18566 } 18567 } 18568 18569 @Override 18570 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18571 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18572 synchronized (mPackages) { 18573 PackageSetting ps = mSettings.mPackages.get(packageName); 18574 if (ps == null) { 18575 Log.w(TAG, "Package doesn't exist: " + packageName); 18576 return false; 18577 } 18578 if (systemUserApp) { 18579 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18580 } else { 18581 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18582 } 18583 mSettings.writeLPr(); 18584 } 18585 return true; 18586 } 18587 18588 /* 18589 * This method handles package deletion in general 18590 */ 18591 private boolean deletePackageLIF(String packageName, UserHandle user, 18592 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18593 PackageRemovedInfo outInfo, boolean writeSettings, 18594 PackageParser.Package replacingPackage) { 18595 if (packageName == null) { 18596 Slog.w(TAG, "Attempt to delete null packageName."); 18597 return false; 18598 } 18599 18600 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18601 18602 PackageSetting ps; 18603 synchronized (mPackages) { 18604 ps = mSettings.mPackages.get(packageName); 18605 if (ps == null) { 18606 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18607 return false; 18608 } 18609 18610 if (ps.parentPackageName != null && (!isSystemApp(ps) 18611 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18612 if (DEBUG_REMOVE) { 18613 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18614 + ((user == null) ? UserHandle.USER_ALL : user)); 18615 } 18616 final int removedUserId = (user != null) ? user.getIdentifier() 18617 : UserHandle.USER_ALL; 18618 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18619 return false; 18620 } 18621 markPackageUninstalledForUserLPw(ps, user); 18622 scheduleWritePackageRestrictionsLocked(user); 18623 return true; 18624 } 18625 } 18626 18627 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18628 && user.getIdentifier() != UserHandle.USER_ALL)) { 18629 // The caller is asking that the package only be deleted for a single 18630 // user. To do this, we just mark its uninstalled state and delete 18631 // its data. If this is a system app, we only allow this to happen if 18632 // they have set the special DELETE_SYSTEM_APP which requests different 18633 // semantics than normal for uninstalling system apps. 18634 markPackageUninstalledForUserLPw(ps, user); 18635 18636 if (!isSystemApp(ps)) { 18637 // Do not uninstall the APK if an app should be cached 18638 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18639 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18640 // Other user still have this package installed, so all 18641 // we need to do is clear this user's data and save that 18642 // it is uninstalled. 18643 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18644 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18645 return false; 18646 } 18647 scheduleWritePackageRestrictionsLocked(user); 18648 return true; 18649 } else { 18650 // We need to set it back to 'installed' so the uninstall 18651 // broadcasts will be sent correctly. 18652 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18653 ps.setInstalled(true, user.getIdentifier()); 18654 mSettings.writeKernelMappingLPr(ps); 18655 } 18656 } else { 18657 // This is a system app, so we assume that the 18658 // other users still have this package installed, so all 18659 // we need to do is clear this user's data and save that 18660 // it is uninstalled. 18661 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18662 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18663 return false; 18664 } 18665 scheduleWritePackageRestrictionsLocked(user); 18666 return true; 18667 } 18668 } 18669 18670 // If we are deleting a composite package for all users, keep track 18671 // of result for each child. 18672 if (ps.childPackageNames != null && outInfo != null) { 18673 synchronized (mPackages) { 18674 final int childCount = ps.childPackageNames.size(); 18675 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18676 for (int i = 0; i < childCount; i++) { 18677 String childPackageName = ps.childPackageNames.get(i); 18678 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18679 childInfo.removedPackage = childPackageName; 18680 childInfo.installerPackageName = ps.installerPackageName; 18681 outInfo.removedChildPackages.put(childPackageName, childInfo); 18682 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18683 if (childPs != null) { 18684 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18685 } 18686 } 18687 } 18688 } 18689 18690 boolean ret = false; 18691 if (isSystemApp(ps)) { 18692 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18693 // When an updated system application is deleted we delete the existing resources 18694 // as well and fall back to existing code in system partition 18695 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18696 } else { 18697 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18698 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18699 outInfo, writeSettings, replacingPackage); 18700 } 18701 18702 // Take a note whether we deleted the package for all users 18703 if (outInfo != null) { 18704 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18705 if (outInfo.removedChildPackages != null) { 18706 synchronized (mPackages) { 18707 final int childCount = outInfo.removedChildPackages.size(); 18708 for (int i = 0; i < childCount; i++) { 18709 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18710 if (childInfo != null) { 18711 childInfo.removedForAllUsers = mPackages.get( 18712 childInfo.removedPackage) == null; 18713 } 18714 } 18715 } 18716 } 18717 // If we uninstalled an update to a system app there may be some 18718 // child packages that appeared as they are declared in the system 18719 // app but were not declared in the update. 18720 if (isSystemApp(ps)) { 18721 synchronized (mPackages) { 18722 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18723 final int childCount = (updatedPs.childPackageNames != null) 18724 ? updatedPs.childPackageNames.size() : 0; 18725 for (int i = 0; i < childCount; i++) { 18726 String childPackageName = updatedPs.childPackageNames.get(i); 18727 if (outInfo.removedChildPackages == null 18728 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18729 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18730 if (childPs == null) { 18731 continue; 18732 } 18733 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18734 installRes.name = childPackageName; 18735 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18736 installRes.pkg = mPackages.get(childPackageName); 18737 installRes.uid = childPs.pkg.applicationInfo.uid; 18738 if (outInfo.appearedChildPackages == null) { 18739 outInfo.appearedChildPackages = new ArrayMap<>(); 18740 } 18741 outInfo.appearedChildPackages.put(childPackageName, installRes); 18742 } 18743 } 18744 } 18745 } 18746 } 18747 18748 return ret; 18749 } 18750 18751 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18752 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18753 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18754 for (int nextUserId : userIds) { 18755 if (DEBUG_REMOVE) { 18756 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18757 } 18758 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18759 false /*installed*/, 18760 true /*stopped*/, 18761 true /*notLaunched*/, 18762 false /*hidden*/, 18763 false /*suspended*/, 18764 false /*instantApp*/, 18765 false /*virtualPreload*/, 18766 null /*lastDisableAppCaller*/, 18767 null /*enabledComponents*/, 18768 null /*disabledComponents*/, 18769 ps.readUserState(nextUserId).domainVerificationStatus, 18770 0, PackageManager.INSTALL_REASON_UNKNOWN, 18771 null /*harmfulAppWarning*/); 18772 } 18773 mSettings.writeKernelMappingLPr(ps); 18774 } 18775 18776 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18777 PackageRemovedInfo outInfo) { 18778 final PackageParser.Package pkg; 18779 synchronized (mPackages) { 18780 pkg = mPackages.get(ps.name); 18781 } 18782 18783 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18784 : new int[] {userId}; 18785 for (int nextUserId : userIds) { 18786 if (DEBUG_REMOVE) { 18787 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18788 + nextUserId); 18789 } 18790 18791 destroyAppDataLIF(pkg, userId, 18792 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18793 destroyAppProfilesLIF(pkg, userId); 18794 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18795 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18796 schedulePackageCleaning(ps.name, nextUserId, false); 18797 synchronized (mPackages) { 18798 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18799 scheduleWritePackageRestrictionsLocked(nextUserId); 18800 } 18801 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18802 } 18803 } 18804 18805 if (outInfo != null) { 18806 outInfo.removedPackage = ps.name; 18807 outInfo.installerPackageName = ps.installerPackageName; 18808 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18809 outInfo.removedAppId = ps.appId; 18810 outInfo.removedUsers = userIds; 18811 outInfo.broadcastUsers = userIds; 18812 } 18813 18814 return true; 18815 } 18816 18817 private static final class ClearStorageConnection implements ServiceConnection { 18818 IMediaContainerService mContainerService; 18819 18820 @Override 18821 public void onServiceConnected(ComponentName name, IBinder service) { 18822 synchronized (this) { 18823 mContainerService = IMediaContainerService.Stub 18824 .asInterface(Binder.allowBlocking(service)); 18825 notifyAll(); 18826 } 18827 } 18828 18829 @Override 18830 public void onServiceDisconnected(ComponentName name) { 18831 } 18832 } 18833 18834 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18835 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18836 18837 final boolean mounted; 18838 if (Environment.isExternalStorageEmulated()) { 18839 mounted = true; 18840 } else { 18841 final String status = Environment.getExternalStorageState(); 18842 18843 mounted = status.equals(Environment.MEDIA_MOUNTED) 18844 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18845 } 18846 18847 if (!mounted) { 18848 return; 18849 } 18850 18851 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18852 int[] users; 18853 if (userId == UserHandle.USER_ALL) { 18854 users = sUserManager.getUserIds(); 18855 } else { 18856 users = new int[] { userId }; 18857 } 18858 final ClearStorageConnection conn = new ClearStorageConnection(); 18859 if (mContext.bindServiceAsUser( 18860 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18861 try { 18862 for (int curUser : users) { 18863 long timeout = SystemClock.uptimeMillis() + 5000; 18864 synchronized (conn) { 18865 long now; 18866 while (conn.mContainerService == null && 18867 (now = SystemClock.uptimeMillis()) < timeout) { 18868 try { 18869 conn.wait(timeout - now); 18870 } catch (InterruptedException e) { 18871 } 18872 } 18873 } 18874 if (conn.mContainerService == null) { 18875 return; 18876 } 18877 18878 final UserEnvironment userEnv = new UserEnvironment(curUser); 18879 clearDirectory(conn.mContainerService, 18880 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18881 if (allData) { 18882 clearDirectory(conn.mContainerService, 18883 userEnv.buildExternalStorageAppDataDirs(packageName)); 18884 clearDirectory(conn.mContainerService, 18885 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18886 } 18887 } 18888 } finally { 18889 mContext.unbindService(conn); 18890 } 18891 } 18892 } 18893 18894 @Override 18895 public void clearApplicationProfileData(String packageName) { 18896 enforceSystemOrRoot("Only the system can clear all profile data"); 18897 18898 final PackageParser.Package pkg; 18899 synchronized (mPackages) { 18900 pkg = mPackages.get(packageName); 18901 } 18902 18903 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18904 synchronized (mInstallLock) { 18905 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18906 } 18907 } 18908 } 18909 18910 @Override 18911 public void clearApplicationUserData(final String packageName, 18912 final IPackageDataObserver observer, final int userId) { 18913 mContext.enforceCallingOrSelfPermission( 18914 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18915 18916 final int callingUid = Binder.getCallingUid(); 18917 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18918 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18919 18920 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18921 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18922 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18923 throw new SecurityException("Cannot clear data for a protected package: " 18924 + packageName); 18925 } 18926 // Queue up an async operation since the package deletion may take a little while. 18927 mHandler.post(new Runnable() { 18928 public void run() { 18929 mHandler.removeCallbacks(this); 18930 final boolean succeeded; 18931 if (!filterApp) { 18932 try (PackageFreezer freezer = freezePackage(packageName, 18933 "clearApplicationUserData")) { 18934 synchronized (mInstallLock) { 18935 succeeded = clearApplicationUserDataLIF(packageName, userId); 18936 } 18937 clearExternalStorageDataSync(packageName, userId, true); 18938 synchronized (mPackages) { 18939 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18940 packageName, userId); 18941 } 18942 } 18943 if (succeeded) { 18944 // invoke DeviceStorageMonitor's update method to clear any notifications 18945 DeviceStorageMonitorInternal dsm = LocalServices 18946 .getService(DeviceStorageMonitorInternal.class); 18947 if (dsm != null) { 18948 dsm.checkMemory(); 18949 } 18950 } 18951 } else { 18952 succeeded = false; 18953 } 18954 if (observer != null) { 18955 try { 18956 observer.onRemoveCompleted(packageName, succeeded); 18957 } catch (RemoteException e) { 18958 Log.i(TAG, "Observer no longer exists."); 18959 } 18960 } //end if observer 18961 } //end run 18962 }); 18963 } 18964 18965 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18966 if (packageName == null) { 18967 Slog.w(TAG, "Attempt to delete null packageName."); 18968 return false; 18969 } 18970 18971 // Try finding details about the requested package 18972 PackageParser.Package pkg; 18973 synchronized (mPackages) { 18974 pkg = mPackages.get(packageName); 18975 if (pkg == null) { 18976 final PackageSetting ps = mSettings.mPackages.get(packageName); 18977 if (ps != null) { 18978 pkg = ps.pkg; 18979 } 18980 } 18981 18982 if (pkg == null) { 18983 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18984 return false; 18985 } 18986 18987 PackageSetting ps = (PackageSetting) pkg.mExtras; 18988 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18989 } 18990 18991 clearAppDataLIF(pkg, userId, 18992 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18993 18994 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18995 removeKeystoreDataIfNeeded(userId, appId); 18996 18997 UserManagerInternal umInternal = getUserManagerInternal(); 18998 final int flags; 18999 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19000 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19001 } else if (umInternal.isUserRunning(userId)) { 19002 flags = StorageManager.FLAG_STORAGE_DE; 19003 } else { 19004 flags = 0; 19005 } 19006 prepareAppDataContentsLIF(pkg, userId, flags); 19007 19008 return true; 19009 } 19010 19011 /** 19012 * Reverts user permission state changes (permissions and flags) in 19013 * all packages for a given user. 19014 * 19015 * @param userId The device user for which to do a reset. 19016 */ 19017 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19018 final int packageCount = mPackages.size(); 19019 for (int i = 0; i < packageCount; i++) { 19020 PackageParser.Package pkg = mPackages.valueAt(i); 19021 PackageSetting ps = (PackageSetting) pkg.mExtras; 19022 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19023 } 19024 } 19025 19026 private void resetNetworkPolicies(int userId) { 19027 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19028 } 19029 19030 /** 19031 * Reverts user permission state changes (permissions and flags). 19032 * 19033 * @param ps The package for which to reset. 19034 * @param userId The device user for which to do a reset. 19035 */ 19036 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19037 final PackageSetting ps, final int userId) { 19038 if (ps.pkg == null) { 19039 return; 19040 } 19041 19042 // These are flags that can change base on user actions. 19043 final int userSettableMask = FLAG_PERMISSION_USER_SET 19044 | FLAG_PERMISSION_USER_FIXED 19045 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19046 | FLAG_PERMISSION_REVIEW_REQUIRED; 19047 19048 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19049 | FLAG_PERMISSION_POLICY_FIXED; 19050 19051 boolean writeInstallPermissions = false; 19052 boolean writeRuntimePermissions = false; 19053 19054 final int permissionCount = ps.pkg.requestedPermissions.size(); 19055 for (int i = 0; i < permissionCount; i++) { 19056 final String permName = ps.pkg.requestedPermissions.get(i); 19057 final BasePermission bp = 19058 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19059 if (bp == null) { 19060 continue; 19061 } 19062 19063 // If shared user we just reset the state to which only this app contributed. 19064 if (ps.sharedUser != null) { 19065 boolean used = false; 19066 final int packageCount = ps.sharedUser.packages.size(); 19067 for (int j = 0; j < packageCount; j++) { 19068 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19069 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19070 && pkg.pkg.requestedPermissions.contains(permName)) { 19071 used = true; 19072 break; 19073 } 19074 } 19075 if (used) { 19076 continue; 19077 } 19078 } 19079 19080 final PermissionsState permissionsState = ps.getPermissionsState(); 19081 19082 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19083 19084 // Always clear the user settable flags. 19085 final boolean hasInstallState = 19086 permissionsState.getInstallPermissionState(permName) != null; 19087 // If permission review is enabled and this is a legacy app, mark the 19088 // permission as requiring a review as this is the initial state. 19089 int flags = 0; 19090 if (mSettings.mPermissions.mPermissionReviewRequired 19091 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19092 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19093 } 19094 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19095 if (hasInstallState) { 19096 writeInstallPermissions = true; 19097 } else { 19098 writeRuntimePermissions = true; 19099 } 19100 } 19101 19102 // Below is only runtime permission handling. 19103 if (!bp.isRuntime()) { 19104 continue; 19105 } 19106 19107 // Never clobber system or policy. 19108 if ((oldFlags & policyOrSystemFlags) != 0) { 19109 continue; 19110 } 19111 19112 // If this permission was granted by default, make sure it is. 19113 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19114 if (permissionsState.grantRuntimePermission(bp, userId) 19115 != PERMISSION_OPERATION_FAILURE) { 19116 writeRuntimePermissions = true; 19117 } 19118 // If permission review is enabled the permissions for a legacy apps 19119 // are represented as constantly granted runtime ones, so don't revoke. 19120 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19121 // Otherwise, reset the permission. 19122 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19123 switch (revokeResult) { 19124 case PERMISSION_OPERATION_SUCCESS: 19125 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19126 writeRuntimePermissions = true; 19127 final int appId = ps.appId; 19128 mHandler.post(new Runnable() { 19129 @Override 19130 public void run() { 19131 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19132 } 19133 }); 19134 } break; 19135 } 19136 } 19137 } 19138 19139 // Synchronously write as we are taking permissions away. 19140 if (writeRuntimePermissions) { 19141 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19142 } 19143 19144 // Synchronously write as we are taking permissions away. 19145 if (writeInstallPermissions) { 19146 mSettings.writeLPr(); 19147 } 19148 } 19149 19150 /** 19151 * Remove entries from the keystore daemon. Will only remove it if the 19152 * {@code appId} is valid. 19153 */ 19154 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19155 if (appId < 0) { 19156 return; 19157 } 19158 19159 final KeyStore keyStore = KeyStore.getInstance(); 19160 if (keyStore != null) { 19161 if (userId == UserHandle.USER_ALL) { 19162 for (final int individual : sUserManager.getUserIds()) { 19163 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19164 } 19165 } else { 19166 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19167 } 19168 } else { 19169 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19170 } 19171 } 19172 19173 @Override 19174 public void deleteApplicationCacheFiles(final String packageName, 19175 final IPackageDataObserver observer) { 19176 final int userId = UserHandle.getCallingUserId(); 19177 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19178 } 19179 19180 @Override 19181 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19182 final IPackageDataObserver observer) { 19183 final int callingUid = Binder.getCallingUid(); 19184 if (mContext.checkCallingOrSelfPermission( 19185 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19186 != PackageManager.PERMISSION_GRANTED) { 19187 // If the caller has the old delete cache permission, silently ignore. Else throw. 19188 if (mContext.checkCallingOrSelfPermission( 19189 android.Manifest.permission.DELETE_CACHE_FILES) 19190 == PackageManager.PERMISSION_GRANTED) { 19191 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19192 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19193 ", silently ignoring"); 19194 return; 19195 } 19196 mContext.enforceCallingOrSelfPermission( 19197 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19198 } 19199 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19200 /* requireFullPermission= */ true, /* checkShell= */ false, 19201 "delete application cache files"); 19202 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19203 android.Manifest.permission.ACCESS_INSTANT_APPS); 19204 19205 final PackageParser.Package pkg; 19206 synchronized (mPackages) { 19207 pkg = mPackages.get(packageName); 19208 } 19209 19210 // Queue up an async operation since the package deletion may take a little while. 19211 mHandler.post(new Runnable() { 19212 public void run() { 19213 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19214 boolean doClearData = true; 19215 if (ps != null) { 19216 final boolean targetIsInstantApp = 19217 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19218 doClearData = !targetIsInstantApp 19219 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19220 } 19221 if (doClearData) { 19222 synchronized (mInstallLock) { 19223 final int flags = StorageManager.FLAG_STORAGE_DE 19224 | StorageManager.FLAG_STORAGE_CE; 19225 // We're only clearing cache files, so we don't care if the 19226 // app is unfrozen and still able to run 19227 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19228 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19229 } 19230 clearExternalStorageDataSync(packageName, userId, false); 19231 } 19232 if (observer != null) { 19233 try { 19234 observer.onRemoveCompleted(packageName, true); 19235 } catch (RemoteException e) { 19236 Log.i(TAG, "Observer no longer exists."); 19237 } 19238 } 19239 } 19240 }); 19241 } 19242 19243 @Override 19244 public void getPackageSizeInfo(final String packageName, int userHandle, 19245 final IPackageStatsObserver observer) { 19246 throw new UnsupportedOperationException( 19247 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19248 } 19249 19250 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19251 final PackageSetting ps; 19252 synchronized (mPackages) { 19253 ps = mSettings.mPackages.get(packageName); 19254 if (ps == null) { 19255 Slog.w(TAG, "Failed to find settings for " + packageName); 19256 return false; 19257 } 19258 } 19259 19260 final String[] packageNames = { packageName }; 19261 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19262 final String[] codePaths = { ps.codePathString }; 19263 19264 try { 19265 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19266 ps.appId, ceDataInodes, codePaths, stats); 19267 19268 // For now, ignore code size of packages on system partition 19269 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19270 stats.codeSize = 0; 19271 } 19272 19273 // External clients expect these to be tracked separately 19274 stats.dataSize -= stats.cacheSize; 19275 19276 } catch (InstallerException e) { 19277 Slog.w(TAG, String.valueOf(e)); 19278 return false; 19279 } 19280 19281 return true; 19282 } 19283 19284 private int getUidTargetSdkVersionLockedLPr(int uid) { 19285 Object obj = mSettings.getUserIdLPr(uid); 19286 if (obj instanceof SharedUserSetting) { 19287 final SharedUserSetting sus = (SharedUserSetting) obj; 19288 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19289 final Iterator<PackageSetting> it = sus.packages.iterator(); 19290 while (it.hasNext()) { 19291 final PackageSetting ps = it.next(); 19292 if (ps.pkg != null) { 19293 int v = ps.pkg.applicationInfo.targetSdkVersion; 19294 if (v < vers) vers = v; 19295 } 19296 } 19297 return vers; 19298 } else if (obj instanceof PackageSetting) { 19299 final PackageSetting ps = (PackageSetting) obj; 19300 if (ps.pkg != null) { 19301 return ps.pkg.applicationInfo.targetSdkVersion; 19302 } 19303 } 19304 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19305 } 19306 19307 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19308 final PackageParser.Package p = mPackages.get(packageName); 19309 if (p != null) { 19310 return p.applicationInfo.targetSdkVersion; 19311 } 19312 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19313 } 19314 19315 @Override 19316 public void addPreferredActivity(IntentFilter filter, int match, 19317 ComponentName[] set, ComponentName activity, int userId) { 19318 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19319 "Adding preferred"); 19320 } 19321 19322 private void addPreferredActivityInternal(IntentFilter filter, int match, 19323 ComponentName[] set, ComponentName activity, boolean always, int userId, 19324 String opname) { 19325 // writer 19326 int callingUid = Binder.getCallingUid(); 19327 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19328 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19329 if (filter.countActions() == 0) { 19330 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19331 return; 19332 } 19333 synchronized (mPackages) { 19334 if (mContext.checkCallingOrSelfPermission( 19335 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19336 != PackageManager.PERMISSION_GRANTED) { 19337 if (getUidTargetSdkVersionLockedLPr(callingUid) 19338 < Build.VERSION_CODES.FROYO) { 19339 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19340 + callingUid); 19341 return; 19342 } 19343 mContext.enforceCallingOrSelfPermission( 19344 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19345 } 19346 19347 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19348 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19349 + userId + ":"); 19350 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19351 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19352 scheduleWritePackageRestrictionsLocked(userId); 19353 postPreferredActivityChangedBroadcast(userId); 19354 } 19355 } 19356 19357 private void postPreferredActivityChangedBroadcast(int userId) { 19358 mHandler.post(() -> { 19359 final IActivityManager am = ActivityManager.getService(); 19360 if (am == null) { 19361 return; 19362 } 19363 19364 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19365 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19366 try { 19367 am.broadcastIntent(null, intent, null, null, 19368 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19369 null, false, false, userId); 19370 } catch (RemoteException e) { 19371 } 19372 }); 19373 } 19374 19375 @Override 19376 public void replacePreferredActivity(IntentFilter filter, int match, 19377 ComponentName[] set, ComponentName activity, int userId) { 19378 if (filter.countActions() != 1) { 19379 throw new IllegalArgumentException( 19380 "replacePreferredActivity expects filter to have only 1 action."); 19381 } 19382 if (filter.countDataAuthorities() != 0 19383 || filter.countDataPaths() != 0 19384 || filter.countDataSchemes() > 1 19385 || filter.countDataTypes() != 0) { 19386 throw new IllegalArgumentException( 19387 "replacePreferredActivity expects filter to have no data authorities, " + 19388 "paths, or types; and at most one scheme."); 19389 } 19390 19391 final int callingUid = Binder.getCallingUid(); 19392 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19393 true /* requireFullPermission */, false /* checkShell */, 19394 "replace preferred activity"); 19395 synchronized (mPackages) { 19396 if (mContext.checkCallingOrSelfPermission( 19397 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19398 != PackageManager.PERMISSION_GRANTED) { 19399 if (getUidTargetSdkVersionLockedLPr(callingUid) 19400 < Build.VERSION_CODES.FROYO) { 19401 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19402 + Binder.getCallingUid()); 19403 return; 19404 } 19405 mContext.enforceCallingOrSelfPermission( 19406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19407 } 19408 19409 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19410 if (pir != null) { 19411 // Get all of the existing entries that exactly match this filter. 19412 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19413 if (existing != null && existing.size() == 1) { 19414 PreferredActivity cur = existing.get(0); 19415 if (DEBUG_PREFERRED) { 19416 Slog.i(TAG, "Checking replace of preferred:"); 19417 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19418 if (!cur.mPref.mAlways) { 19419 Slog.i(TAG, " -- CUR; not mAlways!"); 19420 } else { 19421 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19422 Slog.i(TAG, " -- CUR: mSet=" 19423 + Arrays.toString(cur.mPref.mSetComponents)); 19424 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19425 Slog.i(TAG, " -- NEW: mMatch=" 19426 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19427 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19428 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19429 } 19430 } 19431 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19432 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19433 && cur.mPref.sameSet(set)) { 19434 // Setting the preferred activity to what it happens to be already 19435 if (DEBUG_PREFERRED) { 19436 Slog.i(TAG, "Replacing with same preferred activity " 19437 + cur.mPref.mShortComponent + " for user " 19438 + userId + ":"); 19439 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19440 } 19441 return; 19442 } 19443 } 19444 19445 if (existing != null) { 19446 if (DEBUG_PREFERRED) { 19447 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19448 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19449 } 19450 for (int i = 0; i < existing.size(); i++) { 19451 PreferredActivity pa = existing.get(i); 19452 if (DEBUG_PREFERRED) { 19453 Slog.i(TAG, "Removing existing preferred activity " 19454 + pa.mPref.mComponent + ":"); 19455 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19456 } 19457 pir.removeFilter(pa); 19458 } 19459 } 19460 } 19461 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19462 "Replacing preferred"); 19463 } 19464 } 19465 19466 @Override 19467 public void clearPackagePreferredActivities(String packageName) { 19468 final int callingUid = Binder.getCallingUid(); 19469 if (getInstantAppPackageName(callingUid) != null) { 19470 return; 19471 } 19472 // writer 19473 synchronized (mPackages) { 19474 PackageParser.Package pkg = mPackages.get(packageName); 19475 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19476 if (mContext.checkCallingOrSelfPermission( 19477 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19478 != PackageManager.PERMISSION_GRANTED) { 19479 if (getUidTargetSdkVersionLockedLPr(callingUid) 19480 < Build.VERSION_CODES.FROYO) { 19481 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19482 + callingUid); 19483 return; 19484 } 19485 mContext.enforceCallingOrSelfPermission( 19486 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19487 } 19488 } 19489 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19490 if (ps != null 19491 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19492 return; 19493 } 19494 int user = UserHandle.getCallingUserId(); 19495 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19496 scheduleWritePackageRestrictionsLocked(user); 19497 } 19498 } 19499 } 19500 19501 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19502 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19503 ArrayList<PreferredActivity> removed = null; 19504 boolean changed = false; 19505 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19506 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19507 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19508 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19509 continue; 19510 } 19511 Iterator<PreferredActivity> it = pir.filterIterator(); 19512 while (it.hasNext()) { 19513 PreferredActivity pa = it.next(); 19514 // Mark entry for removal only if it matches the package name 19515 // and the entry is of type "always". 19516 if (packageName == null || 19517 (pa.mPref.mComponent.getPackageName().equals(packageName) 19518 && pa.mPref.mAlways)) { 19519 if (removed == null) { 19520 removed = new ArrayList<PreferredActivity>(); 19521 } 19522 removed.add(pa); 19523 } 19524 } 19525 if (removed != null) { 19526 for (int j=0; j<removed.size(); j++) { 19527 PreferredActivity pa = removed.get(j); 19528 pir.removeFilter(pa); 19529 } 19530 changed = true; 19531 } 19532 } 19533 if (changed) { 19534 postPreferredActivityChangedBroadcast(userId); 19535 } 19536 return changed; 19537 } 19538 19539 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19540 private void clearIntentFilterVerificationsLPw(int userId) { 19541 final int packageCount = mPackages.size(); 19542 for (int i = 0; i < packageCount; i++) { 19543 PackageParser.Package pkg = mPackages.valueAt(i); 19544 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19545 } 19546 } 19547 19548 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19549 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19550 if (userId == UserHandle.USER_ALL) { 19551 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19552 sUserManager.getUserIds())) { 19553 for (int oneUserId : sUserManager.getUserIds()) { 19554 scheduleWritePackageRestrictionsLocked(oneUserId); 19555 } 19556 } 19557 } else { 19558 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19559 scheduleWritePackageRestrictionsLocked(userId); 19560 } 19561 } 19562 } 19563 19564 /** Clears state for all users, and touches intent filter verification policy */ 19565 void clearDefaultBrowserIfNeeded(String packageName) { 19566 for (int oneUserId : sUserManager.getUserIds()) { 19567 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19568 } 19569 } 19570 19571 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19572 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19573 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19574 if (packageName.equals(defaultBrowserPackageName)) { 19575 setDefaultBrowserPackageName(null, userId); 19576 } 19577 } 19578 } 19579 19580 @Override 19581 public void resetApplicationPreferences(int userId) { 19582 mContext.enforceCallingOrSelfPermission( 19583 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19584 final long identity = Binder.clearCallingIdentity(); 19585 // writer 19586 try { 19587 synchronized (mPackages) { 19588 clearPackagePreferredActivitiesLPw(null, userId); 19589 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19590 // TODO: We have to reset the default SMS and Phone. This requires 19591 // significant refactoring to keep all default apps in the package 19592 // manager (cleaner but more work) or have the services provide 19593 // callbacks to the package manager to request a default app reset. 19594 applyFactoryDefaultBrowserLPw(userId); 19595 clearIntentFilterVerificationsLPw(userId); 19596 primeDomainVerificationsLPw(userId); 19597 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19598 scheduleWritePackageRestrictionsLocked(userId); 19599 } 19600 resetNetworkPolicies(userId); 19601 } finally { 19602 Binder.restoreCallingIdentity(identity); 19603 } 19604 } 19605 19606 @Override 19607 public int getPreferredActivities(List<IntentFilter> outFilters, 19608 List<ComponentName> outActivities, String packageName) { 19609 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19610 return 0; 19611 } 19612 int num = 0; 19613 final int userId = UserHandle.getCallingUserId(); 19614 // reader 19615 synchronized (mPackages) { 19616 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19617 if (pir != null) { 19618 final Iterator<PreferredActivity> it = pir.filterIterator(); 19619 while (it.hasNext()) { 19620 final PreferredActivity pa = it.next(); 19621 if (packageName == null 19622 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19623 && pa.mPref.mAlways)) { 19624 if (outFilters != null) { 19625 outFilters.add(new IntentFilter(pa)); 19626 } 19627 if (outActivities != null) { 19628 outActivities.add(pa.mPref.mComponent); 19629 } 19630 } 19631 } 19632 } 19633 } 19634 19635 return num; 19636 } 19637 19638 @Override 19639 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19640 int userId) { 19641 int callingUid = Binder.getCallingUid(); 19642 if (callingUid != Process.SYSTEM_UID) { 19643 throw new SecurityException( 19644 "addPersistentPreferredActivity can only be run by the system"); 19645 } 19646 if (filter.countActions() == 0) { 19647 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19648 return; 19649 } 19650 synchronized (mPackages) { 19651 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19652 ":"); 19653 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19654 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19655 new PersistentPreferredActivity(filter, activity)); 19656 scheduleWritePackageRestrictionsLocked(userId); 19657 postPreferredActivityChangedBroadcast(userId); 19658 } 19659 } 19660 19661 @Override 19662 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19663 int callingUid = Binder.getCallingUid(); 19664 if (callingUid != Process.SYSTEM_UID) { 19665 throw new SecurityException( 19666 "clearPackagePersistentPreferredActivities can only be run by the system"); 19667 } 19668 ArrayList<PersistentPreferredActivity> removed = null; 19669 boolean changed = false; 19670 synchronized (mPackages) { 19671 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19672 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19673 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19674 .valueAt(i); 19675 if (userId != thisUserId) { 19676 continue; 19677 } 19678 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19679 while (it.hasNext()) { 19680 PersistentPreferredActivity ppa = it.next(); 19681 // Mark entry for removal only if it matches the package name. 19682 if (ppa.mComponent.getPackageName().equals(packageName)) { 19683 if (removed == null) { 19684 removed = new ArrayList<PersistentPreferredActivity>(); 19685 } 19686 removed.add(ppa); 19687 } 19688 } 19689 if (removed != null) { 19690 for (int j=0; j<removed.size(); j++) { 19691 PersistentPreferredActivity ppa = removed.get(j); 19692 ppir.removeFilter(ppa); 19693 } 19694 changed = true; 19695 } 19696 } 19697 19698 if (changed) { 19699 scheduleWritePackageRestrictionsLocked(userId); 19700 postPreferredActivityChangedBroadcast(userId); 19701 } 19702 } 19703 } 19704 19705 /** 19706 * Common machinery for picking apart a restored XML blob and passing 19707 * it to a caller-supplied functor to be applied to the running system. 19708 */ 19709 private void restoreFromXml(XmlPullParser parser, int userId, 19710 String expectedStartTag, BlobXmlRestorer functor) 19711 throws IOException, XmlPullParserException { 19712 int type; 19713 while ((type = parser.next()) != XmlPullParser.START_TAG 19714 && type != XmlPullParser.END_DOCUMENT) { 19715 } 19716 if (type != XmlPullParser.START_TAG) { 19717 // oops didn't find a start tag?! 19718 if (DEBUG_BACKUP) { 19719 Slog.e(TAG, "Didn't find start tag during restore"); 19720 } 19721 return; 19722 } 19723Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19724 // this is supposed to be TAG_PREFERRED_BACKUP 19725 if (!expectedStartTag.equals(parser.getName())) { 19726 if (DEBUG_BACKUP) { 19727 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19728 } 19729 return; 19730 } 19731 19732 // skip interfering stuff, then we're aligned with the backing implementation 19733 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19734Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19735 functor.apply(parser, userId); 19736 } 19737 19738 private interface BlobXmlRestorer { 19739 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19740 } 19741 19742 /** 19743 * Non-Binder method, support for the backup/restore mechanism: write the 19744 * full set of preferred activities in its canonical XML format. Returns the 19745 * XML output as a byte array, or null if there is none. 19746 */ 19747 @Override 19748 public byte[] getPreferredActivityBackup(int userId) { 19749 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19750 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19751 } 19752 19753 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19754 try { 19755 final XmlSerializer serializer = new FastXmlSerializer(); 19756 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19757 serializer.startDocument(null, true); 19758 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19759 19760 synchronized (mPackages) { 19761 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19762 } 19763 19764 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19765 serializer.endDocument(); 19766 serializer.flush(); 19767 } catch (Exception e) { 19768 if (DEBUG_BACKUP) { 19769 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19770 } 19771 return null; 19772 } 19773 19774 return dataStream.toByteArray(); 19775 } 19776 19777 @Override 19778 public void restorePreferredActivities(byte[] backup, int userId) { 19779 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19780 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19781 } 19782 19783 try { 19784 final XmlPullParser parser = Xml.newPullParser(); 19785 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19786 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19787 new BlobXmlRestorer() { 19788 @Override 19789 public void apply(XmlPullParser parser, int userId) 19790 throws XmlPullParserException, IOException { 19791 synchronized (mPackages) { 19792 mSettings.readPreferredActivitiesLPw(parser, userId); 19793 } 19794 } 19795 } ); 19796 } catch (Exception e) { 19797 if (DEBUG_BACKUP) { 19798 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19799 } 19800 } 19801 } 19802 19803 /** 19804 * Non-Binder method, support for the backup/restore mechanism: write the 19805 * default browser (etc) settings in its canonical XML format. Returns the default 19806 * browser XML representation as a byte array, or null if there is none. 19807 */ 19808 @Override 19809 public byte[] getDefaultAppsBackup(int userId) { 19810 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19811 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19812 } 19813 19814 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19815 try { 19816 final XmlSerializer serializer = new FastXmlSerializer(); 19817 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19818 serializer.startDocument(null, true); 19819 serializer.startTag(null, TAG_DEFAULT_APPS); 19820 19821 synchronized (mPackages) { 19822 mSettings.writeDefaultAppsLPr(serializer, userId); 19823 } 19824 19825 serializer.endTag(null, TAG_DEFAULT_APPS); 19826 serializer.endDocument(); 19827 serializer.flush(); 19828 } catch (Exception e) { 19829 if (DEBUG_BACKUP) { 19830 Slog.e(TAG, "Unable to write default apps for backup", e); 19831 } 19832 return null; 19833 } 19834 19835 return dataStream.toByteArray(); 19836 } 19837 19838 @Override 19839 public void restoreDefaultApps(byte[] backup, int userId) { 19840 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19841 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19842 } 19843 19844 try { 19845 final XmlPullParser parser = Xml.newPullParser(); 19846 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19847 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19848 new BlobXmlRestorer() { 19849 @Override 19850 public void apply(XmlPullParser parser, int userId) 19851 throws XmlPullParserException, IOException { 19852 synchronized (mPackages) { 19853 mSettings.readDefaultAppsLPw(parser, userId); 19854 } 19855 } 19856 } ); 19857 } catch (Exception e) { 19858 if (DEBUG_BACKUP) { 19859 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19860 } 19861 } 19862 } 19863 19864 @Override 19865 public byte[] getIntentFilterVerificationBackup(int userId) { 19866 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19867 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19868 } 19869 19870 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19871 try { 19872 final XmlSerializer serializer = new FastXmlSerializer(); 19873 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19874 serializer.startDocument(null, true); 19875 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19876 19877 synchronized (mPackages) { 19878 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19879 } 19880 19881 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19882 serializer.endDocument(); 19883 serializer.flush(); 19884 } catch (Exception e) { 19885 if (DEBUG_BACKUP) { 19886 Slog.e(TAG, "Unable to write default apps for backup", e); 19887 } 19888 return null; 19889 } 19890 19891 return dataStream.toByteArray(); 19892 } 19893 19894 @Override 19895 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19896 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19897 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19898 } 19899 19900 try { 19901 final XmlPullParser parser = Xml.newPullParser(); 19902 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19903 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19904 new BlobXmlRestorer() { 19905 @Override 19906 public void apply(XmlPullParser parser, int userId) 19907 throws XmlPullParserException, IOException { 19908 synchronized (mPackages) { 19909 mSettings.readAllDomainVerificationsLPr(parser, userId); 19910 mSettings.writeLPr(); 19911 } 19912 } 19913 } ); 19914 } catch (Exception e) { 19915 if (DEBUG_BACKUP) { 19916 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19917 } 19918 } 19919 } 19920 19921 @Override 19922 public byte[] getPermissionGrantBackup(int userId) { 19923 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19924 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19925 } 19926 19927 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19928 try { 19929 final XmlSerializer serializer = new FastXmlSerializer(); 19930 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19931 serializer.startDocument(null, true); 19932 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19933 19934 synchronized (mPackages) { 19935 serializeRuntimePermissionGrantsLPr(serializer, userId); 19936 } 19937 19938 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19939 serializer.endDocument(); 19940 serializer.flush(); 19941 } catch (Exception e) { 19942 if (DEBUG_BACKUP) { 19943 Slog.e(TAG, "Unable to write default apps for backup", e); 19944 } 19945 return null; 19946 } 19947 19948 return dataStream.toByteArray(); 19949 } 19950 19951 @Override 19952 public void restorePermissionGrants(byte[] backup, int userId) { 19953 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19954 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19955 } 19956 19957 try { 19958 final XmlPullParser parser = Xml.newPullParser(); 19959 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19960 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19961 new BlobXmlRestorer() { 19962 @Override 19963 public void apply(XmlPullParser parser, int userId) 19964 throws XmlPullParserException, IOException { 19965 synchronized (mPackages) { 19966 processRestoredPermissionGrantsLPr(parser, userId); 19967 } 19968 } 19969 } ); 19970 } catch (Exception e) { 19971 if (DEBUG_BACKUP) { 19972 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19973 } 19974 } 19975 } 19976 19977 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19978 throws IOException { 19979 serializer.startTag(null, TAG_ALL_GRANTS); 19980 19981 final int N = mSettings.mPackages.size(); 19982 for (int i = 0; i < N; i++) { 19983 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19984 boolean pkgGrantsKnown = false; 19985 19986 PermissionsState packagePerms = ps.getPermissionsState(); 19987 19988 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19989 final int grantFlags = state.getFlags(); 19990 // only look at grants that are not system/policy fixed 19991 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19992 final boolean isGranted = state.isGranted(); 19993 // And only back up the user-twiddled state bits 19994 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19995 final String packageName = mSettings.mPackages.keyAt(i); 19996 if (!pkgGrantsKnown) { 19997 serializer.startTag(null, TAG_GRANT); 19998 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19999 pkgGrantsKnown = true; 20000 } 20001 20002 final boolean userSet = 20003 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20004 final boolean userFixed = 20005 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20006 final boolean revoke = 20007 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20008 20009 serializer.startTag(null, TAG_PERMISSION); 20010 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20011 if (isGranted) { 20012 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20013 } 20014 if (userSet) { 20015 serializer.attribute(null, ATTR_USER_SET, "true"); 20016 } 20017 if (userFixed) { 20018 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20019 } 20020 if (revoke) { 20021 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20022 } 20023 serializer.endTag(null, TAG_PERMISSION); 20024 } 20025 } 20026 } 20027 20028 if (pkgGrantsKnown) { 20029 serializer.endTag(null, TAG_GRANT); 20030 } 20031 } 20032 20033 serializer.endTag(null, TAG_ALL_GRANTS); 20034 } 20035 20036 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20037 throws XmlPullParserException, IOException { 20038 String pkgName = null; 20039 int outerDepth = parser.getDepth(); 20040 int type; 20041 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20042 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20043 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20044 continue; 20045 } 20046 20047 final String tagName = parser.getName(); 20048 if (tagName.equals(TAG_GRANT)) { 20049 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20050 if (DEBUG_BACKUP) { 20051 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20052 } 20053 } else if (tagName.equals(TAG_PERMISSION)) { 20054 20055 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20056 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20057 20058 int newFlagSet = 0; 20059 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20060 newFlagSet |= FLAG_PERMISSION_USER_SET; 20061 } 20062 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20063 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20064 } 20065 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20066 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20067 } 20068 if (DEBUG_BACKUP) { 20069 Slog.v(TAG, " + Restoring grant:" 20070 + " pkg=" + pkgName 20071 + " perm=" + permName 20072 + " granted=" + isGranted 20073 + " bits=0x" + Integer.toHexString(newFlagSet)); 20074 } 20075 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20076 if (ps != null) { 20077 // Already installed so we apply the grant immediately 20078 if (DEBUG_BACKUP) { 20079 Slog.v(TAG, " + already installed; applying"); 20080 } 20081 PermissionsState perms = ps.getPermissionsState(); 20082 BasePermission bp = 20083 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20084 if (bp != null) { 20085 if (isGranted) { 20086 perms.grantRuntimePermission(bp, userId); 20087 } 20088 if (newFlagSet != 0) { 20089 perms.updatePermissionFlags( 20090 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20091 } 20092 } 20093 } else { 20094 // Need to wait for post-restore install to apply the grant 20095 if (DEBUG_BACKUP) { 20096 Slog.v(TAG, " - not yet installed; saving for later"); 20097 } 20098 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20099 isGranted, newFlagSet, userId); 20100 } 20101 } else { 20102 PackageManagerService.reportSettingsProblem(Log.WARN, 20103 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20104 XmlUtils.skipCurrentTag(parser); 20105 } 20106 } 20107 20108 scheduleWriteSettingsLocked(); 20109 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20110 } 20111 20112 @Override 20113 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20114 int sourceUserId, int targetUserId, int flags) { 20115 mContext.enforceCallingOrSelfPermission( 20116 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20117 int callingUid = Binder.getCallingUid(); 20118 enforceOwnerRights(ownerPackage, callingUid); 20119 PackageManagerServiceUtils.enforceShellRestriction( 20120 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20121 if (intentFilter.countActions() == 0) { 20122 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20123 return; 20124 } 20125 synchronized (mPackages) { 20126 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20127 ownerPackage, targetUserId, flags); 20128 CrossProfileIntentResolver resolver = 20129 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20130 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20131 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20132 if (existing != null) { 20133 int size = existing.size(); 20134 for (int i = 0; i < size; i++) { 20135 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20136 return; 20137 } 20138 } 20139 } 20140 resolver.addFilter(newFilter); 20141 scheduleWritePackageRestrictionsLocked(sourceUserId); 20142 } 20143 } 20144 20145 @Override 20146 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20147 mContext.enforceCallingOrSelfPermission( 20148 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20149 final int callingUid = Binder.getCallingUid(); 20150 enforceOwnerRights(ownerPackage, callingUid); 20151 PackageManagerServiceUtils.enforceShellRestriction( 20152 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20153 synchronized (mPackages) { 20154 CrossProfileIntentResolver resolver = 20155 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20156 ArraySet<CrossProfileIntentFilter> set = 20157 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20158 for (CrossProfileIntentFilter filter : set) { 20159 if (filter.getOwnerPackage().equals(ownerPackage)) { 20160 resolver.removeFilter(filter); 20161 } 20162 } 20163 scheduleWritePackageRestrictionsLocked(sourceUserId); 20164 } 20165 } 20166 20167 // Enforcing that callingUid is owning pkg on userId 20168 private void enforceOwnerRights(String pkg, int callingUid) { 20169 // The system owns everything. 20170 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20171 return; 20172 } 20173 final int callingUserId = UserHandle.getUserId(callingUid); 20174 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20175 if (pi == null) { 20176 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20177 + callingUserId); 20178 } 20179 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20180 throw new SecurityException("Calling uid " + callingUid 20181 + " does not own package " + pkg); 20182 } 20183 } 20184 20185 @Override 20186 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20187 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20188 return null; 20189 } 20190 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20191 } 20192 20193 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20194 UserManagerService ums = UserManagerService.getInstance(); 20195 if (ums != null) { 20196 final UserInfo parent = ums.getProfileParent(userId); 20197 final int launcherUid = (parent != null) ? parent.id : userId; 20198 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20199 if (launcherComponent != null) { 20200 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20201 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20202 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20203 .setPackage(launcherComponent.getPackageName()); 20204 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20205 } 20206 } 20207 } 20208 20209 /** 20210 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20211 * then reports the most likely home activity or null if there are more than one. 20212 */ 20213 private ComponentName getDefaultHomeActivity(int userId) { 20214 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20215 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20216 if (cn != null) { 20217 return cn; 20218 } 20219 20220 // Find the launcher with the highest priority and return that component if there are no 20221 // other home activity with the same priority. 20222 int lastPriority = Integer.MIN_VALUE; 20223 ComponentName lastComponent = null; 20224 final int size = allHomeCandidates.size(); 20225 for (int i = 0; i < size; i++) { 20226 final ResolveInfo ri = allHomeCandidates.get(i); 20227 if (ri.priority > lastPriority) { 20228 lastComponent = ri.activityInfo.getComponentName(); 20229 lastPriority = ri.priority; 20230 } else if (ri.priority == lastPriority) { 20231 // Two components found with same priority. 20232 lastComponent = null; 20233 } 20234 } 20235 return lastComponent; 20236 } 20237 20238 private Intent getHomeIntent() { 20239 Intent intent = new Intent(Intent.ACTION_MAIN); 20240 intent.addCategory(Intent.CATEGORY_HOME); 20241 intent.addCategory(Intent.CATEGORY_DEFAULT); 20242 return intent; 20243 } 20244 20245 private IntentFilter getHomeFilter() { 20246 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20247 filter.addCategory(Intent.CATEGORY_HOME); 20248 filter.addCategory(Intent.CATEGORY_DEFAULT); 20249 return filter; 20250 } 20251 20252 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20253 int userId) { 20254 Intent intent = getHomeIntent(); 20255 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20256 PackageManager.GET_META_DATA, userId); 20257 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20258 true, false, false, userId); 20259 20260 allHomeCandidates.clear(); 20261 if (list != null) { 20262 for (ResolveInfo ri : list) { 20263 allHomeCandidates.add(ri); 20264 } 20265 } 20266 return (preferred == null || preferred.activityInfo == null) 20267 ? null 20268 : new ComponentName(preferred.activityInfo.packageName, 20269 preferred.activityInfo.name); 20270 } 20271 20272 @Override 20273 public void setHomeActivity(ComponentName comp, int userId) { 20274 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20275 return; 20276 } 20277 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20278 getHomeActivitiesAsUser(homeActivities, userId); 20279 20280 boolean found = false; 20281 20282 final int size = homeActivities.size(); 20283 final ComponentName[] set = new ComponentName[size]; 20284 for (int i = 0; i < size; i++) { 20285 final ResolveInfo candidate = homeActivities.get(i); 20286 final ActivityInfo info = candidate.activityInfo; 20287 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20288 set[i] = activityName; 20289 if (!found && activityName.equals(comp)) { 20290 found = true; 20291 } 20292 } 20293 if (!found) { 20294 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20295 + userId); 20296 } 20297 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20298 set, comp, userId); 20299 } 20300 20301 private @Nullable String getSetupWizardPackageName() { 20302 final Intent intent = new Intent(Intent.ACTION_MAIN); 20303 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20304 20305 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20306 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20307 | MATCH_DISABLED_COMPONENTS, 20308 UserHandle.myUserId()); 20309 if (matches.size() == 1) { 20310 return matches.get(0).getComponentInfo().packageName; 20311 } else { 20312 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20313 + ": matches=" + matches); 20314 return null; 20315 } 20316 } 20317 20318 private @Nullable String getStorageManagerPackageName() { 20319 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20320 20321 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20322 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20323 | MATCH_DISABLED_COMPONENTS, 20324 UserHandle.myUserId()); 20325 if (matches.size() == 1) { 20326 return matches.get(0).getComponentInfo().packageName; 20327 } else { 20328 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20329 + matches.size() + ": matches=" + matches); 20330 return null; 20331 } 20332 } 20333 20334 @Override 20335 public String getSystemTextClassifierPackageName() { 20336 return mContext.getString(R.string.config_defaultTextClassifierPackage); 20337 } 20338 20339 @Override 20340 public void setApplicationEnabledSetting(String appPackageName, 20341 int newState, int flags, int userId, String callingPackage) { 20342 if (!sUserManager.exists(userId)) return; 20343 if (callingPackage == null) { 20344 callingPackage = Integer.toString(Binder.getCallingUid()); 20345 } 20346 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20347 } 20348 20349 @Override 20350 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20352 synchronized (mPackages) { 20353 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20354 if (pkgSetting != null) { 20355 pkgSetting.setUpdateAvailable(updateAvailable); 20356 } 20357 } 20358 } 20359 20360 @Override 20361 public void setComponentEnabledSetting(ComponentName componentName, 20362 int newState, int flags, int userId) { 20363 if (!sUserManager.exists(userId)) return; 20364 setEnabledSetting(componentName.getPackageName(), 20365 componentName.getClassName(), newState, flags, userId, null); 20366 } 20367 20368 private void setEnabledSetting(final String packageName, String className, int newState, 20369 final int flags, int userId, String callingPackage) { 20370 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20371 || newState == COMPONENT_ENABLED_STATE_ENABLED 20372 || newState == COMPONENT_ENABLED_STATE_DISABLED 20373 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20374 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20375 throw new IllegalArgumentException("Invalid new component state: " 20376 + newState); 20377 } 20378 PackageSetting pkgSetting; 20379 final int callingUid = Binder.getCallingUid(); 20380 final int permission; 20381 if (callingUid == Process.SYSTEM_UID) { 20382 permission = PackageManager.PERMISSION_GRANTED; 20383 } else { 20384 permission = mContext.checkCallingOrSelfPermission( 20385 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20386 } 20387 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20388 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20389 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20390 boolean sendNow = false; 20391 boolean isApp = (className == null); 20392 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20393 String componentName = isApp ? packageName : className; 20394 int packageUid = -1; 20395 ArrayList<String> components; 20396 20397 // reader 20398 synchronized (mPackages) { 20399 pkgSetting = mSettings.mPackages.get(packageName); 20400 if (pkgSetting == null) { 20401 if (!isCallerInstantApp) { 20402 if (className == null) { 20403 throw new IllegalArgumentException("Unknown package: " + packageName); 20404 } 20405 throw new IllegalArgumentException( 20406 "Unknown component: " + packageName + "/" + className); 20407 } else { 20408 // throw SecurityException to prevent leaking package information 20409 throw new SecurityException( 20410 "Attempt to change component state; " 20411 + "pid=" + Binder.getCallingPid() 20412 + ", uid=" + callingUid 20413 + (className == null 20414 ? ", package=" + packageName 20415 : ", component=" + packageName + "/" + className)); 20416 } 20417 } 20418 } 20419 20420 // Limit who can change which apps 20421 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20422 // Don't allow apps that don't have permission to modify other apps 20423 if (!allowedByPermission 20424 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20425 throw new SecurityException( 20426 "Attempt to change component state; " 20427 + "pid=" + Binder.getCallingPid() 20428 + ", uid=" + callingUid 20429 + (className == null 20430 ? ", package=" + packageName 20431 : ", component=" + packageName + "/" + className)); 20432 } 20433 // Don't allow changing protected packages. 20434 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20435 throw new SecurityException("Cannot disable a protected package: " + packageName); 20436 } 20437 } 20438 20439 synchronized (mPackages) { 20440 if (callingUid == Process.SHELL_UID 20441 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20442 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20443 // unless it is a test package. 20444 int oldState = pkgSetting.getEnabled(userId); 20445 if (className == null 20446 && 20447 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20448 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20449 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20450 && 20451 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20452 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20453 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20454 // ok 20455 } else { 20456 throw new SecurityException( 20457 "Shell cannot change component state for " + packageName + "/" 20458 + className + " to " + newState); 20459 } 20460 } 20461 } 20462 if (className == null) { 20463 // We're dealing with an application/package level state change 20464 synchronized (mPackages) { 20465 if (pkgSetting.getEnabled(userId) == newState) { 20466 // Nothing to do 20467 return; 20468 } 20469 } 20470 // If we're enabling a system stub, there's a little more work to do. 20471 // Prior to enabling the package, we need to decompress the APK(s) to the 20472 // data partition and then replace the version on the system partition. 20473 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20474 final boolean isSystemStub = deletedPkg.isStub 20475 && deletedPkg.isSystem(); 20476 if (isSystemStub 20477 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20478 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20479 final File codePath = decompressPackage(deletedPkg); 20480 if (codePath == null) { 20481 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20482 return; 20483 } 20484 // TODO remove direct parsing of the package object during internal cleanup 20485 // of scan package 20486 // We need to call parse directly here for no other reason than we need 20487 // the new package in order to disable the old one [we use the information 20488 // for some internal optimization to optionally create a new package setting 20489 // object on replace]. However, we can't get the package from the scan 20490 // because the scan modifies live structures and we need to remove the 20491 // old [system] package from the system before a scan can be attempted. 20492 // Once scan is indempotent we can remove this parse and use the package 20493 // object we scanned, prior to adding it to package settings. 20494 final PackageParser pp = new PackageParser(); 20495 pp.setSeparateProcesses(mSeparateProcesses); 20496 pp.setDisplayMetrics(mMetrics); 20497 pp.setCallback(mPackageParserCallback); 20498 final PackageParser.Package tmpPkg; 20499 try { 20500 final @ParseFlags int parseFlags = mDefParseFlags 20501 | PackageParser.PARSE_MUST_BE_APK 20502 | PackageParser.PARSE_IS_SYSTEM_DIR; 20503 tmpPkg = pp.parsePackage(codePath, parseFlags); 20504 } catch (PackageParserException e) { 20505 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20506 return; 20507 } 20508 synchronized (mInstallLock) { 20509 // Disable the stub and remove any package entries 20510 removePackageLI(deletedPkg, true); 20511 synchronized (mPackages) { 20512 disableSystemPackageLPw(deletedPkg, tmpPkg); 20513 } 20514 final PackageParser.Package pkg; 20515 try (PackageFreezer freezer = 20516 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20517 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20518 | PackageParser.PARSE_ENFORCE_CODE; 20519 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20520 0 /*currentTime*/, null /*user*/); 20521 prepareAppDataAfterInstallLIF(pkg); 20522 synchronized (mPackages) { 20523 try { 20524 updateSharedLibrariesLPr(pkg, null); 20525 } catch (PackageManagerException e) { 20526 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20527 } 20528 mPermissionManager.updatePermissions( 20529 pkg.packageName, pkg, true, mPackages.values(), 20530 mPermissionCallback); 20531 mSettings.writeLPr(); 20532 } 20533 } catch (PackageManagerException e) { 20534 // Whoops! Something went wrong; try to roll back to the stub 20535 Slog.w(TAG, "Failed to install compressed system package:" 20536 + pkgSetting.name, e); 20537 // Remove the failed install 20538 removeCodePathLI(codePath); 20539 20540 // Install the system package 20541 try (PackageFreezer freezer = 20542 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20543 synchronized (mPackages) { 20544 // NOTE: The system package always needs to be enabled; even 20545 // if it's for a compressed stub. If we don't, installing the 20546 // system package fails during scan [scanning checks the disabled 20547 // packages]. We will reverse this later, after we've "installed" 20548 // the stub. 20549 // This leaves us in a fragile state; the stub should never be 20550 // enabled, so, cross your fingers and hope nothing goes wrong 20551 // until we can disable the package later. 20552 enableSystemPackageLPw(deletedPkg); 20553 } 20554 installPackageFromSystemLIF(deletedPkg.codePath, 20555 false /*isPrivileged*/, null /*allUserHandles*/, 20556 null /*origUserHandles*/, null /*origPermissionsState*/, 20557 true /*writeSettings*/); 20558 } catch (PackageManagerException pme) { 20559 Slog.w(TAG, "Failed to restore system package:" 20560 + deletedPkg.packageName, pme); 20561 } finally { 20562 synchronized (mPackages) { 20563 mSettings.disableSystemPackageLPw( 20564 deletedPkg.packageName, true /*replaced*/); 20565 mSettings.writeLPr(); 20566 } 20567 } 20568 return; 20569 } 20570 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20571 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20572 mDexManager.notifyPackageUpdated(pkg.packageName, 20573 pkg.baseCodePath, pkg.splitCodePaths); 20574 } 20575 } 20576 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20577 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20578 // Don't care about who enables an app. 20579 callingPackage = null; 20580 } 20581 synchronized (mPackages) { 20582 pkgSetting.setEnabled(newState, userId, callingPackage); 20583 } 20584 } else { 20585 synchronized (mPackages) { 20586 // We're dealing with a component level state change 20587 // First, verify that this is a valid class name. 20588 PackageParser.Package pkg = pkgSetting.pkg; 20589 if (pkg == null || !pkg.hasComponentClassName(className)) { 20590 if (pkg != null && 20591 pkg.applicationInfo.targetSdkVersion >= 20592 Build.VERSION_CODES.JELLY_BEAN) { 20593 throw new IllegalArgumentException("Component class " + className 20594 + " does not exist in " + packageName); 20595 } else { 20596 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20597 + className + " does not exist in " + packageName); 20598 } 20599 } 20600 switch (newState) { 20601 case COMPONENT_ENABLED_STATE_ENABLED: 20602 if (!pkgSetting.enableComponentLPw(className, userId)) { 20603 return; 20604 } 20605 break; 20606 case COMPONENT_ENABLED_STATE_DISABLED: 20607 if (!pkgSetting.disableComponentLPw(className, userId)) { 20608 return; 20609 } 20610 break; 20611 case COMPONENT_ENABLED_STATE_DEFAULT: 20612 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20613 return; 20614 } 20615 break; 20616 default: 20617 Slog.e(TAG, "Invalid new component state: " + newState); 20618 return; 20619 } 20620 } 20621 } 20622 synchronized (mPackages) { 20623 scheduleWritePackageRestrictionsLocked(userId); 20624 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20625 final long callingId = Binder.clearCallingIdentity(); 20626 try { 20627 updateInstantAppInstallerLocked(packageName); 20628 } finally { 20629 Binder.restoreCallingIdentity(callingId); 20630 } 20631 components = mPendingBroadcasts.get(userId, packageName); 20632 final boolean newPackage = components == null; 20633 if (newPackage) { 20634 components = new ArrayList<String>(); 20635 } 20636 if (!components.contains(componentName)) { 20637 components.add(componentName); 20638 } 20639 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20640 sendNow = true; 20641 // Purge entry from pending broadcast list if another one exists already 20642 // since we are sending one right away. 20643 mPendingBroadcasts.remove(userId, packageName); 20644 } else { 20645 if (newPackage) { 20646 mPendingBroadcasts.put(userId, packageName, components); 20647 } 20648 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20649 // Schedule a message 20650 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20651 } 20652 } 20653 } 20654 20655 long callingId = Binder.clearCallingIdentity(); 20656 try { 20657 if (sendNow) { 20658 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20659 sendPackageChangedBroadcast(packageName, 20660 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20661 } 20662 } finally { 20663 Binder.restoreCallingIdentity(callingId); 20664 } 20665 } 20666 20667 @Override 20668 public void flushPackageRestrictionsAsUser(int userId) { 20669 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20670 return; 20671 } 20672 if (!sUserManager.exists(userId)) { 20673 return; 20674 } 20675 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20676 false /* checkShell */, "flushPackageRestrictions"); 20677 synchronized (mPackages) { 20678 mSettings.writePackageRestrictionsLPr(userId); 20679 mDirtyUsers.remove(userId); 20680 if (mDirtyUsers.isEmpty()) { 20681 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20682 } 20683 } 20684 } 20685 20686 private void sendPackageChangedBroadcast(String packageName, 20687 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20688 if (DEBUG_INSTALL) 20689 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20690 + componentNames); 20691 Bundle extras = new Bundle(4); 20692 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20693 String nameList[] = new String[componentNames.size()]; 20694 componentNames.toArray(nameList); 20695 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20696 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20697 extras.putInt(Intent.EXTRA_UID, packageUid); 20698 // If this is not reporting a change of the overall package, then only send it 20699 // to registered receivers. We don't want to launch a swath of apps for every 20700 // little component state change. 20701 final int flags = !componentNames.contains(packageName) 20702 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20703 final int userId = UserHandle.getUserId(packageUid); 20704 final boolean isInstantApp = isInstantApp(packageName, userId); 20705 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20706 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20707 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20708 userIds, instantUserIds); 20709 } 20710 20711 @Override 20712 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20713 if (!sUserManager.exists(userId)) return; 20714 final int callingUid = Binder.getCallingUid(); 20715 if (getInstantAppPackageName(callingUid) != null) { 20716 return; 20717 } 20718 final int permission = mContext.checkCallingOrSelfPermission( 20719 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20720 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20721 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20722 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20723 // writer 20724 synchronized (mPackages) { 20725 final PackageSetting ps = mSettings.mPackages.get(packageName); 20726 if (!filterAppAccessLPr(ps, callingUid, userId) 20727 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20728 allowedByPermission, callingUid, userId)) { 20729 scheduleWritePackageRestrictionsLocked(userId); 20730 } 20731 } 20732 } 20733 20734 @Override 20735 public String getInstallerPackageName(String packageName) { 20736 final int callingUid = Binder.getCallingUid(); 20737 synchronized (mPackages) { 20738 final PackageSetting ps = mSettings.mPackages.get(packageName); 20739 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20740 return null; 20741 } 20742 return mSettings.getInstallerPackageNameLPr(packageName); 20743 } 20744 } 20745 20746 public boolean isOrphaned(String packageName) { 20747 // reader 20748 synchronized (mPackages) { 20749 return mSettings.isOrphaned(packageName); 20750 } 20751 } 20752 20753 @Override 20754 public int getApplicationEnabledSetting(String packageName, int userId) { 20755 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20756 int callingUid = Binder.getCallingUid(); 20757 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20758 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20759 // reader 20760 synchronized (mPackages) { 20761 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20762 return COMPONENT_ENABLED_STATE_DISABLED; 20763 } 20764 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20765 } 20766 } 20767 20768 @Override 20769 public int getComponentEnabledSetting(ComponentName component, int userId) { 20770 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20771 int callingUid = Binder.getCallingUid(); 20772 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20773 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20774 synchronized (mPackages) { 20775 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20776 component, TYPE_UNKNOWN, userId)) { 20777 return COMPONENT_ENABLED_STATE_DISABLED; 20778 } 20779 return mSettings.getComponentEnabledSettingLPr(component, userId); 20780 } 20781 } 20782 20783 @Override 20784 public void enterSafeMode() { 20785 enforceSystemOrRoot("Only the system can request entering safe mode"); 20786 20787 if (!mSystemReady) { 20788 mSafeMode = true; 20789 } 20790 } 20791 20792 @Override 20793 public void systemReady() { 20794 enforceSystemOrRoot("Only the system can claim the system is ready"); 20795 20796 mSystemReady = true; 20797 final ContentResolver resolver = mContext.getContentResolver(); 20798 ContentObserver co = new ContentObserver(mHandler) { 20799 @Override 20800 public void onChange(boolean selfChange) { 20801 mWebInstantAppsDisabled = 20802 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20803 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20804 } 20805 }; 20806 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20807 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20808 false, co, UserHandle.USER_SYSTEM); 20809 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 20810 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20811 co.onChange(true); 20812 20813 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20814 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20815 // it is done. 20816 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20817 @Override 20818 public void onChange(boolean selfChange) { 20819 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20820 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20821 oobEnabled == 1 ? "true" : "false"); 20822 } 20823 }; 20824 mContext.getContentResolver().registerContentObserver( 20825 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20826 UserHandle.USER_SYSTEM); 20827 // At boot, restore the value from the setting, which persists across reboot. 20828 privAppOobObserver.onChange(true); 20829 20830 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20831 // disabled after already being started. 20832 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20833 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20834 20835 // Read the compatibilty setting when the system is ready. 20836 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20837 mContext.getContentResolver(), 20838 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20839 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20840 if (DEBUG_SETTINGS) { 20841 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20842 } 20843 20844 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20845 20846 synchronized (mPackages) { 20847 // Verify that all of the preferred activity components actually 20848 // exist. It is possible for applications to be updated and at 20849 // that point remove a previously declared activity component that 20850 // had been set as a preferred activity. We try to clean this up 20851 // the next time we encounter that preferred activity, but it is 20852 // possible for the user flow to never be able to return to that 20853 // situation so here we do a sanity check to make sure we haven't 20854 // left any junk around. 20855 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20856 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20857 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20858 removed.clear(); 20859 for (PreferredActivity pa : pir.filterSet()) { 20860 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20861 removed.add(pa); 20862 } 20863 } 20864 if (removed.size() > 0) { 20865 for (int r=0; r<removed.size(); r++) { 20866 PreferredActivity pa = removed.get(r); 20867 Slog.w(TAG, "Removing dangling preferred activity: " 20868 + pa.mPref.mComponent); 20869 pir.removeFilter(pa); 20870 } 20871 mSettings.writePackageRestrictionsLPr( 20872 mSettings.mPreferredActivities.keyAt(i)); 20873 } 20874 } 20875 20876 for (int userId : UserManagerService.getInstance().getUserIds()) { 20877 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20878 grantPermissionsUserIds = ArrayUtils.appendInt( 20879 grantPermissionsUserIds, userId); 20880 } 20881 } 20882 } 20883 sUserManager.systemReady(); 20884 // If we upgraded grant all default permissions before kicking off. 20885 for (int userId : grantPermissionsUserIds) { 20886 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20887 } 20888 20889 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20890 // If we did not grant default permissions, we preload from this the 20891 // default permission exceptions lazily to ensure we don't hit the 20892 // disk on a new user creation. 20893 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20894 } 20895 20896 // Now that we've scanned all packages, and granted any default 20897 // permissions, ensure permissions are updated. Beware of dragons if you 20898 // try optimizing this. 20899 synchronized (mPackages) { 20900 mPermissionManager.updateAllPermissions( 20901 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20902 mPermissionCallback); 20903 } 20904 20905 // Kick off any messages waiting for system ready 20906 if (mPostSystemReadyMessages != null) { 20907 for (Message msg : mPostSystemReadyMessages) { 20908 msg.sendToTarget(); 20909 } 20910 mPostSystemReadyMessages = null; 20911 } 20912 20913 // Watch for external volumes that come and go over time 20914 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20915 storage.registerListener(mStorageListener); 20916 20917 mInstallerService.systemReady(); 20918 mPackageDexOptimizer.systemReady(); 20919 20920 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20921 StorageManagerInternal.class); 20922 StorageManagerInternal.addExternalStoragePolicy( 20923 new StorageManagerInternal.ExternalStorageMountPolicy() { 20924 @Override 20925 public int getMountMode(int uid, String packageName) { 20926 if (Process.isIsolated(uid)) { 20927 return Zygote.MOUNT_EXTERNAL_NONE; 20928 } 20929 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20930 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20931 } 20932 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20933 return Zygote.MOUNT_EXTERNAL_READ; 20934 } 20935 return Zygote.MOUNT_EXTERNAL_WRITE; 20936 } 20937 20938 @Override 20939 public boolean hasExternalStorage(int uid, String packageName) { 20940 return true; 20941 } 20942 }); 20943 20944 // Now that we're mostly running, clean up stale users and apps 20945 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20946 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20947 20948 mPermissionManager.systemReady(); 20949 20950 if (mInstantAppResolverConnection != null) { 20951 mContext.registerReceiver(new BroadcastReceiver() { 20952 @Override 20953 public void onReceive(Context context, Intent intent) { 20954 mInstantAppResolverConnection.optimisticBind(); 20955 mContext.unregisterReceiver(this); 20956 } 20957 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 20958 } 20959 } 20960 20961 public void waitForAppDataPrepared() { 20962 if (mPrepareAppDataFuture == null) { 20963 return; 20964 } 20965 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20966 mPrepareAppDataFuture = null; 20967 } 20968 20969 @Override 20970 public boolean isSafeMode() { 20971 // allow instant applications 20972 return mSafeMode; 20973 } 20974 20975 @Override 20976 public boolean hasSystemUidErrors() { 20977 // allow instant applications 20978 return mHasSystemUidErrors; 20979 } 20980 20981 static String arrayToString(int[] array) { 20982 StringBuffer buf = new StringBuffer(128); 20983 buf.append('['); 20984 if (array != null) { 20985 for (int i=0; i<array.length; i++) { 20986 if (i > 0) buf.append(", "); 20987 buf.append(array[i]); 20988 } 20989 } 20990 buf.append(']'); 20991 return buf.toString(); 20992 } 20993 20994 @Override 20995 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20996 FileDescriptor err, String[] args, ShellCallback callback, 20997 ResultReceiver resultReceiver) { 20998 (new PackageManagerShellCommand(this)).exec( 20999 this, in, out, err, args, callback, resultReceiver); 21000 } 21001 21002 @Override 21003 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21004 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21005 21006 DumpState dumpState = new DumpState(); 21007 boolean fullPreferred = false; 21008 boolean checkin = false; 21009 21010 String packageName = null; 21011 ArraySet<String> permissionNames = null; 21012 21013 int opti = 0; 21014 while (opti < args.length) { 21015 String opt = args[opti]; 21016 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21017 break; 21018 } 21019 opti++; 21020 21021 if ("-a".equals(opt)) { 21022 // Right now we only know how to print all. 21023 } else if ("-h".equals(opt)) { 21024 pw.println("Package manager dump options:"); 21025 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21026 pw.println(" --checkin: dump for a checkin"); 21027 pw.println(" -f: print details of intent filters"); 21028 pw.println(" -h: print this help"); 21029 pw.println(" cmd may be one of:"); 21030 pw.println(" l[ibraries]: list known shared libraries"); 21031 pw.println(" f[eatures]: list device features"); 21032 pw.println(" k[eysets]: print known keysets"); 21033 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21034 pw.println(" perm[issions]: dump permissions"); 21035 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21036 pw.println(" pref[erred]: print preferred package settings"); 21037 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21038 pw.println(" prov[iders]: dump content providers"); 21039 pw.println(" p[ackages]: dump installed packages"); 21040 pw.println(" s[hared-users]: dump shared user IDs"); 21041 pw.println(" m[essages]: print collected runtime messages"); 21042 pw.println(" v[erifiers]: print package verifier info"); 21043 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21044 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21045 pw.println(" version: print database version info"); 21046 pw.println(" write: write current settings now"); 21047 pw.println(" installs: details about install sessions"); 21048 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21049 pw.println(" dexopt: dump dexopt state"); 21050 pw.println(" compiler-stats: dump compiler statistics"); 21051 pw.println(" service-permissions: dump permissions required by services"); 21052 pw.println(" <package.name>: info about given package"); 21053 return; 21054 } else if ("--checkin".equals(opt)) { 21055 checkin = true; 21056 } else if ("-f".equals(opt)) { 21057 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21058 } else if ("--proto".equals(opt)) { 21059 dumpProto(fd); 21060 return; 21061 } else { 21062 pw.println("Unknown argument: " + opt + "; use -h for help"); 21063 } 21064 } 21065 21066 // Is the caller requesting to dump a particular piece of data? 21067 if (opti < args.length) { 21068 String cmd = args[opti]; 21069 opti++; 21070 // Is this a package name? 21071 if ("android".equals(cmd) || cmd.contains(".")) { 21072 packageName = cmd; 21073 // When dumping a single package, we always dump all of its 21074 // filter information since the amount of data will be reasonable. 21075 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21076 } else if ("check-permission".equals(cmd)) { 21077 if (opti >= args.length) { 21078 pw.println("Error: check-permission missing permission argument"); 21079 return; 21080 } 21081 String perm = args[opti]; 21082 opti++; 21083 if (opti >= args.length) { 21084 pw.println("Error: check-permission missing package argument"); 21085 return; 21086 } 21087 21088 String pkg = args[opti]; 21089 opti++; 21090 int user = UserHandle.getUserId(Binder.getCallingUid()); 21091 if (opti < args.length) { 21092 try { 21093 user = Integer.parseInt(args[opti]); 21094 } catch (NumberFormatException e) { 21095 pw.println("Error: check-permission user argument is not a number: " 21096 + args[opti]); 21097 return; 21098 } 21099 } 21100 21101 // Normalize package name to handle renamed packages and static libs 21102 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21103 21104 pw.println(checkPermission(perm, pkg, user)); 21105 return; 21106 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21107 dumpState.setDump(DumpState.DUMP_LIBS); 21108 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21109 dumpState.setDump(DumpState.DUMP_FEATURES); 21110 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21111 if (opti >= args.length) { 21112 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21113 | DumpState.DUMP_SERVICE_RESOLVERS 21114 | DumpState.DUMP_RECEIVER_RESOLVERS 21115 | DumpState.DUMP_CONTENT_RESOLVERS); 21116 } else { 21117 while (opti < args.length) { 21118 String name = args[opti]; 21119 if ("a".equals(name) || "activity".equals(name)) { 21120 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21121 } else if ("s".equals(name) || "service".equals(name)) { 21122 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21123 } else if ("r".equals(name) || "receiver".equals(name)) { 21124 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21125 } else if ("c".equals(name) || "content".equals(name)) { 21126 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21127 } else { 21128 pw.println("Error: unknown resolver table type: " + name); 21129 return; 21130 } 21131 opti++; 21132 } 21133 } 21134 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21135 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21136 } else if ("permission".equals(cmd)) { 21137 if (opti >= args.length) { 21138 pw.println("Error: permission requires permission name"); 21139 return; 21140 } 21141 permissionNames = new ArraySet<>(); 21142 while (opti < args.length) { 21143 permissionNames.add(args[opti]); 21144 opti++; 21145 } 21146 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21147 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21148 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21149 dumpState.setDump(DumpState.DUMP_PREFERRED); 21150 } else if ("preferred-xml".equals(cmd)) { 21151 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21152 if (opti < args.length && "--full".equals(args[opti])) { 21153 fullPreferred = true; 21154 opti++; 21155 } 21156 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21157 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21158 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21159 dumpState.setDump(DumpState.DUMP_PACKAGES); 21160 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21161 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21162 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21163 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21164 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21165 dumpState.setDump(DumpState.DUMP_MESSAGES); 21166 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21167 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21168 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21169 || "intent-filter-verifiers".equals(cmd)) { 21170 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21171 } else if ("version".equals(cmd)) { 21172 dumpState.setDump(DumpState.DUMP_VERSION); 21173 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21174 dumpState.setDump(DumpState.DUMP_KEYSETS); 21175 } else if ("installs".equals(cmd)) { 21176 dumpState.setDump(DumpState.DUMP_INSTALLS); 21177 } else if ("frozen".equals(cmd)) { 21178 dumpState.setDump(DumpState.DUMP_FROZEN); 21179 } else if ("volumes".equals(cmd)) { 21180 dumpState.setDump(DumpState.DUMP_VOLUMES); 21181 } else if ("dexopt".equals(cmd)) { 21182 dumpState.setDump(DumpState.DUMP_DEXOPT); 21183 } else if ("compiler-stats".equals(cmd)) { 21184 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21185 } else if ("changes".equals(cmd)) { 21186 dumpState.setDump(DumpState.DUMP_CHANGES); 21187 } else if ("service-permissions".equals(cmd)) { 21188 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21189 } else if ("write".equals(cmd)) { 21190 synchronized (mPackages) { 21191 mSettings.writeLPr(); 21192 pw.println("Settings written."); 21193 return; 21194 } 21195 } 21196 } 21197 21198 if (checkin) { 21199 pw.println("vers,1"); 21200 } 21201 21202 // reader 21203 synchronized (mPackages) { 21204 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21205 if (!checkin) { 21206 if (dumpState.onTitlePrinted()) 21207 pw.println(); 21208 pw.println("Database versions:"); 21209 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21210 } 21211 } 21212 21213 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21214 if (!checkin) { 21215 if (dumpState.onTitlePrinted()) 21216 pw.println(); 21217 pw.println("Verifiers:"); 21218 pw.print(" Required: "); 21219 pw.print(mRequiredVerifierPackage); 21220 pw.print(" (uid="); 21221 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21222 UserHandle.USER_SYSTEM)); 21223 pw.println(")"); 21224 } else if (mRequiredVerifierPackage != null) { 21225 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21226 pw.print(","); 21227 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21228 UserHandle.USER_SYSTEM)); 21229 } 21230 } 21231 21232 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21233 packageName == null) { 21234 if (mIntentFilterVerifierComponent != null) { 21235 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21236 if (!checkin) { 21237 if (dumpState.onTitlePrinted()) 21238 pw.println(); 21239 pw.println("Intent Filter Verifier:"); 21240 pw.print(" Using: "); 21241 pw.print(verifierPackageName); 21242 pw.print(" (uid="); 21243 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21244 UserHandle.USER_SYSTEM)); 21245 pw.println(")"); 21246 } else if (verifierPackageName != null) { 21247 pw.print("ifv,"); pw.print(verifierPackageName); 21248 pw.print(","); 21249 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21250 UserHandle.USER_SYSTEM)); 21251 } 21252 } else { 21253 pw.println(); 21254 pw.println("No Intent Filter Verifier available!"); 21255 } 21256 } 21257 21258 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21259 boolean printedHeader = false; 21260 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21261 while (it.hasNext()) { 21262 String libName = it.next(); 21263 LongSparseArray<SharedLibraryEntry> versionedLib 21264 = mSharedLibraries.get(libName); 21265 if (versionedLib == null) { 21266 continue; 21267 } 21268 final int versionCount = versionedLib.size(); 21269 for (int i = 0; i < versionCount; i++) { 21270 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21271 if (!checkin) { 21272 if (!printedHeader) { 21273 if (dumpState.onTitlePrinted()) 21274 pw.println(); 21275 pw.println("Libraries:"); 21276 printedHeader = true; 21277 } 21278 pw.print(" "); 21279 } else { 21280 pw.print("lib,"); 21281 } 21282 pw.print(libEntry.info.getName()); 21283 if (libEntry.info.isStatic()) { 21284 pw.print(" version=" + libEntry.info.getLongVersion()); 21285 } 21286 if (!checkin) { 21287 pw.print(" -> "); 21288 } 21289 if (libEntry.path != null) { 21290 pw.print(" (jar) "); 21291 pw.print(libEntry.path); 21292 } else { 21293 pw.print(" (apk) "); 21294 pw.print(libEntry.apk); 21295 } 21296 pw.println(); 21297 } 21298 } 21299 } 21300 21301 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21302 if (dumpState.onTitlePrinted()) 21303 pw.println(); 21304 if (!checkin) { 21305 pw.println("Features:"); 21306 } 21307 21308 synchronized (mAvailableFeatures) { 21309 for (FeatureInfo feat : mAvailableFeatures.values()) { 21310 if (checkin) { 21311 pw.print("feat,"); 21312 pw.print(feat.name); 21313 pw.print(","); 21314 pw.println(feat.version); 21315 } else { 21316 pw.print(" "); 21317 pw.print(feat.name); 21318 if (feat.version > 0) { 21319 pw.print(" version="); 21320 pw.print(feat.version); 21321 } 21322 pw.println(); 21323 } 21324 } 21325 } 21326 } 21327 21328 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21329 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21330 : "Activity Resolver Table:", " ", packageName, 21331 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21332 dumpState.setTitlePrinted(true); 21333 } 21334 } 21335 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21336 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21337 : "Receiver Resolver Table:", " ", packageName, 21338 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21339 dumpState.setTitlePrinted(true); 21340 } 21341 } 21342 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21343 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21344 : "Service Resolver Table:", " ", packageName, 21345 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21346 dumpState.setTitlePrinted(true); 21347 } 21348 } 21349 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21350 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21351 : "Provider Resolver Table:", " ", packageName, 21352 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21353 dumpState.setTitlePrinted(true); 21354 } 21355 } 21356 21357 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21358 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21359 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21360 int user = mSettings.mPreferredActivities.keyAt(i); 21361 if (pir.dump(pw, 21362 dumpState.getTitlePrinted() 21363 ? "\nPreferred Activities User " + user + ":" 21364 : "Preferred Activities User " + user + ":", " ", 21365 packageName, true, false)) { 21366 dumpState.setTitlePrinted(true); 21367 } 21368 } 21369 } 21370 21371 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21372 pw.flush(); 21373 FileOutputStream fout = new FileOutputStream(fd); 21374 BufferedOutputStream str = new BufferedOutputStream(fout); 21375 XmlSerializer serializer = new FastXmlSerializer(); 21376 try { 21377 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21378 serializer.startDocument(null, true); 21379 serializer.setFeature( 21380 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21381 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21382 serializer.endDocument(); 21383 serializer.flush(); 21384 } catch (IllegalArgumentException e) { 21385 pw.println("Failed writing: " + e); 21386 } catch (IllegalStateException e) { 21387 pw.println("Failed writing: " + e); 21388 } catch (IOException e) { 21389 pw.println("Failed writing: " + e); 21390 } 21391 } 21392 21393 if (!checkin 21394 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21395 && packageName == null) { 21396 pw.println(); 21397 int count = mSettings.mPackages.size(); 21398 if (count == 0) { 21399 pw.println("No applications!"); 21400 pw.println(); 21401 } else { 21402 final String prefix = " "; 21403 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21404 if (allPackageSettings.size() == 0) { 21405 pw.println("No domain preferred apps!"); 21406 pw.println(); 21407 } else { 21408 pw.println("App verification status:"); 21409 pw.println(); 21410 count = 0; 21411 for (PackageSetting ps : allPackageSettings) { 21412 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21413 if (ivi == null || ivi.getPackageName() == null) continue; 21414 pw.println(prefix + "Package: " + ivi.getPackageName()); 21415 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21416 pw.println(prefix + "Status: " + ivi.getStatusString()); 21417 pw.println(); 21418 count++; 21419 } 21420 if (count == 0) { 21421 pw.println(prefix + "No app verification established."); 21422 pw.println(); 21423 } 21424 for (int userId : sUserManager.getUserIds()) { 21425 pw.println("App linkages for user " + userId + ":"); 21426 pw.println(); 21427 count = 0; 21428 for (PackageSetting ps : allPackageSettings) { 21429 final long status = ps.getDomainVerificationStatusForUser(userId); 21430 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21431 && !DEBUG_DOMAIN_VERIFICATION) { 21432 continue; 21433 } 21434 pw.println(prefix + "Package: " + ps.name); 21435 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21436 String statusStr = IntentFilterVerificationInfo. 21437 getStatusStringFromValue(status); 21438 pw.println(prefix + "Status: " + statusStr); 21439 pw.println(); 21440 count++; 21441 } 21442 if (count == 0) { 21443 pw.println(prefix + "No configured app linkages."); 21444 pw.println(); 21445 } 21446 } 21447 } 21448 } 21449 } 21450 21451 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21452 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21453 } 21454 21455 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21456 boolean printedSomething = false; 21457 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21458 if (packageName != null && !packageName.equals(p.info.packageName)) { 21459 continue; 21460 } 21461 if (!printedSomething) { 21462 if (dumpState.onTitlePrinted()) 21463 pw.println(); 21464 pw.println("Registered ContentProviders:"); 21465 printedSomething = true; 21466 } 21467 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21468 pw.print(" "); pw.println(p.toString()); 21469 } 21470 printedSomething = false; 21471 for (Map.Entry<String, PackageParser.Provider> entry : 21472 mProvidersByAuthority.entrySet()) { 21473 PackageParser.Provider p = entry.getValue(); 21474 if (packageName != null && !packageName.equals(p.info.packageName)) { 21475 continue; 21476 } 21477 if (!printedSomething) { 21478 if (dumpState.onTitlePrinted()) 21479 pw.println(); 21480 pw.println("ContentProvider Authorities:"); 21481 printedSomething = true; 21482 } 21483 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21484 pw.print(" "); pw.println(p.toString()); 21485 if (p.info != null && p.info.applicationInfo != null) { 21486 final String appInfo = p.info.applicationInfo.toString(); 21487 pw.print(" applicationInfo="); pw.println(appInfo); 21488 } 21489 } 21490 } 21491 21492 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21493 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21494 } 21495 21496 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21497 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21498 } 21499 21500 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21501 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21502 } 21503 21504 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21505 if (dumpState.onTitlePrinted()) pw.println(); 21506 pw.println("Package Changes:"); 21507 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21508 final int K = mChangedPackages.size(); 21509 for (int i = 0; i < K; i++) { 21510 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21511 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21512 final int N = changes.size(); 21513 if (N == 0) { 21514 pw.print(" "); pw.println("No packages changed"); 21515 } else { 21516 for (int j = 0; j < N; j++) { 21517 final String pkgName = changes.valueAt(j); 21518 final int sequenceNumber = changes.keyAt(j); 21519 pw.print(" "); 21520 pw.print("seq="); 21521 pw.print(sequenceNumber); 21522 pw.print(", package="); 21523 pw.println(pkgName); 21524 } 21525 } 21526 } 21527 } 21528 21529 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21530 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21531 } 21532 21533 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21534 // XXX should handle packageName != null by dumping only install data that 21535 // the given package is involved with. 21536 if (dumpState.onTitlePrinted()) pw.println(); 21537 21538 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21539 ipw.println(); 21540 ipw.println("Frozen packages:"); 21541 ipw.increaseIndent(); 21542 if (mFrozenPackages.size() == 0) { 21543 ipw.println("(none)"); 21544 } else { 21545 for (int i = 0; i < mFrozenPackages.size(); i++) { 21546 ipw.println(mFrozenPackages.valueAt(i)); 21547 } 21548 } 21549 ipw.decreaseIndent(); 21550 } 21551 } 21552 21553 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21554 if (dumpState.onTitlePrinted()) pw.println(); 21555 21556 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21557 ipw.println(); 21558 ipw.println("Loaded volumes:"); 21559 ipw.increaseIndent(); 21560 if (mLoadedVolumes.size() == 0) { 21561 ipw.println("(none)"); 21562 } else { 21563 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21564 ipw.println(mLoadedVolumes.valueAt(i)); 21565 } 21566 } 21567 ipw.decreaseIndent(); 21568 } 21569 } 21570 21571 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21572 && packageName == null) { 21573 if (dumpState.onTitlePrinted()) pw.println(); 21574 pw.println("Service permissions:"); 21575 21576 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21577 while (filterIterator.hasNext()) { 21578 final ServiceIntentInfo info = filterIterator.next(); 21579 final ServiceInfo serviceInfo = info.service.info; 21580 final String permission = serviceInfo.permission; 21581 if (permission != null) { 21582 pw.print(" "); 21583 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21584 pw.print(": "); 21585 pw.println(permission); 21586 } 21587 } 21588 } 21589 21590 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21591 if (dumpState.onTitlePrinted()) pw.println(); 21592 dumpDexoptStateLPr(pw, packageName); 21593 } 21594 21595 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21596 if (dumpState.onTitlePrinted()) pw.println(); 21597 dumpCompilerStatsLPr(pw, packageName); 21598 } 21599 21600 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21601 if (dumpState.onTitlePrinted()) pw.println(); 21602 mSettings.dumpReadMessagesLPr(pw, dumpState); 21603 21604 pw.println(); 21605 pw.println("Package warning messages:"); 21606 dumpCriticalInfo(pw, null); 21607 } 21608 21609 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21610 dumpCriticalInfo(pw, "msg,"); 21611 } 21612 } 21613 21614 // PackageInstaller should be called outside of mPackages lock 21615 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21616 // XXX should handle packageName != null by dumping only install data that 21617 // the given package is involved with. 21618 if (dumpState.onTitlePrinted()) pw.println(); 21619 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21620 } 21621 } 21622 21623 private void dumpProto(FileDescriptor fd) { 21624 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21625 21626 synchronized (mPackages) { 21627 final long requiredVerifierPackageToken = 21628 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21629 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21630 proto.write( 21631 PackageServiceDumpProto.PackageShortProto.UID, 21632 getPackageUid( 21633 mRequiredVerifierPackage, 21634 MATCH_DEBUG_TRIAGED_MISSING, 21635 UserHandle.USER_SYSTEM)); 21636 proto.end(requiredVerifierPackageToken); 21637 21638 if (mIntentFilterVerifierComponent != null) { 21639 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21640 final long verifierPackageToken = 21641 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21642 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21643 proto.write( 21644 PackageServiceDumpProto.PackageShortProto.UID, 21645 getPackageUid( 21646 verifierPackageName, 21647 MATCH_DEBUG_TRIAGED_MISSING, 21648 UserHandle.USER_SYSTEM)); 21649 proto.end(verifierPackageToken); 21650 } 21651 21652 dumpSharedLibrariesProto(proto); 21653 dumpFeaturesProto(proto); 21654 mSettings.dumpPackagesProto(proto); 21655 mSettings.dumpSharedUsersProto(proto); 21656 dumpCriticalInfo(proto); 21657 } 21658 proto.flush(); 21659 } 21660 21661 private void dumpFeaturesProto(ProtoOutputStream proto) { 21662 synchronized (mAvailableFeatures) { 21663 final int count = mAvailableFeatures.size(); 21664 for (int i = 0; i < count; i++) { 21665 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21666 } 21667 } 21668 } 21669 21670 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21671 final int count = mSharedLibraries.size(); 21672 for (int i = 0; i < count; i++) { 21673 final String libName = mSharedLibraries.keyAt(i); 21674 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21675 if (versionedLib == null) { 21676 continue; 21677 } 21678 final int versionCount = versionedLib.size(); 21679 for (int j = 0; j < versionCount; j++) { 21680 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21681 final long sharedLibraryToken = 21682 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21683 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21684 final boolean isJar = (libEntry.path != null); 21685 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21686 if (isJar) { 21687 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21688 } else { 21689 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21690 } 21691 proto.end(sharedLibraryToken); 21692 } 21693 } 21694 } 21695 21696 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21697 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21698 ipw.println(); 21699 ipw.println("Dexopt state:"); 21700 ipw.increaseIndent(); 21701 Collection<PackageParser.Package> packages = null; 21702 if (packageName != null) { 21703 PackageParser.Package targetPackage = mPackages.get(packageName); 21704 if (targetPackage != null) { 21705 packages = Collections.singletonList(targetPackage); 21706 } else { 21707 ipw.println("Unable to find package: " + packageName); 21708 return; 21709 } 21710 } else { 21711 packages = mPackages.values(); 21712 } 21713 21714 for (PackageParser.Package pkg : packages) { 21715 ipw.println("[" + pkg.packageName + "]"); 21716 ipw.increaseIndent(); 21717 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21718 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21719 ipw.decreaseIndent(); 21720 } 21721 } 21722 } 21723 21724 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21725 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21726 ipw.println(); 21727 ipw.println("Compiler stats:"); 21728 ipw.increaseIndent(); 21729 Collection<PackageParser.Package> packages = null; 21730 if (packageName != null) { 21731 PackageParser.Package targetPackage = mPackages.get(packageName); 21732 if (targetPackage != null) { 21733 packages = Collections.singletonList(targetPackage); 21734 } else { 21735 ipw.println("Unable to find package: " + packageName); 21736 return; 21737 } 21738 } else { 21739 packages = mPackages.values(); 21740 } 21741 21742 for (PackageParser.Package pkg : packages) { 21743 ipw.println("[" + pkg.packageName + "]"); 21744 ipw.increaseIndent(); 21745 21746 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21747 if (stats == null) { 21748 ipw.println("(No recorded stats)"); 21749 } else { 21750 stats.dump(ipw); 21751 } 21752 ipw.decreaseIndent(); 21753 } 21754 } 21755 } 21756 21757 private String dumpDomainString(String packageName) { 21758 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21759 .getList(); 21760 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21761 21762 ArraySet<String> result = new ArraySet<>(); 21763 if (iviList.size() > 0) { 21764 for (IntentFilterVerificationInfo ivi : iviList) { 21765 for (String host : ivi.getDomains()) { 21766 result.add(host); 21767 } 21768 } 21769 } 21770 if (filters != null && filters.size() > 0) { 21771 for (IntentFilter filter : filters) { 21772 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21773 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21774 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21775 result.addAll(filter.getHostsList()); 21776 } 21777 } 21778 } 21779 21780 StringBuilder sb = new StringBuilder(result.size() * 16); 21781 for (String domain : result) { 21782 if (sb.length() > 0) sb.append(" "); 21783 sb.append(domain); 21784 } 21785 return sb.toString(); 21786 } 21787 21788 // ------- apps on sdcard specific code ------- 21789 static final boolean DEBUG_SD_INSTALL = false; 21790 21791 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21792 21793 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21794 21795 private boolean mMediaMounted = false; 21796 21797 static String getEncryptKey() { 21798 try { 21799 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21800 SD_ENCRYPTION_KEYSTORE_NAME); 21801 if (sdEncKey == null) { 21802 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21803 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21804 if (sdEncKey == null) { 21805 Slog.e(TAG, "Failed to create encryption keys"); 21806 return null; 21807 } 21808 } 21809 return sdEncKey; 21810 } catch (NoSuchAlgorithmException nsae) { 21811 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21812 return null; 21813 } catch (IOException ioe) { 21814 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21815 return null; 21816 } 21817 } 21818 21819 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21820 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21821 final int size = infos.size(); 21822 final String[] packageNames = new String[size]; 21823 final int[] packageUids = new int[size]; 21824 for (int i = 0; i < size; i++) { 21825 final ApplicationInfo info = infos.get(i); 21826 packageNames[i] = info.packageName; 21827 packageUids[i] = info.uid; 21828 } 21829 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21830 finishedReceiver); 21831 } 21832 21833 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21834 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21835 sendResourcesChangedBroadcast(mediaStatus, replacing, 21836 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21837 } 21838 21839 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21840 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21841 int size = pkgList.length; 21842 if (size > 0) { 21843 // Send broadcasts here 21844 Bundle extras = new Bundle(); 21845 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21846 if (uidArr != null) { 21847 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21848 } 21849 if (replacing) { 21850 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21851 } 21852 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21853 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21854 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21855 } 21856 } 21857 21858 private void loadPrivatePackages(final VolumeInfo vol) { 21859 mHandler.post(new Runnable() { 21860 @Override 21861 public void run() { 21862 loadPrivatePackagesInner(vol); 21863 } 21864 }); 21865 } 21866 21867 private void loadPrivatePackagesInner(VolumeInfo vol) { 21868 final String volumeUuid = vol.fsUuid; 21869 if (TextUtils.isEmpty(volumeUuid)) { 21870 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21871 return; 21872 } 21873 21874 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21875 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21876 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21877 21878 final VersionInfo ver; 21879 final List<PackageSetting> packages; 21880 synchronized (mPackages) { 21881 ver = mSettings.findOrCreateVersion(volumeUuid); 21882 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21883 } 21884 21885 for (PackageSetting ps : packages) { 21886 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21887 synchronized (mInstallLock) { 21888 final PackageParser.Package pkg; 21889 try { 21890 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21891 loaded.add(pkg.applicationInfo); 21892 21893 } catch (PackageManagerException e) { 21894 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21895 } 21896 21897 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21898 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21899 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21900 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21901 } 21902 } 21903 } 21904 21905 // Reconcile app data for all started/unlocked users 21906 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21907 final UserManager um = mContext.getSystemService(UserManager.class); 21908 UserManagerInternal umInternal = getUserManagerInternal(); 21909 for (UserInfo user : um.getUsers()) { 21910 final int flags; 21911 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21912 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21913 } else if (umInternal.isUserRunning(user.id)) { 21914 flags = StorageManager.FLAG_STORAGE_DE; 21915 } else { 21916 continue; 21917 } 21918 21919 try { 21920 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21921 synchronized (mInstallLock) { 21922 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21923 } 21924 } catch (IllegalStateException e) { 21925 // Device was probably ejected, and we'll process that event momentarily 21926 Slog.w(TAG, "Failed to prepare storage: " + e); 21927 } 21928 } 21929 21930 synchronized (mPackages) { 21931 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21932 if (sdkUpdated) { 21933 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21934 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21935 } 21936 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21937 mPermissionCallback); 21938 21939 // Yay, everything is now upgraded 21940 ver.forceCurrent(); 21941 21942 mSettings.writeLPr(); 21943 } 21944 21945 for (PackageFreezer freezer : freezers) { 21946 freezer.close(); 21947 } 21948 21949 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21950 sendResourcesChangedBroadcast(true, false, loaded, null); 21951 mLoadedVolumes.add(vol.getId()); 21952 } 21953 21954 private void unloadPrivatePackages(final VolumeInfo vol) { 21955 mHandler.post(new Runnable() { 21956 @Override 21957 public void run() { 21958 unloadPrivatePackagesInner(vol); 21959 } 21960 }); 21961 } 21962 21963 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21964 final String volumeUuid = vol.fsUuid; 21965 if (TextUtils.isEmpty(volumeUuid)) { 21966 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21967 return; 21968 } 21969 21970 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21971 synchronized (mInstallLock) { 21972 synchronized (mPackages) { 21973 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21974 for (PackageSetting ps : packages) { 21975 if (ps.pkg == null) continue; 21976 21977 final ApplicationInfo info = ps.pkg.applicationInfo; 21978 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21979 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21980 21981 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21982 "unloadPrivatePackagesInner")) { 21983 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21984 false, null)) { 21985 unloaded.add(info); 21986 } else { 21987 Slog.w(TAG, "Failed to unload " + ps.codePath); 21988 } 21989 } 21990 21991 // Try very hard to release any references to this package 21992 // so we don't risk the system server being killed due to 21993 // open FDs 21994 AttributeCache.instance().removePackage(ps.name); 21995 } 21996 21997 mSettings.writeLPr(); 21998 } 21999 } 22000 22001 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22002 sendResourcesChangedBroadcast(false, false, unloaded, null); 22003 mLoadedVolumes.remove(vol.getId()); 22004 22005 // Try very hard to release any references to this path so we don't risk 22006 // the system server being killed due to open FDs 22007 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22008 22009 for (int i = 0; i < 3; i++) { 22010 System.gc(); 22011 System.runFinalization(); 22012 } 22013 } 22014 22015 private void assertPackageKnown(String volumeUuid, String packageName) 22016 throws PackageManagerException { 22017 synchronized (mPackages) { 22018 // Normalize package name to handle renamed packages 22019 packageName = normalizePackageNameLPr(packageName); 22020 22021 final PackageSetting ps = mSettings.mPackages.get(packageName); 22022 if (ps == null) { 22023 throw new PackageManagerException("Package " + packageName + " is unknown"); 22024 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22025 throw new PackageManagerException( 22026 "Package " + packageName + " found on unknown volume " + volumeUuid 22027 + "; expected volume " + ps.volumeUuid); 22028 } 22029 } 22030 } 22031 22032 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22033 throws PackageManagerException { 22034 synchronized (mPackages) { 22035 // Normalize package name to handle renamed packages 22036 packageName = normalizePackageNameLPr(packageName); 22037 22038 final PackageSetting ps = mSettings.mPackages.get(packageName); 22039 if (ps == null) { 22040 throw new PackageManagerException("Package " + packageName + " is unknown"); 22041 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22042 throw new PackageManagerException( 22043 "Package " + packageName + " found on unknown volume " + volumeUuid 22044 + "; expected volume " + ps.volumeUuid); 22045 } else if (!ps.getInstalled(userId)) { 22046 throw new PackageManagerException( 22047 "Package " + packageName + " not installed for user " + userId); 22048 } 22049 } 22050 } 22051 22052 private List<String> collectAbsoluteCodePaths() { 22053 synchronized (mPackages) { 22054 List<String> codePaths = new ArrayList<>(); 22055 final int packageCount = mSettings.mPackages.size(); 22056 for (int i = 0; i < packageCount; i++) { 22057 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22058 codePaths.add(ps.codePath.getAbsolutePath()); 22059 } 22060 return codePaths; 22061 } 22062 } 22063 22064 /** 22065 * Examine all apps present on given mounted volume, and destroy apps that 22066 * aren't expected, either due to uninstallation or reinstallation on 22067 * another volume. 22068 */ 22069 private void reconcileApps(String volumeUuid) { 22070 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22071 List<File> filesToDelete = null; 22072 22073 final File[] files = FileUtils.listFilesOrEmpty( 22074 Environment.getDataAppDirectory(volumeUuid)); 22075 for (File file : files) { 22076 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22077 && !PackageInstallerService.isStageName(file.getName()); 22078 if (!isPackage) { 22079 // Ignore entries which are not packages 22080 continue; 22081 } 22082 22083 String absolutePath = file.getAbsolutePath(); 22084 22085 boolean pathValid = false; 22086 final int absoluteCodePathCount = absoluteCodePaths.size(); 22087 for (int i = 0; i < absoluteCodePathCount; i++) { 22088 String absoluteCodePath = absoluteCodePaths.get(i); 22089 if (absolutePath.startsWith(absoluteCodePath)) { 22090 pathValid = true; 22091 break; 22092 } 22093 } 22094 22095 if (!pathValid) { 22096 if (filesToDelete == null) { 22097 filesToDelete = new ArrayList<>(); 22098 } 22099 filesToDelete.add(file); 22100 } 22101 } 22102 22103 if (filesToDelete != null) { 22104 final int fileToDeleteCount = filesToDelete.size(); 22105 for (int i = 0; i < fileToDeleteCount; i++) { 22106 File fileToDelete = filesToDelete.get(i); 22107 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22108 synchronized (mInstallLock) { 22109 removeCodePathLI(fileToDelete); 22110 } 22111 } 22112 } 22113 } 22114 22115 /** 22116 * Reconcile all app data for the given user. 22117 * <p> 22118 * Verifies that directories exist and that ownership and labeling is 22119 * correct for all installed apps on all mounted volumes. 22120 */ 22121 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22122 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22123 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22124 final String volumeUuid = vol.getFsUuid(); 22125 synchronized (mInstallLock) { 22126 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22127 } 22128 } 22129 } 22130 22131 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22132 boolean migrateAppData) { 22133 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22134 } 22135 22136 /** 22137 * Reconcile all app data on given mounted volume. 22138 * <p> 22139 * Destroys app data that isn't expected, either due to uninstallation or 22140 * reinstallation on another volume. 22141 * <p> 22142 * Verifies that directories exist and that ownership and labeling is 22143 * correct for all installed apps. 22144 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22145 */ 22146 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22147 boolean migrateAppData, boolean onlyCoreApps) { 22148 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22149 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22150 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22151 22152 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22153 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22154 22155 // First look for stale data that doesn't belong, and check if things 22156 // have changed since we did our last restorecon 22157 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22158 if (StorageManager.isFileEncryptedNativeOrEmulated() 22159 && !StorageManager.isUserKeyUnlocked(userId)) { 22160 throw new RuntimeException( 22161 "Yikes, someone asked us to reconcile CE storage while " + userId 22162 + " was still locked; this would have caused massive data loss!"); 22163 } 22164 22165 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22166 for (File file : files) { 22167 final String packageName = file.getName(); 22168 try { 22169 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22170 } catch (PackageManagerException e) { 22171 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22172 try { 22173 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22174 StorageManager.FLAG_STORAGE_CE, 0); 22175 } catch (InstallerException e2) { 22176 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22177 } 22178 } 22179 } 22180 } 22181 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22182 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22183 for (File file : files) { 22184 final String packageName = file.getName(); 22185 try { 22186 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22187 } catch (PackageManagerException e) { 22188 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22189 try { 22190 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22191 StorageManager.FLAG_STORAGE_DE, 0); 22192 } catch (InstallerException e2) { 22193 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22194 } 22195 } 22196 } 22197 } 22198 22199 // Ensure that data directories are ready to roll for all packages 22200 // installed for this volume and user 22201 final List<PackageSetting> packages; 22202 synchronized (mPackages) { 22203 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22204 } 22205 int preparedCount = 0; 22206 for (PackageSetting ps : packages) { 22207 final String packageName = ps.name; 22208 if (ps.pkg == null) { 22209 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22210 // TODO: might be due to legacy ASEC apps; we should circle back 22211 // and reconcile again once they're scanned 22212 continue; 22213 } 22214 // Skip non-core apps if requested 22215 if (onlyCoreApps && !ps.pkg.coreApp) { 22216 result.add(packageName); 22217 continue; 22218 } 22219 22220 if (ps.getInstalled(userId)) { 22221 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22222 preparedCount++; 22223 } 22224 } 22225 22226 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22227 return result; 22228 } 22229 22230 /** 22231 * Prepare app data for the given app just after it was installed or 22232 * upgraded. This method carefully only touches users that it's installed 22233 * for, and it forces a restorecon to handle any seinfo changes. 22234 * <p> 22235 * Verifies that directories exist and that ownership and labeling is 22236 * correct for all installed apps. If there is an ownership mismatch, it 22237 * will try recovering system apps by wiping data; third-party app data is 22238 * left intact. 22239 * <p> 22240 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22241 */ 22242 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22243 final PackageSetting ps; 22244 synchronized (mPackages) { 22245 ps = mSettings.mPackages.get(pkg.packageName); 22246 mSettings.writeKernelMappingLPr(ps); 22247 } 22248 22249 final UserManager um = mContext.getSystemService(UserManager.class); 22250 UserManagerInternal umInternal = getUserManagerInternal(); 22251 for (UserInfo user : um.getUsers()) { 22252 final int flags; 22253 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22254 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22255 } else if (umInternal.isUserRunning(user.id)) { 22256 flags = StorageManager.FLAG_STORAGE_DE; 22257 } else { 22258 continue; 22259 } 22260 22261 if (ps.getInstalled(user.id)) { 22262 // TODO: when user data is locked, mark that we're still dirty 22263 prepareAppDataLIF(pkg, user.id, flags); 22264 } 22265 } 22266 } 22267 22268 /** 22269 * Prepare app data for the given app. 22270 * <p> 22271 * Verifies that directories exist and that ownership and labeling is 22272 * correct for all installed apps. If there is an ownership mismatch, this 22273 * will try recovering system apps by wiping data; third-party app data is 22274 * left intact. 22275 */ 22276 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22277 if (pkg == null) { 22278 Slog.wtf(TAG, "Package was null!", new Throwable()); 22279 return; 22280 } 22281 prepareAppDataLeafLIF(pkg, userId, flags); 22282 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22283 for (int i = 0; i < childCount; i++) { 22284 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22285 } 22286 } 22287 22288 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22289 boolean maybeMigrateAppData) { 22290 prepareAppDataLIF(pkg, userId, flags); 22291 22292 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22293 // We may have just shuffled around app data directories, so 22294 // prepare them one more time 22295 prepareAppDataLIF(pkg, userId, flags); 22296 } 22297 } 22298 22299 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22300 if (DEBUG_APP_DATA) { 22301 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22302 + Integer.toHexString(flags)); 22303 } 22304 22305 final String volumeUuid = pkg.volumeUuid; 22306 final String packageName = pkg.packageName; 22307 final ApplicationInfo app = pkg.applicationInfo; 22308 final int appId = UserHandle.getAppId(app.uid); 22309 22310 Preconditions.checkNotNull(app.seInfo); 22311 22312 long ceDataInode = -1; 22313 try { 22314 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22315 appId, app.seInfo, app.targetSdkVersion); 22316 } catch (InstallerException e) { 22317 if (app.isSystemApp()) { 22318 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22319 + ", but trying to recover: " + e); 22320 destroyAppDataLeafLIF(pkg, userId, flags); 22321 try { 22322 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22323 appId, app.seInfo, app.targetSdkVersion); 22324 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22325 } catch (InstallerException e2) { 22326 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22327 } 22328 } else { 22329 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22330 } 22331 } 22332 // Prepare the application profiles only for upgrades and first boot (so that we don't 22333 // repeat the same operation at each boot). 22334 // We only have to cover the upgrade and first boot here because for app installs we 22335 // prepare the profiles before invoking dexopt (in installPackageLI). 22336 // 22337 // We also have to cover non system users because we do not call the usual install package 22338 // methods for them. 22339 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22340 mArtManagerService.prepareAppProfiles(pkg, userId); 22341 } 22342 22343 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22344 // TODO: mark this structure as dirty so we persist it! 22345 synchronized (mPackages) { 22346 final PackageSetting ps = mSettings.mPackages.get(packageName); 22347 if (ps != null) { 22348 ps.setCeDataInode(ceDataInode, userId); 22349 } 22350 } 22351 } 22352 22353 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22354 } 22355 22356 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22357 if (pkg == null) { 22358 Slog.wtf(TAG, "Package was null!", new Throwable()); 22359 return; 22360 } 22361 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22362 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22363 for (int i = 0; i < childCount; i++) { 22364 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22365 } 22366 } 22367 22368 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22369 final String volumeUuid = pkg.volumeUuid; 22370 final String packageName = pkg.packageName; 22371 final ApplicationInfo app = pkg.applicationInfo; 22372 22373 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22374 // Create a native library symlink only if we have native libraries 22375 // and if the native libraries are 32 bit libraries. We do not provide 22376 // this symlink for 64 bit libraries. 22377 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22378 final String nativeLibPath = app.nativeLibraryDir; 22379 try { 22380 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22381 nativeLibPath, userId); 22382 } catch (InstallerException e) { 22383 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22384 } 22385 } 22386 } 22387 } 22388 22389 /** 22390 * For system apps on non-FBE devices, this method migrates any existing 22391 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22392 * requested by the app. 22393 */ 22394 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22395 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22396 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22397 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22398 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22399 try { 22400 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22401 storageTarget); 22402 } catch (InstallerException e) { 22403 logCriticalInfo(Log.WARN, 22404 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22405 } 22406 return true; 22407 } else { 22408 return false; 22409 } 22410 } 22411 22412 public PackageFreezer freezePackage(String packageName, String killReason) { 22413 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22414 } 22415 22416 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22417 return new PackageFreezer(packageName, userId, killReason); 22418 } 22419 22420 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22421 String killReason) { 22422 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22423 } 22424 22425 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22426 String killReason) { 22427 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22428 return new PackageFreezer(); 22429 } else { 22430 return freezePackage(packageName, userId, killReason); 22431 } 22432 } 22433 22434 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22435 String killReason) { 22436 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22437 } 22438 22439 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22440 String killReason) { 22441 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22442 return new PackageFreezer(); 22443 } else { 22444 return freezePackage(packageName, userId, killReason); 22445 } 22446 } 22447 22448 /** 22449 * Class that freezes and kills the given package upon creation, and 22450 * unfreezes it upon closing. This is typically used when doing surgery on 22451 * app code/data to prevent the app from running while you're working. 22452 */ 22453 private class PackageFreezer implements AutoCloseable { 22454 private final String mPackageName; 22455 private final PackageFreezer[] mChildren; 22456 22457 private final boolean mWeFroze; 22458 22459 private final AtomicBoolean mClosed = new AtomicBoolean(); 22460 private final CloseGuard mCloseGuard = CloseGuard.get(); 22461 22462 /** 22463 * Create and return a stub freezer that doesn't actually do anything, 22464 * typically used when someone requested 22465 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22466 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22467 */ 22468 public PackageFreezer() { 22469 mPackageName = null; 22470 mChildren = null; 22471 mWeFroze = false; 22472 mCloseGuard.open("close"); 22473 } 22474 22475 public PackageFreezer(String packageName, int userId, String killReason) { 22476 synchronized (mPackages) { 22477 mPackageName = packageName; 22478 mWeFroze = mFrozenPackages.add(mPackageName); 22479 22480 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22481 if (ps != null) { 22482 killApplication(ps.name, ps.appId, userId, killReason); 22483 } 22484 22485 final PackageParser.Package p = mPackages.get(packageName); 22486 if (p != null && p.childPackages != null) { 22487 final int N = p.childPackages.size(); 22488 mChildren = new PackageFreezer[N]; 22489 for (int i = 0; i < N; i++) { 22490 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22491 userId, killReason); 22492 } 22493 } else { 22494 mChildren = null; 22495 } 22496 } 22497 mCloseGuard.open("close"); 22498 } 22499 22500 @Override 22501 protected void finalize() throws Throwable { 22502 try { 22503 if (mCloseGuard != null) { 22504 mCloseGuard.warnIfOpen(); 22505 } 22506 22507 close(); 22508 } finally { 22509 super.finalize(); 22510 } 22511 } 22512 22513 @Override 22514 public void close() { 22515 mCloseGuard.close(); 22516 if (mClosed.compareAndSet(false, true)) { 22517 synchronized (mPackages) { 22518 if (mWeFroze) { 22519 mFrozenPackages.remove(mPackageName); 22520 } 22521 22522 if (mChildren != null) { 22523 for (PackageFreezer freezer : mChildren) { 22524 freezer.close(); 22525 } 22526 } 22527 } 22528 } 22529 } 22530 } 22531 22532 /** 22533 * Verify that given package is currently frozen. 22534 */ 22535 private void checkPackageFrozen(String packageName) { 22536 synchronized (mPackages) { 22537 if (!mFrozenPackages.contains(packageName)) { 22538 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22539 } 22540 } 22541 } 22542 22543 @Override 22544 public int movePackage(final String packageName, final String volumeUuid) { 22545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22546 22547 final int callingUid = Binder.getCallingUid(); 22548 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22549 final int moveId = mNextMoveId.getAndIncrement(); 22550 mHandler.post(new Runnable() { 22551 @Override 22552 public void run() { 22553 try { 22554 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22555 } catch (PackageManagerException e) { 22556 Slog.w(TAG, "Failed to move " + packageName, e); 22557 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22558 } 22559 } 22560 }); 22561 return moveId; 22562 } 22563 22564 private void movePackageInternal(final String packageName, final String volumeUuid, 22565 final int moveId, final int callingUid, UserHandle user) 22566 throws PackageManagerException { 22567 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22568 final PackageManager pm = mContext.getPackageManager(); 22569 22570 final boolean currentAsec; 22571 final String currentVolumeUuid; 22572 final File codeFile; 22573 final String installerPackageName; 22574 final String packageAbiOverride; 22575 final int appId; 22576 final String seinfo; 22577 final String label; 22578 final int targetSdkVersion; 22579 final PackageFreezer freezer; 22580 final int[] installedUserIds; 22581 22582 // reader 22583 synchronized (mPackages) { 22584 final PackageParser.Package pkg = mPackages.get(packageName); 22585 final PackageSetting ps = mSettings.mPackages.get(packageName); 22586 if (pkg == null 22587 || ps == null 22588 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22589 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22590 } 22591 if (pkg.applicationInfo.isSystemApp()) { 22592 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22593 "Cannot move system application"); 22594 } 22595 22596 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22597 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22598 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22599 if (isInternalStorage && !allow3rdPartyOnInternal) { 22600 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22601 "3rd party apps are not allowed on internal storage"); 22602 } 22603 22604 if (pkg.applicationInfo.isExternalAsec()) { 22605 currentAsec = true; 22606 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22607 } else if (pkg.applicationInfo.isForwardLocked()) { 22608 currentAsec = true; 22609 currentVolumeUuid = "forward_locked"; 22610 } else { 22611 currentAsec = false; 22612 currentVolumeUuid = ps.volumeUuid; 22613 22614 final File probe = new File(pkg.codePath); 22615 final File probeOat = new File(probe, "oat"); 22616 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22617 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22618 "Move only supported for modern cluster style installs"); 22619 } 22620 } 22621 22622 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22623 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22624 "Package already moved to " + volumeUuid); 22625 } 22626 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22627 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22628 "Device admin cannot be moved"); 22629 } 22630 22631 if (mFrozenPackages.contains(packageName)) { 22632 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22633 "Failed to move already frozen package"); 22634 } 22635 22636 codeFile = new File(pkg.codePath); 22637 installerPackageName = ps.installerPackageName; 22638 packageAbiOverride = ps.cpuAbiOverrideString; 22639 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22640 seinfo = pkg.applicationInfo.seInfo; 22641 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22642 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22643 freezer = freezePackage(packageName, "movePackageInternal"); 22644 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22645 } 22646 22647 final Bundle extras = new Bundle(); 22648 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22649 extras.putString(Intent.EXTRA_TITLE, label); 22650 mMoveCallbacks.notifyCreated(moveId, extras); 22651 22652 int installFlags; 22653 final boolean moveCompleteApp; 22654 final File measurePath; 22655 22656 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22657 installFlags = INSTALL_INTERNAL; 22658 moveCompleteApp = !currentAsec; 22659 measurePath = Environment.getDataAppDirectory(volumeUuid); 22660 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22661 installFlags = INSTALL_EXTERNAL; 22662 moveCompleteApp = false; 22663 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22664 } else { 22665 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22666 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22667 || !volume.isMountedWritable()) { 22668 freezer.close(); 22669 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22670 "Move location not mounted private volume"); 22671 } 22672 22673 Preconditions.checkState(!currentAsec); 22674 22675 installFlags = INSTALL_INTERNAL; 22676 moveCompleteApp = true; 22677 measurePath = Environment.getDataAppDirectory(volumeUuid); 22678 } 22679 22680 // If we're moving app data around, we need all the users unlocked 22681 if (moveCompleteApp) { 22682 for (int userId : installedUserIds) { 22683 if (StorageManager.isFileEncryptedNativeOrEmulated() 22684 && !StorageManager.isUserKeyUnlocked(userId)) { 22685 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22686 "User " + userId + " must be unlocked"); 22687 } 22688 } 22689 } 22690 22691 final PackageStats stats = new PackageStats(null, -1); 22692 synchronized (mInstaller) { 22693 for (int userId : installedUserIds) { 22694 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22695 freezer.close(); 22696 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22697 "Failed to measure package size"); 22698 } 22699 } 22700 } 22701 22702 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22703 + stats.dataSize); 22704 22705 final long startFreeBytes = measurePath.getUsableSpace(); 22706 final long sizeBytes; 22707 if (moveCompleteApp) { 22708 sizeBytes = stats.codeSize + stats.dataSize; 22709 } else { 22710 sizeBytes = stats.codeSize; 22711 } 22712 22713 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22714 freezer.close(); 22715 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22716 "Not enough free space to move"); 22717 } 22718 22719 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22720 22721 final CountDownLatch installedLatch = new CountDownLatch(1); 22722 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22723 @Override 22724 public void onUserActionRequired(Intent intent) throws RemoteException { 22725 throw new IllegalStateException(); 22726 } 22727 22728 @Override 22729 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22730 Bundle extras) throws RemoteException { 22731 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22732 + PackageManager.installStatusToString(returnCode, msg)); 22733 22734 installedLatch.countDown(); 22735 freezer.close(); 22736 22737 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22738 switch (status) { 22739 case PackageInstaller.STATUS_SUCCESS: 22740 mMoveCallbacks.notifyStatusChanged(moveId, 22741 PackageManager.MOVE_SUCCEEDED); 22742 break; 22743 case PackageInstaller.STATUS_FAILURE_STORAGE: 22744 mMoveCallbacks.notifyStatusChanged(moveId, 22745 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22746 break; 22747 default: 22748 mMoveCallbacks.notifyStatusChanged(moveId, 22749 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22750 break; 22751 } 22752 } 22753 }; 22754 22755 final MoveInfo move; 22756 if (moveCompleteApp) { 22757 // Kick off a thread to report progress estimates 22758 new Thread() { 22759 @Override 22760 public void run() { 22761 while (true) { 22762 try { 22763 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22764 break; 22765 } 22766 } catch (InterruptedException ignored) { 22767 } 22768 22769 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22770 final int progress = 10 + (int) MathUtils.constrain( 22771 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22772 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22773 } 22774 } 22775 }.start(); 22776 22777 final String dataAppName = codeFile.getName(); 22778 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22779 dataAppName, appId, seinfo, targetSdkVersion); 22780 } else { 22781 move = null; 22782 } 22783 22784 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22785 22786 final Message msg = mHandler.obtainMessage(INIT_COPY); 22787 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22788 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22789 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22790 packageAbiOverride, null /*grantedPermissions*/, 22791 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22792 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22793 msg.obj = params; 22794 22795 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22796 System.identityHashCode(msg.obj)); 22797 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22798 System.identityHashCode(msg.obj)); 22799 22800 mHandler.sendMessage(msg); 22801 } 22802 22803 @Override 22804 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22805 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22806 22807 final int realMoveId = mNextMoveId.getAndIncrement(); 22808 final Bundle extras = new Bundle(); 22809 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22810 mMoveCallbacks.notifyCreated(realMoveId, extras); 22811 22812 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22813 @Override 22814 public void onCreated(int moveId, Bundle extras) { 22815 // Ignored 22816 } 22817 22818 @Override 22819 public void onStatusChanged(int moveId, int status, long estMillis) { 22820 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22821 } 22822 }; 22823 22824 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22825 storage.setPrimaryStorageUuid(volumeUuid, callback); 22826 return realMoveId; 22827 } 22828 22829 @Override 22830 public int getMoveStatus(int moveId) { 22831 mContext.enforceCallingOrSelfPermission( 22832 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22833 return mMoveCallbacks.mLastStatus.get(moveId); 22834 } 22835 22836 @Override 22837 public void registerMoveCallback(IPackageMoveObserver callback) { 22838 mContext.enforceCallingOrSelfPermission( 22839 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22840 mMoveCallbacks.register(callback); 22841 } 22842 22843 @Override 22844 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22845 mContext.enforceCallingOrSelfPermission( 22846 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22847 mMoveCallbacks.unregister(callback); 22848 } 22849 22850 @Override 22851 public boolean setInstallLocation(int loc) { 22852 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22853 null); 22854 if (getInstallLocation() == loc) { 22855 return true; 22856 } 22857 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22858 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22859 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22860 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22861 return true; 22862 } 22863 return false; 22864 } 22865 22866 @Override 22867 public int getInstallLocation() { 22868 // allow instant app access 22869 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22870 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22871 PackageHelper.APP_INSTALL_AUTO); 22872 } 22873 22874 /** Called by UserManagerService */ 22875 void cleanUpUser(UserManagerService userManager, int userHandle) { 22876 synchronized (mPackages) { 22877 mDirtyUsers.remove(userHandle); 22878 mUserNeedsBadging.delete(userHandle); 22879 mSettings.removeUserLPw(userHandle); 22880 mPendingBroadcasts.remove(userHandle); 22881 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22882 removeUnusedPackagesLPw(userManager, userHandle); 22883 } 22884 } 22885 22886 /** 22887 * We're removing userHandle and would like to remove any downloaded packages 22888 * that are no longer in use by any other user. 22889 * @param userHandle the user being removed 22890 */ 22891 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22892 final boolean DEBUG_CLEAN_APKS = false; 22893 int [] users = userManager.getUserIds(); 22894 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22895 while (psit.hasNext()) { 22896 PackageSetting ps = psit.next(); 22897 if (ps.pkg == null) { 22898 continue; 22899 } 22900 final String packageName = ps.pkg.packageName; 22901 // Skip over if system app 22902 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22903 continue; 22904 } 22905 if (DEBUG_CLEAN_APKS) { 22906 Slog.i(TAG, "Checking package " + packageName); 22907 } 22908 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22909 if (keep) { 22910 if (DEBUG_CLEAN_APKS) { 22911 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22912 } 22913 } else { 22914 for (int i = 0; i < users.length; i++) { 22915 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22916 keep = true; 22917 if (DEBUG_CLEAN_APKS) { 22918 Slog.i(TAG, " Keeping package " + packageName + " for user " 22919 + users[i]); 22920 } 22921 break; 22922 } 22923 } 22924 } 22925 if (!keep) { 22926 if (DEBUG_CLEAN_APKS) { 22927 Slog.i(TAG, " Removing package " + packageName); 22928 } 22929 mHandler.post(new Runnable() { 22930 public void run() { 22931 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22932 userHandle, 0); 22933 } //end run 22934 }); 22935 } 22936 } 22937 } 22938 22939 /** Called by UserManagerService */ 22940 void createNewUser(int userId, String[] disallowedPackages) { 22941 synchronized (mInstallLock) { 22942 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22943 } 22944 synchronized (mPackages) { 22945 scheduleWritePackageRestrictionsLocked(userId); 22946 scheduleWritePackageListLocked(userId); 22947 applyFactoryDefaultBrowserLPw(userId); 22948 primeDomainVerificationsLPw(userId); 22949 } 22950 } 22951 22952 void onNewUserCreated(final int userId) { 22953 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22954 synchronized(mPackages) { 22955 // If permission review for legacy apps is required, we represent 22956 // dagerous permissions for such apps as always granted runtime 22957 // permissions to keep per user flag state whether review is needed. 22958 // Hence, if a new user is added we have to propagate dangerous 22959 // permission grants for these legacy apps. 22960 if (mSettings.mPermissions.mPermissionReviewRequired) { 22961// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22962 mPermissionManager.updateAllPermissions( 22963 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22964 mPermissionCallback); 22965 } 22966 } 22967 } 22968 22969 @Override 22970 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22971 mContext.enforceCallingOrSelfPermission( 22972 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22973 "Only package verification agents can read the verifier device identity"); 22974 22975 synchronized (mPackages) { 22976 return mSettings.getVerifierDeviceIdentityLPw(); 22977 } 22978 } 22979 22980 @Override 22981 public void setPermissionEnforced(String permission, boolean enforced) { 22982 // TODO: Now that we no longer change GID for storage, this should to away. 22983 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22984 "setPermissionEnforced"); 22985 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22986 synchronized (mPackages) { 22987 if (mSettings.mReadExternalStorageEnforced == null 22988 || mSettings.mReadExternalStorageEnforced != enforced) { 22989 mSettings.mReadExternalStorageEnforced = 22990 enforced ? Boolean.TRUE : Boolean.FALSE; 22991 mSettings.writeLPr(); 22992 } 22993 } 22994 // kill any non-foreground processes so we restart them and 22995 // grant/revoke the GID. 22996 final IActivityManager am = ActivityManager.getService(); 22997 if (am != null) { 22998 final long token = Binder.clearCallingIdentity(); 22999 try { 23000 am.killProcessesBelowForeground("setPermissionEnforcement"); 23001 } catch (RemoteException e) { 23002 } finally { 23003 Binder.restoreCallingIdentity(token); 23004 } 23005 } 23006 } else { 23007 throw new IllegalArgumentException("No selective enforcement for " + permission); 23008 } 23009 } 23010 23011 @Override 23012 @Deprecated 23013 public boolean isPermissionEnforced(String permission) { 23014 // allow instant applications 23015 return true; 23016 } 23017 23018 @Override 23019 public boolean isStorageLow() { 23020 // allow instant applications 23021 final long token = Binder.clearCallingIdentity(); 23022 try { 23023 final DeviceStorageMonitorInternal 23024 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23025 if (dsm != null) { 23026 return dsm.isMemoryLow(); 23027 } else { 23028 return false; 23029 } 23030 } finally { 23031 Binder.restoreCallingIdentity(token); 23032 } 23033 } 23034 23035 @Override 23036 public IPackageInstaller getPackageInstaller() { 23037 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23038 return null; 23039 } 23040 return mInstallerService; 23041 } 23042 23043 @Override 23044 public IArtManager getArtManager() { 23045 return mArtManagerService; 23046 } 23047 23048 private boolean userNeedsBadging(int userId) { 23049 int index = mUserNeedsBadging.indexOfKey(userId); 23050 if (index < 0) { 23051 final UserInfo userInfo; 23052 final long token = Binder.clearCallingIdentity(); 23053 try { 23054 userInfo = sUserManager.getUserInfo(userId); 23055 } finally { 23056 Binder.restoreCallingIdentity(token); 23057 } 23058 final boolean b; 23059 if (userInfo != null && userInfo.isManagedProfile()) { 23060 b = true; 23061 } else { 23062 b = false; 23063 } 23064 mUserNeedsBadging.put(userId, b); 23065 return b; 23066 } 23067 return mUserNeedsBadging.valueAt(index); 23068 } 23069 23070 @Override 23071 public KeySet getKeySetByAlias(String packageName, String alias) { 23072 if (packageName == null || alias == null) { 23073 return null; 23074 } 23075 synchronized(mPackages) { 23076 final PackageParser.Package pkg = mPackages.get(packageName); 23077 if (pkg == null) { 23078 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23079 throw new IllegalArgumentException("Unknown package: " + packageName); 23080 } 23081 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23082 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23083 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23084 throw new IllegalArgumentException("Unknown package: " + packageName); 23085 } 23086 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23087 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23088 } 23089 } 23090 23091 @Override 23092 public KeySet getSigningKeySet(String packageName) { 23093 if (packageName == null) { 23094 return null; 23095 } 23096 synchronized(mPackages) { 23097 final int callingUid = Binder.getCallingUid(); 23098 final int callingUserId = UserHandle.getUserId(callingUid); 23099 final PackageParser.Package pkg = mPackages.get(packageName); 23100 if (pkg == null) { 23101 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23102 throw new IllegalArgumentException("Unknown package: " + packageName); 23103 } 23104 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23105 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23106 // filter and pretend the package doesn't exist 23107 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23108 + ", uid:" + callingUid); 23109 throw new IllegalArgumentException("Unknown package: " + packageName); 23110 } 23111 if (pkg.applicationInfo.uid != callingUid 23112 && Process.SYSTEM_UID != callingUid) { 23113 throw new SecurityException("May not access signing KeySet of other apps."); 23114 } 23115 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23116 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23117 } 23118 } 23119 23120 @Override 23121 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23122 final int callingUid = Binder.getCallingUid(); 23123 if (getInstantAppPackageName(callingUid) != null) { 23124 return false; 23125 } 23126 if (packageName == null || ks == null) { 23127 return false; 23128 } 23129 synchronized(mPackages) { 23130 final PackageParser.Package pkg = mPackages.get(packageName); 23131 if (pkg == null 23132 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23133 UserHandle.getUserId(callingUid))) { 23134 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23135 throw new IllegalArgumentException("Unknown package: " + packageName); 23136 } 23137 IBinder ksh = ks.getToken(); 23138 if (ksh instanceof KeySetHandle) { 23139 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23140 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23141 } 23142 return false; 23143 } 23144 } 23145 23146 @Override 23147 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23148 final int callingUid = Binder.getCallingUid(); 23149 if (getInstantAppPackageName(callingUid) != null) { 23150 return false; 23151 } 23152 if (packageName == null || ks == null) { 23153 return false; 23154 } 23155 synchronized(mPackages) { 23156 final PackageParser.Package pkg = mPackages.get(packageName); 23157 if (pkg == null 23158 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23159 UserHandle.getUserId(callingUid))) { 23160 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23161 throw new IllegalArgumentException("Unknown package: " + packageName); 23162 } 23163 IBinder ksh = ks.getToken(); 23164 if (ksh instanceof KeySetHandle) { 23165 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23166 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23167 } 23168 return false; 23169 } 23170 } 23171 23172 private void deletePackageIfUnusedLPr(final String packageName) { 23173 PackageSetting ps = mSettings.mPackages.get(packageName); 23174 if (ps == null) { 23175 return; 23176 } 23177 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23178 // TODO Implement atomic delete if package is unused 23179 // It is currently possible that the package will be deleted even if it is installed 23180 // after this method returns. 23181 mHandler.post(new Runnable() { 23182 public void run() { 23183 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23184 0, PackageManager.DELETE_ALL_USERS); 23185 } 23186 }); 23187 } 23188 } 23189 23190 /** 23191 * Check and throw if the given before/after packages would be considered a 23192 * downgrade. 23193 */ 23194 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23195 throws PackageManagerException { 23196 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23197 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23198 "Update version code " + after.versionCode + " is older than current " 23199 + before.getLongVersionCode()); 23200 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23201 if (after.baseRevisionCode < before.baseRevisionCode) { 23202 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23203 "Update base revision code " + after.baseRevisionCode 23204 + " is older than current " + before.baseRevisionCode); 23205 } 23206 23207 if (!ArrayUtils.isEmpty(after.splitNames)) { 23208 for (int i = 0; i < after.splitNames.length; i++) { 23209 final String splitName = after.splitNames[i]; 23210 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23211 if (j != -1) { 23212 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23213 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23214 "Update split " + splitName + " revision code " 23215 + after.splitRevisionCodes[i] + " is older than current " 23216 + before.splitRevisionCodes[j]); 23217 } 23218 } 23219 } 23220 } 23221 } 23222 } 23223 23224 private static class MoveCallbacks extends Handler { 23225 private static final int MSG_CREATED = 1; 23226 private static final int MSG_STATUS_CHANGED = 2; 23227 23228 private final RemoteCallbackList<IPackageMoveObserver> 23229 mCallbacks = new RemoteCallbackList<>(); 23230 23231 private final SparseIntArray mLastStatus = new SparseIntArray(); 23232 23233 public MoveCallbacks(Looper looper) { 23234 super(looper); 23235 } 23236 23237 public void register(IPackageMoveObserver callback) { 23238 mCallbacks.register(callback); 23239 } 23240 23241 public void unregister(IPackageMoveObserver callback) { 23242 mCallbacks.unregister(callback); 23243 } 23244 23245 @Override 23246 public void handleMessage(Message msg) { 23247 final SomeArgs args = (SomeArgs) msg.obj; 23248 final int n = mCallbacks.beginBroadcast(); 23249 for (int i = 0; i < n; i++) { 23250 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23251 try { 23252 invokeCallback(callback, msg.what, args); 23253 } catch (RemoteException ignored) { 23254 } 23255 } 23256 mCallbacks.finishBroadcast(); 23257 args.recycle(); 23258 } 23259 23260 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23261 throws RemoteException { 23262 switch (what) { 23263 case MSG_CREATED: { 23264 callback.onCreated(args.argi1, (Bundle) args.arg2); 23265 break; 23266 } 23267 case MSG_STATUS_CHANGED: { 23268 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23269 break; 23270 } 23271 } 23272 } 23273 23274 private void notifyCreated(int moveId, Bundle extras) { 23275 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23276 23277 final SomeArgs args = SomeArgs.obtain(); 23278 args.argi1 = moveId; 23279 args.arg2 = extras; 23280 obtainMessage(MSG_CREATED, args).sendToTarget(); 23281 } 23282 23283 private void notifyStatusChanged(int moveId, int status) { 23284 notifyStatusChanged(moveId, status, -1); 23285 } 23286 23287 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23288 Slog.v(TAG, "Move " + moveId + " status " + status); 23289 23290 final SomeArgs args = SomeArgs.obtain(); 23291 args.argi1 = moveId; 23292 args.argi2 = status; 23293 args.arg3 = estMillis; 23294 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23295 23296 synchronized (mLastStatus) { 23297 mLastStatus.put(moveId, status); 23298 } 23299 } 23300 } 23301 23302 private final static class OnPermissionChangeListeners extends Handler { 23303 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23304 23305 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23306 new RemoteCallbackList<>(); 23307 23308 public OnPermissionChangeListeners(Looper looper) { 23309 super(looper); 23310 } 23311 23312 @Override 23313 public void handleMessage(Message msg) { 23314 switch (msg.what) { 23315 case MSG_ON_PERMISSIONS_CHANGED: { 23316 final int uid = msg.arg1; 23317 handleOnPermissionsChanged(uid); 23318 } break; 23319 } 23320 } 23321 23322 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23323 mPermissionListeners.register(listener); 23324 23325 } 23326 23327 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23328 mPermissionListeners.unregister(listener); 23329 } 23330 23331 public void onPermissionsChanged(int uid) { 23332 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23333 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23334 } 23335 } 23336 23337 private void handleOnPermissionsChanged(int uid) { 23338 final int count = mPermissionListeners.beginBroadcast(); 23339 try { 23340 for (int i = 0; i < count; i++) { 23341 IOnPermissionsChangeListener callback = mPermissionListeners 23342 .getBroadcastItem(i); 23343 try { 23344 callback.onPermissionsChanged(uid); 23345 } catch (RemoteException e) { 23346 Log.e(TAG, "Permission listener is dead", e); 23347 } 23348 } 23349 } finally { 23350 mPermissionListeners.finishBroadcast(); 23351 } 23352 } 23353 } 23354 23355 private class PackageManagerNative extends IPackageManagerNative.Stub { 23356 @Override 23357 public String[] getNamesForUids(int[] uids) throws RemoteException { 23358 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23359 // massage results so they can be parsed by the native binder 23360 for (int i = results.length - 1; i >= 0; --i) { 23361 if (results[i] == null) { 23362 results[i] = ""; 23363 } 23364 } 23365 return results; 23366 } 23367 23368 // NB: this differentiates between preloads and sideloads 23369 @Override 23370 public String getInstallerForPackage(String packageName) throws RemoteException { 23371 final String installerName = getInstallerPackageName(packageName); 23372 if (!TextUtils.isEmpty(installerName)) { 23373 return installerName; 23374 } 23375 // differentiate between preload and sideload 23376 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23377 ApplicationInfo appInfo = getApplicationInfo(packageName, 23378 /*flags*/ 0, 23379 /*userId*/ callingUser); 23380 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23381 return "preload"; 23382 } 23383 return ""; 23384 } 23385 23386 @Override 23387 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23388 try { 23389 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23390 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23391 if (pInfo != null) { 23392 return pInfo.getLongVersionCode(); 23393 } 23394 } catch (Exception e) { 23395 } 23396 return 0; 23397 } 23398 } 23399 23400 private class PackageManagerInternalImpl extends PackageManagerInternal { 23401 @Override 23402 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23403 int flagValues, int userId) { 23404 PackageManagerService.this.updatePermissionFlags( 23405 permName, packageName, flagMask, flagValues, userId); 23406 } 23407 23408 @Override 23409 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 23410 SigningDetails sd = getSigningDetails(packageName); 23411 if (sd == null) { 23412 return false; 23413 } 23414 return sd.hasSha256Certificate(restoringFromSigHash, 23415 SigningDetails.CertCapabilities.INSTALLED_DATA); 23416 } 23417 23418 @Override 23419 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 23420 SigningDetails sd = getSigningDetails(packageName); 23421 if (sd == null) { 23422 return false; 23423 } 23424 return sd.hasCertificate(restoringFromSig, 23425 SigningDetails.CertCapabilities.INSTALLED_DATA); 23426 } 23427 23428 private SigningDetails getSigningDetails(@NonNull String packageName) { 23429 synchronized (mPackages) { 23430 PackageParser.Package p = mPackages.get(packageName); 23431 if (p == null) { 23432 return null; 23433 } 23434 return p.mSigningDetails; 23435 } 23436 } 23437 23438 @Override 23439 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23440 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23441 } 23442 23443 @Override 23444 public boolean isInstantApp(String packageName, int userId) { 23445 return PackageManagerService.this.isInstantApp(packageName, userId); 23446 } 23447 23448 @Override 23449 public String getInstantAppPackageName(int uid) { 23450 return PackageManagerService.this.getInstantAppPackageName(uid); 23451 } 23452 23453 @Override 23454 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23455 synchronized (mPackages) { 23456 return PackageManagerService.this.filterAppAccessLPr( 23457 (PackageSetting) pkg.mExtras, callingUid, userId); 23458 } 23459 } 23460 23461 @Override 23462 public PackageParser.Package getPackage(String packageName) { 23463 synchronized (mPackages) { 23464 packageName = resolveInternalPackageNameLPr( 23465 packageName, PackageManager.VERSION_CODE_HIGHEST); 23466 return mPackages.get(packageName); 23467 } 23468 } 23469 23470 @Override 23471 public PackageList getPackageList(PackageListObserver observer) { 23472 synchronized (mPackages) { 23473 final int N = mPackages.size(); 23474 final ArrayList<String> list = new ArrayList<>(N); 23475 for (int i = 0; i < N; i++) { 23476 list.add(mPackages.keyAt(i)); 23477 } 23478 final PackageList packageList = new PackageList(list, observer); 23479 if (observer != null) { 23480 mPackageListObservers.add(packageList); 23481 } 23482 return packageList; 23483 } 23484 } 23485 23486 @Override 23487 public void removePackageListObserver(PackageListObserver observer) { 23488 synchronized (mPackages) { 23489 mPackageListObservers.remove(observer); 23490 } 23491 } 23492 23493 @Override 23494 public PackageParser.Package getDisabledPackage(String packageName) { 23495 synchronized (mPackages) { 23496 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23497 return (ps != null) ? ps.pkg : null; 23498 } 23499 } 23500 23501 @Override 23502 public String getKnownPackageName(int knownPackage, int userId) { 23503 switch(knownPackage) { 23504 case PackageManagerInternal.PACKAGE_BROWSER: 23505 return getDefaultBrowserPackageName(userId); 23506 case PackageManagerInternal.PACKAGE_INSTALLER: 23507 return mRequiredInstallerPackage; 23508 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23509 return mSetupWizardPackage; 23510 case PackageManagerInternal.PACKAGE_SYSTEM: 23511 return "android"; 23512 case PackageManagerInternal.PACKAGE_VERIFIER: 23513 return mRequiredVerifierPackage; 23514 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23515 return mSystemTextClassifierPackage; 23516 } 23517 return null; 23518 } 23519 23520 @Override 23521 public boolean isResolveActivityComponent(ComponentInfo component) { 23522 return mResolveActivity.packageName.equals(component.packageName) 23523 && mResolveActivity.name.equals(component.name); 23524 } 23525 23526 @Override 23527 public void setLocationPackagesProvider(PackagesProvider provider) { 23528 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23529 } 23530 23531 @Override 23532 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23533 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23534 } 23535 23536 @Override 23537 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23538 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23539 } 23540 23541 @Override 23542 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23543 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23544 } 23545 23546 @Override 23547 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23548 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23549 } 23550 23551 @Override 23552 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23553 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23554 } 23555 23556 @Override 23557 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23558 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23559 } 23560 23561 @Override 23562 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23563 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23564 } 23565 23566 @Override 23567 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23568 synchronized (mPackages) { 23569 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23570 } 23571 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23572 } 23573 23574 @Override 23575 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23576 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23577 packageName, userId); 23578 } 23579 23580 @Override 23581 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23582 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23583 packageName, userId); 23584 } 23585 23586 @Override 23587 public void setKeepUninstalledPackages(final List<String> packageList) { 23588 Preconditions.checkNotNull(packageList); 23589 List<String> removedFromList = null; 23590 synchronized (mPackages) { 23591 if (mKeepUninstalledPackages != null) { 23592 final int packagesCount = mKeepUninstalledPackages.size(); 23593 for (int i = 0; i < packagesCount; i++) { 23594 String oldPackage = mKeepUninstalledPackages.get(i); 23595 if (packageList != null && packageList.contains(oldPackage)) { 23596 continue; 23597 } 23598 if (removedFromList == null) { 23599 removedFromList = new ArrayList<>(); 23600 } 23601 removedFromList.add(oldPackage); 23602 } 23603 } 23604 mKeepUninstalledPackages = new ArrayList<>(packageList); 23605 if (removedFromList != null) { 23606 final int removedCount = removedFromList.size(); 23607 for (int i = 0; i < removedCount; i++) { 23608 deletePackageIfUnusedLPr(removedFromList.get(i)); 23609 } 23610 } 23611 } 23612 } 23613 23614 @Override 23615 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23616 synchronized (mPackages) { 23617 return mPermissionManager.isPermissionsReviewRequired( 23618 mPackages.get(packageName), userId); 23619 } 23620 } 23621 23622 @Override 23623 public PackageInfo getPackageInfo( 23624 String packageName, int flags, int filterCallingUid, int userId) { 23625 return PackageManagerService.this 23626 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23627 flags, filterCallingUid, userId); 23628 } 23629 23630 @Override 23631 public int getPackageUid(String packageName, int flags, int userId) { 23632 return PackageManagerService.this 23633 .getPackageUid(packageName, flags, userId); 23634 } 23635 23636 @Override 23637 public ApplicationInfo getApplicationInfo( 23638 String packageName, int flags, int filterCallingUid, int userId) { 23639 return PackageManagerService.this 23640 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23641 } 23642 23643 @Override 23644 public ActivityInfo getActivityInfo( 23645 ComponentName component, int flags, int filterCallingUid, int userId) { 23646 return PackageManagerService.this 23647 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23648 } 23649 23650 @Override 23651 public List<ResolveInfo> queryIntentActivities( 23652 Intent intent, int flags, int filterCallingUid, int userId) { 23653 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23654 return PackageManagerService.this 23655 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23656 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23657 } 23658 23659 @Override 23660 public List<ResolveInfo> queryIntentServices( 23661 Intent intent, int flags, int callingUid, int userId) { 23662 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23663 return PackageManagerService.this 23664 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23665 false); 23666 } 23667 23668 @Override 23669 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23670 int userId) { 23671 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23672 } 23673 23674 @Override 23675 public ComponentName getDefaultHomeActivity(int userId) { 23676 return PackageManagerService.this.getDefaultHomeActivity(userId); 23677 } 23678 23679 @Override 23680 public void setDeviceAndProfileOwnerPackages( 23681 int deviceOwnerUserId, String deviceOwnerPackage, 23682 SparseArray<String> profileOwnerPackages) { 23683 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23684 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23685 } 23686 23687 @Override 23688 public boolean isPackageDataProtected(int userId, String packageName) { 23689 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23690 } 23691 23692 @Override 23693 public boolean isPackageEphemeral(int userId, String packageName) { 23694 synchronized (mPackages) { 23695 final PackageSetting ps = mSettings.mPackages.get(packageName); 23696 return ps != null ? ps.getInstantApp(userId) : false; 23697 } 23698 } 23699 23700 @Override 23701 public boolean wasPackageEverLaunched(String packageName, int userId) { 23702 synchronized (mPackages) { 23703 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23704 } 23705 } 23706 23707 @Override 23708 public void grantRuntimePermission(String packageName, String permName, int userId, 23709 boolean overridePolicy) { 23710 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23711 permName, packageName, overridePolicy, getCallingUid(), userId, 23712 mPermissionCallback); 23713 } 23714 23715 @Override 23716 public void revokeRuntimePermission(String packageName, String permName, int userId, 23717 boolean overridePolicy) { 23718 mPermissionManager.revokeRuntimePermission( 23719 permName, packageName, overridePolicy, getCallingUid(), userId, 23720 mPermissionCallback); 23721 } 23722 23723 @Override 23724 public String getNameForUid(int uid) { 23725 return PackageManagerService.this.getNameForUid(uid); 23726 } 23727 23728 @Override 23729 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23730 Intent origIntent, String resolvedType, String callingPackage, 23731 Bundle verificationBundle, int userId) { 23732 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23733 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23734 userId); 23735 } 23736 23737 @Override 23738 public void grantEphemeralAccess(int userId, Intent intent, 23739 int targetAppId, int ephemeralAppId) { 23740 synchronized (mPackages) { 23741 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23742 targetAppId, ephemeralAppId); 23743 } 23744 } 23745 23746 @Override 23747 public boolean isInstantAppInstallerComponent(ComponentName component) { 23748 synchronized (mPackages) { 23749 return mInstantAppInstallerActivity != null 23750 && mInstantAppInstallerActivity.getComponentName().equals(component); 23751 } 23752 } 23753 23754 @Override 23755 public void pruneInstantApps() { 23756 mInstantAppRegistry.pruneInstantApps(); 23757 } 23758 23759 @Override 23760 public String getSetupWizardPackageName() { 23761 return mSetupWizardPackage; 23762 } 23763 23764 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23765 if (policy != null) { 23766 mExternalSourcesPolicy = policy; 23767 } 23768 } 23769 23770 @Override 23771 public boolean isPackagePersistent(String packageName) { 23772 synchronized (mPackages) { 23773 PackageParser.Package pkg = mPackages.get(packageName); 23774 return pkg != null 23775 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23776 | ApplicationInfo.FLAG_PERSISTENT)) == 23777 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23778 : false; 23779 } 23780 } 23781 23782 @Override 23783 public boolean isLegacySystemApp(Package pkg) { 23784 synchronized (mPackages) { 23785 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23786 return mPromoteSystemApps 23787 && ps.isSystem() 23788 && mExistingSystemPackages.contains(ps.name); 23789 } 23790 } 23791 23792 @Override 23793 public List<PackageInfo> getOverlayPackages(int userId) { 23794 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23795 synchronized (mPackages) { 23796 for (PackageParser.Package p : mPackages.values()) { 23797 if (p.mOverlayTarget != null) { 23798 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23799 if (pkg != null) { 23800 overlayPackages.add(pkg); 23801 } 23802 } 23803 } 23804 } 23805 return overlayPackages; 23806 } 23807 23808 @Override 23809 public List<String> getTargetPackageNames(int userId) { 23810 List<String> targetPackages = new ArrayList<>(); 23811 synchronized (mPackages) { 23812 for (PackageParser.Package p : mPackages.values()) { 23813 if (p.mOverlayTarget == null) { 23814 targetPackages.add(p.packageName); 23815 } 23816 } 23817 } 23818 return targetPackages; 23819 } 23820 23821 @Override 23822 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23823 @Nullable List<String> overlayPackageNames) { 23824 synchronized (mPackages) { 23825 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23826 Slog.e(TAG, "failed to find package " + targetPackageName); 23827 return false; 23828 } 23829 ArrayList<String> overlayPaths = null; 23830 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23831 final int N = overlayPackageNames.size(); 23832 overlayPaths = new ArrayList<>(N); 23833 for (int i = 0; i < N; i++) { 23834 final String packageName = overlayPackageNames.get(i); 23835 final PackageParser.Package pkg = mPackages.get(packageName); 23836 if (pkg == null) { 23837 Slog.e(TAG, "failed to find package " + packageName); 23838 return false; 23839 } 23840 overlayPaths.add(pkg.baseCodePath); 23841 } 23842 } 23843 23844 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23845 ps.setOverlayPaths(overlayPaths, userId); 23846 return true; 23847 } 23848 } 23849 23850 @Override 23851 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23852 int flags, int userId, boolean resolveForStart) { 23853 return resolveIntentInternal( 23854 intent, resolvedType, flags, userId, resolveForStart); 23855 } 23856 23857 @Override 23858 public ResolveInfo resolveService(Intent intent, String resolvedType, 23859 int flags, int userId, int callingUid) { 23860 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23861 } 23862 23863 @Override 23864 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23865 return PackageManagerService.this.resolveContentProviderInternal( 23866 name, flags, userId); 23867 } 23868 23869 @Override 23870 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23871 synchronized (mPackages) { 23872 mIsolatedOwners.put(isolatedUid, ownerUid); 23873 } 23874 } 23875 23876 @Override 23877 public void removeIsolatedUid(int isolatedUid) { 23878 synchronized (mPackages) { 23879 mIsolatedOwners.delete(isolatedUid); 23880 } 23881 } 23882 23883 @Override 23884 public int getUidTargetSdkVersion(int uid) { 23885 synchronized (mPackages) { 23886 return getUidTargetSdkVersionLockedLPr(uid); 23887 } 23888 } 23889 23890 @Override 23891 public int getPackageTargetSdkVersion(String packageName) { 23892 synchronized (mPackages) { 23893 return getPackageTargetSdkVersionLockedLPr(packageName); 23894 } 23895 } 23896 23897 @Override 23898 public boolean canAccessInstantApps(int callingUid, int userId) { 23899 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23900 } 23901 23902 @Override 23903 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 23904 synchronized (mPackages) { 23905 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 23906 return !PackageManagerService.this.filterAppAccessLPr( 23907 ps, callingUid, component, TYPE_UNKNOWN, userId); 23908 } 23909 } 23910 23911 @Override 23912 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23913 synchronized (mPackages) { 23914 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23915 } 23916 } 23917 23918 @Override 23919 public void notifyPackageUse(String packageName, int reason) { 23920 synchronized (mPackages) { 23921 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23922 } 23923 } 23924 } 23925 23926 @Override 23927 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23928 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23929 synchronized (mPackages) { 23930 final long identity = Binder.clearCallingIdentity(); 23931 try { 23932 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23933 packageNames, userId); 23934 } finally { 23935 Binder.restoreCallingIdentity(identity); 23936 } 23937 } 23938 } 23939 23940 @Override 23941 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23942 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23943 synchronized (mPackages) { 23944 final long identity = Binder.clearCallingIdentity(); 23945 try { 23946 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23947 packageNames, userId); 23948 } finally { 23949 Binder.restoreCallingIdentity(identity); 23950 } 23951 } 23952 } 23953 23954 private static void enforceSystemOrPhoneCaller(String tag) { 23955 int callingUid = Binder.getCallingUid(); 23956 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23957 throw new SecurityException( 23958 "Cannot call " + tag + " from UID " + callingUid); 23959 } 23960 } 23961 23962 boolean isHistoricalPackageUsageAvailable() { 23963 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23964 } 23965 23966 /** 23967 * Return a <b>copy</b> of the collection of packages known to the package manager. 23968 * @return A copy of the values of mPackages. 23969 */ 23970 Collection<PackageParser.Package> getPackages() { 23971 synchronized (mPackages) { 23972 return new ArrayList<>(mPackages.values()); 23973 } 23974 } 23975 23976 /** 23977 * Logs process start information (including base APK hash) to the security log. 23978 * @hide 23979 */ 23980 @Override 23981 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23982 String apkFile, int pid) { 23983 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23984 return; 23985 } 23986 if (!SecurityLog.isLoggingEnabled()) { 23987 return; 23988 } 23989 Bundle data = new Bundle(); 23990 data.putLong("startTimestamp", System.currentTimeMillis()); 23991 data.putString("processName", processName); 23992 data.putInt("uid", uid); 23993 data.putString("seinfo", seinfo); 23994 data.putString("apkFile", apkFile); 23995 data.putInt("pid", pid); 23996 Message msg = mProcessLoggingHandler.obtainMessage( 23997 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23998 msg.setData(data); 23999 mProcessLoggingHandler.sendMessage(msg); 24000 } 24001 24002 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24003 return mCompilerStats.getPackageStats(pkgName); 24004 } 24005 24006 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24007 return getOrCreateCompilerPackageStats(pkg.packageName); 24008 } 24009 24010 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24011 return mCompilerStats.getOrCreatePackageStats(pkgName); 24012 } 24013 24014 public void deleteCompilerPackageStats(String pkgName) { 24015 mCompilerStats.deletePackageStats(pkgName); 24016 } 24017 24018 @Override 24019 public int getInstallReason(String packageName, int userId) { 24020 final int callingUid = Binder.getCallingUid(); 24021 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24022 true /* requireFullPermission */, false /* checkShell */, 24023 "get install reason"); 24024 synchronized (mPackages) { 24025 final PackageSetting ps = mSettings.mPackages.get(packageName); 24026 if (filterAppAccessLPr(ps, callingUid, userId)) { 24027 return PackageManager.INSTALL_REASON_UNKNOWN; 24028 } 24029 if (ps != null) { 24030 return ps.getInstallReason(userId); 24031 } 24032 } 24033 return PackageManager.INSTALL_REASON_UNKNOWN; 24034 } 24035 24036 @Override 24037 public boolean canRequestPackageInstalls(String packageName, int userId) { 24038 return canRequestPackageInstallsInternal(packageName, 0, userId, 24039 true /* throwIfPermNotDeclared*/); 24040 } 24041 24042 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24043 boolean throwIfPermNotDeclared) { 24044 int callingUid = Binder.getCallingUid(); 24045 int uid = getPackageUid(packageName, 0, userId); 24046 if (callingUid != uid && callingUid != Process.ROOT_UID 24047 && callingUid != Process.SYSTEM_UID) { 24048 throw new SecurityException( 24049 "Caller uid " + callingUid + " does not own package " + packageName); 24050 } 24051 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24052 if (info == null) { 24053 return false; 24054 } 24055 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24056 return false; 24057 } 24058 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24059 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24060 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24061 if (throwIfPermNotDeclared) { 24062 throw new SecurityException("Need to declare " + appOpPermission 24063 + " to call this api"); 24064 } else { 24065 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24066 return false; 24067 } 24068 } 24069 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24070 return false; 24071 } 24072 if (mExternalSourcesPolicy != null) { 24073 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24074 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24075 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24076 } 24077 } 24078 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24079 } 24080 24081 @Override 24082 public ComponentName getInstantAppResolverSettingsComponent() { 24083 return mInstantAppResolverSettingsComponent; 24084 } 24085 24086 @Override 24087 public ComponentName getInstantAppInstallerComponent() { 24088 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24089 return null; 24090 } 24091 return mInstantAppInstallerActivity == null 24092 ? null : mInstantAppInstallerActivity.getComponentName(); 24093 } 24094 24095 @Override 24096 public String getInstantAppAndroidId(String packageName, int userId) { 24097 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24098 "getInstantAppAndroidId"); 24099 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 24100 true /* requireFullPermission */, false /* checkShell */, 24101 "getInstantAppAndroidId"); 24102 // Make sure the target is an Instant App. 24103 if (!isInstantApp(packageName, userId)) { 24104 return null; 24105 } 24106 synchronized (mPackages) { 24107 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24108 } 24109 } 24110 24111 boolean canHaveOatDir(String packageName) { 24112 synchronized (mPackages) { 24113 PackageParser.Package p = mPackages.get(packageName); 24114 if (p == null) { 24115 return false; 24116 } 24117 return p.canHaveOatDir(); 24118 } 24119 } 24120 24121 private String getOatDir(PackageParser.Package pkg) { 24122 if (!pkg.canHaveOatDir()) { 24123 return null; 24124 } 24125 File codePath = new File(pkg.codePath); 24126 if (codePath.isDirectory()) { 24127 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24128 } 24129 return null; 24130 } 24131 24132 void deleteOatArtifactsOfPackage(String packageName) { 24133 final String[] instructionSets; 24134 final List<String> codePaths; 24135 final String oatDir; 24136 final PackageParser.Package pkg; 24137 synchronized (mPackages) { 24138 pkg = mPackages.get(packageName); 24139 } 24140 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24141 codePaths = pkg.getAllCodePaths(); 24142 oatDir = getOatDir(pkg); 24143 24144 for (String codePath : codePaths) { 24145 for (String isa : instructionSets) { 24146 try { 24147 mInstaller.deleteOdex(codePath, isa, oatDir); 24148 } catch (InstallerException e) { 24149 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24150 } 24151 } 24152 } 24153 } 24154 24155 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24156 Set<String> unusedPackages = new HashSet<>(); 24157 long currentTimeInMillis = System.currentTimeMillis(); 24158 synchronized (mPackages) { 24159 for (PackageParser.Package pkg : mPackages.values()) { 24160 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24161 if (ps == null) { 24162 continue; 24163 } 24164 PackageDexUsage.PackageUseInfo packageUseInfo = 24165 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24166 if (PackageManagerServiceUtils 24167 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24168 downgradeTimeThresholdMillis, packageUseInfo, 24169 pkg.getLatestPackageUseTimeInMills(), 24170 pkg.getLatestForegroundPackageUseTimeInMills())) { 24171 unusedPackages.add(pkg.packageName); 24172 } 24173 } 24174 } 24175 return unusedPackages; 24176 } 24177 24178 @Override 24179 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24180 int userId) { 24181 final int callingUid = Binder.getCallingUid(); 24182 final int callingAppId = UserHandle.getAppId(callingUid); 24183 24184 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24185 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24186 24187 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24188 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24189 throw new SecurityException("Caller must have the " 24190 + SET_HARMFUL_APP_WARNINGS + " permission."); 24191 } 24192 24193 synchronized(mPackages) { 24194 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24195 scheduleWritePackageRestrictionsLocked(userId); 24196 } 24197 } 24198 24199 @Nullable 24200 @Override 24201 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24202 final int callingUid = Binder.getCallingUid(); 24203 final int callingAppId = UserHandle.getAppId(callingUid); 24204 24205 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24206 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24207 24208 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24209 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24210 throw new SecurityException("Caller must have the " 24211 + SET_HARMFUL_APP_WARNINGS + " permission."); 24212 } 24213 24214 synchronized(mPackages) { 24215 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24216 } 24217 } 24218} 24219 24220interface PackageSender { 24221 /** 24222 * @param userIds User IDs where the action occurred on a full application 24223 * @param instantUserIds User IDs where the action occurred on an instant application 24224 */ 24225 void sendPackageBroadcast(final String action, final String pkg, 24226 final Bundle extras, final int flags, final String targetPkg, 24227 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24228 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24229 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24230 void notifyPackageAdded(String packageName); 24231 void notifyPackageRemoved(String packageName); 24232} 24233