PackageManagerService.java revision 7cc9a817d4a0e2d0dc10f982b54f855351432a82
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.MANAGE_DEVICE_ADMINS; 21import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 22import static android.Manifest.permission.INSTALL_PACKAGES; 23import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 24import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 25import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 26import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 27import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 28import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 29import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 34import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 35import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 42import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 43import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 44import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 45import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 52import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 53import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 54import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 55import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 57import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 58import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 59import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 60import static android.content.pm.PackageManager.INSTALL_INTERNAL; 61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 67import static android.content.pm.PackageManager.MATCH_ALL; 68import static android.content.pm.PackageManager.MATCH_ANY_USER; 69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 81import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 82import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 83import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 84import static android.content.pm.PackageManager.PERMISSION_DENIED; 85import static android.content.pm.PackageManager.PERMISSION_GRANTED; 86import static android.content.pm.PackageParser.isApkFile; 87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 88import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 89import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 90import static android.system.OsConstants.O_CREAT; 91import static android.system.OsConstants.O_RDWR; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 96import static com.android.internal.util.ArrayUtils.appendInt; 97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 104import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 105import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 106import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 107import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 108import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 109import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 110import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 111import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 112import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 116 117import android.Manifest; 118import android.annotation.IntDef; 119import android.annotation.NonNull; 120import android.annotation.Nullable; 121import android.annotation.UserIdInt; 122import android.app.ActivityManager; 123import android.app.ActivityManagerInternal; 124import android.app.AppOpsManager; 125import android.app.IActivityManager; 126import android.app.ResourcesManager; 127import android.app.admin.IDevicePolicyManager; 128import android.app.admin.SecurityLog; 129import android.app.backup.IBackupManager; 130import android.content.BroadcastReceiver; 131import android.content.ComponentName; 132import android.content.ContentResolver; 133import android.content.Context; 134import android.content.IIntentReceiver; 135import android.content.Intent; 136import android.content.IntentFilter; 137import android.content.IntentSender; 138import android.content.IntentSender.SendIntentException; 139import android.content.ServiceConnection; 140import android.content.pm.ActivityInfo; 141import android.content.pm.ApplicationInfo; 142import android.content.pm.AppsQueryHelper; 143import android.content.pm.AuxiliaryResolveInfo; 144import android.content.pm.ChangedPackages; 145import android.content.pm.ComponentInfo; 146import android.content.pm.FallbackCategoryProvider; 147import android.content.pm.FeatureInfo; 148import android.content.pm.IDexModuleRegisterCallback; 149import android.content.pm.IOnPermissionsChangeListener; 150import android.content.pm.IPackageDataObserver; 151import android.content.pm.IPackageDeleteObserver; 152import android.content.pm.IPackageDeleteObserver2; 153import android.content.pm.IPackageInstallObserver2; 154import android.content.pm.IPackageInstaller; 155import android.content.pm.IPackageManager; 156import android.content.pm.IPackageManagerNative; 157import android.content.pm.IPackageMoveObserver; 158import android.content.pm.IPackageStatsObserver; 159import android.content.pm.InstantAppInfo; 160import android.content.pm.InstantAppRequest; 161import android.content.pm.InstantAppResolveInfo; 162import android.content.pm.InstrumentationInfo; 163import android.content.pm.IntentFilterVerificationInfo; 164import android.content.pm.KeySet; 165import android.content.pm.PackageCleanItem; 166import android.content.pm.PackageInfo; 167import android.content.pm.PackageInfoLite; 168import android.content.pm.PackageInstaller; 169import android.content.pm.PackageList; 170import android.content.pm.PackageManager; 171import android.content.pm.PackageManagerInternal; 172import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 173import android.content.pm.PackageManagerInternal.PackageListObserver; 174import android.content.pm.PackageParser; 175import android.content.pm.PackageParser.ActivityIntentInfo; 176import android.content.pm.PackageParser.Package; 177import android.content.pm.PackageParser.PackageLite; 178import android.content.pm.PackageParser.PackageParserException; 179import android.content.pm.PackageParser.ParseFlags; 180import android.content.pm.PackageParser.ServiceIntentInfo; 181import android.content.pm.PackageParser.SigningDetails; 182import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 183import android.content.pm.PackageStats; 184import android.content.pm.PackageUserState; 185import android.content.pm.ParceledListSlice; 186import android.content.pm.PermissionGroupInfo; 187import android.content.pm.PermissionInfo; 188import android.content.pm.ProviderInfo; 189import android.content.pm.ResolveInfo; 190import android.content.pm.ServiceInfo; 191import android.content.pm.SharedLibraryInfo; 192import android.content.pm.Signature; 193import android.content.pm.UserInfo; 194import android.content.pm.VerifierDeviceIdentity; 195import android.content.pm.VerifierInfo; 196import android.content.pm.VersionedPackage; 197import android.content.pm.dex.ArtManager; 198import android.content.pm.dex.DexMetadataHelper; 199import android.content.pm.dex.IArtManager; 200import android.content.res.Resources; 201import android.database.ContentObserver; 202import android.graphics.Bitmap; 203import android.hardware.display.DisplayManager; 204import android.net.Uri; 205import android.os.Binder; 206import android.os.Build; 207import android.os.Bundle; 208import android.os.Debug; 209import android.os.Environment; 210import android.os.Environment.UserEnvironment; 211import android.os.FileUtils; 212import android.os.Handler; 213import android.os.IBinder; 214import android.os.Looper; 215import android.os.Message; 216import android.os.Parcel; 217import android.os.ParcelFileDescriptor; 218import android.os.PatternMatcher; 219import android.os.Process; 220import android.os.RemoteCallbackList; 221import android.os.RemoteException; 222import android.os.ResultReceiver; 223import android.os.SELinux; 224import android.os.ServiceManager; 225import android.os.ShellCallback; 226import android.os.SystemClock; 227import android.os.SystemProperties; 228import android.os.Trace; 229import android.os.UserHandle; 230import android.os.UserManager; 231import android.os.UserManagerInternal; 232import android.os.storage.IStorageManager; 233import android.os.storage.StorageEventListener; 234import android.os.storage.StorageManager; 235import android.os.storage.StorageManagerInternal; 236import android.os.storage.VolumeInfo; 237import android.os.storage.VolumeRecord; 238import android.provider.Settings.Global; 239import android.provider.Settings.Secure; 240import android.security.KeyStore; 241import android.security.SystemKeyStore; 242import android.service.pm.PackageServiceDumpProto; 243import android.service.textclassifier.TextClassifierService; 244import android.system.ErrnoException; 245import android.system.Os; 246import android.text.TextUtils; 247import android.text.format.DateUtils; 248import android.util.ArrayMap; 249import android.util.ArraySet; 250import android.util.Base64; 251import android.util.ByteStringUtils; 252import android.util.DisplayMetrics; 253import android.util.EventLog; 254import android.util.ExceptionUtils; 255import android.util.Log; 256import android.util.LogPrinter; 257import android.util.LongSparseArray; 258import android.util.LongSparseLongArray; 259import android.util.MathUtils; 260import android.util.PackageUtils; 261import android.util.Pair; 262import android.util.PrintStreamPrinter; 263import android.util.Slog; 264import android.util.SparseArray; 265import android.util.SparseBooleanArray; 266import android.util.SparseIntArray; 267import android.util.TimingsTraceLog; 268import android.util.Xml; 269import android.util.jar.StrictJarFile; 270import android.util.proto.ProtoOutputStream; 271import android.view.Display; 272 273import com.android.internal.R; 274import com.android.internal.annotations.GuardedBy; 275import com.android.internal.app.IMediaContainerService; 276import com.android.internal.app.ResolverActivity; 277import com.android.internal.content.NativeLibraryHelper; 278import com.android.internal.content.PackageHelper; 279import com.android.internal.logging.MetricsLogger; 280import com.android.internal.os.IParcelFileDescriptorFactory; 281import com.android.internal.os.SomeArgs; 282import com.android.internal.os.Zygote; 283import com.android.internal.telephony.CarrierAppUtils; 284import com.android.internal.util.ArrayUtils; 285import com.android.internal.util.ConcurrentUtils; 286import com.android.internal.util.DumpUtils; 287import com.android.internal.util.FastXmlSerializer; 288import com.android.internal.util.IndentingPrintWriter; 289import com.android.internal.util.Preconditions; 290import com.android.internal.util.XmlUtils; 291import com.android.server.AttributeCache; 292import com.android.server.DeviceIdleController; 293import com.android.server.EventLogTags; 294import com.android.server.FgThread; 295import com.android.server.IntentResolver; 296import com.android.server.LocalServices; 297import com.android.server.LockGuard; 298import com.android.server.ServiceThread; 299import com.android.server.SystemConfig; 300import com.android.server.SystemServerInitThreadPool; 301import com.android.server.Watchdog; 302import com.android.server.net.NetworkPolicyManagerInternal; 303import com.android.server.pm.Installer.InstallerException; 304import com.android.server.pm.Settings.DatabaseVersion; 305import com.android.server.pm.Settings.VersionInfo; 306import com.android.server.pm.dex.ArtManagerService; 307import com.android.server.pm.dex.DexLogger; 308import com.android.server.pm.dex.DexManager; 309import com.android.server.pm.dex.DexoptOptions; 310import com.android.server.pm.dex.PackageDexUsage; 311import com.android.server.pm.permission.BasePermission; 312import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 313import com.android.server.pm.permission.PermissionManagerService; 314import com.android.server.pm.permission.PermissionManagerInternal; 315import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 316import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 317import com.android.server.pm.permission.PermissionsState; 318import com.android.server.pm.permission.PermissionsState.PermissionState; 319import com.android.server.security.VerityUtils; 320import com.android.server.storage.DeviceStorageMonitorInternal; 321 322import dalvik.system.CloseGuard; 323import dalvik.system.VMRuntime; 324 325import libcore.io.IoUtils; 326 327import org.xmlpull.v1.XmlPullParser; 328import org.xmlpull.v1.XmlPullParserException; 329import org.xmlpull.v1.XmlSerializer; 330 331import java.io.BufferedOutputStream; 332import java.io.ByteArrayInputStream; 333import java.io.ByteArrayOutputStream; 334import java.io.File; 335import java.io.FileDescriptor; 336import java.io.FileInputStream; 337import java.io.FileOutputStream; 338import java.io.FilenameFilter; 339import java.io.IOException; 340import java.io.PrintWriter; 341import java.lang.annotation.Retention; 342import java.lang.annotation.RetentionPolicy; 343import java.nio.charset.StandardCharsets; 344import java.security.DigestException; 345import java.security.DigestInputStream; 346import java.security.MessageDigest; 347import java.security.NoSuchAlgorithmException; 348import java.security.PublicKey; 349import java.security.SecureRandom; 350import java.security.cert.CertificateException; 351import java.util.ArrayList; 352import java.util.Arrays; 353import java.util.Collection; 354import java.util.Collections; 355import java.util.Comparator; 356import java.util.HashMap; 357import java.util.HashSet; 358import java.util.Iterator; 359import java.util.LinkedHashSet; 360import java.util.List; 361import java.util.Map; 362import java.util.Objects; 363import java.util.Set; 364import java.util.concurrent.CountDownLatch; 365import java.util.concurrent.Future; 366import java.util.concurrent.TimeUnit; 367import java.util.concurrent.atomic.AtomicBoolean; 368import java.util.concurrent.atomic.AtomicInteger; 369 370/** 371 * Keep track of all those APKs everywhere. 372 * <p> 373 * Internally there are two important locks: 374 * <ul> 375 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 376 * and other related state. It is a fine-grained lock that should only be held 377 * momentarily, as it's one of the most contended locks in the system. 378 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 379 * operations typically involve heavy lifting of application data on disk. Since 380 * {@code installd} is single-threaded, and it's operations can often be slow, 381 * this lock should never be acquired while already holding {@link #mPackages}. 382 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 383 * holding {@link #mInstallLock}. 384 * </ul> 385 * Many internal methods rely on the caller to hold the appropriate locks, and 386 * this contract is expressed through method name suffixes: 387 * <ul> 388 * <li>fooLI(): the caller must hold {@link #mInstallLock} 389 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 390 * being modified must be frozen 391 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 392 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 393 * </ul> 394 * <p> 395 * Because this class is very central to the platform's security; please run all 396 * CTS and unit tests whenever making modifications: 397 * 398 * <pre> 399 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 400 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 401 * </pre> 402 */ 403public class PackageManagerService extends IPackageManager.Stub 404 implements PackageSender { 405 static final String TAG = "PackageManager"; 406 public static final boolean DEBUG_SETTINGS = false; 407 static final boolean DEBUG_PREFERRED = false; 408 static final boolean DEBUG_UPGRADE = false; 409 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 410 private static final boolean DEBUG_BACKUP = false; 411 public static final boolean DEBUG_INSTALL = false; 412 public static final boolean DEBUG_REMOVE = false; 413 private static final boolean DEBUG_BROADCASTS = false; 414 private static final boolean DEBUG_SHOW_INFO = false; 415 private static final boolean DEBUG_PACKAGE_INFO = false; 416 private static final boolean DEBUG_INTENT_MATCHING = false; 417 public static final boolean DEBUG_PACKAGE_SCANNING = false; 418 private static final boolean DEBUG_VERIFY = false; 419 private static final boolean DEBUG_FILTERS = false; 420 public static final boolean DEBUG_PERMISSIONS = false; 421 private static final boolean DEBUG_SHARED_LIBRARIES = false; 422 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 423 424 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 425 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 426 // user, but by default initialize to this. 427 public static final boolean DEBUG_DEXOPT = false; 428 429 private static final boolean DEBUG_ABI_SELECTION = false; 430 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 431 private static final boolean DEBUG_TRIAGED_MISSING = false; 432 private static final boolean DEBUG_APP_DATA = false; 433 434 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 435 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 436 437 private static final boolean HIDE_EPHEMERAL_APIS = false; 438 439 private static final boolean ENABLE_FREE_CACHE_V2 = 440 SystemProperties.getBoolean("fw.free_cache_v2", true); 441 442 private static final int RADIO_UID = Process.PHONE_UID; 443 private static final int LOG_UID = Process.LOG_UID; 444 private static final int NFC_UID = Process.NFC_UID; 445 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 446 private static final int SHELL_UID = Process.SHELL_UID; 447 private static final int SE_UID = Process.SE_UID; 448 449 // Suffix used during package installation when copying/moving 450 // package apks to install directory. 451 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 452 453 static final int SCAN_NO_DEX = 1<<0; 454 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 455 static final int SCAN_NEW_INSTALL = 1<<2; 456 static final int SCAN_UPDATE_TIME = 1<<3; 457 static final int SCAN_BOOTING = 1<<4; 458 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 459 static final int SCAN_REQUIRE_KNOWN = 1<<7; 460 static final int SCAN_MOVE = 1<<8; 461 static final int SCAN_INITIAL = 1<<9; 462 static final int SCAN_CHECK_ONLY = 1<<10; 463 static final int SCAN_DONT_KILL_APP = 1<<11; 464 static final int SCAN_IGNORE_FROZEN = 1<<12; 465 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 466 static final int SCAN_AS_INSTANT_APP = 1<<14; 467 static final int SCAN_AS_FULL_APP = 1<<15; 468 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 469 static final int SCAN_AS_SYSTEM = 1<<17; 470 static final int SCAN_AS_PRIVILEGED = 1<<18; 471 static final int SCAN_AS_OEM = 1<<19; 472 static final int SCAN_AS_VENDOR = 1<<20; 473 static final int SCAN_AS_PRODUCT = 1<<21; 474 475 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 476 SCAN_NO_DEX, 477 SCAN_UPDATE_SIGNATURE, 478 SCAN_NEW_INSTALL, 479 SCAN_UPDATE_TIME, 480 SCAN_BOOTING, 481 SCAN_DELETE_DATA_ON_FAILURES, 482 SCAN_REQUIRE_KNOWN, 483 SCAN_MOVE, 484 SCAN_INITIAL, 485 SCAN_CHECK_ONLY, 486 SCAN_DONT_KILL_APP, 487 SCAN_IGNORE_FROZEN, 488 SCAN_FIRST_BOOT_OR_UPGRADE, 489 SCAN_AS_INSTANT_APP, 490 SCAN_AS_FULL_APP, 491 SCAN_AS_VIRTUAL_PRELOAD, 492 }) 493 @Retention(RetentionPolicy.SOURCE) 494 public @interface ScanFlags {} 495 496 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 497 /** Extension of the compressed packages */ 498 public final static String COMPRESSED_EXTENSION = ".gz"; 499 /** Suffix of stub packages on the system partition */ 500 public final static String STUB_SUFFIX = "-Stub"; 501 502 private static final int[] EMPTY_INT_ARRAY = new int[0]; 503 504 private static final int TYPE_UNKNOWN = 0; 505 private static final int TYPE_ACTIVITY = 1; 506 private static final int TYPE_RECEIVER = 2; 507 private static final int TYPE_SERVICE = 3; 508 private static final int TYPE_PROVIDER = 4; 509 @IntDef(prefix = { "TYPE_" }, value = { 510 TYPE_UNKNOWN, 511 TYPE_ACTIVITY, 512 TYPE_RECEIVER, 513 TYPE_SERVICE, 514 TYPE_PROVIDER, 515 }) 516 @Retention(RetentionPolicy.SOURCE) 517 public @interface ComponentType {} 518 519 /** 520 * Timeout (in milliseconds) after which the watchdog should declare that 521 * our handler thread is wedged. The usual default for such things is one 522 * minute but we sometimes do very lengthy I/O operations on this thread, 523 * such as installing multi-gigabyte applications, so ours needs to be longer. 524 */ 525 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 526 527 /** 528 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 529 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 530 * settings entry if available, otherwise we use the hardcoded default. If it's been 531 * more than this long since the last fstrim, we force one during the boot sequence. 532 * 533 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 534 * one gets run at the next available charging+idle time. This final mandatory 535 * no-fstrim check kicks in only of the other scheduling criteria is never met. 536 */ 537 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 538 539 /** 540 * Whether verification is enabled by default. 541 */ 542 private static final boolean DEFAULT_VERIFY_ENABLE = true; 543 544 /** 545 * The default maximum time to wait for the verification agent to return in 546 * milliseconds. 547 */ 548 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 549 550 /** 551 * The default response for package verification timeout. 552 * 553 * This can be either PackageManager.VERIFICATION_ALLOW or 554 * PackageManager.VERIFICATION_REJECT. 555 */ 556 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 557 558 public static final String PLATFORM_PACKAGE_NAME = "android"; 559 560 public static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 561 562 public static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 563 DEFAULT_CONTAINER_PACKAGE, 564 "com.android.defcontainer.DefaultContainerService"); 565 566 private static final String KILL_APP_REASON_GIDS_CHANGED = 567 "permission grant or revoke changed gids"; 568 569 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 570 "permissions revoked"; 571 572 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 573 574 private static final String PACKAGE_SCHEME = "package"; 575 576 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 577 578 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 579 580 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 581 582 /** Canonical intent used to identify what counts as a "web browser" app */ 583 private static final Intent sBrowserIntent; 584 static { 585 sBrowserIntent = new Intent(); 586 sBrowserIntent.setAction(Intent.ACTION_VIEW); 587 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 588 sBrowserIntent.setData(Uri.parse("http:")); 589 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 590 } 591 592 /** 593 * The set of all protected actions [i.e. those actions for which a high priority 594 * intent filter is disallowed]. 595 */ 596 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 597 static { 598 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 599 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 600 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 601 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 602 } 603 604 // Compilation reasons. 605 public static final int REASON_UNKNOWN = -1; 606 public static final int REASON_FIRST_BOOT = 0; 607 public static final int REASON_BOOT = 1; 608 public static final int REASON_INSTALL = 2; 609 public static final int REASON_BACKGROUND_DEXOPT = 3; 610 public static final int REASON_AB_OTA = 4; 611 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 612 public static final int REASON_SHARED = 6; 613 614 public static final int REASON_LAST = REASON_SHARED; 615 616 /** 617 * Version number for the package parser cache. Increment this whenever the format or 618 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 619 */ 620 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 621 622 /** 623 * Whether the package parser cache is enabled. 624 */ 625 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 626 627 /** 628 * Permissions required in order to receive instant application lifecycle broadcasts. 629 */ 630 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 631 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 632 633 final ServiceThread mHandlerThread; 634 635 final PackageHandler mHandler; 636 637 private final ProcessLoggingHandler mProcessLoggingHandler; 638 639 /** 640 * Messages for {@link #mHandler} that need to wait for system ready before 641 * being dispatched. 642 */ 643 private ArrayList<Message> mPostSystemReadyMessages; 644 645 final int mSdkVersion = Build.VERSION.SDK_INT; 646 647 final Context mContext; 648 final boolean mFactoryTest; 649 final boolean mOnlyCore; 650 final DisplayMetrics mMetrics; 651 final int mDefParseFlags; 652 final String[] mSeparateProcesses; 653 final boolean mIsUpgrade; 654 final boolean mIsPreNUpgrade; 655 final boolean mIsPreNMR1Upgrade; 656 657 // Have we told the Activity Manager to whitelist the default container service by uid yet? 658 @GuardedBy("mPackages") 659 boolean mDefaultContainerWhitelisted = false; 660 661 @GuardedBy("mPackages") 662 private boolean mDexOptDialogShown; 663 664 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 665 // LOCK HELD. Can be called with mInstallLock held. 666 @GuardedBy("mInstallLock") 667 final Installer mInstaller; 668 669 /** Directory where installed applications are stored */ 670 private static final File sAppInstallDir = 671 new File(Environment.getDataDirectory(), "app"); 672 /** Directory where installed application's 32-bit native libraries are copied. */ 673 private static final File sAppLib32InstallDir = 674 new File(Environment.getDataDirectory(), "app-lib"); 675 /** Directory where code and non-resource assets of forward-locked applications are stored */ 676 private static final File sDrmAppPrivateInstallDir = 677 new File(Environment.getDataDirectory(), "app-private"); 678 679 // ---------------------------------------------------------------- 680 681 // Lock for state used when installing and doing other long running 682 // operations. Methods that must be called with this lock held have 683 // the suffix "LI". 684 final Object mInstallLock = new Object(); 685 686 // ---------------------------------------------------------------- 687 688 // Keys are String (package name), values are Package. This also serves 689 // as the lock for the global state. Methods that must be called with 690 // this lock held have the prefix "LP". 691 @GuardedBy("mPackages") 692 final ArrayMap<String, PackageParser.Package> mPackages = 693 new ArrayMap<String, PackageParser.Package>(); 694 695 final ArrayMap<String, Set<String>> mKnownCodebase = 696 new ArrayMap<String, Set<String>>(); 697 698 // Keys are isolated uids and values are the uid of the application 699 // that created the isolated proccess. 700 @GuardedBy("mPackages") 701 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 702 703 /** 704 * Tracks new system packages [received in an OTA] that we expect to 705 * find updated user-installed versions. Keys are package name, values 706 * are package location. 707 */ 708 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 709 /** 710 * Tracks high priority intent filters for protected actions. During boot, certain 711 * filter actions are protected and should never be allowed to have a high priority 712 * intent filter for them. However, there is one, and only one exception -- the 713 * setup wizard. It must be able to define a high priority intent filter for these 714 * actions to ensure there are no escapes from the wizard. We need to delay processing 715 * of these during boot as we need to look at all of the system packages in order 716 * to know which component is the setup wizard. 717 */ 718 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 719 /** 720 * Whether or not processing protected filters should be deferred. 721 */ 722 private boolean mDeferProtectedFilters = true; 723 724 /** 725 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 726 */ 727 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 728 /** 729 * Whether or not system app permissions should be promoted from install to runtime. 730 */ 731 boolean mPromoteSystemApps; 732 733 @GuardedBy("mPackages") 734 final Settings mSettings; 735 736 /** 737 * Set of package names that are currently "frozen", which means active 738 * surgery is being done on the code/data for that package. The platform 739 * will refuse to launch frozen packages to avoid race conditions. 740 * 741 * @see PackageFreezer 742 */ 743 @GuardedBy("mPackages") 744 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 745 746 final ProtectedPackages mProtectedPackages; 747 748 @GuardedBy("mLoadedVolumes") 749 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 750 751 boolean mFirstBoot; 752 753 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 754 755 @GuardedBy("mAvailableFeatures") 756 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 757 758 private final InstantAppRegistry mInstantAppRegistry; 759 760 @GuardedBy("mPackages") 761 int mChangedPackagesSequenceNumber; 762 /** 763 * List of changed [installed, removed or updated] packages. 764 * mapping from user id -> sequence number -> package name 765 */ 766 @GuardedBy("mPackages") 767 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 768 /** 769 * The sequence number of the last change to a package. 770 * mapping from user id -> package name -> sequence number 771 */ 772 @GuardedBy("mPackages") 773 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 774 775 @GuardedBy("mPackages") 776 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 777 778 class PackageParserCallback implements PackageParser.Callback { 779 @Override public final boolean hasFeature(String feature) { 780 return PackageManagerService.this.hasSystemFeature(feature, 0); 781 } 782 783 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 784 Collection<PackageParser.Package> allPackages, String targetPackageName) { 785 List<PackageParser.Package> overlayPackages = null; 786 for (PackageParser.Package p : allPackages) { 787 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 788 if (overlayPackages == null) { 789 overlayPackages = new ArrayList<PackageParser.Package>(); 790 } 791 overlayPackages.add(p); 792 } 793 } 794 if (overlayPackages != null) { 795 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 796 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 797 return p1.mOverlayPriority - p2.mOverlayPriority; 798 } 799 }; 800 Collections.sort(overlayPackages, cmp); 801 } 802 return overlayPackages; 803 } 804 805 @GuardedBy("mInstallLock") 806 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 807 String targetPackageName, String targetPath) { 808 if ("android".equals(targetPackageName)) { 809 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 810 // native AssetManager. 811 return null; 812 } 813 List<PackageParser.Package> overlayPackages = 814 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 815 if (overlayPackages == null || overlayPackages.isEmpty()) { 816 return null; 817 } 818 List<String> overlayPathList = null; 819 for (PackageParser.Package overlayPackage : overlayPackages) { 820 if (targetPath == null) { 821 if (overlayPathList == null) { 822 overlayPathList = new ArrayList<String>(); 823 } 824 overlayPathList.add(overlayPackage.baseCodePath); 825 continue; 826 } 827 828 try { 829 // Creates idmaps for system to parse correctly the Android manifest of the 830 // target package. 831 // 832 // OverlayManagerService will update each of them with a correct gid from its 833 // target package app id. 834 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 835 UserHandle.getSharedAppGid( 836 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 837 if (overlayPathList == null) { 838 overlayPathList = new ArrayList<String>(); 839 } 840 overlayPathList.add(overlayPackage.baseCodePath); 841 } catch (InstallerException e) { 842 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 843 overlayPackage.baseCodePath); 844 } 845 } 846 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 847 } 848 849 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 850 synchronized (mPackages) { 851 return getStaticOverlayPathsLocked( 852 mPackages.values(), targetPackageName, targetPath); 853 } 854 } 855 856 @Override public final String[] getOverlayApks(String targetPackageName) { 857 return getStaticOverlayPaths(targetPackageName, null); 858 } 859 860 @Override public final String[] getOverlayPaths(String targetPackageName, 861 String targetPath) { 862 return getStaticOverlayPaths(targetPackageName, targetPath); 863 } 864 } 865 866 class ParallelPackageParserCallback extends PackageParserCallback { 867 List<PackageParser.Package> mOverlayPackages = null; 868 869 void findStaticOverlayPackages() { 870 synchronized (mPackages) { 871 for (PackageParser.Package p : mPackages.values()) { 872 if (p.mOverlayIsStatic) { 873 if (mOverlayPackages == null) { 874 mOverlayPackages = new ArrayList<PackageParser.Package>(); 875 } 876 mOverlayPackages.add(p); 877 } 878 } 879 } 880 } 881 882 @Override 883 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 884 // We can trust mOverlayPackages without holding mPackages because package uninstall 885 // can't happen while running parallel parsing. 886 // Moreover holding mPackages on each parsing thread causes dead-lock. 887 return mOverlayPackages == null ? null : 888 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 889 } 890 } 891 892 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 893 final ParallelPackageParserCallback mParallelPackageParserCallback = 894 new ParallelPackageParserCallback(); 895 896 public static final class SharedLibraryEntry { 897 public final @Nullable String path; 898 public final @Nullable String apk; 899 public final @NonNull SharedLibraryInfo info; 900 901 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 902 String declaringPackageName, long declaringPackageVersionCode) { 903 path = _path; 904 apk = _apk; 905 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 906 declaringPackageName, declaringPackageVersionCode), null); 907 } 908 } 909 910 // Currently known shared libraries. 911 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 912 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 913 new ArrayMap<>(); 914 915 // All available activities, for your resolving pleasure. 916 final ActivityIntentResolver mActivities = 917 new ActivityIntentResolver(); 918 919 // All available receivers, for your resolving pleasure. 920 final ActivityIntentResolver mReceivers = 921 new ActivityIntentResolver(); 922 923 // All available services, for your resolving pleasure. 924 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 925 926 // All available providers, for your resolving pleasure. 927 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 928 929 // Mapping from provider base names (first directory in content URI codePath) 930 // to the provider information. 931 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 932 new ArrayMap<String, PackageParser.Provider>(); 933 934 // Mapping from instrumentation class names to info about them. 935 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 936 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 937 938 // Packages whose data we have transfered into another package, thus 939 // should no longer exist. 940 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 941 942 // Broadcast actions that are only available to the system. 943 @GuardedBy("mProtectedBroadcasts") 944 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 945 946 /** List of packages waiting for verification. */ 947 final SparseArray<PackageVerificationState> mPendingVerification 948 = new SparseArray<PackageVerificationState>(); 949 950 final PackageInstallerService mInstallerService; 951 952 final ArtManagerService mArtManagerService; 953 954 private final PackageDexOptimizer mPackageDexOptimizer; 955 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 956 // is used by other apps). 957 private final DexManager mDexManager; 958 959 private AtomicInteger mNextMoveId = new AtomicInteger(); 960 private final MoveCallbacks mMoveCallbacks; 961 962 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 963 964 // Cache of users who need badging. 965 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 966 967 /** Token for keys in mPendingVerification. */ 968 private int mPendingVerificationToken = 0; 969 970 volatile boolean mSystemReady; 971 volatile boolean mSafeMode; 972 volatile boolean mHasSystemUidErrors; 973 private volatile boolean mWebInstantAppsDisabled; 974 975 ApplicationInfo mAndroidApplication; 976 final ActivityInfo mResolveActivity = new ActivityInfo(); 977 final ResolveInfo mResolveInfo = new ResolveInfo(); 978 ComponentName mResolveComponentName; 979 PackageParser.Package mPlatformPackage; 980 ComponentName mCustomResolverComponentName; 981 982 boolean mResolverReplaced = false; 983 984 private final @Nullable ComponentName mIntentFilterVerifierComponent; 985 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 986 987 private int mIntentFilterVerificationToken = 0; 988 989 /** The service connection to the ephemeral resolver */ 990 final InstantAppResolverConnection mInstantAppResolverConnection; 991 /** Component used to show resolver settings for Instant Apps */ 992 final ComponentName mInstantAppResolverSettingsComponent; 993 994 /** Activity used to install instant applications */ 995 ActivityInfo mInstantAppInstallerActivity; 996 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 997 998 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 999 = new SparseArray<IntentFilterVerificationState>(); 1000 1001 // TODO remove this and go through mPermissonManager directly 1002 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1003 private final PermissionManagerInternal mPermissionManager; 1004 1005 // List of packages names to keep cached, even if they are uninstalled for all users 1006 private List<String> mKeepUninstalledPackages; 1007 1008 private UserManagerInternal mUserManagerInternal; 1009 private ActivityManagerInternal mActivityManagerInternal; 1010 1011 private DeviceIdleController.LocalService mDeviceIdleController; 1012 1013 private File mCacheDir; 1014 1015 private Future<?> mPrepareAppDataFuture; 1016 1017 private static class IFVerificationParams { 1018 PackageParser.Package pkg; 1019 boolean replacing; 1020 int userId; 1021 int verifierUid; 1022 1023 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1024 int _userId, int _verifierUid) { 1025 pkg = _pkg; 1026 replacing = _replacing; 1027 userId = _userId; 1028 replacing = _replacing; 1029 verifierUid = _verifierUid; 1030 } 1031 } 1032 1033 private interface IntentFilterVerifier<T extends IntentFilter> { 1034 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1035 T filter, String packageName); 1036 void startVerifications(int userId); 1037 void receiveVerificationResponse(int verificationId); 1038 } 1039 1040 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1041 private Context mContext; 1042 private ComponentName mIntentFilterVerifierComponent; 1043 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1044 1045 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1046 mContext = context; 1047 mIntentFilterVerifierComponent = verifierComponent; 1048 } 1049 1050 private String getDefaultScheme() { 1051 return IntentFilter.SCHEME_HTTPS; 1052 } 1053 1054 @Override 1055 public void startVerifications(int userId) { 1056 // Launch verifications requests 1057 int count = mCurrentIntentFilterVerifications.size(); 1058 for (int n=0; n<count; n++) { 1059 int verificationId = mCurrentIntentFilterVerifications.get(n); 1060 final IntentFilterVerificationState ivs = 1061 mIntentFilterVerificationStates.get(verificationId); 1062 1063 String packageName = ivs.getPackageName(); 1064 1065 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1066 final int filterCount = filters.size(); 1067 ArraySet<String> domainsSet = new ArraySet<>(); 1068 for (int m=0; m<filterCount; m++) { 1069 PackageParser.ActivityIntentInfo filter = filters.get(m); 1070 domainsSet.addAll(filter.getHostsList()); 1071 } 1072 synchronized (mPackages) { 1073 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1074 packageName, domainsSet) != null) { 1075 scheduleWriteSettingsLocked(); 1076 } 1077 } 1078 sendVerificationRequest(verificationId, ivs); 1079 } 1080 mCurrentIntentFilterVerifications.clear(); 1081 } 1082 1083 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1084 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1085 verificationIntent.putExtra( 1086 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1087 verificationId); 1088 verificationIntent.putExtra( 1089 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1090 getDefaultScheme()); 1091 verificationIntent.putExtra( 1092 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1093 ivs.getHostsString()); 1094 verificationIntent.putExtra( 1095 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1096 ivs.getPackageName()); 1097 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1098 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1099 1100 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1101 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1102 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1103 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1104 1105 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1106 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1107 "Sending IntentFilter verification broadcast"); 1108 } 1109 1110 public void receiveVerificationResponse(int verificationId) { 1111 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1112 1113 final boolean verified = ivs.isVerified(); 1114 1115 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1116 final int count = filters.size(); 1117 if (DEBUG_DOMAIN_VERIFICATION) { 1118 Slog.i(TAG, "Received verification response " + verificationId 1119 + " for " + count + " filters, verified=" + verified); 1120 } 1121 for (int n=0; n<count; n++) { 1122 PackageParser.ActivityIntentInfo filter = filters.get(n); 1123 filter.setVerified(verified); 1124 1125 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1126 + " verified with result:" + verified + " and hosts:" 1127 + ivs.getHostsString()); 1128 } 1129 1130 mIntentFilterVerificationStates.remove(verificationId); 1131 1132 final String packageName = ivs.getPackageName(); 1133 IntentFilterVerificationInfo ivi = null; 1134 1135 synchronized (mPackages) { 1136 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1137 } 1138 if (ivi == null) { 1139 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1140 + verificationId + " packageName:" + packageName); 1141 return; 1142 } 1143 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1144 "Updating IntentFilterVerificationInfo for package " + packageName 1145 +" verificationId:" + verificationId); 1146 1147 synchronized (mPackages) { 1148 if (verified) { 1149 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1150 } else { 1151 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1152 } 1153 scheduleWriteSettingsLocked(); 1154 1155 final int userId = ivs.getUserId(); 1156 if (userId != UserHandle.USER_ALL) { 1157 final int userStatus = 1158 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1159 1160 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1161 boolean needUpdate = false; 1162 1163 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1164 // already been set by the User thru the Disambiguation dialog 1165 switch (userStatus) { 1166 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1167 if (verified) { 1168 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1169 } else { 1170 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1171 } 1172 needUpdate = true; 1173 break; 1174 1175 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1176 if (verified) { 1177 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1178 needUpdate = true; 1179 } 1180 break; 1181 1182 default: 1183 // Nothing to do 1184 } 1185 1186 if (needUpdate) { 1187 mSettings.updateIntentFilterVerificationStatusLPw( 1188 packageName, updatedStatus, userId); 1189 scheduleWritePackageRestrictionsLocked(userId); 1190 } 1191 } 1192 } 1193 } 1194 1195 @Override 1196 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1197 ActivityIntentInfo filter, String packageName) { 1198 if (!hasValidDomains(filter)) { 1199 return false; 1200 } 1201 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1202 if (ivs == null) { 1203 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1204 packageName); 1205 } 1206 if (DEBUG_DOMAIN_VERIFICATION) { 1207 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1208 } 1209 ivs.addFilter(filter); 1210 return true; 1211 } 1212 1213 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1214 int userId, int verificationId, String packageName) { 1215 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1216 verifierUid, userId, packageName); 1217 ivs.setPendingState(); 1218 synchronized (mPackages) { 1219 mIntentFilterVerificationStates.append(verificationId, ivs); 1220 mCurrentIntentFilterVerifications.add(verificationId); 1221 } 1222 return ivs; 1223 } 1224 } 1225 1226 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1227 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1228 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1229 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1230 } 1231 1232 // Set of pending broadcasts for aggregating enable/disable of components. 1233 static class PendingPackageBroadcasts { 1234 // for each user id, a map of <package name -> components within that package> 1235 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1236 1237 public PendingPackageBroadcasts() { 1238 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1239 } 1240 1241 public ArrayList<String> get(int userId, String packageName) { 1242 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1243 return packages.get(packageName); 1244 } 1245 1246 public void put(int userId, String packageName, ArrayList<String> components) { 1247 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1248 packages.put(packageName, components); 1249 } 1250 1251 public void remove(int userId, String packageName) { 1252 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1253 if (packages != null) { 1254 packages.remove(packageName); 1255 } 1256 } 1257 1258 public void remove(int userId) { 1259 mUidMap.remove(userId); 1260 } 1261 1262 public int userIdCount() { 1263 return mUidMap.size(); 1264 } 1265 1266 public int userIdAt(int n) { 1267 return mUidMap.keyAt(n); 1268 } 1269 1270 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1271 return mUidMap.get(userId); 1272 } 1273 1274 public int size() { 1275 // total number of pending broadcast entries across all userIds 1276 int num = 0; 1277 for (int i = 0; i< mUidMap.size(); i++) { 1278 num += mUidMap.valueAt(i).size(); 1279 } 1280 return num; 1281 } 1282 1283 public void clear() { 1284 mUidMap.clear(); 1285 } 1286 1287 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1288 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1289 if (map == null) { 1290 map = new ArrayMap<String, ArrayList<String>>(); 1291 mUidMap.put(userId, map); 1292 } 1293 return map; 1294 } 1295 } 1296 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1297 1298 // Service Connection to remote media container service to copy 1299 // package uri's from external media onto secure containers 1300 // or internal storage. 1301 private IMediaContainerService mContainerService = null; 1302 1303 static final int SEND_PENDING_BROADCAST = 1; 1304 static final int MCS_BOUND = 3; 1305 static final int END_COPY = 4; 1306 static final int INIT_COPY = 5; 1307 static final int MCS_UNBIND = 6; 1308 static final int START_CLEANING_PACKAGE = 7; 1309 static final int FIND_INSTALL_LOC = 8; 1310 static final int POST_INSTALL = 9; 1311 static final int MCS_RECONNECT = 10; 1312 static final int MCS_GIVE_UP = 11; 1313 static final int WRITE_SETTINGS = 13; 1314 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1315 static final int PACKAGE_VERIFIED = 15; 1316 static final int CHECK_PENDING_VERIFICATION = 16; 1317 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1318 static final int INTENT_FILTER_VERIFIED = 18; 1319 static final int WRITE_PACKAGE_LIST = 19; 1320 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1321 1322 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1323 1324 // Delay time in millisecs 1325 static final int BROADCAST_DELAY = 10 * 1000; 1326 1327 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1328 2 * 60 * 60 * 1000L; /* two hours */ 1329 1330 static UserManagerService sUserManager; 1331 1332 // Stores a list of users whose package restrictions file needs to be updated 1333 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1334 1335 final private DefaultContainerConnection mDefContainerConn = 1336 new DefaultContainerConnection(); 1337 class DefaultContainerConnection implements ServiceConnection { 1338 public void onServiceConnected(ComponentName name, IBinder service) { 1339 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1340 final IMediaContainerService imcs = IMediaContainerService.Stub 1341 .asInterface(Binder.allowBlocking(service)); 1342 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1343 } 1344 1345 public void onServiceDisconnected(ComponentName name) { 1346 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1347 } 1348 } 1349 1350 // Recordkeeping of restore-after-install operations that are currently in flight 1351 // between the Package Manager and the Backup Manager 1352 static class PostInstallData { 1353 public InstallArgs args; 1354 public PackageInstalledInfo res; 1355 1356 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1357 args = _a; 1358 res = _r; 1359 } 1360 } 1361 1362 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1363 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1364 1365 // XML tags for backup/restore of various bits of state 1366 private static final String TAG_PREFERRED_BACKUP = "pa"; 1367 private static final String TAG_DEFAULT_APPS = "da"; 1368 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1369 1370 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1371 private static final String TAG_ALL_GRANTS = "rt-grants"; 1372 private static final String TAG_GRANT = "grant"; 1373 private static final String ATTR_PACKAGE_NAME = "pkg"; 1374 1375 private static final String TAG_PERMISSION = "perm"; 1376 private static final String ATTR_PERMISSION_NAME = "name"; 1377 private static final String ATTR_IS_GRANTED = "g"; 1378 private static final String ATTR_USER_SET = "set"; 1379 private static final String ATTR_USER_FIXED = "fixed"; 1380 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1381 1382 // System/policy permission grants are not backed up 1383 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1384 FLAG_PERMISSION_POLICY_FIXED 1385 | FLAG_PERMISSION_SYSTEM_FIXED 1386 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1387 1388 // And we back up these user-adjusted states 1389 private static final int USER_RUNTIME_GRANT_MASK = 1390 FLAG_PERMISSION_USER_SET 1391 | FLAG_PERMISSION_USER_FIXED 1392 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1393 1394 final @Nullable String mRequiredVerifierPackage; 1395 final @NonNull String mRequiredInstallerPackage; 1396 final @NonNull String mRequiredUninstallerPackage; 1397 final @Nullable String mSetupWizardPackage; 1398 final @Nullable String mStorageManagerPackage; 1399 final @Nullable String mSystemTextClassifierPackage; 1400 final @NonNull String mServicesSystemSharedLibraryPackageName; 1401 final @NonNull String mSharedSystemSharedLibraryPackageName; 1402 1403 private final PackageUsage mPackageUsage = new PackageUsage(); 1404 private final CompilerStats mCompilerStats = new CompilerStats(); 1405 1406 class PackageHandler extends Handler { 1407 private boolean mBound = false; 1408 final ArrayList<HandlerParams> mPendingInstalls = 1409 new ArrayList<HandlerParams>(); 1410 1411 private boolean connectToService() { 1412 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1413 " DefaultContainerService"); 1414 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1416 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1417 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1419 mBound = true; 1420 return true; 1421 } 1422 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1423 return false; 1424 } 1425 1426 private void disconnectService() { 1427 mContainerService = null; 1428 mBound = false; 1429 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1430 mContext.unbindService(mDefContainerConn); 1431 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1432 } 1433 1434 PackageHandler(Looper looper) { 1435 super(looper); 1436 } 1437 1438 public void handleMessage(Message msg) { 1439 try { 1440 doHandleMessage(msg); 1441 } finally { 1442 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1443 } 1444 } 1445 1446 void doHandleMessage(Message msg) { 1447 switch (msg.what) { 1448 case INIT_COPY: { 1449 HandlerParams params = (HandlerParams) msg.obj; 1450 int idx = mPendingInstalls.size(); 1451 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1452 // If a bind was already initiated we dont really 1453 // need to do anything. The pending install 1454 // will be processed later on. 1455 if (!mBound) { 1456 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1457 System.identityHashCode(mHandler)); 1458 // If this is the only one pending we might 1459 // have to bind to the service again. 1460 if (!connectToService()) { 1461 Slog.e(TAG, "Failed to bind to media container service"); 1462 params.serviceError(); 1463 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1464 System.identityHashCode(mHandler)); 1465 if (params.traceMethod != null) { 1466 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1467 params.traceCookie); 1468 } 1469 return; 1470 } else { 1471 // Once we bind to the service, the first 1472 // pending request will be processed. 1473 mPendingInstalls.add(idx, params); 1474 } 1475 } else { 1476 mPendingInstalls.add(idx, params); 1477 // Already bound to the service. Just make 1478 // sure we trigger off processing the first request. 1479 if (idx == 0) { 1480 mHandler.sendEmptyMessage(MCS_BOUND); 1481 } 1482 } 1483 break; 1484 } 1485 case MCS_BOUND: { 1486 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1487 if (msg.obj != null) { 1488 mContainerService = (IMediaContainerService) msg.obj; 1489 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1490 System.identityHashCode(mHandler)); 1491 } 1492 if (mContainerService == null) { 1493 if (!mBound) { 1494 // Something seriously wrong since we are not bound and we are not 1495 // waiting for connection. Bail out. 1496 Slog.e(TAG, "Cannot bind to media container service"); 1497 for (HandlerParams params : mPendingInstalls) { 1498 // Indicate service bind error 1499 params.serviceError(); 1500 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1501 System.identityHashCode(params)); 1502 if (params.traceMethod != null) { 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1504 params.traceMethod, params.traceCookie); 1505 } 1506 return; 1507 } 1508 mPendingInstalls.clear(); 1509 } else { 1510 Slog.w(TAG, "Waiting to connect to media container service"); 1511 } 1512 } else if (mPendingInstalls.size() > 0) { 1513 HandlerParams params = mPendingInstalls.get(0); 1514 if (params != null) { 1515 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1516 System.identityHashCode(params)); 1517 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1518 if (params.startCopy()) { 1519 // We are done... look for more work or to 1520 // go idle. 1521 if (DEBUG_SD_INSTALL) Log.i(TAG, 1522 "Checking for more work or unbind..."); 1523 // Delete pending install 1524 if (mPendingInstalls.size() > 0) { 1525 mPendingInstalls.remove(0); 1526 } 1527 if (mPendingInstalls.size() == 0) { 1528 if (mBound) { 1529 if (DEBUG_SD_INSTALL) Log.i(TAG, 1530 "Posting delayed MCS_UNBIND"); 1531 removeMessages(MCS_UNBIND); 1532 Message ubmsg = obtainMessage(MCS_UNBIND); 1533 // Unbind after a little delay, to avoid 1534 // continual thrashing. 1535 sendMessageDelayed(ubmsg, 10000); 1536 } 1537 } else { 1538 // There are more pending requests in queue. 1539 // Just post MCS_BOUND message to trigger processing 1540 // of next pending install. 1541 if (DEBUG_SD_INSTALL) Log.i(TAG, 1542 "Posting MCS_BOUND for next work"); 1543 mHandler.sendEmptyMessage(MCS_BOUND); 1544 } 1545 } 1546 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1547 } 1548 } else { 1549 // Should never happen ideally. 1550 Slog.w(TAG, "Empty queue"); 1551 } 1552 break; 1553 } 1554 case MCS_RECONNECT: { 1555 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1556 if (mPendingInstalls.size() > 0) { 1557 if (mBound) { 1558 disconnectService(); 1559 } 1560 if (!connectToService()) { 1561 Slog.e(TAG, "Failed to bind to media container service"); 1562 for (HandlerParams params : mPendingInstalls) { 1563 // Indicate service bind error 1564 params.serviceError(); 1565 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1566 System.identityHashCode(params)); 1567 } 1568 mPendingInstalls.clear(); 1569 } 1570 } 1571 break; 1572 } 1573 case MCS_UNBIND: { 1574 // If there is no actual work left, then time to unbind. 1575 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1576 1577 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1578 if (mBound) { 1579 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1580 1581 disconnectService(); 1582 } 1583 } else if (mPendingInstalls.size() > 0) { 1584 // There are more pending requests in queue. 1585 // Just post MCS_BOUND message to trigger processing 1586 // of next pending install. 1587 mHandler.sendEmptyMessage(MCS_BOUND); 1588 } 1589 1590 break; 1591 } 1592 case MCS_GIVE_UP: { 1593 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1594 HandlerParams params = mPendingInstalls.remove(0); 1595 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1596 System.identityHashCode(params)); 1597 break; 1598 } 1599 case SEND_PENDING_BROADCAST: { 1600 String packages[]; 1601 ArrayList<String> components[]; 1602 int size = 0; 1603 int uids[]; 1604 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1605 synchronized (mPackages) { 1606 if (mPendingBroadcasts == null) { 1607 return; 1608 } 1609 size = mPendingBroadcasts.size(); 1610 if (size <= 0) { 1611 // Nothing to be done. Just return 1612 return; 1613 } 1614 packages = new String[size]; 1615 components = new ArrayList[size]; 1616 uids = new int[size]; 1617 int i = 0; // filling out the above arrays 1618 1619 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1620 int packageUserId = mPendingBroadcasts.userIdAt(n); 1621 Iterator<Map.Entry<String, ArrayList<String>>> it 1622 = mPendingBroadcasts.packagesForUserId(packageUserId) 1623 .entrySet().iterator(); 1624 while (it.hasNext() && i < size) { 1625 Map.Entry<String, ArrayList<String>> ent = it.next(); 1626 packages[i] = ent.getKey(); 1627 components[i] = ent.getValue(); 1628 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1629 uids[i] = (ps != null) 1630 ? UserHandle.getUid(packageUserId, ps.appId) 1631 : -1; 1632 i++; 1633 } 1634 } 1635 size = i; 1636 mPendingBroadcasts.clear(); 1637 } 1638 // Send broadcasts 1639 for (int i = 0; i < size; i++) { 1640 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1641 } 1642 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1643 break; 1644 } 1645 case START_CLEANING_PACKAGE: { 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1647 final String packageName = (String)msg.obj; 1648 final int userId = msg.arg1; 1649 final boolean andCode = msg.arg2 != 0; 1650 synchronized (mPackages) { 1651 if (userId == UserHandle.USER_ALL) { 1652 int[] users = sUserManager.getUserIds(); 1653 for (int user : users) { 1654 mSettings.addPackageToCleanLPw( 1655 new PackageCleanItem(user, packageName, andCode)); 1656 } 1657 } else { 1658 mSettings.addPackageToCleanLPw( 1659 new PackageCleanItem(userId, packageName, andCode)); 1660 } 1661 } 1662 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1663 startCleaningPackages(); 1664 } break; 1665 case POST_INSTALL: { 1666 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1667 1668 PostInstallData data = mRunningInstalls.get(msg.arg1); 1669 final boolean didRestore = (msg.arg2 != 0); 1670 mRunningInstalls.delete(msg.arg1); 1671 1672 if (data != null) { 1673 InstallArgs args = data.args; 1674 PackageInstalledInfo parentRes = data.res; 1675 1676 final boolean grantPermissions = (args.installFlags 1677 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1678 final boolean killApp = (args.installFlags 1679 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1680 final boolean virtualPreload = ((args.installFlags 1681 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1682 final String[] grantedPermissions = args.installGrantPermissions; 1683 1684 // Handle the parent package 1685 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1686 virtualPreload, grantedPermissions, didRestore, 1687 args.installerPackageName, args.observer); 1688 1689 // Handle the child packages 1690 final int childCount = (parentRes.addedChildPackages != null) 1691 ? parentRes.addedChildPackages.size() : 0; 1692 for (int i = 0; i < childCount; i++) { 1693 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1694 handlePackagePostInstall(childRes, grantPermissions, killApp, 1695 virtualPreload, grantedPermissions, false /*didRestore*/, 1696 args.installerPackageName, args.observer); 1697 } 1698 1699 // Log tracing if needed 1700 if (args.traceMethod != null) { 1701 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1702 args.traceCookie); 1703 } 1704 } else { 1705 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1706 } 1707 1708 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1709 } break; 1710 case WRITE_SETTINGS: { 1711 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1712 synchronized (mPackages) { 1713 removeMessages(WRITE_SETTINGS); 1714 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1715 mSettings.writeLPr(); 1716 mDirtyUsers.clear(); 1717 } 1718 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1719 } break; 1720 case WRITE_PACKAGE_RESTRICTIONS: { 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1722 synchronized (mPackages) { 1723 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1724 for (int userId : mDirtyUsers) { 1725 mSettings.writePackageRestrictionsLPr(userId); 1726 } 1727 mDirtyUsers.clear(); 1728 } 1729 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1730 } break; 1731 case WRITE_PACKAGE_LIST: { 1732 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1733 synchronized (mPackages) { 1734 removeMessages(WRITE_PACKAGE_LIST); 1735 mSettings.writePackageListLPr(msg.arg1); 1736 } 1737 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1738 } break; 1739 case CHECK_PENDING_VERIFICATION: { 1740 final int verificationId = msg.arg1; 1741 final PackageVerificationState state = mPendingVerification.get(verificationId); 1742 1743 if ((state != null) && !state.timeoutExtended()) { 1744 final InstallArgs args = state.getInstallArgs(); 1745 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1746 1747 Slog.i(TAG, "Verification timed out for " + originUri); 1748 mPendingVerification.remove(verificationId); 1749 1750 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1751 1752 final UserHandle user = args.getUser(); 1753 if (getDefaultVerificationResponse(user) 1754 == PackageManager.VERIFICATION_ALLOW) { 1755 Slog.i(TAG, "Continuing with installation of " + originUri); 1756 state.setVerifierResponse(Binder.getCallingUid(), 1757 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1758 broadcastPackageVerified(verificationId, originUri, 1759 PackageManager.VERIFICATION_ALLOW, user); 1760 try { 1761 ret = args.copyApk(mContainerService, true); 1762 } catch (RemoteException e) { 1763 Slog.e(TAG, "Could not contact the ContainerService"); 1764 } 1765 } else { 1766 broadcastPackageVerified(verificationId, originUri, 1767 PackageManager.VERIFICATION_REJECT, user); 1768 } 1769 1770 Trace.asyncTraceEnd( 1771 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1772 1773 processPendingInstall(args, ret); 1774 mHandler.sendEmptyMessage(MCS_UNBIND); 1775 } 1776 break; 1777 } 1778 case PACKAGE_VERIFIED: { 1779 final int verificationId = msg.arg1; 1780 1781 final PackageVerificationState state = mPendingVerification.get(verificationId); 1782 if (state == null) { 1783 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1784 break; 1785 } 1786 1787 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1788 1789 state.setVerifierResponse(response.callerUid, response.code); 1790 1791 if (state.isVerificationComplete()) { 1792 mPendingVerification.remove(verificationId); 1793 1794 final InstallArgs args = state.getInstallArgs(); 1795 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1796 1797 int ret; 1798 if (state.isInstallAllowed()) { 1799 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1800 broadcastPackageVerified(verificationId, originUri, 1801 response.code, state.getInstallArgs().getUser()); 1802 try { 1803 ret = args.copyApk(mContainerService, true); 1804 } catch (RemoteException e) { 1805 Slog.e(TAG, "Could not contact the ContainerService"); 1806 } 1807 } else { 1808 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1809 } 1810 1811 Trace.asyncTraceEnd( 1812 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1813 1814 processPendingInstall(args, ret); 1815 mHandler.sendEmptyMessage(MCS_UNBIND); 1816 } 1817 1818 break; 1819 } 1820 case START_INTENT_FILTER_VERIFICATIONS: { 1821 IFVerificationParams params = (IFVerificationParams) msg.obj; 1822 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1823 params.replacing, params.pkg); 1824 break; 1825 } 1826 case INTENT_FILTER_VERIFIED: { 1827 final int verificationId = msg.arg1; 1828 1829 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1830 verificationId); 1831 if (state == null) { 1832 Slog.w(TAG, "Invalid IntentFilter verification token " 1833 + verificationId + " received"); 1834 break; 1835 } 1836 1837 final int userId = state.getUserId(); 1838 1839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1840 "Processing IntentFilter verification with token:" 1841 + verificationId + " and userId:" + userId); 1842 1843 final IntentFilterVerificationResponse response = 1844 (IntentFilterVerificationResponse) msg.obj; 1845 1846 state.setVerifierResponse(response.callerUid, response.code); 1847 1848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1849 "IntentFilter verification with token:" + verificationId 1850 + " and userId:" + userId 1851 + " is settings verifier response with response code:" 1852 + response.code); 1853 1854 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1856 + response.getFailedDomainsString()); 1857 } 1858 1859 if (state.isVerificationComplete()) { 1860 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1861 } else { 1862 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1863 "IntentFilter verification with token:" + verificationId 1864 + " was not said to be complete"); 1865 } 1866 1867 break; 1868 } 1869 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1870 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1871 mInstantAppResolverConnection, 1872 (InstantAppRequest) msg.obj, 1873 mInstantAppInstallerActivity, 1874 mHandler); 1875 } 1876 } 1877 } 1878 } 1879 1880 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1881 @Override 1882 public void onGidsChanged(int appId, int userId) { 1883 mHandler.post(new Runnable() { 1884 @Override 1885 public void run() { 1886 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1887 } 1888 }); 1889 } 1890 @Override 1891 public void onPermissionGranted(int uid, int userId) { 1892 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1893 1894 // Not critical; if this is lost, the application has to request again. 1895 synchronized (mPackages) { 1896 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1897 } 1898 } 1899 @Override 1900 public void onInstallPermissionGranted() { 1901 synchronized (mPackages) { 1902 scheduleWriteSettingsLocked(); 1903 } 1904 } 1905 @Override 1906 public void onPermissionRevoked(int uid, int userId) { 1907 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1908 1909 synchronized (mPackages) { 1910 // Critical; after this call the application should never have the permission 1911 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1912 } 1913 1914 final int appId = UserHandle.getAppId(uid); 1915 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1916 } 1917 @Override 1918 public void onInstallPermissionRevoked() { 1919 synchronized (mPackages) { 1920 scheduleWriteSettingsLocked(); 1921 } 1922 } 1923 @Override 1924 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1925 synchronized (mPackages) { 1926 for (int userId : updatedUserIds) { 1927 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1928 } 1929 } 1930 } 1931 @Override 1932 public void onInstallPermissionUpdated() { 1933 synchronized (mPackages) { 1934 scheduleWriteSettingsLocked(); 1935 } 1936 } 1937 @Override 1938 public void onPermissionRemoved() { 1939 synchronized (mPackages) { 1940 mSettings.writeLPr(); 1941 } 1942 } 1943 }; 1944 1945 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1946 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1947 boolean launchedForRestore, String installerPackage, 1948 IPackageInstallObserver2 installObserver) { 1949 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1950 // Send the removed broadcasts 1951 if (res.removedInfo != null) { 1952 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1953 } 1954 1955 // Now that we successfully installed the package, grant runtime 1956 // permissions if requested before broadcasting the install. Also 1957 // for legacy apps in permission review mode we clear the permission 1958 // review flag which is used to emulate runtime permissions for 1959 // legacy apps. 1960 if (grantPermissions) { 1961 final int callingUid = Binder.getCallingUid(); 1962 mPermissionManager.grantRequestedRuntimePermissions( 1963 res.pkg, res.newUsers, grantedPermissions, callingUid, 1964 mPermissionCallback); 1965 } 1966 1967 final boolean update = res.removedInfo != null 1968 && res.removedInfo.removedPackage != null; 1969 final String installerPackageName = 1970 res.installerPackageName != null 1971 ? res.installerPackageName 1972 : res.removedInfo != null 1973 ? res.removedInfo.installerPackageName 1974 : null; 1975 1976 // If this is the first time we have child packages for a disabled privileged 1977 // app that had no children, we grant requested runtime permissions to the new 1978 // children if the parent on the system image had them already granted. 1979 if (res.pkg.parentPackage != null) { 1980 final int callingUid = Binder.getCallingUid(); 1981 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1982 res.pkg, callingUid, mPermissionCallback); 1983 } 1984 1985 synchronized (mPackages) { 1986 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1987 } 1988 1989 final String packageName = res.pkg.applicationInfo.packageName; 1990 1991 // Determine the set of users who are adding this package for 1992 // the first time vs. those who are seeing an update. 1993 int[] firstUserIds = EMPTY_INT_ARRAY; 1994 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1995 int[] updateUserIds = EMPTY_INT_ARRAY; 1996 int[] instantUserIds = EMPTY_INT_ARRAY; 1997 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1998 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1999 for (int newUser : res.newUsers) { 2000 final boolean isInstantApp = ps.getInstantApp(newUser); 2001 if (allNewUsers) { 2002 if (isInstantApp) { 2003 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2004 } else { 2005 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2006 } 2007 continue; 2008 } 2009 boolean isNew = true; 2010 for (int origUser : res.origUsers) { 2011 if (origUser == newUser) { 2012 isNew = false; 2013 break; 2014 } 2015 } 2016 if (isNew) { 2017 if (isInstantApp) { 2018 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2019 } else { 2020 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2021 } 2022 } else { 2023 if (isInstantApp) { 2024 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2025 } else { 2026 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2027 } 2028 } 2029 } 2030 2031 // Send installed broadcasts if the package is not a static shared lib. 2032 if (res.pkg.staticSharedLibName == null) { 2033 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2034 2035 // Send added for users that see the package for the first time 2036 // sendPackageAddedForNewUsers also deals with system apps 2037 int appId = UserHandle.getAppId(res.uid); 2038 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2039 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2040 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2041 2042 // Send added for users that don't see the package for the first time 2043 Bundle extras = new Bundle(1); 2044 extras.putInt(Intent.EXTRA_UID, res.uid); 2045 if (update) { 2046 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2047 } 2048 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2049 extras, 0 /*flags*/, 2050 null /*targetPackage*/, null /*finishedReceiver*/, 2051 updateUserIds, instantUserIds); 2052 if (installerPackageName != null) { 2053 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2054 extras, 0 /*flags*/, 2055 installerPackageName, null /*finishedReceiver*/, 2056 updateUserIds, instantUserIds); 2057 } 2058 2059 // Send replaced for users that don't see the package for the first time 2060 if (update) { 2061 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2062 packageName, extras, 0 /*flags*/, 2063 null /*targetPackage*/, null /*finishedReceiver*/, 2064 updateUserIds, instantUserIds); 2065 if (installerPackageName != null) { 2066 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2067 extras, 0 /*flags*/, 2068 installerPackageName, null /*finishedReceiver*/, 2069 updateUserIds, instantUserIds); 2070 } 2071 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2072 null /*package*/, null /*extras*/, 0 /*flags*/, 2073 packageName /*targetPackage*/, 2074 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2075 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2076 // First-install and we did a restore, so we're responsible for the 2077 // first-launch broadcast. 2078 if (DEBUG_BACKUP) { 2079 Slog.i(TAG, "Post-restore of " + packageName 2080 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2081 } 2082 sendFirstLaunchBroadcast(packageName, installerPackage, 2083 firstUserIds, firstInstantUserIds); 2084 } 2085 2086 // Send broadcast package appeared if forward locked/external for all users 2087 // treat asec-hosted packages like removable media on upgrade 2088 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2089 if (DEBUG_INSTALL) { 2090 Slog.i(TAG, "upgrading pkg " + res.pkg 2091 + " is ASEC-hosted -> AVAILABLE"); 2092 } 2093 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2094 ArrayList<String> pkgList = new ArrayList<>(1); 2095 pkgList.add(packageName); 2096 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2097 } 2098 } 2099 2100 // Work that needs to happen on first install within each user 2101 if (firstUserIds != null && firstUserIds.length > 0) { 2102 synchronized (mPackages) { 2103 for (int userId : firstUserIds) { 2104 // If this app is a browser and it's newly-installed for some 2105 // users, clear any default-browser state in those users. The 2106 // app's nature doesn't depend on the user, so we can just check 2107 // its browser nature in any user and generalize. 2108 if (packageIsBrowser(packageName, userId)) { 2109 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2110 } 2111 2112 // We may also need to apply pending (restored) runtime 2113 // permission grants within these users. 2114 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2115 } 2116 } 2117 } 2118 2119 if (allNewUsers && !update) { 2120 notifyPackageAdded(packageName); 2121 } 2122 2123 // Log current value of "unknown sources" setting 2124 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2125 getUnknownSourcesSettings()); 2126 2127 // Remove the replaced package's older resources safely now 2128 // We delete after a gc for applications on sdcard. 2129 if (res.removedInfo != null && res.removedInfo.args != null) { 2130 Runtime.getRuntime().gc(); 2131 synchronized (mInstallLock) { 2132 res.removedInfo.args.doPostDeleteLI(true); 2133 } 2134 } else { 2135 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2136 // and not block here. 2137 VMRuntime.getRuntime().requestConcurrentGC(); 2138 } 2139 2140 // Notify DexManager that the package was installed for new users. 2141 // The updated users should already be indexed and the package code paths 2142 // should not change. 2143 // Don't notify the manager for ephemeral apps as they are not expected to 2144 // survive long enough to benefit of background optimizations. 2145 for (int userId : firstUserIds) { 2146 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2147 // There's a race currently where some install events may interleave with an uninstall. 2148 // This can lead to package info being null (b/36642664). 2149 if (info != null) { 2150 mDexManager.notifyPackageInstalled(info, userId); 2151 } 2152 } 2153 } 2154 2155 // If someone is watching installs - notify them 2156 if (installObserver != null) { 2157 try { 2158 Bundle extras = extrasForInstallResult(res); 2159 installObserver.onPackageInstalled(res.name, res.returnCode, 2160 res.returnMsg, extras); 2161 } catch (RemoteException e) { 2162 Slog.i(TAG, "Observer no longer exists."); 2163 } 2164 } 2165 } 2166 2167 private StorageEventListener mStorageListener = new StorageEventListener() { 2168 @Override 2169 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2170 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2171 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2172 final String volumeUuid = vol.getFsUuid(); 2173 2174 // Clean up any users or apps that were removed or recreated 2175 // while this volume was missing 2176 sUserManager.reconcileUsers(volumeUuid); 2177 reconcileApps(volumeUuid); 2178 2179 // Clean up any install sessions that expired or were 2180 // cancelled while this volume was missing 2181 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2182 2183 loadPrivatePackages(vol); 2184 2185 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2186 unloadPrivatePackages(vol); 2187 } 2188 } 2189 } 2190 2191 @Override 2192 public void onVolumeForgotten(String fsUuid) { 2193 if (TextUtils.isEmpty(fsUuid)) { 2194 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2195 return; 2196 } 2197 2198 // Remove any apps installed on the forgotten volume 2199 synchronized (mPackages) { 2200 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2201 for (PackageSetting ps : packages) { 2202 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2203 deletePackageVersioned(new VersionedPackage(ps.name, 2204 PackageManager.VERSION_CODE_HIGHEST), 2205 new LegacyPackageDeleteObserver(null).getBinder(), 2206 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2207 // Try very hard to release any references to this package 2208 // so we don't risk the system server being killed due to 2209 // open FDs 2210 AttributeCache.instance().removePackage(ps.name); 2211 } 2212 2213 mSettings.onVolumeForgotten(fsUuid); 2214 mSettings.writeLPr(); 2215 } 2216 } 2217 }; 2218 2219 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2220 Bundle extras = null; 2221 switch (res.returnCode) { 2222 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2223 extras = new Bundle(); 2224 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2225 res.origPermission); 2226 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2227 res.origPackage); 2228 break; 2229 } 2230 case PackageManager.INSTALL_SUCCEEDED: { 2231 extras = new Bundle(); 2232 extras.putBoolean(Intent.EXTRA_REPLACING, 2233 res.removedInfo != null && res.removedInfo.removedPackage != null); 2234 break; 2235 } 2236 } 2237 return extras; 2238 } 2239 2240 void scheduleWriteSettingsLocked() { 2241 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2242 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2243 } 2244 } 2245 2246 void scheduleWritePackageListLocked(int userId) { 2247 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2248 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2249 msg.arg1 = userId; 2250 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2251 } 2252 } 2253 2254 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2255 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2256 scheduleWritePackageRestrictionsLocked(userId); 2257 } 2258 2259 void scheduleWritePackageRestrictionsLocked(int userId) { 2260 final int[] userIds = (userId == UserHandle.USER_ALL) 2261 ? sUserManager.getUserIds() : new int[]{userId}; 2262 for (int nextUserId : userIds) { 2263 if (!sUserManager.exists(nextUserId)) return; 2264 mDirtyUsers.add(nextUserId); 2265 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2266 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2267 } 2268 } 2269 } 2270 2271 public static PackageManagerService main(Context context, Installer installer, 2272 boolean factoryTest, boolean onlyCore) { 2273 // Self-check for initial settings. 2274 PackageManagerServiceCompilerMapping.checkProperties(); 2275 2276 PackageManagerService m = new PackageManagerService(context, installer, 2277 factoryTest, onlyCore); 2278 m.enableSystemUserPackages(); 2279 ServiceManager.addService("package", m); 2280 final PackageManagerNative pmn = m.new PackageManagerNative(); 2281 ServiceManager.addService("package_native", pmn); 2282 return m; 2283 } 2284 2285 private void enableSystemUserPackages() { 2286 if (!UserManager.isSplitSystemUser()) { 2287 return; 2288 } 2289 // For system user, enable apps based on the following conditions: 2290 // - app is whitelisted or belong to one of these groups: 2291 // -- system app which has no launcher icons 2292 // -- system app which has INTERACT_ACROSS_USERS permission 2293 // -- system IME app 2294 // - app is not in the blacklist 2295 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2296 Set<String> enableApps = new ArraySet<>(); 2297 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2298 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2299 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2300 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2301 enableApps.addAll(wlApps); 2302 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2303 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2304 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2305 enableApps.removeAll(blApps); 2306 Log.i(TAG, "Applications installed for system user: " + enableApps); 2307 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2308 UserHandle.SYSTEM); 2309 final int allAppsSize = allAps.size(); 2310 synchronized (mPackages) { 2311 for (int i = 0; i < allAppsSize; i++) { 2312 String pName = allAps.get(i); 2313 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2314 // Should not happen, but we shouldn't be failing if it does 2315 if (pkgSetting == null) { 2316 continue; 2317 } 2318 boolean install = enableApps.contains(pName); 2319 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2320 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2321 + " for system user"); 2322 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2323 } 2324 } 2325 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2326 } 2327 } 2328 2329 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2330 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2331 Context.DISPLAY_SERVICE); 2332 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2333 } 2334 2335 /** 2336 * Requests that files preopted on a secondary system partition be copied to the data partition 2337 * if possible. Note that the actual copying of the files is accomplished by init for security 2338 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2339 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2340 */ 2341 private static void requestCopyPreoptedFiles() { 2342 final int WAIT_TIME_MS = 100; 2343 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2344 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2345 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2346 // We will wait for up to 100 seconds. 2347 final long timeStart = SystemClock.uptimeMillis(); 2348 final long timeEnd = timeStart + 100 * 1000; 2349 long timeNow = timeStart; 2350 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2351 try { 2352 Thread.sleep(WAIT_TIME_MS); 2353 } catch (InterruptedException e) { 2354 // Do nothing 2355 } 2356 timeNow = SystemClock.uptimeMillis(); 2357 if (timeNow > timeEnd) { 2358 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2359 Slog.wtf(TAG, "cppreopt did not finish!"); 2360 break; 2361 } 2362 } 2363 2364 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2365 } 2366 } 2367 2368 public PackageManagerService(Context context, Installer installer, 2369 boolean factoryTest, boolean onlyCore) { 2370 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2371 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2372 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2373 SystemClock.uptimeMillis()); 2374 2375 if (mSdkVersion <= 0) { 2376 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2377 } 2378 2379 mContext = context; 2380 2381 mFactoryTest = factoryTest; 2382 mOnlyCore = onlyCore; 2383 mMetrics = new DisplayMetrics(); 2384 mInstaller = installer; 2385 2386 // Create sub-components that provide services / data. Order here is important. 2387 synchronized (mInstallLock) { 2388 synchronized (mPackages) { 2389 // Expose private service for system components to use. 2390 LocalServices.addService( 2391 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2392 sUserManager = new UserManagerService(context, this, 2393 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2394 mPermissionManager = PermissionManagerService.create(context, 2395 new DefaultPermissionGrantedCallback() { 2396 @Override 2397 public void onDefaultRuntimePermissionsGranted(int userId) { 2398 synchronized(mPackages) { 2399 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2400 } 2401 } 2402 }, mPackages /*externalLock*/); 2403 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2404 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2405 } 2406 } 2407 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2408 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2409 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2410 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2411 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2412 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2413 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2414 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2415 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2416 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2417 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2418 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2419 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2420 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2421 2422 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2423 if (separateProcesses != null && separateProcesses.length() > 0) { 2424 if ("*".equals(separateProcesses)) { 2425 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2426 mSeparateProcesses = null; 2427 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2428 } else { 2429 mDefParseFlags = 0; 2430 mSeparateProcesses = separateProcesses.split(","); 2431 Slog.w(TAG, "Running with debug.separate_processes: " 2432 + separateProcesses); 2433 } 2434 } else { 2435 mDefParseFlags = 0; 2436 mSeparateProcesses = null; 2437 } 2438 2439 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2440 "*dexopt*"); 2441 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2442 installer, mInstallLock); 2443 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2444 dexManagerListener); 2445 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2446 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2447 2448 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2449 FgThread.get().getLooper()); 2450 2451 getDefaultDisplayMetrics(context, mMetrics); 2452 2453 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2454 SystemConfig systemConfig = SystemConfig.getInstance(); 2455 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2457 2458 mProtectedPackages = new ProtectedPackages(mContext); 2459 2460 synchronized (mInstallLock) { 2461 // writer 2462 synchronized (mPackages) { 2463 mHandlerThread = new ServiceThread(TAG, 2464 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2465 mHandlerThread.start(); 2466 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2467 mProcessLoggingHandler = new ProcessLoggingHandler(); 2468 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2469 mInstantAppRegistry = new InstantAppRegistry(this); 2470 2471 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2472 final int builtInLibCount = libConfig.size(); 2473 for (int i = 0; i < builtInLibCount; i++) { 2474 String name = libConfig.keyAt(i); 2475 String path = libConfig.valueAt(i); 2476 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2477 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2478 } 2479 2480 SELinuxMMAC.readInstallPolicy(); 2481 2482 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2483 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2485 2486 // Clean up orphaned packages for which the code path doesn't exist 2487 // and they are an update to a system app - caused by bug/32321269 2488 final int packageSettingCount = mSettings.mPackages.size(); 2489 for (int i = packageSettingCount - 1; i >= 0; i--) { 2490 PackageSetting ps = mSettings.mPackages.valueAt(i); 2491 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2492 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2493 mSettings.mPackages.removeAt(i); 2494 mSettings.enableSystemPackageLPw(ps.name); 2495 } 2496 } 2497 2498 if (mFirstBoot) { 2499 requestCopyPreoptedFiles(); 2500 } 2501 2502 String customResolverActivity = Resources.getSystem().getString( 2503 R.string.config_customResolverActivity); 2504 if (TextUtils.isEmpty(customResolverActivity)) { 2505 customResolverActivity = null; 2506 } else { 2507 mCustomResolverComponentName = ComponentName.unflattenFromString( 2508 customResolverActivity); 2509 } 2510 2511 long startTime = SystemClock.uptimeMillis(); 2512 2513 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2514 startTime); 2515 2516 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2517 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2518 2519 if (bootClassPath == null) { 2520 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2521 } 2522 2523 if (systemServerClassPath == null) { 2524 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2525 } 2526 2527 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2528 2529 final VersionInfo ver = mSettings.getInternalVersion(); 2530 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2531 if (mIsUpgrade) { 2532 logCriticalInfo(Log.INFO, 2533 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2534 } 2535 2536 // when upgrading from pre-M, promote system app permissions from install to runtime 2537 mPromoteSystemApps = 2538 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2539 2540 // When upgrading from pre-N, we need to handle package extraction like first boot, 2541 // as there is no profiling data available. 2542 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2543 2544 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2545 2546 // save off the names of pre-existing system packages prior to scanning; we don't 2547 // want to automatically grant runtime permissions for new system apps 2548 if (mPromoteSystemApps) { 2549 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2550 while (pkgSettingIter.hasNext()) { 2551 PackageSetting ps = pkgSettingIter.next(); 2552 if (isSystemApp(ps)) { 2553 mExistingSystemPackages.add(ps.name); 2554 } 2555 } 2556 } 2557 2558 mCacheDir = preparePackageParserCache(mIsUpgrade); 2559 2560 // Set flag to monitor and not change apk file paths when 2561 // scanning install directories. 2562 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2563 2564 if (mIsUpgrade || mFirstBoot) { 2565 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2566 } 2567 2568 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2569 // For security and version matching reason, only consider 2570 // overlay packages if they reside in the right directory. 2571 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2572 mDefParseFlags 2573 | PackageParser.PARSE_IS_SYSTEM_DIR, 2574 scanFlags 2575 | SCAN_AS_SYSTEM 2576 | SCAN_AS_VENDOR, 2577 0); 2578 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2579 mDefParseFlags 2580 | PackageParser.PARSE_IS_SYSTEM_DIR, 2581 scanFlags 2582 | SCAN_AS_SYSTEM 2583 | SCAN_AS_PRODUCT, 2584 0); 2585 2586 mParallelPackageParserCallback.findStaticOverlayPackages(); 2587 2588 // Find base frameworks (resource packages without code). 2589 scanDirTracedLI(frameworkDir, 2590 mDefParseFlags 2591 | PackageParser.PARSE_IS_SYSTEM_DIR, 2592 scanFlags 2593 | SCAN_NO_DEX 2594 | SCAN_AS_SYSTEM 2595 | SCAN_AS_PRIVILEGED, 2596 0); 2597 2598 // Collect privileged system packages. 2599 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2600 scanDirTracedLI(privilegedAppDir, 2601 mDefParseFlags 2602 | PackageParser.PARSE_IS_SYSTEM_DIR, 2603 scanFlags 2604 | SCAN_AS_SYSTEM 2605 | SCAN_AS_PRIVILEGED, 2606 0); 2607 2608 // Collect ordinary system packages. 2609 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2610 scanDirTracedLI(systemAppDir, 2611 mDefParseFlags 2612 | PackageParser.PARSE_IS_SYSTEM_DIR, 2613 scanFlags 2614 | SCAN_AS_SYSTEM, 2615 0); 2616 2617 // Collect privileged vendor packages. 2618 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2619 try { 2620 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2621 } catch (IOException e) { 2622 // failed to look up canonical path, continue with original one 2623 } 2624 scanDirTracedLI(privilegedVendorAppDir, 2625 mDefParseFlags 2626 | PackageParser.PARSE_IS_SYSTEM_DIR, 2627 scanFlags 2628 | SCAN_AS_SYSTEM 2629 | SCAN_AS_VENDOR 2630 | SCAN_AS_PRIVILEGED, 2631 0); 2632 2633 // Collect ordinary vendor packages. 2634 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2635 try { 2636 vendorAppDir = vendorAppDir.getCanonicalFile(); 2637 } catch (IOException e) { 2638 // failed to look up canonical path, continue with original one 2639 } 2640 scanDirTracedLI(vendorAppDir, 2641 mDefParseFlags 2642 | PackageParser.PARSE_IS_SYSTEM_DIR, 2643 scanFlags 2644 | SCAN_AS_SYSTEM 2645 | SCAN_AS_VENDOR, 2646 0); 2647 2648 // Collect privileged odm packages. /odm is another vendor partition 2649 // other than /vendor. 2650 File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), 2651 "priv-app"); 2652 try { 2653 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile(); 2654 } catch (IOException e) { 2655 // failed to look up canonical path, continue with original one 2656 } 2657 scanDirTracedLI(privilegedOdmAppDir, 2658 mDefParseFlags 2659 | PackageParser.PARSE_IS_SYSTEM_DIR, 2660 scanFlags 2661 | SCAN_AS_SYSTEM 2662 | SCAN_AS_VENDOR 2663 | SCAN_AS_PRIVILEGED, 2664 0); 2665 2666 // Collect ordinary odm packages. /odm is another vendor partition 2667 // other than /vendor. 2668 File odmAppDir = new File(Environment.getOdmDirectory(), "app"); 2669 try { 2670 odmAppDir = odmAppDir.getCanonicalFile(); 2671 } catch (IOException e) { 2672 // failed to look up canonical path, continue with original one 2673 } 2674 scanDirTracedLI(odmAppDir, 2675 mDefParseFlags 2676 | PackageParser.PARSE_IS_SYSTEM_DIR, 2677 scanFlags 2678 | SCAN_AS_SYSTEM 2679 | SCAN_AS_VENDOR, 2680 0); 2681 2682 // Collect all OEM packages. 2683 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2684 scanDirTracedLI(oemAppDir, 2685 mDefParseFlags 2686 | PackageParser.PARSE_IS_SYSTEM_DIR, 2687 scanFlags 2688 | SCAN_AS_SYSTEM 2689 | SCAN_AS_OEM, 2690 0); 2691 2692 // Collected privileged product packages. 2693 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2694 try { 2695 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2696 } catch (IOException e) { 2697 // failed to look up canonical path, continue with original one 2698 } 2699 scanDirTracedLI(privilegedProductAppDir, 2700 mDefParseFlags 2701 | PackageParser.PARSE_IS_SYSTEM_DIR, 2702 scanFlags 2703 | SCAN_AS_SYSTEM 2704 | SCAN_AS_PRODUCT 2705 | SCAN_AS_PRIVILEGED, 2706 0); 2707 2708 // Collect ordinary product packages. 2709 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2710 try { 2711 productAppDir = productAppDir.getCanonicalFile(); 2712 } catch (IOException e) { 2713 // failed to look up canonical path, continue with original one 2714 } 2715 scanDirTracedLI(productAppDir, 2716 mDefParseFlags 2717 | PackageParser.PARSE_IS_SYSTEM_DIR, 2718 scanFlags 2719 | SCAN_AS_SYSTEM 2720 | SCAN_AS_PRODUCT, 2721 0); 2722 2723 // Prune any system packages that no longer exist. 2724 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2725 // Stub packages must either be replaced with full versions in the /data 2726 // partition or be disabled. 2727 final List<String> stubSystemApps = new ArrayList<>(); 2728 if (!mOnlyCore) { 2729 // do this first before mucking with mPackages for the "expecting better" case 2730 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2731 while (pkgIterator.hasNext()) { 2732 final PackageParser.Package pkg = pkgIterator.next(); 2733 if (pkg.isStub) { 2734 stubSystemApps.add(pkg.packageName); 2735 } 2736 } 2737 2738 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2739 while (psit.hasNext()) { 2740 PackageSetting ps = psit.next(); 2741 2742 /* 2743 * If this is not a system app, it can't be a 2744 * disable system app. 2745 */ 2746 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2747 continue; 2748 } 2749 2750 /* 2751 * If the package is scanned, it's not erased. 2752 */ 2753 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2754 if (scannedPkg != null) { 2755 /* 2756 * If the system app is both scanned and in the 2757 * disabled packages list, then it must have been 2758 * added via OTA. Remove it from the currently 2759 * scanned package so the previously user-installed 2760 * application can be scanned. 2761 */ 2762 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2763 logCriticalInfo(Log.WARN, 2764 "Expecting better updated system app for " + ps.name 2765 + "; removing system app. Last known" 2766 + " codePath=" + ps.codePathString 2767 + ", versionCode=" + ps.versionCode 2768 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2769 removePackageLI(scannedPkg, true); 2770 mExpectingBetter.put(ps.name, ps.codePath); 2771 } 2772 2773 continue; 2774 } 2775 2776 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2777 psit.remove(); 2778 logCriticalInfo(Log.WARN, "System package " + ps.name 2779 + " no longer exists; it's data will be wiped"); 2780 // Actual deletion of code and data will be handled by later 2781 // reconciliation step 2782 } else { 2783 // we still have a disabled system package, but, it still might have 2784 // been removed. check the code path still exists and check there's 2785 // still a package. the latter can happen if an OTA keeps the same 2786 // code path, but, changes the package name. 2787 final PackageSetting disabledPs = 2788 mSettings.getDisabledSystemPkgLPr(ps.name); 2789 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2790 || disabledPs.pkg == null) { 2791 possiblyDeletedUpdatedSystemApps.add(ps.name); 2792 } 2793 } 2794 } 2795 } 2796 2797 //delete tmp files 2798 deleteTempPackageFiles(); 2799 2800 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2801 2802 // Remove any shared userIDs that have no associated packages 2803 mSettings.pruneSharedUsersLPw(); 2804 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2805 final int systemPackagesCount = mPackages.size(); 2806 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2807 + " ms, packageCount: " + systemPackagesCount 2808 + " , timePerPackage: " 2809 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2810 + " , cached: " + cachedSystemApps); 2811 if (mIsUpgrade && systemPackagesCount > 0) { 2812 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2813 ((int) systemScanTime) / systemPackagesCount); 2814 } 2815 if (!mOnlyCore) { 2816 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2817 SystemClock.uptimeMillis()); 2818 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2819 2820 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2821 | PackageParser.PARSE_FORWARD_LOCK, 2822 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2823 2824 // Remove disable package settings for updated system apps that were 2825 // removed via an OTA. If the update is no longer present, remove the 2826 // app completely. Otherwise, revoke their system privileges. 2827 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2828 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2829 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2830 final String msg; 2831 if (deletedPkg == null) { 2832 // should have found an update, but, we didn't; remove everything 2833 msg = "Updated system package " + deletedAppName 2834 + " no longer exists; removing its data"; 2835 // Actual deletion of code and data will be handled by later 2836 // reconciliation step 2837 } else { 2838 // found an update; revoke system privileges 2839 msg = "Updated system package + " + deletedAppName 2840 + " no longer exists; revoking system privileges"; 2841 2842 // Don't do anything if a stub is removed from the system image. If 2843 // we were to remove the uncompressed version from the /data partition, 2844 // this is where it'd be done. 2845 2846 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2847 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2848 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2849 } 2850 logCriticalInfo(Log.WARN, msg); 2851 } 2852 2853 /* 2854 * Make sure all system apps that we expected to appear on 2855 * the userdata partition actually showed up. If they never 2856 * appeared, crawl back and revive the system version. 2857 */ 2858 for (int i = 0; i < mExpectingBetter.size(); i++) { 2859 final String packageName = mExpectingBetter.keyAt(i); 2860 if (!mPackages.containsKey(packageName)) { 2861 final File scanFile = mExpectingBetter.valueAt(i); 2862 2863 logCriticalInfo(Log.WARN, "Expected better " + packageName 2864 + " but never showed up; reverting to system"); 2865 2866 final @ParseFlags int reparseFlags; 2867 final @ScanFlags int rescanFlags; 2868 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2869 reparseFlags = 2870 mDefParseFlags | 2871 PackageParser.PARSE_IS_SYSTEM_DIR; 2872 rescanFlags = 2873 scanFlags 2874 | SCAN_AS_SYSTEM 2875 | SCAN_AS_PRIVILEGED; 2876 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2877 reparseFlags = 2878 mDefParseFlags | 2879 PackageParser.PARSE_IS_SYSTEM_DIR; 2880 rescanFlags = 2881 scanFlags 2882 | SCAN_AS_SYSTEM; 2883 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile) 2884 || FileUtils.contains(privilegedOdmAppDir, scanFile)) { 2885 reparseFlags = 2886 mDefParseFlags | 2887 PackageParser.PARSE_IS_SYSTEM_DIR; 2888 rescanFlags = 2889 scanFlags 2890 | SCAN_AS_SYSTEM 2891 | SCAN_AS_VENDOR 2892 | SCAN_AS_PRIVILEGED; 2893 } else if (FileUtils.contains(vendorAppDir, scanFile) 2894 || FileUtils.contains(odmAppDir, scanFile)) { 2895 reparseFlags = 2896 mDefParseFlags | 2897 PackageParser.PARSE_IS_SYSTEM_DIR; 2898 rescanFlags = 2899 scanFlags 2900 | SCAN_AS_SYSTEM 2901 | SCAN_AS_VENDOR; 2902 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2903 reparseFlags = 2904 mDefParseFlags | 2905 PackageParser.PARSE_IS_SYSTEM_DIR; 2906 rescanFlags = 2907 scanFlags 2908 | SCAN_AS_SYSTEM 2909 | SCAN_AS_OEM; 2910 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2911 reparseFlags = 2912 mDefParseFlags | 2913 PackageParser.PARSE_IS_SYSTEM_DIR; 2914 rescanFlags = 2915 scanFlags 2916 | SCAN_AS_SYSTEM 2917 | SCAN_AS_PRODUCT 2918 | SCAN_AS_PRIVILEGED; 2919 } else if (FileUtils.contains(productAppDir, scanFile)) { 2920 reparseFlags = 2921 mDefParseFlags | 2922 PackageParser.PARSE_IS_SYSTEM_DIR; 2923 rescanFlags = 2924 scanFlags 2925 | SCAN_AS_SYSTEM 2926 | SCAN_AS_PRODUCT; 2927 } else { 2928 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2929 continue; 2930 } 2931 2932 mSettings.enableSystemPackageLPw(packageName); 2933 2934 try { 2935 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2936 } catch (PackageManagerException e) { 2937 Slog.e(TAG, "Failed to parse original system package: " 2938 + e.getMessage()); 2939 } 2940 } 2941 } 2942 2943 // Uncompress and install any stubbed system applications. 2944 // This must be done last to ensure all stubs are replaced or disabled. 2945 decompressSystemApplications(stubSystemApps, scanFlags); 2946 2947 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2948 - cachedSystemApps; 2949 2950 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2951 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2952 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2953 + " ms, packageCount: " + dataPackagesCount 2954 + " , timePerPackage: " 2955 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2956 + " , cached: " + cachedNonSystemApps); 2957 if (mIsUpgrade && dataPackagesCount > 0) { 2958 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2959 ((int) dataScanTime) / dataPackagesCount); 2960 } 2961 } 2962 mExpectingBetter.clear(); 2963 2964 // Resolve the storage manager. 2965 mStorageManagerPackage = getStorageManagerPackageName(); 2966 2967 // Resolve protected action filters. Only the setup wizard is allowed to 2968 // have a high priority filter for these actions. 2969 mSetupWizardPackage = getSetupWizardPackageName(); 2970 if (mProtectedFilters.size() > 0) { 2971 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2972 Slog.i(TAG, "No setup wizard;" 2973 + " All protected intents capped to priority 0"); 2974 } 2975 for (ActivityIntentInfo filter : mProtectedFilters) { 2976 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2977 if (DEBUG_FILTERS) { 2978 Slog.i(TAG, "Found setup wizard;" 2979 + " allow priority " + filter.getPriority() + ";" 2980 + " package: " + filter.activity.info.packageName 2981 + " activity: " + filter.activity.className 2982 + " priority: " + filter.getPriority()); 2983 } 2984 // skip setup wizard; allow it to keep the high priority filter 2985 continue; 2986 } 2987 if (DEBUG_FILTERS) { 2988 Slog.i(TAG, "Protected action; cap priority to 0;" 2989 + " package: " + filter.activity.info.packageName 2990 + " activity: " + filter.activity.className 2991 + " origPrio: " + filter.getPriority()); 2992 } 2993 filter.setPriority(0); 2994 } 2995 } 2996 2997 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 2998 2999 mDeferProtectedFilters = false; 3000 mProtectedFilters.clear(); 3001 3002 // Now that we know all of the shared libraries, update all clients to have 3003 // the correct library paths. 3004 updateAllSharedLibrariesLPw(null); 3005 3006 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3007 // NOTE: We ignore potential failures here during a system scan (like 3008 // the rest of the commands above) because there's precious little we 3009 // can do about it. A settings error is reported, though. 3010 final List<String> changedAbiCodePath = 3011 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 3012 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3013 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3014 final String codePathString = changedAbiCodePath.get(i); 3015 try { 3016 mInstaller.rmdex(codePathString, 3017 getDexCodeInstructionSet(getPreferredInstructionSet())); 3018 } catch (InstallerException ignored) { 3019 } 3020 } 3021 } 3022 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3023 // SELinux domain. 3024 setting.fixSeInfoLocked(); 3025 } 3026 3027 // Now that we know all the packages we are keeping, 3028 // read and update their last usage times. 3029 mPackageUsage.read(mPackages); 3030 mCompilerStats.read(); 3031 3032 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3033 SystemClock.uptimeMillis()); 3034 Slog.i(TAG, "Time to scan packages: " 3035 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3036 + " seconds"); 3037 3038 // If the platform SDK has changed since the last time we booted, 3039 // we need to re-grant app permission to catch any new ones that 3040 // appear. This is really a hack, and means that apps can in some 3041 // cases get permissions that the user didn't initially explicitly 3042 // allow... it would be nice to have some better way to handle 3043 // this situation. 3044 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3045 if (sdkUpdated) { 3046 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3047 + mSdkVersion + "; regranting permissions for internal storage"); 3048 } 3049 mPermissionManager.updateAllPermissions( 3050 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3051 mPermissionCallback); 3052 ver.sdkVersion = mSdkVersion; 3053 3054 // If this is the first boot or an update from pre-M, and it is a normal 3055 // boot, then we need to initialize the default preferred apps across 3056 // all defined users. 3057 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3058 for (UserInfo user : sUserManager.getUsers(true)) { 3059 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3060 applyFactoryDefaultBrowserLPw(user.id); 3061 primeDomainVerificationsLPw(user.id); 3062 } 3063 } 3064 3065 // Prepare storage for system user really early during boot, 3066 // since core system apps like SettingsProvider and SystemUI 3067 // can't wait for user to start 3068 final int storageFlags; 3069 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3070 storageFlags = StorageManager.FLAG_STORAGE_DE; 3071 } else { 3072 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3073 } 3074 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3075 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3076 true /* onlyCoreApps */); 3077 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3078 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3079 Trace.TRACE_TAG_PACKAGE_MANAGER); 3080 traceLog.traceBegin("AppDataFixup"); 3081 try { 3082 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3083 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3084 } catch (InstallerException e) { 3085 Slog.w(TAG, "Trouble fixing GIDs", e); 3086 } 3087 traceLog.traceEnd(); 3088 3089 traceLog.traceBegin("AppDataPrepare"); 3090 if (deferPackages == null || deferPackages.isEmpty()) { 3091 return; 3092 } 3093 int count = 0; 3094 for (String pkgName : deferPackages) { 3095 PackageParser.Package pkg = null; 3096 synchronized (mPackages) { 3097 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3098 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3099 pkg = ps.pkg; 3100 } 3101 } 3102 if (pkg != null) { 3103 synchronized (mInstallLock) { 3104 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3105 true /* maybeMigrateAppData */); 3106 } 3107 count++; 3108 } 3109 } 3110 traceLog.traceEnd(); 3111 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3112 }, "prepareAppData"); 3113 3114 // If this is first boot after an OTA, and a normal boot, then 3115 // we need to clear code cache directories. 3116 // Note that we do *not* clear the application profiles. These remain valid 3117 // across OTAs and are used to drive profile verification (post OTA) and 3118 // profile compilation (without waiting to collect a fresh set of profiles). 3119 if (mIsUpgrade && !onlyCore) { 3120 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3121 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3122 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3123 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3124 // No apps are running this early, so no need to freeze 3125 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3126 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3127 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3128 } 3129 } 3130 ver.fingerprint = Build.FINGERPRINT; 3131 } 3132 3133 checkDefaultBrowser(); 3134 3135 // clear only after permissions and other defaults have been updated 3136 mExistingSystemPackages.clear(); 3137 mPromoteSystemApps = false; 3138 3139 // All the changes are done during package scanning. 3140 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3141 3142 // can downgrade to reader 3143 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3144 mSettings.writeLPr(); 3145 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3146 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3147 SystemClock.uptimeMillis()); 3148 3149 if (!mOnlyCore) { 3150 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3151 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3152 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3153 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3154 if (mIntentFilterVerifierComponent != null) { 3155 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3156 mIntentFilterVerifierComponent); 3157 } else { 3158 mIntentFilterVerifier = null; 3159 } 3160 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3161 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3162 SharedLibraryInfo.VERSION_UNDEFINED); 3163 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3164 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3165 SharedLibraryInfo.VERSION_UNDEFINED); 3166 } else { 3167 mRequiredVerifierPackage = null; 3168 mRequiredInstallerPackage = null; 3169 mRequiredUninstallerPackage = null; 3170 mIntentFilterVerifierComponent = null; 3171 mIntentFilterVerifier = null; 3172 mServicesSystemSharedLibraryPackageName = null; 3173 mSharedSystemSharedLibraryPackageName = null; 3174 } 3175 3176 mInstallerService = new PackageInstallerService(context, this); 3177 final Pair<ComponentName, String> instantAppResolverComponent = 3178 getInstantAppResolverLPr(); 3179 if (instantAppResolverComponent != null) { 3180 if (DEBUG_INSTANT) { 3181 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3182 } 3183 mInstantAppResolverConnection = new InstantAppResolverConnection( 3184 mContext, instantAppResolverComponent.first, 3185 instantAppResolverComponent.second); 3186 mInstantAppResolverSettingsComponent = 3187 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3188 } else { 3189 mInstantAppResolverConnection = null; 3190 mInstantAppResolverSettingsComponent = null; 3191 } 3192 updateInstantAppInstallerLocked(null); 3193 3194 // Read and update the usage of dex files. 3195 // Do this at the end of PM init so that all the packages have their 3196 // data directory reconciled. 3197 // At this point we know the code paths of the packages, so we can validate 3198 // the disk file and build the internal cache. 3199 // The usage file is expected to be small so loading and verifying it 3200 // should take a fairly small time compare to the other activities (e.g. package 3201 // scanning). 3202 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3203 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3204 for (int userId : currentUserIds) { 3205 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3206 } 3207 mDexManager.load(userPackages); 3208 if (mIsUpgrade) { 3209 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3210 (int) (SystemClock.uptimeMillis() - startTime)); 3211 } 3212 } // synchronized (mPackages) 3213 } // synchronized (mInstallLock) 3214 3215 // Now after opening every single application zip, make sure they 3216 // are all flushed. Not really needed, but keeps things nice and 3217 // tidy. 3218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3219 Runtime.getRuntime().gc(); 3220 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3221 3222 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3223 FallbackCategoryProvider.loadFallbacks(); 3224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3225 3226 // The initial scanning above does many calls into installd while 3227 // holding the mPackages lock, but we're mostly interested in yelling 3228 // once we have a booted system. 3229 mInstaller.setWarnIfHeld(mPackages); 3230 3231 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3232 } 3233 3234 /** 3235 * Uncompress and install stub applications. 3236 * <p>In order to save space on the system partition, some applications are shipped in a 3237 * compressed form. In addition the compressed bits for the full application, the 3238 * system image contains a tiny stub comprised of only the Android manifest. 3239 * <p>During the first boot, attempt to uncompress and install the full application. If 3240 * the application can't be installed for any reason, disable the stub and prevent 3241 * uncompressing the full application during future boots. 3242 * <p>In order to forcefully attempt an installation of a full application, go to app 3243 * settings and enable the application. 3244 */ 3245 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3246 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3247 final String pkgName = stubSystemApps.get(i); 3248 // skip if the system package is already disabled 3249 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3250 stubSystemApps.remove(i); 3251 continue; 3252 } 3253 // skip if the package isn't installed (?!); this should never happen 3254 final PackageParser.Package pkg = mPackages.get(pkgName); 3255 if (pkg == null) { 3256 stubSystemApps.remove(i); 3257 continue; 3258 } 3259 // skip if the package has been disabled by the user 3260 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3261 if (ps != null) { 3262 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3263 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3264 stubSystemApps.remove(i); 3265 continue; 3266 } 3267 } 3268 3269 if (DEBUG_COMPRESSION) { 3270 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3271 } 3272 3273 // uncompress the binary to its eventual destination on /data 3274 final File scanFile = decompressPackage(pkg); 3275 if (scanFile == null) { 3276 continue; 3277 } 3278 3279 // install the package to replace the stub on /system 3280 try { 3281 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3282 removePackageLI(pkg, true /*chatty*/); 3283 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3284 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3285 UserHandle.USER_SYSTEM, "android"); 3286 stubSystemApps.remove(i); 3287 continue; 3288 } catch (PackageManagerException e) { 3289 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3290 } 3291 3292 // any failed attempt to install the package will be cleaned up later 3293 } 3294 3295 // disable any stub still left; these failed to install the full application 3296 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3297 final String pkgName = stubSystemApps.get(i); 3298 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3299 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3300 UserHandle.USER_SYSTEM, "android"); 3301 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3302 } 3303 } 3304 3305 /** 3306 * Decompresses the given package on the system image onto 3307 * the /data partition. 3308 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3309 */ 3310 private File decompressPackage(PackageParser.Package pkg) { 3311 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3312 if (compressedFiles == null || compressedFiles.length == 0) { 3313 if (DEBUG_COMPRESSION) { 3314 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3315 } 3316 return null; 3317 } 3318 final File dstCodePath = 3319 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3320 int ret = PackageManager.INSTALL_SUCCEEDED; 3321 try { 3322 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3323 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3324 for (File srcFile : compressedFiles) { 3325 final String srcFileName = srcFile.getName(); 3326 final String dstFileName = srcFileName.substring( 3327 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3328 final File dstFile = new File(dstCodePath, dstFileName); 3329 ret = decompressFile(srcFile, dstFile); 3330 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3331 logCriticalInfo(Log.ERROR, "Failed to decompress" 3332 + "; pkg: " + pkg.packageName 3333 + ", file: " + dstFileName); 3334 break; 3335 } 3336 } 3337 } catch (ErrnoException e) { 3338 logCriticalInfo(Log.ERROR, "Failed to decompress" 3339 + "; pkg: " + pkg.packageName 3340 + ", err: " + e.errno); 3341 } 3342 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3343 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3344 NativeLibraryHelper.Handle handle = null; 3345 try { 3346 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3347 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3348 null /*abiOverride*/); 3349 } catch (IOException e) { 3350 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3351 + "; pkg: " + pkg.packageName); 3352 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3353 } finally { 3354 IoUtils.closeQuietly(handle); 3355 } 3356 } 3357 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3358 if (dstCodePath == null || !dstCodePath.exists()) { 3359 return null; 3360 } 3361 removeCodePathLI(dstCodePath); 3362 return null; 3363 } 3364 3365 return dstCodePath; 3366 } 3367 3368 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3369 // we're only interested in updating the installer appliction when 1) it's not 3370 // already set or 2) the modified package is the installer 3371 if (mInstantAppInstallerActivity != null 3372 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3373 .equals(modifiedPackage)) { 3374 return; 3375 } 3376 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3377 } 3378 3379 private static File preparePackageParserCache(boolean isUpgrade) { 3380 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3381 return null; 3382 } 3383 3384 // Disable package parsing on eng builds to allow for faster incremental development. 3385 if (Build.IS_ENG) { 3386 return null; 3387 } 3388 3389 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3390 Slog.i(TAG, "Disabling package parser cache due to system property."); 3391 return null; 3392 } 3393 3394 // The base directory for the package parser cache lives under /data/system/. 3395 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3396 "package_cache"); 3397 if (cacheBaseDir == null) { 3398 return null; 3399 } 3400 3401 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3402 // This also serves to "GC" unused entries when the package cache version changes (which 3403 // can only happen during upgrades). 3404 if (isUpgrade) { 3405 FileUtils.deleteContents(cacheBaseDir); 3406 } 3407 3408 3409 // Return the versioned package cache directory. This is something like 3410 // "/data/system/package_cache/1" 3411 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3412 3413 if (cacheDir == null) { 3414 // Something went wrong. Attempt to delete everything and return. 3415 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3416 FileUtils.deleteContentsAndDir(cacheBaseDir); 3417 return null; 3418 } 3419 3420 // The following is a workaround to aid development on non-numbered userdebug 3421 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3422 // the system partition is newer. 3423 // 3424 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3425 // that starts with "eng." to signify that this is an engineering build and not 3426 // destined for release. 3427 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3428 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3429 3430 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3431 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3432 // in general and should not be used for production changes. In this specific case, 3433 // we know that they will work. 3434 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3435 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3436 FileUtils.deleteContents(cacheBaseDir); 3437 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3438 } 3439 } 3440 3441 return cacheDir; 3442 } 3443 3444 @Override 3445 public boolean isFirstBoot() { 3446 // allow instant applications 3447 return mFirstBoot; 3448 } 3449 3450 @Override 3451 public boolean isOnlyCoreApps() { 3452 // allow instant applications 3453 return mOnlyCore; 3454 } 3455 3456 @Override 3457 public boolean isUpgrade() { 3458 // allow instant applications 3459 // The system property allows testing ota flow when upgraded to the same image. 3460 return mIsUpgrade || SystemProperties.getBoolean( 3461 "persist.pm.mock-upgrade", false /* default */); 3462 } 3463 3464 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3465 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3466 3467 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3468 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3469 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3470 if (matches.size() == 1) { 3471 return matches.get(0).getComponentInfo().packageName; 3472 } else if (matches.size() == 0) { 3473 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3474 return null; 3475 } 3476 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3477 } 3478 3479 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3480 synchronized (mPackages) { 3481 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3482 if (libraryEntry == null) { 3483 throw new IllegalStateException("Missing required shared library:" + name); 3484 } 3485 return libraryEntry.apk; 3486 } 3487 } 3488 3489 private @NonNull String getRequiredInstallerLPr() { 3490 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3491 intent.addCategory(Intent.CATEGORY_DEFAULT); 3492 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3493 3494 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3495 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3496 UserHandle.USER_SYSTEM); 3497 if (matches.size() == 1) { 3498 ResolveInfo resolveInfo = matches.get(0); 3499 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3500 throw new RuntimeException("The installer must be a privileged app"); 3501 } 3502 return matches.get(0).getComponentInfo().packageName; 3503 } else { 3504 throw new RuntimeException("There must be exactly one installer; found " + matches); 3505 } 3506 } 3507 3508 private @NonNull String getRequiredUninstallerLPr() { 3509 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3510 intent.addCategory(Intent.CATEGORY_DEFAULT); 3511 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3512 3513 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3514 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3515 UserHandle.USER_SYSTEM); 3516 if (resolveInfo == null || 3517 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3518 throw new RuntimeException("There must be exactly one uninstaller; found " 3519 + resolveInfo); 3520 } 3521 return resolveInfo.getComponentInfo().packageName; 3522 } 3523 3524 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3525 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3526 3527 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3528 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3529 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3530 ResolveInfo best = null; 3531 final int N = matches.size(); 3532 for (int i = 0; i < N; i++) { 3533 final ResolveInfo cur = matches.get(i); 3534 final String packageName = cur.getComponentInfo().packageName; 3535 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3536 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3537 continue; 3538 } 3539 3540 if (best == null || cur.priority > best.priority) { 3541 best = cur; 3542 } 3543 } 3544 3545 if (best != null) { 3546 return best.getComponentInfo().getComponentName(); 3547 } 3548 Slog.w(TAG, "Intent filter verifier not found"); 3549 return null; 3550 } 3551 3552 @Override 3553 public @Nullable ComponentName getInstantAppResolverComponent() { 3554 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3555 return null; 3556 } 3557 synchronized (mPackages) { 3558 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3559 if (instantAppResolver == null) { 3560 return null; 3561 } 3562 return instantAppResolver.first; 3563 } 3564 } 3565 3566 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3567 final String[] packageArray = 3568 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3569 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3570 if (DEBUG_INSTANT) { 3571 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3572 } 3573 return null; 3574 } 3575 3576 final int callingUid = Binder.getCallingUid(); 3577 final int resolveFlags = 3578 MATCH_DIRECT_BOOT_AWARE 3579 | MATCH_DIRECT_BOOT_UNAWARE 3580 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3581 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3582 final Intent resolverIntent = new Intent(actionName); 3583 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3584 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3585 final int N = resolvers.size(); 3586 if (N == 0) { 3587 if (DEBUG_INSTANT) { 3588 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3589 } 3590 return null; 3591 } 3592 3593 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3594 for (int i = 0; i < N; i++) { 3595 final ResolveInfo info = resolvers.get(i); 3596 3597 if (info.serviceInfo == null) { 3598 continue; 3599 } 3600 3601 final String packageName = info.serviceInfo.packageName; 3602 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3603 if (DEBUG_INSTANT) { 3604 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3605 + " pkg: " + packageName + ", info:" + info); 3606 } 3607 continue; 3608 } 3609 3610 if (DEBUG_INSTANT) { 3611 Slog.v(TAG, "Ephemeral resolver found;" 3612 + " pkg: " + packageName + ", info:" + info); 3613 } 3614 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3615 } 3616 if (DEBUG_INSTANT) { 3617 Slog.v(TAG, "Ephemeral resolver NOT found"); 3618 } 3619 return null; 3620 } 3621 3622 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3623 String[] orderedActions = Build.IS_ENG 3624 ? new String[]{ 3625 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3626 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3627 : new String[]{ 3628 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3629 3630 final int resolveFlags = 3631 MATCH_DIRECT_BOOT_AWARE 3632 | MATCH_DIRECT_BOOT_UNAWARE 3633 | Intent.FLAG_IGNORE_EPHEMERAL 3634 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3635 final Intent intent = new Intent(); 3636 intent.addCategory(Intent.CATEGORY_DEFAULT); 3637 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3638 List<ResolveInfo> matches = null; 3639 for (String action : orderedActions) { 3640 intent.setAction(action); 3641 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3642 resolveFlags, UserHandle.USER_SYSTEM); 3643 if (matches.isEmpty()) { 3644 if (DEBUG_INSTANT) { 3645 Slog.d(TAG, "Instant App installer not found with " + action); 3646 } 3647 } else { 3648 break; 3649 } 3650 } 3651 Iterator<ResolveInfo> iter = matches.iterator(); 3652 while (iter.hasNext()) { 3653 final ResolveInfo rInfo = iter.next(); 3654 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3655 if (ps != null) { 3656 final PermissionsState permissionsState = ps.getPermissionsState(); 3657 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3658 || Build.IS_ENG) { 3659 continue; 3660 } 3661 } 3662 iter.remove(); 3663 } 3664 if (matches.size() == 0) { 3665 return null; 3666 } else if (matches.size() == 1) { 3667 return (ActivityInfo) matches.get(0).getComponentInfo(); 3668 } else { 3669 throw new RuntimeException( 3670 "There must be at most one ephemeral installer; found " + matches); 3671 } 3672 } 3673 3674 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3675 @NonNull ComponentName resolver) { 3676 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3677 .addCategory(Intent.CATEGORY_DEFAULT) 3678 .setPackage(resolver.getPackageName()); 3679 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3680 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3681 UserHandle.USER_SYSTEM); 3682 if (matches.isEmpty()) { 3683 return null; 3684 } 3685 return matches.get(0).getComponentInfo().getComponentName(); 3686 } 3687 3688 private void primeDomainVerificationsLPw(int userId) { 3689 if (DEBUG_DOMAIN_VERIFICATION) { 3690 Slog.d(TAG, "Priming domain verifications in user " + userId); 3691 } 3692 3693 SystemConfig systemConfig = SystemConfig.getInstance(); 3694 ArraySet<String> packages = systemConfig.getLinkedApps(); 3695 3696 for (String packageName : packages) { 3697 PackageParser.Package pkg = mPackages.get(packageName); 3698 if (pkg != null) { 3699 if (!pkg.isSystem()) { 3700 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3701 continue; 3702 } 3703 3704 ArraySet<String> domains = null; 3705 for (PackageParser.Activity a : pkg.activities) { 3706 for (ActivityIntentInfo filter : a.intents) { 3707 if (hasValidDomains(filter)) { 3708 if (domains == null) { 3709 domains = new ArraySet<String>(); 3710 } 3711 domains.addAll(filter.getHostsList()); 3712 } 3713 } 3714 } 3715 3716 if (domains != null && domains.size() > 0) { 3717 if (DEBUG_DOMAIN_VERIFICATION) { 3718 Slog.v(TAG, " + " + packageName); 3719 } 3720 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3721 // state w.r.t. the formal app-linkage "no verification attempted" state; 3722 // and then 'always' in the per-user state actually used for intent resolution. 3723 final IntentFilterVerificationInfo ivi; 3724 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3725 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3726 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3727 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3728 } else { 3729 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3730 + "' does not handle web links"); 3731 } 3732 } else { 3733 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3734 } 3735 } 3736 3737 scheduleWritePackageRestrictionsLocked(userId); 3738 scheduleWriteSettingsLocked(); 3739 } 3740 3741 private void applyFactoryDefaultBrowserLPw(int userId) { 3742 // The default browser app's package name is stored in a string resource, 3743 // with a product-specific overlay used for vendor customization. 3744 String browserPkg = mContext.getResources().getString( 3745 com.android.internal.R.string.default_browser); 3746 if (!TextUtils.isEmpty(browserPkg)) { 3747 // non-empty string => required to be a known package 3748 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3749 if (ps == null) { 3750 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3751 browserPkg = null; 3752 } else { 3753 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3754 } 3755 } 3756 3757 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3758 // default. If there's more than one, just leave everything alone. 3759 if (browserPkg == null) { 3760 calculateDefaultBrowserLPw(userId); 3761 } 3762 } 3763 3764 private void calculateDefaultBrowserLPw(int userId) { 3765 List<String> allBrowsers = resolveAllBrowserApps(userId); 3766 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3767 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3768 } 3769 3770 private List<String> resolveAllBrowserApps(int userId) { 3771 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3772 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3773 PackageManager.MATCH_ALL, userId); 3774 3775 final int count = list.size(); 3776 List<String> result = new ArrayList<String>(count); 3777 for (int i=0; i<count; i++) { 3778 ResolveInfo info = list.get(i); 3779 if (info.activityInfo == null 3780 || !info.handleAllWebDataURI 3781 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3782 || result.contains(info.activityInfo.packageName)) { 3783 continue; 3784 } 3785 result.add(info.activityInfo.packageName); 3786 } 3787 3788 return result; 3789 } 3790 3791 private boolean packageIsBrowser(String packageName, int userId) { 3792 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3793 PackageManager.MATCH_ALL, userId); 3794 final int N = list.size(); 3795 for (int i = 0; i < N; i++) { 3796 ResolveInfo info = list.get(i); 3797 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3798 return true; 3799 } 3800 } 3801 return false; 3802 } 3803 3804 private void checkDefaultBrowser() { 3805 final int myUserId = UserHandle.myUserId(); 3806 final String packageName = getDefaultBrowserPackageName(myUserId); 3807 if (packageName != null) { 3808 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3809 if (info == null) { 3810 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3811 synchronized (mPackages) { 3812 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3813 } 3814 } 3815 } 3816 } 3817 3818 @Override 3819 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3820 throws RemoteException { 3821 try { 3822 return super.onTransact(code, data, reply, flags); 3823 } catch (RuntimeException e) { 3824 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3825 Slog.wtf(TAG, "Package Manager Crash", e); 3826 } 3827 throw e; 3828 } 3829 } 3830 3831 static int[] appendInts(int[] cur, int[] add) { 3832 if (add == null) return cur; 3833 if (cur == null) return add; 3834 final int N = add.length; 3835 for (int i=0; i<N; i++) { 3836 cur = appendInt(cur, add[i]); 3837 } 3838 return cur; 3839 } 3840 3841 /** 3842 * Returns whether or not a full application can see an instant application. 3843 * <p> 3844 * Currently, there are three cases in which this can occur: 3845 * <ol> 3846 * <li>The calling application is a "special" process. Special processes 3847 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3848 * <li>The calling application has the permission 3849 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3850 * <li>The calling application is the default launcher on the 3851 * system partition.</li> 3852 * </ol> 3853 */ 3854 private boolean canViewInstantApps(int callingUid, int userId) { 3855 if (callingUid < Process.FIRST_APPLICATION_UID) { 3856 return true; 3857 } 3858 if (mContext.checkCallingOrSelfPermission( 3859 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3860 return true; 3861 } 3862 if (mContext.checkCallingOrSelfPermission( 3863 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3864 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3865 if (homeComponent != null 3866 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3867 return true; 3868 } 3869 } 3870 return false; 3871 } 3872 3873 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3874 if (!sUserManager.exists(userId)) return null; 3875 if (ps == null) { 3876 return null; 3877 } 3878 final int callingUid = Binder.getCallingUid(); 3879 // Filter out ephemeral app metadata: 3880 // * The system/shell/root can see metadata for any app 3881 // * An installed app can see metadata for 1) other installed apps 3882 // and 2) ephemeral apps that have explicitly interacted with it 3883 // * Ephemeral apps can only see their own data and exposed installed apps 3884 // * Holding a signature permission allows seeing instant apps 3885 if (filterAppAccessLPr(ps, callingUid, userId)) { 3886 return null; 3887 } 3888 3889 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3890 && ps.isSystem()) { 3891 flags |= MATCH_ANY_USER; 3892 } 3893 3894 final PackageUserState state = ps.readUserState(userId); 3895 PackageParser.Package p = ps.pkg; 3896 if (p != null) { 3897 final PermissionsState permissionsState = ps.getPermissionsState(); 3898 3899 // Compute GIDs only if requested 3900 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3901 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3902 // Compute granted permissions only if package has requested permissions 3903 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3904 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3905 3906 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3907 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3908 3909 if (packageInfo == null) { 3910 return null; 3911 } 3912 3913 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3914 resolveExternalPackageNameLPr(p); 3915 3916 return packageInfo; 3917 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 3918 PackageInfo pi = new PackageInfo(); 3919 pi.packageName = ps.name; 3920 pi.setLongVersionCode(ps.versionCode); 3921 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 3922 pi.firstInstallTime = ps.firstInstallTime; 3923 pi.lastUpdateTime = ps.lastUpdateTime; 3924 3925 ApplicationInfo ai = new ApplicationInfo(); 3926 ai.packageName = ps.name; 3927 ai.uid = UserHandle.getUid(userId, ps.appId); 3928 ai.primaryCpuAbi = ps.primaryCpuAbiString; 3929 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 3930 ai.versionCode = ps.versionCode; 3931 ai.flags = ps.pkgFlags; 3932 ai.privateFlags = ps.pkgPrivateFlags; 3933 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 3934 3935 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 3936 + ps.name + "]. Provides a minimum info."); 3937 return pi; 3938 } else { 3939 return null; 3940 } 3941 } 3942 3943 @Override 3944 public void checkPackageStartable(String packageName, int userId) { 3945 final int callingUid = Binder.getCallingUid(); 3946 if (getInstantAppPackageName(callingUid) != null) { 3947 throw new SecurityException("Instant applications don't have access to this method"); 3948 } 3949 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3950 synchronized (mPackages) { 3951 final PackageSetting ps = mSettings.mPackages.get(packageName); 3952 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3953 throw new SecurityException("Package " + packageName + " was not found!"); 3954 } 3955 3956 if (!ps.getInstalled(userId)) { 3957 throw new SecurityException( 3958 "Package " + packageName + " was not installed for user " + userId + "!"); 3959 } 3960 3961 if (mSafeMode && !ps.isSystem()) { 3962 throw new SecurityException("Package " + packageName + " not a system app!"); 3963 } 3964 3965 if (mFrozenPackages.contains(packageName)) { 3966 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3967 } 3968 3969 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3970 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3971 } 3972 } 3973 } 3974 3975 @Override 3976 public boolean isPackageAvailable(String packageName, int userId) { 3977 if (!sUserManager.exists(userId)) return false; 3978 final int callingUid = Binder.getCallingUid(); 3979 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3980 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3981 synchronized (mPackages) { 3982 PackageParser.Package p = mPackages.get(packageName); 3983 if (p != null) { 3984 final PackageSetting ps = (PackageSetting) p.mExtras; 3985 if (filterAppAccessLPr(ps, callingUid, userId)) { 3986 return false; 3987 } 3988 if (ps != null) { 3989 final PackageUserState state = ps.readUserState(userId); 3990 if (state != null) { 3991 return PackageParser.isAvailable(state); 3992 } 3993 } 3994 } 3995 } 3996 return false; 3997 } 3998 3999 @Override 4000 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 4001 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4002 flags, Binder.getCallingUid(), userId); 4003 } 4004 4005 @Override 4006 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4007 int flags, int userId) { 4008 return getPackageInfoInternal(versionedPackage.getPackageName(), 4009 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4010 } 4011 4012 /** 4013 * Important: The provided filterCallingUid is used exclusively to filter out packages 4014 * that can be seen based on user state. It's typically the original caller uid prior 4015 * to clearing. Because it can only be provided by trusted code, it's value can be 4016 * trusted and will be used as-is; unlike userId which will be validated by this method. 4017 */ 4018 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4019 int flags, int filterCallingUid, int userId) { 4020 if (!sUserManager.exists(userId)) return null; 4021 flags = updateFlagsForPackage(flags, userId, packageName); 4022 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4023 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4024 4025 // reader 4026 synchronized (mPackages) { 4027 // Normalize package name to handle renamed packages and static libs 4028 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4029 4030 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4031 if (matchFactoryOnly) { 4032 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4033 if (ps != null) { 4034 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4035 return null; 4036 } 4037 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4038 return null; 4039 } 4040 return generatePackageInfo(ps, flags, userId); 4041 } 4042 } 4043 4044 PackageParser.Package p = mPackages.get(packageName); 4045 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4046 return null; 4047 } 4048 if (DEBUG_PACKAGE_INFO) 4049 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4050 if (p != null) { 4051 final PackageSetting ps = (PackageSetting) p.mExtras; 4052 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4053 return null; 4054 } 4055 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4056 return null; 4057 } 4058 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4059 } 4060 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4061 final PackageSetting ps = mSettings.mPackages.get(packageName); 4062 if (ps == null) return null; 4063 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4064 return null; 4065 } 4066 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4067 return null; 4068 } 4069 return generatePackageInfo(ps, flags, userId); 4070 } 4071 } 4072 return null; 4073 } 4074 4075 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4076 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4077 return true; 4078 } 4079 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4080 return true; 4081 } 4082 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4083 return true; 4084 } 4085 return false; 4086 } 4087 4088 private boolean isComponentVisibleToInstantApp( 4089 @Nullable ComponentName component, @ComponentType int type) { 4090 if (type == TYPE_ACTIVITY) { 4091 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4092 if (activity == null) { 4093 return false; 4094 } 4095 final boolean visibleToInstantApp = 4096 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4097 final boolean explicitlyVisibleToInstantApp = 4098 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4099 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4100 } else if (type == TYPE_RECEIVER) { 4101 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4102 if (activity == null) { 4103 return false; 4104 } 4105 final boolean visibleToInstantApp = 4106 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4107 final boolean explicitlyVisibleToInstantApp = 4108 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4109 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4110 } else if (type == TYPE_SERVICE) { 4111 final PackageParser.Service service = mServices.mServices.get(component); 4112 return service != null 4113 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4114 : false; 4115 } else if (type == TYPE_PROVIDER) { 4116 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4117 return provider != null 4118 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4119 : false; 4120 } else if (type == TYPE_UNKNOWN) { 4121 return isComponentVisibleToInstantApp(component); 4122 } 4123 return false; 4124 } 4125 4126 /** 4127 * Returns whether or not access to the application should be filtered. 4128 * <p> 4129 * Access may be limited based upon whether the calling or target applications 4130 * are instant applications. 4131 * 4132 * @see #canAccessInstantApps(int) 4133 */ 4134 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4135 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4136 // if we're in an isolated process, get the real calling UID 4137 if (Process.isIsolated(callingUid)) { 4138 callingUid = mIsolatedOwners.get(callingUid); 4139 } 4140 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4141 final boolean callerIsInstantApp = instantAppPkgName != null; 4142 if (ps == null) { 4143 if (callerIsInstantApp) { 4144 // pretend the application exists, but, needs to be filtered 4145 return true; 4146 } 4147 return false; 4148 } 4149 // if the target and caller are the same application, don't filter 4150 if (isCallerSameApp(ps.name, callingUid)) { 4151 return false; 4152 } 4153 if (callerIsInstantApp) { 4154 // both caller and target are both instant, but, different applications, filter 4155 if (ps.getInstantApp(userId)) { 4156 return true; 4157 } 4158 // request for a specific component; if it hasn't been explicitly exposed through 4159 // property or instrumentation target, filter 4160 if (component != null) { 4161 final PackageParser.Instrumentation instrumentation = 4162 mInstrumentation.get(component); 4163 if (instrumentation != null 4164 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4165 return false; 4166 } 4167 return !isComponentVisibleToInstantApp(component, componentType); 4168 } 4169 // request for application; if no components have been explicitly exposed, filter 4170 return !ps.pkg.visibleToInstantApps; 4171 } 4172 if (ps.getInstantApp(userId)) { 4173 // caller can see all components of all instant applications, don't filter 4174 if (canViewInstantApps(callingUid, userId)) { 4175 return false; 4176 } 4177 // request for a specific instant application component, filter 4178 if (component != null) { 4179 return true; 4180 } 4181 // request for an instant application; if the caller hasn't been granted access, filter 4182 return !mInstantAppRegistry.isInstantAccessGranted( 4183 userId, UserHandle.getAppId(callingUid), ps.appId); 4184 } 4185 return false; 4186 } 4187 4188 /** 4189 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4190 */ 4191 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4192 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4193 } 4194 4195 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4196 int flags) { 4197 // Callers can access only the libs they depend on, otherwise they need to explicitly 4198 // ask for the shared libraries given the caller is allowed to access all static libs. 4199 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4200 // System/shell/root get to see all static libs 4201 final int appId = UserHandle.getAppId(uid); 4202 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4203 || appId == Process.ROOT_UID) { 4204 return false; 4205 } 4206 } 4207 4208 // No package means no static lib as it is always on internal storage 4209 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4210 return false; 4211 } 4212 4213 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4214 ps.pkg.staticSharedLibVersion); 4215 if (libEntry == null) { 4216 return false; 4217 } 4218 4219 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4220 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4221 if (uidPackageNames == null) { 4222 return true; 4223 } 4224 4225 for (String uidPackageName : uidPackageNames) { 4226 if (ps.name.equals(uidPackageName)) { 4227 return false; 4228 } 4229 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4230 if (uidPs != null) { 4231 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4232 libEntry.info.getName()); 4233 if (index < 0) { 4234 continue; 4235 } 4236 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4237 return false; 4238 } 4239 } 4240 } 4241 return true; 4242 } 4243 4244 @Override 4245 public String[] currentToCanonicalPackageNames(String[] names) { 4246 final int callingUid = Binder.getCallingUid(); 4247 if (getInstantAppPackageName(callingUid) != null) { 4248 return names; 4249 } 4250 final String[] out = new String[names.length]; 4251 // reader 4252 synchronized (mPackages) { 4253 final int callingUserId = UserHandle.getUserId(callingUid); 4254 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4255 for (int i=names.length-1; i>=0; i--) { 4256 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4257 boolean translateName = false; 4258 if (ps != null && ps.realName != null) { 4259 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4260 translateName = !targetIsInstantApp 4261 || canViewInstantApps 4262 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4263 UserHandle.getAppId(callingUid), ps.appId); 4264 } 4265 out[i] = translateName ? ps.realName : names[i]; 4266 } 4267 } 4268 return out; 4269 } 4270 4271 @Override 4272 public String[] canonicalToCurrentPackageNames(String[] names) { 4273 final int callingUid = Binder.getCallingUid(); 4274 if (getInstantAppPackageName(callingUid) != null) { 4275 return names; 4276 } 4277 final String[] out = new String[names.length]; 4278 // reader 4279 synchronized (mPackages) { 4280 final int callingUserId = UserHandle.getUserId(callingUid); 4281 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4282 for (int i=names.length-1; i>=0; i--) { 4283 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4284 boolean translateName = false; 4285 if (cur != null) { 4286 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4287 final boolean targetIsInstantApp = 4288 ps != null && ps.getInstantApp(callingUserId); 4289 translateName = !targetIsInstantApp 4290 || canViewInstantApps 4291 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4292 UserHandle.getAppId(callingUid), ps.appId); 4293 } 4294 out[i] = translateName ? cur : names[i]; 4295 } 4296 } 4297 return out; 4298 } 4299 4300 @Override 4301 public int getPackageUid(String packageName, int flags, int userId) { 4302 if (!sUserManager.exists(userId)) return -1; 4303 final int callingUid = Binder.getCallingUid(); 4304 flags = updateFlagsForPackage(flags, userId, packageName); 4305 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4306 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4307 4308 // reader 4309 synchronized (mPackages) { 4310 final PackageParser.Package p = mPackages.get(packageName); 4311 if (p != null && p.isMatch(flags)) { 4312 PackageSetting ps = (PackageSetting) p.mExtras; 4313 if (filterAppAccessLPr(ps, callingUid, userId)) { 4314 return -1; 4315 } 4316 return UserHandle.getUid(userId, p.applicationInfo.uid); 4317 } 4318 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4319 final PackageSetting ps = mSettings.mPackages.get(packageName); 4320 if (ps != null && ps.isMatch(flags) 4321 && !filterAppAccessLPr(ps, callingUid, userId)) { 4322 return UserHandle.getUid(userId, ps.appId); 4323 } 4324 } 4325 } 4326 4327 return -1; 4328 } 4329 4330 @Override 4331 public int[] getPackageGids(String packageName, int flags, int userId) { 4332 if (!sUserManager.exists(userId)) return null; 4333 final int callingUid = Binder.getCallingUid(); 4334 flags = updateFlagsForPackage(flags, userId, packageName); 4335 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4336 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4337 4338 // reader 4339 synchronized (mPackages) { 4340 final PackageParser.Package p = mPackages.get(packageName); 4341 if (p != null && p.isMatch(flags)) { 4342 PackageSetting ps = (PackageSetting) p.mExtras; 4343 if (filterAppAccessLPr(ps, callingUid, userId)) { 4344 return null; 4345 } 4346 // TODO: Shouldn't this be checking for package installed state for userId and 4347 // return null? 4348 return ps.getPermissionsState().computeGids(userId); 4349 } 4350 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4351 final PackageSetting ps = mSettings.mPackages.get(packageName); 4352 if (ps != null && ps.isMatch(flags) 4353 && !filterAppAccessLPr(ps, callingUid, userId)) { 4354 return ps.getPermissionsState().computeGids(userId); 4355 } 4356 } 4357 } 4358 4359 return null; 4360 } 4361 4362 @Override 4363 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4364 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4365 } 4366 4367 @Override 4368 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4369 int flags) { 4370 final List<PermissionInfo> permissionList = 4371 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4372 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4373 } 4374 4375 @Override 4376 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4377 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4378 } 4379 4380 @Override 4381 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4382 final List<PermissionGroupInfo> permissionList = 4383 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4384 return (permissionList == null) 4385 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4386 } 4387 4388 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4389 int filterCallingUid, int userId) { 4390 if (!sUserManager.exists(userId)) return null; 4391 PackageSetting ps = mSettings.mPackages.get(packageName); 4392 if (ps != null) { 4393 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4394 return null; 4395 } 4396 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4397 return null; 4398 } 4399 if (ps.pkg == null) { 4400 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4401 if (pInfo != null) { 4402 return pInfo.applicationInfo; 4403 } 4404 return null; 4405 } 4406 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4407 ps.readUserState(userId), userId); 4408 if (ai != null) { 4409 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4410 } 4411 return ai; 4412 } 4413 return null; 4414 } 4415 4416 @Override 4417 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4418 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4419 } 4420 4421 /** 4422 * Important: The provided filterCallingUid is used exclusively to filter out applications 4423 * that can be seen based on user state. It's typically the original caller uid prior 4424 * to clearing. Because it can only be provided by trusted code, it's value can be 4425 * trusted and will be used as-is; unlike userId which will be validated by this method. 4426 */ 4427 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4428 int filterCallingUid, int userId) { 4429 if (!sUserManager.exists(userId)) return null; 4430 flags = updateFlagsForApplication(flags, userId, packageName); 4431 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4432 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4433 4434 // writer 4435 synchronized (mPackages) { 4436 // Normalize package name to handle renamed packages and static libs 4437 packageName = resolveInternalPackageNameLPr(packageName, 4438 PackageManager.VERSION_CODE_HIGHEST); 4439 4440 PackageParser.Package p = mPackages.get(packageName); 4441 if (DEBUG_PACKAGE_INFO) Log.v( 4442 TAG, "getApplicationInfo " + packageName 4443 + ": " + p); 4444 if (p != null) { 4445 PackageSetting ps = mSettings.mPackages.get(packageName); 4446 if (ps == null) return null; 4447 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4448 return null; 4449 } 4450 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4451 return null; 4452 } 4453 // Note: isEnabledLP() does not apply here - always return info 4454 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4455 p, flags, ps.readUserState(userId), userId); 4456 if (ai != null) { 4457 ai.packageName = resolveExternalPackageNameLPr(p); 4458 } 4459 return ai; 4460 } 4461 if ("android".equals(packageName)||"system".equals(packageName)) { 4462 return mAndroidApplication; 4463 } 4464 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4465 // Already generates the external package name 4466 return generateApplicationInfoFromSettingsLPw(packageName, 4467 flags, filterCallingUid, userId); 4468 } 4469 } 4470 return null; 4471 } 4472 4473 private String normalizePackageNameLPr(String packageName) { 4474 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4475 return normalizedPackageName != null ? normalizedPackageName : packageName; 4476 } 4477 4478 @Override 4479 public void deletePreloadsFileCache() { 4480 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4481 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4482 } 4483 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4484 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4485 FileUtils.deleteContents(dir); 4486 } 4487 4488 @Override 4489 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4490 final int storageFlags, final IPackageDataObserver observer) { 4491 mContext.enforceCallingOrSelfPermission( 4492 android.Manifest.permission.CLEAR_APP_CACHE, null); 4493 mHandler.post(() -> { 4494 boolean success = false; 4495 try { 4496 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4497 success = true; 4498 } catch (IOException e) { 4499 Slog.w(TAG, e); 4500 } 4501 if (observer != null) { 4502 try { 4503 observer.onRemoveCompleted(null, success); 4504 } catch (RemoteException e) { 4505 Slog.w(TAG, e); 4506 } 4507 } 4508 }); 4509 } 4510 4511 @Override 4512 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4513 final int storageFlags, final IntentSender pi) { 4514 mContext.enforceCallingOrSelfPermission( 4515 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4516 mHandler.post(() -> { 4517 boolean success = false; 4518 try { 4519 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4520 success = true; 4521 } catch (IOException e) { 4522 Slog.w(TAG, e); 4523 } 4524 if (pi != null) { 4525 try { 4526 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4527 } catch (SendIntentException e) { 4528 Slog.w(TAG, e); 4529 } 4530 } 4531 }); 4532 } 4533 4534 /** 4535 * Blocking call to clear various types of cached data across the system 4536 * until the requested bytes are available. 4537 */ 4538 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4539 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4540 final File file = storage.findPathForUuid(volumeUuid); 4541 if (file.getUsableSpace() >= bytes) return; 4542 4543 if (ENABLE_FREE_CACHE_V2) { 4544 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4545 volumeUuid); 4546 final boolean aggressive = (storageFlags 4547 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4548 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4549 4550 // 1. Pre-flight to determine if we have any chance to succeed 4551 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4552 if (internalVolume && (aggressive || SystemProperties 4553 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4554 deletePreloadsFileCache(); 4555 if (file.getUsableSpace() >= bytes) return; 4556 } 4557 4558 // 3. Consider parsed APK data (aggressive only) 4559 if (internalVolume && aggressive) { 4560 FileUtils.deleteContents(mCacheDir); 4561 if (file.getUsableSpace() >= bytes) return; 4562 } 4563 4564 // 4. Consider cached app data (above quotas) 4565 try { 4566 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4567 Installer.FLAG_FREE_CACHE_V2); 4568 } catch (InstallerException ignored) { 4569 } 4570 if (file.getUsableSpace() >= bytes) return; 4571 4572 // 5. Consider shared libraries with refcount=0 and age>min cache period 4573 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4574 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4575 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4576 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4577 return; 4578 } 4579 4580 // 6. Consider dexopt output (aggressive only) 4581 // TODO: Implement 4582 4583 // 7. Consider installed instant apps unused longer than min cache period 4584 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4585 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4586 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4587 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4588 return; 4589 } 4590 4591 // 8. Consider cached app data (below quotas) 4592 try { 4593 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4594 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4595 } catch (InstallerException ignored) { 4596 } 4597 if (file.getUsableSpace() >= bytes) return; 4598 4599 // 9. Consider DropBox entries 4600 // TODO: Implement 4601 4602 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4603 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4604 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4605 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4606 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4607 return; 4608 } 4609 } else { 4610 try { 4611 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4612 } catch (InstallerException ignored) { 4613 } 4614 if (file.getUsableSpace() >= bytes) return; 4615 } 4616 4617 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4618 } 4619 4620 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4621 throws IOException { 4622 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4623 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4624 4625 List<VersionedPackage> packagesToDelete = null; 4626 final long now = System.currentTimeMillis(); 4627 4628 synchronized (mPackages) { 4629 final int[] allUsers = sUserManager.getUserIds(); 4630 final int libCount = mSharedLibraries.size(); 4631 for (int i = 0; i < libCount; i++) { 4632 final LongSparseArray<SharedLibraryEntry> versionedLib 4633 = mSharedLibraries.valueAt(i); 4634 if (versionedLib == null) { 4635 continue; 4636 } 4637 final int versionCount = versionedLib.size(); 4638 for (int j = 0; j < versionCount; j++) { 4639 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4640 // Skip packages that are not static shared libs. 4641 if (!libInfo.isStatic()) { 4642 break; 4643 } 4644 // Important: We skip static shared libs used for some user since 4645 // in such a case we need to keep the APK on the device. The check for 4646 // a lib being used for any user is performed by the uninstall call. 4647 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4648 // Resolve the package name - we use synthetic package names internally 4649 final String internalPackageName = resolveInternalPackageNameLPr( 4650 declaringPackage.getPackageName(), 4651 declaringPackage.getLongVersionCode()); 4652 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4653 // Skip unused static shared libs cached less than the min period 4654 // to prevent pruning a lib needed by a subsequently installed package. 4655 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4656 continue; 4657 } 4658 if (packagesToDelete == null) { 4659 packagesToDelete = new ArrayList<>(); 4660 } 4661 packagesToDelete.add(new VersionedPackage(internalPackageName, 4662 declaringPackage.getLongVersionCode())); 4663 } 4664 } 4665 } 4666 4667 if (packagesToDelete != null) { 4668 final int packageCount = packagesToDelete.size(); 4669 for (int i = 0; i < packageCount; i++) { 4670 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4671 // Delete the package synchronously (will fail of the lib used for any user). 4672 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4673 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4674 == PackageManager.DELETE_SUCCEEDED) { 4675 if (volume.getUsableSpace() >= neededSpace) { 4676 return true; 4677 } 4678 } 4679 } 4680 } 4681 4682 return false; 4683 } 4684 4685 /** 4686 * Update given flags based on encryption status of current user. 4687 */ 4688 private int updateFlags(int flags, int userId) { 4689 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4690 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4691 // Caller expressed an explicit opinion about what encryption 4692 // aware/unaware components they want to see, so fall through and 4693 // give them what they want 4694 } else { 4695 // Caller expressed no opinion, so match based on user state 4696 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4697 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4698 } else { 4699 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4700 } 4701 } 4702 return flags; 4703 } 4704 4705 private UserManagerInternal getUserManagerInternal() { 4706 if (mUserManagerInternal == null) { 4707 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4708 } 4709 return mUserManagerInternal; 4710 } 4711 4712 private ActivityManagerInternal getActivityManagerInternal() { 4713 if (mActivityManagerInternal == null) { 4714 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4715 } 4716 return mActivityManagerInternal; 4717 } 4718 4719 4720 private DeviceIdleController.LocalService getDeviceIdleController() { 4721 if (mDeviceIdleController == null) { 4722 mDeviceIdleController = 4723 LocalServices.getService(DeviceIdleController.LocalService.class); 4724 } 4725 return mDeviceIdleController; 4726 } 4727 4728 /** 4729 * Update given flags when being used to request {@link PackageInfo}. 4730 */ 4731 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4732 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4733 boolean triaged = true; 4734 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4735 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4736 // Caller is asking for component details, so they'd better be 4737 // asking for specific encryption matching behavior, or be triaged 4738 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4739 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4740 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4741 triaged = false; 4742 } 4743 } 4744 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4745 | PackageManager.MATCH_SYSTEM_ONLY 4746 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4747 triaged = false; 4748 } 4749 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4750 mPermissionManager.enforceCrossUserPermission( 4751 Binder.getCallingUid(), userId, false, false, 4752 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4753 + Debug.getCallers(5)); 4754 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4755 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4756 // If the caller wants all packages and has a restricted profile associated with it, 4757 // then match all users. This is to make sure that launchers that need to access work 4758 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4759 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4760 flags |= PackageManager.MATCH_ANY_USER; 4761 } 4762 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4763 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4764 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4765 } 4766 return updateFlags(flags, userId); 4767 } 4768 4769 /** 4770 * Update given flags when being used to request {@link ApplicationInfo}. 4771 */ 4772 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4773 return updateFlagsForPackage(flags, userId, cookie); 4774 } 4775 4776 /** 4777 * Update given flags when being used to request {@link ComponentInfo}. 4778 */ 4779 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4780 if (cookie instanceof Intent) { 4781 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4782 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4783 } 4784 } 4785 4786 boolean triaged = true; 4787 // Caller is asking for component details, so they'd better be 4788 // asking for specific encryption matching behavior, or be triaged 4789 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4790 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4791 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4792 triaged = false; 4793 } 4794 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4795 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4796 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4797 } 4798 4799 return updateFlags(flags, userId); 4800 } 4801 4802 /** 4803 * Update given intent when being used to request {@link ResolveInfo}. 4804 */ 4805 private Intent updateIntentForResolve(Intent intent) { 4806 if (intent.getSelector() != null) { 4807 intent = intent.getSelector(); 4808 } 4809 if (DEBUG_PREFERRED) { 4810 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4811 } 4812 return intent; 4813 } 4814 4815 /** 4816 * Update given flags when being used to request {@link ResolveInfo}. 4817 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4818 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4819 * flag set. However, this flag is only honoured in three circumstances: 4820 * <ul> 4821 * <li>when called from a system process</li> 4822 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4823 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4824 * action and a {@code android.intent.category.BROWSABLE} category</li> 4825 * </ul> 4826 */ 4827 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4828 return updateFlagsForResolve(flags, userId, intent, callingUid, 4829 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4830 } 4831 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4832 boolean wantInstantApps) { 4833 return updateFlagsForResolve(flags, userId, intent, callingUid, 4834 wantInstantApps, false /*onlyExposedExplicitly*/); 4835 } 4836 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4837 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4838 // Safe mode means we shouldn't match any third-party components 4839 if (mSafeMode) { 4840 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4841 } 4842 if (getInstantAppPackageName(callingUid) != null) { 4843 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4844 if (onlyExposedExplicitly) { 4845 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4846 } 4847 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4848 flags |= PackageManager.MATCH_INSTANT; 4849 } else { 4850 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4851 final boolean allowMatchInstant = wantInstantApps 4852 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4853 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4854 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4855 if (!allowMatchInstant) { 4856 flags &= ~PackageManager.MATCH_INSTANT; 4857 } 4858 } 4859 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4860 } 4861 4862 @Override 4863 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4864 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4865 } 4866 4867 /** 4868 * Important: The provided filterCallingUid is used exclusively to filter out activities 4869 * that can be seen based on user state. It's typically the original caller uid prior 4870 * to clearing. Because it can only be provided by trusted code, it's value can be 4871 * trusted and will be used as-is; unlike userId which will be validated by this method. 4872 */ 4873 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4874 int filterCallingUid, int userId) { 4875 if (!sUserManager.exists(userId)) return null; 4876 flags = updateFlagsForComponent(flags, userId, component); 4877 4878 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4879 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4880 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4881 } 4882 4883 synchronized (mPackages) { 4884 PackageParser.Activity a = mActivities.mActivities.get(component); 4885 4886 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4887 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4888 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4889 if (ps == null) return null; 4890 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4891 return null; 4892 } 4893 return PackageParser.generateActivityInfo( 4894 a, flags, ps.readUserState(userId), userId); 4895 } 4896 if (mResolveComponentName.equals(component)) { 4897 return PackageParser.generateActivityInfo( 4898 mResolveActivity, flags, new PackageUserState(), userId); 4899 } 4900 } 4901 return null; 4902 } 4903 4904 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4905 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4906 return false; 4907 } 4908 final long token = Binder.clearCallingIdentity(); 4909 try { 4910 final int callingUserId = UserHandle.getUserId(callingUid); 4911 if (ActivityManager.getCurrentUser() != callingUserId) { 4912 return false; 4913 } 4914 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4915 } finally { 4916 Binder.restoreCallingIdentity(token); 4917 } 4918 } 4919 4920 @Override 4921 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4922 String resolvedType) { 4923 synchronized (mPackages) { 4924 if (component.equals(mResolveComponentName)) { 4925 // The resolver supports EVERYTHING! 4926 return true; 4927 } 4928 final int callingUid = Binder.getCallingUid(); 4929 final int callingUserId = UserHandle.getUserId(callingUid); 4930 PackageParser.Activity a = mActivities.mActivities.get(component); 4931 if (a == null) { 4932 return false; 4933 } 4934 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4935 if (ps == null) { 4936 return false; 4937 } 4938 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4939 return false; 4940 } 4941 for (int i=0; i<a.intents.size(); i++) { 4942 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4943 intent.getData(), intent.getCategories(), TAG) >= 0) { 4944 return true; 4945 } 4946 } 4947 return false; 4948 } 4949 } 4950 4951 @Override 4952 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4953 if (!sUserManager.exists(userId)) return null; 4954 final int callingUid = Binder.getCallingUid(); 4955 flags = updateFlagsForComponent(flags, userId, component); 4956 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4957 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4958 synchronized (mPackages) { 4959 PackageParser.Activity a = mReceivers.mActivities.get(component); 4960 if (DEBUG_PACKAGE_INFO) Log.v( 4961 TAG, "getReceiverInfo " + component + ": " + a); 4962 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4963 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4964 if (ps == null) return null; 4965 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4966 return null; 4967 } 4968 return PackageParser.generateActivityInfo( 4969 a, flags, ps.readUserState(userId), userId); 4970 } 4971 } 4972 return null; 4973 } 4974 4975 @Override 4976 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4977 int flags, int userId) { 4978 if (!sUserManager.exists(userId)) return null; 4979 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4980 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4981 return null; 4982 } 4983 4984 flags = updateFlagsForPackage(flags, userId, null); 4985 4986 final boolean canSeeStaticLibraries = 4987 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4988 == PERMISSION_GRANTED 4989 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4990 == PERMISSION_GRANTED 4991 || canRequestPackageInstallsInternal(packageName, 4992 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4993 false /* throwIfPermNotDeclared*/) 4994 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4995 == PERMISSION_GRANTED; 4996 4997 synchronized (mPackages) { 4998 List<SharedLibraryInfo> result = null; 4999 5000 final int libCount = mSharedLibraries.size(); 5001 for (int i = 0; i < libCount; i++) { 5002 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5003 if (versionedLib == null) { 5004 continue; 5005 } 5006 5007 final int versionCount = versionedLib.size(); 5008 for (int j = 0; j < versionCount; j++) { 5009 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 5010 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5011 break; 5012 } 5013 final long identity = Binder.clearCallingIdentity(); 5014 try { 5015 PackageInfo packageInfo = getPackageInfoVersioned( 5016 libInfo.getDeclaringPackage(), flags 5017 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5018 if (packageInfo == null) { 5019 continue; 5020 } 5021 } finally { 5022 Binder.restoreCallingIdentity(identity); 5023 } 5024 5025 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 5026 libInfo.getLongVersion(), libInfo.getType(), 5027 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 5028 flags, userId)); 5029 5030 if (result == null) { 5031 result = new ArrayList<>(); 5032 } 5033 result.add(resLibInfo); 5034 } 5035 } 5036 5037 return result != null ? new ParceledListSlice<>(result) : null; 5038 } 5039 } 5040 5041 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5042 SharedLibraryInfo libInfo, int flags, int userId) { 5043 List<VersionedPackage> versionedPackages = null; 5044 final int packageCount = mSettings.mPackages.size(); 5045 for (int i = 0; i < packageCount; i++) { 5046 PackageSetting ps = mSettings.mPackages.valueAt(i); 5047 5048 if (ps == null) { 5049 continue; 5050 } 5051 5052 if (!ps.getUserState().get(userId).isAvailable(flags)) { 5053 continue; 5054 } 5055 5056 final String libName = libInfo.getName(); 5057 if (libInfo.isStatic()) { 5058 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5059 if (libIdx < 0) { 5060 continue; 5061 } 5062 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5063 continue; 5064 } 5065 if (versionedPackages == null) { 5066 versionedPackages = new ArrayList<>(); 5067 } 5068 // If the dependent is a static shared lib, use the public package name 5069 String dependentPackageName = ps.name; 5070 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5071 dependentPackageName = ps.pkg.manifestPackageName; 5072 } 5073 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5074 } else if (ps.pkg != null) { 5075 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5076 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5077 if (versionedPackages == null) { 5078 versionedPackages = new ArrayList<>(); 5079 } 5080 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5081 } 5082 } 5083 } 5084 5085 return versionedPackages; 5086 } 5087 5088 @Override 5089 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5090 if (!sUserManager.exists(userId)) return null; 5091 final int callingUid = Binder.getCallingUid(); 5092 flags = updateFlagsForComponent(flags, userId, component); 5093 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5094 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5095 synchronized (mPackages) { 5096 PackageParser.Service s = mServices.mServices.get(component); 5097 if (DEBUG_PACKAGE_INFO) Log.v( 5098 TAG, "getServiceInfo " + component + ": " + s); 5099 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5100 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5101 if (ps == null) return null; 5102 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5103 return null; 5104 } 5105 return PackageParser.generateServiceInfo( 5106 s, flags, ps.readUserState(userId), userId); 5107 } 5108 } 5109 return null; 5110 } 5111 5112 @Override 5113 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5114 if (!sUserManager.exists(userId)) return null; 5115 final int callingUid = Binder.getCallingUid(); 5116 flags = updateFlagsForComponent(flags, userId, component); 5117 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5118 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5119 synchronized (mPackages) { 5120 PackageParser.Provider p = mProviders.mProviders.get(component); 5121 if (DEBUG_PACKAGE_INFO) Log.v( 5122 TAG, "getProviderInfo " + component + ": " + p); 5123 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5124 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5125 if (ps == null) return null; 5126 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5127 return null; 5128 } 5129 return PackageParser.generateProviderInfo( 5130 p, flags, ps.readUserState(userId), userId); 5131 } 5132 } 5133 return null; 5134 } 5135 5136 @Override 5137 public String[] getSystemSharedLibraryNames() { 5138 // allow instant applications 5139 synchronized (mPackages) { 5140 Set<String> libs = null; 5141 final int libCount = mSharedLibraries.size(); 5142 for (int i = 0; i < libCount; i++) { 5143 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5144 if (versionedLib == null) { 5145 continue; 5146 } 5147 final int versionCount = versionedLib.size(); 5148 for (int j = 0; j < versionCount; j++) { 5149 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5150 if (!libEntry.info.isStatic()) { 5151 if (libs == null) { 5152 libs = new ArraySet<>(); 5153 } 5154 libs.add(libEntry.info.getName()); 5155 break; 5156 } 5157 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5158 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5159 UserHandle.getUserId(Binder.getCallingUid()), 5160 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5161 if (libs == null) { 5162 libs = new ArraySet<>(); 5163 } 5164 libs.add(libEntry.info.getName()); 5165 break; 5166 } 5167 } 5168 } 5169 5170 if (libs != null) { 5171 String[] libsArray = new String[libs.size()]; 5172 libs.toArray(libsArray); 5173 return libsArray; 5174 } 5175 5176 return null; 5177 } 5178 } 5179 5180 @Override 5181 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5182 // allow instant applications 5183 synchronized (mPackages) { 5184 return mServicesSystemSharedLibraryPackageName; 5185 } 5186 } 5187 5188 @Override 5189 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5190 // allow instant applications 5191 synchronized (mPackages) { 5192 return mSharedSystemSharedLibraryPackageName; 5193 } 5194 } 5195 5196 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5197 for (int i = userList.length - 1; i >= 0; --i) { 5198 final int userId = userList[i]; 5199 // don't add instant app to the list of updates 5200 if (pkgSetting.getInstantApp(userId)) { 5201 continue; 5202 } 5203 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5204 if (changedPackages == null) { 5205 changedPackages = new SparseArray<>(); 5206 mChangedPackages.put(userId, changedPackages); 5207 } 5208 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5209 if (sequenceNumbers == null) { 5210 sequenceNumbers = new HashMap<>(); 5211 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5212 } 5213 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5214 if (sequenceNumber != null) { 5215 changedPackages.remove(sequenceNumber); 5216 } 5217 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5218 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5219 } 5220 mChangedPackagesSequenceNumber++; 5221 } 5222 5223 @Override 5224 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5225 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5226 return null; 5227 } 5228 synchronized (mPackages) { 5229 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5230 return null; 5231 } 5232 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5233 if (changedPackages == null) { 5234 return null; 5235 } 5236 final List<String> packageNames = 5237 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5238 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5239 final String packageName = changedPackages.get(i); 5240 if (packageName != null) { 5241 packageNames.add(packageName); 5242 } 5243 } 5244 return packageNames.isEmpty() 5245 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5246 } 5247 } 5248 5249 @Override 5250 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5251 // allow instant applications 5252 ArrayList<FeatureInfo> res; 5253 synchronized (mAvailableFeatures) { 5254 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5255 res.addAll(mAvailableFeatures.values()); 5256 } 5257 final FeatureInfo fi = new FeatureInfo(); 5258 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5259 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5260 res.add(fi); 5261 5262 return new ParceledListSlice<>(res); 5263 } 5264 5265 @Override 5266 public boolean hasSystemFeature(String name, int version) { 5267 // allow instant applications 5268 synchronized (mAvailableFeatures) { 5269 final FeatureInfo feat = mAvailableFeatures.get(name); 5270 if (feat == null) { 5271 return false; 5272 } else { 5273 return feat.version >= version; 5274 } 5275 } 5276 } 5277 5278 @Override 5279 public int checkPermission(String permName, String pkgName, int userId) { 5280 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5281 } 5282 5283 @Override 5284 public int checkUidPermission(String permName, int uid) { 5285 synchronized (mPackages) { 5286 final String[] packageNames = getPackagesForUid(uid); 5287 final PackageParser.Package pkg = (packageNames != null && packageNames.length > 0) 5288 ? mPackages.get(packageNames[0]) 5289 : null; 5290 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5291 } 5292 } 5293 5294 @Override 5295 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5296 if (UserHandle.getCallingUserId() != userId) { 5297 mContext.enforceCallingPermission( 5298 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5299 "isPermissionRevokedByPolicy for user " + userId); 5300 } 5301 5302 if (checkPermission(permission, packageName, userId) 5303 == PackageManager.PERMISSION_GRANTED) { 5304 return false; 5305 } 5306 5307 final int callingUid = Binder.getCallingUid(); 5308 if (getInstantAppPackageName(callingUid) != null) { 5309 if (!isCallerSameApp(packageName, callingUid)) { 5310 return false; 5311 } 5312 } else { 5313 if (isInstantApp(packageName, userId)) { 5314 return false; 5315 } 5316 } 5317 5318 final long identity = Binder.clearCallingIdentity(); 5319 try { 5320 final int flags = getPermissionFlags(permission, packageName, userId); 5321 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5322 } finally { 5323 Binder.restoreCallingIdentity(identity); 5324 } 5325 } 5326 5327 @Override 5328 public String getPermissionControllerPackageName() { 5329 synchronized (mPackages) { 5330 return mRequiredInstallerPackage; 5331 } 5332 } 5333 5334 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5335 return mPermissionManager.addDynamicPermission( 5336 info, async, getCallingUid(), new PermissionCallback() { 5337 @Override 5338 public void onPermissionChanged() { 5339 if (!async) { 5340 mSettings.writeLPr(); 5341 } else { 5342 scheduleWriteSettingsLocked(); 5343 } 5344 } 5345 }); 5346 } 5347 5348 @Override 5349 public boolean addPermission(PermissionInfo info) { 5350 synchronized (mPackages) { 5351 return addDynamicPermission(info, false); 5352 } 5353 } 5354 5355 @Override 5356 public boolean addPermissionAsync(PermissionInfo info) { 5357 synchronized (mPackages) { 5358 return addDynamicPermission(info, true); 5359 } 5360 } 5361 5362 @Override 5363 public void removePermission(String permName) { 5364 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5365 } 5366 5367 @Override 5368 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5369 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5370 getCallingUid(), userId, mPermissionCallback); 5371 } 5372 5373 @Override 5374 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5375 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5376 getCallingUid(), userId, mPermissionCallback); 5377 } 5378 5379 @Override 5380 public void resetRuntimePermissions() { 5381 mContext.enforceCallingOrSelfPermission( 5382 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5383 "revokeRuntimePermission"); 5384 5385 int callingUid = Binder.getCallingUid(); 5386 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5387 mContext.enforceCallingOrSelfPermission( 5388 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5389 "resetRuntimePermissions"); 5390 } 5391 5392 synchronized (mPackages) { 5393 mPermissionManager.updateAllPermissions( 5394 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5395 mPermissionCallback); 5396 for (int userId : UserManagerService.getInstance().getUserIds()) { 5397 final int packageCount = mPackages.size(); 5398 for (int i = 0; i < packageCount; i++) { 5399 PackageParser.Package pkg = mPackages.valueAt(i); 5400 if (!(pkg.mExtras instanceof PackageSetting)) { 5401 continue; 5402 } 5403 PackageSetting ps = (PackageSetting) pkg.mExtras; 5404 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5405 } 5406 } 5407 } 5408 } 5409 5410 @Override 5411 public int getPermissionFlags(String permName, String packageName, int userId) { 5412 return mPermissionManager.getPermissionFlags( 5413 permName, packageName, getCallingUid(), userId); 5414 } 5415 5416 @Override 5417 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5418 int flagValues, int userId) { 5419 mPermissionManager.updatePermissionFlags( 5420 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5421 mPermissionCallback); 5422 } 5423 5424 /** 5425 * Update the permission flags for all packages and runtime permissions of a user in order 5426 * to allow device or profile owner to remove POLICY_FIXED. 5427 */ 5428 @Override 5429 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5430 synchronized (mPackages) { 5431 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5432 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5433 mPermissionCallback); 5434 if (changed) { 5435 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5436 } 5437 } 5438 } 5439 5440 @Override 5441 public boolean shouldShowRequestPermissionRationale(String permissionName, 5442 String packageName, int userId) { 5443 if (UserHandle.getCallingUserId() != userId) { 5444 mContext.enforceCallingPermission( 5445 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5446 "canShowRequestPermissionRationale for user " + userId); 5447 } 5448 5449 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5450 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5451 return false; 5452 } 5453 5454 if (checkPermission(permissionName, packageName, userId) 5455 == PackageManager.PERMISSION_GRANTED) { 5456 return false; 5457 } 5458 5459 final int flags; 5460 5461 final long identity = Binder.clearCallingIdentity(); 5462 try { 5463 flags = getPermissionFlags(permissionName, 5464 packageName, userId); 5465 } finally { 5466 Binder.restoreCallingIdentity(identity); 5467 } 5468 5469 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5470 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5471 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5472 5473 if ((flags & fixedFlags) != 0) { 5474 return false; 5475 } 5476 5477 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5478 } 5479 5480 @Override 5481 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5482 mContext.enforceCallingOrSelfPermission( 5483 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5484 "addOnPermissionsChangeListener"); 5485 5486 synchronized (mPackages) { 5487 mOnPermissionChangeListeners.addListenerLocked(listener); 5488 } 5489 } 5490 5491 @Override 5492 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5493 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5494 throw new SecurityException("Instant applications don't have access to this method"); 5495 } 5496 synchronized (mPackages) { 5497 mOnPermissionChangeListeners.removeListenerLocked(listener); 5498 } 5499 } 5500 5501 @Override 5502 public boolean isProtectedBroadcast(String actionName) { 5503 // allow instant applications 5504 synchronized (mProtectedBroadcasts) { 5505 if (mProtectedBroadcasts.contains(actionName)) { 5506 return true; 5507 } else if (actionName != null) { 5508 // TODO: remove these terrible hacks 5509 if (actionName.startsWith("android.net.netmon.lingerExpired") 5510 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5511 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5512 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5513 return true; 5514 } 5515 } 5516 } 5517 return false; 5518 } 5519 5520 @Override 5521 public int checkSignatures(String pkg1, String pkg2) { 5522 synchronized (mPackages) { 5523 final PackageParser.Package p1 = mPackages.get(pkg1); 5524 final PackageParser.Package p2 = mPackages.get(pkg2); 5525 if (p1 == null || p1.mExtras == null 5526 || p2 == null || p2.mExtras == null) { 5527 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5528 } 5529 final int callingUid = Binder.getCallingUid(); 5530 final int callingUserId = UserHandle.getUserId(callingUid); 5531 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5532 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5533 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5534 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5535 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5536 } 5537 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5538 } 5539 } 5540 5541 @Override 5542 public int checkUidSignatures(int uid1, int uid2) { 5543 final int callingUid = Binder.getCallingUid(); 5544 final int callingUserId = UserHandle.getUserId(callingUid); 5545 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5546 // Map to base uids. 5547 uid1 = UserHandle.getAppId(uid1); 5548 uid2 = UserHandle.getAppId(uid2); 5549 // reader 5550 synchronized (mPackages) { 5551 Signature[] s1; 5552 Signature[] s2; 5553 Object obj = mSettings.getUserIdLPr(uid1); 5554 if (obj != null) { 5555 if (obj instanceof SharedUserSetting) { 5556 if (isCallerInstantApp) { 5557 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5558 } 5559 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5560 } else if (obj instanceof PackageSetting) { 5561 final PackageSetting ps = (PackageSetting) obj; 5562 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5563 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5564 } 5565 s1 = ps.signatures.mSigningDetails.signatures; 5566 } else { 5567 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5568 } 5569 } else { 5570 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5571 } 5572 obj = mSettings.getUserIdLPr(uid2); 5573 if (obj != null) { 5574 if (obj instanceof SharedUserSetting) { 5575 if (isCallerInstantApp) { 5576 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5577 } 5578 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5579 } else if (obj instanceof PackageSetting) { 5580 final PackageSetting ps = (PackageSetting) obj; 5581 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5582 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5583 } 5584 s2 = ps.signatures.mSigningDetails.signatures; 5585 } else { 5586 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5587 } 5588 } else { 5589 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5590 } 5591 return compareSignatures(s1, s2); 5592 } 5593 } 5594 5595 @Override 5596 public boolean hasSigningCertificate( 5597 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5598 5599 synchronized (mPackages) { 5600 final PackageParser.Package p = mPackages.get(packageName); 5601 if (p == null || p.mExtras == null) { 5602 return false; 5603 } 5604 final int callingUid = Binder.getCallingUid(); 5605 final int callingUserId = UserHandle.getUserId(callingUid); 5606 final PackageSetting ps = (PackageSetting) p.mExtras; 5607 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5608 return false; 5609 } 5610 switch (type) { 5611 case CERT_INPUT_RAW_X509: 5612 return p.mSigningDetails.hasCertificate(certificate); 5613 case CERT_INPUT_SHA256: 5614 return p.mSigningDetails.hasSha256Certificate(certificate); 5615 default: 5616 return false; 5617 } 5618 } 5619 } 5620 5621 @Override 5622 public boolean hasUidSigningCertificate( 5623 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5624 final int callingUid = Binder.getCallingUid(); 5625 final int callingUserId = UserHandle.getUserId(callingUid); 5626 // Map to base uids. 5627 uid = UserHandle.getAppId(uid); 5628 // reader 5629 synchronized (mPackages) { 5630 final PackageParser.SigningDetails signingDetails; 5631 final Object obj = mSettings.getUserIdLPr(uid); 5632 if (obj != null) { 5633 if (obj instanceof SharedUserSetting) { 5634 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5635 if (isCallerInstantApp) { 5636 return false; 5637 } 5638 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5639 } else if (obj instanceof PackageSetting) { 5640 final PackageSetting ps = (PackageSetting) obj; 5641 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5642 return false; 5643 } 5644 signingDetails = ps.signatures.mSigningDetails; 5645 } else { 5646 return false; 5647 } 5648 } else { 5649 return false; 5650 } 5651 switch (type) { 5652 case CERT_INPUT_RAW_X509: 5653 return signingDetails.hasCertificate(certificate); 5654 case CERT_INPUT_SHA256: 5655 return signingDetails.hasSha256Certificate(certificate); 5656 default: 5657 return false; 5658 } 5659 } 5660 } 5661 5662 /** 5663 * This method should typically only be used when granting or revoking 5664 * permissions, since the app may immediately restart after this call. 5665 * <p> 5666 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5667 * guard your work against the app being relaunched. 5668 */ 5669 private void killUid(int appId, int userId, String reason) { 5670 final long identity = Binder.clearCallingIdentity(); 5671 try { 5672 IActivityManager am = ActivityManager.getService(); 5673 if (am != null) { 5674 try { 5675 am.killUid(appId, userId, reason); 5676 } catch (RemoteException e) { 5677 /* ignore - same process */ 5678 } 5679 } 5680 } finally { 5681 Binder.restoreCallingIdentity(identity); 5682 } 5683 } 5684 5685 /** 5686 * If the database version for this type of package (internal storage or 5687 * external storage) is less than the version where package signatures 5688 * were updated, return true. 5689 */ 5690 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5691 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5692 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5693 } 5694 5695 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5696 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5697 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5698 } 5699 5700 @Override 5701 public List<String> getAllPackages() { 5702 final int callingUid = Binder.getCallingUid(); 5703 final int callingUserId = UserHandle.getUserId(callingUid); 5704 synchronized (mPackages) { 5705 if (canViewInstantApps(callingUid, callingUserId)) { 5706 return new ArrayList<String>(mPackages.keySet()); 5707 } 5708 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5709 final List<String> result = new ArrayList<>(); 5710 if (instantAppPkgName != null) { 5711 // caller is an instant application; filter unexposed applications 5712 for (PackageParser.Package pkg : mPackages.values()) { 5713 if (!pkg.visibleToInstantApps) { 5714 continue; 5715 } 5716 result.add(pkg.packageName); 5717 } 5718 } else { 5719 // caller is a normal application; filter instant applications 5720 for (PackageParser.Package pkg : mPackages.values()) { 5721 final PackageSetting ps = 5722 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5723 if (ps != null 5724 && ps.getInstantApp(callingUserId) 5725 && !mInstantAppRegistry.isInstantAccessGranted( 5726 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5727 continue; 5728 } 5729 result.add(pkg.packageName); 5730 } 5731 } 5732 return result; 5733 } 5734 } 5735 5736 @Override 5737 public String[] getPackagesForUid(int uid) { 5738 final int callingUid = Binder.getCallingUid(); 5739 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5740 final int userId = UserHandle.getUserId(uid); 5741 uid = UserHandle.getAppId(uid); 5742 // reader 5743 synchronized (mPackages) { 5744 Object obj = mSettings.getUserIdLPr(uid); 5745 if (obj instanceof SharedUserSetting) { 5746 if (isCallerInstantApp) { 5747 return null; 5748 } 5749 final SharedUserSetting sus = (SharedUserSetting) obj; 5750 final int N = sus.packages.size(); 5751 String[] res = new String[N]; 5752 final Iterator<PackageSetting> it = sus.packages.iterator(); 5753 int i = 0; 5754 while (it.hasNext()) { 5755 PackageSetting ps = it.next(); 5756 if (ps.getInstalled(userId)) { 5757 res[i++] = ps.name; 5758 } else { 5759 res = ArrayUtils.removeElement(String.class, res, res[i]); 5760 } 5761 } 5762 return res; 5763 } else if (obj instanceof PackageSetting) { 5764 final PackageSetting ps = (PackageSetting) obj; 5765 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5766 return new String[]{ps.name}; 5767 } 5768 } 5769 } 5770 return null; 5771 } 5772 5773 @Override 5774 public String getNameForUid(int uid) { 5775 final int callingUid = Binder.getCallingUid(); 5776 if (getInstantAppPackageName(callingUid) != null) { 5777 return null; 5778 } 5779 synchronized (mPackages) { 5780 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5781 if (obj instanceof SharedUserSetting) { 5782 final SharedUserSetting sus = (SharedUserSetting) obj; 5783 return sus.name + ":" + sus.userId; 5784 } else if (obj instanceof PackageSetting) { 5785 final PackageSetting ps = (PackageSetting) obj; 5786 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5787 return null; 5788 } 5789 return ps.name; 5790 } 5791 return null; 5792 } 5793 } 5794 5795 @Override 5796 public String[] getNamesForUids(int[] uids) { 5797 if (uids == null || uids.length == 0) { 5798 return null; 5799 } 5800 final int callingUid = Binder.getCallingUid(); 5801 if (getInstantAppPackageName(callingUid) != null) { 5802 return null; 5803 } 5804 final String[] names = new String[uids.length]; 5805 synchronized (mPackages) { 5806 for (int i = uids.length - 1; i >= 0; i--) { 5807 final int uid = uids[i]; 5808 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5809 if (obj instanceof SharedUserSetting) { 5810 final SharedUserSetting sus = (SharedUserSetting) obj; 5811 names[i] = "shared:" + sus.name; 5812 } else if (obj instanceof PackageSetting) { 5813 final PackageSetting ps = (PackageSetting) obj; 5814 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5815 names[i] = null; 5816 } else { 5817 names[i] = ps.name; 5818 } 5819 } else { 5820 names[i] = null; 5821 } 5822 } 5823 } 5824 return names; 5825 } 5826 5827 @Override 5828 public int getUidForSharedUser(String sharedUserName) { 5829 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5830 return -1; 5831 } 5832 if (sharedUserName == null) { 5833 return -1; 5834 } 5835 // reader 5836 synchronized (mPackages) { 5837 SharedUserSetting suid; 5838 try { 5839 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5840 if (suid != null) { 5841 return suid.userId; 5842 } 5843 } catch (PackageManagerException ignore) { 5844 // can't happen, but, still need to catch it 5845 } 5846 return -1; 5847 } 5848 } 5849 5850 @Override 5851 public int getFlagsForUid(int uid) { 5852 final int callingUid = Binder.getCallingUid(); 5853 if (getInstantAppPackageName(callingUid) != null) { 5854 return 0; 5855 } 5856 synchronized (mPackages) { 5857 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5858 if (obj instanceof SharedUserSetting) { 5859 final SharedUserSetting sus = (SharedUserSetting) obj; 5860 return sus.pkgFlags; 5861 } else if (obj instanceof PackageSetting) { 5862 final PackageSetting ps = (PackageSetting) obj; 5863 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5864 return 0; 5865 } 5866 return ps.pkgFlags; 5867 } 5868 } 5869 return 0; 5870 } 5871 5872 @Override 5873 public int getPrivateFlagsForUid(int uid) { 5874 final int callingUid = Binder.getCallingUid(); 5875 if (getInstantAppPackageName(callingUid) != null) { 5876 return 0; 5877 } 5878 synchronized (mPackages) { 5879 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5880 if (obj instanceof SharedUserSetting) { 5881 final SharedUserSetting sus = (SharedUserSetting) obj; 5882 return sus.pkgPrivateFlags; 5883 } else if (obj instanceof PackageSetting) { 5884 final PackageSetting ps = (PackageSetting) obj; 5885 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5886 return 0; 5887 } 5888 return ps.pkgPrivateFlags; 5889 } 5890 } 5891 return 0; 5892 } 5893 5894 @Override 5895 public boolean isUidPrivileged(int uid) { 5896 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5897 return false; 5898 } 5899 uid = UserHandle.getAppId(uid); 5900 // reader 5901 synchronized (mPackages) { 5902 Object obj = mSettings.getUserIdLPr(uid); 5903 if (obj instanceof SharedUserSetting) { 5904 final SharedUserSetting sus = (SharedUserSetting) obj; 5905 final Iterator<PackageSetting> it = sus.packages.iterator(); 5906 while (it.hasNext()) { 5907 if (it.next().isPrivileged()) { 5908 return true; 5909 } 5910 } 5911 } else if (obj instanceof PackageSetting) { 5912 final PackageSetting ps = (PackageSetting) obj; 5913 return ps.isPrivileged(); 5914 } 5915 } 5916 return false; 5917 } 5918 5919 @Override 5920 public String[] getAppOpPermissionPackages(String permName) { 5921 return mPermissionManager.getAppOpPermissionPackages(permName); 5922 } 5923 5924 @Override 5925 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5926 int flags, int userId) { 5927 return resolveIntentInternal( 5928 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5929 } 5930 5931 /** 5932 * Normally instant apps can only be resolved when they're visible to the caller. 5933 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5934 * since we need to allow the system to start any installed application. 5935 */ 5936 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5937 int flags, int userId, boolean resolveForStart) { 5938 try { 5939 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5940 5941 if (!sUserManager.exists(userId)) return null; 5942 final int callingUid = Binder.getCallingUid(); 5943 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5944 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5945 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5946 5947 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5948 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5949 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5951 5952 final ResolveInfo bestChoice = 5953 chooseBestActivity(intent, resolvedType, flags, query, userId); 5954 return bestChoice; 5955 } finally { 5956 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5957 } 5958 } 5959 5960 @Override 5961 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5962 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5963 throw new SecurityException( 5964 "findPersistentPreferredActivity can only be run by the system"); 5965 } 5966 if (!sUserManager.exists(userId)) { 5967 return null; 5968 } 5969 final int callingUid = Binder.getCallingUid(); 5970 intent = updateIntentForResolve(intent); 5971 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5972 final int flags = updateFlagsForResolve( 5973 0, userId, intent, callingUid, false /*includeInstantApps*/); 5974 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5975 userId); 5976 synchronized (mPackages) { 5977 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5978 userId); 5979 } 5980 } 5981 5982 @Override 5983 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5984 IntentFilter filter, int match, ComponentName activity) { 5985 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5986 return; 5987 } 5988 final int userId = UserHandle.getCallingUserId(); 5989 if (DEBUG_PREFERRED) { 5990 Log.v(TAG, "setLastChosenActivity intent=" + intent 5991 + " resolvedType=" + resolvedType 5992 + " flags=" + flags 5993 + " filter=" + filter 5994 + " match=" + match 5995 + " activity=" + activity); 5996 filter.dump(new PrintStreamPrinter(System.out), " "); 5997 } 5998 intent.setComponent(null); 5999 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6000 userId); 6001 // Find any earlier preferred or last chosen entries and nuke them 6002 findPreferredActivity(intent, resolvedType, 6003 flags, query, 0, false, true, false, userId); 6004 // Add the new activity as the last chosen for this filter 6005 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6006 "Setting last chosen"); 6007 } 6008 6009 @Override 6010 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6011 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6012 return null; 6013 } 6014 final int userId = UserHandle.getCallingUserId(); 6015 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6016 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6017 userId); 6018 return findPreferredActivity(intent, resolvedType, flags, query, 0, 6019 false, false, false, userId); 6020 } 6021 6022 /** 6023 * Returns whether or not instant apps have been disabled remotely. 6024 */ 6025 private boolean areWebInstantAppsDisabled() { 6026 return mWebInstantAppsDisabled; 6027 } 6028 6029 private boolean isInstantAppResolutionAllowed( 6030 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6031 boolean skipPackageCheck) { 6032 if (mInstantAppResolverConnection == null) { 6033 return false; 6034 } 6035 if (mInstantAppInstallerActivity == null) { 6036 return false; 6037 } 6038 if (intent.getComponent() != null) { 6039 return false; 6040 } 6041 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6042 return false; 6043 } 6044 if (!skipPackageCheck && intent.getPackage() != null) { 6045 return false; 6046 } 6047 if (!intent.isWebIntent()) { 6048 // for non web intents, we should not resolve externally if an app already exists to 6049 // handle it or if the caller didn't explicitly request it. 6050 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6051 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6052 return false; 6053 } 6054 } else { 6055 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6056 return false; 6057 } else if (areWebInstantAppsDisabled()) { 6058 return false; 6059 } 6060 } 6061 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6062 // Or if there's already an ephemeral app installed that handles the action 6063 synchronized (mPackages) { 6064 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6065 for (int n = 0; n < count; n++) { 6066 final ResolveInfo info = resolvedActivities.get(n); 6067 final String packageName = info.activityInfo.packageName; 6068 final PackageSetting ps = mSettings.mPackages.get(packageName); 6069 if (ps != null) { 6070 // only check domain verification status if the app is not a browser 6071 if (!info.handleAllWebDataURI) { 6072 // Try to get the status from User settings first 6073 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6074 final int status = (int) (packedStatus >> 32); 6075 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6076 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6077 if (DEBUG_INSTANT) { 6078 Slog.v(TAG, "DENY instant app;" 6079 + " pkg: " + packageName + ", status: " + status); 6080 } 6081 return false; 6082 } 6083 } 6084 if (ps.getInstantApp(userId)) { 6085 if (DEBUG_INSTANT) { 6086 Slog.v(TAG, "DENY instant app installed;" 6087 + " pkg: " + packageName); 6088 } 6089 return false; 6090 } 6091 } 6092 } 6093 } 6094 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6095 return true; 6096 } 6097 6098 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6099 Intent origIntent, String resolvedType, String callingPackage, 6100 Bundle verificationBundle, int userId) { 6101 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6102 new InstantAppRequest(responseObj, origIntent, resolvedType, 6103 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6104 mHandler.sendMessage(msg); 6105 } 6106 6107 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6108 int flags, List<ResolveInfo> query, int userId) { 6109 if (query != null) { 6110 final int N = query.size(); 6111 if (N == 1) { 6112 return query.get(0); 6113 } else if (N > 1) { 6114 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6115 // If there is more than one activity with the same priority, 6116 // then let the user decide between them. 6117 ResolveInfo r0 = query.get(0); 6118 ResolveInfo r1 = query.get(1); 6119 if (DEBUG_INTENT_MATCHING || debug) { 6120 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6121 + r1.activityInfo.name + "=" + r1.priority); 6122 } 6123 // If the first activity has a higher priority, or a different 6124 // default, then it is always desirable to pick it. 6125 if (r0.priority != r1.priority 6126 || r0.preferredOrder != r1.preferredOrder 6127 || r0.isDefault != r1.isDefault) { 6128 return query.get(0); 6129 } 6130 // If we have saved a preference for a preferred activity for 6131 // this Intent, use that. 6132 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6133 flags, query, r0.priority, true, false, debug, userId); 6134 if (ri != null) { 6135 return ri; 6136 } 6137 // If we have an ephemeral app, use it 6138 for (int i = 0; i < N; i++) { 6139 ri = query.get(i); 6140 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6141 final String packageName = ri.activityInfo.packageName; 6142 final PackageSetting ps = mSettings.mPackages.get(packageName); 6143 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6144 final int status = (int)(packedStatus >> 32); 6145 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6146 return ri; 6147 } 6148 } 6149 } 6150 ri = new ResolveInfo(mResolveInfo); 6151 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6152 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6153 // If all of the options come from the same package, show the application's 6154 // label and icon instead of the generic resolver's. 6155 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6156 // and then throw away the ResolveInfo itself, meaning that the caller loses 6157 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6158 // a fallback for this case; we only set the target package's resources on 6159 // the ResolveInfo, not the ActivityInfo. 6160 final String intentPackage = intent.getPackage(); 6161 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6162 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6163 ri.resolvePackageName = intentPackage; 6164 if (userNeedsBadging(userId)) { 6165 ri.noResourceId = true; 6166 } else { 6167 ri.icon = appi.icon; 6168 } 6169 ri.iconResourceId = appi.icon; 6170 ri.labelRes = appi.labelRes; 6171 } 6172 ri.activityInfo.applicationInfo = new ApplicationInfo( 6173 ri.activityInfo.applicationInfo); 6174 if (userId != 0) { 6175 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6176 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6177 } 6178 // Make sure that the resolver is displayable in car mode 6179 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6180 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6181 return ri; 6182 } 6183 } 6184 return null; 6185 } 6186 6187 /** 6188 * Return true if the given list is not empty and all of its contents have 6189 * an activityInfo with the given package name. 6190 */ 6191 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6192 if (ArrayUtils.isEmpty(list)) { 6193 return false; 6194 } 6195 for (int i = 0, N = list.size(); i < N; i++) { 6196 final ResolveInfo ri = list.get(i); 6197 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6198 if (ai == null || !packageName.equals(ai.packageName)) { 6199 return false; 6200 } 6201 } 6202 return true; 6203 } 6204 6205 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6206 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6207 final int N = query.size(); 6208 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6209 .get(userId); 6210 // Get the list of persistent preferred activities that handle the intent 6211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6212 List<PersistentPreferredActivity> pprefs = ppir != null 6213 ? ppir.queryIntent(intent, resolvedType, 6214 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6215 userId) 6216 : null; 6217 if (pprefs != null && pprefs.size() > 0) { 6218 final int M = pprefs.size(); 6219 for (int i=0; i<M; i++) { 6220 final PersistentPreferredActivity ppa = pprefs.get(i); 6221 if (DEBUG_PREFERRED || debug) { 6222 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6223 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6224 + "\n component=" + ppa.mComponent); 6225 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6226 } 6227 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6228 flags | MATCH_DISABLED_COMPONENTS, userId); 6229 if (DEBUG_PREFERRED || debug) { 6230 Slog.v(TAG, "Found persistent preferred activity:"); 6231 if (ai != null) { 6232 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6233 } else { 6234 Slog.v(TAG, " null"); 6235 } 6236 } 6237 if (ai == null) { 6238 // This previously registered persistent preferred activity 6239 // component is no longer known. Ignore it and do NOT remove it. 6240 continue; 6241 } 6242 for (int j=0; j<N; j++) { 6243 final ResolveInfo ri = query.get(j); 6244 if (!ri.activityInfo.applicationInfo.packageName 6245 .equals(ai.applicationInfo.packageName)) { 6246 continue; 6247 } 6248 if (!ri.activityInfo.name.equals(ai.name)) { 6249 continue; 6250 } 6251 // Found a persistent preference that can handle the intent. 6252 if (DEBUG_PREFERRED || debug) { 6253 Slog.v(TAG, "Returning persistent preferred activity: " + 6254 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6255 } 6256 return ri; 6257 } 6258 } 6259 } 6260 return null; 6261 } 6262 6263 // TODO: handle preferred activities missing while user has amnesia 6264 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6265 List<ResolveInfo> query, int priority, boolean always, 6266 boolean removeMatches, boolean debug, int userId) { 6267 if (!sUserManager.exists(userId)) return null; 6268 final int callingUid = Binder.getCallingUid(); 6269 flags = updateFlagsForResolve( 6270 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6271 intent = updateIntentForResolve(intent); 6272 // writer 6273 synchronized (mPackages) { 6274 // Try to find a matching persistent preferred activity. 6275 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6276 debug, userId); 6277 6278 // If a persistent preferred activity matched, use it. 6279 if (pri != null) { 6280 return pri; 6281 } 6282 6283 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6284 // Get the list of preferred activities that handle the intent 6285 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6286 List<PreferredActivity> prefs = pir != null 6287 ? pir.queryIntent(intent, resolvedType, 6288 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6289 userId) 6290 : null; 6291 if (prefs != null && prefs.size() > 0) { 6292 boolean changed = false; 6293 try { 6294 // First figure out how good the original match set is. 6295 // We will only allow preferred activities that came 6296 // from the same match quality. 6297 int match = 0; 6298 6299 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6300 6301 final int N = query.size(); 6302 for (int j=0; j<N; j++) { 6303 final ResolveInfo ri = query.get(j); 6304 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6305 + ": 0x" + Integer.toHexString(match)); 6306 if (ri.match > match) { 6307 match = ri.match; 6308 } 6309 } 6310 6311 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6312 + Integer.toHexString(match)); 6313 6314 match &= IntentFilter.MATCH_CATEGORY_MASK; 6315 final int M = prefs.size(); 6316 for (int i=0; i<M; i++) { 6317 final PreferredActivity pa = prefs.get(i); 6318 if (DEBUG_PREFERRED || debug) { 6319 Slog.v(TAG, "Checking PreferredActivity ds=" 6320 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6321 + "\n component=" + pa.mPref.mComponent); 6322 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6323 } 6324 if (pa.mPref.mMatch != match) { 6325 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6326 + Integer.toHexString(pa.mPref.mMatch)); 6327 continue; 6328 } 6329 // If it's not an "always" type preferred activity and that's what we're 6330 // looking for, skip it. 6331 if (always && !pa.mPref.mAlways) { 6332 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6333 continue; 6334 } 6335 final ActivityInfo ai = getActivityInfo( 6336 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6337 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6338 userId); 6339 if (DEBUG_PREFERRED || debug) { 6340 Slog.v(TAG, "Found preferred activity:"); 6341 if (ai != null) { 6342 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6343 } else { 6344 Slog.v(TAG, " null"); 6345 } 6346 } 6347 if (ai == null) { 6348 // This previously registered preferred activity 6349 // component is no longer known. Most likely an update 6350 // to the app was installed and in the new version this 6351 // component no longer exists. Clean it up by removing 6352 // it from the preferred activities list, and skip it. 6353 Slog.w(TAG, "Removing dangling preferred activity: " 6354 + pa.mPref.mComponent); 6355 pir.removeFilter(pa); 6356 changed = true; 6357 continue; 6358 } 6359 for (int j=0; j<N; j++) { 6360 final ResolveInfo ri = query.get(j); 6361 if (!ri.activityInfo.applicationInfo.packageName 6362 .equals(ai.applicationInfo.packageName)) { 6363 continue; 6364 } 6365 if (!ri.activityInfo.name.equals(ai.name)) { 6366 continue; 6367 } 6368 6369 if (removeMatches) { 6370 pir.removeFilter(pa); 6371 changed = true; 6372 if (DEBUG_PREFERRED) { 6373 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6374 } 6375 break; 6376 } 6377 6378 // Okay we found a previously set preferred or last chosen app. 6379 // If the result set is different from when this 6380 // was created, and is not a subset of the preferred set, we need to 6381 // clear it and re-ask the user their preference, if we're looking for 6382 // an "always" type entry. 6383 if (always && !pa.mPref.sameSet(query)) { 6384 if (pa.mPref.isSuperset(query)) { 6385 // some components of the set are no longer present in 6386 // the query, but the preferred activity can still be reused 6387 if (DEBUG_PREFERRED) { 6388 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6389 + " still valid as only non-preferred components" 6390 + " were removed for " + intent + " type " 6391 + resolvedType); 6392 } 6393 // remove obsolete components and re-add the up-to-date filter 6394 PreferredActivity freshPa = new PreferredActivity(pa, 6395 pa.mPref.mMatch, 6396 pa.mPref.discardObsoleteComponents(query), 6397 pa.mPref.mComponent, 6398 pa.mPref.mAlways); 6399 pir.removeFilter(pa); 6400 pir.addFilter(freshPa); 6401 changed = true; 6402 } else { 6403 Slog.i(TAG, 6404 "Result set changed, dropping preferred activity for " 6405 + intent + " type " + resolvedType); 6406 if (DEBUG_PREFERRED) { 6407 Slog.v(TAG, "Removing preferred activity since set changed " 6408 + pa.mPref.mComponent); 6409 } 6410 pir.removeFilter(pa); 6411 // Re-add the filter as a "last chosen" entry (!always) 6412 PreferredActivity lastChosen = new PreferredActivity( 6413 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6414 pir.addFilter(lastChosen); 6415 changed = true; 6416 return null; 6417 } 6418 } 6419 6420 // Yay! Either the set matched or we're looking for the last chosen 6421 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6422 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6423 return ri; 6424 } 6425 } 6426 } finally { 6427 if (changed) { 6428 if (DEBUG_PREFERRED) { 6429 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6430 } 6431 scheduleWritePackageRestrictionsLocked(userId); 6432 } 6433 } 6434 } 6435 } 6436 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6437 return null; 6438 } 6439 6440 /* 6441 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6442 */ 6443 @Override 6444 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6445 int targetUserId) { 6446 mContext.enforceCallingOrSelfPermission( 6447 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6448 List<CrossProfileIntentFilter> matches = 6449 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6450 if (matches != null) { 6451 int size = matches.size(); 6452 for (int i = 0; i < size; i++) { 6453 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6454 } 6455 } 6456 if (intent.hasWebURI()) { 6457 // cross-profile app linking works only towards the parent. 6458 final int callingUid = Binder.getCallingUid(); 6459 final UserInfo parent = getProfileParent(sourceUserId); 6460 synchronized(mPackages) { 6461 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6462 false /*includeInstantApps*/); 6463 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6464 intent, resolvedType, flags, sourceUserId, parent.id); 6465 return xpDomainInfo != null; 6466 } 6467 } 6468 return false; 6469 } 6470 6471 private UserInfo getProfileParent(int userId) { 6472 final long identity = Binder.clearCallingIdentity(); 6473 try { 6474 return sUserManager.getProfileParent(userId); 6475 } finally { 6476 Binder.restoreCallingIdentity(identity); 6477 } 6478 } 6479 6480 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6481 String resolvedType, int userId) { 6482 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6483 if (resolver != null) { 6484 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6485 } 6486 return null; 6487 } 6488 6489 @Override 6490 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6491 String resolvedType, int flags, int userId) { 6492 try { 6493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6494 6495 return new ParceledListSlice<>( 6496 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6497 } finally { 6498 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6499 } 6500 } 6501 6502 /** 6503 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6504 * instant, returns {@code null}. 6505 */ 6506 private String getInstantAppPackageName(int callingUid) { 6507 synchronized (mPackages) { 6508 // If the caller is an isolated app use the owner's uid for the lookup. 6509 if (Process.isIsolated(callingUid)) { 6510 callingUid = mIsolatedOwners.get(callingUid); 6511 } 6512 final int appId = UserHandle.getAppId(callingUid); 6513 final Object obj = mSettings.getUserIdLPr(appId); 6514 if (obj instanceof PackageSetting) { 6515 final PackageSetting ps = (PackageSetting) obj; 6516 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6517 return isInstantApp ? ps.pkg.packageName : null; 6518 } 6519 } 6520 return null; 6521 } 6522 6523 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6524 String resolvedType, int flags, int userId) { 6525 return queryIntentActivitiesInternal( 6526 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6527 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6528 } 6529 6530 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6531 String resolvedType, int flags, int filterCallingUid, int userId, 6532 boolean resolveForStart, boolean allowDynamicSplits) { 6533 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6534 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6535 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6536 false /* requireFullPermission */, false /* checkShell */, 6537 "query intent activities"); 6538 final String pkgName = intent.getPackage(); 6539 ComponentName comp = intent.getComponent(); 6540 if (comp == null) { 6541 if (intent.getSelector() != null) { 6542 intent = intent.getSelector(); 6543 comp = intent.getComponent(); 6544 } 6545 } 6546 6547 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6548 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6549 if (comp != null) { 6550 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6551 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6552 if (ai != null) { 6553 // When specifying an explicit component, we prevent the activity from being 6554 // used when either 1) the calling package is normal and the activity is within 6555 // an ephemeral application or 2) the calling package is ephemeral and the 6556 // activity is not visible to ephemeral applications. 6557 final boolean matchInstantApp = 6558 (flags & PackageManager.MATCH_INSTANT) != 0; 6559 final boolean matchVisibleToInstantAppOnly = 6560 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6561 final boolean matchExplicitlyVisibleOnly = 6562 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6563 final boolean isCallerInstantApp = 6564 instantAppPkgName != null; 6565 final boolean isTargetSameInstantApp = 6566 comp.getPackageName().equals(instantAppPkgName); 6567 final boolean isTargetInstantApp = 6568 (ai.applicationInfo.privateFlags 6569 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6570 final boolean isTargetVisibleToInstantApp = 6571 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6572 final boolean isTargetExplicitlyVisibleToInstantApp = 6573 isTargetVisibleToInstantApp 6574 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6575 final boolean isTargetHiddenFromInstantApp = 6576 !isTargetVisibleToInstantApp 6577 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6578 final boolean blockResolution = 6579 !isTargetSameInstantApp 6580 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6581 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6582 && isTargetHiddenFromInstantApp)); 6583 if (!blockResolution) { 6584 final ResolveInfo ri = new ResolveInfo(); 6585 ri.activityInfo = ai; 6586 list.add(ri); 6587 } 6588 } 6589 return applyPostResolutionFilter( 6590 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6591 } 6592 6593 // reader 6594 boolean sortResult = false; 6595 boolean addInstant = false; 6596 List<ResolveInfo> result; 6597 synchronized (mPackages) { 6598 if (pkgName == null) { 6599 List<CrossProfileIntentFilter> matchingFilters = 6600 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6601 // Check for results that need to skip the current profile. 6602 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6603 resolvedType, flags, userId); 6604 if (xpResolveInfo != null) { 6605 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6606 xpResult.add(xpResolveInfo); 6607 return applyPostResolutionFilter( 6608 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6609 allowDynamicSplits, filterCallingUid, userId, intent); 6610 } 6611 6612 // Check for results in the current profile. 6613 result = filterIfNotSystemUser(mActivities.queryIntent( 6614 intent, resolvedType, flags, userId), userId); 6615 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 6616 false /*skipPackageCheck*/); 6617 // Check for cross profile results. 6618 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6619 xpResolveInfo = queryCrossProfileIntents( 6620 matchingFilters, intent, resolvedType, flags, userId, 6621 hasNonNegativePriorityResult); 6622 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6623 boolean isVisibleToUser = filterIfNotSystemUser( 6624 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6625 if (isVisibleToUser) { 6626 result.add(xpResolveInfo); 6627 sortResult = true; 6628 } 6629 } 6630 if (intent.hasWebURI()) { 6631 CrossProfileDomainInfo xpDomainInfo = null; 6632 final UserInfo parent = getProfileParent(userId); 6633 if (parent != null) { 6634 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6635 flags, userId, parent.id); 6636 } 6637 if (xpDomainInfo != null) { 6638 if (xpResolveInfo != null) { 6639 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6640 // in the result. 6641 result.remove(xpResolveInfo); 6642 } 6643 if (result.size() == 0 && !addInstant) { 6644 // No result in current profile, but found candidate in parent user. 6645 // And we are not going to add emphemeral app, so we can return the 6646 // result straight away. 6647 result.add(xpDomainInfo.resolveInfo); 6648 return applyPostResolutionFilter(result, instantAppPkgName, 6649 allowDynamicSplits, filterCallingUid, userId, intent); 6650 } 6651 } else if (result.size() <= 1 && !addInstant) { 6652 // No result in parent user and <= 1 result in current profile, and we 6653 // are not going to add emphemeral app, so we can return the result without 6654 // further processing. 6655 return applyPostResolutionFilter(result, instantAppPkgName, 6656 allowDynamicSplits, filterCallingUid, userId, intent); 6657 } 6658 // We have more than one candidate (combining results from current and parent 6659 // profile), so we need filtering and sorting. 6660 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6661 intent, flags, result, xpDomainInfo, userId); 6662 sortResult = true; 6663 } 6664 } else { 6665 final PackageParser.Package pkg = mPackages.get(pkgName); 6666 result = null; 6667 if (pkg != null) { 6668 result = filterIfNotSystemUser( 6669 mActivities.queryIntentForPackage( 6670 intent, resolvedType, flags, pkg.activities, userId), 6671 userId); 6672 } 6673 if (result == null || result.size() == 0) { 6674 // the caller wants to resolve for a particular package; however, there 6675 // were no installed results, so, try to find an ephemeral result 6676 addInstant = isInstantAppResolutionAllowed( 6677 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6678 if (result == null) { 6679 result = new ArrayList<>(); 6680 } 6681 } 6682 } 6683 } 6684 if (addInstant) { 6685 result = maybeAddInstantAppInstaller( 6686 result, intent, resolvedType, flags, userId, resolveForStart); 6687 } 6688 if (sortResult) { 6689 Collections.sort(result, mResolvePrioritySorter); 6690 } 6691 return applyPostResolutionFilter( 6692 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId, intent); 6693 } 6694 6695 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6696 String resolvedType, int flags, int userId, boolean resolveForStart) { 6697 // first, check to see if we've got an instant app already installed 6698 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6699 ResolveInfo localInstantApp = null; 6700 boolean blockResolution = false; 6701 if (!alreadyResolvedLocally) { 6702 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6703 flags 6704 | PackageManager.GET_RESOLVED_FILTER 6705 | PackageManager.MATCH_INSTANT 6706 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6707 userId); 6708 for (int i = instantApps.size() - 1; i >= 0; --i) { 6709 final ResolveInfo info = instantApps.get(i); 6710 final String packageName = info.activityInfo.packageName; 6711 final PackageSetting ps = mSettings.mPackages.get(packageName); 6712 if (ps.getInstantApp(userId)) { 6713 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6714 final int status = (int)(packedStatus >> 32); 6715 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6716 // there's a local instant application installed, but, the user has 6717 // chosen to never use it; skip resolution and don't acknowledge 6718 // an instant application is even available 6719 if (DEBUG_INSTANT) { 6720 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6721 } 6722 blockResolution = true; 6723 break; 6724 } else { 6725 // we have a locally installed instant application; skip resolution 6726 // but acknowledge there's an instant application available 6727 if (DEBUG_INSTANT) { 6728 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6729 } 6730 localInstantApp = info; 6731 break; 6732 } 6733 } 6734 } 6735 } 6736 // no app installed, let's see if one's available 6737 AuxiliaryResolveInfo auxiliaryResponse = null; 6738 if (!blockResolution) { 6739 if (localInstantApp == null) { 6740 // we don't have an instant app locally, resolve externally 6741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6742 final InstantAppRequest requestObject = new InstantAppRequest( 6743 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6744 null /*callingPackage*/, userId, null /*verificationBundle*/, 6745 resolveForStart); 6746 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 6747 mInstantAppResolverConnection, requestObject); 6748 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6749 } else { 6750 // we have an instant application locally, but, we can't admit that since 6751 // callers shouldn't be able to determine prior browsing. create a dummy 6752 // auxiliary response so the downstream code behaves as if there's an 6753 // instant application available externally. when it comes time to start 6754 // the instant application, we'll do the right thing. 6755 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6756 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 6757 ai.packageName, ai.versionCode, null /* splitName */); 6758 } 6759 } 6760 if (intent.isWebIntent() && auxiliaryResponse == null) { 6761 return result; 6762 } 6763 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6764 if (ps == null 6765 || ps.getUserState().get(userId) == null 6766 || !ps.getUserState().get(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 6767 return result; 6768 } 6769 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6770 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6771 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6772 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6773 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6774 // add a non-generic filter 6775 ephemeralInstaller.filter = new IntentFilter(); 6776 if (intent.getAction() != null) { 6777 ephemeralInstaller.filter.addAction(intent.getAction()); 6778 } 6779 if (intent.getData() != null && intent.getData().getPath() != null) { 6780 ephemeralInstaller.filter.addDataPath( 6781 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6782 } 6783 ephemeralInstaller.isInstantAppAvailable = true; 6784 // make sure this resolver is the default 6785 ephemeralInstaller.isDefault = true; 6786 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6787 if (DEBUG_INSTANT) { 6788 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6789 } 6790 6791 result.add(ephemeralInstaller); 6792 return result; 6793 } 6794 6795 private static class CrossProfileDomainInfo { 6796 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6797 ResolveInfo resolveInfo; 6798 /* Best domain verification status of the activities found in the other profile */ 6799 int bestDomainVerificationStatus; 6800 } 6801 6802 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6803 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6804 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6805 sourceUserId)) { 6806 return null; 6807 } 6808 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6809 resolvedType, flags, parentUserId); 6810 6811 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6812 return null; 6813 } 6814 CrossProfileDomainInfo result = null; 6815 int size = resultTargetUser.size(); 6816 for (int i = 0; i < size; i++) { 6817 ResolveInfo riTargetUser = resultTargetUser.get(i); 6818 // Intent filter verification is only for filters that specify a host. So don't return 6819 // those that handle all web uris. 6820 if (riTargetUser.handleAllWebDataURI) { 6821 continue; 6822 } 6823 String packageName = riTargetUser.activityInfo.packageName; 6824 PackageSetting ps = mSettings.mPackages.get(packageName); 6825 if (ps == null) { 6826 continue; 6827 } 6828 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6829 int status = (int)(verificationState >> 32); 6830 if (result == null) { 6831 result = new CrossProfileDomainInfo(); 6832 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6833 sourceUserId, parentUserId); 6834 result.bestDomainVerificationStatus = status; 6835 } else { 6836 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6837 result.bestDomainVerificationStatus); 6838 } 6839 } 6840 // Don't consider matches with status NEVER across profiles. 6841 if (result != null && result.bestDomainVerificationStatus 6842 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6843 return null; 6844 } 6845 return result; 6846 } 6847 6848 /** 6849 * Verification statuses are ordered from the worse to the best, except for 6850 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6851 */ 6852 private int bestDomainVerificationStatus(int status1, int status2) { 6853 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6854 return status2; 6855 } 6856 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6857 return status1; 6858 } 6859 return (int) MathUtils.max(status1, status2); 6860 } 6861 6862 private boolean isUserEnabled(int userId) { 6863 long callingId = Binder.clearCallingIdentity(); 6864 try { 6865 UserInfo userInfo = sUserManager.getUserInfo(userId); 6866 return userInfo != null && userInfo.isEnabled(); 6867 } finally { 6868 Binder.restoreCallingIdentity(callingId); 6869 } 6870 } 6871 6872 /** 6873 * Filter out activities with systemUserOnly flag set, when current user is not System. 6874 * 6875 * @return filtered list 6876 */ 6877 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6878 if (userId == UserHandle.USER_SYSTEM) { 6879 return resolveInfos; 6880 } 6881 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6882 ResolveInfo info = resolveInfos.get(i); 6883 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6884 resolveInfos.remove(i); 6885 } 6886 } 6887 return resolveInfos; 6888 } 6889 6890 /** 6891 * Filters out ephemeral activities. 6892 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6893 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6894 * 6895 * @param resolveInfos The pre-filtered list of resolved activities 6896 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6897 * is performed. 6898 * @param intent 6899 * @return A filtered list of resolved activities. 6900 */ 6901 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6902 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId, 6903 Intent intent) { 6904 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(); 6905 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6906 final ResolveInfo info = resolveInfos.get(i); 6907 // remove locally resolved instant app web results when disabled 6908 if (info.isInstantAppAvailable && blockInstant) { 6909 resolveInfos.remove(i); 6910 continue; 6911 } 6912 // allow activities that are defined in the provided package 6913 if (allowDynamicSplits 6914 && info.activityInfo != null 6915 && info.activityInfo.splitName != null 6916 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6917 info.activityInfo.splitName)) { 6918 if (mInstantAppInstallerActivity == null) { 6919 if (DEBUG_INSTALL) { 6920 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6921 } 6922 resolveInfos.remove(i); 6923 continue; 6924 } 6925 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 6926 resolveInfos.remove(i); 6927 continue; 6928 } 6929 // requested activity is defined in a split that hasn't been installed yet. 6930 // add the installer to the resolve list 6931 if (DEBUG_INSTALL) { 6932 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6933 } 6934 final ResolveInfo installerInfo = new ResolveInfo( 6935 mInstantAppInstallerInfo); 6936 final ComponentName installFailureActivity = findInstallFailureActivity( 6937 info.activityInfo.packageName, filterCallingUid, userId); 6938 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6939 installFailureActivity, 6940 info.activityInfo.packageName, 6941 info.activityInfo.applicationInfo.versionCode, 6942 info.activityInfo.splitName); 6943 // add a non-generic filter 6944 installerInfo.filter = new IntentFilter(); 6945 6946 // This resolve info may appear in the chooser UI, so let us make it 6947 // look as the one it replaces as far as the user is concerned which 6948 // requires loading the correct label and icon for the resolve info. 6949 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6950 installerInfo.labelRes = info.resolveLabelResId(); 6951 installerInfo.icon = info.resolveIconResId(); 6952 installerInfo.isInstantAppAvailable = true; 6953 resolveInfos.set(i, installerInfo); 6954 continue; 6955 } 6956 // caller is a full app, don't need to apply any other filtering 6957 if (ephemeralPkgName == null) { 6958 continue; 6959 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6960 // caller is same app; don't need to apply any other filtering 6961 continue; 6962 } 6963 // allow activities that have been explicitly exposed to ephemeral apps 6964 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6965 if (!isEphemeralApp 6966 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6967 continue; 6968 } 6969 resolveInfos.remove(i); 6970 } 6971 return resolveInfos; 6972 } 6973 6974 /** 6975 * Returns the activity component that can handle install failures. 6976 * <p>By default, the instant application installer handles failures. However, an 6977 * application may want to handle failures on its own. Applications do this by 6978 * creating an activity with an intent filter that handles the action 6979 * {@link Intent#ACTION_INSTALL_FAILURE}. 6980 */ 6981 private @Nullable ComponentName findInstallFailureActivity( 6982 String packageName, int filterCallingUid, int userId) { 6983 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6984 failureActivityIntent.setPackage(packageName); 6985 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6986 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6987 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6988 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6989 final int NR = result.size(); 6990 if (NR > 0) { 6991 for (int i = 0; i < NR; i++) { 6992 final ResolveInfo info = result.get(i); 6993 if (info.activityInfo.splitName != null) { 6994 continue; 6995 } 6996 return new ComponentName(packageName, info.activityInfo.name); 6997 } 6998 } 6999 return null; 7000 } 7001 7002 /** 7003 * @param resolveInfos list of resolve infos in descending priority order 7004 * @return if the list contains a resolve info with non-negative priority 7005 */ 7006 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7007 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7008 } 7009 7010 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7011 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7012 int userId) { 7013 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7014 7015 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7016 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7017 candidates.size()); 7018 } 7019 7020 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 7021 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 7022 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 7023 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 7024 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 7025 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 7026 7027 synchronized (mPackages) { 7028 final int count = candidates.size(); 7029 // First, try to use linked apps. Partition the candidates into four lists: 7030 // one for the final results, one for the "do not use ever", one for "undefined status" 7031 // and finally one for "browser app type". 7032 for (int n=0; n<count; n++) { 7033 ResolveInfo info = candidates.get(n); 7034 String packageName = info.activityInfo.packageName; 7035 PackageSetting ps = mSettings.mPackages.get(packageName); 7036 if (ps != null) { 7037 // Add to the special match all list (Browser use case) 7038 if (info.handleAllWebDataURI) { 7039 matchAllList.add(info); 7040 continue; 7041 } 7042 // Try to get the status from User settings first 7043 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7044 int status = (int)(packedStatus >> 32); 7045 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7046 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7047 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7048 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7049 + " : linkgen=" + linkGeneration); 7050 } 7051 // Use link-enabled generation as preferredOrder, i.e. 7052 // prefer newly-enabled over earlier-enabled. 7053 info.preferredOrder = linkGeneration; 7054 alwaysList.add(info); 7055 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7056 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7057 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7058 } 7059 neverList.add(info); 7060 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7061 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7062 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7063 } 7064 alwaysAskList.add(info); 7065 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7066 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7067 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7068 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7069 } 7070 undefinedList.add(info); 7071 } 7072 } 7073 } 7074 7075 // We'll want to include browser possibilities in a few cases 7076 boolean includeBrowser = false; 7077 7078 // First try to add the "always" resolution(s) for the current user, if any 7079 if (alwaysList.size() > 0) { 7080 result.addAll(alwaysList); 7081 } else { 7082 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7083 result.addAll(undefinedList); 7084 // Maybe add one for the other profile. 7085 if (xpDomainInfo != null && ( 7086 xpDomainInfo.bestDomainVerificationStatus 7087 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7088 result.add(xpDomainInfo.resolveInfo); 7089 } 7090 includeBrowser = true; 7091 } 7092 7093 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7094 // If there were 'always' entries their preferred order has been set, so we also 7095 // back that off to make the alternatives equivalent 7096 if (alwaysAskList.size() > 0) { 7097 for (ResolveInfo i : result) { 7098 i.preferredOrder = 0; 7099 } 7100 result.addAll(alwaysAskList); 7101 includeBrowser = true; 7102 } 7103 7104 if (includeBrowser) { 7105 // Also add browsers (all of them or only the default one) 7106 if (DEBUG_DOMAIN_VERIFICATION) { 7107 Slog.v(TAG, " ...including browsers in candidate set"); 7108 } 7109 if ((matchFlags & MATCH_ALL) != 0) { 7110 result.addAll(matchAllList); 7111 } else { 7112 // Browser/generic handling case. If there's a default browser, go straight 7113 // to that (but only if there is no other higher-priority match). 7114 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7115 int maxMatchPrio = 0; 7116 ResolveInfo defaultBrowserMatch = null; 7117 final int numCandidates = matchAllList.size(); 7118 for (int n = 0; n < numCandidates; n++) { 7119 ResolveInfo info = matchAllList.get(n); 7120 // track the highest overall match priority... 7121 if (info.priority > maxMatchPrio) { 7122 maxMatchPrio = info.priority; 7123 } 7124 // ...and the highest-priority default browser match 7125 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7126 if (defaultBrowserMatch == null 7127 || (defaultBrowserMatch.priority < info.priority)) { 7128 if (debug) { 7129 Slog.v(TAG, "Considering default browser match " + info); 7130 } 7131 defaultBrowserMatch = info; 7132 } 7133 } 7134 } 7135 if (defaultBrowserMatch != null 7136 && defaultBrowserMatch.priority >= maxMatchPrio 7137 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7138 { 7139 if (debug) { 7140 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7141 } 7142 result.add(defaultBrowserMatch); 7143 } else { 7144 result.addAll(matchAllList); 7145 } 7146 } 7147 7148 // If there is nothing selected, add all candidates and remove the ones that the user 7149 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7150 if (result.size() == 0) { 7151 result.addAll(candidates); 7152 result.removeAll(neverList); 7153 } 7154 } 7155 } 7156 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7157 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7158 result.size()); 7159 for (ResolveInfo info : result) { 7160 Slog.v(TAG, " + " + info.activityInfo); 7161 } 7162 } 7163 return result; 7164 } 7165 7166 // Returns a packed value as a long: 7167 // 7168 // high 'int'-sized word: link status: undefined/ask/never/always. 7169 // low 'int'-sized word: relative priority among 'always' results. 7170 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7171 long result = ps.getDomainVerificationStatusForUser(userId); 7172 // if none available, get the master status 7173 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7174 if (ps.getIntentFilterVerificationInfo() != null) { 7175 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7176 } 7177 } 7178 return result; 7179 } 7180 7181 private ResolveInfo querySkipCurrentProfileIntents( 7182 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7183 int flags, int sourceUserId) { 7184 if (matchingFilters != null) { 7185 int size = matchingFilters.size(); 7186 for (int i = 0; i < size; i ++) { 7187 CrossProfileIntentFilter filter = matchingFilters.get(i); 7188 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7189 // Checking if there are activities in the target user that can handle the 7190 // intent. 7191 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7192 resolvedType, flags, sourceUserId); 7193 if (resolveInfo != null) { 7194 return resolveInfo; 7195 } 7196 } 7197 } 7198 } 7199 return null; 7200 } 7201 7202 // Return matching ResolveInfo in target user if any. 7203 private ResolveInfo queryCrossProfileIntents( 7204 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7205 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7206 if (matchingFilters != null) { 7207 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7208 // match the same intent. For performance reasons, it is better not to 7209 // run queryIntent twice for the same userId 7210 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7211 int size = matchingFilters.size(); 7212 for (int i = 0; i < size; i++) { 7213 CrossProfileIntentFilter filter = matchingFilters.get(i); 7214 int targetUserId = filter.getTargetUserId(); 7215 boolean skipCurrentProfile = 7216 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7217 boolean skipCurrentProfileIfNoMatchFound = 7218 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7219 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7220 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7221 // Checking if there are activities in the target user that can handle the 7222 // intent. 7223 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7224 resolvedType, flags, sourceUserId); 7225 if (resolveInfo != null) return resolveInfo; 7226 alreadyTriedUserIds.put(targetUserId, true); 7227 } 7228 } 7229 } 7230 return null; 7231 } 7232 7233 /** 7234 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7235 * will forward the intent to the filter's target user. 7236 * Otherwise, returns null. 7237 */ 7238 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7239 String resolvedType, int flags, int sourceUserId) { 7240 int targetUserId = filter.getTargetUserId(); 7241 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7242 resolvedType, flags, targetUserId); 7243 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7244 // If all the matches in the target profile are suspended, return null. 7245 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7246 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7247 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7248 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7249 targetUserId); 7250 } 7251 } 7252 } 7253 return null; 7254 } 7255 7256 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7257 int sourceUserId, int targetUserId) { 7258 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7259 long ident = Binder.clearCallingIdentity(); 7260 boolean targetIsProfile; 7261 try { 7262 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7263 } finally { 7264 Binder.restoreCallingIdentity(ident); 7265 } 7266 String className; 7267 if (targetIsProfile) { 7268 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7269 } else { 7270 className = FORWARD_INTENT_TO_PARENT; 7271 } 7272 ComponentName forwardingActivityComponentName = new ComponentName( 7273 mAndroidApplication.packageName, className); 7274 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7275 sourceUserId); 7276 if (!targetIsProfile) { 7277 forwardingActivityInfo.showUserIcon = targetUserId; 7278 forwardingResolveInfo.noResourceId = true; 7279 } 7280 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7281 forwardingResolveInfo.priority = 0; 7282 forwardingResolveInfo.preferredOrder = 0; 7283 forwardingResolveInfo.match = 0; 7284 forwardingResolveInfo.isDefault = true; 7285 forwardingResolveInfo.filter = filter; 7286 forwardingResolveInfo.targetUserId = targetUserId; 7287 return forwardingResolveInfo; 7288 } 7289 7290 @Override 7291 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7292 Intent[] specifics, String[] specificTypes, Intent intent, 7293 String resolvedType, int flags, int userId) { 7294 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7295 specificTypes, intent, resolvedType, flags, userId)); 7296 } 7297 7298 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7299 Intent[] specifics, String[] specificTypes, Intent intent, 7300 String resolvedType, int flags, int userId) { 7301 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7302 final int callingUid = Binder.getCallingUid(); 7303 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7304 false /*includeInstantApps*/); 7305 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7306 false /*requireFullPermission*/, false /*checkShell*/, 7307 "query intent activity options"); 7308 final String resultsAction = intent.getAction(); 7309 7310 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7311 | PackageManager.GET_RESOLVED_FILTER, userId); 7312 7313 if (DEBUG_INTENT_MATCHING) { 7314 Log.v(TAG, "Query " + intent + ": " + results); 7315 } 7316 7317 int specificsPos = 0; 7318 int N; 7319 7320 // todo: note that the algorithm used here is O(N^2). This 7321 // isn't a problem in our current environment, but if we start running 7322 // into situations where we have more than 5 or 10 matches then this 7323 // should probably be changed to something smarter... 7324 7325 // First we go through and resolve each of the specific items 7326 // that were supplied, taking care of removing any corresponding 7327 // duplicate items in the generic resolve list. 7328 if (specifics != null) { 7329 for (int i=0; i<specifics.length; i++) { 7330 final Intent sintent = specifics[i]; 7331 if (sintent == null) { 7332 continue; 7333 } 7334 7335 if (DEBUG_INTENT_MATCHING) { 7336 Log.v(TAG, "Specific #" + i + ": " + sintent); 7337 } 7338 7339 String action = sintent.getAction(); 7340 if (resultsAction != null && resultsAction.equals(action)) { 7341 // If this action was explicitly requested, then don't 7342 // remove things that have it. 7343 action = null; 7344 } 7345 7346 ResolveInfo ri = null; 7347 ActivityInfo ai = null; 7348 7349 ComponentName comp = sintent.getComponent(); 7350 if (comp == null) { 7351 ri = resolveIntent( 7352 sintent, 7353 specificTypes != null ? specificTypes[i] : null, 7354 flags, userId); 7355 if (ri == null) { 7356 continue; 7357 } 7358 if (ri == mResolveInfo) { 7359 // ACK! Must do something better with this. 7360 } 7361 ai = ri.activityInfo; 7362 comp = new ComponentName(ai.applicationInfo.packageName, 7363 ai.name); 7364 } else { 7365 ai = getActivityInfo(comp, flags, userId); 7366 if (ai == null) { 7367 continue; 7368 } 7369 } 7370 7371 // Look for any generic query activities that are duplicates 7372 // of this specific one, and remove them from the results. 7373 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7374 N = results.size(); 7375 int j; 7376 for (j=specificsPos; j<N; j++) { 7377 ResolveInfo sri = results.get(j); 7378 if ((sri.activityInfo.name.equals(comp.getClassName()) 7379 && sri.activityInfo.applicationInfo.packageName.equals( 7380 comp.getPackageName())) 7381 || (action != null && sri.filter.matchAction(action))) { 7382 results.remove(j); 7383 if (DEBUG_INTENT_MATCHING) Log.v( 7384 TAG, "Removing duplicate item from " + j 7385 + " due to specific " + specificsPos); 7386 if (ri == null) { 7387 ri = sri; 7388 } 7389 j--; 7390 N--; 7391 } 7392 } 7393 7394 // Add this specific item to its proper place. 7395 if (ri == null) { 7396 ri = new ResolveInfo(); 7397 ri.activityInfo = ai; 7398 } 7399 results.add(specificsPos, ri); 7400 ri.specificIndex = i; 7401 specificsPos++; 7402 } 7403 } 7404 7405 // Now we go through the remaining generic results and remove any 7406 // duplicate actions that are found here. 7407 N = results.size(); 7408 for (int i=specificsPos; i<N-1; i++) { 7409 final ResolveInfo rii = results.get(i); 7410 if (rii.filter == null) { 7411 continue; 7412 } 7413 7414 // Iterate over all of the actions of this result's intent 7415 // filter... typically this should be just one. 7416 final Iterator<String> it = rii.filter.actionsIterator(); 7417 if (it == null) { 7418 continue; 7419 } 7420 while (it.hasNext()) { 7421 final String action = it.next(); 7422 if (resultsAction != null && resultsAction.equals(action)) { 7423 // If this action was explicitly requested, then don't 7424 // remove things that have it. 7425 continue; 7426 } 7427 for (int j=i+1; j<N; j++) { 7428 final ResolveInfo rij = results.get(j); 7429 if (rij.filter != null && rij.filter.hasAction(action)) { 7430 results.remove(j); 7431 if (DEBUG_INTENT_MATCHING) Log.v( 7432 TAG, "Removing duplicate item from " + j 7433 + " due to action " + action + " at " + i); 7434 j--; 7435 N--; 7436 } 7437 } 7438 } 7439 7440 // If the caller didn't request filter information, drop it now 7441 // so we don't have to marshall/unmarshall it. 7442 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7443 rii.filter = null; 7444 } 7445 } 7446 7447 // Filter out the caller activity if so requested. 7448 if (caller != null) { 7449 N = results.size(); 7450 for (int i=0; i<N; i++) { 7451 ActivityInfo ainfo = results.get(i).activityInfo; 7452 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7453 && caller.getClassName().equals(ainfo.name)) { 7454 results.remove(i); 7455 break; 7456 } 7457 } 7458 } 7459 7460 // If the caller didn't request filter information, 7461 // drop them now so we don't have to 7462 // marshall/unmarshall it. 7463 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7464 N = results.size(); 7465 for (int i=0; i<N; i++) { 7466 results.get(i).filter = null; 7467 } 7468 } 7469 7470 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7471 return results; 7472 } 7473 7474 @Override 7475 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7476 String resolvedType, int flags, int userId) { 7477 return new ParceledListSlice<>( 7478 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7479 false /*allowDynamicSplits*/)); 7480 } 7481 7482 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7483 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7484 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7485 final int callingUid = Binder.getCallingUid(); 7486 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7487 false /*requireFullPermission*/, false /*checkShell*/, 7488 "query intent receivers"); 7489 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7490 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7491 false /*includeInstantApps*/); 7492 ComponentName comp = intent.getComponent(); 7493 if (comp == null) { 7494 if (intent.getSelector() != null) { 7495 intent = intent.getSelector(); 7496 comp = intent.getComponent(); 7497 } 7498 } 7499 if (comp != null) { 7500 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7501 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7502 if (ai != null) { 7503 // When specifying an explicit component, we prevent the activity from being 7504 // used when either 1) the calling package is normal and the activity is within 7505 // an instant application or 2) the calling package is ephemeral and the 7506 // activity is not visible to instant applications. 7507 final boolean matchInstantApp = 7508 (flags & PackageManager.MATCH_INSTANT) != 0; 7509 final boolean matchVisibleToInstantAppOnly = 7510 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7511 final boolean matchExplicitlyVisibleOnly = 7512 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7513 final boolean isCallerInstantApp = 7514 instantAppPkgName != null; 7515 final boolean isTargetSameInstantApp = 7516 comp.getPackageName().equals(instantAppPkgName); 7517 final boolean isTargetInstantApp = 7518 (ai.applicationInfo.privateFlags 7519 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7520 final boolean isTargetVisibleToInstantApp = 7521 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7522 final boolean isTargetExplicitlyVisibleToInstantApp = 7523 isTargetVisibleToInstantApp 7524 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7525 final boolean isTargetHiddenFromInstantApp = 7526 !isTargetVisibleToInstantApp 7527 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7528 final boolean blockResolution = 7529 !isTargetSameInstantApp 7530 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7531 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7532 && isTargetHiddenFromInstantApp)); 7533 if (!blockResolution) { 7534 ResolveInfo ri = new ResolveInfo(); 7535 ri.activityInfo = ai; 7536 list.add(ri); 7537 } 7538 } 7539 return applyPostResolutionFilter( 7540 list, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7541 } 7542 7543 // reader 7544 synchronized (mPackages) { 7545 String pkgName = intent.getPackage(); 7546 if (pkgName == null) { 7547 final List<ResolveInfo> result = 7548 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7549 return applyPostResolutionFilter( 7550 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7551 } 7552 final PackageParser.Package pkg = mPackages.get(pkgName); 7553 if (pkg != null) { 7554 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7555 intent, resolvedType, flags, pkg.receivers, userId); 7556 return applyPostResolutionFilter( 7557 result, instantAppPkgName, allowDynamicSplits, callingUid, userId, intent); 7558 } 7559 return Collections.emptyList(); 7560 } 7561 } 7562 7563 @Override 7564 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7565 final int callingUid = Binder.getCallingUid(); 7566 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7567 } 7568 7569 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7570 int userId, int callingUid) { 7571 if (!sUserManager.exists(userId)) return null; 7572 flags = updateFlagsForResolve( 7573 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7574 List<ResolveInfo> query = queryIntentServicesInternal( 7575 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7576 if (query != null) { 7577 if (query.size() >= 1) { 7578 // If there is more than one service with the same priority, 7579 // just arbitrarily pick the first one. 7580 return query.get(0); 7581 } 7582 } 7583 return null; 7584 } 7585 7586 @Override 7587 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7588 String resolvedType, int flags, int userId) { 7589 final int callingUid = Binder.getCallingUid(); 7590 return new ParceledListSlice<>(queryIntentServicesInternal( 7591 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7592 } 7593 7594 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7595 String resolvedType, int flags, int userId, int callingUid, 7596 boolean includeInstantApps) { 7597 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7598 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7599 false /*requireFullPermission*/, false /*checkShell*/, 7600 "query intent receivers"); 7601 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7602 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7603 ComponentName comp = intent.getComponent(); 7604 if (comp == null) { 7605 if (intent.getSelector() != null) { 7606 intent = intent.getSelector(); 7607 comp = intent.getComponent(); 7608 } 7609 } 7610 if (comp != null) { 7611 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7612 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7613 if (si != null) { 7614 // When specifying an explicit component, we prevent the service from being 7615 // used when either 1) the service is in an instant application and the 7616 // caller is not the same instant application or 2) the calling package is 7617 // ephemeral and the activity is not visible to ephemeral applications. 7618 final boolean matchInstantApp = 7619 (flags & PackageManager.MATCH_INSTANT) != 0; 7620 final boolean matchVisibleToInstantAppOnly = 7621 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7622 final boolean isCallerInstantApp = 7623 instantAppPkgName != null; 7624 final boolean isTargetSameInstantApp = 7625 comp.getPackageName().equals(instantAppPkgName); 7626 final boolean isTargetInstantApp = 7627 (si.applicationInfo.privateFlags 7628 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7629 final boolean isTargetHiddenFromInstantApp = 7630 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7631 final boolean blockResolution = 7632 !isTargetSameInstantApp 7633 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7634 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7635 && isTargetHiddenFromInstantApp)); 7636 if (!blockResolution) { 7637 final ResolveInfo ri = new ResolveInfo(); 7638 ri.serviceInfo = si; 7639 list.add(ri); 7640 } 7641 } 7642 return list; 7643 } 7644 7645 // reader 7646 synchronized (mPackages) { 7647 String pkgName = intent.getPackage(); 7648 if (pkgName == null) { 7649 return applyPostServiceResolutionFilter( 7650 mServices.queryIntent(intent, resolvedType, flags, userId), 7651 instantAppPkgName); 7652 } 7653 final PackageParser.Package pkg = mPackages.get(pkgName); 7654 if (pkg != null) { 7655 return applyPostServiceResolutionFilter( 7656 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7657 userId), 7658 instantAppPkgName); 7659 } 7660 return Collections.emptyList(); 7661 } 7662 } 7663 7664 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7665 String instantAppPkgName) { 7666 if (instantAppPkgName == null) { 7667 return resolveInfos; 7668 } 7669 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7670 final ResolveInfo info = resolveInfos.get(i); 7671 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7672 // allow services that are defined in the provided package 7673 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7674 if (info.serviceInfo.splitName != null 7675 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7676 info.serviceInfo.splitName)) { 7677 // requested service is defined in a split that hasn't been installed yet. 7678 // add the installer to the resolve list 7679 if (DEBUG_INSTANT) { 7680 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7681 } 7682 final ResolveInfo installerInfo = new ResolveInfo( 7683 mInstantAppInstallerInfo); 7684 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7685 null /* installFailureActivity */, 7686 info.serviceInfo.packageName, 7687 info.serviceInfo.applicationInfo.versionCode, 7688 info.serviceInfo.splitName); 7689 // add a non-generic filter 7690 installerInfo.filter = new IntentFilter(); 7691 // load resources from the correct package 7692 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7693 resolveInfos.set(i, installerInfo); 7694 } 7695 continue; 7696 } 7697 // allow services that have been explicitly exposed to ephemeral apps 7698 if (!isEphemeralApp 7699 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7700 continue; 7701 } 7702 resolveInfos.remove(i); 7703 } 7704 return resolveInfos; 7705 } 7706 7707 @Override 7708 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7709 String resolvedType, int flags, int userId) { 7710 return new ParceledListSlice<>( 7711 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7712 } 7713 7714 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7715 Intent intent, String resolvedType, int flags, int userId) { 7716 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7717 final int callingUid = Binder.getCallingUid(); 7718 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7719 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7720 false /*includeInstantApps*/); 7721 ComponentName comp = intent.getComponent(); 7722 if (comp == null) { 7723 if (intent.getSelector() != null) { 7724 intent = intent.getSelector(); 7725 comp = intent.getComponent(); 7726 } 7727 } 7728 if (comp != null) { 7729 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7730 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7731 if (pi != null) { 7732 // When specifying an explicit component, we prevent the provider from being 7733 // used when either 1) the provider is in an instant application and the 7734 // caller is not the same instant application or 2) the calling package is an 7735 // instant application and the provider is not visible to instant applications. 7736 final boolean matchInstantApp = 7737 (flags & PackageManager.MATCH_INSTANT) != 0; 7738 final boolean matchVisibleToInstantAppOnly = 7739 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7740 final boolean isCallerInstantApp = 7741 instantAppPkgName != null; 7742 final boolean isTargetSameInstantApp = 7743 comp.getPackageName().equals(instantAppPkgName); 7744 final boolean isTargetInstantApp = 7745 (pi.applicationInfo.privateFlags 7746 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7747 final boolean isTargetHiddenFromInstantApp = 7748 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7749 final boolean blockResolution = 7750 !isTargetSameInstantApp 7751 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7752 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7753 && isTargetHiddenFromInstantApp)); 7754 if (!blockResolution) { 7755 final ResolveInfo ri = new ResolveInfo(); 7756 ri.providerInfo = pi; 7757 list.add(ri); 7758 } 7759 } 7760 return list; 7761 } 7762 7763 // reader 7764 synchronized (mPackages) { 7765 String pkgName = intent.getPackage(); 7766 if (pkgName == null) { 7767 return applyPostContentProviderResolutionFilter( 7768 mProviders.queryIntent(intent, resolvedType, flags, userId), 7769 instantAppPkgName); 7770 } 7771 final PackageParser.Package pkg = mPackages.get(pkgName); 7772 if (pkg != null) { 7773 return applyPostContentProviderResolutionFilter( 7774 mProviders.queryIntentForPackage( 7775 intent, resolvedType, flags, pkg.providers, userId), 7776 instantAppPkgName); 7777 } 7778 return Collections.emptyList(); 7779 } 7780 } 7781 7782 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7783 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7784 if (instantAppPkgName == null) { 7785 return resolveInfos; 7786 } 7787 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7788 final ResolveInfo info = resolveInfos.get(i); 7789 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7790 // allow providers that are defined in the provided package 7791 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7792 if (info.providerInfo.splitName != null 7793 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7794 info.providerInfo.splitName)) { 7795 // requested provider is defined in a split that hasn't been installed yet. 7796 // add the installer to the resolve list 7797 if (DEBUG_INSTANT) { 7798 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7799 } 7800 final ResolveInfo installerInfo = new ResolveInfo( 7801 mInstantAppInstallerInfo); 7802 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7803 null /*failureActivity*/, 7804 info.providerInfo.packageName, 7805 info.providerInfo.applicationInfo.versionCode, 7806 info.providerInfo.splitName); 7807 // add a non-generic filter 7808 installerInfo.filter = new IntentFilter(); 7809 // load resources from the correct package 7810 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7811 resolveInfos.set(i, installerInfo); 7812 } 7813 continue; 7814 } 7815 // allow providers that have been explicitly exposed to instant applications 7816 if (!isEphemeralApp 7817 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7818 continue; 7819 } 7820 resolveInfos.remove(i); 7821 } 7822 return resolveInfos; 7823 } 7824 7825 @Override 7826 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7827 final int callingUid = Binder.getCallingUid(); 7828 if (getInstantAppPackageName(callingUid) != null) { 7829 return ParceledListSlice.emptyList(); 7830 } 7831 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7832 flags = updateFlagsForPackage(flags, userId, null); 7833 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7834 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7835 true /* requireFullPermission */, false /* checkShell */, 7836 "get installed packages"); 7837 7838 // writer 7839 synchronized (mPackages) { 7840 ArrayList<PackageInfo> list; 7841 if (listUninstalled) { 7842 list = new ArrayList<>(mSettings.mPackages.size()); 7843 for (PackageSetting ps : mSettings.mPackages.values()) { 7844 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7845 continue; 7846 } 7847 if (filterAppAccessLPr(ps, callingUid, userId)) { 7848 continue; 7849 } 7850 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7851 if (pi != null) { 7852 list.add(pi); 7853 } 7854 } 7855 } else { 7856 list = new ArrayList<>(mPackages.size()); 7857 for (PackageParser.Package p : mPackages.values()) { 7858 final PackageSetting ps = (PackageSetting) p.mExtras; 7859 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7860 continue; 7861 } 7862 if (filterAppAccessLPr(ps, callingUid, userId)) { 7863 continue; 7864 } 7865 final PackageInfo pi = generatePackageInfo((PackageSetting) 7866 p.mExtras, flags, userId); 7867 if (pi != null) { 7868 list.add(pi); 7869 } 7870 } 7871 } 7872 7873 return new ParceledListSlice<>(list); 7874 } 7875 } 7876 7877 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7878 String[] permissions, boolean[] tmp, int flags, int userId) { 7879 int numMatch = 0; 7880 final PermissionsState permissionsState = ps.getPermissionsState(); 7881 for (int i=0; i<permissions.length; i++) { 7882 final String permission = permissions[i]; 7883 if (permissionsState.hasPermission(permission, userId)) { 7884 tmp[i] = true; 7885 numMatch++; 7886 } else { 7887 tmp[i] = false; 7888 } 7889 } 7890 if (numMatch == 0) { 7891 return; 7892 } 7893 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7894 7895 // The above might return null in cases of uninstalled apps or install-state 7896 // skew across users/profiles. 7897 if (pi != null) { 7898 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7899 if (numMatch == permissions.length) { 7900 pi.requestedPermissions = permissions; 7901 } else { 7902 pi.requestedPermissions = new String[numMatch]; 7903 numMatch = 0; 7904 for (int i=0; i<permissions.length; i++) { 7905 if (tmp[i]) { 7906 pi.requestedPermissions[numMatch] = permissions[i]; 7907 numMatch++; 7908 } 7909 } 7910 } 7911 } 7912 list.add(pi); 7913 } 7914 } 7915 7916 @Override 7917 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7918 String[] permissions, int flags, int userId) { 7919 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7920 flags = updateFlagsForPackage(flags, userId, permissions); 7921 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7922 true /* requireFullPermission */, false /* checkShell */, 7923 "get packages holding permissions"); 7924 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7925 7926 // writer 7927 synchronized (mPackages) { 7928 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7929 boolean[] tmpBools = new boolean[permissions.length]; 7930 if (listUninstalled) { 7931 for (PackageSetting ps : mSettings.mPackages.values()) { 7932 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7933 userId); 7934 } 7935 } else { 7936 for (PackageParser.Package pkg : mPackages.values()) { 7937 PackageSetting ps = (PackageSetting)pkg.mExtras; 7938 if (ps != null) { 7939 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7940 userId); 7941 } 7942 } 7943 } 7944 7945 return new ParceledListSlice<PackageInfo>(list); 7946 } 7947 } 7948 7949 @Override 7950 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7951 final int callingUid = Binder.getCallingUid(); 7952 if (getInstantAppPackageName(callingUid) != null) { 7953 return ParceledListSlice.emptyList(); 7954 } 7955 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7956 flags = updateFlagsForApplication(flags, userId, null); 7957 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7958 7959 // writer 7960 synchronized (mPackages) { 7961 ArrayList<ApplicationInfo> list; 7962 if (listUninstalled) { 7963 list = new ArrayList<>(mSettings.mPackages.size()); 7964 for (PackageSetting ps : mSettings.mPackages.values()) { 7965 ApplicationInfo ai; 7966 int effectiveFlags = flags; 7967 if (ps.isSystem()) { 7968 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7969 } 7970 if (ps.pkg != null) { 7971 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7972 continue; 7973 } 7974 if (filterAppAccessLPr(ps, callingUid, userId)) { 7975 continue; 7976 } 7977 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7978 ps.readUserState(userId), userId); 7979 if (ai != null) { 7980 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7981 } 7982 } else { 7983 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7984 // and already converts to externally visible package name 7985 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7986 callingUid, effectiveFlags, userId); 7987 } 7988 if (ai != null) { 7989 list.add(ai); 7990 } 7991 } 7992 } else { 7993 list = new ArrayList<>(mPackages.size()); 7994 for (PackageParser.Package p : mPackages.values()) { 7995 if (p.mExtras != null) { 7996 PackageSetting ps = (PackageSetting) p.mExtras; 7997 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7998 continue; 7999 } 8000 if (filterAppAccessLPr(ps, callingUid, userId)) { 8001 continue; 8002 } 8003 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8004 ps.readUserState(userId), userId); 8005 if (ai != null) { 8006 ai.packageName = resolveExternalPackageNameLPr(p); 8007 list.add(ai); 8008 } 8009 } 8010 } 8011 } 8012 8013 return new ParceledListSlice<>(list); 8014 } 8015 } 8016 8017 @Override 8018 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8019 if (HIDE_EPHEMERAL_APIS) { 8020 return null; 8021 } 8022 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8023 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8024 "getEphemeralApplications"); 8025 } 8026 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8027 true /* requireFullPermission */, false /* checkShell */, 8028 "getEphemeralApplications"); 8029 synchronized (mPackages) { 8030 List<InstantAppInfo> instantApps = mInstantAppRegistry 8031 .getInstantAppsLPr(userId); 8032 if (instantApps != null) { 8033 return new ParceledListSlice<>(instantApps); 8034 } 8035 } 8036 return null; 8037 } 8038 8039 @Override 8040 public boolean isInstantApp(String packageName, int userId) { 8041 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8042 true /* requireFullPermission */, false /* checkShell */, 8043 "isInstantApp"); 8044 if (HIDE_EPHEMERAL_APIS) { 8045 return false; 8046 } 8047 8048 synchronized (mPackages) { 8049 int callingUid = Binder.getCallingUid(); 8050 if (Process.isIsolated(callingUid)) { 8051 callingUid = mIsolatedOwners.get(callingUid); 8052 } 8053 final PackageSetting ps = mSettings.mPackages.get(packageName); 8054 PackageParser.Package pkg = mPackages.get(packageName); 8055 final boolean returnAllowed = 8056 ps != null 8057 && (isCallerSameApp(packageName, callingUid) 8058 || canViewInstantApps(callingUid, userId) 8059 || mInstantAppRegistry.isInstantAccessGranted( 8060 userId, UserHandle.getAppId(callingUid), ps.appId)); 8061 if (returnAllowed) { 8062 return ps.getInstantApp(userId); 8063 } 8064 } 8065 return false; 8066 } 8067 8068 @Override 8069 public byte[] getInstantAppCookie(String packageName, int userId) { 8070 if (HIDE_EPHEMERAL_APIS) { 8071 return null; 8072 } 8073 8074 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8075 true /* requireFullPermission */, false /* checkShell */, 8076 "getInstantAppCookie"); 8077 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8078 return null; 8079 } 8080 synchronized (mPackages) { 8081 return mInstantAppRegistry.getInstantAppCookieLPw( 8082 packageName, userId); 8083 } 8084 } 8085 8086 @Override 8087 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8088 if (HIDE_EPHEMERAL_APIS) { 8089 return true; 8090 } 8091 8092 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8093 true /* requireFullPermission */, true /* checkShell */, 8094 "setInstantAppCookie"); 8095 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8096 return false; 8097 } 8098 synchronized (mPackages) { 8099 return mInstantAppRegistry.setInstantAppCookieLPw( 8100 packageName, cookie, userId); 8101 } 8102 } 8103 8104 @Override 8105 public Bitmap getInstantAppIcon(String packageName, int userId) { 8106 if (HIDE_EPHEMERAL_APIS) { 8107 return null; 8108 } 8109 8110 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8111 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8112 "getInstantAppIcon"); 8113 } 8114 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8115 true /* requireFullPermission */, false /* checkShell */, 8116 "getInstantAppIcon"); 8117 8118 synchronized (mPackages) { 8119 return mInstantAppRegistry.getInstantAppIconLPw( 8120 packageName, userId); 8121 } 8122 } 8123 8124 private boolean isCallerSameApp(String packageName, int uid) { 8125 PackageParser.Package pkg = mPackages.get(packageName); 8126 return pkg != null 8127 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8128 } 8129 8130 @Override 8131 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8132 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8133 return ParceledListSlice.emptyList(); 8134 } 8135 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8136 } 8137 8138 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8139 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8140 8141 // reader 8142 synchronized (mPackages) { 8143 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8144 final int userId = UserHandle.getCallingUserId(); 8145 while (i.hasNext()) { 8146 final PackageParser.Package p = i.next(); 8147 if (p.applicationInfo == null) continue; 8148 8149 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8150 && !p.applicationInfo.isDirectBootAware(); 8151 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8152 && p.applicationInfo.isDirectBootAware(); 8153 8154 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8155 && (!mSafeMode || isSystemApp(p)) 8156 && (matchesUnaware || matchesAware)) { 8157 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8158 if (ps != null) { 8159 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8160 ps.readUserState(userId), userId); 8161 if (ai != null) { 8162 finalList.add(ai); 8163 } 8164 } 8165 } 8166 } 8167 } 8168 8169 return finalList; 8170 } 8171 8172 @Override 8173 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8174 return resolveContentProviderInternal(name, flags, userId); 8175 } 8176 8177 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8178 if (!sUserManager.exists(userId)) return null; 8179 flags = updateFlagsForComponent(flags, userId, name); 8180 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8181 // reader 8182 synchronized (mPackages) { 8183 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8184 PackageSetting ps = provider != null 8185 ? mSettings.mPackages.get(provider.owner.packageName) 8186 : null; 8187 if (ps != null) { 8188 final boolean isInstantApp = ps.getInstantApp(userId); 8189 // normal application; filter out instant application provider 8190 if (instantAppPkgName == null && isInstantApp) { 8191 return null; 8192 } 8193 // instant application; filter out other instant applications 8194 if (instantAppPkgName != null 8195 && isInstantApp 8196 && !provider.owner.packageName.equals(instantAppPkgName)) { 8197 return null; 8198 } 8199 // instant application; filter out non-exposed provider 8200 if (instantAppPkgName != null 8201 && !isInstantApp 8202 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8203 return null; 8204 } 8205 // provider not enabled 8206 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8207 return null; 8208 } 8209 return PackageParser.generateProviderInfo( 8210 provider, flags, ps.readUserState(userId), userId); 8211 } 8212 return null; 8213 } 8214 } 8215 8216 /** 8217 * @deprecated 8218 */ 8219 @Deprecated 8220 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8221 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8222 return; 8223 } 8224 // reader 8225 synchronized (mPackages) { 8226 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8227 .entrySet().iterator(); 8228 final int userId = UserHandle.getCallingUserId(); 8229 while (i.hasNext()) { 8230 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8231 PackageParser.Provider p = entry.getValue(); 8232 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8233 8234 if (ps != null && p.syncable 8235 && (!mSafeMode || (p.info.applicationInfo.flags 8236 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8237 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8238 ps.readUserState(userId), userId); 8239 if (info != null) { 8240 outNames.add(entry.getKey()); 8241 outInfo.add(info); 8242 } 8243 } 8244 } 8245 } 8246 } 8247 8248 @Override 8249 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8250 int uid, int flags, String metaDataKey) { 8251 final int callingUid = Binder.getCallingUid(); 8252 final int userId = processName != null ? UserHandle.getUserId(uid) 8253 : UserHandle.getCallingUserId(); 8254 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8255 flags = updateFlagsForComponent(flags, userId, processName); 8256 ArrayList<ProviderInfo> finalList = null; 8257 // reader 8258 synchronized (mPackages) { 8259 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8260 while (i.hasNext()) { 8261 final PackageParser.Provider p = i.next(); 8262 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8263 if (ps != null && p.info.authority != null 8264 && (processName == null 8265 || (p.info.processName.equals(processName) 8266 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8267 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8268 8269 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8270 // parameter. 8271 if (metaDataKey != null 8272 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8273 continue; 8274 } 8275 final ComponentName component = 8276 new ComponentName(p.info.packageName, p.info.name); 8277 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8278 continue; 8279 } 8280 if (finalList == null) { 8281 finalList = new ArrayList<ProviderInfo>(3); 8282 } 8283 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8284 ps.readUserState(userId), userId); 8285 if (info != null) { 8286 finalList.add(info); 8287 } 8288 } 8289 } 8290 } 8291 8292 if (finalList != null) { 8293 Collections.sort(finalList, mProviderInitOrderSorter); 8294 return new ParceledListSlice<ProviderInfo>(finalList); 8295 } 8296 8297 return ParceledListSlice.emptyList(); 8298 } 8299 8300 @Override 8301 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8302 // reader 8303 synchronized (mPackages) { 8304 final int callingUid = Binder.getCallingUid(); 8305 final int callingUserId = UserHandle.getUserId(callingUid); 8306 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8307 if (ps == null) return null; 8308 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8309 return null; 8310 } 8311 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8312 return PackageParser.generateInstrumentationInfo(i, flags); 8313 } 8314 } 8315 8316 @Override 8317 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8318 String targetPackage, int flags) { 8319 final int callingUid = Binder.getCallingUid(); 8320 final int callingUserId = UserHandle.getUserId(callingUid); 8321 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8322 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8323 return ParceledListSlice.emptyList(); 8324 } 8325 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8326 } 8327 8328 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8329 int flags) { 8330 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8331 8332 // reader 8333 synchronized (mPackages) { 8334 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8335 while (i.hasNext()) { 8336 final PackageParser.Instrumentation p = i.next(); 8337 if (targetPackage == null 8338 || targetPackage.equals(p.info.targetPackage)) { 8339 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8340 flags); 8341 if (ii != null) { 8342 finalList.add(ii); 8343 } 8344 } 8345 } 8346 } 8347 8348 return finalList; 8349 } 8350 8351 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8352 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8353 try { 8354 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8355 } finally { 8356 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8357 } 8358 } 8359 8360 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8361 final File[] files = scanDir.listFiles(); 8362 if (ArrayUtils.isEmpty(files)) { 8363 Log.d(TAG, "No files in app dir " + scanDir); 8364 return; 8365 } 8366 8367 if (DEBUG_PACKAGE_SCANNING) { 8368 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8369 + " flags=0x" + Integer.toHexString(parseFlags)); 8370 } 8371 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8372 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8373 mParallelPackageParserCallback)) { 8374 // Submit files for parsing in parallel 8375 int fileCount = 0; 8376 for (File file : files) { 8377 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8378 && !PackageInstallerService.isStageName(file.getName()); 8379 if (!isPackage) { 8380 // Ignore entries which are not packages 8381 continue; 8382 } 8383 parallelPackageParser.submit(file, parseFlags); 8384 fileCount++; 8385 } 8386 8387 // Process results one by one 8388 for (; fileCount > 0; fileCount--) { 8389 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8390 Throwable throwable = parseResult.throwable; 8391 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8392 8393 if (throwable == null) { 8394 // TODO(toddke): move lower in the scan chain 8395 // Static shared libraries have synthetic package names 8396 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8397 renameStaticSharedLibraryPackage(parseResult.pkg); 8398 } 8399 try { 8400 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8401 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8402 currentTime, null); 8403 } 8404 } catch (PackageManagerException e) { 8405 errorCode = e.error; 8406 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8407 } 8408 } else if (throwable instanceof PackageParser.PackageParserException) { 8409 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8410 throwable; 8411 errorCode = e.error; 8412 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8413 } else { 8414 throw new IllegalStateException("Unexpected exception occurred while parsing " 8415 + parseResult.scanFile, throwable); 8416 } 8417 8418 // Delete invalid userdata apps 8419 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8420 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8421 logCriticalInfo(Log.WARN, 8422 "Deleting invalid package at " + parseResult.scanFile); 8423 removeCodePathLI(parseResult.scanFile); 8424 } 8425 } 8426 } 8427 } 8428 8429 public static void reportSettingsProblem(int priority, String msg) { 8430 logCriticalInfo(priority, msg); 8431 } 8432 8433 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8434 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 8435 // When upgrading from pre-N MR1, verify the package time stamp using the package 8436 // directory and not the APK file. 8437 final long lastModifiedTime = mIsPreNMR1Upgrade 8438 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8439 if (ps != null && !forceCollect 8440 && ps.codePathString.equals(pkg.codePath) 8441 && ps.timeStamp == lastModifiedTime 8442 && !isCompatSignatureUpdateNeeded(pkg) 8443 && !isRecoverSignatureUpdateNeeded(pkg)) { 8444 if (ps.signatures.mSigningDetails.signatures != null 8445 && ps.signatures.mSigningDetails.signatures.length != 0 8446 && ps.signatures.mSigningDetails.signatureSchemeVersion 8447 != SignatureSchemeVersion.UNKNOWN) { 8448 // Optimization: reuse the existing cached signing data 8449 // if the package appears to be unchanged. 8450 pkg.mSigningDetails = 8451 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8452 return; 8453 } 8454 8455 Slog.w(TAG, "PackageSetting for " + ps.name 8456 + " is missing signatures. Collecting certs again to recover them."); 8457 } else { 8458 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8459 (forceCollect ? " (forced)" : "")); 8460 } 8461 8462 try { 8463 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8464 PackageParser.collectCertificates(pkg, skipVerify); 8465 } catch (PackageParserException e) { 8466 throw PackageManagerException.from(e); 8467 } finally { 8468 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8469 } 8470 } 8471 8472 /** 8473 * Traces a package scan. 8474 * @see #scanPackageLI(File, int, int, long, UserHandle) 8475 */ 8476 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8477 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8479 try { 8480 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8481 } finally { 8482 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8483 } 8484 } 8485 8486 /** 8487 * Scans a package and returns the newly parsed package. 8488 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8489 */ 8490 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8491 long currentTime, UserHandle user) throws PackageManagerException { 8492 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8493 PackageParser pp = new PackageParser(); 8494 pp.setSeparateProcesses(mSeparateProcesses); 8495 pp.setOnlyCoreApps(mOnlyCore); 8496 pp.setDisplayMetrics(mMetrics); 8497 pp.setCallback(mPackageParserCallback); 8498 8499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8500 final PackageParser.Package pkg; 8501 try { 8502 pkg = pp.parsePackage(scanFile, parseFlags); 8503 } catch (PackageParserException e) { 8504 throw PackageManagerException.from(e); 8505 } finally { 8506 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8507 } 8508 8509 // Static shared libraries have synthetic package names 8510 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8511 renameStaticSharedLibraryPackage(pkg); 8512 } 8513 8514 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8515 } 8516 8517 /** 8518 * Scans a package and returns the newly parsed package. 8519 * @throws PackageManagerException on a parse error. 8520 */ 8521 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8522 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8523 @Nullable UserHandle user) 8524 throws PackageManagerException { 8525 // If the package has children and this is the first dive in the function 8526 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8527 // packages (parent and children) would be successfully scanned before the 8528 // actual scan since scanning mutates internal state and we want to atomically 8529 // install the package and its children. 8530 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8531 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8532 scanFlags |= SCAN_CHECK_ONLY; 8533 } 8534 } else { 8535 scanFlags &= ~SCAN_CHECK_ONLY; 8536 } 8537 8538 // Scan the parent 8539 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8540 scanFlags, currentTime, user); 8541 8542 // Scan the children 8543 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8544 for (int i = 0; i < childCount; i++) { 8545 PackageParser.Package childPackage = pkg.childPackages.get(i); 8546 addForInitLI(childPackage, parseFlags, scanFlags, 8547 currentTime, user); 8548 } 8549 8550 8551 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8552 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8553 } 8554 8555 return scannedPkg; 8556 } 8557 8558 /** 8559 * Returns if full apk verification can be skipped for the whole package, including the splits. 8560 */ 8561 private boolean canSkipFullPackageVerification(PackageParser.Package pkg) { 8562 if (!canSkipFullApkVerification(pkg.baseCodePath)) { 8563 return false; 8564 } 8565 // TODO: Allow base and splits to be verified individually. 8566 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8567 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8568 if (!canSkipFullApkVerification(pkg.splitCodePaths[i])) { 8569 return false; 8570 } 8571 } 8572 } 8573 return true; 8574 } 8575 8576 /** 8577 * Returns if full apk verification can be skipped, depending on current FSVerity setup and 8578 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 8579 * match one in a trusted source, and should be done separately. 8580 */ 8581 private boolean canSkipFullApkVerification(String apkPath) { 8582 byte[] rootHashObserved = null; 8583 try { 8584 rootHashObserved = VerityUtils.generateFsverityRootHash(apkPath); 8585 if (rootHashObserved == null) { 8586 return false; // APK does not contain Merkle tree root hash. 8587 } 8588 synchronized (mInstallLock) { 8589 // Returns whether the observed root hash matches what kernel has. 8590 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 8591 return true; 8592 } 8593 } catch (InstallerException | IOException | DigestException | 8594 NoSuchAlgorithmException e) { 8595 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 8596 } 8597 return false; 8598 } 8599 8600 /** 8601 * Adds a new package to the internal data structures during platform initialization. 8602 * <p>After adding, the package is known to the system and available for querying. 8603 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8604 * etc...], additional checks are performed. Basic verification [such as ensuring 8605 * matching signatures, checking version codes, etc...] occurs if the package is 8606 * identical to a previously known package. If the package fails a signature check, 8607 * the version installed on /data will be removed. If the version of the new package 8608 * is less than or equal than the version on /data, it will be ignored. 8609 * <p>Regardless of the package location, the results are applied to the internal 8610 * structures and the package is made available to the rest of the system. 8611 * <p>NOTE: The return value should be removed. It's the passed in package object. 8612 */ 8613 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8614 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8615 @Nullable UserHandle user) 8616 throws PackageManagerException { 8617 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8618 final String renamedPkgName; 8619 final PackageSetting disabledPkgSetting; 8620 final boolean isSystemPkgUpdated; 8621 final boolean pkgAlreadyExists; 8622 PackageSetting pkgSetting; 8623 8624 // NOTE: installPackageLI() has the same code to setup the package's 8625 // application info. This probably should be done lower in the call 8626 // stack [such as scanPackageOnly()]. However, we verify the application 8627 // info prior to that [in scanPackageNew()] and thus have to setup 8628 // the application info early. 8629 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8630 pkg.setApplicationInfoCodePath(pkg.codePath); 8631 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8632 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8633 pkg.setApplicationInfoResourcePath(pkg.codePath); 8634 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8635 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8636 8637 synchronized (mPackages) { 8638 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8639 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8640 if (realPkgName != null) { 8641 ensurePackageRenamed(pkg, renamedPkgName); 8642 } 8643 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8644 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8645 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8646 pkgAlreadyExists = pkgSetting != null; 8647 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8648 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8649 isSystemPkgUpdated = disabledPkgSetting != null; 8650 8651 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8652 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8653 } 8654 8655 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8656 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8657 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8658 : null; 8659 if (DEBUG_PACKAGE_SCANNING 8660 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8661 && sharedUserSetting != null) { 8662 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8663 + " (uid=" + sharedUserSetting.userId + "):" 8664 + " packages=" + sharedUserSetting.packages); 8665 } 8666 8667 if (scanSystemPartition) { 8668 // Potentially prune child packages. If the application on the /system 8669 // partition has been updated via OTA, but, is still disabled by a 8670 // version on /data, cycle through all of its children packages and 8671 // remove children that are no longer defined. 8672 if (isSystemPkgUpdated) { 8673 final int scannedChildCount = (pkg.childPackages != null) 8674 ? pkg.childPackages.size() : 0; 8675 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8676 ? disabledPkgSetting.childPackageNames.size() : 0; 8677 for (int i = 0; i < disabledChildCount; i++) { 8678 String disabledChildPackageName = 8679 disabledPkgSetting.childPackageNames.get(i); 8680 boolean disabledPackageAvailable = false; 8681 for (int j = 0; j < scannedChildCount; j++) { 8682 PackageParser.Package childPkg = pkg.childPackages.get(j); 8683 if (childPkg.packageName.equals(disabledChildPackageName)) { 8684 disabledPackageAvailable = true; 8685 break; 8686 } 8687 } 8688 if (!disabledPackageAvailable) { 8689 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8690 } 8691 } 8692 // we're updating the disabled package, so, scan it as the package setting 8693 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8694 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8695 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8696 (pkg == mPlatformPackage), user); 8697 applyPolicy(pkg, parseFlags, scanFlags); 8698 scanPackageOnlyLI(request, mFactoryTest, -1L); 8699 } 8700 } 8701 } 8702 8703 final boolean newPkgChangedPaths = 8704 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8705 final boolean newPkgVersionGreater = 8706 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8707 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8708 && newPkgChangedPaths && newPkgVersionGreater; 8709 if (isSystemPkgBetter) { 8710 // The version of the application on /system is greater than the version on 8711 // /data. Switch back to the application on /system. 8712 // It's safe to assume the application on /system will correctly scan. If not, 8713 // there won't be a working copy of the application. 8714 synchronized (mPackages) { 8715 // just remove the loaded entries from package lists 8716 mPackages.remove(pkgSetting.name); 8717 } 8718 8719 logCriticalInfo(Log.WARN, 8720 "System package updated;" 8721 + " name: " + pkgSetting.name 8722 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8723 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8724 8725 final InstallArgs args = createInstallArgsForExisting( 8726 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8727 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8728 args.cleanUpResourcesLI(); 8729 synchronized (mPackages) { 8730 mSettings.enableSystemPackageLPw(pkgSetting.name); 8731 } 8732 } 8733 8734 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8735 // The version of the application on the /system partition is less than or 8736 // equal to the version on the /data partition. Throw an exception and use 8737 // the application already installed on the /data partition. 8738 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8739 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8740 + " better than this " + pkg.getLongVersionCode()); 8741 } 8742 8743 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8744 // force re-collecting certificate. 8745 final boolean forceCollect = PackageManagerServiceUtils.isApkVerificationForced( 8746 disabledPkgSetting); 8747 // Full APK verification can be skipped during certificate collection, only if the file is 8748 // in verified partition, or can be verified on access (when apk verity is enabled). In both 8749 // cases, only data in Signing Block is verified instead of the whole file. 8750 final boolean skipVerify = ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) || 8751 (forceCollect && canSkipFullPackageVerification(pkg)); 8752 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 8753 8754 boolean shouldHideSystemApp = false; 8755 // A new application appeared on /system, but, we already have a copy of 8756 // the application installed on /data. 8757 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8758 && !pkgSetting.isSystem()) { 8759 8760 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 8761 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 8762 logCriticalInfo(Log.WARN, 8763 "System package signature mismatch;" 8764 + " name: " + pkgSetting.name); 8765 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8766 "scanPackageInternalLI")) { 8767 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8768 } 8769 pkgSetting = null; 8770 } else if (newPkgVersionGreater) { 8771 // The application on /system is newer than the application on /data. 8772 // Simply remove the application on /data [keeping application data] 8773 // and replace it with the version on /system. 8774 logCriticalInfo(Log.WARN, 8775 "System package enabled;" 8776 + " name: " + pkgSetting.name 8777 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8778 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8779 InstallArgs args = createInstallArgsForExisting( 8780 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8781 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8782 synchronized (mInstallLock) { 8783 args.cleanUpResourcesLI(); 8784 } 8785 } else { 8786 // The application on /system is older than the application on /data. Hide 8787 // the application on /system and the version on /data will be scanned later 8788 // and re-added like an update. 8789 shouldHideSystemApp = true; 8790 logCriticalInfo(Log.INFO, 8791 "System package disabled;" 8792 + " name: " + pkgSetting.name 8793 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8794 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8795 } 8796 } 8797 8798 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8799 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8800 8801 if (shouldHideSystemApp) { 8802 synchronized (mPackages) { 8803 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8804 } 8805 } 8806 return scannedPkg; 8807 } 8808 8809 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8810 // Derive the new package synthetic package name 8811 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8812 + pkg.staticSharedLibVersion); 8813 } 8814 8815 private static String fixProcessName(String defProcessName, 8816 String processName) { 8817 if (processName == null) { 8818 return defProcessName; 8819 } 8820 return processName; 8821 } 8822 8823 /** 8824 * Enforces that only the system UID or root's UID can call a method exposed 8825 * via Binder. 8826 * 8827 * @param message used as message if SecurityException is thrown 8828 * @throws SecurityException if the caller is not system or root 8829 */ 8830 private static final void enforceSystemOrRoot(String message) { 8831 final int uid = Binder.getCallingUid(); 8832 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8833 throw new SecurityException(message); 8834 } 8835 } 8836 8837 @Override 8838 public void performFstrimIfNeeded() { 8839 enforceSystemOrRoot("Only the system can request fstrim"); 8840 8841 // Before everything else, see whether we need to fstrim. 8842 try { 8843 IStorageManager sm = PackageHelper.getStorageManager(); 8844 if (sm != null) { 8845 boolean doTrim = false; 8846 final long interval = android.provider.Settings.Global.getLong( 8847 mContext.getContentResolver(), 8848 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8849 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8850 if (interval > 0) { 8851 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8852 if (timeSinceLast > interval) { 8853 doTrim = true; 8854 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8855 + "; running immediately"); 8856 } 8857 } 8858 if (doTrim) { 8859 final boolean dexOptDialogShown; 8860 synchronized (mPackages) { 8861 dexOptDialogShown = mDexOptDialogShown; 8862 } 8863 if (!isFirstBoot() && dexOptDialogShown) { 8864 try { 8865 ActivityManager.getService().showBootMessage( 8866 mContext.getResources().getString( 8867 R.string.android_upgrading_fstrim), true); 8868 } catch (RemoteException e) { 8869 } 8870 } 8871 sm.runMaintenance(); 8872 } 8873 } else { 8874 Slog.e(TAG, "storageManager service unavailable!"); 8875 } 8876 } catch (RemoteException e) { 8877 // Can't happen; StorageManagerService is local 8878 } 8879 } 8880 8881 @Override 8882 public void updatePackagesIfNeeded() { 8883 enforceSystemOrRoot("Only the system can request package update"); 8884 8885 // We need to re-extract after an OTA. 8886 boolean causeUpgrade = isUpgrade(); 8887 8888 // First boot or factory reset. 8889 // Note: we also handle devices that are upgrading to N right now as if it is their 8890 // first boot, as they do not have profile data. 8891 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8892 8893 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8894 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8895 8896 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8897 return; 8898 } 8899 8900 List<PackageParser.Package> pkgs; 8901 synchronized (mPackages) { 8902 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8903 } 8904 8905 final long startTime = System.nanoTime(); 8906 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8907 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 8908 false /* bootComplete */); 8909 8910 final int elapsedTimeSeconds = 8911 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8912 8913 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8914 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8915 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8916 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8917 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8918 } 8919 8920 /* 8921 * Return the prebuilt profile path given a package base code path. 8922 */ 8923 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8924 return pkg.baseCodePath + ".prof"; 8925 } 8926 8927 /** 8928 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8929 * containing statistics about the invocation. The array consists of three elements, 8930 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8931 * and {@code numberOfPackagesFailed}. 8932 */ 8933 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8934 final int compilationReason, boolean bootComplete) { 8935 8936 int numberOfPackagesVisited = 0; 8937 int numberOfPackagesOptimized = 0; 8938 int numberOfPackagesSkipped = 0; 8939 int numberOfPackagesFailed = 0; 8940 final int numberOfPackagesToDexopt = pkgs.size(); 8941 8942 for (PackageParser.Package pkg : pkgs) { 8943 numberOfPackagesVisited++; 8944 8945 boolean useProfileForDexopt = false; 8946 8947 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8948 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8949 // that are already compiled. 8950 File profileFile = new File(getPrebuildProfilePath(pkg)); 8951 // Copy profile if it exists. 8952 if (profileFile.exists()) { 8953 try { 8954 // We could also do this lazily before calling dexopt in 8955 // PackageDexOptimizer to prevent this happening on first boot. The issue 8956 // is that we don't have a good way to say "do this only once". 8957 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8958 pkg.applicationInfo.uid, pkg.packageName, 8959 ArtManager.getProfileName(null))) { 8960 Log.e(TAG, "Installer failed to copy system profile!"); 8961 } else { 8962 // Disabled as this causes speed-profile compilation during first boot 8963 // even if things are already compiled. 8964 // useProfileForDexopt = true; 8965 } 8966 } catch (Exception e) { 8967 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8968 e); 8969 } 8970 } else { 8971 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8972 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8973 // minimize the number off apps being speed-profile compiled during first boot. 8974 // The other paths will not change the filter. 8975 if (disabledPs != null && disabledPs.pkg.isStub) { 8976 // The package is the stub one, remove the stub suffix to get the normal 8977 // package and APK names. 8978 String systemProfilePath = 8979 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8980 profileFile = new File(systemProfilePath); 8981 // If we have a profile for a compressed APK, copy it to the reference 8982 // location. 8983 // Note that copying the profile here will cause it to override the 8984 // reference profile every OTA even though the existing reference profile 8985 // may have more data. We can't copy during decompression since the 8986 // directories are not set up at that point. 8987 if (profileFile.exists()) { 8988 try { 8989 // We could also do this lazily before calling dexopt in 8990 // PackageDexOptimizer to prevent this happening on first boot. The 8991 // issue is that we don't have a good way to say "do this only 8992 // once". 8993 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8994 pkg.applicationInfo.uid, pkg.packageName, 8995 ArtManager.getProfileName(null))) { 8996 Log.e(TAG, "Failed to copy system profile for stub package!"); 8997 } else { 8998 useProfileForDexopt = true; 8999 } 9000 } catch (Exception e) { 9001 Log.e(TAG, "Failed to copy profile " + 9002 profileFile.getAbsolutePath() + " ", e); 9003 } 9004 } 9005 } 9006 } 9007 } 9008 9009 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9010 if (DEBUG_DEXOPT) { 9011 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9012 } 9013 numberOfPackagesSkipped++; 9014 continue; 9015 } 9016 9017 if (DEBUG_DEXOPT) { 9018 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9019 numberOfPackagesToDexopt + ": " + pkg.packageName); 9020 } 9021 9022 if (showDialog) { 9023 try { 9024 ActivityManager.getService().showBootMessage( 9025 mContext.getResources().getString(R.string.android_upgrading_apk, 9026 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9027 } catch (RemoteException e) { 9028 } 9029 synchronized (mPackages) { 9030 mDexOptDialogShown = true; 9031 } 9032 } 9033 9034 int pkgCompilationReason = compilationReason; 9035 if (useProfileForDexopt) { 9036 // Use background dexopt mode to try and use the profile. Note that this does not 9037 // guarantee usage of the profile. 9038 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9039 } 9040 9041 // checkProfiles is false to avoid merging profiles during boot which 9042 // might interfere with background compilation (b/28612421). 9043 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9044 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9045 // trade-off worth doing to save boot time work. 9046 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9047 if (compilationReason == REASON_FIRST_BOOT) { 9048 // TODO: This doesn't cover the upgrade case, we should check for this too. 9049 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9050 } 9051 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9052 pkg.packageName, 9053 pkgCompilationReason, 9054 dexoptFlags)); 9055 9056 switch (primaryDexOptStaus) { 9057 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9058 numberOfPackagesOptimized++; 9059 break; 9060 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9061 numberOfPackagesSkipped++; 9062 break; 9063 case PackageDexOptimizer.DEX_OPT_FAILED: 9064 numberOfPackagesFailed++; 9065 break; 9066 default: 9067 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9068 break; 9069 } 9070 } 9071 9072 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9073 numberOfPackagesFailed }; 9074 } 9075 9076 @Override 9077 public void notifyPackageUse(String packageName, int reason) { 9078 synchronized (mPackages) { 9079 final int callingUid = Binder.getCallingUid(); 9080 final int callingUserId = UserHandle.getUserId(callingUid); 9081 if (getInstantAppPackageName(callingUid) != null) { 9082 if (!isCallerSameApp(packageName, callingUid)) { 9083 return; 9084 } 9085 } else { 9086 if (isInstantApp(packageName, callingUserId)) { 9087 return; 9088 } 9089 } 9090 notifyPackageUseLocked(packageName, reason); 9091 } 9092 } 9093 9094 @GuardedBy("mPackages") 9095 private void notifyPackageUseLocked(String packageName, int reason) { 9096 final PackageParser.Package p = mPackages.get(packageName); 9097 if (p == null) { 9098 return; 9099 } 9100 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9101 } 9102 9103 @Override 9104 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9105 List<String> classPaths, String loaderIsa) { 9106 int userId = UserHandle.getCallingUserId(); 9107 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9108 if (ai == null) { 9109 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9110 + loadingPackageName + ", user=" + userId); 9111 return; 9112 } 9113 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9114 } 9115 9116 @Override 9117 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9118 IDexModuleRegisterCallback callback) { 9119 int userId = UserHandle.getCallingUserId(); 9120 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9121 DexManager.RegisterDexModuleResult result; 9122 if (ai == null) { 9123 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9124 " calling user. package=" + packageName + ", user=" + userId); 9125 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9126 } else { 9127 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9128 } 9129 9130 if (callback != null) { 9131 mHandler.post(() -> { 9132 try { 9133 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9134 } catch (RemoteException e) { 9135 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9136 } 9137 }); 9138 } 9139 } 9140 9141 /** 9142 * Ask the package manager to perform a dex-opt with the given compiler filter. 9143 * 9144 * Note: exposed only for the shell command to allow moving packages explicitly to a 9145 * definite state. 9146 */ 9147 @Override 9148 public boolean performDexOptMode(String packageName, 9149 boolean checkProfiles, String targetCompilerFilter, boolean force, 9150 boolean bootComplete, String splitName) { 9151 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9152 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9153 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9154 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9155 targetCompilerFilter, splitName, flags)); 9156 } 9157 9158 /** 9159 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9160 * secondary dex files belonging to the given package. 9161 * 9162 * Note: exposed only for the shell command to allow moving packages explicitly to a 9163 * definite state. 9164 */ 9165 @Override 9166 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9167 boolean force) { 9168 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9169 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9170 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9171 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9172 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9173 } 9174 9175 /*package*/ boolean performDexOpt(DexoptOptions options) { 9176 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9177 return false; 9178 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9179 return false; 9180 } 9181 9182 if (options.isDexoptOnlySecondaryDex()) { 9183 return mDexManager.dexoptSecondaryDex(options); 9184 } else { 9185 int dexoptStatus = performDexOptWithStatus(options); 9186 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9187 } 9188 } 9189 9190 /** 9191 * Perform dexopt on the given package and return one of following result: 9192 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9193 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9194 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9195 */ 9196 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9197 return performDexOptTraced(options); 9198 } 9199 9200 private int performDexOptTraced(DexoptOptions options) { 9201 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9202 try { 9203 return performDexOptInternal(options); 9204 } finally { 9205 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9206 } 9207 } 9208 9209 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9210 // if the package can now be considered up to date for the given filter. 9211 private int performDexOptInternal(DexoptOptions options) { 9212 PackageParser.Package p; 9213 synchronized (mPackages) { 9214 p = mPackages.get(options.getPackageName()); 9215 if (p == null) { 9216 // Package could not be found. Report failure. 9217 return PackageDexOptimizer.DEX_OPT_FAILED; 9218 } 9219 mPackageUsage.maybeWriteAsync(mPackages); 9220 mCompilerStats.maybeWriteAsync(); 9221 } 9222 long callingId = Binder.clearCallingIdentity(); 9223 try { 9224 synchronized (mInstallLock) { 9225 return performDexOptInternalWithDependenciesLI(p, options); 9226 } 9227 } finally { 9228 Binder.restoreCallingIdentity(callingId); 9229 } 9230 } 9231 9232 public ArraySet<String> getOptimizablePackages() { 9233 ArraySet<String> pkgs = new ArraySet<String>(); 9234 synchronized (mPackages) { 9235 for (PackageParser.Package p : mPackages.values()) { 9236 if (PackageDexOptimizer.canOptimizePackage(p)) { 9237 pkgs.add(p.packageName); 9238 } 9239 } 9240 } 9241 return pkgs; 9242 } 9243 9244 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9245 DexoptOptions options) { 9246 // Select the dex optimizer based on the force parameter. 9247 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9248 // allocate an object here. 9249 PackageDexOptimizer pdo = options.isForce() 9250 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9251 : mPackageDexOptimizer; 9252 9253 // Dexopt all dependencies first. Note: we ignore the return value and march on 9254 // on errors. 9255 // Note that we are going to call performDexOpt on those libraries as many times as 9256 // they are referenced in packages. When we do a batch of performDexOpt (for example 9257 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9258 // and the first package that uses the library will dexopt it. The 9259 // others will see that the compiled code for the library is up to date. 9260 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9261 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9262 if (!deps.isEmpty()) { 9263 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9264 options.getCompilationReason(), options.getCompilerFilter(), 9265 options.getSplitName(), 9266 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9267 for (PackageParser.Package depPackage : deps) { 9268 // TODO: Analyze and investigate if we (should) profile libraries. 9269 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9270 getOrCreateCompilerPackageStats(depPackage), 9271 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9272 } 9273 } 9274 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9275 getOrCreateCompilerPackageStats(p), 9276 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9277 } 9278 9279 /** 9280 * Reconcile the information we have about the secondary dex files belonging to 9281 * {@code packagName} and the actual dex files. For all dex files that were 9282 * deleted, update the internal records and delete the generated oat files. 9283 */ 9284 @Override 9285 public void reconcileSecondaryDexFiles(String packageName) { 9286 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9287 return; 9288 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9289 return; 9290 } 9291 mDexManager.reconcileSecondaryDexFiles(packageName); 9292 } 9293 9294 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9295 // a reference there. 9296 /*package*/ DexManager getDexManager() { 9297 return mDexManager; 9298 } 9299 9300 /** 9301 * Execute the background dexopt job immediately. 9302 */ 9303 @Override 9304 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9305 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9306 return false; 9307 } 9308 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9309 } 9310 9311 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9312 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9313 || p.usesStaticLibraries != null) { 9314 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9315 Set<String> collectedNames = new HashSet<>(); 9316 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9317 9318 retValue.remove(p); 9319 9320 return retValue; 9321 } else { 9322 return Collections.emptyList(); 9323 } 9324 } 9325 9326 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9327 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9328 if (!collectedNames.contains(p.packageName)) { 9329 collectedNames.add(p.packageName); 9330 collected.add(p); 9331 9332 if (p.usesLibraries != null) { 9333 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9334 null, collected, collectedNames); 9335 } 9336 if (p.usesOptionalLibraries != null) { 9337 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9338 null, collected, collectedNames); 9339 } 9340 if (p.usesStaticLibraries != null) { 9341 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9342 p.usesStaticLibrariesVersions, collected, collectedNames); 9343 } 9344 } 9345 } 9346 9347 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9348 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9349 final int libNameCount = libs.size(); 9350 for (int i = 0; i < libNameCount; i++) { 9351 String libName = libs.get(i); 9352 long version = (versions != null && versions.length == libNameCount) 9353 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9354 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9355 if (libPkg != null) { 9356 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9357 } 9358 } 9359 } 9360 9361 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9362 synchronized (mPackages) { 9363 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9364 if (libEntry != null) { 9365 return mPackages.get(libEntry.apk); 9366 } 9367 return null; 9368 } 9369 } 9370 9371 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9372 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9373 if (versionedLib == null) { 9374 return null; 9375 } 9376 return versionedLib.get(version); 9377 } 9378 9379 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9380 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9381 pkg.staticSharedLibName); 9382 if (versionedLib == null) { 9383 return null; 9384 } 9385 long previousLibVersion = -1; 9386 final int versionCount = versionedLib.size(); 9387 for (int i = 0; i < versionCount; i++) { 9388 final long libVersion = versionedLib.keyAt(i); 9389 if (libVersion < pkg.staticSharedLibVersion) { 9390 previousLibVersion = Math.max(previousLibVersion, libVersion); 9391 } 9392 } 9393 if (previousLibVersion >= 0) { 9394 return versionedLib.get(previousLibVersion); 9395 } 9396 return null; 9397 } 9398 9399 public void shutdown() { 9400 mPackageUsage.writeNow(mPackages); 9401 mCompilerStats.writeNow(); 9402 mDexManager.writePackageDexUsageNow(); 9403 } 9404 9405 @Override 9406 public void dumpProfiles(String packageName) { 9407 PackageParser.Package pkg; 9408 synchronized (mPackages) { 9409 pkg = mPackages.get(packageName); 9410 if (pkg == null) { 9411 throw new IllegalArgumentException("Unknown package: " + packageName); 9412 } 9413 } 9414 /* Only the shell, root, or the app user should be able to dump profiles. */ 9415 int callingUid = Binder.getCallingUid(); 9416 if (callingUid != Process.SHELL_UID && 9417 callingUid != Process.ROOT_UID && 9418 callingUid != pkg.applicationInfo.uid) { 9419 throw new SecurityException("dumpProfiles"); 9420 } 9421 9422 synchronized (mInstallLock) { 9423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9424 mArtManagerService.dumpProfiles(pkg); 9425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9426 } 9427 } 9428 9429 @Override 9430 public void forceDexOpt(String packageName) { 9431 enforceSystemOrRoot("forceDexOpt"); 9432 9433 PackageParser.Package pkg; 9434 synchronized (mPackages) { 9435 pkg = mPackages.get(packageName); 9436 if (pkg == null) { 9437 throw new IllegalArgumentException("Unknown package: " + packageName); 9438 } 9439 } 9440 9441 synchronized (mInstallLock) { 9442 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9443 9444 // Whoever is calling forceDexOpt wants a compiled package. 9445 // Don't use profiles since that may cause compilation to be skipped. 9446 final int res = performDexOptInternalWithDependenciesLI( 9447 pkg, 9448 new DexoptOptions(packageName, 9449 getDefaultCompilerFilter(), 9450 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9451 9452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9453 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9454 throw new IllegalStateException("Failed to dexopt: " + res); 9455 } 9456 } 9457 } 9458 9459 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9460 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9461 Slog.w(TAG, "Unable to update from " + oldPkg.name 9462 + " to " + newPkg.packageName 9463 + ": old package not in system partition"); 9464 return false; 9465 } else if (mPackages.get(oldPkg.name) != null) { 9466 Slog.w(TAG, "Unable to update from " + oldPkg.name 9467 + " to " + newPkg.packageName 9468 + ": old package still exists"); 9469 return false; 9470 } 9471 return true; 9472 } 9473 9474 void removeCodePathLI(File codePath) { 9475 if (codePath.isDirectory()) { 9476 try { 9477 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9478 } catch (InstallerException e) { 9479 Slog.w(TAG, "Failed to remove code path", e); 9480 } 9481 } else { 9482 codePath.delete(); 9483 } 9484 } 9485 9486 private int[] resolveUserIds(int userId) { 9487 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9488 } 9489 9490 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9491 if (pkg == null) { 9492 Slog.wtf(TAG, "Package was null!", new Throwable()); 9493 return; 9494 } 9495 clearAppDataLeafLIF(pkg, userId, flags); 9496 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9497 for (int i = 0; i < childCount; i++) { 9498 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9499 } 9500 9501 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 9502 } 9503 9504 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9505 final PackageSetting ps; 9506 synchronized (mPackages) { 9507 ps = mSettings.mPackages.get(pkg.packageName); 9508 } 9509 for (int realUserId : resolveUserIds(userId)) { 9510 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9511 try { 9512 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9513 ceDataInode); 9514 } catch (InstallerException e) { 9515 Slog.w(TAG, String.valueOf(e)); 9516 } 9517 } 9518 } 9519 9520 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9521 if (pkg == null) { 9522 Slog.wtf(TAG, "Package was null!", new Throwable()); 9523 return; 9524 } 9525 destroyAppDataLeafLIF(pkg, userId, flags); 9526 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9527 for (int i = 0; i < childCount; i++) { 9528 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9529 } 9530 } 9531 9532 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9533 final PackageSetting ps; 9534 synchronized (mPackages) { 9535 ps = mSettings.mPackages.get(pkg.packageName); 9536 } 9537 for (int realUserId : resolveUserIds(userId)) { 9538 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9539 try { 9540 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9541 ceDataInode); 9542 } catch (InstallerException e) { 9543 Slog.w(TAG, String.valueOf(e)); 9544 } 9545 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9546 } 9547 } 9548 9549 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9550 if (pkg == null) { 9551 Slog.wtf(TAG, "Package was null!", new Throwable()); 9552 return; 9553 } 9554 destroyAppProfilesLeafLIF(pkg); 9555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9556 for (int i = 0; i < childCount; i++) { 9557 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9558 } 9559 } 9560 9561 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9562 try { 9563 mInstaller.destroyAppProfiles(pkg.packageName); 9564 } catch (InstallerException e) { 9565 Slog.w(TAG, String.valueOf(e)); 9566 } 9567 } 9568 9569 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9570 if (pkg == null) { 9571 Slog.wtf(TAG, "Package was null!", new Throwable()); 9572 return; 9573 } 9574 mArtManagerService.clearAppProfiles(pkg); 9575 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9576 for (int i = 0; i < childCount; i++) { 9577 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 9578 } 9579 } 9580 9581 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9582 long lastUpdateTime) { 9583 // Set parent install/update time 9584 PackageSetting ps = (PackageSetting) pkg.mExtras; 9585 if (ps != null) { 9586 ps.firstInstallTime = firstInstallTime; 9587 ps.lastUpdateTime = lastUpdateTime; 9588 } 9589 // Set children install/update time 9590 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9591 for (int i = 0; i < childCount; i++) { 9592 PackageParser.Package childPkg = pkg.childPackages.get(i); 9593 ps = (PackageSetting) childPkg.mExtras; 9594 if (ps != null) { 9595 ps.firstInstallTime = firstInstallTime; 9596 ps.lastUpdateTime = lastUpdateTime; 9597 } 9598 } 9599 } 9600 9601 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9602 SharedLibraryEntry file, 9603 PackageParser.Package changingLib) { 9604 if (file.path != null) { 9605 usesLibraryFiles.add(file.path); 9606 return; 9607 } 9608 PackageParser.Package p = mPackages.get(file.apk); 9609 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9610 // If we are doing this while in the middle of updating a library apk, 9611 // then we need to make sure to use that new apk for determining the 9612 // dependencies here. (We haven't yet finished committing the new apk 9613 // to the package manager state.) 9614 if (p == null || p.packageName.equals(changingLib.packageName)) { 9615 p = changingLib; 9616 } 9617 } 9618 if (p != null) { 9619 usesLibraryFiles.addAll(p.getAllCodePaths()); 9620 if (p.usesLibraryFiles != null) { 9621 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9622 } 9623 } 9624 } 9625 9626 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9627 PackageParser.Package changingLib) throws PackageManagerException { 9628 if (pkg == null) { 9629 return; 9630 } 9631 // The collection used here must maintain the order of addition (so 9632 // that libraries are searched in the correct order) and must have no 9633 // duplicates. 9634 Set<String> usesLibraryFiles = null; 9635 if (pkg.usesLibraries != null) { 9636 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9637 null, null, pkg.packageName, changingLib, true, 9638 pkg.applicationInfo.targetSdkVersion, null); 9639 } 9640 if (pkg.usesStaticLibraries != null) { 9641 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9642 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9643 pkg.packageName, changingLib, true, 9644 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9645 } 9646 if (pkg.usesOptionalLibraries != null) { 9647 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9648 null, null, pkg.packageName, changingLib, false, 9649 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9650 } 9651 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9652 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9653 } else { 9654 pkg.usesLibraryFiles = null; 9655 } 9656 } 9657 9658 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9659 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9660 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9661 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9662 throws PackageManagerException { 9663 final int libCount = requestedLibraries.size(); 9664 for (int i = 0; i < libCount; i++) { 9665 final String libName = requestedLibraries.get(i); 9666 final long libVersion = requiredVersions != null ? requiredVersions[i] 9667 : SharedLibraryInfo.VERSION_UNDEFINED; 9668 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9669 if (libEntry == null) { 9670 if (required) { 9671 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9672 "Package " + packageName + " requires unavailable shared library " 9673 + libName + "; failing!"); 9674 } else if (DEBUG_SHARED_LIBRARIES) { 9675 Slog.i(TAG, "Package " + packageName 9676 + " desires unavailable shared library " 9677 + libName + "; ignoring!"); 9678 } 9679 } else { 9680 if (requiredVersions != null && requiredCertDigests != null) { 9681 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9682 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9683 "Package " + packageName + " requires unavailable static shared" 9684 + " library " + libName + " version " 9685 + libEntry.info.getLongVersion() + "; failing!"); 9686 } 9687 9688 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9689 if (libPkg == null) { 9690 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9691 "Package " + packageName + " requires unavailable static shared" 9692 + " library; failing!"); 9693 } 9694 9695 final String[] expectedCertDigests = requiredCertDigests[i]; 9696 9697 9698 if (expectedCertDigests.length > 1) { 9699 9700 // For apps targeting O MR1 we require explicit enumeration of all certs. 9701 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9702 ? PackageUtils.computeSignaturesSha256Digests( 9703 libPkg.mSigningDetails.signatures) 9704 : PackageUtils.computeSignaturesSha256Digests( 9705 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9706 9707 // Take a shortcut if sizes don't match. Note that if an app doesn't 9708 // target O we don't parse the "additional-certificate" tags similarly 9709 // how we only consider all certs only for apps targeting O (see above). 9710 // Therefore, the size check is safe to make. 9711 if (expectedCertDigests.length != libCertDigests.length) { 9712 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9713 "Package " + packageName + " requires differently signed" + 9714 " static shared library; failing!"); 9715 } 9716 9717 // Use a predictable order as signature order may vary 9718 Arrays.sort(libCertDigests); 9719 Arrays.sort(expectedCertDigests); 9720 9721 final int certCount = libCertDigests.length; 9722 for (int j = 0; j < certCount; j++) { 9723 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9724 throw new PackageManagerException( 9725 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9726 "Package " + packageName + " requires differently signed" + 9727 " static shared library; failing!"); 9728 } 9729 } 9730 } else { 9731 9732 // lib signing cert could have rotated beyond the one expected, check to see 9733 // if the new one has been blessed by the old 9734 if (!libPkg.mSigningDetails.hasSha256Certificate( 9735 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 9736 throw new PackageManagerException( 9737 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9738 "Package " + packageName + " requires differently signed" + 9739 " static shared library; failing!"); 9740 } 9741 } 9742 } 9743 9744 if (outUsedLibraries == null) { 9745 // Use LinkedHashSet to preserve the order of files added to 9746 // usesLibraryFiles while eliminating duplicates. 9747 outUsedLibraries = new LinkedHashSet<>(); 9748 } 9749 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9750 } 9751 } 9752 return outUsedLibraries; 9753 } 9754 9755 private static boolean hasString(List<String> list, List<String> which) { 9756 if (list == null) { 9757 return false; 9758 } 9759 for (int i=list.size()-1; i>=0; i--) { 9760 for (int j=which.size()-1; j>=0; j--) { 9761 if (which.get(j).equals(list.get(i))) { 9762 return true; 9763 } 9764 } 9765 } 9766 return false; 9767 } 9768 9769 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9770 PackageParser.Package changingPkg) { 9771 ArrayList<PackageParser.Package> res = null; 9772 for (PackageParser.Package pkg : mPackages.values()) { 9773 if (changingPkg != null 9774 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9775 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9776 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9777 changingPkg.staticSharedLibName)) { 9778 return null; 9779 } 9780 if (res == null) { 9781 res = new ArrayList<>(); 9782 } 9783 res.add(pkg); 9784 try { 9785 updateSharedLibrariesLPr(pkg, changingPkg); 9786 } catch (PackageManagerException e) { 9787 // If a system app update or an app and a required lib missing we 9788 // delete the package and for updated system apps keep the data as 9789 // it is better for the user to reinstall than to be in an limbo 9790 // state. Also libs disappearing under an app should never happen 9791 // - just in case. 9792 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9793 final int flags = pkg.isUpdatedSystemApp() 9794 ? PackageManager.DELETE_KEEP_DATA : 0; 9795 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9796 flags , null, true, null); 9797 } 9798 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9799 } 9800 } 9801 return res; 9802 } 9803 9804 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9805 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9806 @Nullable UserHandle user) throws PackageManagerException { 9807 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9808 // If the package has children and this is the first dive in the function 9809 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9810 // whether all packages (parent and children) would be successfully scanned 9811 // before the actual scan since scanning mutates internal state and we want 9812 // to atomically install the package and its children. 9813 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9814 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9815 scanFlags |= SCAN_CHECK_ONLY; 9816 } 9817 } else { 9818 scanFlags &= ~SCAN_CHECK_ONLY; 9819 } 9820 9821 final PackageParser.Package scannedPkg; 9822 try { 9823 // Scan the parent 9824 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9825 // Scan the children 9826 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9827 for (int i = 0; i < childCount; i++) { 9828 PackageParser.Package childPkg = pkg.childPackages.get(i); 9829 scanPackageNewLI(childPkg, parseFlags, 9830 scanFlags, currentTime, user); 9831 } 9832 } finally { 9833 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9834 } 9835 9836 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9837 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9838 } 9839 9840 return scannedPkg; 9841 } 9842 9843 /** The result of a package scan. */ 9844 private static class ScanResult { 9845 /** Whether or not the package scan was successful */ 9846 public final boolean success; 9847 /** 9848 * The final package settings. This may be the same object passed in 9849 * the {@link ScanRequest}, but, with modified values. 9850 */ 9851 @Nullable public final PackageSetting pkgSetting; 9852 /** ABI code paths that have changed in the package scan */ 9853 @Nullable public final List<String> changedAbiCodePath; 9854 public ScanResult( 9855 boolean success, 9856 @Nullable PackageSetting pkgSetting, 9857 @Nullable List<String> changedAbiCodePath) { 9858 this.success = success; 9859 this.pkgSetting = pkgSetting; 9860 this.changedAbiCodePath = changedAbiCodePath; 9861 } 9862 } 9863 9864 /** A package to be scanned */ 9865 private static class ScanRequest { 9866 /** The parsed package */ 9867 @NonNull public final PackageParser.Package pkg; 9868 /** Shared user settings, if the package has a shared user */ 9869 @Nullable public final SharedUserSetting sharedUserSetting; 9870 /** 9871 * Package settings of the currently installed version. 9872 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9873 * during scan. 9874 */ 9875 @Nullable public final PackageSetting pkgSetting; 9876 /** A copy of the settings for the currently installed version */ 9877 @Nullable public final PackageSetting oldPkgSetting; 9878 /** Package settings for the disabled version on the /system partition */ 9879 @Nullable public final PackageSetting disabledPkgSetting; 9880 /** Package settings for the installed version under its original package name */ 9881 @Nullable public final PackageSetting originalPkgSetting; 9882 /** The real package name of a renamed application */ 9883 @Nullable public final String realPkgName; 9884 public final @ParseFlags int parseFlags; 9885 public final @ScanFlags int scanFlags; 9886 /** The user for which the package is being scanned */ 9887 @Nullable public final UserHandle user; 9888 /** Whether or not the platform package is being scanned */ 9889 public final boolean isPlatformPackage; 9890 public ScanRequest( 9891 @NonNull PackageParser.Package pkg, 9892 @Nullable SharedUserSetting sharedUserSetting, 9893 @Nullable PackageSetting pkgSetting, 9894 @Nullable PackageSetting disabledPkgSetting, 9895 @Nullable PackageSetting originalPkgSetting, 9896 @Nullable String realPkgName, 9897 @ParseFlags int parseFlags, 9898 @ScanFlags int scanFlags, 9899 boolean isPlatformPackage, 9900 @Nullable UserHandle user) { 9901 this.pkg = pkg; 9902 this.pkgSetting = pkgSetting; 9903 this.sharedUserSetting = sharedUserSetting; 9904 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9905 this.disabledPkgSetting = disabledPkgSetting; 9906 this.originalPkgSetting = originalPkgSetting; 9907 this.realPkgName = realPkgName; 9908 this.parseFlags = parseFlags; 9909 this.scanFlags = scanFlags; 9910 this.isPlatformPackage = isPlatformPackage; 9911 this.user = user; 9912 } 9913 } 9914 9915 /** 9916 * Returns the actual scan flags depending upon the state of the other settings. 9917 * <p>Updated system applications will not have the following flags set 9918 * by default and need to be adjusted after the fact: 9919 * <ul> 9920 * <li>{@link #SCAN_AS_SYSTEM}</li> 9921 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9922 * <li>{@link #SCAN_AS_OEM}</li> 9923 * <li>{@link #SCAN_AS_VENDOR}</li> 9924 * <li>{@link #SCAN_AS_PRODUCT}</li> 9925 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9926 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9927 * </ul> 9928 */ 9929 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9930 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9931 PackageParser.Package pkg) { 9932 if (disabledPkgSetting != null) { 9933 // updated system application, must at least have SCAN_AS_SYSTEM 9934 scanFlags |= SCAN_AS_SYSTEM; 9935 if ((disabledPkgSetting.pkgPrivateFlags 9936 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9937 scanFlags |= SCAN_AS_PRIVILEGED; 9938 } 9939 if ((disabledPkgSetting.pkgPrivateFlags 9940 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9941 scanFlags |= SCAN_AS_OEM; 9942 } 9943 if ((disabledPkgSetting.pkgPrivateFlags 9944 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9945 scanFlags |= SCAN_AS_VENDOR; 9946 } 9947 if ((disabledPkgSetting.pkgPrivateFlags 9948 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9949 scanFlags |= SCAN_AS_PRODUCT; 9950 } 9951 } 9952 if (pkgSetting != null) { 9953 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9954 if (pkgSetting.getInstantApp(userId)) { 9955 scanFlags |= SCAN_AS_INSTANT_APP; 9956 } 9957 if (pkgSetting.getVirtulalPreload(userId)) { 9958 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9959 } 9960 } 9961 9962 // Scan as privileged apps that share a user with a priv-app. 9963 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9964 && (pkg.mSharedUserId != null)) { 9965 SharedUserSetting sharedUserSetting = null; 9966 try { 9967 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9968 } catch (PackageManagerException ignore) {} 9969 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9970 // Exempt SharedUsers signed with the platform key. 9971 // TODO(b/72378145) Fix this exemption. Force signature apps 9972 // to whitelist their privileged permissions just like other 9973 // priv-apps. 9974 synchronized (mPackages) { 9975 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9976 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9977 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9978 scanFlags |= SCAN_AS_PRIVILEGED; 9979 } 9980 } 9981 } 9982 } 9983 9984 return scanFlags; 9985 } 9986 9987 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 9988 // the results / removing app data needs to be moved up a level to the callers of this 9989 // method. Also, we need to solve the problem of potentially creating a new shared user 9990 // setting. That can probably be done later and patch things up after the fact. 9991 @GuardedBy("mInstallLock") 9992 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9993 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9994 @Nullable UserHandle user) throws PackageManagerException { 9995 9996 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9997 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9998 if (realPkgName != null) { 9999 ensurePackageRenamed(pkg, renamedPkgName); 10000 } 10001 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10002 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10003 final PackageSetting disabledPkgSetting = 10004 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10005 10006 if (mTransferedPackages.contains(pkg.packageName)) { 10007 Slog.w(TAG, "Package " + pkg.packageName 10008 + " was transferred to another, but its .apk remains"); 10009 } 10010 10011 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10012 synchronized (mPackages) { 10013 applyPolicy(pkg, parseFlags, scanFlags); 10014 assertPackageIsValid(pkg, parseFlags, scanFlags); 10015 10016 SharedUserSetting sharedUserSetting = null; 10017 if (pkg.mSharedUserId != null) { 10018 // SIDE EFFECTS; may potentially allocate a new shared user 10019 sharedUserSetting = mSettings.getSharedUserLPw( 10020 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10021 if (DEBUG_PACKAGE_SCANNING) { 10022 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10023 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10024 + " (uid=" + sharedUserSetting.userId + "):" 10025 + " packages=" + sharedUserSetting.packages); 10026 } 10027 } 10028 10029 boolean scanSucceeded = false; 10030 try { 10031 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 10032 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 10033 (pkg == mPlatformPackage), user); 10034 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 10035 if (result.success) { 10036 commitScanResultsLocked(request, result); 10037 } 10038 scanSucceeded = true; 10039 } finally { 10040 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10041 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10042 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10043 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10044 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10045 } 10046 } 10047 } 10048 return pkg; 10049 } 10050 10051 /** 10052 * Commits the package scan and modifies system state. 10053 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10054 * of committing the package, leaving the system in an inconsistent state. 10055 * This needs to be fixed so, once we get to this point, no errors are 10056 * possible and the system is not left in an inconsistent state. 10057 */ 10058 @GuardedBy("mPackages") 10059 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10060 throws PackageManagerException { 10061 final PackageParser.Package pkg = request.pkg; 10062 final @ParseFlags int parseFlags = request.parseFlags; 10063 final @ScanFlags int scanFlags = request.scanFlags; 10064 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10065 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10066 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10067 final UserHandle user = request.user; 10068 final String realPkgName = request.realPkgName; 10069 final PackageSetting pkgSetting = result.pkgSetting; 10070 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10071 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10072 10073 if (newPkgSettingCreated) { 10074 if (originalPkgSetting != null) { 10075 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10076 } 10077 // THROWS: when we can't allocate a user id. add call to check if there's 10078 // enough space to ensure we won't throw; otherwise, don't modify state 10079 mSettings.addUserToSettingLPw(pkgSetting); 10080 10081 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10082 mTransferedPackages.add(originalPkgSetting.name); 10083 } 10084 } 10085 // TODO(toddke): Consider a method specifically for modifying the Package object 10086 // post scan; or, moving this stuff out of the Package object since it has nothing 10087 // to do with the package on disk. 10088 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10089 // for creating the application ID. If we did this earlier, we would be saving the 10090 // correct ID. 10091 pkg.applicationInfo.uid = pkgSetting.appId; 10092 10093 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10094 10095 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10096 mTransferedPackages.add(pkg.packageName); 10097 } 10098 10099 // THROWS: when requested libraries that can't be found. it only changes 10100 // the state of the passed in pkg object, so, move to the top of the method 10101 // and allow it to abort 10102 if ((scanFlags & SCAN_BOOTING) == 0 10103 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10104 // Check all shared libraries and map to their actual file path. 10105 // We only do this here for apps not on a system dir, because those 10106 // are the only ones that can fail an install due to this. We 10107 // will take care of the system apps by updating all of their 10108 // library paths after the scan is done. Also during the initial 10109 // scan don't update any libs as we do this wholesale after all 10110 // apps are scanned to avoid dependency based scanning. 10111 updateSharedLibrariesLPr(pkg, null); 10112 } 10113 10114 // All versions of a static shared library are referenced with the same 10115 // package name. Internally, we use a synthetic package name to allow 10116 // multiple versions of the same shared library to be installed. So, 10117 // we need to generate the synthetic package name of the latest shared 10118 // library in order to compare signatures. 10119 PackageSetting signatureCheckPs = pkgSetting; 10120 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10121 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10122 if (libraryEntry != null) { 10123 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10124 } 10125 } 10126 10127 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10128 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10129 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10130 // We just determined the app is signed correctly, so bring 10131 // over the latest parsed certs. 10132 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10133 } else { 10134 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10135 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10136 "Package " + pkg.packageName + " upgrade keys do not match the " 10137 + "previously installed version"); 10138 } else { 10139 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10140 String msg = "System package " + pkg.packageName 10141 + " signature changed; retaining data."; 10142 reportSettingsProblem(Log.WARN, msg); 10143 } 10144 } 10145 } else { 10146 try { 10147 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10148 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10149 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10150 pkg.mSigningDetails, compareCompat, compareRecover); 10151 // The new KeySets will be re-added later in the scanning process. 10152 if (compatMatch) { 10153 synchronized (mPackages) { 10154 ksms.removeAppKeySetDataLPw(pkg.packageName); 10155 } 10156 } 10157 // We just determined the app is signed correctly, so bring 10158 // over the latest parsed certs. 10159 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10160 10161 10162 // if this is is a sharedUser, check to see if the new package is signed by a newer 10163 // signing certificate than the existing one, and if so, copy over the new details 10164 if (signatureCheckPs.sharedUser != null 10165 && pkg.mSigningDetails.hasAncestor( 10166 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 10167 signatureCheckPs.sharedUser.signatures.mSigningDetails = pkg.mSigningDetails; 10168 } 10169 } catch (PackageManagerException e) { 10170 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10171 throw e; 10172 } 10173 // The signature has changed, but this package is in the system 10174 // image... let's recover! 10175 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10176 // However... if this package is part of a shared user, but it 10177 // doesn't match the signature of the shared user, let's fail. 10178 // What this means is that you can't change the signatures 10179 // associated with an overall shared user, which doesn't seem all 10180 // that unreasonable. 10181 if (signatureCheckPs.sharedUser != null) { 10182 if (compareSignatures( 10183 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10184 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10185 throw new PackageManagerException( 10186 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10187 "Signature mismatch for shared user: " 10188 + pkgSetting.sharedUser); 10189 } 10190 } 10191 // File a report about this. 10192 String msg = "System package " + pkg.packageName 10193 + " signature changed; retaining data."; 10194 reportSettingsProblem(Log.WARN, msg); 10195 } catch (IllegalArgumentException e) { 10196 10197 // should never happen: certs matched when checking, but not when comparing 10198 // old to new for sharedUser 10199 throw new PackageManagerException(INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10200 "Signing certificates comparison made on incomparable signing details" 10201 + " but somehow passed verifySignatures!"); 10202 } 10203 } 10204 10205 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10206 // This package wants to adopt ownership of permissions from 10207 // another package. 10208 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10209 final String origName = pkg.mAdoptPermissions.get(i); 10210 final PackageSetting orig = mSettings.getPackageLPr(origName); 10211 if (orig != null) { 10212 if (verifyPackageUpdateLPr(orig, pkg)) { 10213 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10214 + pkg.packageName); 10215 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10216 } 10217 } 10218 } 10219 } 10220 10221 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10222 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10223 final String codePathString = changedAbiCodePath.get(i); 10224 try { 10225 mInstaller.rmdex(codePathString, 10226 getDexCodeInstructionSet(getPreferredInstructionSet())); 10227 } catch (InstallerException ignored) { 10228 } 10229 } 10230 } 10231 10232 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10233 if (oldPkgSetting != null) { 10234 synchronized (mPackages) { 10235 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10236 } 10237 } 10238 } else { 10239 final int userId = user == null ? 0 : user.getIdentifier(); 10240 // Modify state for the given package setting 10241 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10242 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10243 if (pkgSetting.getInstantApp(userId)) { 10244 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10245 } 10246 } 10247 } 10248 10249 /** 10250 * Returns the "real" name of the package. 10251 * <p>This may differ from the package's actual name if the application has already 10252 * been installed under one of this package's original names. 10253 */ 10254 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10255 @Nullable String renamedPkgName) { 10256 if (isPackageRenamed(pkg, renamedPkgName)) { 10257 return pkg.mRealPackage; 10258 } 10259 return null; 10260 } 10261 10262 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10263 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10264 @Nullable String renamedPkgName) { 10265 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10266 } 10267 10268 /** 10269 * Returns the original package setting. 10270 * <p>A package can migrate its name during an update. In this scenario, a package 10271 * designates a set of names that it considers as one of its original names. 10272 * <p>An original package must be signed identically and it must have the same 10273 * shared user [if any]. 10274 */ 10275 @GuardedBy("mPackages") 10276 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10277 @Nullable String renamedPkgName) { 10278 if (!isPackageRenamed(pkg, renamedPkgName)) { 10279 return null; 10280 } 10281 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10282 final PackageSetting originalPs = 10283 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10284 if (originalPs != null) { 10285 // the package is already installed under its original name... 10286 // but, should we use it? 10287 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10288 // the new package is incompatible with the original 10289 continue; 10290 } else if (originalPs.sharedUser != null) { 10291 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10292 // the shared user id is incompatible with the original 10293 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10294 + " to " + pkg.packageName + ": old uid " 10295 + originalPs.sharedUser.name 10296 + " differs from " + pkg.mSharedUserId); 10297 continue; 10298 } 10299 // TODO: Add case when shared user id is added [b/28144775] 10300 } else { 10301 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10302 + pkg.packageName + " to old name " + originalPs.name); 10303 } 10304 return originalPs; 10305 } 10306 } 10307 return null; 10308 } 10309 10310 /** 10311 * Renames the package if it was installed under a different name. 10312 * <p>When we've already installed the package under an original name, update 10313 * the new package so we can continue to have the old name. 10314 */ 10315 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10316 @NonNull String renamedPackageName) { 10317 if (pkg.mOriginalPackages == null 10318 || !pkg.mOriginalPackages.contains(renamedPackageName) 10319 || pkg.packageName.equals(renamedPackageName)) { 10320 return; 10321 } 10322 pkg.setPackageName(renamedPackageName); 10323 } 10324 10325 /** 10326 * Just scans the package without any side effects. 10327 * <p>Not entirely true at the moment. There is still one side effect -- this 10328 * method potentially modifies a live {@link PackageSetting} object representing 10329 * the package being scanned. This will be resolved in the future. 10330 * 10331 * @param request Information about the package to be scanned 10332 * @param isUnderFactoryTest Whether or not the device is under factory test 10333 * @param currentTime The current time, in millis 10334 * @return The results of the scan 10335 */ 10336 @GuardedBy("mInstallLock") 10337 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10338 boolean isUnderFactoryTest, long currentTime) 10339 throws PackageManagerException { 10340 final PackageParser.Package pkg = request.pkg; 10341 PackageSetting pkgSetting = request.pkgSetting; 10342 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10343 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10344 final @ParseFlags int parseFlags = request.parseFlags; 10345 final @ScanFlags int scanFlags = request.scanFlags; 10346 final String realPkgName = request.realPkgName; 10347 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10348 final UserHandle user = request.user; 10349 final boolean isPlatformPackage = request.isPlatformPackage; 10350 10351 List<String> changedAbiCodePath = null; 10352 10353 if (DEBUG_PACKAGE_SCANNING) { 10354 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10355 Log.d(TAG, "Scanning package " + pkg.packageName); 10356 } 10357 10358 if (Build.IS_DEBUGGABLE && 10359 pkg.isPrivileged() && 10360 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10361 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10362 } 10363 10364 // Initialize package source and resource directories 10365 final File scanFile = new File(pkg.codePath); 10366 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10367 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10368 10369 // We keep references to the derived CPU Abis from settings in oder to reuse 10370 // them in the case where we're not upgrading or booting for the first time. 10371 String primaryCpuAbiFromSettings = null; 10372 String secondaryCpuAbiFromSettings = null; 10373 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10374 10375 if (!needToDeriveAbi) { 10376 if (pkgSetting != null) { 10377 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10378 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10379 } else { 10380 // Re-scanning a system package after uninstalling updates; need to derive ABI 10381 needToDeriveAbi = true; 10382 } 10383 } 10384 10385 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10386 PackageManagerService.reportSettingsProblem(Log.WARN, 10387 "Package " + pkg.packageName + " shared user changed from " 10388 + (pkgSetting.sharedUser != null 10389 ? pkgSetting.sharedUser.name : "<nothing>") 10390 + " to " 10391 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10392 + "; replacing with new"); 10393 pkgSetting = null; 10394 } 10395 10396 String[] usesStaticLibraries = null; 10397 if (pkg.usesStaticLibraries != null) { 10398 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10399 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10400 } 10401 final boolean createNewPackage = (pkgSetting == null); 10402 if (createNewPackage) { 10403 final String parentPackageName = (pkg.parentPackage != null) 10404 ? pkg.parentPackage.packageName : null; 10405 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10406 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10407 // REMOVE SharedUserSetting from method; update in a separate call 10408 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10409 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10410 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10411 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10412 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10413 user, true /*allowInstall*/, instantApp, virtualPreload, 10414 parentPackageName, pkg.getChildPackageNames(), 10415 UserManagerService.getInstance(), usesStaticLibraries, 10416 pkg.usesStaticLibrariesVersions); 10417 } else { 10418 // REMOVE SharedUserSetting from method; update in a separate call. 10419 // 10420 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10421 // secondaryCpuAbi are not known at this point so we always update them 10422 // to null here, only to reset them at a later point. 10423 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10424 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10425 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10426 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10427 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10428 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10429 } 10430 if (createNewPackage && originalPkgSetting != null) { 10431 // This is the initial transition from the original package, so, 10432 // fix up the new package's name now. We must do this after looking 10433 // up the package under its new name, so getPackageLP takes care of 10434 // fiddling things correctly. 10435 pkg.setPackageName(originalPkgSetting.name); 10436 10437 // File a report about this. 10438 String msg = "New package " + pkgSetting.realName 10439 + " renamed to replace old package " + pkgSetting.name; 10440 reportSettingsProblem(Log.WARN, msg); 10441 } 10442 10443 if (disabledPkgSetting != null) { 10444 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10445 } 10446 10447 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 10448 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 10449 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 10450 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 10451 // least restrictive selinux domain. 10452 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 10453 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 10454 // ensures that all packages continue to run in the same selinux domain. 10455 final int targetSdkVersion = 10456 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 10457 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 10458 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 10459 // They currently can be if the sharedUser apps are signed with the platform key. 10460 final boolean isPrivileged = (sharedUserSetting != null) ? 10461 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 10462 10463 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 10464 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 10465 10466 pkg.mExtras = pkgSetting; 10467 pkg.applicationInfo.processName = fixProcessName( 10468 pkg.applicationInfo.packageName, 10469 pkg.applicationInfo.processName); 10470 10471 if (!isPlatformPackage) { 10472 // Get all of our default paths setup 10473 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10474 } 10475 10476 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10477 10478 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10479 if (needToDeriveAbi) { 10480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10481 final boolean extractNativeLibs = !pkg.isLibrary(); 10482 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10483 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10484 10485 // Some system apps still use directory structure for native libraries 10486 // in which case we might end up not detecting abi solely based on apk 10487 // structure. Try to detect abi based on directory structure. 10488 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10489 pkg.applicationInfo.primaryCpuAbi == null) { 10490 setBundledAppAbisAndRoots(pkg, pkgSetting); 10491 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10492 } 10493 } else { 10494 // This is not a first boot or an upgrade, don't bother deriving the 10495 // ABI during the scan. Instead, trust the value that was stored in the 10496 // package setting. 10497 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10498 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10499 10500 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10501 10502 if (DEBUG_ABI_SELECTION) { 10503 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10504 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10505 pkg.applicationInfo.secondaryCpuAbi); 10506 } 10507 } 10508 } else { 10509 if ((scanFlags & SCAN_MOVE) != 0) { 10510 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10511 // but we already have this packages package info in the PackageSetting. We just 10512 // use that and derive the native library path based on the new codepath. 10513 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10514 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10515 } 10516 10517 // Set native library paths again. For moves, the path will be updated based on the 10518 // ABIs we've determined above. For non-moves, the path will be updated based on the 10519 // ABIs we determined during compilation, but the path will depend on the final 10520 // package path (after the rename away from the stage path). 10521 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10522 } 10523 10524 // This is a special case for the "system" package, where the ABI is 10525 // dictated by the zygote configuration (and init.rc). We should keep track 10526 // of this ABI so that we can deal with "normal" applications that run under 10527 // the same UID correctly. 10528 if (isPlatformPackage) { 10529 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10530 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10531 } 10532 10533 // If there's a mismatch between the abi-override in the package setting 10534 // and the abiOverride specified for the install. Warn about this because we 10535 // would've already compiled the app without taking the package setting into 10536 // account. 10537 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10538 if (cpuAbiOverride == null && pkg.packageName != null) { 10539 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10540 " for package " + pkg.packageName); 10541 } 10542 } 10543 10544 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10545 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10546 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10547 10548 // Copy the derived override back to the parsed package, so that we can 10549 // update the package settings accordingly. 10550 pkg.cpuAbiOverride = cpuAbiOverride; 10551 10552 if (DEBUG_ABI_SELECTION) { 10553 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10554 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10555 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10556 } 10557 10558 // Push the derived path down into PackageSettings so we know what to 10559 // clean up at uninstall time. 10560 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10561 10562 if (DEBUG_ABI_SELECTION) { 10563 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10564 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10565 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10566 } 10567 10568 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10569 // We don't do this here during boot because we can do it all 10570 // at once after scanning all existing packages. 10571 // 10572 // We also do this *before* we perform dexopt on this package, so that 10573 // we can avoid redundant dexopts, and also to make sure we've got the 10574 // code and package path correct. 10575 changedAbiCodePath = 10576 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10577 } 10578 10579 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10580 android.Manifest.permission.FACTORY_TEST)) { 10581 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10582 } 10583 10584 if (isSystemApp(pkg)) { 10585 pkgSetting.isOrphaned = true; 10586 } 10587 10588 // Take care of first install / last update times. 10589 final long scanFileTime = getLastModifiedTime(pkg); 10590 if (currentTime != 0) { 10591 if (pkgSetting.firstInstallTime == 0) { 10592 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10593 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10594 pkgSetting.lastUpdateTime = currentTime; 10595 } 10596 } else if (pkgSetting.firstInstallTime == 0) { 10597 // We need *something*. Take time time stamp of the file. 10598 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10599 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10600 if (scanFileTime != pkgSetting.timeStamp) { 10601 // A package on the system image has changed; consider this 10602 // to be an update. 10603 pkgSetting.lastUpdateTime = scanFileTime; 10604 } 10605 } 10606 pkgSetting.setTimeStamp(scanFileTime); 10607 10608 pkgSetting.pkg = pkg; 10609 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10610 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10611 pkgSetting.versionCode = pkg.getLongVersionCode(); 10612 } 10613 // Update volume if needed 10614 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10615 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10616 Slog.i(PackageManagerService.TAG, 10617 "Update" + (pkgSetting.isSystem() ? " system" : "") 10618 + " package " + pkg.packageName 10619 + " volume from " + pkgSetting.volumeUuid 10620 + " to " + volumeUuid); 10621 pkgSetting.volumeUuid = volumeUuid; 10622 } 10623 10624 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10625 } 10626 10627 /** 10628 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10629 */ 10630 private static boolean apkHasCode(String fileName) { 10631 StrictJarFile jarFile = null; 10632 try { 10633 jarFile = new StrictJarFile(fileName, 10634 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10635 return jarFile.findEntry("classes.dex") != null; 10636 } catch (IOException ignore) { 10637 } finally { 10638 try { 10639 if (jarFile != null) { 10640 jarFile.close(); 10641 } 10642 } catch (IOException ignore) {} 10643 } 10644 return false; 10645 } 10646 10647 /** 10648 * Enforces code policy for the package. This ensures that if an APK has 10649 * declared hasCode="true" in its manifest that the APK actually contains 10650 * code. 10651 * 10652 * @throws PackageManagerException If bytecode could not be found when it should exist 10653 */ 10654 private static void assertCodePolicy(PackageParser.Package pkg) 10655 throws PackageManagerException { 10656 final boolean shouldHaveCode = 10657 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10658 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10659 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10660 "Package " + pkg.baseCodePath + " code is missing"); 10661 } 10662 10663 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10664 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10665 final boolean splitShouldHaveCode = 10666 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10667 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10668 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10669 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10670 } 10671 } 10672 } 10673 } 10674 10675 /** 10676 * Applies policy to the parsed package based upon the given policy flags. 10677 * Ensures the package is in a good state. 10678 * <p> 10679 * Implementation detail: This method must NOT have any side effect. It would 10680 * ideally be static, but, it requires locks to read system state. 10681 */ 10682 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10683 final @ScanFlags int scanFlags) { 10684 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10685 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10686 if (pkg.applicationInfo.isDirectBootAware()) { 10687 // we're direct boot aware; set for all components 10688 for (PackageParser.Service s : pkg.services) { 10689 s.info.encryptionAware = s.info.directBootAware = true; 10690 } 10691 for (PackageParser.Provider p : pkg.providers) { 10692 p.info.encryptionAware = p.info.directBootAware = true; 10693 } 10694 for (PackageParser.Activity a : pkg.activities) { 10695 a.info.encryptionAware = a.info.directBootAware = true; 10696 } 10697 for (PackageParser.Activity r : pkg.receivers) { 10698 r.info.encryptionAware = r.info.directBootAware = true; 10699 } 10700 } 10701 if (compressedFileExists(pkg.codePath)) { 10702 pkg.isStub = true; 10703 } 10704 } else { 10705 // non system apps can't be flagged as core 10706 pkg.coreApp = false; 10707 // clear flags not applicable to regular apps 10708 pkg.applicationInfo.flags &= 10709 ~ApplicationInfo.FLAG_PERSISTENT; 10710 pkg.applicationInfo.privateFlags &= 10711 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10712 pkg.applicationInfo.privateFlags &= 10713 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10714 // cap permission priorities 10715 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10716 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10717 pkg.permissionGroups.get(i).info.priority = 0; 10718 } 10719 } 10720 } 10721 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10722 // clear protected broadcasts 10723 pkg.protectedBroadcasts = null; 10724 // ignore export request for single user receivers 10725 if (pkg.receivers != null) { 10726 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10727 final PackageParser.Activity receiver = pkg.receivers.get(i); 10728 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10729 receiver.info.exported = false; 10730 } 10731 } 10732 } 10733 // ignore export request for single user services 10734 if (pkg.services != null) { 10735 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10736 final PackageParser.Service service = pkg.services.get(i); 10737 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10738 service.info.exported = false; 10739 } 10740 } 10741 } 10742 // ignore export request for single user providers 10743 if (pkg.providers != null) { 10744 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10745 final PackageParser.Provider provider = pkg.providers.get(i); 10746 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10747 provider.info.exported = false; 10748 } 10749 } 10750 } 10751 } 10752 10753 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10754 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10755 } 10756 10757 if ((scanFlags & SCAN_AS_OEM) != 0) { 10758 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10759 } 10760 10761 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10762 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10763 } 10764 10765 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10766 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10767 } 10768 10769 if (!isSystemApp(pkg)) { 10770 // Only system apps can use these features. 10771 pkg.mOriginalPackages = null; 10772 pkg.mRealPackage = null; 10773 pkg.mAdoptPermissions = null; 10774 } 10775 } 10776 10777 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10778 throws PackageManagerException { 10779 if (object == null) { 10780 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10781 } 10782 return object; 10783 } 10784 10785 /** 10786 * Asserts the parsed package is valid according to the given policy. If the 10787 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10788 * <p> 10789 * Implementation detail: This method must NOT have any side effects. It would 10790 * ideally be static, but, it requires locks to read system state. 10791 * 10792 * @throws PackageManagerException If the package fails any of the validation checks 10793 */ 10794 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10795 final @ScanFlags int scanFlags) 10796 throws PackageManagerException { 10797 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10798 assertCodePolicy(pkg); 10799 } 10800 10801 if (pkg.applicationInfo.getCodePath() == null || 10802 pkg.applicationInfo.getResourcePath() == null) { 10803 // Bail out. The resource and code paths haven't been set. 10804 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10805 "Code and resource paths haven't been set correctly"); 10806 } 10807 10808 // Make sure we're not adding any bogus keyset info 10809 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10810 ksms.assertScannedPackageValid(pkg); 10811 10812 synchronized (mPackages) { 10813 // The special "android" package can only be defined once 10814 if (pkg.packageName.equals("android")) { 10815 if (mAndroidApplication != null) { 10816 Slog.w(TAG, "*************************************************"); 10817 Slog.w(TAG, "Core android package being redefined. Skipping."); 10818 Slog.w(TAG, " codePath=" + pkg.codePath); 10819 Slog.w(TAG, "*************************************************"); 10820 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10821 "Core android package being redefined. Skipping."); 10822 } 10823 } 10824 10825 // A package name must be unique; don't allow duplicates 10826 if (mPackages.containsKey(pkg.packageName)) { 10827 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10828 "Application package " + pkg.packageName 10829 + " already installed. Skipping duplicate."); 10830 } 10831 10832 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10833 // Static libs have a synthetic package name containing the version 10834 // but we still want the base name to be unique. 10835 if (mPackages.containsKey(pkg.manifestPackageName)) { 10836 throw new PackageManagerException( 10837 "Duplicate static shared lib provider package"); 10838 } 10839 10840 // Static shared libraries should have at least O target SDK 10841 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10842 throw new PackageManagerException( 10843 "Packages declaring static-shared libs must target O SDK or higher"); 10844 } 10845 10846 // Package declaring static a shared lib cannot be instant apps 10847 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10848 throw new PackageManagerException( 10849 "Packages declaring static-shared libs cannot be instant apps"); 10850 } 10851 10852 // Package declaring static a shared lib cannot be renamed since the package 10853 // name is synthetic and apps can't code around package manager internals. 10854 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10855 throw new PackageManagerException( 10856 "Packages declaring static-shared libs cannot be renamed"); 10857 } 10858 10859 // Package declaring static a shared lib cannot declare child packages 10860 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10861 throw new PackageManagerException( 10862 "Packages declaring static-shared libs cannot have child packages"); 10863 } 10864 10865 // Package declaring static a shared lib cannot declare dynamic libs 10866 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10867 throw new PackageManagerException( 10868 "Packages declaring static-shared libs cannot declare dynamic libs"); 10869 } 10870 10871 // Package declaring static a shared lib cannot declare shared users 10872 if (pkg.mSharedUserId != null) { 10873 throw new PackageManagerException( 10874 "Packages declaring static-shared libs cannot declare shared users"); 10875 } 10876 10877 // Static shared libs cannot declare activities 10878 if (!pkg.activities.isEmpty()) { 10879 throw new PackageManagerException( 10880 "Static shared libs cannot declare activities"); 10881 } 10882 10883 // Static shared libs cannot declare services 10884 if (!pkg.services.isEmpty()) { 10885 throw new PackageManagerException( 10886 "Static shared libs cannot declare services"); 10887 } 10888 10889 // Static shared libs cannot declare providers 10890 if (!pkg.providers.isEmpty()) { 10891 throw new PackageManagerException( 10892 "Static shared libs cannot declare content providers"); 10893 } 10894 10895 // Static shared libs cannot declare receivers 10896 if (!pkg.receivers.isEmpty()) { 10897 throw new PackageManagerException( 10898 "Static shared libs cannot declare broadcast receivers"); 10899 } 10900 10901 // Static shared libs cannot declare permission groups 10902 if (!pkg.permissionGroups.isEmpty()) { 10903 throw new PackageManagerException( 10904 "Static shared libs cannot declare permission groups"); 10905 } 10906 10907 // Static shared libs cannot declare permissions 10908 if (!pkg.permissions.isEmpty()) { 10909 throw new PackageManagerException( 10910 "Static shared libs cannot declare permissions"); 10911 } 10912 10913 // Static shared libs cannot declare protected broadcasts 10914 if (pkg.protectedBroadcasts != null) { 10915 throw new PackageManagerException( 10916 "Static shared libs cannot declare protected broadcasts"); 10917 } 10918 10919 // Static shared libs cannot be overlay targets 10920 if (pkg.mOverlayTarget != null) { 10921 throw new PackageManagerException( 10922 "Static shared libs cannot be overlay targets"); 10923 } 10924 10925 // The version codes must be ordered as lib versions 10926 long minVersionCode = Long.MIN_VALUE; 10927 long maxVersionCode = Long.MAX_VALUE; 10928 10929 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10930 pkg.staticSharedLibName); 10931 if (versionedLib != null) { 10932 final int versionCount = versionedLib.size(); 10933 for (int i = 0; i < versionCount; i++) { 10934 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10935 final long libVersionCode = libInfo.getDeclaringPackage() 10936 .getLongVersionCode(); 10937 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10938 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10939 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10940 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10941 } else { 10942 minVersionCode = maxVersionCode = libVersionCode; 10943 break; 10944 } 10945 } 10946 } 10947 if (pkg.getLongVersionCode() < minVersionCode 10948 || pkg.getLongVersionCode() > maxVersionCode) { 10949 throw new PackageManagerException("Static shared" 10950 + " lib version codes must be ordered as lib versions"); 10951 } 10952 } 10953 10954 // Only privileged apps and updated privileged apps can add child packages. 10955 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10956 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10957 throw new PackageManagerException("Only privileged apps can add child " 10958 + "packages. Ignoring package " + pkg.packageName); 10959 } 10960 final int childCount = pkg.childPackages.size(); 10961 for (int i = 0; i < childCount; i++) { 10962 PackageParser.Package childPkg = pkg.childPackages.get(i); 10963 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10964 childPkg.packageName)) { 10965 throw new PackageManagerException("Can't override child of " 10966 + "another disabled app. Ignoring package " + pkg.packageName); 10967 } 10968 } 10969 } 10970 10971 // If we're only installing presumed-existing packages, require that the 10972 // scanned APK is both already known and at the path previously established 10973 // for it. Previously unknown packages we pick up normally, but if we have an 10974 // a priori expectation about this package's install presence, enforce it. 10975 // With a singular exception for new system packages. When an OTA contains 10976 // a new system package, we allow the codepath to change from a system location 10977 // to the user-installed location. If we don't allow this change, any newer, 10978 // user-installed version of the application will be ignored. 10979 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10980 if (mExpectingBetter.containsKey(pkg.packageName)) { 10981 logCriticalInfo(Log.WARN, 10982 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10983 } else { 10984 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10985 if (known != null) { 10986 if (DEBUG_PACKAGE_SCANNING) { 10987 Log.d(TAG, "Examining " + pkg.codePath 10988 + " and requiring known paths " + known.codePathString 10989 + " & " + known.resourcePathString); 10990 } 10991 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10992 || !pkg.applicationInfo.getResourcePath().equals( 10993 known.resourcePathString)) { 10994 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10995 "Application package " + pkg.packageName 10996 + " found at " + pkg.applicationInfo.getCodePath() 10997 + " but expected at " + known.codePathString 10998 + "; ignoring."); 10999 } 11000 } else { 11001 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11002 "Application package " + pkg.packageName 11003 + " not found; ignoring."); 11004 } 11005 } 11006 } 11007 11008 // Verify that this new package doesn't have any content providers 11009 // that conflict with existing packages. Only do this if the 11010 // package isn't already installed, since we don't want to break 11011 // things that are installed. 11012 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11013 final int N = pkg.providers.size(); 11014 int i; 11015 for (i=0; i<N; i++) { 11016 PackageParser.Provider p = pkg.providers.get(i); 11017 if (p.info.authority != null) { 11018 String names[] = p.info.authority.split(";"); 11019 for (int j = 0; j < names.length; j++) { 11020 if (mProvidersByAuthority.containsKey(names[j])) { 11021 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11022 final String otherPackageName = 11023 ((other != null && other.getComponentName() != null) ? 11024 other.getComponentName().getPackageName() : "?"); 11025 throw new PackageManagerException( 11026 INSTALL_FAILED_CONFLICTING_PROVIDER, 11027 "Can't install because provider name " + names[j] 11028 + " (in package " + pkg.applicationInfo.packageName 11029 + ") is already used by " + otherPackageName); 11030 } 11031 } 11032 } 11033 } 11034 } 11035 11036 // Verify that packages sharing a user with a privileged app are marked as privileged. 11037 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11038 SharedUserSetting sharedUserSetting = null; 11039 try { 11040 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11041 } catch (PackageManagerException ignore) {} 11042 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11043 // Exempt SharedUsers signed with the platform key. 11044 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11045 if ((platformPkgSetting.signatures.mSigningDetails 11046 != PackageParser.SigningDetails.UNKNOWN) 11047 && (compareSignatures( 11048 platformPkgSetting.signatures.mSigningDetails.signatures, 11049 pkg.mSigningDetails.signatures) 11050 != PackageManager.SIGNATURE_MATCH)) { 11051 throw new PackageManagerException("Apps that share a user with a " + 11052 "privileged app must themselves be marked as privileged. " + 11053 pkg.packageName + " shares privileged user " + 11054 pkg.mSharedUserId + "."); 11055 } 11056 } 11057 } 11058 11059 // Apply policies specific for runtime resource overlays (RROs). 11060 if (pkg.mOverlayTarget != null) { 11061 // System overlays have some restrictions on their use of the 'static' state. 11062 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11063 // We are scanning a system overlay. This can be the first scan of the 11064 // system/vendor/oem partition, or an update to the system overlay. 11065 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11066 // This must be an update to a system overlay. 11067 final PackageSetting previousPkg = assertNotNull( 11068 mSettings.getPackageLPr(pkg.packageName), 11069 "previous package state not present"); 11070 11071 // Static overlays cannot be updated. 11072 if (previousPkg.pkg.mOverlayIsStatic) { 11073 throw new PackageManagerException("Overlay " + pkg.packageName + 11074 " is static and cannot be upgraded."); 11075 // Non-static overlays cannot be converted to static overlays. 11076 } else if (pkg.mOverlayIsStatic) { 11077 throw new PackageManagerException("Overlay " + pkg.packageName + 11078 " cannot be upgraded into a static overlay."); 11079 } 11080 } 11081 } else { 11082 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11083 if (pkg.mOverlayIsStatic) { 11084 throw new PackageManagerException("Overlay " + pkg.packageName + 11085 " is static but not pre-installed."); 11086 } 11087 11088 // The only case where we allow installation of a non-system overlay is when 11089 // its signature is signed with the platform certificate. 11090 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11091 if ((platformPkgSetting.signatures.mSigningDetails 11092 != PackageParser.SigningDetails.UNKNOWN) 11093 && (compareSignatures( 11094 platformPkgSetting.signatures.mSigningDetails.signatures, 11095 pkg.mSigningDetails.signatures) 11096 != PackageManager.SIGNATURE_MATCH)) { 11097 throw new PackageManagerException("Overlay " + pkg.packageName + 11098 " must be signed with the platform certificate."); 11099 } 11100 } 11101 } 11102 } 11103 } 11104 11105 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11106 int type, String declaringPackageName, long declaringVersionCode) { 11107 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11108 if (versionedLib == null) { 11109 versionedLib = new LongSparseArray<>(); 11110 mSharedLibraries.put(name, versionedLib); 11111 if (type == SharedLibraryInfo.TYPE_STATIC) { 11112 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11113 } 11114 } else if (versionedLib.indexOfKey(version) >= 0) { 11115 return false; 11116 } 11117 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11118 version, type, declaringPackageName, declaringVersionCode); 11119 versionedLib.put(version, libEntry); 11120 return true; 11121 } 11122 11123 private boolean removeSharedLibraryLPw(String name, long version) { 11124 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11125 if (versionedLib == null) { 11126 return false; 11127 } 11128 final int libIdx = versionedLib.indexOfKey(version); 11129 if (libIdx < 0) { 11130 return false; 11131 } 11132 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11133 versionedLib.remove(version); 11134 if (versionedLib.size() <= 0) { 11135 mSharedLibraries.remove(name); 11136 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11137 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11138 .getPackageName()); 11139 } 11140 } 11141 return true; 11142 } 11143 11144 /** 11145 * Adds a scanned package to the system. When this method is finished, the package will 11146 * be available for query, resolution, etc... 11147 */ 11148 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11149 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11150 final String pkgName = pkg.packageName; 11151 if (mCustomResolverComponentName != null && 11152 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11153 setUpCustomResolverActivity(pkg); 11154 } 11155 11156 if (pkg.packageName.equals("android")) { 11157 synchronized (mPackages) { 11158 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11159 // Set up information for our fall-back user intent resolution activity. 11160 mPlatformPackage = pkg; 11161 pkg.mVersionCode = mSdkVersion; 11162 pkg.mVersionCodeMajor = 0; 11163 mAndroidApplication = pkg.applicationInfo; 11164 if (!mResolverReplaced) { 11165 mResolveActivity.applicationInfo = mAndroidApplication; 11166 mResolveActivity.name = ResolverActivity.class.getName(); 11167 mResolveActivity.packageName = mAndroidApplication.packageName; 11168 mResolveActivity.processName = "system:ui"; 11169 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11170 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11171 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11172 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11173 mResolveActivity.exported = true; 11174 mResolveActivity.enabled = true; 11175 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11176 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11177 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11178 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11179 | ActivityInfo.CONFIG_ORIENTATION 11180 | ActivityInfo.CONFIG_KEYBOARD 11181 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11182 mResolveInfo.activityInfo = mResolveActivity; 11183 mResolveInfo.priority = 0; 11184 mResolveInfo.preferredOrder = 0; 11185 mResolveInfo.match = 0; 11186 mResolveComponentName = new ComponentName( 11187 mAndroidApplication.packageName, mResolveActivity.name); 11188 } 11189 } 11190 } 11191 } 11192 11193 ArrayList<PackageParser.Package> clientLibPkgs = null; 11194 // writer 11195 synchronized (mPackages) { 11196 boolean hasStaticSharedLibs = false; 11197 11198 // Any app can add new static shared libraries 11199 if (pkg.staticSharedLibName != null) { 11200 // Static shared libs don't allow renaming as they have synthetic package 11201 // names to allow install of multiple versions, so use name from manifest. 11202 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11203 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11204 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11205 hasStaticSharedLibs = true; 11206 } else { 11207 Slog.w(TAG, "Package " + pkg.packageName + " library " 11208 + pkg.staticSharedLibName + " already exists; skipping"); 11209 } 11210 // Static shared libs cannot be updated once installed since they 11211 // use synthetic package name which includes the version code, so 11212 // not need to update other packages's shared lib dependencies. 11213 } 11214 11215 if (!hasStaticSharedLibs 11216 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11217 // Only system apps can add new dynamic shared libraries. 11218 if (pkg.libraryNames != null) { 11219 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11220 String name = pkg.libraryNames.get(i); 11221 boolean allowed = false; 11222 if (pkg.isUpdatedSystemApp()) { 11223 // New library entries can only be added through the 11224 // system image. This is important to get rid of a lot 11225 // of nasty edge cases: for example if we allowed a non- 11226 // system update of the app to add a library, then uninstalling 11227 // the update would make the library go away, and assumptions 11228 // we made such as through app install filtering would now 11229 // have allowed apps on the device which aren't compatible 11230 // with it. Better to just have the restriction here, be 11231 // conservative, and create many fewer cases that can negatively 11232 // impact the user experience. 11233 final PackageSetting sysPs = mSettings 11234 .getDisabledSystemPkgLPr(pkg.packageName); 11235 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11236 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11237 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11238 allowed = true; 11239 break; 11240 } 11241 } 11242 } 11243 } else { 11244 allowed = true; 11245 } 11246 if (allowed) { 11247 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11248 SharedLibraryInfo.VERSION_UNDEFINED, 11249 SharedLibraryInfo.TYPE_DYNAMIC, 11250 pkg.packageName, pkg.getLongVersionCode())) { 11251 Slog.w(TAG, "Package " + pkg.packageName + " library " 11252 + name + " already exists; skipping"); 11253 } 11254 } else { 11255 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11256 + name + " that is not declared on system image; skipping"); 11257 } 11258 } 11259 11260 if ((scanFlags & SCAN_BOOTING) == 0) { 11261 // If we are not booting, we need to update any applications 11262 // that are clients of our shared library. If we are booting, 11263 // this will all be done once the scan is complete. 11264 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11265 } 11266 } 11267 } 11268 } 11269 11270 if ((scanFlags & SCAN_BOOTING) != 0) { 11271 // No apps can run during boot scan, so they don't need to be frozen 11272 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11273 // Caller asked to not kill app, so it's probably not frozen 11274 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11275 // Caller asked us to ignore frozen check for some reason; they 11276 // probably didn't know the package name 11277 } else { 11278 // We're doing major surgery on this package, so it better be frozen 11279 // right now to keep it from launching 11280 checkPackageFrozen(pkgName); 11281 } 11282 11283 // Also need to kill any apps that are dependent on the library. 11284 if (clientLibPkgs != null) { 11285 for (int i=0; i<clientLibPkgs.size(); i++) { 11286 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11287 killApplication(clientPkg.applicationInfo.packageName, 11288 clientPkg.applicationInfo.uid, "update lib"); 11289 } 11290 } 11291 11292 // writer 11293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11294 11295 synchronized (mPackages) { 11296 // We don't expect installation to fail beyond this point 11297 11298 // Add the new setting to mSettings 11299 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11300 // Add the new setting to mPackages 11301 mPackages.put(pkg.applicationInfo.packageName, pkg); 11302 // Make sure we don't accidentally delete its data. 11303 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11304 while (iter.hasNext()) { 11305 PackageCleanItem item = iter.next(); 11306 if (pkgName.equals(item.packageName)) { 11307 iter.remove(); 11308 } 11309 } 11310 11311 // Add the package's KeySets to the global KeySetManagerService 11312 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11313 ksms.addScannedPackageLPw(pkg); 11314 11315 int N = pkg.providers.size(); 11316 StringBuilder r = null; 11317 int i; 11318 for (i=0; i<N; i++) { 11319 PackageParser.Provider p = pkg.providers.get(i); 11320 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11321 p.info.processName); 11322 mProviders.addProvider(p); 11323 p.syncable = p.info.isSyncable; 11324 if (p.info.authority != null) { 11325 String names[] = p.info.authority.split(";"); 11326 p.info.authority = null; 11327 for (int j = 0; j < names.length; j++) { 11328 if (j == 1 && p.syncable) { 11329 // We only want the first authority for a provider to possibly be 11330 // syncable, so if we already added this provider using a different 11331 // authority clear the syncable flag. We copy the provider before 11332 // changing it because the mProviders object contains a reference 11333 // to a provider that we don't want to change. 11334 // Only do this for the second authority since the resulting provider 11335 // object can be the same for all future authorities for this provider. 11336 p = new PackageParser.Provider(p); 11337 p.syncable = false; 11338 } 11339 if (!mProvidersByAuthority.containsKey(names[j])) { 11340 mProvidersByAuthority.put(names[j], p); 11341 if (p.info.authority == null) { 11342 p.info.authority = names[j]; 11343 } else { 11344 p.info.authority = p.info.authority + ";" + names[j]; 11345 } 11346 if (DEBUG_PACKAGE_SCANNING) { 11347 if (chatty) 11348 Log.d(TAG, "Registered content provider: " + names[j] 11349 + ", className = " + p.info.name + ", isSyncable = " 11350 + p.info.isSyncable); 11351 } 11352 } else { 11353 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11354 Slog.w(TAG, "Skipping provider name " + names[j] + 11355 " (in package " + pkg.applicationInfo.packageName + 11356 "): name already used by " 11357 + ((other != null && other.getComponentName() != null) 11358 ? other.getComponentName().getPackageName() : "?")); 11359 } 11360 } 11361 } 11362 if (chatty) { 11363 if (r == null) { 11364 r = new StringBuilder(256); 11365 } else { 11366 r.append(' '); 11367 } 11368 r.append(p.info.name); 11369 } 11370 } 11371 if (r != null) { 11372 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11373 } 11374 11375 N = pkg.services.size(); 11376 r = null; 11377 for (i=0; i<N; i++) { 11378 PackageParser.Service s = pkg.services.get(i); 11379 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11380 s.info.processName); 11381 mServices.addService(s); 11382 if (chatty) { 11383 if (r == null) { 11384 r = new StringBuilder(256); 11385 } else { 11386 r.append(' '); 11387 } 11388 r.append(s.info.name); 11389 } 11390 } 11391 if (r != null) { 11392 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11393 } 11394 11395 N = pkg.receivers.size(); 11396 r = null; 11397 for (i=0; i<N; i++) { 11398 PackageParser.Activity a = pkg.receivers.get(i); 11399 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11400 a.info.processName); 11401 mReceivers.addActivity(a, "receiver"); 11402 if (chatty) { 11403 if (r == null) { 11404 r = new StringBuilder(256); 11405 } else { 11406 r.append(' '); 11407 } 11408 r.append(a.info.name); 11409 } 11410 } 11411 if (r != null) { 11412 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11413 } 11414 11415 N = pkg.activities.size(); 11416 r = null; 11417 for (i=0; i<N; i++) { 11418 PackageParser.Activity a = pkg.activities.get(i); 11419 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11420 a.info.processName); 11421 mActivities.addActivity(a, "activity"); 11422 if (chatty) { 11423 if (r == null) { 11424 r = new StringBuilder(256); 11425 } else { 11426 r.append(' '); 11427 } 11428 r.append(a.info.name); 11429 } 11430 } 11431 if (r != null) { 11432 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11433 } 11434 11435 // Don't allow ephemeral applications to define new permissions groups. 11436 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11437 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11438 + " ignored: instant apps cannot define new permission groups."); 11439 } else { 11440 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11441 } 11442 11443 // Don't allow ephemeral applications to define new permissions. 11444 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11445 Slog.w(TAG, "Permissions from package " + pkg.packageName 11446 + " ignored: instant apps cannot define new permissions."); 11447 } else { 11448 mPermissionManager.addAllPermissions(pkg, chatty); 11449 } 11450 11451 N = pkg.instrumentation.size(); 11452 r = null; 11453 for (i=0; i<N; i++) { 11454 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11455 a.info.packageName = pkg.applicationInfo.packageName; 11456 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11457 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11458 a.info.splitNames = pkg.splitNames; 11459 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11460 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11461 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11462 a.info.dataDir = pkg.applicationInfo.dataDir; 11463 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11464 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11465 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11466 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11467 mInstrumentation.put(a.getComponentName(), a); 11468 if (chatty) { 11469 if (r == null) { 11470 r = new StringBuilder(256); 11471 } else { 11472 r.append(' '); 11473 } 11474 r.append(a.info.name); 11475 } 11476 } 11477 if (r != null) { 11478 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11479 } 11480 11481 if (pkg.protectedBroadcasts != null) { 11482 N = pkg.protectedBroadcasts.size(); 11483 synchronized (mProtectedBroadcasts) { 11484 for (i = 0; i < N; i++) { 11485 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11486 } 11487 } 11488 } 11489 } 11490 11491 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11492 } 11493 11494 /** 11495 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11496 * is derived purely on the basis of the contents of {@code scanFile} and 11497 * {@code cpuAbiOverride}. 11498 * 11499 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11500 */ 11501 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11502 boolean extractLibs) 11503 throws PackageManagerException { 11504 // Give ourselves some initial paths; we'll come back for another 11505 // pass once we've determined ABI below. 11506 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11507 11508 // We would never need to extract libs for forward-locked and external packages, 11509 // since the container service will do it for us. We shouldn't attempt to 11510 // extract libs from system app when it was not updated. 11511 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11512 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11513 extractLibs = false; 11514 } 11515 11516 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11517 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11518 11519 NativeLibraryHelper.Handle handle = null; 11520 try { 11521 handle = NativeLibraryHelper.Handle.create(pkg); 11522 // TODO(multiArch): This can be null for apps that didn't go through the 11523 // usual installation process. We can calculate it again, like we 11524 // do during install time. 11525 // 11526 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11527 // unnecessary. 11528 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11529 11530 // Null out the abis so that they can be recalculated. 11531 pkg.applicationInfo.primaryCpuAbi = null; 11532 pkg.applicationInfo.secondaryCpuAbi = null; 11533 if (isMultiArch(pkg.applicationInfo)) { 11534 // Warn if we've set an abiOverride for multi-lib packages.. 11535 // By definition, we need to copy both 32 and 64 bit libraries for 11536 // such packages. 11537 if (pkg.cpuAbiOverride != null 11538 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11539 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11540 } 11541 11542 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11543 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11544 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11545 if (extractLibs) { 11546 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11547 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11548 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11549 useIsaSpecificSubdirs); 11550 } else { 11551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11552 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11553 } 11554 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11555 } 11556 11557 // Shared library native code should be in the APK zip aligned 11558 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11559 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11560 "Shared library native lib extraction not supported"); 11561 } 11562 11563 maybeThrowExceptionForMultiArchCopy( 11564 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11565 11566 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11567 if (extractLibs) { 11568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11569 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11570 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11571 useIsaSpecificSubdirs); 11572 } else { 11573 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11574 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11575 } 11576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11577 } 11578 11579 maybeThrowExceptionForMultiArchCopy( 11580 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11581 11582 if (abi64 >= 0) { 11583 // Shared library native libs should be in the APK zip aligned 11584 if (extractLibs && pkg.isLibrary()) { 11585 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11586 "Shared library native lib extraction not supported"); 11587 } 11588 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11589 } 11590 11591 if (abi32 >= 0) { 11592 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11593 if (abi64 >= 0) { 11594 if (pkg.use32bitAbi) { 11595 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11596 pkg.applicationInfo.primaryCpuAbi = abi; 11597 } else { 11598 pkg.applicationInfo.secondaryCpuAbi = abi; 11599 } 11600 } else { 11601 pkg.applicationInfo.primaryCpuAbi = abi; 11602 } 11603 } 11604 } else { 11605 String[] abiList = (cpuAbiOverride != null) ? 11606 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11607 11608 // Enable gross and lame hacks for apps that are built with old 11609 // SDK tools. We must scan their APKs for renderscript bitcode and 11610 // not launch them if it's present. Don't bother checking on devices 11611 // that don't have 64 bit support. 11612 boolean needsRenderScriptOverride = false; 11613 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11614 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11615 abiList = Build.SUPPORTED_32_BIT_ABIS; 11616 needsRenderScriptOverride = true; 11617 } 11618 11619 final int copyRet; 11620 if (extractLibs) { 11621 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11622 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11623 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11624 } else { 11625 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11626 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11627 } 11628 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11629 11630 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11631 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11632 "Error unpackaging native libs for app, errorCode=" + copyRet); 11633 } 11634 11635 if (copyRet >= 0) { 11636 // Shared libraries that have native libs must be multi-architecture 11637 if (pkg.isLibrary()) { 11638 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11639 "Shared library with native libs must be multiarch"); 11640 } 11641 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11642 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11643 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11644 } else if (needsRenderScriptOverride) { 11645 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11646 } 11647 } 11648 } catch (IOException ioe) { 11649 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11650 } finally { 11651 IoUtils.closeQuietly(handle); 11652 } 11653 11654 // Now that we've calculated the ABIs and determined if it's an internal app, 11655 // we will go ahead and populate the nativeLibraryPath. 11656 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11657 } 11658 11659 /** 11660 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11661 * i.e, so that all packages can be run inside a single process if required. 11662 * 11663 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11664 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11665 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11666 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11667 * updating a package that belongs to a shared user. 11668 * 11669 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11670 * adds unnecessary complexity. 11671 */ 11672 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11673 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11674 List<String> changedAbiCodePath = null; 11675 String requiredInstructionSet = null; 11676 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11677 requiredInstructionSet = VMRuntime.getInstructionSet( 11678 scannedPackage.applicationInfo.primaryCpuAbi); 11679 } 11680 11681 PackageSetting requirer = null; 11682 for (PackageSetting ps : packagesForUser) { 11683 // If packagesForUser contains scannedPackage, we skip it. This will happen 11684 // when scannedPackage is an update of an existing package. Without this check, 11685 // we will never be able to change the ABI of any package belonging to a shared 11686 // user, even if it's compatible with other packages. 11687 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11688 if (ps.primaryCpuAbiString == null) { 11689 continue; 11690 } 11691 11692 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11693 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11694 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11695 // this but there's not much we can do. 11696 String errorMessage = "Instruction set mismatch, " 11697 + ((requirer == null) ? "[caller]" : requirer) 11698 + " requires " + requiredInstructionSet + " whereas " + ps 11699 + " requires " + instructionSet; 11700 Slog.w(TAG, errorMessage); 11701 } 11702 11703 if (requiredInstructionSet == null) { 11704 requiredInstructionSet = instructionSet; 11705 requirer = ps; 11706 } 11707 } 11708 } 11709 11710 if (requiredInstructionSet != null) { 11711 String adjustedAbi; 11712 if (requirer != null) { 11713 // requirer != null implies that either scannedPackage was null or that scannedPackage 11714 // did not require an ABI, in which case we have to adjust scannedPackage to match 11715 // the ABI of the set (which is the same as requirer's ABI) 11716 adjustedAbi = requirer.primaryCpuAbiString; 11717 if (scannedPackage != null) { 11718 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11719 } 11720 } else { 11721 // requirer == null implies that we're updating all ABIs in the set to 11722 // match scannedPackage. 11723 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11724 } 11725 11726 for (PackageSetting ps : packagesForUser) { 11727 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11728 if (ps.primaryCpuAbiString != null) { 11729 continue; 11730 } 11731 11732 ps.primaryCpuAbiString = adjustedAbi; 11733 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11734 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11735 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11736 if (DEBUG_ABI_SELECTION) { 11737 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11738 + " (requirer=" 11739 + (requirer != null ? requirer.pkg : "null") 11740 + ", scannedPackage=" 11741 + (scannedPackage != null ? scannedPackage : "null") 11742 + ")"); 11743 } 11744 if (changedAbiCodePath == null) { 11745 changedAbiCodePath = new ArrayList<>(); 11746 } 11747 changedAbiCodePath.add(ps.codePathString); 11748 } 11749 } 11750 } 11751 } 11752 return changedAbiCodePath; 11753 } 11754 11755 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11756 synchronized (mPackages) { 11757 mResolverReplaced = true; 11758 // Set up information for custom user intent resolution activity. 11759 mResolveActivity.applicationInfo = pkg.applicationInfo; 11760 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11761 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11762 mResolveActivity.processName = pkg.applicationInfo.packageName; 11763 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11764 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11765 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11766 mResolveActivity.theme = 0; 11767 mResolveActivity.exported = true; 11768 mResolveActivity.enabled = true; 11769 mResolveInfo.activityInfo = mResolveActivity; 11770 mResolveInfo.priority = 0; 11771 mResolveInfo.preferredOrder = 0; 11772 mResolveInfo.match = 0; 11773 mResolveComponentName = mCustomResolverComponentName; 11774 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11775 mResolveComponentName); 11776 } 11777 } 11778 11779 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11780 if (installerActivity == null) { 11781 if (DEBUG_INSTANT) { 11782 Slog.d(TAG, "Clear ephemeral installer activity"); 11783 } 11784 mInstantAppInstallerActivity = null; 11785 return; 11786 } 11787 11788 if (DEBUG_INSTANT) { 11789 Slog.d(TAG, "Set ephemeral installer activity: " 11790 + installerActivity.getComponentName()); 11791 } 11792 // Set up information for ephemeral installer activity 11793 mInstantAppInstallerActivity = installerActivity; 11794 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11795 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11796 mInstantAppInstallerActivity.exported = true; 11797 mInstantAppInstallerActivity.enabled = true; 11798 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11799 mInstantAppInstallerInfo.priority = 1; 11800 mInstantAppInstallerInfo.preferredOrder = 1; 11801 mInstantAppInstallerInfo.isDefault = true; 11802 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11803 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11804 } 11805 11806 private static String calculateBundledApkRoot(final String codePathString) { 11807 final File codePath = new File(codePathString); 11808 final File codeRoot; 11809 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11810 codeRoot = Environment.getRootDirectory(); 11811 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11812 codeRoot = Environment.getOemDirectory(); 11813 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11814 codeRoot = Environment.getVendorDirectory(); 11815 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 11816 codeRoot = Environment.getOdmDirectory(); 11817 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11818 codeRoot = Environment.getProductDirectory(); 11819 } else { 11820 // Unrecognized code path; take its top real segment as the apk root: 11821 // e.g. /something/app/blah.apk => /something 11822 try { 11823 File f = codePath.getCanonicalFile(); 11824 File parent = f.getParentFile(); // non-null because codePath is a file 11825 File tmp; 11826 while ((tmp = parent.getParentFile()) != null) { 11827 f = parent; 11828 parent = tmp; 11829 } 11830 codeRoot = f; 11831 Slog.w(TAG, "Unrecognized code path " 11832 + codePath + " - using " + codeRoot); 11833 } catch (IOException e) { 11834 // Can't canonicalize the code path -- shenanigans? 11835 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11836 return Environment.getRootDirectory().getPath(); 11837 } 11838 } 11839 return codeRoot.getPath(); 11840 } 11841 11842 /** 11843 * Derive and set the location of native libraries for the given package, 11844 * which varies depending on where and how the package was installed. 11845 */ 11846 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11847 final ApplicationInfo info = pkg.applicationInfo; 11848 final String codePath = pkg.codePath; 11849 final File codeFile = new File(codePath); 11850 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11851 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11852 11853 info.nativeLibraryRootDir = null; 11854 info.nativeLibraryRootRequiresIsa = false; 11855 info.nativeLibraryDir = null; 11856 info.secondaryNativeLibraryDir = null; 11857 11858 if (isApkFile(codeFile)) { 11859 // Monolithic install 11860 if (bundledApp) { 11861 // If "/system/lib64/apkname" exists, assume that is the per-package 11862 // native library directory to use; otherwise use "/system/lib/apkname". 11863 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11864 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11865 getPrimaryInstructionSet(info)); 11866 11867 // This is a bundled system app so choose the path based on the ABI. 11868 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11869 // is just the default path. 11870 final String apkName = deriveCodePathName(codePath); 11871 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11872 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11873 apkName).getAbsolutePath(); 11874 11875 if (info.secondaryCpuAbi != null) { 11876 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11877 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11878 secondaryLibDir, apkName).getAbsolutePath(); 11879 } 11880 } else if (asecApp) { 11881 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11882 .getAbsolutePath(); 11883 } else { 11884 final String apkName = deriveCodePathName(codePath); 11885 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11886 .getAbsolutePath(); 11887 } 11888 11889 info.nativeLibraryRootRequiresIsa = false; 11890 info.nativeLibraryDir = info.nativeLibraryRootDir; 11891 } else { 11892 // Cluster install 11893 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11894 info.nativeLibraryRootRequiresIsa = true; 11895 11896 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11897 getPrimaryInstructionSet(info)).getAbsolutePath(); 11898 11899 if (info.secondaryCpuAbi != null) { 11900 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11901 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11902 } 11903 } 11904 } 11905 11906 /** 11907 * Calculate the abis and roots for a bundled app. These can uniquely 11908 * be determined from the contents of the system partition, i.e whether 11909 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11910 * of this information, and instead assume that the system was built 11911 * sensibly. 11912 */ 11913 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11914 PackageSetting pkgSetting) { 11915 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11916 11917 // If "/system/lib64/apkname" exists, assume that is the per-package 11918 // native library directory to use; otherwise use "/system/lib/apkname". 11919 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11920 setBundledAppAbi(pkg, apkRoot, apkName); 11921 // pkgSetting might be null during rescan following uninstall of updates 11922 // to a bundled app, so accommodate that possibility. The settings in 11923 // that case will be established later from the parsed package. 11924 // 11925 // If the settings aren't null, sync them up with what we've just derived. 11926 // note that apkRoot isn't stored in the package settings. 11927 if (pkgSetting != null) { 11928 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11929 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11930 } 11931 } 11932 11933 /** 11934 * Deduces the ABI of a bundled app and sets the relevant fields on the 11935 * parsed pkg object. 11936 * 11937 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11938 * under which system libraries are installed. 11939 * @param apkName the name of the installed package. 11940 */ 11941 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11942 final File codeFile = new File(pkg.codePath); 11943 11944 final boolean has64BitLibs; 11945 final boolean has32BitLibs; 11946 if (isApkFile(codeFile)) { 11947 // Monolithic install 11948 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11949 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11950 } else { 11951 // Cluster install 11952 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11953 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11954 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11955 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11956 has64BitLibs = (new File(rootDir, isa)).exists(); 11957 } else { 11958 has64BitLibs = false; 11959 } 11960 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11961 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11962 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11963 has32BitLibs = (new File(rootDir, isa)).exists(); 11964 } else { 11965 has32BitLibs = false; 11966 } 11967 } 11968 11969 if (has64BitLibs && !has32BitLibs) { 11970 // The package has 64 bit libs, but not 32 bit libs. Its primary 11971 // ABI should be 64 bit. We can safely assume here that the bundled 11972 // native libraries correspond to the most preferred ABI in the list. 11973 11974 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11975 pkg.applicationInfo.secondaryCpuAbi = null; 11976 } else if (has32BitLibs && !has64BitLibs) { 11977 // The package has 32 bit libs but not 64 bit libs. Its primary 11978 // ABI should be 32 bit. 11979 11980 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11981 pkg.applicationInfo.secondaryCpuAbi = null; 11982 } else if (has32BitLibs && has64BitLibs) { 11983 // The application has both 64 and 32 bit bundled libraries. We check 11984 // here that the app declares multiArch support, and warn if it doesn't. 11985 // 11986 // We will be lenient here and record both ABIs. The primary will be the 11987 // ABI that's higher on the list, i.e, a device that's configured to prefer 11988 // 64 bit apps will see a 64 bit primary ABI, 11989 11990 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11991 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11992 } 11993 11994 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11995 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11996 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11997 } else { 11998 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11999 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12000 } 12001 } else { 12002 pkg.applicationInfo.primaryCpuAbi = null; 12003 pkg.applicationInfo.secondaryCpuAbi = null; 12004 } 12005 } 12006 12007 private void killApplication(String pkgName, int appId, String reason) { 12008 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12009 } 12010 12011 private void killApplication(String pkgName, int appId, int userId, String reason) { 12012 // Request the ActivityManager to kill the process(only for existing packages) 12013 // so that we do not end up in a confused state while the user is still using the older 12014 // version of the application while the new one gets installed. 12015 final long token = Binder.clearCallingIdentity(); 12016 try { 12017 IActivityManager am = ActivityManager.getService(); 12018 if (am != null) { 12019 try { 12020 am.killApplication(pkgName, appId, userId, reason); 12021 } catch (RemoteException e) { 12022 } 12023 } 12024 } finally { 12025 Binder.restoreCallingIdentity(token); 12026 } 12027 } 12028 12029 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12030 // Remove the parent package setting 12031 PackageSetting ps = (PackageSetting) pkg.mExtras; 12032 if (ps != null) { 12033 removePackageLI(ps, chatty); 12034 } 12035 // Remove the child package setting 12036 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12037 for (int i = 0; i < childCount; i++) { 12038 PackageParser.Package childPkg = pkg.childPackages.get(i); 12039 ps = (PackageSetting) childPkg.mExtras; 12040 if (ps != null) { 12041 removePackageLI(ps, chatty); 12042 } 12043 } 12044 } 12045 12046 void removePackageLI(PackageSetting ps, boolean chatty) { 12047 if (DEBUG_INSTALL) { 12048 if (chatty) 12049 Log.d(TAG, "Removing package " + ps.name); 12050 } 12051 12052 // writer 12053 synchronized (mPackages) { 12054 mPackages.remove(ps.name); 12055 final PackageParser.Package pkg = ps.pkg; 12056 if (pkg != null) { 12057 cleanPackageDataStructuresLILPw(pkg, chatty); 12058 } 12059 } 12060 } 12061 12062 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12063 if (DEBUG_INSTALL) { 12064 if (chatty) 12065 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12066 } 12067 12068 // writer 12069 synchronized (mPackages) { 12070 // Remove the parent package 12071 mPackages.remove(pkg.applicationInfo.packageName); 12072 cleanPackageDataStructuresLILPw(pkg, chatty); 12073 12074 // Remove the child packages 12075 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12076 for (int i = 0; i < childCount; i++) { 12077 PackageParser.Package childPkg = pkg.childPackages.get(i); 12078 mPackages.remove(childPkg.applicationInfo.packageName); 12079 cleanPackageDataStructuresLILPw(childPkg, chatty); 12080 } 12081 } 12082 } 12083 12084 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12085 int N = pkg.providers.size(); 12086 StringBuilder r = null; 12087 int i; 12088 for (i=0; i<N; i++) { 12089 PackageParser.Provider p = pkg.providers.get(i); 12090 mProviders.removeProvider(p); 12091 if (p.info.authority == null) { 12092 12093 /* There was another ContentProvider with this authority when 12094 * this app was installed so this authority is null, 12095 * Ignore it as we don't have to unregister the provider. 12096 */ 12097 continue; 12098 } 12099 String names[] = p.info.authority.split(";"); 12100 for (int j = 0; j < names.length; j++) { 12101 if (mProvidersByAuthority.get(names[j]) == p) { 12102 mProvidersByAuthority.remove(names[j]); 12103 if (DEBUG_REMOVE) { 12104 if (chatty) 12105 Log.d(TAG, "Unregistered content provider: " + names[j] 12106 + ", className = " + p.info.name + ", isSyncable = " 12107 + p.info.isSyncable); 12108 } 12109 } 12110 } 12111 if (DEBUG_REMOVE && chatty) { 12112 if (r == null) { 12113 r = new StringBuilder(256); 12114 } else { 12115 r.append(' '); 12116 } 12117 r.append(p.info.name); 12118 } 12119 } 12120 if (r != null) { 12121 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12122 } 12123 12124 N = pkg.services.size(); 12125 r = null; 12126 for (i=0; i<N; i++) { 12127 PackageParser.Service s = pkg.services.get(i); 12128 mServices.removeService(s); 12129 if (chatty) { 12130 if (r == null) { 12131 r = new StringBuilder(256); 12132 } else { 12133 r.append(' '); 12134 } 12135 r.append(s.info.name); 12136 } 12137 } 12138 if (r != null) { 12139 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12140 } 12141 12142 N = pkg.receivers.size(); 12143 r = null; 12144 for (i=0; i<N; i++) { 12145 PackageParser.Activity a = pkg.receivers.get(i); 12146 mReceivers.removeActivity(a, "receiver"); 12147 if (DEBUG_REMOVE && chatty) { 12148 if (r == null) { 12149 r = new StringBuilder(256); 12150 } else { 12151 r.append(' '); 12152 } 12153 r.append(a.info.name); 12154 } 12155 } 12156 if (r != null) { 12157 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12158 } 12159 12160 N = pkg.activities.size(); 12161 r = null; 12162 for (i=0; i<N; i++) { 12163 PackageParser.Activity a = pkg.activities.get(i); 12164 mActivities.removeActivity(a, "activity"); 12165 if (DEBUG_REMOVE && chatty) { 12166 if (r == null) { 12167 r = new StringBuilder(256); 12168 } else { 12169 r.append(' '); 12170 } 12171 r.append(a.info.name); 12172 } 12173 } 12174 if (r != null) { 12175 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12176 } 12177 12178 mPermissionManager.removeAllPermissions(pkg, chatty); 12179 12180 N = pkg.instrumentation.size(); 12181 r = null; 12182 for (i=0; i<N; i++) { 12183 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12184 mInstrumentation.remove(a.getComponentName()); 12185 if (DEBUG_REMOVE && chatty) { 12186 if (r == null) { 12187 r = new StringBuilder(256); 12188 } else { 12189 r.append(' '); 12190 } 12191 r.append(a.info.name); 12192 } 12193 } 12194 if (r != null) { 12195 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12196 } 12197 12198 r = null; 12199 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12200 // Only system apps can hold shared libraries. 12201 if (pkg.libraryNames != null) { 12202 for (i = 0; i < pkg.libraryNames.size(); i++) { 12203 String name = pkg.libraryNames.get(i); 12204 if (removeSharedLibraryLPw(name, 0)) { 12205 if (DEBUG_REMOVE && chatty) { 12206 if (r == null) { 12207 r = new StringBuilder(256); 12208 } else { 12209 r.append(' '); 12210 } 12211 r.append(name); 12212 } 12213 } 12214 } 12215 } 12216 } 12217 12218 r = null; 12219 12220 // Any package can hold static shared libraries. 12221 if (pkg.staticSharedLibName != null) { 12222 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12223 if (DEBUG_REMOVE && chatty) { 12224 if (r == null) { 12225 r = new StringBuilder(256); 12226 } else { 12227 r.append(' '); 12228 } 12229 r.append(pkg.staticSharedLibName); 12230 } 12231 } 12232 } 12233 12234 if (r != null) { 12235 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12236 } 12237 } 12238 12239 12240 final class ActivityIntentResolver 12241 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12242 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12243 boolean defaultOnly, int userId) { 12244 if (!sUserManager.exists(userId)) return null; 12245 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12246 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12247 } 12248 12249 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12250 int userId) { 12251 if (!sUserManager.exists(userId)) return null; 12252 mFlags = flags; 12253 return super.queryIntent(intent, resolvedType, 12254 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12255 userId); 12256 } 12257 12258 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12259 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12260 if (!sUserManager.exists(userId)) return null; 12261 if (packageActivities == null) { 12262 return null; 12263 } 12264 mFlags = flags; 12265 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12266 final int N = packageActivities.size(); 12267 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12268 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12269 12270 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12271 for (int i = 0; i < N; ++i) { 12272 intentFilters = packageActivities.get(i).intents; 12273 if (intentFilters != null && intentFilters.size() > 0) { 12274 PackageParser.ActivityIntentInfo[] array = 12275 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12276 intentFilters.toArray(array); 12277 listCut.add(array); 12278 } 12279 } 12280 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12281 } 12282 12283 /** 12284 * Finds a privileged activity that matches the specified activity names. 12285 */ 12286 private PackageParser.Activity findMatchingActivity( 12287 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12288 for (PackageParser.Activity sysActivity : activityList) { 12289 if (sysActivity.info.name.equals(activityInfo.name)) { 12290 return sysActivity; 12291 } 12292 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12293 return sysActivity; 12294 } 12295 if (sysActivity.info.targetActivity != null) { 12296 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12297 return sysActivity; 12298 } 12299 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12300 return sysActivity; 12301 } 12302 } 12303 } 12304 return null; 12305 } 12306 12307 public class IterGenerator<E> { 12308 public Iterator<E> generate(ActivityIntentInfo info) { 12309 return null; 12310 } 12311 } 12312 12313 public class ActionIterGenerator extends IterGenerator<String> { 12314 @Override 12315 public Iterator<String> generate(ActivityIntentInfo info) { 12316 return info.actionsIterator(); 12317 } 12318 } 12319 12320 public class CategoriesIterGenerator extends IterGenerator<String> { 12321 @Override 12322 public Iterator<String> generate(ActivityIntentInfo info) { 12323 return info.categoriesIterator(); 12324 } 12325 } 12326 12327 public class SchemesIterGenerator extends IterGenerator<String> { 12328 @Override 12329 public Iterator<String> generate(ActivityIntentInfo info) { 12330 return info.schemesIterator(); 12331 } 12332 } 12333 12334 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12335 @Override 12336 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12337 return info.authoritiesIterator(); 12338 } 12339 } 12340 12341 /** 12342 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12343 * MODIFIED. Do not pass in a list that should not be changed. 12344 */ 12345 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12346 IterGenerator<T> generator, Iterator<T> searchIterator) { 12347 // loop through the set of actions; every one must be found in the intent filter 12348 while (searchIterator.hasNext()) { 12349 // we must have at least one filter in the list to consider a match 12350 if (intentList.size() == 0) { 12351 break; 12352 } 12353 12354 final T searchAction = searchIterator.next(); 12355 12356 // loop through the set of intent filters 12357 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12358 while (intentIter.hasNext()) { 12359 final ActivityIntentInfo intentInfo = intentIter.next(); 12360 boolean selectionFound = false; 12361 12362 // loop through the intent filter's selection criteria; at least one 12363 // of them must match the searched criteria 12364 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12365 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12366 final T intentSelection = intentSelectionIter.next(); 12367 if (intentSelection != null && intentSelection.equals(searchAction)) { 12368 selectionFound = true; 12369 break; 12370 } 12371 } 12372 12373 // the selection criteria wasn't found in this filter's set; this filter 12374 // is not a potential match 12375 if (!selectionFound) { 12376 intentIter.remove(); 12377 } 12378 } 12379 } 12380 } 12381 12382 private boolean isProtectedAction(ActivityIntentInfo filter) { 12383 final Iterator<String> actionsIter = filter.actionsIterator(); 12384 while (actionsIter != null && actionsIter.hasNext()) { 12385 final String filterAction = actionsIter.next(); 12386 if (PROTECTED_ACTIONS.contains(filterAction)) { 12387 return true; 12388 } 12389 } 12390 return false; 12391 } 12392 12393 /** 12394 * Adjusts the priority of the given intent filter according to policy. 12395 * <p> 12396 * <ul> 12397 * <li>The priority for non privileged applications is capped to '0'</li> 12398 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12399 * <li>The priority for unbundled updates to privileged applications is capped to the 12400 * priority defined on the system partition</li> 12401 * </ul> 12402 * <p> 12403 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12404 * allowed to obtain any priority on any action. 12405 */ 12406 private void adjustPriority( 12407 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12408 // nothing to do; priority is fine as-is 12409 if (intent.getPriority() <= 0) { 12410 return; 12411 } 12412 12413 final ActivityInfo activityInfo = intent.activity.info; 12414 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12415 12416 final boolean privilegedApp = 12417 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12418 if (!privilegedApp) { 12419 // non-privileged applications can never define a priority >0 12420 if (DEBUG_FILTERS) { 12421 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12422 + " package: " + applicationInfo.packageName 12423 + " activity: " + intent.activity.className 12424 + " origPrio: " + intent.getPriority()); 12425 } 12426 intent.setPriority(0); 12427 return; 12428 } 12429 12430 if (systemActivities == null) { 12431 // the system package is not disabled; we're parsing the system partition 12432 if (isProtectedAction(intent)) { 12433 if (mDeferProtectedFilters) { 12434 // We can't deal with these just yet. No component should ever obtain a 12435 // >0 priority for a protected actions, with ONE exception -- the setup 12436 // wizard. The setup wizard, however, cannot be known until we're able to 12437 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12438 // until all intent filters have been processed. Chicken, meet egg. 12439 // Let the filter temporarily have a high priority and rectify the 12440 // priorities after all system packages have been scanned. 12441 mProtectedFilters.add(intent); 12442 if (DEBUG_FILTERS) { 12443 Slog.i(TAG, "Protected action; save for later;" 12444 + " package: " + applicationInfo.packageName 12445 + " activity: " + intent.activity.className 12446 + " origPrio: " + intent.getPriority()); 12447 } 12448 return; 12449 } else { 12450 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12451 Slog.i(TAG, "No setup wizard;" 12452 + " All protected intents capped to priority 0"); 12453 } 12454 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12455 if (DEBUG_FILTERS) { 12456 Slog.i(TAG, "Found setup wizard;" 12457 + " allow priority " + intent.getPriority() + ";" 12458 + " package: " + intent.activity.info.packageName 12459 + " activity: " + intent.activity.className 12460 + " priority: " + intent.getPriority()); 12461 } 12462 // setup wizard gets whatever it wants 12463 return; 12464 } 12465 if (DEBUG_FILTERS) { 12466 Slog.i(TAG, "Protected action; cap priority to 0;" 12467 + " package: " + intent.activity.info.packageName 12468 + " activity: " + intent.activity.className 12469 + " origPrio: " + intent.getPriority()); 12470 } 12471 intent.setPriority(0); 12472 return; 12473 } 12474 } 12475 // privileged apps on the system image get whatever priority they request 12476 return; 12477 } 12478 12479 // privileged app unbundled update ... try to find the same activity 12480 final PackageParser.Activity foundActivity = 12481 findMatchingActivity(systemActivities, activityInfo); 12482 if (foundActivity == null) { 12483 // this is a new activity; it cannot obtain >0 priority 12484 if (DEBUG_FILTERS) { 12485 Slog.i(TAG, "New activity; cap priority to 0;" 12486 + " package: " + applicationInfo.packageName 12487 + " activity: " + intent.activity.className 12488 + " origPrio: " + intent.getPriority()); 12489 } 12490 intent.setPriority(0); 12491 return; 12492 } 12493 12494 // found activity, now check for filter equivalence 12495 12496 // a shallow copy is enough; we modify the list, not its contents 12497 final List<ActivityIntentInfo> intentListCopy = 12498 new ArrayList<>(foundActivity.intents); 12499 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12500 12501 // find matching action subsets 12502 final Iterator<String> actionsIterator = intent.actionsIterator(); 12503 if (actionsIterator != null) { 12504 getIntentListSubset( 12505 intentListCopy, new ActionIterGenerator(), actionsIterator); 12506 if (intentListCopy.size() == 0) { 12507 // no more intents to match; we're not equivalent 12508 if (DEBUG_FILTERS) { 12509 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12510 + " package: " + applicationInfo.packageName 12511 + " activity: " + intent.activity.className 12512 + " origPrio: " + intent.getPriority()); 12513 } 12514 intent.setPriority(0); 12515 return; 12516 } 12517 } 12518 12519 // find matching category subsets 12520 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12521 if (categoriesIterator != null) { 12522 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12523 categoriesIterator); 12524 if (intentListCopy.size() == 0) { 12525 // no more intents to match; we're not equivalent 12526 if (DEBUG_FILTERS) { 12527 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12528 + " package: " + applicationInfo.packageName 12529 + " activity: " + intent.activity.className 12530 + " origPrio: " + intent.getPriority()); 12531 } 12532 intent.setPriority(0); 12533 return; 12534 } 12535 } 12536 12537 // find matching schemes subsets 12538 final Iterator<String> schemesIterator = intent.schemesIterator(); 12539 if (schemesIterator != null) { 12540 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12541 schemesIterator); 12542 if (intentListCopy.size() == 0) { 12543 // no more intents to match; we're not equivalent 12544 if (DEBUG_FILTERS) { 12545 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12546 + " package: " + applicationInfo.packageName 12547 + " activity: " + intent.activity.className 12548 + " origPrio: " + intent.getPriority()); 12549 } 12550 intent.setPriority(0); 12551 return; 12552 } 12553 } 12554 12555 // find matching authorities subsets 12556 final Iterator<IntentFilter.AuthorityEntry> 12557 authoritiesIterator = intent.authoritiesIterator(); 12558 if (authoritiesIterator != null) { 12559 getIntentListSubset(intentListCopy, 12560 new AuthoritiesIterGenerator(), 12561 authoritiesIterator); 12562 if (intentListCopy.size() == 0) { 12563 // no more intents to match; we're not equivalent 12564 if (DEBUG_FILTERS) { 12565 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12566 + " package: " + applicationInfo.packageName 12567 + " activity: " + intent.activity.className 12568 + " origPrio: " + intent.getPriority()); 12569 } 12570 intent.setPriority(0); 12571 return; 12572 } 12573 } 12574 12575 // we found matching filter(s); app gets the max priority of all intents 12576 int cappedPriority = 0; 12577 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12578 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12579 } 12580 if (intent.getPriority() > cappedPriority) { 12581 if (DEBUG_FILTERS) { 12582 Slog.i(TAG, "Found matching filter(s);" 12583 + " cap priority to " + cappedPriority + ";" 12584 + " package: " + applicationInfo.packageName 12585 + " activity: " + intent.activity.className 12586 + " origPrio: " + intent.getPriority()); 12587 } 12588 intent.setPriority(cappedPriority); 12589 return; 12590 } 12591 // all this for nothing; the requested priority was <= what was on the system 12592 } 12593 12594 public final void addActivity(PackageParser.Activity a, String type) { 12595 mActivities.put(a.getComponentName(), a); 12596 if (DEBUG_SHOW_INFO) 12597 Log.v( 12598 TAG, " " + type + " " + 12599 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12600 if (DEBUG_SHOW_INFO) 12601 Log.v(TAG, " Class=" + a.info.name); 12602 final int NI = a.intents.size(); 12603 for (int j=0; j<NI; j++) { 12604 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12605 if ("activity".equals(type)) { 12606 final PackageSetting ps = 12607 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12608 final List<PackageParser.Activity> systemActivities = 12609 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12610 adjustPriority(systemActivities, intent); 12611 } 12612 if (DEBUG_SHOW_INFO) { 12613 Log.v(TAG, " IntentFilter:"); 12614 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12615 } 12616 if (!intent.debugCheck()) { 12617 Log.w(TAG, "==> For Activity " + a.info.name); 12618 } 12619 addFilter(intent); 12620 } 12621 } 12622 12623 public final void removeActivity(PackageParser.Activity a, String type) { 12624 mActivities.remove(a.getComponentName()); 12625 if (DEBUG_SHOW_INFO) { 12626 Log.v(TAG, " " + type + " " 12627 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12628 : a.info.name) + ":"); 12629 Log.v(TAG, " Class=" + a.info.name); 12630 } 12631 final int NI = a.intents.size(); 12632 for (int j=0; j<NI; j++) { 12633 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12634 if (DEBUG_SHOW_INFO) { 12635 Log.v(TAG, " IntentFilter:"); 12636 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12637 } 12638 removeFilter(intent); 12639 } 12640 } 12641 12642 @Override 12643 protected boolean allowFilterResult( 12644 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12645 ActivityInfo filterAi = filter.activity.info; 12646 for (int i=dest.size()-1; i>=0; i--) { 12647 ActivityInfo destAi = dest.get(i).activityInfo; 12648 if (destAi.name == filterAi.name 12649 && destAi.packageName == filterAi.packageName) { 12650 return false; 12651 } 12652 } 12653 return true; 12654 } 12655 12656 @Override 12657 protected ActivityIntentInfo[] newArray(int size) { 12658 return new ActivityIntentInfo[size]; 12659 } 12660 12661 @Override 12662 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12663 if (!sUserManager.exists(userId)) return true; 12664 PackageParser.Package p = filter.activity.owner; 12665 if (p != null) { 12666 PackageSetting ps = (PackageSetting)p.mExtras; 12667 if (ps != null) { 12668 // System apps are never considered stopped for purposes of 12669 // filtering, because there may be no way for the user to 12670 // actually re-launch them. 12671 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12672 && ps.getStopped(userId); 12673 } 12674 } 12675 return false; 12676 } 12677 12678 @Override 12679 protected boolean isPackageForFilter(String packageName, 12680 PackageParser.ActivityIntentInfo info) { 12681 return packageName.equals(info.activity.owner.packageName); 12682 } 12683 12684 @Override 12685 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12686 int match, int userId) { 12687 if (!sUserManager.exists(userId)) return null; 12688 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12689 return null; 12690 } 12691 final PackageParser.Activity activity = info.activity; 12692 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12693 if (ps == null) { 12694 return null; 12695 } 12696 final PackageUserState userState = ps.readUserState(userId); 12697 ActivityInfo ai = 12698 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12699 if (ai == null) { 12700 return null; 12701 } 12702 final boolean matchExplicitlyVisibleOnly = 12703 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12704 final boolean matchVisibleToInstantApp = 12705 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12706 final boolean componentVisible = 12707 matchVisibleToInstantApp 12708 && info.isVisibleToInstantApp() 12709 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12710 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12711 // throw out filters that aren't visible to ephemeral apps 12712 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12713 return null; 12714 } 12715 // throw out instant app filters if we're not explicitly requesting them 12716 if (!matchInstantApp && userState.instantApp) { 12717 return null; 12718 } 12719 // throw out instant app filters if updates are available; will trigger 12720 // instant app resolution 12721 if (userState.instantApp && ps.isUpdateAvailable()) { 12722 return null; 12723 } 12724 final ResolveInfo res = new ResolveInfo(); 12725 res.activityInfo = ai; 12726 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12727 res.filter = info; 12728 } 12729 if (info != null) { 12730 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12731 } 12732 res.priority = info.getPriority(); 12733 res.preferredOrder = activity.owner.mPreferredOrder; 12734 //System.out.println("Result: " + res.activityInfo.className + 12735 // " = " + res.priority); 12736 res.match = match; 12737 res.isDefault = info.hasDefault; 12738 res.labelRes = info.labelRes; 12739 res.nonLocalizedLabel = info.nonLocalizedLabel; 12740 if (userNeedsBadging(userId)) { 12741 res.noResourceId = true; 12742 } else { 12743 res.icon = info.icon; 12744 } 12745 res.iconResourceId = info.icon; 12746 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12747 res.isInstantAppAvailable = userState.instantApp; 12748 return res; 12749 } 12750 12751 @Override 12752 protected void sortResults(List<ResolveInfo> results) { 12753 Collections.sort(results, mResolvePrioritySorter); 12754 } 12755 12756 @Override 12757 protected void dumpFilter(PrintWriter out, String prefix, 12758 PackageParser.ActivityIntentInfo filter) { 12759 out.print(prefix); out.print( 12760 Integer.toHexString(System.identityHashCode(filter.activity))); 12761 out.print(' '); 12762 filter.activity.printComponentShortName(out); 12763 out.print(" filter "); 12764 out.println(Integer.toHexString(System.identityHashCode(filter))); 12765 } 12766 12767 @Override 12768 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12769 return filter.activity; 12770 } 12771 12772 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12773 PackageParser.Activity activity = (PackageParser.Activity)label; 12774 out.print(prefix); out.print( 12775 Integer.toHexString(System.identityHashCode(activity))); 12776 out.print(' '); 12777 activity.printComponentShortName(out); 12778 if (count > 1) { 12779 out.print(" ("); out.print(count); out.print(" filters)"); 12780 } 12781 out.println(); 12782 } 12783 12784 // Keys are String (activity class name), values are Activity. 12785 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12786 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12787 private int mFlags; 12788 } 12789 12790 private final class ServiceIntentResolver 12791 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12792 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12793 boolean defaultOnly, int userId) { 12794 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12795 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12796 } 12797 12798 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12799 int userId) { 12800 if (!sUserManager.exists(userId)) return null; 12801 mFlags = flags; 12802 return super.queryIntent(intent, resolvedType, 12803 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12804 userId); 12805 } 12806 12807 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12808 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12809 if (!sUserManager.exists(userId)) return null; 12810 if (packageServices == null) { 12811 return null; 12812 } 12813 mFlags = flags; 12814 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12815 final int N = packageServices.size(); 12816 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12817 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12818 12819 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12820 for (int i = 0; i < N; ++i) { 12821 intentFilters = packageServices.get(i).intents; 12822 if (intentFilters != null && intentFilters.size() > 0) { 12823 PackageParser.ServiceIntentInfo[] array = 12824 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12825 intentFilters.toArray(array); 12826 listCut.add(array); 12827 } 12828 } 12829 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12830 } 12831 12832 public final void addService(PackageParser.Service s) { 12833 mServices.put(s.getComponentName(), s); 12834 if (DEBUG_SHOW_INFO) { 12835 Log.v(TAG, " " 12836 + (s.info.nonLocalizedLabel != null 12837 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12838 Log.v(TAG, " Class=" + s.info.name); 12839 } 12840 final int NI = s.intents.size(); 12841 int j; 12842 for (j=0; j<NI; j++) { 12843 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12844 if (DEBUG_SHOW_INFO) { 12845 Log.v(TAG, " IntentFilter:"); 12846 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12847 } 12848 if (!intent.debugCheck()) { 12849 Log.w(TAG, "==> For Service " + s.info.name); 12850 } 12851 addFilter(intent); 12852 } 12853 } 12854 12855 public final void removeService(PackageParser.Service s) { 12856 mServices.remove(s.getComponentName()); 12857 if (DEBUG_SHOW_INFO) { 12858 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12859 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12860 Log.v(TAG, " Class=" + s.info.name); 12861 } 12862 final int NI = s.intents.size(); 12863 int j; 12864 for (j=0; j<NI; j++) { 12865 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12866 if (DEBUG_SHOW_INFO) { 12867 Log.v(TAG, " IntentFilter:"); 12868 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12869 } 12870 removeFilter(intent); 12871 } 12872 } 12873 12874 @Override 12875 protected boolean allowFilterResult( 12876 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12877 ServiceInfo filterSi = filter.service.info; 12878 for (int i=dest.size()-1; i>=0; i--) { 12879 ServiceInfo destAi = dest.get(i).serviceInfo; 12880 if (destAi.name == filterSi.name 12881 && destAi.packageName == filterSi.packageName) { 12882 return false; 12883 } 12884 } 12885 return true; 12886 } 12887 12888 @Override 12889 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12890 return new PackageParser.ServiceIntentInfo[size]; 12891 } 12892 12893 @Override 12894 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12895 if (!sUserManager.exists(userId)) return true; 12896 PackageParser.Package p = filter.service.owner; 12897 if (p != null) { 12898 PackageSetting ps = (PackageSetting)p.mExtras; 12899 if (ps != null) { 12900 // System apps are never considered stopped for purposes of 12901 // filtering, because there may be no way for the user to 12902 // actually re-launch them. 12903 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12904 && ps.getStopped(userId); 12905 } 12906 } 12907 return false; 12908 } 12909 12910 @Override 12911 protected boolean isPackageForFilter(String packageName, 12912 PackageParser.ServiceIntentInfo info) { 12913 return packageName.equals(info.service.owner.packageName); 12914 } 12915 12916 @Override 12917 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12918 int match, int userId) { 12919 if (!sUserManager.exists(userId)) return null; 12920 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12921 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12922 return null; 12923 } 12924 final PackageParser.Service service = info.service; 12925 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12926 if (ps == null) { 12927 return null; 12928 } 12929 final PackageUserState userState = ps.readUserState(userId); 12930 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12931 userState, userId); 12932 if (si == null) { 12933 return null; 12934 } 12935 final boolean matchVisibleToInstantApp = 12936 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12937 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12938 // throw out filters that aren't visible to ephemeral apps 12939 if (matchVisibleToInstantApp 12940 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12941 return null; 12942 } 12943 // throw out ephemeral filters if we're not explicitly requesting them 12944 if (!isInstantApp && userState.instantApp) { 12945 return null; 12946 } 12947 // throw out instant app filters if updates are available; will trigger 12948 // instant app resolution 12949 if (userState.instantApp && ps.isUpdateAvailable()) { 12950 return null; 12951 } 12952 final ResolveInfo res = new ResolveInfo(); 12953 res.serviceInfo = si; 12954 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12955 res.filter = filter; 12956 } 12957 res.priority = info.getPriority(); 12958 res.preferredOrder = service.owner.mPreferredOrder; 12959 res.match = match; 12960 res.isDefault = info.hasDefault; 12961 res.labelRes = info.labelRes; 12962 res.nonLocalizedLabel = info.nonLocalizedLabel; 12963 res.icon = info.icon; 12964 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12965 return res; 12966 } 12967 12968 @Override 12969 protected void sortResults(List<ResolveInfo> results) { 12970 Collections.sort(results, mResolvePrioritySorter); 12971 } 12972 12973 @Override 12974 protected void dumpFilter(PrintWriter out, String prefix, 12975 PackageParser.ServiceIntentInfo filter) { 12976 out.print(prefix); out.print( 12977 Integer.toHexString(System.identityHashCode(filter.service))); 12978 out.print(' '); 12979 filter.service.printComponentShortName(out); 12980 out.print(" filter "); 12981 out.print(Integer.toHexString(System.identityHashCode(filter))); 12982 if (filter.service.info.permission != null) { 12983 out.print(" permission "); out.println(filter.service.info.permission); 12984 } else { 12985 out.println(); 12986 } 12987 } 12988 12989 @Override 12990 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12991 return filter.service; 12992 } 12993 12994 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12995 PackageParser.Service service = (PackageParser.Service)label; 12996 out.print(prefix); out.print( 12997 Integer.toHexString(System.identityHashCode(service))); 12998 out.print(' '); 12999 service.printComponentShortName(out); 13000 if (count > 1) { 13001 out.print(" ("); out.print(count); out.print(" filters)"); 13002 } 13003 out.println(); 13004 } 13005 13006// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 13007// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 13008// final List<ResolveInfo> retList = Lists.newArrayList(); 13009// while (i.hasNext()) { 13010// final ResolveInfo resolveInfo = (ResolveInfo) i; 13011// if (isEnabledLP(resolveInfo.serviceInfo)) { 13012// retList.add(resolveInfo); 13013// } 13014// } 13015// return retList; 13016// } 13017 13018 // Keys are String (activity class name), values are Activity. 13019 private final ArrayMap<ComponentName, PackageParser.Service> mServices 13020 = new ArrayMap<ComponentName, PackageParser.Service>(); 13021 private int mFlags; 13022 } 13023 13024 private final class ProviderIntentResolver 13025 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 13026 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 13027 boolean defaultOnly, int userId) { 13028 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 13029 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 13030 } 13031 13032 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 13033 int userId) { 13034 if (!sUserManager.exists(userId)) 13035 return null; 13036 mFlags = flags; 13037 return super.queryIntent(intent, resolvedType, 13038 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 13039 userId); 13040 } 13041 13042 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 13043 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 13044 if (!sUserManager.exists(userId)) 13045 return null; 13046 if (packageProviders == null) { 13047 return null; 13048 } 13049 mFlags = flags; 13050 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 13051 final int N = packageProviders.size(); 13052 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 13053 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 13054 13055 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 13056 for (int i = 0; i < N; ++i) { 13057 intentFilters = packageProviders.get(i).intents; 13058 if (intentFilters != null && intentFilters.size() > 0) { 13059 PackageParser.ProviderIntentInfo[] array = 13060 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 13061 intentFilters.toArray(array); 13062 listCut.add(array); 13063 } 13064 } 13065 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 13066 } 13067 13068 public final void addProvider(PackageParser.Provider p) { 13069 if (mProviders.containsKey(p.getComponentName())) { 13070 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 13071 return; 13072 } 13073 13074 mProviders.put(p.getComponentName(), p); 13075 if (DEBUG_SHOW_INFO) { 13076 Log.v(TAG, " " 13077 + (p.info.nonLocalizedLabel != null 13078 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13079 Log.v(TAG, " Class=" + p.info.name); 13080 } 13081 final int NI = p.intents.size(); 13082 int j; 13083 for (j = 0; j < NI; j++) { 13084 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13085 if (DEBUG_SHOW_INFO) { 13086 Log.v(TAG, " IntentFilter:"); 13087 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13088 } 13089 if (!intent.debugCheck()) { 13090 Log.w(TAG, "==> For Provider " + p.info.name); 13091 } 13092 addFilter(intent); 13093 } 13094 } 13095 13096 public final void removeProvider(PackageParser.Provider p) { 13097 mProviders.remove(p.getComponentName()); 13098 if (DEBUG_SHOW_INFO) { 13099 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13100 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13101 Log.v(TAG, " Class=" + p.info.name); 13102 } 13103 final int NI = p.intents.size(); 13104 int j; 13105 for (j = 0; j < NI; j++) { 13106 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13107 if (DEBUG_SHOW_INFO) { 13108 Log.v(TAG, " IntentFilter:"); 13109 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13110 } 13111 removeFilter(intent); 13112 } 13113 } 13114 13115 @Override 13116 protected boolean allowFilterResult( 13117 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13118 ProviderInfo filterPi = filter.provider.info; 13119 for (int i = dest.size() - 1; i >= 0; i--) { 13120 ProviderInfo destPi = dest.get(i).providerInfo; 13121 if (destPi.name == filterPi.name 13122 && destPi.packageName == filterPi.packageName) { 13123 return false; 13124 } 13125 } 13126 return true; 13127 } 13128 13129 @Override 13130 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13131 return new PackageParser.ProviderIntentInfo[size]; 13132 } 13133 13134 @Override 13135 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13136 if (!sUserManager.exists(userId)) 13137 return true; 13138 PackageParser.Package p = filter.provider.owner; 13139 if (p != null) { 13140 PackageSetting ps = (PackageSetting) p.mExtras; 13141 if (ps != null) { 13142 // System apps are never considered stopped for purposes of 13143 // filtering, because there may be no way for the user to 13144 // actually re-launch them. 13145 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13146 && ps.getStopped(userId); 13147 } 13148 } 13149 return false; 13150 } 13151 13152 @Override 13153 protected boolean isPackageForFilter(String packageName, 13154 PackageParser.ProviderIntentInfo info) { 13155 return packageName.equals(info.provider.owner.packageName); 13156 } 13157 13158 @Override 13159 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13160 int match, int userId) { 13161 if (!sUserManager.exists(userId)) 13162 return null; 13163 final PackageParser.ProviderIntentInfo info = filter; 13164 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13165 return null; 13166 } 13167 final PackageParser.Provider provider = info.provider; 13168 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13169 if (ps == null) { 13170 return null; 13171 } 13172 final PackageUserState userState = ps.readUserState(userId); 13173 final boolean matchVisibleToInstantApp = 13174 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13175 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13176 // throw out filters that aren't visible to instant applications 13177 if (matchVisibleToInstantApp 13178 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13179 return null; 13180 } 13181 // throw out instant application filters if we're not explicitly requesting them 13182 if (!isInstantApp && userState.instantApp) { 13183 return null; 13184 } 13185 // throw out instant application filters if updates are available; will trigger 13186 // instant application resolution 13187 if (userState.instantApp && ps.isUpdateAvailable()) { 13188 return null; 13189 } 13190 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13191 userState, userId); 13192 if (pi == null) { 13193 return null; 13194 } 13195 final ResolveInfo res = new ResolveInfo(); 13196 res.providerInfo = pi; 13197 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13198 res.filter = filter; 13199 } 13200 res.priority = info.getPriority(); 13201 res.preferredOrder = provider.owner.mPreferredOrder; 13202 res.match = match; 13203 res.isDefault = info.hasDefault; 13204 res.labelRes = info.labelRes; 13205 res.nonLocalizedLabel = info.nonLocalizedLabel; 13206 res.icon = info.icon; 13207 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13208 return res; 13209 } 13210 13211 @Override 13212 protected void sortResults(List<ResolveInfo> results) { 13213 Collections.sort(results, mResolvePrioritySorter); 13214 } 13215 13216 @Override 13217 protected void dumpFilter(PrintWriter out, String prefix, 13218 PackageParser.ProviderIntentInfo filter) { 13219 out.print(prefix); 13220 out.print( 13221 Integer.toHexString(System.identityHashCode(filter.provider))); 13222 out.print(' '); 13223 filter.provider.printComponentShortName(out); 13224 out.print(" filter "); 13225 out.println(Integer.toHexString(System.identityHashCode(filter))); 13226 } 13227 13228 @Override 13229 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13230 return filter.provider; 13231 } 13232 13233 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13234 PackageParser.Provider provider = (PackageParser.Provider)label; 13235 out.print(prefix); out.print( 13236 Integer.toHexString(System.identityHashCode(provider))); 13237 out.print(' '); 13238 provider.printComponentShortName(out); 13239 if (count > 1) { 13240 out.print(" ("); out.print(count); out.print(" filters)"); 13241 } 13242 out.println(); 13243 } 13244 13245 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13246 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13247 private int mFlags; 13248 } 13249 13250 static final class InstantAppIntentResolver 13251 extends IntentResolver<AuxiliaryResolveInfo.AuxiliaryFilter, 13252 AuxiliaryResolveInfo.AuxiliaryFilter> { 13253 /** 13254 * The result that has the highest defined order. Ordering applies on a 13255 * per-package basis. Mapping is from package name to Pair of order and 13256 * EphemeralResolveInfo. 13257 * <p> 13258 * NOTE: This is implemented as a field variable for convenience and efficiency. 13259 * By having a field variable, we're able to track filter ordering as soon as 13260 * a non-zero order is defined. Otherwise, multiple loops across the result set 13261 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13262 * this needs to be contained entirely within {@link #filterResults}. 13263 */ 13264 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13265 13266 @Override 13267 protected AuxiliaryResolveInfo.AuxiliaryFilter[] newArray(int size) { 13268 return new AuxiliaryResolveInfo.AuxiliaryFilter[size]; 13269 } 13270 13271 @Override 13272 protected boolean isPackageForFilter(String packageName, 13273 AuxiliaryResolveInfo.AuxiliaryFilter responseObj) { 13274 return true; 13275 } 13276 13277 @Override 13278 protected AuxiliaryResolveInfo.AuxiliaryFilter newResult( 13279 AuxiliaryResolveInfo.AuxiliaryFilter responseObj, int match, int userId) { 13280 if (!sUserManager.exists(userId)) { 13281 return null; 13282 } 13283 final String packageName = responseObj.resolveInfo.getPackageName(); 13284 final Integer order = responseObj.getOrder(); 13285 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13286 mOrderResult.get(packageName); 13287 // ordering is enabled and this item's order isn't high enough 13288 if (lastOrderResult != null && lastOrderResult.first >= order) { 13289 return null; 13290 } 13291 final InstantAppResolveInfo res = responseObj.resolveInfo; 13292 if (order > 0) { 13293 // non-zero order, enable ordering 13294 mOrderResult.put(packageName, new Pair<>(order, res)); 13295 } 13296 return responseObj; 13297 } 13298 13299 @Override 13300 protected void filterResults(List<AuxiliaryResolveInfo.AuxiliaryFilter> results) { 13301 // only do work if ordering is enabled [most of the time it won't be] 13302 if (mOrderResult.size() == 0) { 13303 return; 13304 } 13305 int resultSize = results.size(); 13306 for (int i = 0; i < resultSize; i++) { 13307 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13308 final String packageName = info.getPackageName(); 13309 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13310 if (savedInfo == null) { 13311 // package doesn't having ordering 13312 continue; 13313 } 13314 if (savedInfo.second == info) { 13315 // circled back to the highest ordered item; remove from order list 13316 mOrderResult.remove(packageName); 13317 if (mOrderResult.size() == 0) { 13318 // no more ordered items 13319 break; 13320 } 13321 continue; 13322 } 13323 // item has a worse order, remove it from the result list 13324 results.remove(i); 13325 resultSize--; 13326 i--; 13327 } 13328 } 13329 } 13330 13331 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13332 new Comparator<ResolveInfo>() { 13333 public int compare(ResolveInfo r1, ResolveInfo r2) { 13334 int v1 = r1.priority; 13335 int v2 = r2.priority; 13336 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13337 if (v1 != v2) { 13338 return (v1 > v2) ? -1 : 1; 13339 } 13340 v1 = r1.preferredOrder; 13341 v2 = r2.preferredOrder; 13342 if (v1 != v2) { 13343 return (v1 > v2) ? -1 : 1; 13344 } 13345 if (r1.isDefault != r2.isDefault) { 13346 return r1.isDefault ? -1 : 1; 13347 } 13348 v1 = r1.match; 13349 v2 = r2.match; 13350 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13351 if (v1 != v2) { 13352 return (v1 > v2) ? -1 : 1; 13353 } 13354 if (r1.system != r2.system) { 13355 return r1.system ? -1 : 1; 13356 } 13357 if (r1.activityInfo != null) { 13358 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13359 } 13360 if (r1.serviceInfo != null) { 13361 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13362 } 13363 if (r1.providerInfo != null) { 13364 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13365 } 13366 return 0; 13367 } 13368 }; 13369 13370 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13371 new Comparator<ProviderInfo>() { 13372 public int compare(ProviderInfo p1, ProviderInfo p2) { 13373 final int v1 = p1.initOrder; 13374 final int v2 = p2.initOrder; 13375 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13376 } 13377 }; 13378 13379 @Override 13380 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13381 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13382 final int[] userIds, int[] instantUserIds) { 13383 mHandler.post(new Runnable() { 13384 @Override 13385 public void run() { 13386 try { 13387 final IActivityManager am = ActivityManager.getService(); 13388 if (am == null) return; 13389 final int[] resolvedUserIds; 13390 if (userIds == null) { 13391 resolvedUserIds = am.getRunningUserIds(); 13392 } else { 13393 resolvedUserIds = userIds; 13394 } 13395 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13396 resolvedUserIds, false); 13397 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13398 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13399 instantUserIds, true); 13400 } 13401 } catch (RemoteException ex) { 13402 } 13403 } 13404 }); 13405 } 13406 13407 @Override 13408 public void notifyPackageAdded(String packageName) { 13409 final PackageListObserver[] observers; 13410 synchronized (mPackages) { 13411 if (mPackageListObservers.size() == 0) { 13412 return; 13413 } 13414 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13415 } 13416 for (int i = observers.length - 1; i >= 0; --i) { 13417 observers[i].onPackageAdded(packageName); 13418 } 13419 } 13420 13421 @Override 13422 public void notifyPackageRemoved(String packageName) { 13423 final PackageListObserver[] observers; 13424 synchronized (mPackages) { 13425 if (mPackageListObservers.size() == 0) { 13426 return; 13427 } 13428 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13429 } 13430 for (int i = observers.length - 1; i >= 0; --i) { 13431 observers[i].onPackageRemoved(packageName); 13432 } 13433 } 13434 13435 /** 13436 * Sends a broadcast for the given action. 13437 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13438 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13439 * the system and applications allowed to see instant applications to receive package 13440 * lifecycle events for instant applications. 13441 */ 13442 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13443 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13444 int[] userIds, boolean isInstantApp) 13445 throws RemoteException { 13446 for (int id : userIds) { 13447 final Intent intent = new Intent(action, 13448 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13449 final String[] requiredPermissions = 13450 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13451 if (extras != null) { 13452 intent.putExtras(extras); 13453 } 13454 if (targetPkg != null) { 13455 intent.setPackage(targetPkg); 13456 } 13457 // Modify the UID when posting to other users 13458 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13459 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13460 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13461 intent.putExtra(Intent.EXTRA_UID, uid); 13462 } 13463 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13464 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13465 if (DEBUG_BROADCASTS) { 13466 RuntimeException here = new RuntimeException("here"); 13467 here.fillInStackTrace(); 13468 Slog.d(TAG, "Sending to user " + id + ": " 13469 + intent.toShortString(false, true, false, false) 13470 + " " + intent.getExtras(), here); 13471 } 13472 am.broadcastIntent(null, intent, null, finishedReceiver, 13473 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13474 null, finishedReceiver != null, false, id); 13475 } 13476 } 13477 13478 /** 13479 * Check if the external storage media is available. This is true if there 13480 * is a mounted external storage medium or if the external storage is 13481 * emulated. 13482 */ 13483 private boolean isExternalMediaAvailable() { 13484 return mMediaMounted || Environment.isExternalStorageEmulated(); 13485 } 13486 13487 @Override 13488 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13489 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13490 return null; 13491 } 13492 if (!isExternalMediaAvailable()) { 13493 // If the external storage is no longer mounted at this point, 13494 // the caller may not have been able to delete all of this 13495 // packages files and can not delete any more. Bail. 13496 return null; 13497 } 13498 synchronized (mPackages) { 13499 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13500 if (lastPackage != null) { 13501 pkgs.remove(lastPackage); 13502 } 13503 if (pkgs.size() > 0) { 13504 return pkgs.get(0); 13505 } 13506 } 13507 return null; 13508 } 13509 13510 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13511 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13512 userId, andCode ? 1 : 0, packageName); 13513 if (mSystemReady) { 13514 msg.sendToTarget(); 13515 } else { 13516 if (mPostSystemReadyMessages == null) { 13517 mPostSystemReadyMessages = new ArrayList<>(); 13518 } 13519 mPostSystemReadyMessages.add(msg); 13520 } 13521 } 13522 13523 void startCleaningPackages() { 13524 // reader 13525 if (!isExternalMediaAvailable()) { 13526 return; 13527 } 13528 synchronized (mPackages) { 13529 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13530 return; 13531 } 13532 } 13533 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13534 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13535 IActivityManager am = ActivityManager.getService(); 13536 if (am != null) { 13537 int dcsUid = -1; 13538 synchronized (mPackages) { 13539 if (!mDefaultContainerWhitelisted) { 13540 mDefaultContainerWhitelisted = true; 13541 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13542 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13543 } 13544 } 13545 try { 13546 if (dcsUid > 0) { 13547 am.backgroundWhitelistUid(dcsUid); 13548 } 13549 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13550 UserHandle.USER_SYSTEM); 13551 } catch (RemoteException e) { 13552 } 13553 } 13554 } 13555 13556 /** 13557 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13558 * it is acting on behalf on an enterprise or the user). 13559 * 13560 * Note that the ordering of the conditionals in this method is important. The checks we perform 13561 * are as follows, in this order: 13562 * 13563 * 1) If the install is being performed by a system app, we can trust the app to have set the 13564 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13565 * what it is. 13566 * 2) If the install is being performed by a device or profile owner app, the install reason 13567 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13568 * set the install reason correctly. If the app targets an older SDK version where install 13569 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13570 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13571 * 3) In all other cases, the install is being performed by a regular app that is neither part 13572 * of the system nor a device or profile owner. We have no reason to believe that this app is 13573 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13574 * set to enterprise policy and if so, change it to unknown instead. 13575 */ 13576 private int fixUpInstallReason(String installerPackageName, int installerUid, 13577 int installReason) { 13578 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13579 == PERMISSION_GRANTED) { 13580 // If the install is being performed by a system app, we trust that app to have set the 13581 // install reason correctly. 13582 return installReason; 13583 } 13584 13585 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13586 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13587 if (dpm != null) { 13588 ComponentName owner = null; 13589 try { 13590 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13591 if (owner == null) { 13592 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13593 } 13594 } catch (RemoteException e) { 13595 } 13596 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13597 // If the install is being performed by a device or profile owner, the install 13598 // reason should be enterprise policy. 13599 return PackageManager.INSTALL_REASON_POLICY; 13600 } 13601 } 13602 13603 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13604 // If the install is being performed by a regular app (i.e. neither system app nor 13605 // device or profile owner), we have no reason to believe that the app is acting on 13606 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13607 // change it to unknown instead. 13608 return PackageManager.INSTALL_REASON_UNKNOWN; 13609 } 13610 13611 // If the install is being performed by a regular app and the install reason was set to any 13612 // value but enterprise policy, leave the install reason unchanged. 13613 return installReason; 13614 } 13615 13616 void installStage(String packageName, File stagedDir, 13617 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13618 String installerPackageName, int installerUid, UserHandle user, 13619 PackageParser.SigningDetails signingDetails) { 13620 if (DEBUG_INSTANT) { 13621 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13622 Slog.d(TAG, "Ephemeral install of " + packageName); 13623 } 13624 } 13625 final VerificationInfo verificationInfo = new VerificationInfo( 13626 sessionParams.originatingUri, sessionParams.referrerUri, 13627 sessionParams.originatingUid, installerUid); 13628 13629 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13630 13631 final Message msg = mHandler.obtainMessage(INIT_COPY); 13632 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13633 sessionParams.installReason); 13634 final InstallParams params = new InstallParams(origin, null, observer, 13635 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13636 verificationInfo, user, sessionParams.abiOverride, 13637 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13638 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13639 msg.obj = params; 13640 13641 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13642 System.identityHashCode(msg.obj)); 13643 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13644 System.identityHashCode(msg.obj)); 13645 13646 mHandler.sendMessage(msg); 13647 } 13648 13649 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13650 int userId) { 13651 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13652 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13653 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13654 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13655 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13656 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13657 13658 // Send a session commit broadcast 13659 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13660 info.installReason = pkgSetting.getInstallReason(userId); 13661 info.appPackageName = packageName; 13662 sendSessionCommitBroadcast(info, userId); 13663 } 13664 13665 @Override 13666 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13667 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13668 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13669 return; 13670 } 13671 Bundle extras = new Bundle(1); 13672 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13673 final int uid = UserHandle.getUid( 13674 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13675 extras.putInt(Intent.EXTRA_UID, uid); 13676 13677 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13678 packageName, extras, 0, null, null, userIds, instantUserIds); 13679 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13680 mHandler.post(() -> { 13681 for (int userId : userIds) { 13682 sendBootCompletedBroadcastToSystemApp( 13683 packageName, includeStopped, userId); 13684 } 13685 } 13686 ); 13687 } 13688 } 13689 13690 /** 13691 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13692 * automatically without needing an explicit launch. 13693 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13694 */ 13695 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13696 int userId) { 13697 // If user is not running, the app didn't miss any broadcast 13698 if (!mUserManagerInternal.isUserRunning(userId)) { 13699 return; 13700 } 13701 final IActivityManager am = ActivityManager.getService(); 13702 try { 13703 // Deliver LOCKED_BOOT_COMPLETED first 13704 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13705 .setPackage(packageName); 13706 if (includeStopped) { 13707 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13708 } 13709 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13710 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13711 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13712 13713 // Deliver BOOT_COMPLETED only if user is unlocked 13714 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13715 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13716 if (includeStopped) { 13717 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13718 } 13719 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13720 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13721 } 13722 } catch (RemoteException e) { 13723 throw e.rethrowFromSystemServer(); 13724 } 13725 } 13726 13727 @Override 13728 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13729 int userId) { 13730 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13731 PackageSetting pkgSetting; 13732 final int callingUid = Binder.getCallingUid(); 13733 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13734 true /* requireFullPermission */, true /* checkShell */, 13735 "setApplicationHiddenSetting for user " + userId); 13736 13737 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13738 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13739 return false; 13740 } 13741 13742 long callingId = Binder.clearCallingIdentity(); 13743 try { 13744 boolean sendAdded = false; 13745 boolean sendRemoved = false; 13746 // writer 13747 synchronized (mPackages) { 13748 pkgSetting = mSettings.mPackages.get(packageName); 13749 if (pkgSetting == null) { 13750 return false; 13751 } 13752 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13753 return false; 13754 } 13755 // Do not allow "android" is being disabled 13756 if ("android".equals(packageName)) { 13757 Slog.w(TAG, "Cannot hide package: android"); 13758 return false; 13759 } 13760 // Cannot hide static shared libs as they are considered 13761 // a part of the using app (emulating static linking). Also 13762 // static libs are installed always on internal storage. 13763 PackageParser.Package pkg = mPackages.get(packageName); 13764 if (pkg != null && pkg.staticSharedLibName != null) { 13765 Slog.w(TAG, "Cannot hide package: " + packageName 13766 + " providing static shared library: " 13767 + pkg.staticSharedLibName); 13768 return false; 13769 } 13770 // Only allow protected packages to hide themselves. 13771 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13772 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13773 Slog.w(TAG, "Not hiding protected package: " + packageName); 13774 return false; 13775 } 13776 13777 if (pkgSetting.getHidden(userId) != hidden) { 13778 pkgSetting.setHidden(hidden, userId); 13779 mSettings.writePackageRestrictionsLPr(userId); 13780 if (hidden) { 13781 sendRemoved = true; 13782 } else { 13783 sendAdded = true; 13784 } 13785 } 13786 } 13787 if (sendAdded) { 13788 sendPackageAddedForUser(packageName, pkgSetting, userId); 13789 return true; 13790 } 13791 if (sendRemoved) { 13792 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13793 "hiding pkg"); 13794 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13795 return true; 13796 } 13797 } finally { 13798 Binder.restoreCallingIdentity(callingId); 13799 } 13800 return false; 13801 } 13802 13803 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13804 int userId) { 13805 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13806 info.removedPackage = packageName; 13807 info.installerPackageName = pkgSetting.installerPackageName; 13808 info.removedUsers = new int[] {userId}; 13809 info.broadcastUsers = new int[] {userId}; 13810 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13811 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13812 } 13813 13814 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13815 if (pkgList.length > 0) { 13816 Bundle extras = new Bundle(1); 13817 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13818 13819 sendPackageBroadcast( 13820 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13821 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13822 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13823 new int[] {userId}, null); 13824 } 13825 } 13826 13827 /** 13828 * Returns true if application is not found or there was an error. Otherwise it returns 13829 * the hidden state of the package for the given user. 13830 */ 13831 @Override 13832 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13833 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13834 final int callingUid = Binder.getCallingUid(); 13835 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13836 true /* requireFullPermission */, false /* checkShell */, 13837 "getApplicationHidden for user " + userId); 13838 PackageSetting ps; 13839 long callingId = Binder.clearCallingIdentity(); 13840 try { 13841 // writer 13842 synchronized (mPackages) { 13843 ps = mSettings.mPackages.get(packageName); 13844 if (ps == null) { 13845 return true; 13846 } 13847 if (filterAppAccessLPr(ps, callingUid, userId)) { 13848 return true; 13849 } 13850 return ps.getHidden(userId); 13851 } 13852 } finally { 13853 Binder.restoreCallingIdentity(callingId); 13854 } 13855 } 13856 13857 /** 13858 * @hide 13859 */ 13860 @Override 13861 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13862 int installReason) { 13863 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13864 null); 13865 PackageSetting pkgSetting; 13866 final int callingUid = Binder.getCallingUid(); 13867 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13868 true /* requireFullPermission */, true /* checkShell */, 13869 "installExistingPackage for user " + userId); 13870 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13871 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13872 } 13873 13874 long callingId = Binder.clearCallingIdentity(); 13875 try { 13876 boolean installed = false; 13877 final boolean instantApp = 13878 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13879 final boolean fullApp = 13880 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13881 13882 // writer 13883 synchronized (mPackages) { 13884 pkgSetting = mSettings.mPackages.get(packageName); 13885 if (pkgSetting == null) { 13886 return PackageManager.INSTALL_FAILED_INVALID_URI; 13887 } 13888 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13889 // only allow the existing package to be used if it's installed as a full 13890 // application for at least one user 13891 boolean installAllowed = false; 13892 for (int checkUserId : sUserManager.getUserIds()) { 13893 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13894 if (installAllowed) { 13895 break; 13896 } 13897 } 13898 if (!installAllowed) { 13899 return PackageManager.INSTALL_FAILED_INVALID_URI; 13900 } 13901 } 13902 if (!pkgSetting.getInstalled(userId)) { 13903 pkgSetting.setInstalled(true, userId); 13904 pkgSetting.setHidden(false, userId); 13905 pkgSetting.setInstallReason(installReason, userId); 13906 mSettings.writePackageRestrictionsLPr(userId); 13907 mSettings.writeKernelMappingLPr(pkgSetting); 13908 installed = true; 13909 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13910 // upgrade app from instant to full; we don't allow app downgrade 13911 installed = true; 13912 } 13913 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13914 } 13915 13916 if (installed) { 13917 if (pkgSetting.pkg != null) { 13918 synchronized (mInstallLock) { 13919 // We don't need to freeze for a brand new install 13920 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13921 } 13922 } 13923 sendPackageAddedForUser(packageName, pkgSetting, userId); 13924 synchronized (mPackages) { 13925 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13926 } 13927 } 13928 } finally { 13929 Binder.restoreCallingIdentity(callingId); 13930 } 13931 13932 return PackageManager.INSTALL_SUCCEEDED; 13933 } 13934 13935 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13936 boolean instantApp, boolean fullApp) { 13937 // no state specified; do nothing 13938 if (!instantApp && !fullApp) { 13939 return; 13940 } 13941 if (userId != UserHandle.USER_ALL) { 13942 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13943 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13944 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13945 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13946 } 13947 } else { 13948 for (int currentUserId : sUserManager.getUserIds()) { 13949 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13950 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13951 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13952 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13953 } 13954 } 13955 } 13956 } 13957 13958 boolean isUserRestricted(int userId, String restrictionKey) { 13959 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13960 if (restrictions.getBoolean(restrictionKey, false)) { 13961 Log.w(TAG, "User is restricted: " + restrictionKey); 13962 return true; 13963 } 13964 return false; 13965 } 13966 13967 @Override 13968 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13969 int userId) { 13970 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13971 final int callingUid = Binder.getCallingUid(); 13972 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13973 true /* requireFullPermission */, true /* checkShell */, 13974 "setPackagesSuspended for user " + userId); 13975 13976 if (ArrayUtils.isEmpty(packageNames)) { 13977 return packageNames; 13978 } 13979 13980 // List of package names for whom the suspended state has changed. 13981 List<String> changedPackages = new ArrayList<>(packageNames.length); 13982 // List of package names for whom the suspended state is not set as requested in this 13983 // method. 13984 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13985 long callingId = Binder.clearCallingIdentity(); 13986 try { 13987 for (int i = 0; i < packageNames.length; i++) { 13988 String packageName = packageNames[i]; 13989 boolean changed = false; 13990 final int appId; 13991 synchronized (mPackages) { 13992 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13993 if (pkgSetting == null 13994 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13995 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13996 + "\". Skipping suspending/un-suspending."); 13997 unactionedPackages.add(packageName); 13998 continue; 13999 } 14000 appId = pkgSetting.appId; 14001 if (pkgSetting.getSuspended(userId) != suspended) { 14002 if (!canSuspendPackageForUserLocked(packageName, userId)) { 14003 unactionedPackages.add(packageName); 14004 continue; 14005 } 14006 pkgSetting.setSuspended(suspended, userId); 14007 mSettings.writePackageRestrictionsLPr(userId); 14008 changed = true; 14009 changedPackages.add(packageName); 14010 } 14011 } 14012 14013 if (changed && suspended) { 14014 killApplication(packageName, UserHandle.getUid(userId, appId), 14015 "suspending package"); 14016 } 14017 } 14018 } finally { 14019 Binder.restoreCallingIdentity(callingId); 14020 } 14021 14022 if (!changedPackages.isEmpty()) { 14023 sendPackagesSuspendedForUser(changedPackages.toArray( 14024 new String[changedPackages.size()]), userId, suspended); 14025 } 14026 14027 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 14028 } 14029 14030 @Override 14031 public boolean isPackageSuspendedForUser(String packageName, int userId) { 14032 final int callingUid = Binder.getCallingUid(); 14033 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 14034 true /* requireFullPermission */, false /* checkShell */, 14035 "isPackageSuspendedForUser for user " + userId); 14036 synchronized (mPackages) { 14037 final PackageSetting ps = mSettings.mPackages.get(packageName); 14038 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 14039 throw new IllegalArgumentException("Unknown target package: " + packageName); 14040 } 14041 return ps.getSuspended(userId); 14042 } 14043 } 14044 14045 @GuardedBy("mPackages") 14046 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 14047 if (isPackageDeviceAdmin(packageName, userId)) { 14048 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14049 + "\": has an active device admin"); 14050 return false; 14051 } 14052 14053 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 14054 if (packageName.equals(activeLauncherPackageName)) { 14055 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14056 + "\": contains the active launcher"); 14057 return false; 14058 } 14059 14060 if (packageName.equals(mRequiredInstallerPackage)) { 14061 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14062 + "\": required for package installation"); 14063 return false; 14064 } 14065 14066 if (packageName.equals(mRequiredUninstallerPackage)) { 14067 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14068 + "\": required for package uninstallation"); 14069 return false; 14070 } 14071 14072 if (packageName.equals(mRequiredVerifierPackage)) { 14073 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14074 + "\": required for package verification"); 14075 return false; 14076 } 14077 14078 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14079 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14080 + "\": is the default dialer"); 14081 return false; 14082 } 14083 14084 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14085 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14086 + "\": protected package"); 14087 return false; 14088 } 14089 14090 // Cannot suspend static shared libs as they are considered 14091 // a part of the using app (emulating static linking). Also 14092 // static libs are installed always on internal storage. 14093 PackageParser.Package pkg = mPackages.get(packageName); 14094 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14095 Slog.w(TAG, "Cannot suspend package: " + packageName 14096 + " providing static shared library: " 14097 + pkg.staticSharedLibName); 14098 return false; 14099 } 14100 14101 return true; 14102 } 14103 14104 private String getActiveLauncherPackageName(int userId) { 14105 Intent intent = new Intent(Intent.ACTION_MAIN); 14106 intent.addCategory(Intent.CATEGORY_HOME); 14107 ResolveInfo resolveInfo = resolveIntent( 14108 intent, 14109 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14110 PackageManager.MATCH_DEFAULT_ONLY, 14111 userId); 14112 14113 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14114 } 14115 14116 private String getDefaultDialerPackageName(int userId) { 14117 synchronized (mPackages) { 14118 return mSettings.getDefaultDialerPackageNameLPw(userId); 14119 } 14120 } 14121 14122 @Override 14123 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14124 mContext.enforceCallingOrSelfPermission( 14125 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14126 "Only package verification agents can verify applications"); 14127 14128 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14129 final PackageVerificationResponse response = new PackageVerificationResponse( 14130 verificationCode, Binder.getCallingUid()); 14131 msg.arg1 = id; 14132 msg.obj = response; 14133 mHandler.sendMessage(msg); 14134 } 14135 14136 @Override 14137 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14138 long millisecondsToDelay) { 14139 mContext.enforceCallingOrSelfPermission( 14140 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14141 "Only package verification agents can extend verification timeouts"); 14142 14143 final PackageVerificationState state = mPendingVerification.get(id); 14144 final PackageVerificationResponse response = new PackageVerificationResponse( 14145 verificationCodeAtTimeout, Binder.getCallingUid()); 14146 14147 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14148 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14149 } 14150 if (millisecondsToDelay < 0) { 14151 millisecondsToDelay = 0; 14152 } 14153 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14154 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14155 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14156 } 14157 14158 if ((state != null) && !state.timeoutExtended()) { 14159 state.extendTimeout(); 14160 14161 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14162 msg.arg1 = id; 14163 msg.obj = response; 14164 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14165 } 14166 } 14167 14168 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14169 int verificationCode, UserHandle user) { 14170 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14171 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14172 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14173 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14174 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14175 14176 mContext.sendBroadcastAsUser(intent, user, 14177 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14178 } 14179 14180 private ComponentName matchComponentForVerifier(String packageName, 14181 List<ResolveInfo> receivers) { 14182 ActivityInfo targetReceiver = null; 14183 14184 final int NR = receivers.size(); 14185 for (int i = 0; i < NR; i++) { 14186 final ResolveInfo info = receivers.get(i); 14187 if (info.activityInfo == null) { 14188 continue; 14189 } 14190 14191 if (packageName.equals(info.activityInfo.packageName)) { 14192 targetReceiver = info.activityInfo; 14193 break; 14194 } 14195 } 14196 14197 if (targetReceiver == null) { 14198 return null; 14199 } 14200 14201 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14202 } 14203 14204 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14205 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14206 if (pkgInfo.verifiers.length == 0) { 14207 return null; 14208 } 14209 14210 final int N = pkgInfo.verifiers.length; 14211 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14212 for (int i = 0; i < N; i++) { 14213 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14214 14215 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14216 receivers); 14217 if (comp == null) { 14218 continue; 14219 } 14220 14221 final int verifierUid = getUidForVerifier(verifierInfo); 14222 if (verifierUid == -1) { 14223 continue; 14224 } 14225 14226 if (DEBUG_VERIFY) { 14227 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14228 + " with the correct signature"); 14229 } 14230 sufficientVerifiers.add(comp); 14231 verificationState.addSufficientVerifier(verifierUid); 14232 } 14233 14234 return sufficientVerifiers; 14235 } 14236 14237 private int getUidForVerifier(VerifierInfo verifierInfo) { 14238 synchronized (mPackages) { 14239 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14240 if (pkg == null) { 14241 return -1; 14242 } else if (pkg.mSigningDetails.signatures.length != 1) { 14243 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14244 + " has more than one signature; ignoring"); 14245 return -1; 14246 } 14247 14248 /* 14249 * If the public key of the package's signature does not match 14250 * our expected public key, then this is a different package and 14251 * we should skip. 14252 */ 14253 14254 final byte[] expectedPublicKey; 14255 try { 14256 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14257 final PublicKey publicKey = verifierSig.getPublicKey(); 14258 expectedPublicKey = publicKey.getEncoded(); 14259 } catch (CertificateException e) { 14260 return -1; 14261 } 14262 14263 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14264 14265 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14266 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14267 + " does not have the expected public key; ignoring"); 14268 return -1; 14269 } 14270 14271 return pkg.applicationInfo.uid; 14272 } 14273 } 14274 14275 @Override 14276 public void finishPackageInstall(int token, boolean didLaunch) { 14277 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14278 14279 if (DEBUG_INSTALL) { 14280 Slog.v(TAG, "BM finishing package install for " + token); 14281 } 14282 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14283 14284 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14285 mHandler.sendMessage(msg); 14286 } 14287 14288 /** 14289 * Get the verification agent timeout. Used for both the APK verifier and the 14290 * intent filter verifier. 14291 * 14292 * @return verification timeout in milliseconds 14293 */ 14294 private long getVerificationTimeout() { 14295 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14296 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14297 DEFAULT_VERIFICATION_TIMEOUT); 14298 } 14299 14300 /** 14301 * Get the default verification agent response code. 14302 * 14303 * @return default verification response code 14304 */ 14305 private int getDefaultVerificationResponse(UserHandle user) { 14306 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14307 return PackageManager.VERIFICATION_REJECT; 14308 } 14309 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14310 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14311 DEFAULT_VERIFICATION_RESPONSE); 14312 } 14313 14314 /** 14315 * Check whether or not package verification has been enabled. 14316 * 14317 * @return true if verification should be performed 14318 */ 14319 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14320 if (!DEFAULT_VERIFY_ENABLE) { 14321 return false; 14322 } 14323 14324 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14325 14326 // Check if installing from ADB 14327 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14328 // Do not run verification in a test harness environment 14329 if (ActivityManager.isRunningInTestHarness()) { 14330 return false; 14331 } 14332 if (ensureVerifyAppsEnabled) { 14333 return true; 14334 } 14335 // Check if the developer does not want package verification for ADB installs 14336 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14337 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14338 return false; 14339 } 14340 } else { 14341 // only when not installed from ADB, skip verification for instant apps when 14342 // the installer and verifier are the same. 14343 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14344 if (mInstantAppInstallerActivity != null 14345 && mInstantAppInstallerActivity.packageName.equals( 14346 mRequiredVerifierPackage)) { 14347 try { 14348 mContext.getSystemService(AppOpsManager.class) 14349 .checkPackage(installerUid, mRequiredVerifierPackage); 14350 if (DEBUG_VERIFY) { 14351 Slog.i(TAG, "disable verification for instant app"); 14352 } 14353 return false; 14354 } catch (SecurityException ignore) { } 14355 } 14356 } 14357 } 14358 14359 if (ensureVerifyAppsEnabled) { 14360 return true; 14361 } 14362 14363 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14364 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14365 } 14366 14367 @Override 14368 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14369 throws RemoteException { 14370 mContext.enforceCallingOrSelfPermission( 14371 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14372 "Only intentfilter verification agents can verify applications"); 14373 14374 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14375 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14376 Binder.getCallingUid(), verificationCode, failedDomains); 14377 msg.arg1 = id; 14378 msg.obj = response; 14379 mHandler.sendMessage(msg); 14380 } 14381 14382 @Override 14383 public int getIntentVerificationStatus(String packageName, int userId) { 14384 final int callingUid = Binder.getCallingUid(); 14385 if (UserHandle.getUserId(callingUid) != userId) { 14386 mContext.enforceCallingOrSelfPermission( 14387 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14388 "getIntentVerificationStatus" + userId); 14389 } 14390 if (getInstantAppPackageName(callingUid) != null) { 14391 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14392 } 14393 synchronized (mPackages) { 14394 final PackageSetting ps = mSettings.mPackages.get(packageName); 14395 if (ps == null 14396 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14397 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14398 } 14399 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14400 } 14401 } 14402 14403 @Override 14404 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14405 mContext.enforceCallingOrSelfPermission( 14406 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14407 14408 boolean result = false; 14409 synchronized (mPackages) { 14410 final PackageSetting ps = mSettings.mPackages.get(packageName); 14411 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14412 return false; 14413 } 14414 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14415 } 14416 if (result) { 14417 scheduleWritePackageRestrictionsLocked(userId); 14418 } 14419 return result; 14420 } 14421 14422 @Override 14423 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14424 String packageName) { 14425 final int callingUid = Binder.getCallingUid(); 14426 if (getInstantAppPackageName(callingUid) != null) { 14427 return ParceledListSlice.emptyList(); 14428 } 14429 synchronized (mPackages) { 14430 final PackageSetting ps = mSettings.mPackages.get(packageName); 14431 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14432 return ParceledListSlice.emptyList(); 14433 } 14434 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14435 } 14436 } 14437 14438 @Override 14439 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14440 if (TextUtils.isEmpty(packageName)) { 14441 return ParceledListSlice.emptyList(); 14442 } 14443 final int callingUid = Binder.getCallingUid(); 14444 final int callingUserId = UserHandle.getUserId(callingUid); 14445 synchronized (mPackages) { 14446 PackageParser.Package pkg = mPackages.get(packageName); 14447 if (pkg == null || pkg.activities == null) { 14448 return ParceledListSlice.emptyList(); 14449 } 14450 if (pkg.mExtras == null) { 14451 return ParceledListSlice.emptyList(); 14452 } 14453 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14454 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14455 return ParceledListSlice.emptyList(); 14456 } 14457 final int count = pkg.activities.size(); 14458 ArrayList<IntentFilter> result = new ArrayList<>(); 14459 for (int n=0; n<count; n++) { 14460 PackageParser.Activity activity = pkg.activities.get(n); 14461 if (activity.intents != null && activity.intents.size() > 0) { 14462 result.addAll(activity.intents); 14463 } 14464 } 14465 return new ParceledListSlice<>(result); 14466 } 14467 } 14468 14469 @Override 14470 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14471 mContext.enforceCallingOrSelfPermission( 14472 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14473 if (UserHandle.getCallingUserId() != userId) { 14474 mContext.enforceCallingOrSelfPermission( 14475 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14476 } 14477 14478 synchronized (mPackages) { 14479 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14480 if (packageName != null) { 14481 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14482 packageName, userId); 14483 } 14484 return result; 14485 } 14486 } 14487 14488 @Override 14489 public String getDefaultBrowserPackageName(int userId) { 14490 if (UserHandle.getCallingUserId() != userId) { 14491 mContext.enforceCallingOrSelfPermission( 14492 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14493 } 14494 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14495 return null; 14496 } 14497 synchronized (mPackages) { 14498 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14499 } 14500 } 14501 14502 /** 14503 * Get the "allow unknown sources" setting. 14504 * 14505 * @return the current "allow unknown sources" setting 14506 */ 14507 private int getUnknownSourcesSettings() { 14508 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14509 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14510 -1); 14511 } 14512 14513 @Override 14514 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14515 final int callingUid = Binder.getCallingUid(); 14516 if (getInstantAppPackageName(callingUid) != null) { 14517 return; 14518 } 14519 // writer 14520 synchronized (mPackages) { 14521 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14522 if (targetPackageSetting == null 14523 || filterAppAccessLPr( 14524 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14525 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14526 } 14527 14528 PackageSetting installerPackageSetting; 14529 if (installerPackageName != null) { 14530 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14531 if (installerPackageSetting == null) { 14532 throw new IllegalArgumentException("Unknown installer package: " 14533 + installerPackageName); 14534 } 14535 } else { 14536 installerPackageSetting = null; 14537 } 14538 14539 Signature[] callerSignature; 14540 Object obj = mSettings.getUserIdLPr(callingUid); 14541 if (obj != null) { 14542 if (obj instanceof SharedUserSetting) { 14543 callerSignature = 14544 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14545 } else if (obj instanceof PackageSetting) { 14546 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14547 } else { 14548 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14549 } 14550 } else { 14551 throw new SecurityException("Unknown calling UID: " + callingUid); 14552 } 14553 14554 // Verify: can't set installerPackageName to a package that is 14555 // not signed with the same cert as the caller. 14556 if (installerPackageSetting != null) { 14557 if (compareSignatures(callerSignature, 14558 installerPackageSetting.signatures.mSigningDetails.signatures) 14559 != PackageManager.SIGNATURE_MATCH) { 14560 throw new SecurityException( 14561 "Caller does not have same cert as new installer package " 14562 + installerPackageName); 14563 } 14564 } 14565 14566 // Verify: if target already has an installer package, it must 14567 // be signed with the same cert as the caller. 14568 if (targetPackageSetting.installerPackageName != null) { 14569 PackageSetting setting = mSettings.mPackages.get( 14570 targetPackageSetting.installerPackageName); 14571 // If the currently set package isn't valid, then it's always 14572 // okay to change it. 14573 if (setting != null) { 14574 if (compareSignatures(callerSignature, 14575 setting.signatures.mSigningDetails.signatures) 14576 != PackageManager.SIGNATURE_MATCH) { 14577 throw new SecurityException( 14578 "Caller does not have same cert as old installer package " 14579 + targetPackageSetting.installerPackageName); 14580 } 14581 } 14582 } 14583 14584 // Okay! 14585 targetPackageSetting.installerPackageName = installerPackageName; 14586 if (installerPackageName != null) { 14587 mSettings.mInstallerPackages.add(installerPackageName); 14588 } 14589 scheduleWriteSettingsLocked(); 14590 } 14591 } 14592 14593 @Override 14594 public void setApplicationCategoryHint(String packageName, int categoryHint, 14595 String callerPackageName) { 14596 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14597 throw new SecurityException("Instant applications don't have access to this method"); 14598 } 14599 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14600 callerPackageName); 14601 synchronized (mPackages) { 14602 PackageSetting ps = mSettings.mPackages.get(packageName); 14603 if (ps == null) { 14604 throw new IllegalArgumentException("Unknown target package " + packageName); 14605 } 14606 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14607 throw new IllegalArgumentException("Unknown target package " + packageName); 14608 } 14609 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14610 throw new IllegalArgumentException("Calling package " + callerPackageName 14611 + " is not installer for " + packageName); 14612 } 14613 14614 if (ps.categoryHint != categoryHint) { 14615 ps.categoryHint = categoryHint; 14616 scheduleWriteSettingsLocked(); 14617 } 14618 } 14619 } 14620 14621 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14622 // Queue up an async operation since the package installation may take a little while. 14623 mHandler.post(new Runnable() { 14624 public void run() { 14625 mHandler.removeCallbacks(this); 14626 // Result object to be returned 14627 PackageInstalledInfo res = new PackageInstalledInfo(); 14628 res.setReturnCode(currentStatus); 14629 res.uid = -1; 14630 res.pkg = null; 14631 res.removedInfo = null; 14632 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14633 args.doPreInstall(res.returnCode); 14634 synchronized (mInstallLock) { 14635 installPackageTracedLI(args, res); 14636 } 14637 args.doPostInstall(res.returnCode, res.uid); 14638 } 14639 14640 // A restore should be performed at this point if (a) the install 14641 // succeeded, (b) the operation is not an update, and (c) the new 14642 // package has not opted out of backup participation. 14643 final boolean update = res.removedInfo != null 14644 && res.removedInfo.removedPackage != null; 14645 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14646 boolean doRestore = !update 14647 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14648 14649 // Set up the post-install work request bookkeeping. This will be used 14650 // and cleaned up by the post-install event handling regardless of whether 14651 // there's a restore pass performed. Token values are >= 1. 14652 int token; 14653 if (mNextInstallToken < 0) mNextInstallToken = 1; 14654 token = mNextInstallToken++; 14655 14656 PostInstallData data = new PostInstallData(args, res); 14657 mRunningInstalls.put(token, data); 14658 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14659 14660 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14661 // Pass responsibility to the Backup Manager. It will perform a 14662 // restore if appropriate, then pass responsibility back to the 14663 // Package Manager to run the post-install observer callbacks 14664 // and broadcasts. 14665 IBackupManager bm = IBackupManager.Stub.asInterface( 14666 ServiceManager.getService(Context.BACKUP_SERVICE)); 14667 if (bm != null) { 14668 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14669 + " to BM for possible restore"); 14670 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14671 try { 14672 // TODO: http://b/22388012 14673 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14674 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14675 } else { 14676 doRestore = false; 14677 } 14678 } catch (RemoteException e) { 14679 // can't happen; the backup manager is local 14680 } catch (Exception e) { 14681 Slog.e(TAG, "Exception trying to enqueue restore", e); 14682 doRestore = false; 14683 } 14684 } else { 14685 Slog.e(TAG, "Backup Manager not found!"); 14686 doRestore = false; 14687 } 14688 } 14689 14690 if (!doRestore) { 14691 // No restore possible, or the Backup Manager was mysteriously not 14692 // available -- just fire the post-install work request directly. 14693 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14694 14695 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14696 14697 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14698 mHandler.sendMessage(msg); 14699 } 14700 } 14701 }); 14702 } 14703 14704 /** 14705 * Callback from PackageSettings whenever an app is first transitioned out of the 14706 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14707 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14708 * here whether the app is the target of an ongoing install, and only send the 14709 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14710 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14711 * handling. 14712 */ 14713 void notifyFirstLaunch(final String packageName, final String installerPackage, 14714 final int userId) { 14715 // Serialize this with the rest of the install-process message chain. In the 14716 // restore-at-install case, this Runnable will necessarily run before the 14717 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14718 // are coherent. In the non-restore case, the app has already completed install 14719 // and been launched through some other means, so it is not in a problematic 14720 // state for observers to see the FIRST_LAUNCH signal. 14721 mHandler.post(new Runnable() { 14722 @Override 14723 public void run() { 14724 for (int i = 0; i < mRunningInstalls.size(); i++) { 14725 final PostInstallData data = mRunningInstalls.valueAt(i); 14726 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14727 continue; 14728 } 14729 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14730 // right package; but is it for the right user? 14731 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14732 if (userId == data.res.newUsers[uIndex]) { 14733 if (DEBUG_BACKUP) { 14734 Slog.i(TAG, "Package " + packageName 14735 + " being restored so deferring FIRST_LAUNCH"); 14736 } 14737 return; 14738 } 14739 } 14740 } 14741 } 14742 // didn't find it, so not being restored 14743 if (DEBUG_BACKUP) { 14744 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14745 } 14746 final boolean isInstantApp = isInstantApp(packageName, userId); 14747 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14748 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14749 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14750 } 14751 }); 14752 } 14753 14754 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14755 int[] userIds, int[] instantUserIds) { 14756 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14757 installerPkg, null, userIds, instantUserIds); 14758 } 14759 14760 private abstract class HandlerParams { 14761 private static final int MAX_RETRIES = 4; 14762 14763 /** 14764 * Number of times startCopy() has been attempted and had a non-fatal 14765 * error. 14766 */ 14767 private int mRetries = 0; 14768 14769 /** User handle for the user requesting the information or installation. */ 14770 private final UserHandle mUser; 14771 String traceMethod; 14772 int traceCookie; 14773 14774 HandlerParams(UserHandle user) { 14775 mUser = user; 14776 } 14777 14778 UserHandle getUser() { 14779 return mUser; 14780 } 14781 14782 HandlerParams setTraceMethod(String traceMethod) { 14783 this.traceMethod = traceMethod; 14784 return this; 14785 } 14786 14787 HandlerParams setTraceCookie(int traceCookie) { 14788 this.traceCookie = traceCookie; 14789 return this; 14790 } 14791 14792 final boolean startCopy() { 14793 boolean res; 14794 try { 14795 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14796 14797 if (++mRetries > MAX_RETRIES) { 14798 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14799 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14800 handleServiceError(); 14801 return false; 14802 } else { 14803 handleStartCopy(); 14804 res = true; 14805 } 14806 } catch (RemoteException e) { 14807 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14808 mHandler.sendEmptyMessage(MCS_RECONNECT); 14809 res = false; 14810 } 14811 handleReturnCode(); 14812 return res; 14813 } 14814 14815 final void serviceError() { 14816 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14817 handleServiceError(); 14818 handleReturnCode(); 14819 } 14820 14821 abstract void handleStartCopy() throws RemoteException; 14822 abstract void handleServiceError(); 14823 abstract void handleReturnCode(); 14824 } 14825 14826 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14827 for (File path : paths) { 14828 try { 14829 mcs.clearDirectory(path.getAbsolutePath()); 14830 } catch (RemoteException e) { 14831 } 14832 } 14833 } 14834 14835 static class OriginInfo { 14836 /** 14837 * Location where install is coming from, before it has been 14838 * copied/renamed into place. This could be a single monolithic APK 14839 * file, or a cluster directory. This location may be untrusted. 14840 */ 14841 final File file; 14842 14843 /** 14844 * Flag indicating that {@link #file} or {@link #cid} has already been 14845 * staged, meaning downstream users don't need to defensively copy the 14846 * contents. 14847 */ 14848 final boolean staged; 14849 14850 /** 14851 * Flag indicating that {@link #file} or {@link #cid} is an already 14852 * installed app that is being moved. 14853 */ 14854 final boolean existing; 14855 14856 final String resolvedPath; 14857 final File resolvedFile; 14858 14859 static OriginInfo fromNothing() { 14860 return new OriginInfo(null, false, false); 14861 } 14862 14863 static OriginInfo fromUntrustedFile(File file) { 14864 return new OriginInfo(file, false, false); 14865 } 14866 14867 static OriginInfo fromExistingFile(File file) { 14868 return new OriginInfo(file, false, true); 14869 } 14870 14871 static OriginInfo fromStagedFile(File file) { 14872 return new OriginInfo(file, true, false); 14873 } 14874 14875 private OriginInfo(File file, boolean staged, boolean existing) { 14876 this.file = file; 14877 this.staged = staged; 14878 this.existing = existing; 14879 14880 if (file != null) { 14881 resolvedPath = file.getAbsolutePath(); 14882 resolvedFile = file; 14883 } else { 14884 resolvedPath = null; 14885 resolvedFile = null; 14886 } 14887 } 14888 } 14889 14890 static class MoveInfo { 14891 final int moveId; 14892 final String fromUuid; 14893 final String toUuid; 14894 final String packageName; 14895 final String dataAppName; 14896 final int appId; 14897 final String seinfo; 14898 final int targetSdkVersion; 14899 14900 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14901 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14902 this.moveId = moveId; 14903 this.fromUuid = fromUuid; 14904 this.toUuid = toUuid; 14905 this.packageName = packageName; 14906 this.dataAppName = dataAppName; 14907 this.appId = appId; 14908 this.seinfo = seinfo; 14909 this.targetSdkVersion = targetSdkVersion; 14910 } 14911 } 14912 14913 static class VerificationInfo { 14914 /** A constant used to indicate that a uid value is not present. */ 14915 public static final int NO_UID = -1; 14916 14917 /** URI referencing where the package was downloaded from. */ 14918 final Uri originatingUri; 14919 14920 /** HTTP referrer URI associated with the originatingURI. */ 14921 final Uri referrer; 14922 14923 /** UID of the application that the install request originated from. */ 14924 final int originatingUid; 14925 14926 /** UID of application requesting the install */ 14927 final int installerUid; 14928 14929 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14930 this.originatingUri = originatingUri; 14931 this.referrer = referrer; 14932 this.originatingUid = originatingUid; 14933 this.installerUid = installerUid; 14934 } 14935 } 14936 14937 class InstallParams extends HandlerParams { 14938 final OriginInfo origin; 14939 final MoveInfo move; 14940 final IPackageInstallObserver2 observer; 14941 int installFlags; 14942 final String installerPackageName; 14943 final String volumeUuid; 14944 private InstallArgs mArgs; 14945 private int mRet; 14946 final String packageAbiOverride; 14947 final String[] grantedRuntimePermissions; 14948 final VerificationInfo verificationInfo; 14949 final PackageParser.SigningDetails signingDetails; 14950 final int installReason; 14951 14952 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14953 int installFlags, String installerPackageName, String volumeUuid, 14954 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14955 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14956 super(user); 14957 this.origin = origin; 14958 this.move = move; 14959 this.observer = observer; 14960 this.installFlags = installFlags; 14961 this.installerPackageName = installerPackageName; 14962 this.volumeUuid = volumeUuid; 14963 this.verificationInfo = verificationInfo; 14964 this.packageAbiOverride = packageAbiOverride; 14965 this.grantedRuntimePermissions = grantedPermissions; 14966 this.signingDetails = signingDetails; 14967 this.installReason = installReason; 14968 } 14969 14970 @Override 14971 public String toString() { 14972 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14973 + " file=" + origin.file + "}"; 14974 } 14975 14976 private int installLocationPolicy(PackageInfoLite pkgLite) { 14977 String packageName = pkgLite.packageName; 14978 int installLocation = pkgLite.installLocation; 14979 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14980 // reader 14981 synchronized (mPackages) { 14982 // Currently installed package which the new package is attempting to replace or 14983 // null if no such package is installed. 14984 PackageParser.Package installedPkg = mPackages.get(packageName); 14985 // Package which currently owns the data which the new package will own if installed. 14986 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14987 // will be null whereas dataOwnerPkg will contain information about the package 14988 // which was uninstalled while keeping its data. 14989 PackageParser.Package dataOwnerPkg = installedPkg; 14990 if (dataOwnerPkg == null) { 14991 PackageSetting ps = mSettings.mPackages.get(packageName); 14992 if (ps != null) { 14993 dataOwnerPkg = ps.pkg; 14994 } 14995 } 14996 14997 if (dataOwnerPkg != null) { 14998 // If installed, the package will get access to data left on the device by its 14999 // predecessor. As a security measure, this is permited only if this is not a 15000 // version downgrade or if the predecessor package is marked as debuggable and 15001 // a downgrade is explicitly requested. 15002 // 15003 // On debuggable platform builds, downgrades are permitted even for 15004 // non-debuggable packages to make testing easier. Debuggable platform builds do 15005 // not offer security guarantees and thus it's OK to disable some security 15006 // mechanisms to make debugging/testing easier on those builds. However, even on 15007 // debuggable builds downgrades of packages are permitted only if requested via 15008 // installFlags. This is because we aim to keep the behavior of debuggable 15009 // platform builds as close as possible to the behavior of non-debuggable 15010 // platform builds. 15011 final boolean downgradeRequested = 15012 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 15013 final boolean packageDebuggable = 15014 (dataOwnerPkg.applicationInfo.flags 15015 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 15016 final boolean downgradePermitted = 15017 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 15018 if (!downgradePermitted) { 15019 try { 15020 checkDowngrade(dataOwnerPkg, pkgLite); 15021 } catch (PackageManagerException e) { 15022 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15023 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15024 } 15025 } 15026 } 15027 15028 if (installedPkg != null) { 15029 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15030 // Check for updated system application. 15031 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15032 if (onSd) { 15033 Slog.w(TAG, "Cannot install update to system app on sdcard"); 15034 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 15035 } 15036 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15037 } else { 15038 if (onSd) { 15039 // Install flag overrides everything. 15040 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15041 } 15042 // If current upgrade specifies particular preference 15043 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15044 // Application explicitly specified internal. 15045 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15046 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15047 // App explictly prefers external. Let policy decide 15048 } else { 15049 // Prefer previous location 15050 if (isExternal(installedPkg)) { 15051 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15052 } 15053 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15054 } 15055 } 15056 } else { 15057 // Invalid install. Return error code 15058 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15059 } 15060 } 15061 } 15062 // All the special cases have been taken care of. 15063 // Return result based on recommended install location. 15064 if (onSd) { 15065 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15066 } 15067 return pkgLite.recommendedInstallLocation; 15068 } 15069 15070 /* 15071 * Invoke remote method to get package information and install 15072 * location values. Override install location based on default 15073 * policy if needed and then create install arguments based 15074 * on the install location. 15075 */ 15076 public void handleStartCopy() throws RemoteException { 15077 int ret = PackageManager.INSTALL_SUCCEEDED; 15078 15079 // If we're already staged, we've firmly committed to an install location 15080 if (origin.staged) { 15081 if (origin.file != null) { 15082 installFlags |= PackageManager.INSTALL_INTERNAL; 15083 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15084 } else { 15085 throw new IllegalStateException("Invalid stage location"); 15086 } 15087 } 15088 15089 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15090 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15091 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15092 PackageInfoLite pkgLite = null; 15093 15094 if (onInt && onSd) { 15095 // Check if both bits are set. 15096 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15097 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15098 } else if (onSd && ephemeral) { 15099 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15100 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15101 } else { 15102 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15103 packageAbiOverride); 15104 15105 if (DEBUG_INSTANT && ephemeral) { 15106 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15107 } 15108 15109 /* 15110 * If we have too little free space, try to free cache 15111 * before giving up. 15112 */ 15113 if (!origin.staged && pkgLite.recommendedInstallLocation 15114 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15115 // TODO: focus freeing disk space on the target device 15116 final StorageManager storage = StorageManager.from(mContext); 15117 final long lowThreshold = storage.getStorageLowBytes( 15118 Environment.getDataDirectory()); 15119 15120 final long sizeBytes = mContainerService.calculateInstalledSize( 15121 origin.resolvedPath, packageAbiOverride); 15122 15123 try { 15124 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15125 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15126 installFlags, packageAbiOverride); 15127 } catch (InstallerException e) { 15128 Slog.w(TAG, "Failed to free cache", e); 15129 } 15130 15131 /* 15132 * The cache free must have deleted the file we 15133 * downloaded to install. 15134 * 15135 * TODO: fix the "freeCache" call to not delete 15136 * the file we care about. 15137 */ 15138 if (pkgLite.recommendedInstallLocation 15139 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15140 pkgLite.recommendedInstallLocation 15141 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15142 } 15143 } 15144 } 15145 15146 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15147 int loc = pkgLite.recommendedInstallLocation; 15148 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15149 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15150 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15151 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15152 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15153 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15154 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15155 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15156 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15157 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15158 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15159 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15160 } else { 15161 // Override with defaults if needed. 15162 loc = installLocationPolicy(pkgLite); 15163 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15164 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15165 } else if (!onSd && !onInt) { 15166 // Override install location with flags 15167 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15168 // Set the flag to install on external media. 15169 installFlags |= PackageManager.INSTALL_EXTERNAL; 15170 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15171 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15172 if (DEBUG_INSTANT) { 15173 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15174 } 15175 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15176 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15177 |PackageManager.INSTALL_INTERNAL); 15178 } else { 15179 // Make sure the flag for installing on external 15180 // media is unset 15181 installFlags |= PackageManager.INSTALL_INTERNAL; 15182 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15183 } 15184 } 15185 } 15186 } 15187 15188 final InstallArgs args = createInstallArgs(this); 15189 mArgs = args; 15190 15191 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15192 // TODO: http://b/22976637 15193 // Apps installed for "all" users use the device owner to verify the app 15194 UserHandle verifierUser = getUser(); 15195 if (verifierUser == UserHandle.ALL) { 15196 verifierUser = UserHandle.SYSTEM; 15197 } 15198 15199 /* 15200 * Determine if we have any installed package verifiers. If we 15201 * do, then we'll defer to them to verify the packages. 15202 */ 15203 final int requiredUid = mRequiredVerifierPackage == null ? -1 15204 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15205 verifierUser.getIdentifier()); 15206 final int installerUid = 15207 verificationInfo == null ? -1 : verificationInfo.installerUid; 15208 if (!origin.existing && requiredUid != -1 15209 && isVerificationEnabled( 15210 verifierUser.getIdentifier(), installFlags, installerUid)) { 15211 final Intent verification = new Intent( 15212 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15213 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15214 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15215 PACKAGE_MIME_TYPE); 15216 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15217 15218 // Query all live verifiers based on current user state 15219 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15220 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15221 false /*allowDynamicSplits*/); 15222 15223 if (DEBUG_VERIFY) { 15224 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15225 + verification.toString() + " with " + pkgLite.verifiers.length 15226 + " optional verifiers"); 15227 } 15228 15229 final int verificationId = mPendingVerificationToken++; 15230 15231 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15232 15233 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15234 installerPackageName); 15235 15236 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15237 installFlags); 15238 15239 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15240 pkgLite.packageName); 15241 15242 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15243 pkgLite.versionCode); 15244 15245 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15246 pkgLite.getLongVersionCode()); 15247 15248 if (verificationInfo != null) { 15249 if (verificationInfo.originatingUri != null) { 15250 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15251 verificationInfo.originatingUri); 15252 } 15253 if (verificationInfo.referrer != null) { 15254 verification.putExtra(Intent.EXTRA_REFERRER, 15255 verificationInfo.referrer); 15256 } 15257 if (verificationInfo.originatingUid >= 0) { 15258 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15259 verificationInfo.originatingUid); 15260 } 15261 if (verificationInfo.installerUid >= 0) { 15262 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15263 verificationInfo.installerUid); 15264 } 15265 } 15266 15267 final PackageVerificationState verificationState = new PackageVerificationState( 15268 requiredUid, args); 15269 15270 mPendingVerification.append(verificationId, verificationState); 15271 15272 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15273 receivers, verificationState); 15274 15275 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15276 final long idleDuration = getVerificationTimeout(); 15277 15278 /* 15279 * If any sufficient verifiers were listed in the package 15280 * manifest, attempt to ask them. 15281 */ 15282 if (sufficientVerifiers != null) { 15283 final int N = sufficientVerifiers.size(); 15284 if (N == 0) { 15285 Slog.i(TAG, "Additional verifiers required, but none installed."); 15286 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15287 } else { 15288 for (int i = 0; i < N; i++) { 15289 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15290 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15291 verifierComponent.getPackageName(), idleDuration, 15292 verifierUser.getIdentifier(), false, "package verifier"); 15293 15294 final Intent sufficientIntent = new Intent(verification); 15295 sufficientIntent.setComponent(verifierComponent); 15296 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15297 } 15298 } 15299 } 15300 15301 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15302 mRequiredVerifierPackage, receivers); 15303 if (ret == PackageManager.INSTALL_SUCCEEDED 15304 && mRequiredVerifierPackage != null) { 15305 Trace.asyncTraceBegin( 15306 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15307 /* 15308 * Send the intent to the required verification agent, 15309 * but only start the verification timeout after the 15310 * target BroadcastReceivers have run. 15311 */ 15312 verification.setComponent(requiredVerifierComponent); 15313 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15314 mRequiredVerifierPackage, idleDuration, 15315 verifierUser.getIdentifier(), false, "package verifier"); 15316 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15317 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15318 new BroadcastReceiver() { 15319 @Override 15320 public void onReceive(Context context, Intent intent) { 15321 final Message msg = mHandler 15322 .obtainMessage(CHECK_PENDING_VERIFICATION); 15323 msg.arg1 = verificationId; 15324 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15325 } 15326 }, null, 0, null, null); 15327 15328 /* 15329 * We don't want the copy to proceed until verification 15330 * succeeds, so null out this field. 15331 */ 15332 mArgs = null; 15333 } 15334 } else { 15335 /* 15336 * No package verification is enabled, so immediately start 15337 * the remote call to initiate copy using temporary file. 15338 */ 15339 ret = args.copyApk(mContainerService, true); 15340 } 15341 } 15342 15343 mRet = ret; 15344 } 15345 15346 @Override 15347 void handleReturnCode() { 15348 // If mArgs is null, then MCS couldn't be reached. When it 15349 // reconnects, it will try again to install. At that point, this 15350 // will succeed. 15351 if (mArgs != null) { 15352 processPendingInstall(mArgs, mRet); 15353 } 15354 } 15355 15356 @Override 15357 void handleServiceError() { 15358 mArgs = createInstallArgs(this); 15359 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15360 } 15361 } 15362 15363 private InstallArgs createInstallArgs(InstallParams params) { 15364 if (params.move != null) { 15365 return new MoveInstallArgs(params); 15366 } else { 15367 return new FileInstallArgs(params); 15368 } 15369 } 15370 15371 /** 15372 * Create args that describe an existing installed package. Typically used 15373 * when cleaning up old installs, or used as a move source. 15374 */ 15375 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15376 String resourcePath, String[] instructionSets) { 15377 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15378 } 15379 15380 static abstract class InstallArgs { 15381 /** @see InstallParams#origin */ 15382 final OriginInfo origin; 15383 /** @see InstallParams#move */ 15384 final MoveInfo move; 15385 15386 final IPackageInstallObserver2 observer; 15387 // Always refers to PackageManager flags only 15388 final int installFlags; 15389 final String installerPackageName; 15390 final String volumeUuid; 15391 final UserHandle user; 15392 final String abiOverride; 15393 final String[] installGrantPermissions; 15394 /** If non-null, drop an async trace when the install completes */ 15395 final String traceMethod; 15396 final int traceCookie; 15397 final PackageParser.SigningDetails signingDetails; 15398 final int installReason; 15399 15400 // The list of instruction sets supported by this app. This is currently 15401 // only used during the rmdex() phase to clean up resources. We can get rid of this 15402 // if we move dex files under the common app path. 15403 /* nullable */ String[] instructionSets; 15404 15405 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15406 int installFlags, String installerPackageName, String volumeUuid, 15407 UserHandle user, String[] instructionSets, 15408 String abiOverride, String[] installGrantPermissions, 15409 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15410 int installReason) { 15411 this.origin = origin; 15412 this.move = move; 15413 this.installFlags = installFlags; 15414 this.observer = observer; 15415 this.installerPackageName = installerPackageName; 15416 this.volumeUuid = volumeUuid; 15417 this.user = user; 15418 this.instructionSets = instructionSets; 15419 this.abiOverride = abiOverride; 15420 this.installGrantPermissions = installGrantPermissions; 15421 this.traceMethod = traceMethod; 15422 this.traceCookie = traceCookie; 15423 this.signingDetails = signingDetails; 15424 this.installReason = installReason; 15425 } 15426 15427 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15428 abstract int doPreInstall(int status); 15429 15430 /** 15431 * Rename package into final resting place. All paths on the given 15432 * scanned package should be updated to reflect the rename. 15433 */ 15434 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15435 abstract int doPostInstall(int status, int uid); 15436 15437 /** @see PackageSettingBase#codePathString */ 15438 abstract String getCodePath(); 15439 /** @see PackageSettingBase#resourcePathString */ 15440 abstract String getResourcePath(); 15441 15442 // Need installer lock especially for dex file removal. 15443 abstract void cleanUpResourcesLI(); 15444 abstract boolean doPostDeleteLI(boolean delete); 15445 15446 /** 15447 * Called before the source arguments are copied. This is used mostly 15448 * for MoveParams when it needs to read the source file to put it in the 15449 * destination. 15450 */ 15451 int doPreCopy() { 15452 return PackageManager.INSTALL_SUCCEEDED; 15453 } 15454 15455 /** 15456 * Called after the source arguments are copied. This is used mostly for 15457 * MoveParams when it needs to read the source file to put it in the 15458 * destination. 15459 */ 15460 int doPostCopy(int uid) { 15461 return PackageManager.INSTALL_SUCCEEDED; 15462 } 15463 15464 protected boolean isFwdLocked() { 15465 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15466 } 15467 15468 protected boolean isExternalAsec() { 15469 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15470 } 15471 15472 protected boolean isEphemeral() { 15473 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15474 } 15475 15476 UserHandle getUser() { 15477 return user; 15478 } 15479 } 15480 15481 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15482 if (!allCodePaths.isEmpty()) { 15483 if (instructionSets == null) { 15484 throw new IllegalStateException("instructionSet == null"); 15485 } 15486 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15487 for (String codePath : allCodePaths) { 15488 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15489 try { 15490 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15491 } catch (InstallerException ignored) { 15492 } 15493 } 15494 } 15495 } 15496 } 15497 15498 /** 15499 * Logic to handle installation of non-ASEC applications, including copying 15500 * and renaming logic. 15501 */ 15502 class FileInstallArgs extends InstallArgs { 15503 private File codeFile; 15504 private File resourceFile; 15505 15506 // Example topology: 15507 // /data/app/com.example/base.apk 15508 // /data/app/com.example/split_foo.apk 15509 // /data/app/com.example/lib/arm/libfoo.so 15510 // /data/app/com.example/lib/arm64/libfoo.so 15511 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15512 15513 /** New install */ 15514 FileInstallArgs(InstallParams params) { 15515 super(params.origin, params.move, params.observer, params.installFlags, 15516 params.installerPackageName, params.volumeUuid, 15517 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15518 params.grantedRuntimePermissions, 15519 params.traceMethod, params.traceCookie, params.signingDetails, 15520 params.installReason); 15521 if (isFwdLocked()) { 15522 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15523 } 15524 } 15525 15526 /** Existing install */ 15527 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15528 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15529 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15530 PackageManager.INSTALL_REASON_UNKNOWN); 15531 this.codeFile = (codePath != null) ? new File(codePath) : null; 15532 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15533 } 15534 15535 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15536 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15537 try { 15538 return doCopyApk(imcs, temp); 15539 } finally { 15540 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15541 } 15542 } 15543 15544 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15545 if (origin.staged) { 15546 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15547 codeFile = origin.file; 15548 resourceFile = origin.file; 15549 return PackageManager.INSTALL_SUCCEEDED; 15550 } 15551 15552 try { 15553 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15554 final File tempDir = 15555 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15556 codeFile = tempDir; 15557 resourceFile = tempDir; 15558 } catch (IOException e) { 15559 Slog.w(TAG, "Failed to create copy file: " + e); 15560 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15561 } 15562 15563 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15564 @Override 15565 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15566 if (!FileUtils.isValidExtFilename(name)) { 15567 throw new IllegalArgumentException("Invalid filename: " + name); 15568 } 15569 try { 15570 final File file = new File(codeFile, name); 15571 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15572 O_RDWR | O_CREAT, 0644); 15573 Os.chmod(file.getAbsolutePath(), 0644); 15574 return new ParcelFileDescriptor(fd); 15575 } catch (ErrnoException e) { 15576 throw new RemoteException("Failed to open: " + e.getMessage()); 15577 } 15578 } 15579 }; 15580 15581 int ret = PackageManager.INSTALL_SUCCEEDED; 15582 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15583 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15584 Slog.e(TAG, "Failed to copy package"); 15585 return ret; 15586 } 15587 15588 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15589 NativeLibraryHelper.Handle handle = null; 15590 try { 15591 handle = NativeLibraryHelper.Handle.create(codeFile); 15592 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15593 abiOverride); 15594 } catch (IOException e) { 15595 Slog.e(TAG, "Copying native libraries failed", e); 15596 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15597 } finally { 15598 IoUtils.closeQuietly(handle); 15599 } 15600 15601 return ret; 15602 } 15603 15604 int doPreInstall(int status) { 15605 if (status != PackageManager.INSTALL_SUCCEEDED) { 15606 cleanUp(); 15607 } 15608 return status; 15609 } 15610 15611 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15612 if (status != PackageManager.INSTALL_SUCCEEDED) { 15613 cleanUp(); 15614 return false; 15615 } 15616 15617 final File targetDir = codeFile.getParentFile(); 15618 final File beforeCodeFile = codeFile; 15619 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15620 15621 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15622 try { 15623 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15624 } catch (ErrnoException e) { 15625 Slog.w(TAG, "Failed to rename", e); 15626 return false; 15627 } 15628 15629 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15630 Slog.w(TAG, "Failed to restorecon"); 15631 return false; 15632 } 15633 15634 // Reflect the rename internally 15635 codeFile = afterCodeFile; 15636 resourceFile = afterCodeFile; 15637 15638 // Reflect the rename in scanned details 15639 try { 15640 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15641 } catch (IOException e) { 15642 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15643 return false; 15644 } 15645 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15646 afterCodeFile, pkg.baseCodePath)); 15647 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15648 afterCodeFile, pkg.splitCodePaths)); 15649 15650 // Reflect the rename in app info 15651 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15652 pkg.setApplicationInfoCodePath(pkg.codePath); 15653 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15654 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15655 pkg.setApplicationInfoResourcePath(pkg.codePath); 15656 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15657 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15658 15659 return true; 15660 } 15661 15662 int doPostInstall(int status, int uid) { 15663 if (status != PackageManager.INSTALL_SUCCEEDED) { 15664 cleanUp(); 15665 } 15666 return status; 15667 } 15668 15669 @Override 15670 String getCodePath() { 15671 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15672 } 15673 15674 @Override 15675 String getResourcePath() { 15676 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15677 } 15678 15679 private boolean cleanUp() { 15680 if (codeFile == null || !codeFile.exists()) { 15681 return false; 15682 } 15683 15684 removeCodePathLI(codeFile); 15685 15686 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15687 resourceFile.delete(); 15688 } 15689 15690 return true; 15691 } 15692 15693 void cleanUpResourcesLI() { 15694 // Try enumerating all code paths before deleting 15695 List<String> allCodePaths = Collections.EMPTY_LIST; 15696 if (codeFile != null && codeFile.exists()) { 15697 try { 15698 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15699 allCodePaths = pkg.getAllCodePaths(); 15700 } catch (PackageParserException e) { 15701 // Ignored; we tried our best 15702 } 15703 } 15704 15705 cleanUp(); 15706 removeDexFiles(allCodePaths, instructionSets); 15707 } 15708 15709 boolean doPostDeleteLI(boolean delete) { 15710 // XXX err, shouldn't we respect the delete flag? 15711 cleanUpResourcesLI(); 15712 return true; 15713 } 15714 } 15715 15716 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15717 PackageManagerException { 15718 if (copyRet < 0) { 15719 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15720 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15721 throw new PackageManagerException(copyRet, message); 15722 } 15723 } 15724 } 15725 15726 /** 15727 * Extract the StorageManagerService "container ID" from the full code path of an 15728 * .apk. 15729 */ 15730 static String cidFromCodePath(String fullCodePath) { 15731 int eidx = fullCodePath.lastIndexOf("/"); 15732 String subStr1 = fullCodePath.substring(0, eidx); 15733 int sidx = subStr1.lastIndexOf("/"); 15734 return subStr1.substring(sidx+1, eidx); 15735 } 15736 15737 /** 15738 * Logic to handle movement of existing installed applications. 15739 */ 15740 class MoveInstallArgs extends InstallArgs { 15741 private File codeFile; 15742 private File resourceFile; 15743 15744 /** New install */ 15745 MoveInstallArgs(InstallParams params) { 15746 super(params.origin, params.move, params.observer, params.installFlags, 15747 params.installerPackageName, params.volumeUuid, 15748 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15749 params.grantedRuntimePermissions, 15750 params.traceMethod, params.traceCookie, params.signingDetails, 15751 params.installReason); 15752 } 15753 15754 int copyApk(IMediaContainerService imcs, boolean temp) { 15755 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15756 + move.fromUuid + " to " + move.toUuid); 15757 synchronized (mInstaller) { 15758 try { 15759 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15760 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15761 } catch (InstallerException e) { 15762 Slog.w(TAG, "Failed to move app", e); 15763 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15764 } 15765 } 15766 15767 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15768 resourceFile = codeFile; 15769 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15770 15771 return PackageManager.INSTALL_SUCCEEDED; 15772 } 15773 15774 int doPreInstall(int status) { 15775 if (status != PackageManager.INSTALL_SUCCEEDED) { 15776 cleanUp(move.toUuid); 15777 } 15778 return status; 15779 } 15780 15781 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15782 if (status != PackageManager.INSTALL_SUCCEEDED) { 15783 cleanUp(move.toUuid); 15784 return false; 15785 } 15786 15787 // Reflect the move in app info 15788 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15789 pkg.setApplicationInfoCodePath(pkg.codePath); 15790 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15791 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15792 pkg.setApplicationInfoResourcePath(pkg.codePath); 15793 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15794 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15795 15796 return true; 15797 } 15798 15799 int doPostInstall(int status, int uid) { 15800 if (status == PackageManager.INSTALL_SUCCEEDED) { 15801 cleanUp(move.fromUuid); 15802 } else { 15803 cleanUp(move.toUuid); 15804 } 15805 return status; 15806 } 15807 15808 @Override 15809 String getCodePath() { 15810 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15811 } 15812 15813 @Override 15814 String getResourcePath() { 15815 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15816 } 15817 15818 private boolean cleanUp(String volumeUuid) { 15819 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15820 move.dataAppName); 15821 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15822 final int[] userIds = sUserManager.getUserIds(); 15823 synchronized (mInstallLock) { 15824 // Clean up both app data and code 15825 // All package moves are frozen until finished 15826 for (int userId : userIds) { 15827 try { 15828 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15829 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15830 } catch (InstallerException e) { 15831 Slog.w(TAG, String.valueOf(e)); 15832 } 15833 } 15834 removeCodePathLI(codeFile); 15835 } 15836 return true; 15837 } 15838 15839 void cleanUpResourcesLI() { 15840 throw new UnsupportedOperationException(); 15841 } 15842 15843 boolean doPostDeleteLI(boolean delete) { 15844 throw new UnsupportedOperationException(); 15845 } 15846 } 15847 15848 static String getAsecPackageName(String packageCid) { 15849 int idx = packageCid.lastIndexOf("-"); 15850 if (idx == -1) { 15851 return packageCid; 15852 } 15853 return packageCid.substring(0, idx); 15854 } 15855 15856 // Utility method used to create code paths based on package name and available index. 15857 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15858 String idxStr = ""; 15859 int idx = 1; 15860 // Fall back to default value of idx=1 if prefix is not 15861 // part of oldCodePath 15862 if (oldCodePath != null) { 15863 String subStr = oldCodePath; 15864 // Drop the suffix right away 15865 if (suffix != null && subStr.endsWith(suffix)) { 15866 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15867 } 15868 // If oldCodePath already contains prefix find out the 15869 // ending index to either increment or decrement. 15870 int sidx = subStr.lastIndexOf(prefix); 15871 if (sidx != -1) { 15872 subStr = subStr.substring(sidx + prefix.length()); 15873 if (subStr != null) { 15874 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15875 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15876 } 15877 try { 15878 idx = Integer.parseInt(subStr); 15879 if (idx <= 1) { 15880 idx++; 15881 } else { 15882 idx--; 15883 } 15884 } catch(NumberFormatException e) { 15885 } 15886 } 15887 } 15888 } 15889 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15890 return prefix + idxStr; 15891 } 15892 15893 private File getNextCodePath(File targetDir, String packageName) { 15894 File result; 15895 SecureRandom random = new SecureRandom(); 15896 byte[] bytes = new byte[16]; 15897 do { 15898 random.nextBytes(bytes); 15899 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15900 result = new File(targetDir, packageName + "-" + suffix); 15901 } while (result.exists()); 15902 return result; 15903 } 15904 15905 // Utility method that returns the relative package path with respect 15906 // to the installation directory. Like say for /data/data/com.test-1.apk 15907 // string com.test-1 is returned. 15908 static String deriveCodePathName(String codePath) { 15909 if (codePath == null) { 15910 return null; 15911 } 15912 final File codeFile = new File(codePath); 15913 final String name = codeFile.getName(); 15914 if (codeFile.isDirectory()) { 15915 return name; 15916 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15917 final int lastDot = name.lastIndexOf('.'); 15918 return name.substring(0, lastDot); 15919 } else { 15920 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15921 return null; 15922 } 15923 } 15924 15925 static class PackageInstalledInfo { 15926 String name; 15927 int uid; 15928 // The set of users that originally had this package installed. 15929 int[] origUsers; 15930 // The set of users that now have this package installed. 15931 int[] newUsers; 15932 PackageParser.Package pkg; 15933 int returnCode; 15934 String returnMsg; 15935 String installerPackageName; 15936 PackageRemovedInfo removedInfo; 15937 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15938 15939 public void setError(int code, String msg) { 15940 setReturnCode(code); 15941 setReturnMessage(msg); 15942 Slog.w(TAG, msg); 15943 } 15944 15945 public void setError(String msg, PackageParserException e) { 15946 setReturnCode(e.error); 15947 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15948 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15949 for (int i = 0; i < childCount; i++) { 15950 addedChildPackages.valueAt(i).setError(msg, e); 15951 } 15952 Slog.w(TAG, msg, e); 15953 } 15954 15955 public void setError(String msg, PackageManagerException e) { 15956 returnCode = e.error; 15957 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15958 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15959 for (int i = 0; i < childCount; i++) { 15960 addedChildPackages.valueAt(i).setError(msg, e); 15961 } 15962 Slog.w(TAG, msg, e); 15963 } 15964 15965 public void setReturnCode(int returnCode) { 15966 this.returnCode = returnCode; 15967 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15968 for (int i = 0; i < childCount; i++) { 15969 addedChildPackages.valueAt(i).returnCode = returnCode; 15970 } 15971 } 15972 15973 private void setReturnMessage(String returnMsg) { 15974 this.returnMsg = returnMsg; 15975 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15976 for (int i = 0; i < childCount; i++) { 15977 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15978 } 15979 } 15980 15981 // In some error cases we want to convey more info back to the observer 15982 String origPackage; 15983 String origPermission; 15984 } 15985 15986 /* 15987 * Install a non-existing package. 15988 */ 15989 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15990 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15991 String volumeUuid, PackageInstalledInfo res, int installReason) { 15992 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15993 15994 // Remember this for later, in case we need to rollback this install 15995 String pkgName = pkg.packageName; 15996 15997 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15998 15999 synchronized(mPackages) { 16000 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 16001 if (renamedPackage != null) { 16002 // A package with the same name is already installed, though 16003 // it has been renamed to an older name. The package we 16004 // are trying to install should be installed as an update to 16005 // the existing one, but that has not been requested, so bail. 16006 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16007 + " without first uninstalling package running as " 16008 + renamedPackage); 16009 return; 16010 } 16011 if (mPackages.containsKey(pkgName)) { 16012 // Don't allow installation over an existing package with the same name. 16013 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 16014 + " without first uninstalling."); 16015 return; 16016 } 16017 } 16018 16019 try { 16020 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 16021 System.currentTimeMillis(), user); 16022 16023 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 16024 16025 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16026 prepareAppDataAfterInstallLIF(newPackage); 16027 16028 } else { 16029 // Remove package from internal structures, but keep around any 16030 // data that might have already existed 16031 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 16032 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 16033 } 16034 } catch (PackageManagerException e) { 16035 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16036 } 16037 16038 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16039 } 16040 16041 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16042 try (DigestInputStream digestStream = 16043 new DigestInputStream(new FileInputStream(file), digest)) { 16044 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16045 } 16046 } 16047 16048 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 16049 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 16050 PackageInstalledInfo res, int installReason) { 16051 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16052 16053 final PackageParser.Package oldPackage; 16054 final PackageSetting ps; 16055 final String pkgName = pkg.packageName; 16056 final int[] allUsers; 16057 final int[] installedUsers; 16058 16059 synchronized(mPackages) { 16060 oldPackage = mPackages.get(pkgName); 16061 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 16062 16063 // don't allow upgrade to target a release SDK from a pre-release SDK 16064 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 16065 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16066 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 16067 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 16068 if (oldTargetsPreRelease 16069 && !newTargetsPreRelease 16070 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 16071 Slog.w(TAG, "Can't install package targeting released sdk"); 16072 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 16073 return; 16074 } 16075 16076 ps = mSettings.mPackages.get(pkgName); 16077 16078 // verify signatures are valid 16079 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16080 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16081 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16082 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16083 "New package not signed by keys specified by upgrade-keysets: " 16084 + pkgName); 16085 return; 16086 } 16087 } else { 16088 16089 // default to original signature matching 16090 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 16091 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA)) { 16092 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16093 "New package has a different signature: " + pkgName); 16094 return; 16095 } 16096 } 16097 16098 // don't allow a system upgrade unless the upgrade hash matches 16099 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16100 byte[] digestBytes = null; 16101 try { 16102 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16103 updateDigest(digest, new File(pkg.baseCodePath)); 16104 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16105 for (String path : pkg.splitCodePaths) { 16106 updateDigest(digest, new File(path)); 16107 } 16108 } 16109 digestBytes = digest.digest(); 16110 } catch (NoSuchAlgorithmException | IOException e) { 16111 res.setError(INSTALL_FAILED_INVALID_APK, 16112 "Could not compute hash: " + pkgName); 16113 return; 16114 } 16115 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16116 res.setError(INSTALL_FAILED_INVALID_APK, 16117 "New package fails restrict-update check: " + pkgName); 16118 return; 16119 } 16120 // retain upgrade restriction 16121 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16122 } 16123 16124 // Check for shared user id changes 16125 String invalidPackageName = 16126 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16127 if (invalidPackageName != null) { 16128 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16129 "Package " + invalidPackageName + " tried to change user " 16130 + oldPackage.mSharedUserId); 16131 return; 16132 } 16133 16134 // check if the new package supports all of the abis which the old package supports 16135 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16136 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16137 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16138 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16139 "Update to package " + pkgName + " doesn't support multi arch"); 16140 return; 16141 } 16142 16143 // In case of rollback, remember per-user/profile install state 16144 allUsers = sUserManager.getUserIds(); 16145 installedUsers = ps.queryInstalledUsers(allUsers, true); 16146 16147 // don't allow an upgrade from full to ephemeral 16148 if (isInstantApp) { 16149 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16150 for (int currentUser : allUsers) { 16151 if (!ps.getInstantApp(currentUser)) { 16152 // can't downgrade from full to instant 16153 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16154 + " for user: " + currentUser); 16155 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16156 return; 16157 } 16158 } 16159 } else if (!ps.getInstantApp(user.getIdentifier())) { 16160 // can't downgrade from full to instant 16161 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16162 + " for user: " + user.getIdentifier()); 16163 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16164 return; 16165 } 16166 } 16167 } 16168 16169 // Update what is removed 16170 res.removedInfo = new PackageRemovedInfo(this); 16171 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16172 res.removedInfo.removedPackage = oldPackage.packageName; 16173 res.removedInfo.installerPackageName = ps.installerPackageName; 16174 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16175 res.removedInfo.isUpdate = true; 16176 res.removedInfo.origUsers = installedUsers; 16177 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16178 for (int i = 0; i < installedUsers.length; i++) { 16179 final int userId = installedUsers[i]; 16180 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16181 } 16182 16183 final int childCount = (oldPackage.childPackages != null) 16184 ? oldPackage.childPackages.size() : 0; 16185 for (int i = 0; i < childCount; i++) { 16186 boolean childPackageUpdated = false; 16187 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16188 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16189 if (res.addedChildPackages != null) { 16190 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16191 if (childRes != null) { 16192 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16193 childRes.removedInfo.removedPackage = childPkg.packageName; 16194 if (childPs != null) { 16195 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16196 } 16197 childRes.removedInfo.isUpdate = true; 16198 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16199 childPackageUpdated = true; 16200 } 16201 } 16202 if (!childPackageUpdated) { 16203 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16204 childRemovedRes.removedPackage = childPkg.packageName; 16205 if (childPs != null) { 16206 childRemovedRes.installerPackageName = childPs.installerPackageName; 16207 } 16208 childRemovedRes.isUpdate = false; 16209 childRemovedRes.dataRemoved = true; 16210 synchronized (mPackages) { 16211 if (childPs != null) { 16212 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16213 } 16214 } 16215 if (res.removedInfo.removedChildPackages == null) { 16216 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16217 } 16218 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16219 } 16220 } 16221 16222 boolean sysPkg = (isSystemApp(oldPackage)); 16223 if (sysPkg) { 16224 // Set the system/privileged/oem/vendor/product flags as needed 16225 final boolean privileged = 16226 (oldPackage.applicationInfo.privateFlags 16227 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16228 final boolean oem = 16229 (oldPackage.applicationInfo.privateFlags 16230 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16231 final boolean vendor = 16232 (oldPackage.applicationInfo.privateFlags 16233 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16234 final boolean product = 16235 (oldPackage.applicationInfo.privateFlags 16236 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16237 final @ParseFlags int systemParseFlags = parseFlags; 16238 final @ScanFlags int systemScanFlags = scanFlags 16239 | SCAN_AS_SYSTEM 16240 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16241 | (oem ? SCAN_AS_OEM : 0) 16242 | (vendor ? SCAN_AS_VENDOR : 0) 16243 | (product ? SCAN_AS_PRODUCT : 0); 16244 16245 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16246 user, allUsers, installerPackageName, res, installReason); 16247 } else { 16248 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16249 user, allUsers, installerPackageName, res, installReason); 16250 } 16251 } 16252 16253 @Override 16254 public List<String> getPreviousCodePaths(String packageName) { 16255 final int callingUid = Binder.getCallingUid(); 16256 final List<String> result = new ArrayList<>(); 16257 if (getInstantAppPackageName(callingUid) != null) { 16258 return result; 16259 } 16260 final PackageSetting ps = mSettings.mPackages.get(packageName); 16261 if (ps != null 16262 && ps.oldCodePaths != null 16263 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16264 result.addAll(ps.oldCodePaths); 16265 } 16266 return result; 16267 } 16268 16269 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16270 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16271 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16272 String installerPackageName, PackageInstalledInfo res, int installReason) { 16273 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16274 + deletedPackage); 16275 16276 String pkgName = deletedPackage.packageName; 16277 boolean deletedPkg = true; 16278 boolean addedPkg = false; 16279 boolean updatedSettings = false; 16280 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16281 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16282 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16283 16284 final long origUpdateTime = (pkg.mExtras != null) 16285 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16286 16287 // First delete the existing package while retaining the data directory 16288 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16289 res.removedInfo, true, pkg)) { 16290 // If the existing package wasn't successfully deleted 16291 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16292 deletedPkg = false; 16293 } else { 16294 // Successfully deleted the old package; proceed with replace. 16295 16296 // If deleted package lived in a container, give users a chance to 16297 // relinquish resources before killing. 16298 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16299 if (DEBUG_INSTALL) { 16300 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16301 } 16302 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16303 final ArrayList<String> pkgList = new ArrayList<String>(1); 16304 pkgList.add(deletedPackage.applicationInfo.packageName); 16305 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16306 } 16307 16308 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16309 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16310 16311 try { 16312 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16313 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16314 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16315 installReason); 16316 16317 // Update the in-memory copy of the previous code paths. 16318 PackageSetting ps = mSettings.mPackages.get(pkgName); 16319 if (!killApp) { 16320 if (ps.oldCodePaths == null) { 16321 ps.oldCodePaths = new ArraySet<>(); 16322 } 16323 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16324 if (deletedPackage.splitCodePaths != null) { 16325 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16326 } 16327 } else { 16328 ps.oldCodePaths = null; 16329 } 16330 if (ps.childPackageNames != null) { 16331 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16332 final String childPkgName = ps.childPackageNames.get(i); 16333 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16334 childPs.oldCodePaths = ps.oldCodePaths; 16335 } 16336 } 16337 // set instant app status, but, only if it's explicitly specified 16338 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16339 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16340 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16341 prepareAppDataAfterInstallLIF(newPackage); 16342 addedPkg = true; 16343 mDexManager.notifyPackageUpdated(newPackage.packageName, 16344 newPackage.baseCodePath, newPackage.splitCodePaths); 16345 } catch (PackageManagerException e) { 16346 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16347 } 16348 } 16349 16350 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16351 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16352 16353 // Revert all internal state mutations and added folders for the failed install 16354 if (addedPkg) { 16355 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16356 res.removedInfo, true, null); 16357 } 16358 16359 // Restore the old package 16360 if (deletedPkg) { 16361 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16362 File restoreFile = new File(deletedPackage.codePath); 16363 // Parse old package 16364 boolean oldExternal = isExternal(deletedPackage); 16365 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16366 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16367 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16368 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16369 try { 16370 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16371 null); 16372 } catch (PackageManagerException e) { 16373 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16374 + e.getMessage()); 16375 return; 16376 } 16377 16378 synchronized (mPackages) { 16379 // Ensure the installer package name up to date 16380 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16381 16382 // Update permissions for restored package 16383 mPermissionManager.updatePermissions( 16384 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16385 mPermissionCallback); 16386 16387 mSettings.writeLPr(); 16388 } 16389 16390 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16391 } 16392 } else { 16393 synchronized (mPackages) { 16394 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16395 if (ps != null) { 16396 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16397 if (res.removedInfo.removedChildPackages != null) { 16398 final int childCount = res.removedInfo.removedChildPackages.size(); 16399 // Iterate in reverse as we may modify the collection 16400 for (int i = childCount - 1; i >= 0; i--) { 16401 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16402 if (res.addedChildPackages.containsKey(childPackageName)) { 16403 res.removedInfo.removedChildPackages.removeAt(i); 16404 } else { 16405 PackageRemovedInfo childInfo = res.removedInfo 16406 .removedChildPackages.valueAt(i); 16407 childInfo.removedForAllUsers = mPackages.get( 16408 childInfo.removedPackage) == null; 16409 } 16410 } 16411 } 16412 } 16413 } 16414 } 16415 } 16416 16417 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16418 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16419 final @ScanFlags int scanFlags, UserHandle user, 16420 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16421 int installReason) { 16422 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16423 + ", old=" + deletedPackage); 16424 16425 final boolean disabledSystem; 16426 16427 // Remove existing system package 16428 removePackageLI(deletedPackage, true); 16429 16430 synchronized (mPackages) { 16431 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16432 } 16433 if (!disabledSystem) { 16434 // We didn't need to disable the .apk as a current system package, 16435 // which means we are replacing another update that is already 16436 // installed. We need to make sure to delete the older one's .apk. 16437 res.removedInfo.args = createInstallArgsForExisting(0, 16438 deletedPackage.applicationInfo.getCodePath(), 16439 deletedPackage.applicationInfo.getResourcePath(), 16440 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16441 } else { 16442 res.removedInfo.args = null; 16443 } 16444 16445 // Successfully disabled the old package. Now proceed with re-installation 16446 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16447 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16448 16449 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16450 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16451 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16452 16453 PackageParser.Package newPackage = null; 16454 try { 16455 // Add the package to the internal data structures 16456 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16457 16458 // Set the update and install times 16459 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16460 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16461 System.currentTimeMillis()); 16462 16463 // Update the package dynamic state if succeeded 16464 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16465 // Now that the install succeeded make sure we remove data 16466 // directories for any child package the update removed. 16467 final int deletedChildCount = (deletedPackage.childPackages != null) 16468 ? deletedPackage.childPackages.size() : 0; 16469 final int newChildCount = (newPackage.childPackages != null) 16470 ? newPackage.childPackages.size() : 0; 16471 for (int i = 0; i < deletedChildCount; i++) { 16472 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16473 boolean childPackageDeleted = true; 16474 for (int j = 0; j < newChildCount; j++) { 16475 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16476 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16477 childPackageDeleted = false; 16478 break; 16479 } 16480 } 16481 if (childPackageDeleted) { 16482 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16483 deletedChildPkg.packageName); 16484 if (ps != null && res.removedInfo.removedChildPackages != null) { 16485 PackageRemovedInfo removedChildRes = res.removedInfo 16486 .removedChildPackages.get(deletedChildPkg.packageName); 16487 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16488 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16489 } 16490 } 16491 } 16492 16493 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16494 installReason); 16495 prepareAppDataAfterInstallLIF(newPackage); 16496 16497 mDexManager.notifyPackageUpdated(newPackage.packageName, 16498 newPackage.baseCodePath, newPackage.splitCodePaths); 16499 } 16500 } catch (PackageManagerException e) { 16501 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16502 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16503 } 16504 16505 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16506 // Re installation failed. Restore old information 16507 // Remove new pkg information 16508 if (newPackage != null) { 16509 removeInstalledPackageLI(newPackage, true); 16510 } 16511 // Add back the old system package 16512 try { 16513 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16514 } catch (PackageManagerException e) { 16515 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16516 } 16517 16518 synchronized (mPackages) { 16519 if (disabledSystem) { 16520 enableSystemPackageLPw(deletedPackage); 16521 } 16522 16523 // Ensure the installer package name up to date 16524 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16525 16526 // Update permissions for restored package 16527 mPermissionManager.updatePermissions( 16528 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16529 mPermissionCallback); 16530 16531 mSettings.writeLPr(); 16532 } 16533 16534 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16535 + " after failed upgrade"); 16536 } 16537 } 16538 16539 /** 16540 * Checks whether the parent or any of the child packages have a change shared 16541 * user. For a package to be a valid update the shred users of the parent and 16542 * the children should match. We may later support changing child shared users. 16543 * @param oldPkg The updated package. 16544 * @param newPkg The update package. 16545 * @return The shared user that change between the versions. 16546 */ 16547 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16548 PackageParser.Package newPkg) { 16549 // Check parent shared user 16550 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16551 return newPkg.packageName; 16552 } 16553 // Check child shared users 16554 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16555 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16556 for (int i = 0; i < newChildCount; i++) { 16557 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16558 // If this child was present, did it have the same shared user? 16559 for (int j = 0; j < oldChildCount; j++) { 16560 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16561 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16562 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16563 return newChildPkg.packageName; 16564 } 16565 } 16566 } 16567 return null; 16568 } 16569 16570 private void removeNativeBinariesLI(PackageSetting ps) { 16571 // Remove the lib path for the parent package 16572 if (ps != null) { 16573 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16574 // Remove the lib path for the child packages 16575 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16576 for (int i = 0; i < childCount; i++) { 16577 PackageSetting childPs = null; 16578 synchronized (mPackages) { 16579 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16580 } 16581 if (childPs != null) { 16582 NativeLibraryHelper.removeNativeBinariesLI(childPs 16583 .legacyNativeLibraryPathString); 16584 } 16585 } 16586 } 16587 } 16588 16589 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16590 // Enable the parent package 16591 mSettings.enableSystemPackageLPw(pkg.packageName); 16592 // Enable the child packages 16593 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16594 for (int i = 0; i < childCount; i++) { 16595 PackageParser.Package childPkg = pkg.childPackages.get(i); 16596 mSettings.enableSystemPackageLPw(childPkg.packageName); 16597 } 16598 } 16599 16600 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16601 PackageParser.Package newPkg) { 16602 // Disable the parent package (parent always replaced) 16603 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16604 // Disable the child packages 16605 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16606 for (int i = 0; i < childCount; i++) { 16607 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16608 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16609 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16610 } 16611 return disabled; 16612 } 16613 16614 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16615 String installerPackageName) { 16616 // Enable the parent package 16617 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16618 // Enable the child packages 16619 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16620 for (int i = 0; i < childCount; i++) { 16621 PackageParser.Package childPkg = pkg.childPackages.get(i); 16622 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16623 } 16624 } 16625 16626 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16627 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16628 // Update the parent package setting 16629 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16630 res, user, installReason); 16631 // Update the child packages setting 16632 final int childCount = (newPackage.childPackages != null) 16633 ? newPackage.childPackages.size() : 0; 16634 for (int i = 0; i < childCount; i++) { 16635 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16636 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16637 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16638 childRes.origUsers, childRes, user, installReason); 16639 } 16640 } 16641 16642 private void updateSettingsInternalLI(PackageParser.Package pkg, 16643 String installerPackageName, int[] allUsers, int[] installedForUsers, 16644 PackageInstalledInfo res, UserHandle user, int installReason) { 16645 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16646 16647 final String pkgName = pkg.packageName; 16648 16649 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16650 synchronized (mPackages) { 16651// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16652 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16653 mPermissionCallback); 16654 // For system-bundled packages, we assume that installing an upgraded version 16655 // of the package implies that the user actually wants to run that new code, 16656 // so we enable the package. 16657 PackageSetting ps = mSettings.mPackages.get(pkgName); 16658 final int userId = user.getIdentifier(); 16659 if (ps != null) { 16660 if (isSystemApp(pkg)) { 16661 if (DEBUG_INSTALL) { 16662 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16663 } 16664 // Enable system package for requested users 16665 if (res.origUsers != null) { 16666 for (int origUserId : res.origUsers) { 16667 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16668 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16669 origUserId, installerPackageName); 16670 } 16671 } 16672 } 16673 // Also convey the prior install/uninstall state 16674 if (allUsers != null && installedForUsers != null) { 16675 for (int currentUserId : allUsers) { 16676 final boolean installed = ArrayUtils.contains( 16677 installedForUsers, currentUserId); 16678 if (DEBUG_INSTALL) { 16679 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16680 } 16681 ps.setInstalled(installed, currentUserId); 16682 } 16683 // these install state changes will be persisted in the 16684 // upcoming call to mSettings.writeLPr(). 16685 } 16686 } 16687 // It's implied that when a user requests installation, they want the app to be 16688 // installed and enabled. 16689 if (userId != UserHandle.USER_ALL) { 16690 ps.setInstalled(true, userId); 16691 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16692 } else { 16693 for (int currentUserId : sUserManager.getUserIds()) { 16694 ps.setInstalled(true, currentUserId); 16695 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, currentUserId, 16696 installerPackageName); 16697 } 16698 } 16699 16700 // When replacing an existing package, preserve the original install reason for all 16701 // users that had the package installed before. 16702 final Set<Integer> previousUserIds = new ArraySet<>(); 16703 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16704 final int installReasonCount = res.removedInfo.installReasons.size(); 16705 for (int i = 0; i < installReasonCount; i++) { 16706 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16707 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16708 ps.setInstallReason(previousInstallReason, previousUserId); 16709 previousUserIds.add(previousUserId); 16710 } 16711 } 16712 16713 // Set install reason for users that are having the package newly installed. 16714 if (userId == UserHandle.USER_ALL) { 16715 for (int currentUserId : sUserManager.getUserIds()) { 16716 if (!previousUserIds.contains(currentUserId)) { 16717 ps.setInstallReason(installReason, currentUserId); 16718 } 16719 } 16720 } else if (!previousUserIds.contains(userId)) { 16721 ps.setInstallReason(installReason, userId); 16722 } 16723 mSettings.writeKernelMappingLPr(ps); 16724 } 16725 res.name = pkgName; 16726 res.uid = pkg.applicationInfo.uid; 16727 res.pkg = pkg; 16728 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16729 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16730 //to update install status 16731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16732 mSettings.writeLPr(); 16733 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16734 } 16735 16736 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16737 } 16738 16739 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16740 try { 16741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16742 installPackageLI(args, res); 16743 } finally { 16744 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16745 } 16746 } 16747 16748 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16749 final int installFlags = args.installFlags; 16750 final String installerPackageName = args.installerPackageName; 16751 final String volumeUuid = args.volumeUuid; 16752 final File tmpPackageFile = new File(args.getCodePath()); 16753 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16754 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16755 || (args.volumeUuid != null)); 16756 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16757 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16758 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16759 final boolean virtualPreload = 16760 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16761 boolean replace = false; 16762 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16763 if (args.move != null) { 16764 // moving a complete application; perform an initial scan on the new install location 16765 scanFlags |= SCAN_INITIAL; 16766 } 16767 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16768 scanFlags |= SCAN_DONT_KILL_APP; 16769 } 16770 if (instantApp) { 16771 scanFlags |= SCAN_AS_INSTANT_APP; 16772 } 16773 if (fullApp) { 16774 scanFlags |= SCAN_AS_FULL_APP; 16775 } 16776 if (virtualPreload) { 16777 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16778 } 16779 16780 // Result object to be returned 16781 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16782 res.installerPackageName = installerPackageName; 16783 16784 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16785 16786 // Sanity check 16787 if (instantApp && (forwardLocked || onExternal)) { 16788 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16789 + " external=" + onExternal); 16790 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16791 return; 16792 } 16793 16794 // Retrieve PackageSettings and parse package 16795 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16796 | PackageParser.PARSE_ENFORCE_CODE 16797 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16798 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16799 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16800 PackageParser pp = new PackageParser(); 16801 pp.setSeparateProcesses(mSeparateProcesses); 16802 pp.setDisplayMetrics(mMetrics); 16803 pp.setCallback(mPackageParserCallback); 16804 16805 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16806 final PackageParser.Package pkg; 16807 try { 16808 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16809 DexMetadataHelper.validatePackageDexMetadata(pkg); 16810 } catch (PackageParserException e) { 16811 res.setError("Failed parse during installPackageLI", e); 16812 return; 16813 } finally { 16814 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16815 } 16816 16817 // Instant apps have several additional install-time checks. 16818 if (instantApp) { 16819 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16820 Slog.w(TAG, 16821 "Instant app package " + pkg.packageName + " does not target at least O"); 16822 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16823 "Instant app package must target at least O"); 16824 return; 16825 } 16826 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16827 Slog.w(TAG, "Instant app package " + pkg.packageName 16828 + " does not target targetSandboxVersion 2"); 16829 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16830 "Instant app package must use targetSandboxVersion 2"); 16831 return; 16832 } 16833 if (pkg.mSharedUserId != null) { 16834 Slog.w(TAG, "Instant app package " + pkg.packageName 16835 + " may not declare sharedUserId."); 16836 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16837 "Instant app package may not declare a sharedUserId"); 16838 return; 16839 } 16840 } 16841 16842 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16843 // Static shared libraries have synthetic package names 16844 renameStaticSharedLibraryPackage(pkg); 16845 16846 // No static shared libs on external storage 16847 if (onExternal) { 16848 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16849 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16850 "Packages declaring static-shared libs cannot be updated"); 16851 return; 16852 } 16853 } 16854 16855 // If we are installing a clustered package add results for the children 16856 if (pkg.childPackages != null) { 16857 synchronized (mPackages) { 16858 final int childCount = pkg.childPackages.size(); 16859 for (int i = 0; i < childCount; i++) { 16860 PackageParser.Package childPkg = pkg.childPackages.get(i); 16861 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16862 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16863 childRes.pkg = childPkg; 16864 childRes.name = childPkg.packageName; 16865 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16866 if (childPs != null) { 16867 childRes.origUsers = childPs.queryInstalledUsers( 16868 sUserManager.getUserIds(), true); 16869 } 16870 if ((mPackages.containsKey(childPkg.packageName))) { 16871 childRes.removedInfo = new PackageRemovedInfo(this); 16872 childRes.removedInfo.removedPackage = childPkg.packageName; 16873 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16874 } 16875 if (res.addedChildPackages == null) { 16876 res.addedChildPackages = new ArrayMap<>(); 16877 } 16878 res.addedChildPackages.put(childPkg.packageName, childRes); 16879 } 16880 } 16881 } 16882 16883 // If package doesn't declare API override, mark that we have an install 16884 // time CPU ABI override. 16885 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16886 pkg.cpuAbiOverride = args.abiOverride; 16887 } 16888 16889 String pkgName = res.name = pkg.packageName; 16890 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16891 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16892 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16893 return; 16894 } 16895 } 16896 16897 try { 16898 // either use what we've been given or parse directly from the APK 16899 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16900 pkg.setSigningDetails(args.signingDetails); 16901 } else { 16902 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16903 } 16904 } catch (PackageParserException e) { 16905 res.setError("Failed collect during installPackageLI", e); 16906 return; 16907 } 16908 16909 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16910 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16911 Slog.w(TAG, "Instant app package " + pkg.packageName 16912 + " is not signed with at least APK Signature Scheme v2"); 16913 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16914 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16915 return; 16916 } 16917 16918 // Get rid of all references to package scan path via parser. 16919 pp = null; 16920 String oldCodePath = null; 16921 boolean systemApp = false; 16922 synchronized (mPackages) { 16923 // Check if installing already existing package 16924 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16925 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16926 if (pkg.mOriginalPackages != null 16927 && pkg.mOriginalPackages.contains(oldName) 16928 && mPackages.containsKey(oldName)) { 16929 // This package is derived from an original package, 16930 // and this device has been updating from that original 16931 // name. We must continue using the original name, so 16932 // rename the new package here. 16933 pkg.setPackageName(oldName); 16934 pkgName = pkg.packageName; 16935 replace = true; 16936 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16937 + oldName + " pkgName=" + pkgName); 16938 } else if (mPackages.containsKey(pkgName)) { 16939 // This package, under its official name, already exists 16940 // on the device; we should replace it. 16941 replace = true; 16942 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16943 } 16944 16945 // Child packages are installed through the parent package 16946 if (pkg.parentPackage != null) { 16947 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16948 "Package " + pkg.packageName + " is child of package " 16949 + pkg.parentPackage.parentPackage + ". Child packages " 16950 + "can be updated only through the parent package."); 16951 return; 16952 } 16953 16954 if (replace) { 16955 // Prevent apps opting out from runtime permissions 16956 PackageParser.Package oldPackage = mPackages.get(pkgName); 16957 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16958 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16959 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16960 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16961 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16962 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16963 + " doesn't support runtime permissions but the old" 16964 + " target SDK " + oldTargetSdk + " does."); 16965 return; 16966 } 16967 // Prevent persistent apps from being updated 16968 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16969 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16970 "Package " + oldPackage.packageName + " is a persistent app. " 16971 + "Persistent apps are not updateable."); 16972 return; 16973 } 16974 // Prevent apps from downgrading their targetSandbox. 16975 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16976 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16977 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16978 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16979 "Package " + pkg.packageName + " new target sandbox " 16980 + newTargetSandbox + " is incompatible with the previous value of" 16981 + oldTargetSandbox + "."); 16982 return; 16983 } 16984 16985 // Prevent installing of child packages 16986 if (oldPackage.parentPackage != null) { 16987 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16988 "Package " + pkg.packageName + " is child of package " 16989 + oldPackage.parentPackage + ". Child packages " 16990 + "can be updated only through the parent package."); 16991 return; 16992 } 16993 } 16994 } 16995 16996 PackageSetting ps = mSettings.mPackages.get(pkgName); 16997 if (ps != null) { 16998 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16999 17000 // Static shared libs have same package with different versions where 17001 // we internally use a synthetic package name to allow multiple versions 17002 // of the same package, therefore we need to compare signatures against 17003 // the package setting for the latest library version. 17004 PackageSetting signatureCheckPs = ps; 17005 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17006 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 17007 if (libraryEntry != null) { 17008 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 17009 } 17010 } 17011 17012 // Quick sanity check that we're signed correctly if updating; 17013 // we'll check this again later when scanning, but we want to 17014 // bail early here before tripping over redefined permissions. 17015 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17016 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 17017 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 17018 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17019 + pkg.packageName + " upgrade keys do not match the " 17020 + "previously installed version"); 17021 return; 17022 } 17023 } else { 17024 try { 17025 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17026 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17027 // We don't care about disabledPkgSetting on install for now. 17028 final boolean compatMatch = verifySignatures( 17029 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17030 compareRecover); 17031 // The new KeySets will be re-added later in the scanning process. 17032 if (compatMatch) { 17033 synchronized (mPackages) { 17034 ksms.removeAppKeySetDataLPw(pkg.packageName); 17035 } 17036 } 17037 } catch (PackageManagerException e) { 17038 res.setError(e.error, e.getMessage()); 17039 return; 17040 } 17041 } 17042 17043 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 17044 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17045 systemApp = (ps.pkg.applicationInfo.flags & 17046 ApplicationInfo.FLAG_SYSTEM) != 0; 17047 } 17048 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17049 } 17050 17051 int N = pkg.permissions.size(); 17052 for (int i = N-1; i >= 0; i--) { 17053 final PackageParser.Permission perm = pkg.permissions.get(i); 17054 final BasePermission bp = 17055 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17056 17057 // Don't allow anyone but the system to define ephemeral permissions. 17058 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17059 && !systemApp) { 17060 Slog.w(TAG, "Non-System package " + pkg.packageName 17061 + " attempting to delcare ephemeral permission " 17062 + perm.info.name + "; Removing ephemeral."); 17063 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17064 } 17065 17066 // Check whether the newly-scanned package wants to define an already-defined perm 17067 if (bp != null) { 17068 // If the defining package is signed with our cert, it's okay. This 17069 // also includes the "updating the same package" case, of course. 17070 // "updating same package" could also involve key-rotation. 17071 final boolean sigsOk; 17072 final String sourcePackageName = bp.getSourcePackageName(); 17073 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17074 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17075 if (sourcePackageName.equals(pkg.packageName) 17076 && (ksms.shouldCheckUpgradeKeySetLocked( 17077 sourcePackageSetting, scanFlags))) { 17078 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17079 } else { 17080 17081 // in the event of signing certificate rotation, we need to see if the 17082 // package's certificate has rotated from the current one, or if it is an 17083 // older certificate with which the current is ok with sharing permissions 17084 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17085 pkg.mSigningDetails, 17086 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17087 sigsOk = true; 17088 } else if (pkg.mSigningDetails.checkCapability( 17089 sourcePackageSetting.signatures.mSigningDetails, 17090 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17091 17092 // the scanned package checks out, has signing certificate rotation 17093 // history, and is newer; bring it over 17094 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17095 sigsOk = true; 17096 } else { 17097 sigsOk = false; 17098 } 17099 } 17100 if (!sigsOk) { 17101 // If the owning package is the system itself, we log but allow 17102 // install to proceed; we fail the install on all other permission 17103 // redefinitions. 17104 if (!sourcePackageName.equals("android")) { 17105 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17106 + pkg.packageName + " attempting to redeclare permission " 17107 + perm.info.name + " already owned by " + sourcePackageName); 17108 res.origPermission = perm.info.name; 17109 res.origPackage = sourcePackageName; 17110 return; 17111 } else { 17112 Slog.w(TAG, "Package " + pkg.packageName 17113 + " attempting to redeclare system permission " 17114 + perm.info.name + "; ignoring new declaration"); 17115 pkg.permissions.remove(i); 17116 } 17117 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17118 // Prevent apps to change protection level to dangerous from any other 17119 // type as this would allow a privilege escalation where an app adds a 17120 // normal/signature permission in other app's group and later redefines 17121 // it as dangerous leading to the group auto-grant. 17122 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17123 == PermissionInfo.PROTECTION_DANGEROUS) { 17124 if (bp != null && !bp.isRuntime()) { 17125 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17126 + "non-runtime permission " + perm.info.name 17127 + " to runtime; keeping old protection level"); 17128 perm.info.protectionLevel = bp.getProtectionLevel(); 17129 } 17130 } 17131 } 17132 } 17133 } 17134 } 17135 17136 if (systemApp) { 17137 if (onExternal) { 17138 // Abort update; system app can't be replaced with app on sdcard 17139 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17140 "Cannot install updates to system apps on sdcard"); 17141 return; 17142 } else if (instantApp) { 17143 // Abort update; system app can't be replaced with an instant app 17144 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17145 "Cannot update a system app with an instant app"); 17146 return; 17147 } 17148 } 17149 17150 if (args.move != null) { 17151 // We did an in-place move, so dex is ready to roll 17152 scanFlags |= SCAN_NO_DEX; 17153 scanFlags |= SCAN_MOVE; 17154 17155 synchronized (mPackages) { 17156 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17157 if (ps == null) { 17158 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17159 "Missing settings for moved package " + pkgName); 17160 } 17161 17162 // We moved the entire application as-is, so bring over the 17163 // previously derived ABI information. 17164 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17165 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17166 } 17167 17168 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17169 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17170 scanFlags |= SCAN_NO_DEX; 17171 17172 try { 17173 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17174 args.abiOverride : pkg.cpuAbiOverride); 17175 final boolean extractNativeLibs = !pkg.isLibrary(); 17176 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17177 } catch (PackageManagerException pme) { 17178 Slog.e(TAG, "Error deriving application ABI", pme); 17179 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17180 return; 17181 } 17182 17183 // Shared libraries for the package need to be updated. 17184 synchronized (mPackages) { 17185 try { 17186 updateSharedLibrariesLPr(pkg, null); 17187 } catch (PackageManagerException e) { 17188 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17189 } 17190 } 17191 } 17192 17193 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17194 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17195 return; 17196 } 17197 17198 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17199 String apkPath = null; 17200 synchronized (mPackages) { 17201 // Note that if the attacker managed to skip verify setup, for example by tampering 17202 // with the package settings, upon reboot we will do full apk verification when 17203 // verity is not detected. 17204 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17205 if (ps != null && ps.isPrivileged()) { 17206 apkPath = pkg.baseCodePath; 17207 } 17208 } 17209 17210 if (apkPath != null) { 17211 final VerityUtils.SetupResult result = 17212 VerityUtils.generateApkVeritySetupData(apkPath); 17213 if (result.isOk()) { 17214 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17215 FileDescriptor fd = result.getUnownedFileDescriptor(); 17216 try { 17217 mInstaller.installApkVerity(apkPath, fd); 17218 } catch (InstallerException e) { 17219 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17220 "Failed to set up verity: " + e); 17221 return; 17222 } finally { 17223 IoUtils.closeQuietly(fd); 17224 } 17225 } else if (result.isFailed()) { 17226 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17227 return; 17228 } else { 17229 // Do nothing if verity is skipped. Will fall back to full apk verification on 17230 // reboot. 17231 } 17232 } 17233 } 17234 17235 if (!instantApp) { 17236 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17237 } else { 17238 if (DEBUG_DOMAIN_VERIFICATION) { 17239 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17240 } 17241 } 17242 17243 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17244 "installPackageLI")) { 17245 if (replace) { 17246 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17247 // Static libs have a synthetic package name containing the version 17248 // and cannot be updated as an update would get a new package name, 17249 // unless this is the exact same version code which is useful for 17250 // development. 17251 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17252 if (existingPkg != null && 17253 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17254 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17255 + "static-shared libs cannot be updated"); 17256 return; 17257 } 17258 } 17259 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17260 installerPackageName, res, args.installReason); 17261 } else { 17262 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17263 args.user, installerPackageName, volumeUuid, res, args.installReason); 17264 } 17265 } 17266 17267 // Prepare the application profiles for the new code paths. 17268 // This needs to be done before invoking dexopt so that any install-time profile 17269 // can be used for optimizations. 17270 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17271 17272 // Check whether we need to dexopt the app. 17273 // 17274 // NOTE: it is IMPORTANT to call dexopt: 17275 // - after doRename which will sync the package data from PackageParser.Package and its 17276 // corresponding ApplicationInfo. 17277 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17278 // uid of the application (pkg.applicationInfo.uid). 17279 // This update happens in place! 17280 // 17281 // We only need to dexopt if the package meets ALL of the following conditions: 17282 // 1) it is not forward locked. 17283 // 2) it is not on on an external ASEC container. 17284 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17285 // 17286 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17287 // complete, so we skip this step during installation. Instead, we'll take extra time 17288 // the first time the instant app starts. It's preferred to do it this way to provide 17289 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17290 // middle of running an instant app. The default behaviour can be overridden 17291 // via gservices. 17292 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17293 && !forwardLocked 17294 && !pkg.applicationInfo.isExternalAsec() 17295 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17296 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17297 17298 if (performDexopt) { 17299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17300 // Do not run PackageDexOptimizer through the local performDexOpt 17301 // method because `pkg` may not be in `mPackages` yet. 17302 // 17303 // Also, don't fail application installs if the dexopt step fails. 17304 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17305 REASON_INSTALL, 17306 DexoptOptions.DEXOPT_BOOT_COMPLETE | 17307 DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17308 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17309 null /* instructionSets */, 17310 getOrCreateCompilerPackageStats(pkg), 17311 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17312 dexoptOptions); 17313 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17314 } 17315 17316 // Notify BackgroundDexOptService that the package has been changed. 17317 // If this is an update of a package which used to fail to compile, 17318 // BackgroundDexOptService will remove it from its blacklist. 17319 // TODO: Layering violation 17320 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17321 17322 synchronized (mPackages) { 17323 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17324 if (ps != null) { 17325 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17326 ps.setUpdateAvailable(false /*updateAvailable*/); 17327 } 17328 17329 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17330 for (int i = 0; i < childCount; i++) { 17331 PackageParser.Package childPkg = pkg.childPackages.get(i); 17332 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17333 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17334 if (childPs != null) { 17335 childRes.newUsers = childPs.queryInstalledUsers( 17336 sUserManager.getUserIds(), true); 17337 } 17338 } 17339 17340 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17341 updateSequenceNumberLP(ps, res.newUsers); 17342 updateInstantAppInstallerLocked(pkgName); 17343 } 17344 } 17345 } 17346 17347 private void startIntentFilterVerifications(int userId, boolean replacing, 17348 PackageParser.Package pkg) { 17349 if (mIntentFilterVerifierComponent == null) { 17350 Slog.w(TAG, "No IntentFilter verification will not be done as " 17351 + "there is no IntentFilterVerifier available!"); 17352 return; 17353 } 17354 17355 final int verifierUid = getPackageUid( 17356 mIntentFilterVerifierComponent.getPackageName(), 17357 MATCH_DEBUG_TRIAGED_MISSING, 17358 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17359 17360 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17361 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17362 mHandler.sendMessage(msg); 17363 17364 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17365 for (int i = 0; i < childCount; i++) { 17366 PackageParser.Package childPkg = pkg.childPackages.get(i); 17367 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17368 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17369 mHandler.sendMessage(msg); 17370 } 17371 } 17372 17373 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17374 PackageParser.Package pkg) { 17375 int size = pkg.activities.size(); 17376 if (size == 0) { 17377 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17378 "No activity, so no need to verify any IntentFilter!"); 17379 return; 17380 } 17381 17382 final boolean hasDomainURLs = hasDomainURLs(pkg); 17383 if (!hasDomainURLs) { 17384 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17385 "No domain URLs, so no need to verify any IntentFilter!"); 17386 return; 17387 } 17388 17389 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17390 + " if any IntentFilter from the " + size 17391 + " Activities needs verification ..."); 17392 17393 int count = 0; 17394 final String packageName = pkg.packageName; 17395 17396 synchronized (mPackages) { 17397 // If this is a new install and we see that we've already run verification for this 17398 // package, we have nothing to do: it means the state was restored from backup. 17399 if (!replacing) { 17400 IntentFilterVerificationInfo ivi = 17401 mSettings.getIntentFilterVerificationLPr(packageName); 17402 if (ivi != null) { 17403 if (DEBUG_DOMAIN_VERIFICATION) { 17404 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17405 + ivi.getStatusString()); 17406 } 17407 return; 17408 } 17409 } 17410 17411 // If any filters need to be verified, then all need to be. 17412 boolean needToVerify = false; 17413 for (PackageParser.Activity a : pkg.activities) { 17414 for (ActivityIntentInfo filter : a.intents) { 17415 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17416 if (DEBUG_DOMAIN_VERIFICATION) { 17417 Slog.d(TAG, 17418 "Intent filter needs verification, so processing all filters"); 17419 } 17420 needToVerify = true; 17421 break; 17422 } 17423 } 17424 } 17425 17426 if (needToVerify) { 17427 final int verificationId = mIntentFilterVerificationToken++; 17428 for (PackageParser.Activity a : pkg.activities) { 17429 for (ActivityIntentInfo filter : a.intents) { 17430 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17431 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17432 "Verification needed for IntentFilter:" + filter.toString()); 17433 mIntentFilterVerifier.addOneIntentFilterVerification( 17434 verifierUid, userId, verificationId, filter, packageName); 17435 count++; 17436 } 17437 } 17438 } 17439 } 17440 } 17441 17442 if (count > 0) { 17443 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17444 + " IntentFilter verification" + (count > 1 ? "s" : "") 17445 + " for userId:" + userId); 17446 mIntentFilterVerifier.startVerifications(userId); 17447 } else { 17448 if (DEBUG_DOMAIN_VERIFICATION) { 17449 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17450 } 17451 } 17452 } 17453 17454 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17455 final ComponentName cn = filter.activity.getComponentName(); 17456 final String packageName = cn.getPackageName(); 17457 17458 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17459 packageName); 17460 if (ivi == null) { 17461 return true; 17462 } 17463 int status = ivi.getStatus(); 17464 switch (status) { 17465 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17466 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17467 return true; 17468 17469 default: 17470 // Nothing to do 17471 return false; 17472 } 17473 } 17474 17475 private static boolean isMultiArch(ApplicationInfo info) { 17476 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17477 } 17478 17479 private static boolean isExternal(PackageParser.Package pkg) { 17480 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17481 } 17482 17483 private static boolean isExternal(PackageSetting ps) { 17484 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17485 } 17486 17487 private static boolean isSystemApp(PackageParser.Package pkg) { 17488 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17489 } 17490 17491 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17492 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17493 } 17494 17495 private static boolean isOemApp(PackageParser.Package pkg) { 17496 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17497 } 17498 17499 private static boolean isVendorApp(PackageParser.Package pkg) { 17500 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17501 } 17502 17503 private static boolean isProductApp(PackageParser.Package pkg) { 17504 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17505 } 17506 17507 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17508 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17509 } 17510 17511 private static boolean isSystemApp(PackageSetting ps) { 17512 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17513 } 17514 17515 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17516 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17517 } 17518 17519 private int packageFlagsToInstallFlags(PackageSetting ps) { 17520 int installFlags = 0; 17521 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17522 // This existing package was an external ASEC install when we have 17523 // the external flag without a UUID 17524 installFlags |= PackageManager.INSTALL_EXTERNAL; 17525 } 17526 if (ps.isForwardLocked()) { 17527 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17528 } 17529 return installFlags; 17530 } 17531 17532 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17533 if (isExternal(pkg)) { 17534 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17535 return mSettings.getExternalVersion(); 17536 } else { 17537 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17538 } 17539 } else { 17540 return mSettings.getInternalVersion(); 17541 } 17542 } 17543 17544 private void deleteTempPackageFiles() { 17545 final FilenameFilter filter = new FilenameFilter() { 17546 public boolean accept(File dir, String name) { 17547 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17548 } 17549 }; 17550 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17551 file.delete(); 17552 } 17553 } 17554 17555 @Override 17556 public void deletePackageAsUser(String packageName, int versionCode, 17557 IPackageDeleteObserver observer, int userId, int flags) { 17558 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17559 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17560 } 17561 17562 @Override 17563 public void deletePackageVersioned(VersionedPackage versionedPackage, 17564 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17565 final int callingUid = Binder.getCallingUid(); 17566 mContext.enforceCallingOrSelfPermission( 17567 android.Manifest.permission.DELETE_PACKAGES, null); 17568 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17569 Preconditions.checkNotNull(versionedPackage); 17570 Preconditions.checkNotNull(observer); 17571 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17572 PackageManager.VERSION_CODE_HIGHEST, 17573 Long.MAX_VALUE, "versionCode must be >= -1"); 17574 17575 final String packageName = versionedPackage.getPackageName(); 17576 final long versionCode = versionedPackage.getLongVersionCode(); 17577 final String internalPackageName; 17578 synchronized (mPackages) { 17579 // Normalize package name to handle renamed packages and static libs 17580 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17581 } 17582 17583 final int uid = Binder.getCallingUid(); 17584 if (!isOrphaned(internalPackageName) 17585 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17586 try { 17587 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17588 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17589 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17590 observer.onUserActionRequired(intent); 17591 } catch (RemoteException re) { 17592 } 17593 return; 17594 } 17595 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17596 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17597 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17598 mContext.enforceCallingOrSelfPermission( 17599 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17600 "deletePackage for user " + userId); 17601 } 17602 17603 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17604 try { 17605 observer.onPackageDeleted(packageName, 17606 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17607 } catch (RemoteException re) { 17608 } 17609 return; 17610 } 17611 17612 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17613 try { 17614 observer.onPackageDeleted(packageName, 17615 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17616 } catch (RemoteException re) { 17617 } 17618 return; 17619 } 17620 17621 if (DEBUG_REMOVE) { 17622 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17623 + " deleteAllUsers: " + deleteAllUsers + " version=" 17624 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17625 ? "VERSION_CODE_HIGHEST" : versionCode)); 17626 } 17627 // Queue up an async operation since the package deletion may take a little while. 17628 mHandler.post(new Runnable() { 17629 public void run() { 17630 mHandler.removeCallbacks(this); 17631 int returnCode; 17632 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17633 boolean doDeletePackage = true; 17634 if (ps != null) { 17635 final boolean targetIsInstantApp = 17636 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17637 doDeletePackage = !targetIsInstantApp 17638 || canViewInstantApps; 17639 } 17640 if (doDeletePackage) { 17641 if (!deleteAllUsers) { 17642 returnCode = deletePackageX(internalPackageName, versionCode, 17643 userId, deleteFlags); 17644 } else { 17645 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17646 internalPackageName, users); 17647 // If nobody is blocking uninstall, proceed with delete for all users 17648 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17649 returnCode = deletePackageX(internalPackageName, versionCode, 17650 userId, deleteFlags); 17651 } else { 17652 // Otherwise uninstall individually for users with blockUninstalls=false 17653 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17654 for (int userId : users) { 17655 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17656 returnCode = deletePackageX(internalPackageName, versionCode, 17657 userId, userFlags); 17658 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17659 Slog.w(TAG, "Package delete failed for user " + userId 17660 + ", returnCode " + returnCode); 17661 } 17662 } 17663 } 17664 // The app has only been marked uninstalled for certain users. 17665 // We still need to report that delete was blocked 17666 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17667 } 17668 } 17669 } else { 17670 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17671 } 17672 try { 17673 observer.onPackageDeleted(packageName, returnCode, null); 17674 } catch (RemoteException e) { 17675 Log.i(TAG, "Observer no longer exists."); 17676 } //end catch 17677 } //end run 17678 }); 17679 } 17680 17681 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17682 if (pkg.staticSharedLibName != null) { 17683 return pkg.manifestPackageName; 17684 } 17685 return pkg.packageName; 17686 } 17687 17688 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17689 // Handle renamed packages 17690 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17691 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17692 17693 // Is this a static library? 17694 LongSparseArray<SharedLibraryEntry> versionedLib = 17695 mStaticLibsByDeclaringPackage.get(packageName); 17696 if (versionedLib == null || versionedLib.size() <= 0) { 17697 return packageName; 17698 } 17699 17700 // Figure out which lib versions the caller can see 17701 LongSparseLongArray versionsCallerCanSee = null; 17702 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17703 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17704 && callingAppId != Process.ROOT_UID) { 17705 versionsCallerCanSee = new LongSparseLongArray(); 17706 String libName = versionedLib.valueAt(0).info.getName(); 17707 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17708 if (uidPackages != null) { 17709 for (String uidPackage : uidPackages) { 17710 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17711 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17712 if (libIdx >= 0) { 17713 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17714 versionsCallerCanSee.append(libVersion, libVersion); 17715 } 17716 } 17717 } 17718 } 17719 17720 // Caller can see nothing - done 17721 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17722 return packageName; 17723 } 17724 17725 // Find the version the caller can see and the app version code 17726 SharedLibraryEntry highestVersion = null; 17727 final int versionCount = versionedLib.size(); 17728 for (int i = 0; i < versionCount; i++) { 17729 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17730 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17731 libEntry.info.getLongVersion()) < 0) { 17732 continue; 17733 } 17734 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17735 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17736 if (libVersionCode == versionCode) { 17737 return libEntry.apk; 17738 } 17739 } else if (highestVersion == null) { 17740 highestVersion = libEntry; 17741 } else if (libVersionCode > highestVersion.info 17742 .getDeclaringPackage().getLongVersionCode()) { 17743 highestVersion = libEntry; 17744 } 17745 } 17746 17747 if (highestVersion != null) { 17748 return highestVersion.apk; 17749 } 17750 17751 return packageName; 17752 } 17753 17754 boolean isCallerVerifier(int callingUid) { 17755 final int callingUserId = UserHandle.getUserId(callingUid); 17756 return mRequiredVerifierPackage != null && 17757 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17758 } 17759 17760 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17761 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17762 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17763 return true; 17764 } 17765 final int callingUserId = UserHandle.getUserId(callingUid); 17766 // If the caller installed the pkgName, then allow it to silently uninstall. 17767 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17768 return true; 17769 } 17770 17771 // Allow package verifier to silently uninstall. 17772 if (mRequiredVerifierPackage != null && 17773 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17774 return true; 17775 } 17776 17777 // Allow package uninstaller to silently uninstall. 17778 if (mRequiredUninstallerPackage != null && 17779 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17780 return true; 17781 } 17782 17783 // Allow storage manager to silently uninstall. 17784 if (mStorageManagerPackage != null && 17785 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17786 return true; 17787 } 17788 17789 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17790 // uninstall for device owner provisioning. 17791 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17792 == PERMISSION_GRANTED) { 17793 return true; 17794 } 17795 17796 return false; 17797 } 17798 17799 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17800 int[] result = EMPTY_INT_ARRAY; 17801 for (int userId : userIds) { 17802 if (getBlockUninstallForUser(packageName, userId)) { 17803 result = ArrayUtils.appendInt(result, userId); 17804 } 17805 } 17806 return result; 17807 } 17808 17809 @Override 17810 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17811 final int callingUid = Binder.getCallingUid(); 17812 if (getInstantAppPackageName(callingUid) != null 17813 && !isCallerSameApp(packageName, callingUid)) { 17814 return false; 17815 } 17816 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17817 } 17818 17819 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17820 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17821 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17822 try { 17823 if (dpm != null) { 17824 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17825 /* callingUserOnly =*/ false); 17826 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17827 : deviceOwnerComponentName.getPackageName(); 17828 // Does the package contains the device owner? 17829 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17830 // this check is probably not needed, since DO should be registered as a device 17831 // admin on some user too. (Original bug for this: b/17657954) 17832 if (packageName.equals(deviceOwnerPackageName)) { 17833 return true; 17834 } 17835 // Does it contain a device admin for any user? 17836 int[] users; 17837 if (userId == UserHandle.USER_ALL) { 17838 users = sUserManager.getUserIds(); 17839 } else { 17840 users = new int[]{userId}; 17841 } 17842 for (int i = 0; i < users.length; ++i) { 17843 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17844 return true; 17845 } 17846 } 17847 } 17848 } catch (RemoteException e) { 17849 } 17850 return false; 17851 } 17852 17853 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17854 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17855 } 17856 17857 /** 17858 * This method is an internal method that could be get invoked either 17859 * to delete an installed package or to clean up a failed installation. 17860 * After deleting an installed package, a broadcast is sent to notify any 17861 * listeners that the package has been removed. For cleaning up a failed 17862 * installation, the broadcast is not necessary since the package's 17863 * installation wouldn't have sent the initial broadcast either 17864 * The key steps in deleting a package are 17865 * deleting the package information in internal structures like mPackages, 17866 * deleting the packages base directories through installd 17867 * updating mSettings to reflect current status 17868 * persisting settings for later use 17869 * sending a broadcast if necessary 17870 */ 17871 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17872 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17873 final boolean res; 17874 17875 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17876 ? UserHandle.USER_ALL : userId; 17877 17878 if (isPackageDeviceAdmin(packageName, removeUser)) { 17879 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17880 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17881 } 17882 17883 PackageSetting uninstalledPs = null; 17884 PackageParser.Package pkg = null; 17885 17886 // for the uninstall-updates case and restricted profiles, remember the per- 17887 // user handle installed state 17888 int[] allUsers; 17889 synchronized (mPackages) { 17890 uninstalledPs = mSettings.mPackages.get(packageName); 17891 if (uninstalledPs == null) { 17892 Slog.w(TAG, "Not removing non-existent package " + packageName); 17893 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17894 } 17895 17896 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17897 && uninstalledPs.versionCode != versionCode) { 17898 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17899 + uninstalledPs.versionCode + " != " + versionCode); 17900 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17901 } 17902 17903 // Static shared libs can be declared by any package, so let us not 17904 // allow removing a package if it provides a lib others depend on. 17905 pkg = mPackages.get(packageName); 17906 17907 allUsers = sUserManager.getUserIds(); 17908 17909 if (pkg != null && pkg.staticSharedLibName != null) { 17910 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17911 pkg.staticSharedLibVersion); 17912 if (libEntry != null) { 17913 for (int currUserId : allUsers) { 17914 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17915 continue; 17916 } 17917 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17918 libEntry.info, 0, currUserId); 17919 if (!ArrayUtils.isEmpty(libClientPackages)) { 17920 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17921 + " hosting lib " + libEntry.info.getName() + " version " 17922 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17923 + " for user " + currUserId); 17924 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17925 } 17926 } 17927 } 17928 } 17929 17930 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17931 } 17932 17933 final int freezeUser; 17934 if (isUpdatedSystemApp(uninstalledPs) 17935 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17936 // We're downgrading a system app, which will apply to all users, so 17937 // freeze them all during the downgrade 17938 freezeUser = UserHandle.USER_ALL; 17939 } else { 17940 freezeUser = removeUser; 17941 } 17942 17943 synchronized (mInstallLock) { 17944 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17945 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17946 deleteFlags, "deletePackageX")) { 17947 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17948 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17949 } 17950 synchronized (mPackages) { 17951 if (res) { 17952 if (pkg != null) { 17953 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17954 } 17955 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17956 updateInstantAppInstallerLocked(packageName); 17957 } 17958 } 17959 } 17960 17961 if (res) { 17962 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17963 info.sendPackageRemovedBroadcasts(killApp); 17964 info.sendSystemPackageUpdatedBroadcasts(); 17965 info.sendSystemPackageAppearedBroadcasts(); 17966 } 17967 // Force a gc here. 17968 Runtime.getRuntime().gc(); 17969 // Delete the resources here after sending the broadcast to let 17970 // other processes clean up before deleting resources. 17971 if (info.args != null) { 17972 synchronized (mInstallLock) { 17973 info.args.doPostDeleteLI(true); 17974 } 17975 } 17976 17977 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17978 } 17979 17980 static class PackageRemovedInfo { 17981 final PackageSender packageSender; 17982 String removedPackage; 17983 String installerPackageName; 17984 int uid = -1; 17985 int removedAppId = -1; 17986 int[] origUsers; 17987 int[] removedUsers = null; 17988 int[] broadcastUsers = null; 17989 int[] instantUserIds = null; 17990 SparseArray<Integer> installReasons; 17991 boolean isRemovedPackageSystemUpdate = false; 17992 boolean isUpdate; 17993 boolean dataRemoved; 17994 boolean removedForAllUsers; 17995 boolean isStaticSharedLib; 17996 // Clean up resources deleted packages. 17997 InstallArgs args = null; 17998 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17999 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18000 18001 PackageRemovedInfo(PackageSender packageSender) { 18002 this.packageSender = packageSender; 18003 } 18004 18005 void sendPackageRemovedBroadcasts(boolean killApp) { 18006 sendPackageRemovedBroadcastInternal(killApp); 18007 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18008 for (int i = 0; i < childCount; i++) { 18009 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18010 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18011 } 18012 } 18013 18014 void sendSystemPackageUpdatedBroadcasts() { 18015 if (isRemovedPackageSystemUpdate) { 18016 sendSystemPackageUpdatedBroadcastsInternal(); 18017 final int childCount = (removedChildPackages != null) 18018 ? removedChildPackages.size() : 0; 18019 for (int i = 0; i < childCount; i++) { 18020 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18021 if (childInfo.isRemovedPackageSystemUpdate) { 18022 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18023 } 18024 } 18025 } 18026 } 18027 18028 void sendSystemPackageAppearedBroadcasts() { 18029 final int packageCount = (appearedChildPackages != null) 18030 ? appearedChildPackages.size() : 0; 18031 for (int i = 0; i < packageCount; i++) { 18032 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18033 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18034 true /*sendBootCompleted*/, false /*startReceiver*/, 18035 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18036 } 18037 } 18038 18039 private void sendSystemPackageUpdatedBroadcastsInternal() { 18040 Bundle extras = new Bundle(2); 18041 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18042 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18043 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18044 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18045 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18046 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18047 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18048 null, null, 0, removedPackage, null, null, null); 18049 if (installerPackageName != null) { 18050 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18051 removedPackage, extras, 0 /*flags*/, 18052 installerPackageName, null, null, null); 18053 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18054 removedPackage, extras, 0 /*flags*/, 18055 installerPackageName, null, null, null); 18056 } 18057 } 18058 18059 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18060 // Don't send static shared library removal broadcasts as these 18061 // libs are visible only the the apps that depend on them an one 18062 // cannot remove the library if it has a dependency. 18063 if (isStaticSharedLib) { 18064 return; 18065 } 18066 Bundle extras = new Bundle(2); 18067 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18068 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18069 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18070 if (isUpdate || isRemovedPackageSystemUpdate) { 18071 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18072 } 18073 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18074 if (removedPackage != null) { 18075 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18076 removedPackage, extras, 0, null /*targetPackage*/, null, 18077 broadcastUsers, instantUserIds); 18078 if (installerPackageName != null) { 18079 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18080 removedPackage, extras, 0 /*flags*/, 18081 installerPackageName, null, broadcastUsers, instantUserIds); 18082 } 18083 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18084 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18085 removedPackage, extras, 18086 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18087 null, null, broadcastUsers, instantUserIds); 18088 packageSender.notifyPackageRemoved(removedPackage); 18089 } 18090 } 18091 if (removedAppId >= 0) { 18092 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18093 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18094 null, null, broadcastUsers, instantUserIds); 18095 } 18096 } 18097 18098 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18099 removedUsers = userIds; 18100 if (removedUsers == null) { 18101 broadcastUsers = null; 18102 return; 18103 } 18104 18105 broadcastUsers = EMPTY_INT_ARRAY; 18106 instantUserIds = EMPTY_INT_ARRAY; 18107 for (int i = userIds.length - 1; i >= 0; --i) { 18108 final int userId = userIds[i]; 18109 if (deletedPackageSetting.getInstantApp(userId)) { 18110 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18111 } else { 18112 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18113 } 18114 } 18115 } 18116 } 18117 18118 /* 18119 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18120 * flag is not set, the data directory is removed as well. 18121 * make sure this flag is set for partially installed apps. If not its meaningless to 18122 * delete a partially installed application. 18123 */ 18124 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18125 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18126 String packageName = ps.name; 18127 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18128 // Retrieve object to delete permissions for shared user later on 18129 final PackageParser.Package deletedPkg; 18130 final PackageSetting deletedPs; 18131 // reader 18132 synchronized (mPackages) { 18133 deletedPkg = mPackages.get(packageName); 18134 deletedPs = mSettings.mPackages.get(packageName); 18135 if (outInfo != null) { 18136 outInfo.removedPackage = packageName; 18137 outInfo.installerPackageName = ps.installerPackageName; 18138 outInfo.isStaticSharedLib = deletedPkg != null 18139 && deletedPkg.staticSharedLibName != null; 18140 outInfo.populateUsers(deletedPs == null ? null 18141 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18142 } 18143 } 18144 18145 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18146 18147 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18148 final PackageParser.Package resolvedPkg; 18149 if (deletedPkg != null) { 18150 resolvedPkg = deletedPkg; 18151 } else { 18152 // We don't have a parsed package when it lives on an ejected 18153 // adopted storage device, so fake something together 18154 resolvedPkg = new PackageParser.Package(ps.name); 18155 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18156 } 18157 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18158 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18159 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18160 if (outInfo != null) { 18161 outInfo.dataRemoved = true; 18162 } 18163 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18164 } 18165 18166 int removedAppId = -1; 18167 18168 // writer 18169 synchronized (mPackages) { 18170 boolean installedStateChanged = false; 18171 if (deletedPs != null) { 18172 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18173 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18174 clearDefaultBrowserIfNeeded(packageName); 18175 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18176 removedAppId = mSettings.removePackageLPw(packageName); 18177 if (outInfo != null) { 18178 outInfo.removedAppId = removedAppId; 18179 } 18180 mPermissionManager.updatePermissions( 18181 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18182 if (deletedPs.sharedUser != null) { 18183 // Remove permissions associated with package. Since runtime 18184 // permissions are per user we have to kill the removed package 18185 // or packages running under the shared user of the removed 18186 // package if revoking the permissions requested only by the removed 18187 // package is successful and this causes a change in gids. 18188 for (int userId : UserManagerService.getInstance().getUserIds()) { 18189 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18190 userId); 18191 if (userIdToKill == UserHandle.USER_ALL 18192 || userIdToKill >= UserHandle.USER_SYSTEM) { 18193 // If gids changed for this user, kill all affected packages. 18194 mHandler.post(new Runnable() { 18195 @Override 18196 public void run() { 18197 // This has to happen with no lock held. 18198 killApplication(deletedPs.name, deletedPs.appId, 18199 KILL_APP_REASON_GIDS_CHANGED); 18200 } 18201 }); 18202 break; 18203 } 18204 } 18205 } 18206 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18207 } 18208 // make sure to preserve per-user disabled state if this removal was just 18209 // a downgrade of a system app to the factory package 18210 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18211 if (DEBUG_REMOVE) { 18212 Slog.d(TAG, "Propagating install state across downgrade"); 18213 } 18214 for (int userId : allUserHandles) { 18215 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18216 if (DEBUG_REMOVE) { 18217 Slog.d(TAG, " user " + userId + " => " + installed); 18218 } 18219 if (installed != ps.getInstalled(userId)) { 18220 installedStateChanged = true; 18221 } 18222 ps.setInstalled(installed, userId); 18223 } 18224 } 18225 } 18226 // can downgrade to reader 18227 if (writeSettings) { 18228 // Save settings now 18229 mSettings.writeLPr(); 18230 } 18231 if (installedStateChanged) { 18232 mSettings.writeKernelMappingLPr(ps); 18233 } 18234 } 18235 if (removedAppId != -1) { 18236 // A user ID was deleted here. Go through all users and remove it 18237 // from KeyStore. 18238 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18239 } 18240 } 18241 18242 static boolean locationIsPrivileged(String path) { 18243 try { 18244 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18245 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18246 final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app"); 18247 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18248 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18249 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18250 || path.startsWith(privilegedOdmAppDir.getCanonicalPath()) 18251 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18252 } catch (IOException e) { 18253 Slog.e(TAG, "Unable to access code path " + path); 18254 } 18255 return false; 18256 } 18257 18258 static boolean locationIsOem(String path) { 18259 try { 18260 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18261 } catch (IOException e) { 18262 Slog.e(TAG, "Unable to access code path " + path); 18263 } 18264 return false; 18265 } 18266 18267 static boolean locationIsVendor(String path) { 18268 try { 18269 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()) 18270 || path.startsWith(Environment.getOdmDirectory().getCanonicalPath()); 18271 } catch (IOException e) { 18272 Slog.e(TAG, "Unable to access code path " + path); 18273 } 18274 return false; 18275 } 18276 18277 static boolean locationIsProduct(String path) { 18278 try { 18279 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18280 } catch (IOException e) { 18281 Slog.e(TAG, "Unable to access code path " + path); 18282 } 18283 return false; 18284 } 18285 18286 /* 18287 * Tries to delete system package. 18288 */ 18289 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18290 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18291 boolean writeSettings) { 18292 if (deletedPs.parentPackageName != null) { 18293 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18294 return false; 18295 } 18296 18297 final boolean applyUserRestrictions 18298 = (allUserHandles != null) && (outInfo.origUsers != null); 18299 final PackageSetting disabledPs; 18300 // Confirm if the system package has been updated 18301 // An updated system app can be deleted. This will also have to restore 18302 // the system pkg from system partition 18303 // reader 18304 synchronized (mPackages) { 18305 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18306 } 18307 18308 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18309 + " disabledPs=" + disabledPs); 18310 18311 if (disabledPs == null) { 18312 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18313 return false; 18314 } else if (DEBUG_REMOVE) { 18315 Slog.d(TAG, "Deleting system pkg from data partition"); 18316 } 18317 18318 if (DEBUG_REMOVE) { 18319 if (applyUserRestrictions) { 18320 Slog.d(TAG, "Remembering install states:"); 18321 for (int userId : allUserHandles) { 18322 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18323 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18324 } 18325 } 18326 } 18327 18328 // Delete the updated package 18329 outInfo.isRemovedPackageSystemUpdate = true; 18330 if (outInfo.removedChildPackages != null) { 18331 final int childCount = (deletedPs.childPackageNames != null) 18332 ? deletedPs.childPackageNames.size() : 0; 18333 for (int i = 0; i < childCount; i++) { 18334 String childPackageName = deletedPs.childPackageNames.get(i); 18335 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18336 .contains(childPackageName)) { 18337 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18338 childPackageName); 18339 if (childInfo != null) { 18340 childInfo.isRemovedPackageSystemUpdate = true; 18341 } 18342 } 18343 } 18344 } 18345 18346 if (disabledPs.versionCode < deletedPs.versionCode) { 18347 // Delete data for downgrades 18348 flags &= ~PackageManager.DELETE_KEEP_DATA; 18349 } else { 18350 // Preserve data by setting flag 18351 flags |= PackageManager.DELETE_KEEP_DATA; 18352 } 18353 18354 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18355 outInfo, writeSettings, disabledPs.pkg); 18356 if (!ret) { 18357 return false; 18358 } 18359 18360 // writer 18361 synchronized (mPackages) { 18362 // NOTE: The system package always needs to be enabled; even if it's for 18363 // a compressed stub. If we don't, installing the system package fails 18364 // during scan [scanning checks the disabled packages]. We will reverse 18365 // this later, after we've "installed" the stub. 18366 // Reinstate the old system package 18367 enableSystemPackageLPw(disabledPs.pkg); 18368 // Remove any native libraries from the upgraded package. 18369 removeNativeBinariesLI(deletedPs); 18370 } 18371 18372 // Install the system package 18373 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18374 try { 18375 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18376 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18377 } catch (PackageManagerException e) { 18378 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18379 + e.getMessage()); 18380 return false; 18381 } finally { 18382 if (disabledPs.pkg.isStub) { 18383 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18384 } 18385 } 18386 return true; 18387 } 18388 18389 /** 18390 * Installs a package that's already on the system partition. 18391 */ 18392 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18393 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18394 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18395 throws PackageManagerException { 18396 @ParseFlags int parseFlags = 18397 mDefParseFlags 18398 | PackageParser.PARSE_MUST_BE_APK 18399 | PackageParser.PARSE_IS_SYSTEM_DIR; 18400 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18401 if (isPrivileged || locationIsPrivileged(codePathString)) { 18402 scanFlags |= SCAN_AS_PRIVILEGED; 18403 } 18404 if (locationIsOem(codePathString)) { 18405 scanFlags |= SCAN_AS_OEM; 18406 } 18407 if (locationIsVendor(codePathString)) { 18408 scanFlags |= SCAN_AS_VENDOR; 18409 } 18410 if (locationIsProduct(codePathString)) { 18411 scanFlags |= SCAN_AS_PRODUCT; 18412 } 18413 18414 final File codePath = new File(codePathString); 18415 final PackageParser.Package pkg = 18416 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18417 18418 try { 18419 // update shared libraries for the newly re-installed system package 18420 updateSharedLibrariesLPr(pkg, null); 18421 } catch (PackageManagerException e) { 18422 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18423 } 18424 18425 prepareAppDataAfterInstallLIF(pkg); 18426 18427 // writer 18428 synchronized (mPackages) { 18429 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18430 18431 // Propagate the permissions state as we do not want to drop on the floor 18432 // runtime permissions. The update permissions method below will take 18433 // care of removing obsolete permissions and grant install permissions. 18434 if (origPermissionState != null) { 18435 ps.getPermissionsState().copyFrom(origPermissionState); 18436 } 18437 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18438 mPermissionCallback); 18439 18440 final boolean applyUserRestrictions 18441 = (allUserHandles != null) && (origUserHandles != null); 18442 if (applyUserRestrictions) { 18443 boolean installedStateChanged = false; 18444 if (DEBUG_REMOVE) { 18445 Slog.d(TAG, "Propagating install state across reinstall"); 18446 } 18447 for (int userId : allUserHandles) { 18448 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18449 if (DEBUG_REMOVE) { 18450 Slog.d(TAG, " user " + userId + " => " + installed); 18451 } 18452 if (installed != ps.getInstalled(userId)) { 18453 installedStateChanged = true; 18454 } 18455 ps.setInstalled(installed, userId); 18456 18457 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18458 } 18459 // Regardless of writeSettings we need to ensure that this restriction 18460 // state propagation is persisted 18461 mSettings.writeAllUsersPackageRestrictionsLPr(); 18462 if (installedStateChanged) { 18463 mSettings.writeKernelMappingLPr(ps); 18464 } 18465 } 18466 // can downgrade to reader here 18467 if (writeSettings) { 18468 mSettings.writeLPr(); 18469 } 18470 } 18471 return pkg; 18472 } 18473 18474 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18475 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18476 PackageRemovedInfo outInfo, boolean writeSettings, 18477 PackageParser.Package replacingPackage) { 18478 synchronized (mPackages) { 18479 if (outInfo != null) { 18480 outInfo.uid = ps.appId; 18481 } 18482 18483 if (outInfo != null && outInfo.removedChildPackages != null) { 18484 final int childCount = (ps.childPackageNames != null) 18485 ? ps.childPackageNames.size() : 0; 18486 for (int i = 0; i < childCount; i++) { 18487 String childPackageName = ps.childPackageNames.get(i); 18488 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18489 if (childPs == null) { 18490 return false; 18491 } 18492 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18493 childPackageName); 18494 if (childInfo != null) { 18495 childInfo.uid = childPs.appId; 18496 } 18497 } 18498 } 18499 } 18500 18501 // Delete package data from internal structures and also remove data if flag is set 18502 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18503 18504 // Delete the child packages data 18505 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18506 for (int i = 0; i < childCount; i++) { 18507 PackageSetting childPs; 18508 synchronized (mPackages) { 18509 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18510 } 18511 if (childPs != null) { 18512 PackageRemovedInfo childOutInfo = (outInfo != null 18513 && outInfo.removedChildPackages != null) 18514 ? outInfo.removedChildPackages.get(childPs.name) : null; 18515 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18516 && (replacingPackage != null 18517 && !replacingPackage.hasChildPackage(childPs.name)) 18518 ? flags & ~DELETE_KEEP_DATA : flags; 18519 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18520 deleteFlags, writeSettings); 18521 } 18522 } 18523 18524 // Delete application code and resources only for parent packages 18525 if (ps.parentPackageName == null) { 18526 if (deleteCodeAndResources && (outInfo != null)) { 18527 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18528 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18529 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18530 } 18531 } 18532 18533 return true; 18534 } 18535 18536 @Override 18537 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18538 int userId) { 18539 mContext.enforceCallingOrSelfPermission( 18540 android.Manifest.permission.DELETE_PACKAGES, null); 18541 synchronized (mPackages) { 18542 // Cannot block uninstall of static shared libs as they are 18543 // considered a part of the using app (emulating static linking). 18544 // Also static libs are installed always on internal storage. 18545 PackageParser.Package pkg = mPackages.get(packageName); 18546 if (pkg != null && pkg.staticSharedLibName != null) { 18547 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18548 + " providing static shared library: " + pkg.staticSharedLibName); 18549 return false; 18550 } 18551 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18552 mSettings.writePackageRestrictionsLPr(userId); 18553 } 18554 return true; 18555 } 18556 18557 @Override 18558 public boolean getBlockUninstallForUser(String packageName, int userId) { 18559 synchronized (mPackages) { 18560 final PackageSetting ps = mSettings.mPackages.get(packageName); 18561 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18562 return false; 18563 } 18564 return mSettings.getBlockUninstallLPr(userId, packageName); 18565 } 18566 } 18567 18568 @Override 18569 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18570 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18571 synchronized (mPackages) { 18572 PackageSetting ps = mSettings.mPackages.get(packageName); 18573 if (ps == null) { 18574 Log.w(TAG, "Package doesn't exist: " + packageName); 18575 return false; 18576 } 18577 if (systemUserApp) { 18578 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18579 } else { 18580 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18581 } 18582 mSettings.writeLPr(); 18583 } 18584 return true; 18585 } 18586 18587 /* 18588 * This method handles package deletion in general 18589 */ 18590 private boolean deletePackageLIF(String packageName, UserHandle user, 18591 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18592 PackageRemovedInfo outInfo, boolean writeSettings, 18593 PackageParser.Package replacingPackage) { 18594 if (packageName == null) { 18595 Slog.w(TAG, "Attempt to delete null packageName."); 18596 return false; 18597 } 18598 18599 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18600 18601 PackageSetting ps; 18602 synchronized (mPackages) { 18603 ps = mSettings.mPackages.get(packageName); 18604 if (ps == null) { 18605 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18606 return false; 18607 } 18608 18609 if (ps.parentPackageName != null && (!isSystemApp(ps) 18610 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18611 if (DEBUG_REMOVE) { 18612 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18613 + ((user == null) ? UserHandle.USER_ALL : user)); 18614 } 18615 final int removedUserId = (user != null) ? user.getIdentifier() 18616 : UserHandle.USER_ALL; 18617 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18618 return false; 18619 } 18620 markPackageUninstalledForUserLPw(ps, user); 18621 scheduleWritePackageRestrictionsLocked(user); 18622 return true; 18623 } 18624 } 18625 18626 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18627 && user.getIdentifier() != UserHandle.USER_ALL)) { 18628 // The caller is asking that the package only be deleted for a single 18629 // user. To do this, we just mark its uninstalled state and delete 18630 // its data. If this is a system app, we only allow this to happen if 18631 // they have set the special DELETE_SYSTEM_APP which requests different 18632 // semantics than normal for uninstalling system apps. 18633 markPackageUninstalledForUserLPw(ps, user); 18634 18635 if (!isSystemApp(ps)) { 18636 // Do not uninstall the APK if an app should be cached 18637 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18638 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18639 // Other user still have this package installed, so all 18640 // we need to do is clear this user's data and save that 18641 // it is uninstalled. 18642 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18643 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18644 return false; 18645 } 18646 scheduleWritePackageRestrictionsLocked(user); 18647 return true; 18648 } else { 18649 // We need to set it back to 'installed' so the uninstall 18650 // broadcasts will be sent correctly. 18651 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18652 ps.setInstalled(true, user.getIdentifier()); 18653 mSettings.writeKernelMappingLPr(ps); 18654 } 18655 } else { 18656 // This is a system app, so we assume that the 18657 // other users still have this package installed, so all 18658 // we need to do is clear this user's data and save that 18659 // it is uninstalled. 18660 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18661 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18662 return false; 18663 } 18664 scheduleWritePackageRestrictionsLocked(user); 18665 return true; 18666 } 18667 } 18668 18669 // If we are deleting a composite package for all users, keep track 18670 // of result for each child. 18671 if (ps.childPackageNames != null && outInfo != null) { 18672 synchronized (mPackages) { 18673 final int childCount = ps.childPackageNames.size(); 18674 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18675 for (int i = 0; i < childCount; i++) { 18676 String childPackageName = ps.childPackageNames.get(i); 18677 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18678 childInfo.removedPackage = childPackageName; 18679 childInfo.installerPackageName = ps.installerPackageName; 18680 outInfo.removedChildPackages.put(childPackageName, childInfo); 18681 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18682 if (childPs != null) { 18683 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18684 } 18685 } 18686 } 18687 } 18688 18689 boolean ret = false; 18690 if (isSystemApp(ps)) { 18691 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18692 // When an updated system application is deleted we delete the existing resources 18693 // as well and fall back to existing code in system partition 18694 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18695 } else { 18696 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18697 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18698 outInfo, writeSettings, replacingPackage); 18699 } 18700 18701 // Take a note whether we deleted the package for all users 18702 if (outInfo != null) { 18703 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18704 if (outInfo.removedChildPackages != null) { 18705 synchronized (mPackages) { 18706 final int childCount = outInfo.removedChildPackages.size(); 18707 for (int i = 0; i < childCount; i++) { 18708 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18709 if (childInfo != null) { 18710 childInfo.removedForAllUsers = mPackages.get( 18711 childInfo.removedPackage) == null; 18712 } 18713 } 18714 } 18715 } 18716 // If we uninstalled an update to a system app there may be some 18717 // child packages that appeared as they are declared in the system 18718 // app but were not declared in the update. 18719 if (isSystemApp(ps)) { 18720 synchronized (mPackages) { 18721 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18722 final int childCount = (updatedPs.childPackageNames != null) 18723 ? updatedPs.childPackageNames.size() : 0; 18724 for (int i = 0; i < childCount; i++) { 18725 String childPackageName = updatedPs.childPackageNames.get(i); 18726 if (outInfo.removedChildPackages == null 18727 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18728 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18729 if (childPs == null) { 18730 continue; 18731 } 18732 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18733 installRes.name = childPackageName; 18734 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18735 installRes.pkg = mPackages.get(childPackageName); 18736 installRes.uid = childPs.pkg.applicationInfo.uid; 18737 if (outInfo.appearedChildPackages == null) { 18738 outInfo.appearedChildPackages = new ArrayMap<>(); 18739 } 18740 outInfo.appearedChildPackages.put(childPackageName, installRes); 18741 } 18742 } 18743 } 18744 } 18745 } 18746 18747 return ret; 18748 } 18749 18750 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18751 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18752 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18753 for (int nextUserId : userIds) { 18754 if (DEBUG_REMOVE) { 18755 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18756 } 18757 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18758 false /*installed*/, 18759 true /*stopped*/, 18760 true /*notLaunched*/, 18761 false /*hidden*/, 18762 false /*suspended*/, 18763 false /*instantApp*/, 18764 false /*virtualPreload*/, 18765 null /*lastDisableAppCaller*/, 18766 null /*enabledComponents*/, 18767 null /*disabledComponents*/, 18768 ps.readUserState(nextUserId).domainVerificationStatus, 18769 0, PackageManager.INSTALL_REASON_UNKNOWN, 18770 null /*harmfulAppWarning*/); 18771 } 18772 mSettings.writeKernelMappingLPr(ps); 18773 } 18774 18775 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18776 PackageRemovedInfo outInfo) { 18777 final PackageParser.Package pkg; 18778 synchronized (mPackages) { 18779 pkg = mPackages.get(ps.name); 18780 } 18781 18782 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18783 : new int[] {userId}; 18784 for (int nextUserId : userIds) { 18785 if (DEBUG_REMOVE) { 18786 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18787 + nextUserId); 18788 } 18789 18790 destroyAppDataLIF(pkg, userId, 18791 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18792 destroyAppProfilesLIF(pkg, userId); 18793 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18794 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18795 schedulePackageCleaning(ps.name, nextUserId, false); 18796 synchronized (mPackages) { 18797 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18798 scheduleWritePackageRestrictionsLocked(nextUserId); 18799 } 18800 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18801 } 18802 } 18803 18804 if (outInfo != null) { 18805 outInfo.removedPackage = ps.name; 18806 outInfo.installerPackageName = ps.installerPackageName; 18807 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18808 outInfo.removedAppId = ps.appId; 18809 outInfo.removedUsers = userIds; 18810 outInfo.broadcastUsers = userIds; 18811 } 18812 18813 return true; 18814 } 18815 18816 private static final class ClearStorageConnection implements ServiceConnection { 18817 IMediaContainerService mContainerService; 18818 18819 @Override 18820 public void onServiceConnected(ComponentName name, IBinder service) { 18821 synchronized (this) { 18822 mContainerService = IMediaContainerService.Stub 18823 .asInterface(Binder.allowBlocking(service)); 18824 notifyAll(); 18825 } 18826 } 18827 18828 @Override 18829 public void onServiceDisconnected(ComponentName name) { 18830 } 18831 } 18832 18833 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18834 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18835 18836 final boolean mounted; 18837 if (Environment.isExternalStorageEmulated()) { 18838 mounted = true; 18839 } else { 18840 final String status = Environment.getExternalStorageState(); 18841 18842 mounted = status.equals(Environment.MEDIA_MOUNTED) 18843 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18844 } 18845 18846 if (!mounted) { 18847 return; 18848 } 18849 18850 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18851 int[] users; 18852 if (userId == UserHandle.USER_ALL) { 18853 users = sUserManager.getUserIds(); 18854 } else { 18855 users = new int[] { userId }; 18856 } 18857 final ClearStorageConnection conn = new ClearStorageConnection(); 18858 if (mContext.bindServiceAsUser( 18859 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18860 try { 18861 for (int curUser : users) { 18862 long timeout = SystemClock.uptimeMillis() + 5000; 18863 synchronized (conn) { 18864 long now; 18865 while (conn.mContainerService == null && 18866 (now = SystemClock.uptimeMillis()) < timeout) { 18867 try { 18868 conn.wait(timeout - now); 18869 } catch (InterruptedException e) { 18870 } 18871 } 18872 } 18873 if (conn.mContainerService == null) { 18874 return; 18875 } 18876 18877 final UserEnvironment userEnv = new UserEnvironment(curUser); 18878 clearDirectory(conn.mContainerService, 18879 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18880 if (allData) { 18881 clearDirectory(conn.mContainerService, 18882 userEnv.buildExternalStorageAppDataDirs(packageName)); 18883 clearDirectory(conn.mContainerService, 18884 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18885 } 18886 } 18887 } finally { 18888 mContext.unbindService(conn); 18889 } 18890 } 18891 } 18892 18893 @Override 18894 public void clearApplicationProfileData(String packageName) { 18895 enforceSystemOrRoot("Only the system can clear all profile data"); 18896 18897 final PackageParser.Package pkg; 18898 synchronized (mPackages) { 18899 pkg = mPackages.get(packageName); 18900 } 18901 18902 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18903 synchronized (mInstallLock) { 18904 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18905 } 18906 } 18907 } 18908 18909 @Override 18910 public void clearApplicationUserData(final String packageName, 18911 final IPackageDataObserver observer, final int userId) { 18912 mContext.enforceCallingOrSelfPermission( 18913 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18914 18915 final int callingUid = Binder.getCallingUid(); 18916 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18917 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18918 18919 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18920 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18921 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18922 throw new SecurityException("Cannot clear data for a protected package: " 18923 + packageName); 18924 } 18925 // Queue up an async operation since the package deletion may take a little while. 18926 mHandler.post(new Runnable() { 18927 public void run() { 18928 mHandler.removeCallbacks(this); 18929 final boolean succeeded; 18930 if (!filterApp) { 18931 try (PackageFreezer freezer = freezePackage(packageName, 18932 "clearApplicationUserData")) { 18933 synchronized (mInstallLock) { 18934 succeeded = clearApplicationUserDataLIF(packageName, userId); 18935 } 18936 clearExternalStorageDataSync(packageName, userId, true); 18937 synchronized (mPackages) { 18938 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18939 packageName, userId); 18940 } 18941 } 18942 if (succeeded) { 18943 // invoke DeviceStorageMonitor's update method to clear any notifications 18944 DeviceStorageMonitorInternal dsm = LocalServices 18945 .getService(DeviceStorageMonitorInternal.class); 18946 if (dsm != null) { 18947 dsm.checkMemory(); 18948 } 18949 } 18950 } else { 18951 succeeded = false; 18952 } 18953 if (observer != null) { 18954 try { 18955 observer.onRemoveCompleted(packageName, succeeded); 18956 } catch (RemoteException e) { 18957 Log.i(TAG, "Observer no longer exists."); 18958 } 18959 } //end if observer 18960 } //end run 18961 }); 18962 } 18963 18964 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18965 if (packageName == null) { 18966 Slog.w(TAG, "Attempt to delete null packageName."); 18967 return false; 18968 } 18969 18970 // Try finding details about the requested package 18971 PackageParser.Package pkg; 18972 synchronized (mPackages) { 18973 pkg = mPackages.get(packageName); 18974 if (pkg == null) { 18975 final PackageSetting ps = mSettings.mPackages.get(packageName); 18976 if (ps != null) { 18977 pkg = ps.pkg; 18978 } 18979 } 18980 18981 if (pkg == null) { 18982 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18983 return false; 18984 } 18985 18986 PackageSetting ps = (PackageSetting) pkg.mExtras; 18987 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18988 } 18989 18990 clearAppDataLIF(pkg, userId, 18991 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18992 18993 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18994 removeKeystoreDataIfNeeded(userId, appId); 18995 18996 UserManagerInternal umInternal = getUserManagerInternal(); 18997 final int flags; 18998 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18999 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19000 } else if (umInternal.isUserRunning(userId)) { 19001 flags = StorageManager.FLAG_STORAGE_DE; 19002 } else { 19003 flags = 0; 19004 } 19005 prepareAppDataContentsLIF(pkg, userId, flags); 19006 19007 return true; 19008 } 19009 19010 /** 19011 * Reverts user permission state changes (permissions and flags) in 19012 * all packages for a given user. 19013 * 19014 * @param userId The device user for which to do a reset. 19015 */ 19016 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19017 final int packageCount = mPackages.size(); 19018 for (int i = 0; i < packageCount; i++) { 19019 PackageParser.Package pkg = mPackages.valueAt(i); 19020 PackageSetting ps = (PackageSetting) pkg.mExtras; 19021 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19022 } 19023 } 19024 19025 private void resetNetworkPolicies(int userId) { 19026 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19027 } 19028 19029 /** 19030 * Reverts user permission state changes (permissions and flags). 19031 * 19032 * @param ps The package for which to reset. 19033 * @param userId The device user for which to do a reset. 19034 */ 19035 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19036 final PackageSetting ps, final int userId) { 19037 if (ps.pkg == null) { 19038 return; 19039 } 19040 19041 // These are flags that can change base on user actions. 19042 final int userSettableMask = FLAG_PERMISSION_USER_SET 19043 | FLAG_PERMISSION_USER_FIXED 19044 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19045 | FLAG_PERMISSION_REVIEW_REQUIRED; 19046 19047 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19048 | FLAG_PERMISSION_POLICY_FIXED; 19049 19050 boolean writeInstallPermissions = false; 19051 boolean writeRuntimePermissions = false; 19052 19053 final int permissionCount = ps.pkg.requestedPermissions.size(); 19054 for (int i = 0; i < permissionCount; i++) { 19055 final String permName = ps.pkg.requestedPermissions.get(i); 19056 final BasePermission bp = 19057 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19058 if (bp == null) { 19059 continue; 19060 } 19061 19062 // If shared user we just reset the state to which only this app contributed. 19063 if (ps.sharedUser != null) { 19064 boolean used = false; 19065 final int packageCount = ps.sharedUser.packages.size(); 19066 for (int j = 0; j < packageCount; j++) { 19067 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19068 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19069 && pkg.pkg.requestedPermissions.contains(permName)) { 19070 used = true; 19071 break; 19072 } 19073 } 19074 if (used) { 19075 continue; 19076 } 19077 } 19078 19079 final PermissionsState permissionsState = ps.getPermissionsState(); 19080 19081 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 19082 19083 // Always clear the user settable flags. 19084 final boolean hasInstallState = 19085 permissionsState.getInstallPermissionState(permName) != null; 19086 // If permission review is enabled and this is a legacy app, mark the 19087 // permission as requiring a review as this is the initial state. 19088 int flags = 0; 19089 if (mSettings.mPermissions.mPermissionReviewRequired 19090 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 19091 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19092 } 19093 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19094 if (hasInstallState) { 19095 writeInstallPermissions = true; 19096 } else { 19097 writeRuntimePermissions = true; 19098 } 19099 } 19100 19101 // Below is only runtime permission handling. 19102 if (!bp.isRuntime()) { 19103 continue; 19104 } 19105 19106 // Never clobber system or policy. 19107 if ((oldFlags & policyOrSystemFlags) != 0) { 19108 continue; 19109 } 19110 19111 // If this permission was granted by default, make sure it is. 19112 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19113 if (permissionsState.grantRuntimePermission(bp, userId) 19114 != PERMISSION_OPERATION_FAILURE) { 19115 writeRuntimePermissions = true; 19116 } 19117 // If permission review is enabled the permissions for a legacy apps 19118 // are represented as constantly granted runtime ones, so don't revoke. 19119 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19120 // Otherwise, reset the permission. 19121 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19122 switch (revokeResult) { 19123 case PERMISSION_OPERATION_SUCCESS: 19124 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19125 writeRuntimePermissions = true; 19126 final int appId = ps.appId; 19127 mHandler.post(new Runnable() { 19128 @Override 19129 public void run() { 19130 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19131 } 19132 }); 19133 } break; 19134 } 19135 } 19136 } 19137 19138 // Synchronously write as we are taking permissions away. 19139 if (writeRuntimePermissions) { 19140 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19141 } 19142 19143 // Synchronously write as we are taking permissions away. 19144 if (writeInstallPermissions) { 19145 mSettings.writeLPr(); 19146 } 19147 } 19148 19149 /** 19150 * Remove entries from the keystore daemon. Will only remove it if the 19151 * {@code appId} is valid. 19152 */ 19153 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19154 if (appId < 0) { 19155 return; 19156 } 19157 19158 final KeyStore keyStore = KeyStore.getInstance(); 19159 if (keyStore != null) { 19160 if (userId == UserHandle.USER_ALL) { 19161 for (final int individual : sUserManager.getUserIds()) { 19162 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19163 } 19164 } else { 19165 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19166 } 19167 } else { 19168 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19169 } 19170 } 19171 19172 @Override 19173 public void deleteApplicationCacheFiles(final String packageName, 19174 final IPackageDataObserver observer) { 19175 final int userId = UserHandle.getCallingUserId(); 19176 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19177 } 19178 19179 @Override 19180 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19181 final IPackageDataObserver observer) { 19182 final int callingUid = Binder.getCallingUid(); 19183 if (mContext.checkCallingOrSelfPermission( 19184 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19185 != PackageManager.PERMISSION_GRANTED) { 19186 // If the caller has the old delete cache permission, silently ignore. Else throw. 19187 if (mContext.checkCallingOrSelfPermission( 19188 android.Manifest.permission.DELETE_CACHE_FILES) 19189 == PackageManager.PERMISSION_GRANTED) { 19190 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19191 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19192 ", silently ignoring"); 19193 return; 19194 } 19195 mContext.enforceCallingOrSelfPermission( 19196 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19197 } 19198 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19199 /* requireFullPermission= */ true, /* checkShell= */ false, 19200 "delete application cache files"); 19201 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19202 android.Manifest.permission.ACCESS_INSTANT_APPS); 19203 19204 final PackageParser.Package pkg; 19205 synchronized (mPackages) { 19206 pkg = mPackages.get(packageName); 19207 } 19208 19209 // Queue up an async operation since the package deletion may take a little while. 19210 mHandler.post(new Runnable() { 19211 public void run() { 19212 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19213 boolean doClearData = true; 19214 if (ps != null) { 19215 final boolean targetIsInstantApp = 19216 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19217 doClearData = !targetIsInstantApp 19218 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19219 } 19220 if (doClearData) { 19221 synchronized (mInstallLock) { 19222 final int flags = StorageManager.FLAG_STORAGE_DE 19223 | StorageManager.FLAG_STORAGE_CE; 19224 // We're only clearing cache files, so we don't care if the 19225 // app is unfrozen and still able to run 19226 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19227 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19228 } 19229 clearExternalStorageDataSync(packageName, userId, false); 19230 } 19231 if (observer != null) { 19232 try { 19233 observer.onRemoveCompleted(packageName, true); 19234 } catch (RemoteException e) { 19235 Log.i(TAG, "Observer no longer exists."); 19236 } 19237 } 19238 } 19239 }); 19240 } 19241 19242 @Override 19243 public void getPackageSizeInfo(final String packageName, int userHandle, 19244 final IPackageStatsObserver observer) { 19245 throw new UnsupportedOperationException( 19246 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19247 } 19248 19249 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19250 final PackageSetting ps; 19251 synchronized (mPackages) { 19252 ps = mSettings.mPackages.get(packageName); 19253 if (ps == null) { 19254 Slog.w(TAG, "Failed to find settings for " + packageName); 19255 return false; 19256 } 19257 } 19258 19259 final String[] packageNames = { packageName }; 19260 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19261 final String[] codePaths = { ps.codePathString }; 19262 19263 try { 19264 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19265 ps.appId, ceDataInodes, codePaths, stats); 19266 19267 // For now, ignore code size of packages on system partition 19268 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19269 stats.codeSize = 0; 19270 } 19271 19272 // External clients expect these to be tracked separately 19273 stats.dataSize -= stats.cacheSize; 19274 19275 } catch (InstallerException e) { 19276 Slog.w(TAG, String.valueOf(e)); 19277 return false; 19278 } 19279 19280 return true; 19281 } 19282 19283 private int getUidTargetSdkVersionLockedLPr(int uid) { 19284 Object obj = mSettings.getUserIdLPr(uid); 19285 if (obj instanceof SharedUserSetting) { 19286 final SharedUserSetting sus = (SharedUserSetting) obj; 19287 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19288 final Iterator<PackageSetting> it = sus.packages.iterator(); 19289 while (it.hasNext()) { 19290 final PackageSetting ps = it.next(); 19291 if (ps.pkg != null) { 19292 int v = ps.pkg.applicationInfo.targetSdkVersion; 19293 if (v < vers) vers = v; 19294 } 19295 } 19296 return vers; 19297 } else if (obj instanceof PackageSetting) { 19298 final PackageSetting ps = (PackageSetting) obj; 19299 if (ps.pkg != null) { 19300 return ps.pkg.applicationInfo.targetSdkVersion; 19301 } 19302 } 19303 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19304 } 19305 19306 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19307 final PackageParser.Package p = mPackages.get(packageName); 19308 if (p != null) { 19309 return p.applicationInfo.targetSdkVersion; 19310 } 19311 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19312 } 19313 19314 @Override 19315 public void addPreferredActivity(IntentFilter filter, int match, 19316 ComponentName[] set, ComponentName activity, int userId) { 19317 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19318 "Adding preferred"); 19319 } 19320 19321 private void addPreferredActivityInternal(IntentFilter filter, int match, 19322 ComponentName[] set, ComponentName activity, boolean always, int userId, 19323 String opname) { 19324 // writer 19325 int callingUid = Binder.getCallingUid(); 19326 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19327 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19328 if (filter.countActions() == 0) { 19329 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19330 return; 19331 } 19332 synchronized (mPackages) { 19333 if (mContext.checkCallingOrSelfPermission( 19334 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19335 != PackageManager.PERMISSION_GRANTED) { 19336 if (getUidTargetSdkVersionLockedLPr(callingUid) 19337 < Build.VERSION_CODES.FROYO) { 19338 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19339 + callingUid); 19340 return; 19341 } 19342 mContext.enforceCallingOrSelfPermission( 19343 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19344 } 19345 19346 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19347 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19348 + userId + ":"); 19349 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19350 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19351 scheduleWritePackageRestrictionsLocked(userId); 19352 postPreferredActivityChangedBroadcast(userId); 19353 } 19354 } 19355 19356 private void postPreferredActivityChangedBroadcast(int userId) { 19357 mHandler.post(() -> { 19358 final IActivityManager am = ActivityManager.getService(); 19359 if (am == null) { 19360 return; 19361 } 19362 19363 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19364 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19365 try { 19366 am.broadcastIntent(null, intent, null, null, 19367 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19368 null, false, false, userId); 19369 } catch (RemoteException e) { 19370 } 19371 }); 19372 } 19373 19374 @Override 19375 public void replacePreferredActivity(IntentFilter filter, int match, 19376 ComponentName[] set, ComponentName activity, int userId) { 19377 if (filter.countActions() != 1) { 19378 throw new IllegalArgumentException( 19379 "replacePreferredActivity expects filter to have only 1 action."); 19380 } 19381 if (filter.countDataAuthorities() != 0 19382 || filter.countDataPaths() != 0 19383 || filter.countDataSchemes() > 1 19384 || filter.countDataTypes() != 0) { 19385 throw new IllegalArgumentException( 19386 "replacePreferredActivity expects filter to have no data authorities, " + 19387 "paths, or types; and at most one scheme."); 19388 } 19389 19390 final int callingUid = Binder.getCallingUid(); 19391 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19392 true /* requireFullPermission */, false /* checkShell */, 19393 "replace preferred activity"); 19394 synchronized (mPackages) { 19395 if (mContext.checkCallingOrSelfPermission( 19396 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19397 != PackageManager.PERMISSION_GRANTED) { 19398 if (getUidTargetSdkVersionLockedLPr(callingUid) 19399 < Build.VERSION_CODES.FROYO) { 19400 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19401 + Binder.getCallingUid()); 19402 return; 19403 } 19404 mContext.enforceCallingOrSelfPermission( 19405 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19406 } 19407 19408 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19409 if (pir != null) { 19410 // Get all of the existing entries that exactly match this filter. 19411 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19412 if (existing != null && existing.size() == 1) { 19413 PreferredActivity cur = existing.get(0); 19414 if (DEBUG_PREFERRED) { 19415 Slog.i(TAG, "Checking replace of preferred:"); 19416 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19417 if (!cur.mPref.mAlways) { 19418 Slog.i(TAG, " -- CUR; not mAlways!"); 19419 } else { 19420 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19421 Slog.i(TAG, " -- CUR: mSet=" 19422 + Arrays.toString(cur.mPref.mSetComponents)); 19423 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19424 Slog.i(TAG, " -- NEW: mMatch=" 19425 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19426 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19427 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19428 } 19429 } 19430 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19431 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19432 && cur.mPref.sameSet(set)) { 19433 // Setting the preferred activity to what it happens to be already 19434 if (DEBUG_PREFERRED) { 19435 Slog.i(TAG, "Replacing with same preferred activity " 19436 + cur.mPref.mShortComponent + " for user " 19437 + userId + ":"); 19438 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19439 } 19440 return; 19441 } 19442 } 19443 19444 if (existing != null) { 19445 if (DEBUG_PREFERRED) { 19446 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19447 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19448 } 19449 for (int i = 0; i < existing.size(); i++) { 19450 PreferredActivity pa = existing.get(i); 19451 if (DEBUG_PREFERRED) { 19452 Slog.i(TAG, "Removing existing preferred activity " 19453 + pa.mPref.mComponent + ":"); 19454 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19455 } 19456 pir.removeFilter(pa); 19457 } 19458 } 19459 } 19460 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19461 "Replacing preferred"); 19462 } 19463 } 19464 19465 @Override 19466 public void clearPackagePreferredActivities(String packageName) { 19467 final int callingUid = Binder.getCallingUid(); 19468 if (getInstantAppPackageName(callingUid) != null) { 19469 return; 19470 } 19471 // writer 19472 synchronized (mPackages) { 19473 PackageParser.Package pkg = mPackages.get(packageName); 19474 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19475 if (mContext.checkCallingOrSelfPermission( 19476 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19477 != PackageManager.PERMISSION_GRANTED) { 19478 if (getUidTargetSdkVersionLockedLPr(callingUid) 19479 < Build.VERSION_CODES.FROYO) { 19480 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19481 + callingUid); 19482 return; 19483 } 19484 mContext.enforceCallingOrSelfPermission( 19485 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19486 } 19487 } 19488 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19489 if (ps != null 19490 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19491 return; 19492 } 19493 int user = UserHandle.getCallingUserId(); 19494 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19495 scheduleWritePackageRestrictionsLocked(user); 19496 } 19497 } 19498 } 19499 19500 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19501 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19502 ArrayList<PreferredActivity> removed = null; 19503 boolean changed = false; 19504 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19505 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19506 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19507 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19508 continue; 19509 } 19510 Iterator<PreferredActivity> it = pir.filterIterator(); 19511 while (it.hasNext()) { 19512 PreferredActivity pa = it.next(); 19513 // Mark entry for removal only if it matches the package name 19514 // and the entry is of type "always". 19515 if (packageName == null || 19516 (pa.mPref.mComponent.getPackageName().equals(packageName) 19517 && pa.mPref.mAlways)) { 19518 if (removed == null) { 19519 removed = new ArrayList<PreferredActivity>(); 19520 } 19521 removed.add(pa); 19522 } 19523 } 19524 if (removed != null) { 19525 for (int j=0; j<removed.size(); j++) { 19526 PreferredActivity pa = removed.get(j); 19527 pir.removeFilter(pa); 19528 } 19529 changed = true; 19530 } 19531 } 19532 if (changed) { 19533 postPreferredActivityChangedBroadcast(userId); 19534 } 19535 return changed; 19536 } 19537 19538 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19539 private void clearIntentFilterVerificationsLPw(int userId) { 19540 final int packageCount = mPackages.size(); 19541 for (int i = 0; i < packageCount; i++) { 19542 PackageParser.Package pkg = mPackages.valueAt(i); 19543 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19544 } 19545 } 19546 19547 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19548 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19549 if (userId == UserHandle.USER_ALL) { 19550 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19551 sUserManager.getUserIds())) { 19552 for (int oneUserId : sUserManager.getUserIds()) { 19553 scheduleWritePackageRestrictionsLocked(oneUserId); 19554 } 19555 } 19556 } else { 19557 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19558 scheduleWritePackageRestrictionsLocked(userId); 19559 } 19560 } 19561 } 19562 19563 /** Clears state for all users, and touches intent filter verification policy */ 19564 void clearDefaultBrowserIfNeeded(String packageName) { 19565 for (int oneUserId : sUserManager.getUserIds()) { 19566 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19567 } 19568 } 19569 19570 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19571 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19572 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19573 if (packageName.equals(defaultBrowserPackageName)) { 19574 setDefaultBrowserPackageName(null, userId); 19575 } 19576 } 19577 } 19578 19579 @Override 19580 public void resetApplicationPreferences(int userId) { 19581 mContext.enforceCallingOrSelfPermission( 19582 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19583 final long identity = Binder.clearCallingIdentity(); 19584 // writer 19585 try { 19586 synchronized (mPackages) { 19587 clearPackagePreferredActivitiesLPw(null, userId); 19588 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19589 // TODO: We have to reset the default SMS and Phone. This requires 19590 // significant refactoring to keep all default apps in the package 19591 // manager (cleaner but more work) or have the services provide 19592 // callbacks to the package manager to request a default app reset. 19593 applyFactoryDefaultBrowserLPw(userId); 19594 clearIntentFilterVerificationsLPw(userId); 19595 primeDomainVerificationsLPw(userId); 19596 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19597 scheduleWritePackageRestrictionsLocked(userId); 19598 } 19599 resetNetworkPolicies(userId); 19600 } finally { 19601 Binder.restoreCallingIdentity(identity); 19602 } 19603 } 19604 19605 @Override 19606 public int getPreferredActivities(List<IntentFilter> outFilters, 19607 List<ComponentName> outActivities, String packageName) { 19608 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19609 return 0; 19610 } 19611 int num = 0; 19612 final int userId = UserHandle.getCallingUserId(); 19613 // reader 19614 synchronized (mPackages) { 19615 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19616 if (pir != null) { 19617 final Iterator<PreferredActivity> it = pir.filterIterator(); 19618 while (it.hasNext()) { 19619 final PreferredActivity pa = it.next(); 19620 if (packageName == null 19621 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19622 && pa.mPref.mAlways)) { 19623 if (outFilters != null) { 19624 outFilters.add(new IntentFilter(pa)); 19625 } 19626 if (outActivities != null) { 19627 outActivities.add(pa.mPref.mComponent); 19628 } 19629 } 19630 } 19631 } 19632 } 19633 19634 return num; 19635 } 19636 19637 @Override 19638 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19639 int userId) { 19640 int callingUid = Binder.getCallingUid(); 19641 if (callingUid != Process.SYSTEM_UID) { 19642 throw new SecurityException( 19643 "addPersistentPreferredActivity can only be run by the system"); 19644 } 19645 if (filter.countActions() == 0) { 19646 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19647 return; 19648 } 19649 synchronized (mPackages) { 19650 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19651 ":"); 19652 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19653 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19654 new PersistentPreferredActivity(filter, activity)); 19655 scheduleWritePackageRestrictionsLocked(userId); 19656 postPreferredActivityChangedBroadcast(userId); 19657 } 19658 } 19659 19660 @Override 19661 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19662 int callingUid = Binder.getCallingUid(); 19663 if (callingUid != Process.SYSTEM_UID) { 19664 throw new SecurityException( 19665 "clearPackagePersistentPreferredActivities can only be run by the system"); 19666 } 19667 ArrayList<PersistentPreferredActivity> removed = null; 19668 boolean changed = false; 19669 synchronized (mPackages) { 19670 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19671 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19672 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19673 .valueAt(i); 19674 if (userId != thisUserId) { 19675 continue; 19676 } 19677 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19678 while (it.hasNext()) { 19679 PersistentPreferredActivity ppa = it.next(); 19680 // Mark entry for removal only if it matches the package name. 19681 if (ppa.mComponent.getPackageName().equals(packageName)) { 19682 if (removed == null) { 19683 removed = new ArrayList<PersistentPreferredActivity>(); 19684 } 19685 removed.add(ppa); 19686 } 19687 } 19688 if (removed != null) { 19689 for (int j=0; j<removed.size(); j++) { 19690 PersistentPreferredActivity ppa = removed.get(j); 19691 ppir.removeFilter(ppa); 19692 } 19693 changed = true; 19694 } 19695 } 19696 19697 if (changed) { 19698 scheduleWritePackageRestrictionsLocked(userId); 19699 postPreferredActivityChangedBroadcast(userId); 19700 } 19701 } 19702 } 19703 19704 /** 19705 * Common machinery for picking apart a restored XML blob and passing 19706 * it to a caller-supplied functor to be applied to the running system. 19707 */ 19708 private void restoreFromXml(XmlPullParser parser, int userId, 19709 String expectedStartTag, BlobXmlRestorer functor) 19710 throws IOException, XmlPullParserException { 19711 int type; 19712 while ((type = parser.next()) != XmlPullParser.START_TAG 19713 && type != XmlPullParser.END_DOCUMENT) { 19714 } 19715 if (type != XmlPullParser.START_TAG) { 19716 // oops didn't find a start tag?! 19717 if (DEBUG_BACKUP) { 19718 Slog.e(TAG, "Didn't find start tag during restore"); 19719 } 19720 return; 19721 } 19722Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19723 // this is supposed to be TAG_PREFERRED_BACKUP 19724 if (!expectedStartTag.equals(parser.getName())) { 19725 if (DEBUG_BACKUP) { 19726 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19727 } 19728 return; 19729 } 19730 19731 // skip interfering stuff, then we're aligned with the backing implementation 19732 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19733Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19734 functor.apply(parser, userId); 19735 } 19736 19737 private interface BlobXmlRestorer { 19738 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19739 } 19740 19741 /** 19742 * Non-Binder method, support for the backup/restore mechanism: write the 19743 * full set of preferred activities in its canonical XML format. Returns the 19744 * XML output as a byte array, or null if there is none. 19745 */ 19746 @Override 19747 public byte[] getPreferredActivityBackup(int userId) { 19748 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19749 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19750 } 19751 19752 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19753 try { 19754 final XmlSerializer serializer = new FastXmlSerializer(); 19755 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19756 serializer.startDocument(null, true); 19757 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19758 19759 synchronized (mPackages) { 19760 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19761 } 19762 19763 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19764 serializer.endDocument(); 19765 serializer.flush(); 19766 } catch (Exception e) { 19767 if (DEBUG_BACKUP) { 19768 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19769 } 19770 return null; 19771 } 19772 19773 return dataStream.toByteArray(); 19774 } 19775 19776 @Override 19777 public void restorePreferredActivities(byte[] backup, int userId) { 19778 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19779 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19780 } 19781 19782 try { 19783 final XmlPullParser parser = Xml.newPullParser(); 19784 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19785 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19786 new BlobXmlRestorer() { 19787 @Override 19788 public void apply(XmlPullParser parser, int userId) 19789 throws XmlPullParserException, IOException { 19790 synchronized (mPackages) { 19791 mSettings.readPreferredActivitiesLPw(parser, userId); 19792 } 19793 } 19794 } ); 19795 } catch (Exception e) { 19796 if (DEBUG_BACKUP) { 19797 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19798 } 19799 } 19800 } 19801 19802 /** 19803 * Non-Binder method, support for the backup/restore mechanism: write the 19804 * default browser (etc) settings in its canonical XML format. Returns the default 19805 * browser XML representation as a byte array, or null if there is none. 19806 */ 19807 @Override 19808 public byte[] getDefaultAppsBackup(int userId) { 19809 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19810 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19811 } 19812 19813 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19814 try { 19815 final XmlSerializer serializer = new FastXmlSerializer(); 19816 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19817 serializer.startDocument(null, true); 19818 serializer.startTag(null, TAG_DEFAULT_APPS); 19819 19820 synchronized (mPackages) { 19821 mSettings.writeDefaultAppsLPr(serializer, userId); 19822 } 19823 19824 serializer.endTag(null, TAG_DEFAULT_APPS); 19825 serializer.endDocument(); 19826 serializer.flush(); 19827 } catch (Exception e) { 19828 if (DEBUG_BACKUP) { 19829 Slog.e(TAG, "Unable to write default apps for backup", e); 19830 } 19831 return null; 19832 } 19833 19834 return dataStream.toByteArray(); 19835 } 19836 19837 @Override 19838 public void restoreDefaultApps(byte[] backup, int userId) { 19839 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19840 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19841 } 19842 19843 try { 19844 final XmlPullParser parser = Xml.newPullParser(); 19845 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19846 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19847 new BlobXmlRestorer() { 19848 @Override 19849 public void apply(XmlPullParser parser, int userId) 19850 throws XmlPullParserException, IOException { 19851 synchronized (mPackages) { 19852 mSettings.readDefaultAppsLPw(parser, userId); 19853 } 19854 } 19855 } ); 19856 } catch (Exception e) { 19857 if (DEBUG_BACKUP) { 19858 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19859 } 19860 } 19861 } 19862 19863 @Override 19864 public byte[] getIntentFilterVerificationBackup(int userId) { 19865 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19866 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19867 } 19868 19869 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19870 try { 19871 final XmlSerializer serializer = new FastXmlSerializer(); 19872 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19873 serializer.startDocument(null, true); 19874 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19875 19876 synchronized (mPackages) { 19877 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19878 } 19879 19880 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19881 serializer.endDocument(); 19882 serializer.flush(); 19883 } catch (Exception e) { 19884 if (DEBUG_BACKUP) { 19885 Slog.e(TAG, "Unable to write default apps for backup", e); 19886 } 19887 return null; 19888 } 19889 19890 return dataStream.toByteArray(); 19891 } 19892 19893 @Override 19894 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19895 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19896 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19897 } 19898 19899 try { 19900 final XmlPullParser parser = Xml.newPullParser(); 19901 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19902 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19903 new BlobXmlRestorer() { 19904 @Override 19905 public void apply(XmlPullParser parser, int userId) 19906 throws XmlPullParserException, IOException { 19907 synchronized (mPackages) { 19908 mSettings.readAllDomainVerificationsLPr(parser, userId); 19909 mSettings.writeLPr(); 19910 } 19911 } 19912 } ); 19913 } catch (Exception e) { 19914 if (DEBUG_BACKUP) { 19915 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19916 } 19917 } 19918 } 19919 19920 @Override 19921 public byte[] getPermissionGrantBackup(int userId) { 19922 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19923 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19924 } 19925 19926 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19927 try { 19928 final XmlSerializer serializer = new FastXmlSerializer(); 19929 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19930 serializer.startDocument(null, true); 19931 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19932 19933 synchronized (mPackages) { 19934 serializeRuntimePermissionGrantsLPr(serializer, userId); 19935 } 19936 19937 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19938 serializer.endDocument(); 19939 serializer.flush(); 19940 } catch (Exception e) { 19941 if (DEBUG_BACKUP) { 19942 Slog.e(TAG, "Unable to write default apps for backup", e); 19943 } 19944 return null; 19945 } 19946 19947 return dataStream.toByteArray(); 19948 } 19949 19950 @Override 19951 public void restorePermissionGrants(byte[] backup, int userId) { 19952 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19953 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19954 } 19955 19956 try { 19957 final XmlPullParser parser = Xml.newPullParser(); 19958 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19959 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19960 new BlobXmlRestorer() { 19961 @Override 19962 public void apply(XmlPullParser parser, int userId) 19963 throws XmlPullParserException, IOException { 19964 synchronized (mPackages) { 19965 processRestoredPermissionGrantsLPr(parser, userId); 19966 } 19967 } 19968 } ); 19969 } catch (Exception e) { 19970 if (DEBUG_BACKUP) { 19971 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19972 } 19973 } 19974 } 19975 19976 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19977 throws IOException { 19978 serializer.startTag(null, TAG_ALL_GRANTS); 19979 19980 final int N = mSettings.mPackages.size(); 19981 for (int i = 0; i < N; i++) { 19982 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19983 boolean pkgGrantsKnown = false; 19984 19985 PermissionsState packagePerms = ps.getPermissionsState(); 19986 19987 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19988 final int grantFlags = state.getFlags(); 19989 // only look at grants that are not system/policy fixed 19990 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19991 final boolean isGranted = state.isGranted(); 19992 // And only back up the user-twiddled state bits 19993 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19994 final String packageName = mSettings.mPackages.keyAt(i); 19995 if (!pkgGrantsKnown) { 19996 serializer.startTag(null, TAG_GRANT); 19997 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19998 pkgGrantsKnown = true; 19999 } 20000 20001 final boolean userSet = 20002 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 20003 final boolean userFixed = 20004 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 20005 final boolean revoke = 20006 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 20007 20008 serializer.startTag(null, TAG_PERMISSION); 20009 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 20010 if (isGranted) { 20011 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 20012 } 20013 if (userSet) { 20014 serializer.attribute(null, ATTR_USER_SET, "true"); 20015 } 20016 if (userFixed) { 20017 serializer.attribute(null, ATTR_USER_FIXED, "true"); 20018 } 20019 if (revoke) { 20020 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 20021 } 20022 serializer.endTag(null, TAG_PERMISSION); 20023 } 20024 } 20025 } 20026 20027 if (pkgGrantsKnown) { 20028 serializer.endTag(null, TAG_GRANT); 20029 } 20030 } 20031 20032 serializer.endTag(null, TAG_ALL_GRANTS); 20033 } 20034 20035 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 20036 throws XmlPullParserException, IOException { 20037 String pkgName = null; 20038 int outerDepth = parser.getDepth(); 20039 int type; 20040 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 20041 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 20042 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 20043 continue; 20044 } 20045 20046 final String tagName = parser.getName(); 20047 if (tagName.equals(TAG_GRANT)) { 20048 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 20049 if (DEBUG_BACKUP) { 20050 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 20051 } 20052 } else if (tagName.equals(TAG_PERMISSION)) { 20053 20054 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 20055 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 20056 20057 int newFlagSet = 0; 20058 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 20059 newFlagSet |= FLAG_PERMISSION_USER_SET; 20060 } 20061 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 20062 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 20063 } 20064 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 20065 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 20066 } 20067 if (DEBUG_BACKUP) { 20068 Slog.v(TAG, " + Restoring grant:" 20069 + " pkg=" + pkgName 20070 + " perm=" + permName 20071 + " granted=" + isGranted 20072 + " bits=0x" + Integer.toHexString(newFlagSet)); 20073 } 20074 final PackageSetting ps = mSettings.mPackages.get(pkgName); 20075 if (ps != null) { 20076 // Already installed so we apply the grant immediately 20077 if (DEBUG_BACKUP) { 20078 Slog.v(TAG, " + already installed; applying"); 20079 } 20080 PermissionsState perms = ps.getPermissionsState(); 20081 BasePermission bp = 20082 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 20083 if (bp != null) { 20084 if (isGranted) { 20085 perms.grantRuntimePermission(bp, userId); 20086 } 20087 if (newFlagSet != 0) { 20088 perms.updatePermissionFlags( 20089 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 20090 } 20091 } 20092 } else { 20093 // Need to wait for post-restore install to apply the grant 20094 if (DEBUG_BACKUP) { 20095 Slog.v(TAG, " - not yet installed; saving for later"); 20096 } 20097 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 20098 isGranted, newFlagSet, userId); 20099 } 20100 } else { 20101 PackageManagerService.reportSettingsProblem(Log.WARN, 20102 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 20103 XmlUtils.skipCurrentTag(parser); 20104 } 20105 } 20106 20107 scheduleWriteSettingsLocked(); 20108 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20109 } 20110 20111 @Override 20112 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20113 int sourceUserId, int targetUserId, int flags) { 20114 mContext.enforceCallingOrSelfPermission( 20115 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20116 int callingUid = Binder.getCallingUid(); 20117 enforceOwnerRights(ownerPackage, callingUid); 20118 PackageManagerServiceUtils.enforceShellRestriction( 20119 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20120 if (intentFilter.countActions() == 0) { 20121 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20122 return; 20123 } 20124 synchronized (mPackages) { 20125 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20126 ownerPackage, targetUserId, flags); 20127 CrossProfileIntentResolver resolver = 20128 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20129 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20130 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20131 if (existing != null) { 20132 int size = existing.size(); 20133 for (int i = 0; i < size; i++) { 20134 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20135 return; 20136 } 20137 } 20138 } 20139 resolver.addFilter(newFilter); 20140 scheduleWritePackageRestrictionsLocked(sourceUserId); 20141 } 20142 } 20143 20144 @Override 20145 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20146 mContext.enforceCallingOrSelfPermission( 20147 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20148 final int callingUid = Binder.getCallingUid(); 20149 enforceOwnerRights(ownerPackage, callingUid); 20150 PackageManagerServiceUtils.enforceShellRestriction( 20151 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20152 synchronized (mPackages) { 20153 CrossProfileIntentResolver resolver = 20154 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20155 ArraySet<CrossProfileIntentFilter> set = 20156 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20157 for (CrossProfileIntentFilter filter : set) { 20158 if (filter.getOwnerPackage().equals(ownerPackage)) { 20159 resolver.removeFilter(filter); 20160 } 20161 } 20162 scheduleWritePackageRestrictionsLocked(sourceUserId); 20163 } 20164 } 20165 20166 // Enforcing that callingUid is owning pkg on userId 20167 private void enforceOwnerRights(String pkg, int callingUid) { 20168 // The system owns everything. 20169 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20170 return; 20171 } 20172 final int callingUserId = UserHandle.getUserId(callingUid); 20173 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20174 if (pi == null) { 20175 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20176 + callingUserId); 20177 } 20178 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20179 throw new SecurityException("Calling uid " + callingUid 20180 + " does not own package " + pkg); 20181 } 20182 } 20183 20184 @Override 20185 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20186 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20187 return null; 20188 } 20189 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20190 } 20191 20192 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20193 UserManagerService ums = UserManagerService.getInstance(); 20194 if (ums != null) { 20195 final UserInfo parent = ums.getProfileParent(userId); 20196 final int launcherUid = (parent != null) ? parent.id : userId; 20197 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20198 if (launcherComponent != null) { 20199 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20200 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20201 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20202 .setPackage(launcherComponent.getPackageName()); 20203 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20204 } 20205 } 20206 } 20207 20208 /** 20209 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20210 * then reports the most likely home activity or null if there are more than one. 20211 */ 20212 private ComponentName getDefaultHomeActivity(int userId) { 20213 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20214 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20215 if (cn != null) { 20216 return cn; 20217 } 20218 20219 // Find the launcher with the highest priority and return that component if there are no 20220 // other home activity with the same priority. 20221 int lastPriority = Integer.MIN_VALUE; 20222 ComponentName lastComponent = null; 20223 final int size = allHomeCandidates.size(); 20224 for (int i = 0; i < size; i++) { 20225 final ResolveInfo ri = allHomeCandidates.get(i); 20226 if (ri.priority > lastPriority) { 20227 lastComponent = ri.activityInfo.getComponentName(); 20228 lastPriority = ri.priority; 20229 } else if (ri.priority == lastPriority) { 20230 // Two components found with same priority. 20231 lastComponent = null; 20232 } 20233 } 20234 return lastComponent; 20235 } 20236 20237 private Intent getHomeIntent() { 20238 Intent intent = new Intent(Intent.ACTION_MAIN); 20239 intent.addCategory(Intent.CATEGORY_HOME); 20240 intent.addCategory(Intent.CATEGORY_DEFAULT); 20241 return intent; 20242 } 20243 20244 private IntentFilter getHomeFilter() { 20245 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20246 filter.addCategory(Intent.CATEGORY_HOME); 20247 filter.addCategory(Intent.CATEGORY_DEFAULT); 20248 return filter; 20249 } 20250 20251 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20252 int userId) { 20253 Intent intent = getHomeIntent(); 20254 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20255 PackageManager.GET_META_DATA, userId); 20256 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20257 true, false, false, userId); 20258 20259 allHomeCandidates.clear(); 20260 if (list != null) { 20261 for (ResolveInfo ri : list) { 20262 allHomeCandidates.add(ri); 20263 } 20264 } 20265 return (preferred == null || preferred.activityInfo == null) 20266 ? null 20267 : new ComponentName(preferred.activityInfo.packageName, 20268 preferred.activityInfo.name); 20269 } 20270 20271 @Override 20272 public void setHomeActivity(ComponentName comp, int userId) { 20273 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20274 return; 20275 } 20276 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20277 getHomeActivitiesAsUser(homeActivities, userId); 20278 20279 boolean found = false; 20280 20281 final int size = homeActivities.size(); 20282 final ComponentName[] set = new ComponentName[size]; 20283 for (int i = 0; i < size; i++) { 20284 final ResolveInfo candidate = homeActivities.get(i); 20285 final ActivityInfo info = candidate.activityInfo; 20286 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20287 set[i] = activityName; 20288 if (!found && activityName.equals(comp)) { 20289 found = true; 20290 } 20291 } 20292 if (!found) { 20293 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20294 + userId); 20295 } 20296 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20297 set, comp, userId); 20298 } 20299 20300 private @Nullable String getSetupWizardPackageName() { 20301 final Intent intent = new Intent(Intent.ACTION_MAIN); 20302 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20303 20304 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20305 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20306 | MATCH_DISABLED_COMPONENTS, 20307 UserHandle.myUserId()); 20308 if (matches.size() == 1) { 20309 return matches.get(0).getComponentInfo().packageName; 20310 } else { 20311 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20312 + ": matches=" + matches); 20313 return null; 20314 } 20315 } 20316 20317 private @Nullable String getStorageManagerPackageName() { 20318 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20319 20320 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20321 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20322 | MATCH_DISABLED_COMPONENTS, 20323 UserHandle.myUserId()); 20324 if (matches.size() == 1) { 20325 return matches.get(0).getComponentInfo().packageName; 20326 } else { 20327 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20328 + matches.size() + ": matches=" + matches); 20329 return null; 20330 } 20331 } 20332 20333 @Override 20334 public String getSystemTextClassifierPackageName() { 20335 return mContext.getString(R.string.config_defaultTextClassifierPackage); 20336 } 20337 20338 @Override 20339 public void setApplicationEnabledSetting(String appPackageName, 20340 int newState, int flags, int userId, String callingPackage) { 20341 if (!sUserManager.exists(userId)) return; 20342 if (callingPackage == null) { 20343 callingPackage = Integer.toString(Binder.getCallingUid()); 20344 } 20345 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20346 } 20347 20348 @Override 20349 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20350 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20351 synchronized (mPackages) { 20352 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20353 if (pkgSetting != null) { 20354 pkgSetting.setUpdateAvailable(updateAvailable); 20355 } 20356 } 20357 } 20358 20359 @Override 20360 public void setComponentEnabledSetting(ComponentName componentName, 20361 int newState, int flags, int userId) { 20362 if (!sUserManager.exists(userId)) return; 20363 setEnabledSetting(componentName.getPackageName(), 20364 componentName.getClassName(), newState, flags, userId, null); 20365 } 20366 20367 private void setEnabledSetting(final String packageName, String className, int newState, 20368 final int flags, int userId, String callingPackage) { 20369 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20370 || newState == COMPONENT_ENABLED_STATE_ENABLED 20371 || newState == COMPONENT_ENABLED_STATE_DISABLED 20372 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20373 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20374 throw new IllegalArgumentException("Invalid new component state: " 20375 + newState); 20376 } 20377 PackageSetting pkgSetting; 20378 final int callingUid = Binder.getCallingUid(); 20379 final int permission; 20380 if (callingUid == Process.SYSTEM_UID) { 20381 permission = PackageManager.PERMISSION_GRANTED; 20382 } else { 20383 permission = mContext.checkCallingOrSelfPermission( 20384 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20385 } 20386 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20387 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20388 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20389 boolean sendNow = false; 20390 boolean isApp = (className == null); 20391 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20392 String componentName = isApp ? packageName : className; 20393 int packageUid = -1; 20394 ArrayList<String> components; 20395 20396 // reader 20397 synchronized (mPackages) { 20398 pkgSetting = mSettings.mPackages.get(packageName); 20399 if (pkgSetting == null) { 20400 if (!isCallerInstantApp) { 20401 if (className == null) { 20402 throw new IllegalArgumentException("Unknown package: " + packageName); 20403 } 20404 throw new IllegalArgumentException( 20405 "Unknown component: " + packageName + "/" + className); 20406 } else { 20407 // throw SecurityException to prevent leaking package information 20408 throw new SecurityException( 20409 "Attempt to change component state; " 20410 + "pid=" + Binder.getCallingPid() 20411 + ", uid=" + callingUid 20412 + (className == null 20413 ? ", package=" + packageName 20414 : ", component=" + packageName + "/" + className)); 20415 } 20416 } 20417 } 20418 20419 // Limit who can change which apps 20420 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20421 // Don't allow apps that don't have permission to modify other apps 20422 if (!allowedByPermission 20423 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20424 throw new SecurityException( 20425 "Attempt to change component state; " 20426 + "pid=" + Binder.getCallingPid() 20427 + ", uid=" + callingUid 20428 + (className == null 20429 ? ", package=" + packageName 20430 : ", component=" + packageName + "/" + className)); 20431 } 20432 // Don't allow changing protected packages. 20433 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20434 throw new SecurityException("Cannot disable a protected package: " + packageName); 20435 } 20436 } 20437 20438 synchronized (mPackages) { 20439 if (callingUid == Process.SHELL_UID 20440 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20441 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20442 // unless it is a test package. 20443 int oldState = pkgSetting.getEnabled(userId); 20444 if (className == null 20445 && 20446 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20447 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20448 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20449 && 20450 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20451 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20452 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20453 // ok 20454 } else { 20455 throw new SecurityException( 20456 "Shell cannot change component state for " + packageName + "/" 20457 + className + " to " + newState); 20458 } 20459 } 20460 } 20461 if (className == null) { 20462 // We're dealing with an application/package level state change 20463 synchronized (mPackages) { 20464 if (pkgSetting.getEnabled(userId) == newState) { 20465 // Nothing to do 20466 return; 20467 } 20468 } 20469 // If we're enabling a system stub, there's a little more work to do. 20470 // Prior to enabling the package, we need to decompress the APK(s) to the 20471 // data partition and then replace the version on the system partition. 20472 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20473 final boolean isSystemStub = deletedPkg.isStub 20474 && deletedPkg.isSystem(); 20475 if (isSystemStub 20476 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20477 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20478 final File codePath = decompressPackage(deletedPkg); 20479 if (codePath == null) { 20480 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20481 return; 20482 } 20483 // TODO remove direct parsing of the package object during internal cleanup 20484 // of scan package 20485 // We need to call parse directly here for no other reason than we need 20486 // the new package in order to disable the old one [we use the information 20487 // for some internal optimization to optionally create a new package setting 20488 // object on replace]. However, we can't get the package from the scan 20489 // because the scan modifies live structures and we need to remove the 20490 // old [system] package from the system before a scan can be attempted. 20491 // Once scan is indempotent we can remove this parse and use the package 20492 // object we scanned, prior to adding it to package settings. 20493 final PackageParser pp = new PackageParser(); 20494 pp.setSeparateProcesses(mSeparateProcesses); 20495 pp.setDisplayMetrics(mMetrics); 20496 pp.setCallback(mPackageParserCallback); 20497 final PackageParser.Package tmpPkg; 20498 try { 20499 final @ParseFlags int parseFlags = mDefParseFlags 20500 | PackageParser.PARSE_MUST_BE_APK 20501 | PackageParser.PARSE_IS_SYSTEM_DIR; 20502 tmpPkg = pp.parsePackage(codePath, parseFlags); 20503 } catch (PackageParserException e) { 20504 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20505 return; 20506 } 20507 synchronized (mInstallLock) { 20508 // Disable the stub and remove any package entries 20509 removePackageLI(deletedPkg, true); 20510 synchronized (mPackages) { 20511 disableSystemPackageLPw(deletedPkg, tmpPkg); 20512 } 20513 final PackageParser.Package pkg; 20514 try (PackageFreezer freezer = 20515 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20516 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20517 | PackageParser.PARSE_ENFORCE_CODE; 20518 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20519 0 /*currentTime*/, null /*user*/); 20520 prepareAppDataAfterInstallLIF(pkg); 20521 synchronized (mPackages) { 20522 try { 20523 updateSharedLibrariesLPr(pkg, null); 20524 } catch (PackageManagerException e) { 20525 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20526 } 20527 mPermissionManager.updatePermissions( 20528 pkg.packageName, pkg, true, mPackages.values(), 20529 mPermissionCallback); 20530 mSettings.writeLPr(); 20531 } 20532 } catch (PackageManagerException e) { 20533 // Whoops! Something went wrong; try to roll back to the stub 20534 Slog.w(TAG, "Failed to install compressed system package:" 20535 + pkgSetting.name, e); 20536 // Remove the failed install 20537 removeCodePathLI(codePath); 20538 20539 // Install the system package 20540 try (PackageFreezer freezer = 20541 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20542 synchronized (mPackages) { 20543 // NOTE: The system package always needs to be enabled; even 20544 // if it's for a compressed stub. If we don't, installing the 20545 // system package fails during scan [scanning checks the disabled 20546 // packages]. We will reverse this later, after we've "installed" 20547 // the stub. 20548 // This leaves us in a fragile state; the stub should never be 20549 // enabled, so, cross your fingers and hope nothing goes wrong 20550 // until we can disable the package later. 20551 enableSystemPackageLPw(deletedPkg); 20552 } 20553 installPackageFromSystemLIF(deletedPkg.codePath, 20554 false /*isPrivileged*/, null /*allUserHandles*/, 20555 null /*origUserHandles*/, null /*origPermissionsState*/, 20556 true /*writeSettings*/); 20557 } catch (PackageManagerException pme) { 20558 Slog.w(TAG, "Failed to restore system package:" 20559 + deletedPkg.packageName, pme); 20560 } finally { 20561 synchronized (mPackages) { 20562 mSettings.disableSystemPackageLPw( 20563 deletedPkg.packageName, true /*replaced*/); 20564 mSettings.writeLPr(); 20565 } 20566 } 20567 return; 20568 } 20569 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20570 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20571 mDexManager.notifyPackageUpdated(pkg.packageName, 20572 pkg.baseCodePath, pkg.splitCodePaths); 20573 } 20574 } 20575 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20576 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20577 // Don't care about who enables an app. 20578 callingPackage = null; 20579 } 20580 synchronized (mPackages) { 20581 pkgSetting.setEnabled(newState, userId, callingPackage); 20582 } 20583 } else { 20584 synchronized (mPackages) { 20585 // We're dealing with a component level state change 20586 // First, verify that this is a valid class name. 20587 PackageParser.Package pkg = pkgSetting.pkg; 20588 if (pkg == null || !pkg.hasComponentClassName(className)) { 20589 if (pkg != null && 20590 pkg.applicationInfo.targetSdkVersion >= 20591 Build.VERSION_CODES.JELLY_BEAN) { 20592 throw new IllegalArgumentException("Component class " + className 20593 + " does not exist in " + packageName); 20594 } else { 20595 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20596 + className + " does not exist in " + packageName); 20597 } 20598 } 20599 switch (newState) { 20600 case COMPONENT_ENABLED_STATE_ENABLED: 20601 if (!pkgSetting.enableComponentLPw(className, userId)) { 20602 return; 20603 } 20604 break; 20605 case COMPONENT_ENABLED_STATE_DISABLED: 20606 if (!pkgSetting.disableComponentLPw(className, userId)) { 20607 return; 20608 } 20609 break; 20610 case COMPONENT_ENABLED_STATE_DEFAULT: 20611 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20612 return; 20613 } 20614 break; 20615 default: 20616 Slog.e(TAG, "Invalid new component state: " + newState); 20617 return; 20618 } 20619 } 20620 } 20621 synchronized (mPackages) { 20622 scheduleWritePackageRestrictionsLocked(userId); 20623 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20624 final long callingId = Binder.clearCallingIdentity(); 20625 try { 20626 updateInstantAppInstallerLocked(packageName); 20627 } finally { 20628 Binder.restoreCallingIdentity(callingId); 20629 } 20630 components = mPendingBroadcasts.get(userId, packageName); 20631 final boolean newPackage = components == null; 20632 if (newPackage) { 20633 components = new ArrayList<String>(); 20634 } 20635 if (!components.contains(componentName)) { 20636 components.add(componentName); 20637 } 20638 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20639 sendNow = true; 20640 // Purge entry from pending broadcast list if another one exists already 20641 // since we are sending one right away. 20642 mPendingBroadcasts.remove(userId, packageName); 20643 } else { 20644 if (newPackage) { 20645 mPendingBroadcasts.put(userId, packageName, components); 20646 } 20647 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20648 // Schedule a message 20649 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20650 } 20651 } 20652 } 20653 20654 long callingId = Binder.clearCallingIdentity(); 20655 try { 20656 if (sendNow) { 20657 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20658 sendPackageChangedBroadcast(packageName, 20659 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20660 } 20661 } finally { 20662 Binder.restoreCallingIdentity(callingId); 20663 } 20664 } 20665 20666 @Override 20667 public void flushPackageRestrictionsAsUser(int userId) { 20668 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20669 return; 20670 } 20671 if (!sUserManager.exists(userId)) { 20672 return; 20673 } 20674 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20675 false /* checkShell */, "flushPackageRestrictions"); 20676 synchronized (mPackages) { 20677 mSettings.writePackageRestrictionsLPr(userId); 20678 mDirtyUsers.remove(userId); 20679 if (mDirtyUsers.isEmpty()) { 20680 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20681 } 20682 } 20683 } 20684 20685 private void sendPackageChangedBroadcast(String packageName, 20686 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20687 if (DEBUG_INSTALL) 20688 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20689 + componentNames); 20690 Bundle extras = new Bundle(4); 20691 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20692 String nameList[] = new String[componentNames.size()]; 20693 componentNames.toArray(nameList); 20694 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20695 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20696 extras.putInt(Intent.EXTRA_UID, packageUid); 20697 // If this is not reporting a change of the overall package, then only send it 20698 // to registered receivers. We don't want to launch a swath of apps for every 20699 // little component state change. 20700 final int flags = !componentNames.contains(packageName) 20701 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20702 final int userId = UserHandle.getUserId(packageUid); 20703 final boolean isInstantApp = isInstantApp(packageName, userId); 20704 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20705 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20706 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20707 userIds, instantUserIds); 20708 } 20709 20710 @Override 20711 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20712 if (!sUserManager.exists(userId)) return; 20713 final int callingUid = Binder.getCallingUid(); 20714 if (getInstantAppPackageName(callingUid) != null) { 20715 return; 20716 } 20717 final int permission = mContext.checkCallingOrSelfPermission( 20718 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20719 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20720 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20721 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20722 // writer 20723 synchronized (mPackages) { 20724 final PackageSetting ps = mSettings.mPackages.get(packageName); 20725 if (!filterAppAccessLPr(ps, callingUid, userId) 20726 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20727 allowedByPermission, callingUid, userId)) { 20728 scheduleWritePackageRestrictionsLocked(userId); 20729 } 20730 } 20731 } 20732 20733 @Override 20734 public String getInstallerPackageName(String packageName) { 20735 final int callingUid = Binder.getCallingUid(); 20736 synchronized (mPackages) { 20737 final PackageSetting ps = mSettings.mPackages.get(packageName); 20738 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20739 return null; 20740 } 20741 return mSettings.getInstallerPackageNameLPr(packageName); 20742 } 20743 } 20744 20745 public boolean isOrphaned(String packageName) { 20746 // reader 20747 synchronized (mPackages) { 20748 return mSettings.isOrphaned(packageName); 20749 } 20750 } 20751 20752 @Override 20753 public int getApplicationEnabledSetting(String packageName, int userId) { 20754 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20755 int callingUid = Binder.getCallingUid(); 20756 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20757 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20758 // reader 20759 synchronized (mPackages) { 20760 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20761 return COMPONENT_ENABLED_STATE_DISABLED; 20762 } 20763 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20764 } 20765 } 20766 20767 @Override 20768 public int getComponentEnabledSetting(ComponentName component, int userId) { 20769 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20770 int callingUid = Binder.getCallingUid(); 20771 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20772 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20773 synchronized (mPackages) { 20774 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20775 component, TYPE_UNKNOWN, userId)) { 20776 return COMPONENT_ENABLED_STATE_DISABLED; 20777 } 20778 return mSettings.getComponentEnabledSettingLPr(component, userId); 20779 } 20780 } 20781 20782 @Override 20783 public void enterSafeMode() { 20784 enforceSystemOrRoot("Only the system can request entering safe mode"); 20785 20786 if (!mSystemReady) { 20787 mSafeMode = true; 20788 } 20789 } 20790 20791 @Override 20792 public void systemReady() { 20793 enforceSystemOrRoot("Only the system can claim the system is ready"); 20794 20795 mSystemReady = true; 20796 final ContentResolver resolver = mContext.getContentResolver(); 20797 ContentObserver co = new ContentObserver(mHandler) { 20798 @Override 20799 public void onChange(boolean selfChange) { 20800 mWebInstantAppsDisabled = 20801 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20802 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20803 } 20804 }; 20805 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20806 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20807 false, co, UserHandle.USER_SYSTEM); 20808 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 20809 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20810 co.onChange(true); 20811 20812 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20813 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20814 // it is done. 20815 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20816 @Override 20817 public void onChange(boolean selfChange) { 20818 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20819 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20820 oobEnabled == 1 ? "true" : "false"); 20821 } 20822 }; 20823 mContext.getContentResolver().registerContentObserver( 20824 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20825 UserHandle.USER_SYSTEM); 20826 // At boot, restore the value from the setting, which persists across reboot. 20827 privAppOobObserver.onChange(true); 20828 20829 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20830 // disabled after already being started. 20831 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20832 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20833 20834 // Read the compatibilty setting when the system is ready. 20835 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20836 mContext.getContentResolver(), 20837 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20838 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20839 if (DEBUG_SETTINGS) { 20840 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20841 } 20842 20843 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20844 20845 synchronized (mPackages) { 20846 // Verify that all of the preferred activity components actually 20847 // exist. It is possible for applications to be updated and at 20848 // that point remove a previously declared activity component that 20849 // had been set as a preferred activity. We try to clean this up 20850 // the next time we encounter that preferred activity, but it is 20851 // possible for the user flow to never be able to return to that 20852 // situation so here we do a sanity check to make sure we haven't 20853 // left any junk around. 20854 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20855 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20856 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20857 removed.clear(); 20858 for (PreferredActivity pa : pir.filterSet()) { 20859 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20860 removed.add(pa); 20861 } 20862 } 20863 if (removed.size() > 0) { 20864 for (int r=0; r<removed.size(); r++) { 20865 PreferredActivity pa = removed.get(r); 20866 Slog.w(TAG, "Removing dangling preferred activity: " 20867 + pa.mPref.mComponent); 20868 pir.removeFilter(pa); 20869 } 20870 mSettings.writePackageRestrictionsLPr( 20871 mSettings.mPreferredActivities.keyAt(i)); 20872 } 20873 } 20874 20875 for (int userId : UserManagerService.getInstance().getUserIds()) { 20876 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20877 grantPermissionsUserIds = ArrayUtils.appendInt( 20878 grantPermissionsUserIds, userId); 20879 } 20880 } 20881 } 20882 sUserManager.systemReady(); 20883 // If we upgraded grant all default permissions before kicking off. 20884 for (int userId : grantPermissionsUserIds) { 20885 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20886 } 20887 20888 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20889 // If we did not grant default permissions, we preload from this the 20890 // default permission exceptions lazily to ensure we don't hit the 20891 // disk on a new user creation. 20892 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20893 } 20894 20895 // Now that we've scanned all packages, and granted any default 20896 // permissions, ensure permissions are updated. Beware of dragons if you 20897 // try optimizing this. 20898 synchronized (mPackages) { 20899 mPermissionManager.updateAllPermissions( 20900 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20901 mPermissionCallback); 20902 } 20903 20904 // Kick off any messages waiting for system ready 20905 if (mPostSystemReadyMessages != null) { 20906 for (Message msg : mPostSystemReadyMessages) { 20907 msg.sendToTarget(); 20908 } 20909 mPostSystemReadyMessages = null; 20910 } 20911 20912 // Watch for external volumes that come and go over time 20913 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20914 storage.registerListener(mStorageListener); 20915 20916 mInstallerService.systemReady(); 20917 mPackageDexOptimizer.systemReady(); 20918 20919 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20920 StorageManagerInternal.class); 20921 StorageManagerInternal.addExternalStoragePolicy( 20922 new StorageManagerInternal.ExternalStorageMountPolicy() { 20923 @Override 20924 public int getMountMode(int uid, String packageName) { 20925 if (Process.isIsolated(uid)) { 20926 return Zygote.MOUNT_EXTERNAL_NONE; 20927 } 20928 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20929 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20930 } 20931 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20932 return Zygote.MOUNT_EXTERNAL_READ; 20933 } 20934 return Zygote.MOUNT_EXTERNAL_WRITE; 20935 } 20936 20937 @Override 20938 public boolean hasExternalStorage(int uid, String packageName) { 20939 return true; 20940 } 20941 }); 20942 20943 // Now that we're mostly running, clean up stale users and apps 20944 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20945 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20946 20947 mPermissionManager.systemReady(); 20948 20949 if (mInstantAppResolverConnection != null) { 20950 mContext.registerReceiver(new BroadcastReceiver() { 20951 @Override 20952 public void onReceive(Context context, Intent intent) { 20953 mInstantAppResolverConnection.optimisticBind(); 20954 mContext.unregisterReceiver(this); 20955 } 20956 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 20957 } 20958 } 20959 20960 public void waitForAppDataPrepared() { 20961 if (mPrepareAppDataFuture == null) { 20962 return; 20963 } 20964 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20965 mPrepareAppDataFuture = null; 20966 } 20967 20968 @Override 20969 public boolean isSafeMode() { 20970 // allow instant applications 20971 return mSafeMode; 20972 } 20973 20974 @Override 20975 public boolean hasSystemUidErrors() { 20976 // allow instant applications 20977 return mHasSystemUidErrors; 20978 } 20979 20980 static String arrayToString(int[] array) { 20981 StringBuffer buf = new StringBuffer(128); 20982 buf.append('['); 20983 if (array != null) { 20984 for (int i=0; i<array.length; i++) { 20985 if (i > 0) buf.append(", "); 20986 buf.append(array[i]); 20987 } 20988 } 20989 buf.append(']'); 20990 return buf.toString(); 20991 } 20992 20993 @Override 20994 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20995 FileDescriptor err, String[] args, ShellCallback callback, 20996 ResultReceiver resultReceiver) { 20997 (new PackageManagerShellCommand(this)).exec( 20998 this, in, out, err, args, callback, resultReceiver); 20999 } 21000 21001 @Override 21002 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21003 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21004 21005 DumpState dumpState = new DumpState(); 21006 boolean fullPreferred = false; 21007 boolean checkin = false; 21008 21009 String packageName = null; 21010 ArraySet<String> permissionNames = null; 21011 21012 int opti = 0; 21013 while (opti < args.length) { 21014 String opt = args[opti]; 21015 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21016 break; 21017 } 21018 opti++; 21019 21020 if ("-a".equals(opt)) { 21021 // Right now we only know how to print all. 21022 } else if ("-h".equals(opt)) { 21023 pw.println("Package manager dump options:"); 21024 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 21025 pw.println(" --checkin: dump for a checkin"); 21026 pw.println(" -f: print details of intent filters"); 21027 pw.println(" -h: print this help"); 21028 pw.println(" cmd may be one of:"); 21029 pw.println(" l[ibraries]: list known shared libraries"); 21030 pw.println(" f[eatures]: list device features"); 21031 pw.println(" k[eysets]: print known keysets"); 21032 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21033 pw.println(" perm[issions]: dump permissions"); 21034 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21035 pw.println(" pref[erred]: print preferred package settings"); 21036 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21037 pw.println(" prov[iders]: dump content providers"); 21038 pw.println(" p[ackages]: dump installed packages"); 21039 pw.println(" s[hared-users]: dump shared user IDs"); 21040 pw.println(" m[essages]: print collected runtime messages"); 21041 pw.println(" v[erifiers]: print package verifier info"); 21042 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21043 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21044 pw.println(" version: print database version info"); 21045 pw.println(" write: write current settings now"); 21046 pw.println(" installs: details about install sessions"); 21047 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21048 pw.println(" dexopt: dump dexopt state"); 21049 pw.println(" compiler-stats: dump compiler statistics"); 21050 pw.println(" service-permissions: dump permissions required by services"); 21051 pw.println(" <package.name>: info about given package"); 21052 return; 21053 } else if ("--checkin".equals(opt)) { 21054 checkin = true; 21055 } else if ("-f".equals(opt)) { 21056 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21057 } else if ("--proto".equals(opt)) { 21058 dumpProto(fd); 21059 return; 21060 } else { 21061 pw.println("Unknown argument: " + opt + "; use -h for help"); 21062 } 21063 } 21064 21065 // Is the caller requesting to dump a particular piece of data? 21066 if (opti < args.length) { 21067 String cmd = args[opti]; 21068 opti++; 21069 // Is this a package name? 21070 if ("android".equals(cmd) || cmd.contains(".")) { 21071 packageName = cmd; 21072 // When dumping a single package, we always dump all of its 21073 // filter information since the amount of data will be reasonable. 21074 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21075 } else if ("check-permission".equals(cmd)) { 21076 if (opti >= args.length) { 21077 pw.println("Error: check-permission missing permission argument"); 21078 return; 21079 } 21080 String perm = args[opti]; 21081 opti++; 21082 if (opti >= args.length) { 21083 pw.println("Error: check-permission missing package argument"); 21084 return; 21085 } 21086 21087 String pkg = args[opti]; 21088 opti++; 21089 int user = UserHandle.getUserId(Binder.getCallingUid()); 21090 if (opti < args.length) { 21091 try { 21092 user = Integer.parseInt(args[opti]); 21093 } catch (NumberFormatException e) { 21094 pw.println("Error: check-permission user argument is not a number: " 21095 + args[opti]); 21096 return; 21097 } 21098 } 21099 21100 // Normalize package name to handle renamed packages and static libs 21101 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21102 21103 pw.println(checkPermission(perm, pkg, user)); 21104 return; 21105 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21106 dumpState.setDump(DumpState.DUMP_LIBS); 21107 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21108 dumpState.setDump(DumpState.DUMP_FEATURES); 21109 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21110 if (opti >= args.length) { 21111 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21112 | DumpState.DUMP_SERVICE_RESOLVERS 21113 | DumpState.DUMP_RECEIVER_RESOLVERS 21114 | DumpState.DUMP_CONTENT_RESOLVERS); 21115 } else { 21116 while (opti < args.length) { 21117 String name = args[opti]; 21118 if ("a".equals(name) || "activity".equals(name)) { 21119 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21120 } else if ("s".equals(name) || "service".equals(name)) { 21121 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21122 } else if ("r".equals(name) || "receiver".equals(name)) { 21123 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21124 } else if ("c".equals(name) || "content".equals(name)) { 21125 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21126 } else { 21127 pw.println("Error: unknown resolver table type: " + name); 21128 return; 21129 } 21130 opti++; 21131 } 21132 } 21133 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21134 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21135 } else if ("permission".equals(cmd)) { 21136 if (opti >= args.length) { 21137 pw.println("Error: permission requires permission name"); 21138 return; 21139 } 21140 permissionNames = new ArraySet<>(); 21141 while (opti < args.length) { 21142 permissionNames.add(args[opti]); 21143 opti++; 21144 } 21145 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21146 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21147 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21148 dumpState.setDump(DumpState.DUMP_PREFERRED); 21149 } else if ("preferred-xml".equals(cmd)) { 21150 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21151 if (opti < args.length && "--full".equals(args[opti])) { 21152 fullPreferred = true; 21153 opti++; 21154 } 21155 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21156 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21157 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21158 dumpState.setDump(DumpState.DUMP_PACKAGES); 21159 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21160 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21161 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21162 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21163 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21164 dumpState.setDump(DumpState.DUMP_MESSAGES); 21165 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21166 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21167 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21168 || "intent-filter-verifiers".equals(cmd)) { 21169 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21170 } else if ("version".equals(cmd)) { 21171 dumpState.setDump(DumpState.DUMP_VERSION); 21172 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21173 dumpState.setDump(DumpState.DUMP_KEYSETS); 21174 } else if ("installs".equals(cmd)) { 21175 dumpState.setDump(DumpState.DUMP_INSTALLS); 21176 } else if ("frozen".equals(cmd)) { 21177 dumpState.setDump(DumpState.DUMP_FROZEN); 21178 } else if ("volumes".equals(cmd)) { 21179 dumpState.setDump(DumpState.DUMP_VOLUMES); 21180 } else if ("dexopt".equals(cmd)) { 21181 dumpState.setDump(DumpState.DUMP_DEXOPT); 21182 } else if ("compiler-stats".equals(cmd)) { 21183 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21184 } else if ("changes".equals(cmd)) { 21185 dumpState.setDump(DumpState.DUMP_CHANGES); 21186 } else if ("service-permissions".equals(cmd)) { 21187 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21188 } else if ("write".equals(cmd)) { 21189 synchronized (mPackages) { 21190 mSettings.writeLPr(); 21191 pw.println("Settings written."); 21192 return; 21193 } 21194 } 21195 } 21196 21197 if (checkin) { 21198 pw.println("vers,1"); 21199 } 21200 21201 // reader 21202 synchronized (mPackages) { 21203 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21204 if (!checkin) { 21205 if (dumpState.onTitlePrinted()) 21206 pw.println(); 21207 pw.println("Database versions:"); 21208 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21209 } 21210 } 21211 21212 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21213 if (!checkin) { 21214 if (dumpState.onTitlePrinted()) 21215 pw.println(); 21216 pw.println("Verifiers:"); 21217 pw.print(" Required: "); 21218 pw.print(mRequiredVerifierPackage); 21219 pw.print(" (uid="); 21220 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21221 UserHandle.USER_SYSTEM)); 21222 pw.println(")"); 21223 } else if (mRequiredVerifierPackage != null) { 21224 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21225 pw.print(","); 21226 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21227 UserHandle.USER_SYSTEM)); 21228 } 21229 } 21230 21231 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21232 packageName == null) { 21233 if (mIntentFilterVerifierComponent != null) { 21234 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21235 if (!checkin) { 21236 if (dumpState.onTitlePrinted()) 21237 pw.println(); 21238 pw.println("Intent Filter Verifier:"); 21239 pw.print(" Using: "); 21240 pw.print(verifierPackageName); 21241 pw.print(" (uid="); 21242 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21243 UserHandle.USER_SYSTEM)); 21244 pw.println(")"); 21245 } else if (verifierPackageName != null) { 21246 pw.print("ifv,"); pw.print(verifierPackageName); 21247 pw.print(","); 21248 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21249 UserHandle.USER_SYSTEM)); 21250 } 21251 } else { 21252 pw.println(); 21253 pw.println("No Intent Filter Verifier available!"); 21254 } 21255 } 21256 21257 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21258 boolean printedHeader = false; 21259 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21260 while (it.hasNext()) { 21261 String libName = it.next(); 21262 LongSparseArray<SharedLibraryEntry> versionedLib 21263 = mSharedLibraries.get(libName); 21264 if (versionedLib == null) { 21265 continue; 21266 } 21267 final int versionCount = versionedLib.size(); 21268 for (int i = 0; i < versionCount; i++) { 21269 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21270 if (!checkin) { 21271 if (!printedHeader) { 21272 if (dumpState.onTitlePrinted()) 21273 pw.println(); 21274 pw.println("Libraries:"); 21275 printedHeader = true; 21276 } 21277 pw.print(" "); 21278 } else { 21279 pw.print("lib,"); 21280 } 21281 pw.print(libEntry.info.getName()); 21282 if (libEntry.info.isStatic()) { 21283 pw.print(" version=" + libEntry.info.getLongVersion()); 21284 } 21285 if (!checkin) { 21286 pw.print(" -> "); 21287 } 21288 if (libEntry.path != null) { 21289 pw.print(" (jar) "); 21290 pw.print(libEntry.path); 21291 } else { 21292 pw.print(" (apk) "); 21293 pw.print(libEntry.apk); 21294 } 21295 pw.println(); 21296 } 21297 } 21298 } 21299 21300 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21301 if (dumpState.onTitlePrinted()) 21302 pw.println(); 21303 if (!checkin) { 21304 pw.println("Features:"); 21305 } 21306 21307 synchronized (mAvailableFeatures) { 21308 for (FeatureInfo feat : mAvailableFeatures.values()) { 21309 if (checkin) { 21310 pw.print("feat,"); 21311 pw.print(feat.name); 21312 pw.print(","); 21313 pw.println(feat.version); 21314 } else { 21315 pw.print(" "); 21316 pw.print(feat.name); 21317 if (feat.version > 0) { 21318 pw.print(" version="); 21319 pw.print(feat.version); 21320 } 21321 pw.println(); 21322 } 21323 } 21324 } 21325 } 21326 21327 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21328 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21329 : "Activity Resolver Table:", " ", packageName, 21330 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21331 dumpState.setTitlePrinted(true); 21332 } 21333 } 21334 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21335 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21336 : "Receiver Resolver Table:", " ", packageName, 21337 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21338 dumpState.setTitlePrinted(true); 21339 } 21340 } 21341 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21342 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21343 : "Service Resolver Table:", " ", packageName, 21344 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21345 dumpState.setTitlePrinted(true); 21346 } 21347 } 21348 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21349 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21350 : "Provider Resolver Table:", " ", packageName, 21351 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21352 dumpState.setTitlePrinted(true); 21353 } 21354 } 21355 21356 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21357 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21358 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21359 int user = mSettings.mPreferredActivities.keyAt(i); 21360 if (pir.dump(pw, 21361 dumpState.getTitlePrinted() 21362 ? "\nPreferred Activities User " + user + ":" 21363 : "Preferred Activities User " + user + ":", " ", 21364 packageName, true, false)) { 21365 dumpState.setTitlePrinted(true); 21366 } 21367 } 21368 } 21369 21370 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21371 pw.flush(); 21372 FileOutputStream fout = new FileOutputStream(fd); 21373 BufferedOutputStream str = new BufferedOutputStream(fout); 21374 XmlSerializer serializer = new FastXmlSerializer(); 21375 try { 21376 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21377 serializer.startDocument(null, true); 21378 serializer.setFeature( 21379 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21380 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21381 serializer.endDocument(); 21382 serializer.flush(); 21383 } catch (IllegalArgumentException e) { 21384 pw.println("Failed writing: " + e); 21385 } catch (IllegalStateException e) { 21386 pw.println("Failed writing: " + e); 21387 } catch (IOException e) { 21388 pw.println("Failed writing: " + e); 21389 } 21390 } 21391 21392 if (!checkin 21393 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21394 && packageName == null) { 21395 pw.println(); 21396 int count = mSettings.mPackages.size(); 21397 if (count == 0) { 21398 pw.println("No applications!"); 21399 pw.println(); 21400 } else { 21401 final String prefix = " "; 21402 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21403 if (allPackageSettings.size() == 0) { 21404 pw.println("No domain preferred apps!"); 21405 pw.println(); 21406 } else { 21407 pw.println("App verification status:"); 21408 pw.println(); 21409 count = 0; 21410 for (PackageSetting ps : allPackageSettings) { 21411 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21412 if (ivi == null || ivi.getPackageName() == null) continue; 21413 pw.println(prefix + "Package: " + ivi.getPackageName()); 21414 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21415 pw.println(prefix + "Status: " + ivi.getStatusString()); 21416 pw.println(); 21417 count++; 21418 } 21419 if (count == 0) { 21420 pw.println(prefix + "No app verification established."); 21421 pw.println(); 21422 } 21423 for (int userId : sUserManager.getUserIds()) { 21424 pw.println("App linkages for user " + userId + ":"); 21425 pw.println(); 21426 count = 0; 21427 for (PackageSetting ps : allPackageSettings) { 21428 final long status = ps.getDomainVerificationStatusForUser(userId); 21429 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21430 && !DEBUG_DOMAIN_VERIFICATION) { 21431 continue; 21432 } 21433 pw.println(prefix + "Package: " + ps.name); 21434 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21435 String statusStr = IntentFilterVerificationInfo. 21436 getStatusStringFromValue(status); 21437 pw.println(prefix + "Status: " + statusStr); 21438 pw.println(); 21439 count++; 21440 } 21441 if (count == 0) { 21442 pw.println(prefix + "No configured app linkages."); 21443 pw.println(); 21444 } 21445 } 21446 } 21447 } 21448 } 21449 21450 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21451 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21452 } 21453 21454 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21455 boolean printedSomething = false; 21456 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21457 if (packageName != null && !packageName.equals(p.info.packageName)) { 21458 continue; 21459 } 21460 if (!printedSomething) { 21461 if (dumpState.onTitlePrinted()) 21462 pw.println(); 21463 pw.println("Registered ContentProviders:"); 21464 printedSomething = true; 21465 } 21466 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21467 pw.print(" "); pw.println(p.toString()); 21468 } 21469 printedSomething = false; 21470 for (Map.Entry<String, PackageParser.Provider> entry : 21471 mProvidersByAuthority.entrySet()) { 21472 PackageParser.Provider p = entry.getValue(); 21473 if (packageName != null && !packageName.equals(p.info.packageName)) { 21474 continue; 21475 } 21476 if (!printedSomething) { 21477 if (dumpState.onTitlePrinted()) 21478 pw.println(); 21479 pw.println("ContentProvider Authorities:"); 21480 printedSomething = true; 21481 } 21482 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21483 pw.print(" "); pw.println(p.toString()); 21484 if (p.info != null && p.info.applicationInfo != null) { 21485 final String appInfo = p.info.applicationInfo.toString(); 21486 pw.print(" applicationInfo="); pw.println(appInfo); 21487 } 21488 } 21489 } 21490 21491 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21492 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21493 } 21494 21495 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21496 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21497 } 21498 21499 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21500 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21501 } 21502 21503 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21504 if (dumpState.onTitlePrinted()) pw.println(); 21505 pw.println("Package Changes:"); 21506 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21507 final int K = mChangedPackages.size(); 21508 for (int i = 0; i < K; i++) { 21509 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21510 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21511 final int N = changes.size(); 21512 if (N == 0) { 21513 pw.print(" "); pw.println("No packages changed"); 21514 } else { 21515 for (int j = 0; j < N; j++) { 21516 final String pkgName = changes.valueAt(j); 21517 final int sequenceNumber = changes.keyAt(j); 21518 pw.print(" "); 21519 pw.print("seq="); 21520 pw.print(sequenceNumber); 21521 pw.print(", package="); 21522 pw.println(pkgName); 21523 } 21524 } 21525 } 21526 } 21527 21528 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21529 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21530 } 21531 21532 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21533 // XXX should handle packageName != null by dumping only install data that 21534 // the given package is involved with. 21535 if (dumpState.onTitlePrinted()) pw.println(); 21536 21537 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21538 ipw.println(); 21539 ipw.println("Frozen packages:"); 21540 ipw.increaseIndent(); 21541 if (mFrozenPackages.size() == 0) { 21542 ipw.println("(none)"); 21543 } else { 21544 for (int i = 0; i < mFrozenPackages.size(); i++) { 21545 ipw.println(mFrozenPackages.valueAt(i)); 21546 } 21547 } 21548 ipw.decreaseIndent(); 21549 } 21550 } 21551 21552 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21553 if (dumpState.onTitlePrinted()) pw.println(); 21554 21555 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120)) { 21556 ipw.println(); 21557 ipw.println("Loaded volumes:"); 21558 ipw.increaseIndent(); 21559 if (mLoadedVolumes.size() == 0) { 21560 ipw.println("(none)"); 21561 } else { 21562 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21563 ipw.println(mLoadedVolumes.valueAt(i)); 21564 } 21565 } 21566 ipw.decreaseIndent(); 21567 } 21568 } 21569 21570 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21571 && packageName == null) { 21572 if (dumpState.onTitlePrinted()) pw.println(); 21573 pw.println("Service permissions:"); 21574 21575 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21576 while (filterIterator.hasNext()) { 21577 final ServiceIntentInfo info = filterIterator.next(); 21578 final ServiceInfo serviceInfo = info.service.info; 21579 final String permission = serviceInfo.permission; 21580 if (permission != null) { 21581 pw.print(" "); 21582 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21583 pw.print(": "); 21584 pw.println(permission); 21585 } 21586 } 21587 } 21588 21589 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21590 if (dumpState.onTitlePrinted()) pw.println(); 21591 dumpDexoptStateLPr(pw, packageName); 21592 } 21593 21594 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21595 if (dumpState.onTitlePrinted()) pw.println(); 21596 dumpCompilerStatsLPr(pw, packageName); 21597 } 21598 21599 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21600 if (dumpState.onTitlePrinted()) pw.println(); 21601 mSettings.dumpReadMessagesLPr(pw, dumpState); 21602 21603 pw.println(); 21604 pw.println("Package warning messages:"); 21605 dumpCriticalInfo(pw, null); 21606 } 21607 21608 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21609 dumpCriticalInfo(pw, "msg,"); 21610 } 21611 } 21612 21613 // PackageInstaller should be called outside of mPackages lock 21614 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21615 // XXX should handle packageName != null by dumping only install data that 21616 // the given package is involved with. 21617 if (dumpState.onTitlePrinted()) pw.println(); 21618 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21619 } 21620 } 21621 21622 private void dumpProto(FileDescriptor fd) { 21623 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21624 21625 synchronized (mPackages) { 21626 final long requiredVerifierPackageToken = 21627 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21628 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21629 proto.write( 21630 PackageServiceDumpProto.PackageShortProto.UID, 21631 getPackageUid( 21632 mRequiredVerifierPackage, 21633 MATCH_DEBUG_TRIAGED_MISSING, 21634 UserHandle.USER_SYSTEM)); 21635 proto.end(requiredVerifierPackageToken); 21636 21637 if (mIntentFilterVerifierComponent != null) { 21638 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21639 final long verifierPackageToken = 21640 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21641 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21642 proto.write( 21643 PackageServiceDumpProto.PackageShortProto.UID, 21644 getPackageUid( 21645 verifierPackageName, 21646 MATCH_DEBUG_TRIAGED_MISSING, 21647 UserHandle.USER_SYSTEM)); 21648 proto.end(verifierPackageToken); 21649 } 21650 21651 dumpSharedLibrariesProto(proto); 21652 dumpFeaturesProto(proto); 21653 mSettings.dumpPackagesProto(proto); 21654 mSettings.dumpSharedUsersProto(proto); 21655 dumpCriticalInfo(proto); 21656 } 21657 proto.flush(); 21658 } 21659 21660 private void dumpFeaturesProto(ProtoOutputStream proto) { 21661 synchronized (mAvailableFeatures) { 21662 final int count = mAvailableFeatures.size(); 21663 for (int i = 0; i < count; i++) { 21664 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21665 } 21666 } 21667 } 21668 21669 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21670 final int count = mSharedLibraries.size(); 21671 for (int i = 0; i < count; i++) { 21672 final String libName = mSharedLibraries.keyAt(i); 21673 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21674 if (versionedLib == null) { 21675 continue; 21676 } 21677 final int versionCount = versionedLib.size(); 21678 for (int j = 0; j < versionCount; j++) { 21679 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21680 final long sharedLibraryToken = 21681 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21682 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21683 final boolean isJar = (libEntry.path != null); 21684 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21685 if (isJar) { 21686 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21687 } else { 21688 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21689 } 21690 proto.end(sharedLibraryToken); 21691 } 21692 } 21693 } 21694 21695 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21696 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21697 ipw.println(); 21698 ipw.println("Dexopt state:"); 21699 ipw.increaseIndent(); 21700 Collection<PackageParser.Package> packages = null; 21701 if (packageName != null) { 21702 PackageParser.Package targetPackage = mPackages.get(packageName); 21703 if (targetPackage != null) { 21704 packages = Collections.singletonList(targetPackage); 21705 } else { 21706 ipw.println("Unable to find package: " + packageName); 21707 return; 21708 } 21709 } else { 21710 packages = mPackages.values(); 21711 } 21712 21713 for (PackageParser.Package pkg : packages) { 21714 ipw.println("[" + pkg.packageName + "]"); 21715 ipw.increaseIndent(); 21716 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21717 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21718 ipw.decreaseIndent(); 21719 } 21720 } 21721 } 21722 21723 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21724 try (final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ")) { 21725 ipw.println(); 21726 ipw.println("Compiler stats:"); 21727 ipw.increaseIndent(); 21728 Collection<PackageParser.Package> packages = null; 21729 if (packageName != null) { 21730 PackageParser.Package targetPackage = mPackages.get(packageName); 21731 if (targetPackage != null) { 21732 packages = Collections.singletonList(targetPackage); 21733 } else { 21734 ipw.println("Unable to find package: " + packageName); 21735 return; 21736 } 21737 } else { 21738 packages = mPackages.values(); 21739 } 21740 21741 for (PackageParser.Package pkg : packages) { 21742 ipw.println("[" + pkg.packageName + "]"); 21743 ipw.increaseIndent(); 21744 21745 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21746 if (stats == null) { 21747 ipw.println("(No recorded stats)"); 21748 } else { 21749 stats.dump(ipw); 21750 } 21751 ipw.decreaseIndent(); 21752 } 21753 } 21754 } 21755 21756 private String dumpDomainString(String packageName) { 21757 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21758 .getList(); 21759 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21760 21761 ArraySet<String> result = new ArraySet<>(); 21762 if (iviList.size() > 0) { 21763 for (IntentFilterVerificationInfo ivi : iviList) { 21764 for (String host : ivi.getDomains()) { 21765 result.add(host); 21766 } 21767 } 21768 } 21769 if (filters != null && filters.size() > 0) { 21770 for (IntentFilter filter : filters) { 21771 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21772 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21773 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21774 result.addAll(filter.getHostsList()); 21775 } 21776 } 21777 } 21778 21779 StringBuilder sb = new StringBuilder(result.size() * 16); 21780 for (String domain : result) { 21781 if (sb.length() > 0) sb.append(" "); 21782 sb.append(domain); 21783 } 21784 return sb.toString(); 21785 } 21786 21787 // ------- apps on sdcard specific code ------- 21788 static final boolean DEBUG_SD_INSTALL = false; 21789 21790 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21791 21792 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21793 21794 private boolean mMediaMounted = false; 21795 21796 static String getEncryptKey() { 21797 try { 21798 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21799 SD_ENCRYPTION_KEYSTORE_NAME); 21800 if (sdEncKey == null) { 21801 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21802 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21803 if (sdEncKey == null) { 21804 Slog.e(TAG, "Failed to create encryption keys"); 21805 return null; 21806 } 21807 } 21808 return sdEncKey; 21809 } catch (NoSuchAlgorithmException nsae) { 21810 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21811 return null; 21812 } catch (IOException ioe) { 21813 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21814 return null; 21815 } 21816 } 21817 21818 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21819 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21820 final int size = infos.size(); 21821 final String[] packageNames = new String[size]; 21822 final int[] packageUids = new int[size]; 21823 for (int i = 0; i < size; i++) { 21824 final ApplicationInfo info = infos.get(i); 21825 packageNames[i] = info.packageName; 21826 packageUids[i] = info.uid; 21827 } 21828 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21829 finishedReceiver); 21830 } 21831 21832 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21833 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21834 sendResourcesChangedBroadcast(mediaStatus, replacing, 21835 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21836 } 21837 21838 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21839 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21840 int size = pkgList.length; 21841 if (size > 0) { 21842 // Send broadcasts here 21843 Bundle extras = new Bundle(); 21844 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21845 if (uidArr != null) { 21846 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21847 } 21848 if (replacing) { 21849 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21850 } 21851 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21852 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21853 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21854 } 21855 } 21856 21857 private void loadPrivatePackages(final VolumeInfo vol) { 21858 mHandler.post(new Runnable() { 21859 @Override 21860 public void run() { 21861 loadPrivatePackagesInner(vol); 21862 } 21863 }); 21864 } 21865 21866 private void loadPrivatePackagesInner(VolumeInfo vol) { 21867 final String volumeUuid = vol.fsUuid; 21868 if (TextUtils.isEmpty(volumeUuid)) { 21869 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21870 return; 21871 } 21872 21873 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21874 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21875 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21876 21877 final VersionInfo ver; 21878 final List<PackageSetting> packages; 21879 synchronized (mPackages) { 21880 ver = mSettings.findOrCreateVersion(volumeUuid); 21881 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21882 } 21883 21884 for (PackageSetting ps : packages) { 21885 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21886 synchronized (mInstallLock) { 21887 final PackageParser.Package pkg; 21888 try { 21889 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21890 loaded.add(pkg.applicationInfo); 21891 21892 } catch (PackageManagerException e) { 21893 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21894 } 21895 21896 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21897 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21898 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21899 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21900 } 21901 } 21902 } 21903 21904 // Reconcile app data for all started/unlocked users 21905 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21906 final UserManager um = mContext.getSystemService(UserManager.class); 21907 UserManagerInternal umInternal = getUserManagerInternal(); 21908 for (UserInfo user : um.getUsers()) { 21909 final int flags; 21910 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21911 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21912 } else if (umInternal.isUserRunning(user.id)) { 21913 flags = StorageManager.FLAG_STORAGE_DE; 21914 } else { 21915 continue; 21916 } 21917 21918 try { 21919 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21920 synchronized (mInstallLock) { 21921 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21922 } 21923 } catch (IllegalStateException e) { 21924 // Device was probably ejected, and we'll process that event momentarily 21925 Slog.w(TAG, "Failed to prepare storage: " + e); 21926 } 21927 } 21928 21929 synchronized (mPackages) { 21930 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21931 if (sdkUpdated) { 21932 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21933 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21934 } 21935 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21936 mPermissionCallback); 21937 21938 // Yay, everything is now upgraded 21939 ver.forceCurrent(); 21940 21941 mSettings.writeLPr(); 21942 } 21943 21944 for (PackageFreezer freezer : freezers) { 21945 freezer.close(); 21946 } 21947 21948 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21949 sendResourcesChangedBroadcast(true, false, loaded, null); 21950 mLoadedVolumes.add(vol.getId()); 21951 } 21952 21953 private void unloadPrivatePackages(final VolumeInfo vol) { 21954 mHandler.post(new Runnable() { 21955 @Override 21956 public void run() { 21957 unloadPrivatePackagesInner(vol); 21958 } 21959 }); 21960 } 21961 21962 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21963 final String volumeUuid = vol.fsUuid; 21964 if (TextUtils.isEmpty(volumeUuid)) { 21965 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21966 return; 21967 } 21968 21969 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21970 synchronized (mInstallLock) { 21971 synchronized (mPackages) { 21972 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21973 for (PackageSetting ps : packages) { 21974 if (ps.pkg == null) continue; 21975 21976 final ApplicationInfo info = ps.pkg.applicationInfo; 21977 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21978 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21979 21980 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21981 "unloadPrivatePackagesInner")) { 21982 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21983 false, null)) { 21984 unloaded.add(info); 21985 } else { 21986 Slog.w(TAG, "Failed to unload " + ps.codePath); 21987 } 21988 } 21989 21990 // Try very hard to release any references to this package 21991 // so we don't risk the system server being killed due to 21992 // open FDs 21993 AttributeCache.instance().removePackage(ps.name); 21994 } 21995 21996 mSettings.writeLPr(); 21997 } 21998 } 21999 22000 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22001 sendResourcesChangedBroadcast(false, false, unloaded, null); 22002 mLoadedVolumes.remove(vol.getId()); 22003 22004 // Try very hard to release any references to this path so we don't risk 22005 // the system server being killed due to open FDs 22006 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22007 22008 for (int i = 0; i < 3; i++) { 22009 System.gc(); 22010 System.runFinalization(); 22011 } 22012 } 22013 22014 private void assertPackageKnown(String volumeUuid, String packageName) 22015 throws PackageManagerException { 22016 synchronized (mPackages) { 22017 // Normalize package name to handle renamed packages 22018 packageName = normalizePackageNameLPr(packageName); 22019 22020 final PackageSetting ps = mSettings.mPackages.get(packageName); 22021 if (ps == null) { 22022 throw new PackageManagerException("Package " + packageName + " is unknown"); 22023 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22024 throw new PackageManagerException( 22025 "Package " + packageName + " found on unknown volume " + volumeUuid 22026 + "; expected volume " + ps.volumeUuid); 22027 } 22028 } 22029 } 22030 22031 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22032 throws PackageManagerException { 22033 synchronized (mPackages) { 22034 // Normalize package name to handle renamed packages 22035 packageName = normalizePackageNameLPr(packageName); 22036 22037 final PackageSetting ps = mSettings.mPackages.get(packageName); 22038 if (ps == null) { 22039 throw new PackageManagerException("Package " + packageName + " is unknown"); 22040 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22041 throw new PackageManagerException( 22042 "Package " + packageName + " found on unknown volume " + volumeUuid 22043 + "; expected volume " + ps.volumeUuid); 22044 } else if (!ps.getInstalled(userId)) { 22045 throw new PackageManagerException( 22046 "Package " + packageName + " not installed for user " + userId); 22047 } 22048 } 22049 } 22050 22051 private List<String> collectAbsoluteCodePaths() { 22052 synchronized (mPackages) { 22053 List<String> codePaths = new ArrayList<>(); 22054 final int packageCount = mSettings.mPackages.size(); 22055 for (int i = 0; i < packageCount; i++) { 22056 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22057 codePaths.add(ps.codePath.getAbsolutePath()); 22058 } 22059 return codePaths; 22060 } 22061 } 22062 22063 /** 22064 * Examine all apps present on given mounted volume, and destroy apps that 22065 * aren't expected, either due to uninstallation or reinstallation on 22066 * another volume. 22067 */ 22068 private void reconcileApps(String volumeUuid) { 22069 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22070 List<File> filesToDelete = null; 22071 22072 final File[] files = FileUtils.listFilesOrEmpty( 22073 Environment.getDataAppDirectory(volumeUuid)); 22074 for (File file : files) { 22075 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22076 && !PackageInstallerService.isStageName(file.getName()); 22077 if (!isPackage) { 22078 // Ignore entries which are not packages 22079 continue; 22080 } 22081 22082 String absolutePath = file.getAbsolutePath(); 22083 22084 boolean pathValid = false; 22085 final int absoluteCodePathCount = absoluteCodePaths.size(); 22086 for (int i = 0; i < absoluteCodePathCount; i++) { 22087 String absoluteCodePath = absoluteCodePaths.get(i); 22088 if (absolutePath.startsWith(absoluteCodePath)) { 22089 pathValid = true; 22090 break; 22091 } 22092 } 22093 22094 if (!pathValid) { 22095 if (filesToDelete == null) { 22096 filesToDelete = new ArrayList<>(); 22097 } 22098 filesToDelete.add(file); 22099 } 22100 } 22101 22102 if (filesToDelete != null) { 22103 final int fileToDeleteCount = filesToDelete.size(); 22104 for (int i = 0; i < fileToDeleteCount; i++) { 22105 File fileToDelete = filesToDelete.get(i); 22106 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22107 synchronized (mInstallLock) { 22108 removeCodePathLI(fileToDelete); 22109 } 22110 } 22111 } 22112 } 22113 22114 /** 22115 * Reconcile all app data for the given user. 22116 * <p> 22117 * Verifies that directories exist and that ownership and labeling is 22118 * correct for all installed apps on all mounted volumes. 22119 */ 22120 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22121 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22122 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22123 final String volumeUuid = vol.getFsUuid(); 22124 synchronized (mInstallLock) { 22125 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22126 } 22127 } 22128 } 22129 22130 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22131 boolean migrateAppData) { 22132 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22133 } 22134 22135 /** 22136 * Reconcile all app data on given mounted volume. 22137 * <p> 22138 * Destroys app data that isn't expected, either due to uninstallation or 22139 * reinstallation on another volume. 22140 * <p> 22141 * Verifies that directories exist and that ownership and labeling is 22142 * correct for all installed apps. 22143 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22144 */ 22145 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22146 boolean migrateAppData, boolean onlyCoreApps) { 22147 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22148 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22149 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22150 22151 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22152 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22153 22154 // First look for stale data that doesn't belong, and check if things 22155 // have changed since we did our last restorecon 22156 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22157 if (StorageManager.isFileEncryptedNativeOrEmulated() 22158 && !StorageManager.isUserKeyUnlocked(userId)) { 22159 throw new RuntimeException( 22160 "Yikes, someone asked us to reconcile CE storage while " + userId 22161 + " was still locked; this would have caused massive data loss!"); 22162 } 22163 22164 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22165 for (File file : files) { 22166 final String packageName = file.getName(); 22167 try { 22168 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22169 } catch (PackageManagerException e) { 22170 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22171 try { 22172 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22173 StorageManager.FLAG_STORAGE_CE, 0); 22174 } catch (InstallerException e2) { 22175 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22176 } 22177 } 22178 } 22179 } 22180 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22181 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22182 for (File file : files) { 22183 final String packageName = file.getName(); 22184 try { 22185 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22186 } catch (PackageManagerException e) { 22187 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22188 try { 22189 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22190 StorageManager.FLAG_STORAGE_DE, 0); 22191 } catch (InstallerException e2) { 22192 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22193 } 22194 } 22195 } 22196 } 22197 22198 // Ensure that data directories are ready to roll for all packages 22199 // installed for this volume and user 22200 final List<PackageSetting> packages; 22201 synchronized (mPackages) { 22202 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22203 } 22204 int preparedCount = 0; 22205 for (PackageSetting ps : packages) { 22206 final String packageName = ps.name; 22207 if (ps.pkg == null) { 22208 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22209 // TODO: might be due to legacy ASEC apps; we should circle back 22210 // and reconcile again once they're scanned 22211 continue; 22212 } 22213 // Skip non-core apps if requested 22214 if (onlyCoreApps && !ps.pkg.coreApp) { 22215 result.add(packageName); 22216 continue; 22217 } 22218 22219 if (ps.getInstalled(userId)) { 22220 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22221 preparedCount++; 22222 } 22223 } 22224 22225 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22226 return result; 22227 } 22228 22229 /** 22230 * Prepare app data for the given app just after it was installed or 22231 * upgraded. This method carefully only touches users that it's installed 22232 * for, and it forces a restorecon to handle any seinfo changes. 22233 * <p> 22234 * Verifies that directories exist and that ownership and labeling is 22235 * correct for all installed apps. If there is an ownership mismatch, it 22236 * will try recovering system apps by wiping data; third-party app data is 22237 * left intact. 22238 * <p> 22239 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22240 */ 22241 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22242 final PackageSetting ps; 22243 synchronized (mPackages) { 22244 ps = mSettings.mPackages.get(pkg.packageName); 22245 mSettings.writeKernelMappingLPr(ps); 22246 } 22247 22248 final UserManager um = mContext.getSystemService(UserManager.class); 22249 UserManagerInternal umInternal = getUserManagerInternal(); 22250 for (UserInfo user : um.getUsers()) { 22251 final int flags; 22252 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22253 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22254 } else if (umInternal.isUserRunning(user.id)) { 22255 flags = StorageManager.FLAG_STORAGE_DE; 22256 } else { 22257 continue; 22258 } 22259 22260 if (ps.getInstalled(user.id)) { 22261 // TODO: when user data is locked, mark that we're still dirty 22262 prepareAppDataLIF(pkg, user.id, flags); 22263 } 22264 } 22265 } 22266 22267 /** 22268 * Prepare app data for the given app. 22269 * <p> 22270 * Verifies that directories exist and that ownership and labeling is 22271 * correct for all installed apps. If there is an ownership mismatch, this 22272 * will try recovering system apps by wiping data; third-party app data is 22273 * left intact. 22274 */ 22275 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22276 if (pkg == null) { 22277 Slog.wtf(TAG, "Package was null!", new Throwable()); 22278 return; 22279 } 22280 prepareAppDataLeafLIF(pkg, userId, flags); 22281 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22282 for (int i = 0; i < childCount; i++) { 22283 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22284 } 22285 } 22286 22287 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22288 boolean maybeMigrateAppData) { 22289 prepareAppDataLIF(pkg, userId, flags); 22290 22291 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22292 // We may have just shuffled around app data directories, so 22293 // prepare them one more time 22294 prepareAppDataLIF(pkg, userId, flags); 22295 } 22296 } 22297 22298 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22299 if (DEBUG_APP_DATA) { 22300 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22301 + Integer.toHexString(flags)); 22302 } 22303 22304 final String volumeUuid = pkg.volumeUuid; 22305 final String packageName = pkg.packageName; 22306 final ApplicationInfo app = pkg.applicationInfo; 22307 final int appId = UserHandle.getAppId(app.uid); 22308 22309 Preconditions.checkNotNull(app.seInfo); 22310 22311 long ceDataInode = -1; 22312 try { 22313 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22314 appId, app.seInfo, app.targetSdkVersion); 22315 } catch (InstallerException e) { 22316 if (app.isSystemApp()) { 22317 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22318 + ", but trying to recover: " + e); 22319 destroyAppDataLeafLIF(pkg, userId, flags); 22320 try { 22321 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22322 appId, app.seInfo, app.targetSdkVersion); 22323 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22324 } catch (InstallerException e2) { 22325 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22326 } 22327 } else { 22328 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22329 } 22330 } 22331 // Prepare the application profiles only for upgrades and first boot (so that we don't 22332 // repeat the same operation at each boot). 22333 // We only have to cover the upgrade and first boot here because for app installs we 22334 // prepare the profiles before invoking dexopt (in installPackageLI). 22335 // 22336 // We also have to cover non system users because we do not call the usual install package 22337 // methods for them. 22338 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22339 mArtManagerService.prepareAppProfiles(pkg, userId); 22340 } 22341 22342 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22343 // TODO: mark this structure as dirty so we persist it! 22344 synchronized (mPackages) { 22345 final PackageSetting ps = mSettings.mPackages.get(packageName); 22346 if (ps != null) { 22347 ps.setCeDataInode(ceDataInode, userId); 22348 } 22349 } 22350 } 22351 22352 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22353 } 22354 22355 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22356 if (pkg == null) { 22357 Slog.wtf(TAG, "Package was null!", new Throwable()); 22358 return; 22359 } 22360 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22361 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22362 for (int i = 0; i < childCount; i++) { 22363 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22364 } 22365 } 22366 22367 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22368 final String volumeUuid = pkg.volumeUuid; 22369 final String packageName = pkg.packageName; 22370 final ApplicationInfo app = pkg.applicationInfo; 22371 22372 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22373 // Create a native library symlink only if we have native libraries 22374 // and if the native libraries are 32 bit libraries. We do not provide 22375 // this symlink for 64 bit libraries. 22376 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22377 final String nativeLibPath = app.nativeLibraryDir; 22378 try { 22379 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22380 nativeLibPath, userId); 22381 } catch (InstallerException e) { 22382 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22383 } 22384 } 22385 } 22386 } 22387 22388 /** 22389 * For system apps on non-FBE devices, this method migrates any existing 22390 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22391 * requested by the app. 22392 */ 22393 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22394 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22395 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22396 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22397 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22398 try { 22399 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22400 storageTarget); 22401 } catch (InstallerException e) { 22402 logCriticalInfo(Log.WARN, 22403 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22404 } 22405 return true; 22406 } else { 22407 return false; 22408 } 22409 } 22410 22411 public PackageFreezer freezePackage(String packageName, String killReason) { 22412 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22413 } 22414 22415 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22416 return new PackageFreezer(packageName, userId, killReason); 22417 } 22418 22419 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22420 String killReason) { 22421 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22422 } 22423 22424 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22425 String killReason) { 22426 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22427 return new PackageFreezer(); 22428 } else { 22429 return freezePackage(packageName, userId, killReason); 22430 } 22431 } 22432 22433 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22434 String killReason) { 22435 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22436 } 22437 22438 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22439 String killReason) { 22440 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22441 return new PackageFreezer(); 22442 } else { 22443 return freezePackage(packageName, userId, killReason); 22444 } 22445 } 22446 22447 /** 22448 * Class that freezes and kills the given package upon creation, and 22449 * unfreezes it upon closing. This is typically used when doing surgery on 22450 * app code/data to prevent the app from running while you're working. 22451 */ 22452 private class PackageFreezer implements AutoCloseable { 22453 private final String mPackageName; 22454 private final PackageFreezer[] mChildren; 22455 22456 private final boolean mWeFroze; 22457 22458 private final AtomicBoolean mClosed = new AtomicBoolean(); 22459 private final CloseGuard mCloseGuard = CloseGuard.get(); 22460 22461 /** 22462 * Create and return a stub freezer that doesn't actually do anything, 22463 * typically used when someone requested 22464 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22465 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22466 */ 22467 public PackageFreezer() { 22468 mPackageName = null; 22469 mChildren = null; 22470 mWeFroze = false; 22471 mCloseGuard.open("close"); 22472 } 22473 22474 public PackageFreezer(String packageName, int userId, String killReason) { 22475 synchronized (mPackages) { 22476 mPackageName = packageName; 22477 mWeFroze = mFrozenPackages.add(mPackageName); 22478 22479 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22480 if (ps != null) { 22481 killApplication(ps.name, ps.appId, userId, killReason); 22482 } 22483 22484 final PackageParser.Package p = mPackages.get(packageName); 22485 if (p != null && p.childPackages != null) { 22486 final int N = p.childPackages.size(); 22487 mChildren = new PackageFreezer[N]; 22488 for (int i = 0; i < N; i++) { 22489 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22490 userId, killReason); 22491 } 22492 } else { 22493 mChildren = null; 22494 } 22495 } 22496 mCloseGuard.open("close"); 22497 } 22498 22499 @Override 22500 protected void finalize() throws Throwable { 22501 try { 22502 if (mCloseGuard != null) { 22503 mCloseGuard.warnIfOpen(); 22504 } 22505 22506 close(); 22507 } finally { 22508 super.finalize(); 22509 } 22510 } 22511 22512 @Override 22513 public void close() { 22514 mCloseGuard.close(); 22515 if (mClosed.compareAndSet(false, true)) { 22516 synchronized (mPackages) { 22517 if (mWeFroze) { 22518 mFrozenPackages.remove(mPackageName); 22519 } 22520 22521 if (mChildren != null) { 22522 for (PackageFreezer freezer : mChildren) { 22523 freezer.close(); 22524 } 22525 } 22526 } 22527 } 22528 } 22529 } 22530 22531 /** 22532 * Verify that given package is currently frozen. 22533 */ 22534 private void checkPackageFrozen(String packageName) { 22535 synchronized (mPackages) { 22536 if (!mFrozenPackages.contains(packageName)) { 22537 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22538 } 22539 } 22540 } 22541 22542 @Override 22543 public int movePackage(final String packageName, final String volumeUuid) { 22544 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22545 22546 final int callingUid = Binder.getCallingUid(); 22547 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22548 final int moveId = mNextMoveId.getAndIncrement(); 22549 mHandler.post(new Runnable() { 22550 @Override 22551 public void run() { 22552 try { 22553 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22554 } catch (PackageManagerException e) { 22555 Slog.w(TAG, "Failed to move " + packageName, e); 22556 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22557 } 22558 } 22559 }); 22560 return moveId; 22561 } 22562 22563 private void movePackageInternal(final String packageName, final String volumeUuid, 22564 final int moveId, final int callingUid, UserHandle user) 22565 throws PackageManagerException { 22566 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22567 final PackageManager pm = mContext.getPackageManager(); 22568 22569 final boolean currentAsec; 22570 final String currentVolumeUuid; 22571 final File codeFile; 22572 final String installerPackageName; 22573 final String packageAbiOverride; 22574 final int appId; 22575 final String seinfo; 22576 final String label; 22577 final int targetSdkVersion; 22578 final PackageFreezer freezer; 22579 final int[] installedUserIds; 22580 22581 // reader 22582 synchronized (mPackages) { 22583 final PackageParser.Package pkg = mPackages.get(packageName); 22584 final PackageSetting ps = mSettings.mPackages.get(packageName); 22585 if (pkg == null 22586 || ps == null 22587 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22588 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22589 } 22590 if (pkg.applicationInfo.isSystemApp()) { 22591 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22592 "Cannot move system application"); 22593 } 22594 22595 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22596 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22597 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22598 if (isInternalStorage && !allow3rdPartyOnInternal) { 22599 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22600 "3rd party apps are not allowed on internal storage"); 22601 } 22602 22603 if (pkg.applicationInfo.isExternalAsec()) { 22604 currentAsec = true; 22605 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22606 } else if (pkg.applicationInfo.isForwardLocked()) { 22607 currentAsec = true; 22608 currentVolumeUuid = "forward_locked"; 22609 } else { 22610 currentAsec = false; 22611 currentVolumeUuid = ps.volumeUuid; 22612 22613 final File probe = new File(pkg.codePath); 22614 final File probeOat = new File(probe, "oat"); 22615 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22616 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22617 "Move only supported for modern cluster style installs"); 22618 } 22619 } 22620 22621 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22622 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22623 "Package already moved to " + volumeUuid); 22624 } 22625 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22626 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22627 "Device admin cannot be moved"); 22628 } 22629 22630 if (mFrozenPackages.contains(packageName)) { 22631 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22632 "Failed to move already frozen package"); 22633 } 22634 22635 codeFile = new File(pkg.codePath); 22636 installerPackageName = ps.installerPackageName; 22637 packageAbiOverride = ps.cpuAbiOverrideString; 22638 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22639 seinfo = pkg.applicationInfo.seInfo; 22640 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22641 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22642 freezer = freezePackage(packageName, "movePackageInternal"); 22643 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22644 } 22645 22646 final Bundle extras = new Bundle(); 22647 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22648 extras.putString(Intent.EXTRA_TITLE, label); 22649 mMoveCallbacks.notifyCreated(moveId, extras); 22650 22651 int installFlags; 22652 final boolean moveCompleteApp; 22653 final File measurePath; 22654 22655 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22656 installFlags = INSTALL_INTERNAL; 22657 moveCompleteApp = !currentAsec; 22658 measurePath = Environment.getDataAppDirectory(volumeUuid); 22659 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22660 installFlags = INSTALL_EXTERNAL; 22661 moveCompleteApp = false; 22662 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22663 } else { 22664 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22665 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22666 || !volume.isMountedWritable()) { 22667 freezer.close(); 22668 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22669 "Move location not mounted private volume"); 22670 } 22671 22672 Preconditions.checkState(!currentAsec); 22673 22674 installFlags = INSTALL_INTERNAL; 22675 moveCompleteApp = true; 22676 measurePath = Environment.getDataAppDirectory(volumeUuid); 22677 } 22678 22679 // If we're moving app data around, we need all the users unlocked 22680 if (moveCompleteApp) { 22681 for (int userId : installedUserIds) { 22682 if (StorageManager.isFileEncryptedNativeOrEmulated() 22683 && !StorageManager.isUserKeyUnlocked(userId)) { 22684 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22685 "User " + userId + " must be unlocked"); 22686 } 22687 } 22688 } 22689 22690 final PackageStats stats = new PackageStats(null, -1); 22691 synchronized (mInstaller) { 22692 for (int userId : installedUserIds) { 22693 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22694 freezer.close(); 22695 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22696 "Failed to measure package size"); 22697 } 22698 } 22699 } 22700 22701 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22702 + stats.dataSize); 22703 22704 final long startFreeBytes = measurePath.getUsableSpace(); 22705 final long sizeBytes; 22706 if (moveCompleteApp) { 22707 sizeBytes = stats.codeSize + stats.dataSize; 22708 } else { 22709 sizeBytes = stats.codeSize; 22710 } 22711 22712 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22713 freezer.close(); 22714 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22715 "Not enough free space to move"); 22716 } 22717 22718 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22719 22720 final CountDownLatch installedLatch = new CountDownLatch(1); 22721 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22722 @Override 22723 public void onUserActionRequired(Intent intent) throws RemoteException { 22724 throw new IllegalStateException(); 22725 } 22726 22727 @Override 22728 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22729 Bundle extras) throws RemoteException { 22730 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22731 + PackageManager.installStatusToString(returnCode, msg)); 22732 22733 installedLatch.countDown(); 22734 freezer.close(); 22735 22736 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22737 switch (status) { 22738 case PackageInstaller.STATUS_SUCCESS: 22739 mMoveCallbacks.notifyStatusChanged(moveId, 22740 PackageManager.MOVE_SUCCEEDED); 22741 break; 22742 case PackageInstaller.STATUS_FAILURE_STORAGE: 22743 mMoveCallbacks.notifyStatusChanged(moveId, 22744 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22745 break; 22746 default: 22747 mMoveCallbacks.notifyStatusChanged(moveId, 22748 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22749 break; 22750 } 22751 } 22752 }; 22753 22754 final MoveInfo move; 22755 if (moveCompleteApp) { 22756 // Kick off a thread to report progress estimates 22757 new Thread() { 22758 @Override 22759 public void run() { 22760 while (true) { 22761 try { 22762 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22763 break; 22764 } 22765 } catch (InterruptedException ignored) { 22766 } 22767 22768 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22769 final int progress = 10 + (int) MathUtils.constrain( 22770 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22771 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22772 } 22773 } 22774 }.start(); 22775 22776 final String dataAppName = codeFile.getName(); 22777 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22778 dataAppName, appId, seinfo, targetSdkVersion); 22779 } else { 22780 move = null; 22781 } 22782 22783 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22784 22785 final Message msg = mHandler.obtainMessage(INIT_COPY); 22786 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22787 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22788 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22789 packageAbiOverride, null /*grantedPermissions*/, 22790 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22791 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22792 msg.obj = params; 22793 22794 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22795 System.identityHashCode(msg.obj)); 22796 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22797 System.identityHashCode(msg.obj)); 22798 22799 mHandler.sendMessage(msg); 22800 } 22801 22802 @Override 22803 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22804 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22805 22806 final int realMoveId = mNextMoveId.getAndIncrement(); 22807 final Bundle extras = new Bundle(); 22808 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22809 mMoveCallbacks.notifyCreated(realMoveId, extras); 22810 22811 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22812 @Override 22813 public void onCreated(int moveId, Bundle extras) { 22814 // Ignored 22815 } 22816 22817 @Override 22818 public void onStatusChanged(int moveId, int status, long estMillis) { 22819 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22820 } 22821 }; 22822 22823 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22824 storage.setPrimaryStorageUuid(volumeUuid, callback); 22825 return realMoveId; 22826 } 22827 22828 @Override 22829 public int getMoveStatus(int moveId) { 22830 mContext.enforceCallingOrSelfPermission( 22831 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22832 return mMoveCallbacks.mLastStatus.get(moveId); 22833 } 22834 22835 @Override 22836 public void registerMoveCallback(IPackageMoveObserver callback) { 22837 mContext.enforceCallingOrSelfPermission( 22838 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22839 mMoveCallbacks.register(callback); 22840 } 22841 22842 @Override 22843 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22844 mContext.enforceCallingOrSelfPermission( 22845 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22846 mMoveCallbacks.unregister(callback); 22847 } 22848 22849 @Override 22850 public boolean setInstallLocation(int loc) { 22851 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22852 null); 22853 if (getInstallLocation() == loc) { 22854 return true; 22855 } 22856 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22857 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22858 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22859 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22860 return true; 22861 } 22862 return false; 22863 } 22864 22865 @Override 22866 public int getInstallLocation() { 22867 // allow instant app access 22868 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22869 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22870 PackageHelper.APP_INSTALL_AUTO); 22871 } 22872 22873 /** Called by UserManagerService */ 22874 void cleanUpUser(UserManagerService userManager, int userHandle) { 22875 synchronized (mPackages) { 22876 mDirtyUsers.remove(userHandle); 22877 mUserNeedsBadging.delete(userHandle); 22878 mSettings.removeUserLPw(userHandle); 22879 mPendingBroadcasts.remove(userHandle); 22880 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22881 removeUnusedPackagesLPw(userManager, userHandle); 22882 } 22883 } 22884 22885 /** 22886 * We're removing userHandle and would like to remove any downloaded packages 22887 * that are no longer in use by any other user. 22888 * @param userHandle the user being removed 22889 */ 22890 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22891 final boolean DEBUG_CLEAN_APKS = false; 22892 int [] users = userManager.getUserIds(); 22893 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22894 while (psit.hasNext()) { 22895 PackageSetting ps = psit.next(); 22896 if (ps.pkg == null) { 22897 continue; 22898 } 22899 final String packageName = ps.pkg.packageName; 22900 // Skip over if system app 22901 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22902 continue; 22903 } 22904 if (DEBUG_CLEAN_APKS) { 22905 Slog.i(TAG, "Checking package " + packageName); 22906 } 22907 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22908 if (keep) { 22909 if (DEBUG_CLEAN_APKS) { 22910 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22911 } 22912 } else { 22913 for (int i = 0; i < users.length; i++) { 22914 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22915 keep = true; 22916 if (DEBUG_CLEAN_APKS) { 22917 Slog.i(TAG, " Keeping package " + packageName + " for user " 22918 + users[i]); 22919 } 22920 break; 22921 } 22922 } 22923 } 22924 if (!keep) { 22925 if (DEBUG_CLEAN_APKS) { 22926 Slog.i(TAG, " Removing package " + packageName); 22927 } 22928 mHandler.post(new Runnable() { 22929 public void run() { 22930 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22931 userHandle, 0); 22932 } //end run 22933 }); 22934 } 22935 } 22936 } 22937 22938 /** Called by UserManagerService */ 22939 void createNewUser(int userId, String[] disallowedPackages) { 22940 synchronized (mInstallLock) { 22941 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22942 } 22943 synchronized (mPackages) { 22944 scheduleWritePackageRestrictionsLocked(userId); 22945 scheduleWritePackageListLocked(userId); 22946 applyFactoryDefaultBrowserLPw(userId); 22947 primeDomainVerificationsLPw(userId); 22948 } 22949 } 22950 22951 void onNewUserCreated(final int userId) { 22952 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22953 synchronized(mPackages) { 22954 // If permission review for legacy apps is required, we represent 22955 // dagerous permissions for such apps as always granted runtime 22956 // permissions to keep per user flag state whether review is needed. 22957 // Hence, if a new user is added we have to propagate dangerous 22958 // permission grants for these legacy apps. 22959 if (mSettings.mPermissions.mPermissionReviewRequired) { 22960// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22961 mPermissionManager.updateAllPermissions( 22962 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22963 mPermissionCallback); 22964 } 22965 } 22966 } 22967 22968 @Override 22969 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22970 mContext.enforceCallingOrSelfPermission( 22971 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22972 "Only package verification agents can read the verifier device identity"); 22973 22974 synchronized (mPackages) { 22975 return mSettings.getVerifierDeviceIdentityLPw(); 22976 } 22977 } 22978 22979 @Override 22980 public void setPermissionEnforced(String permission, boolean enforced) { 22981 // TODO: Now that we no longer change GID for storage, this should to away. 22982 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22983 "setPermissionEnforced"); 22984 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22985 synchronized (mPackages) { 22986 if (mSettings.mReadExternalStorageEnforced == null 22987 || mSettings.mReadExternalStorageEnforced != enforced) { 22988 mSettings.mReadExternalStorageEnforced = 22989 enforced ? Boolean.TRUE : Boolean.FALSE; 22990 mSettings.writeLPr(); 22991 } 22992 } 22993 // kill any non-foreground processes so we restart them and 22994 // grant/revoke the GID. 22995 final IActivityManager am = ActivityManager.getService(); 22996 if (am != null) { 22997 final long token = Binder.clearCallingIdentity(); 22998 try { 22999 am.killProcessesBelowForeground("setPermissionEnforcement"); 23000 } catch (RemoteException e) { 23001 } finally { 23002 Binder.restoreCallingIdentity(token); 23003 } 23004 } 23005 } else { 23006 throw new IllegalArgumentException("No selective enforcement for " + permission); 23007 } 23008 } 23009 23010 @Override 23011 @Deprecated 23012 public boolean isPermissionEnforced(String permission) { 23013 // allow instant applications 23014 return true; 23015 } 23016 23017 @Override 23018 public boolean isStorageLow() { 23019 // allow instant applications 23020 final long token = Binder.clearCallingIdentity(); 23021 try { 23022 final DeviceStorageMonitorInternal 23023 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23024 if (dsm != null) { 23025 return dsm.isMemoryLow(); 23026 } else { 23027 return false; 23028 } 23029 } finally { 23030 Binder.restoreCallingIdentity(token); 23031 } 23032 } 23033 23034 @Override 23035 public IPackageInstaller getPackageInstaller() { 23036 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23037 return null; 23038 } 23039 return mInstallerService; 23040 } 23041 23042 @Override 23043 public IArtManager getArtManager() { 23044 return mArtManagerService; 23045 } 23046 23047 private boolean userNeedsBadging(int userId) { 23048 int index = mUserNeedsBadging.indexOfKey(userId); 23049 if (index < 0) { 23050 final UserInfo userInfo; 23051 final long token = Binder.clearCallingIdentity(); 23052 try { 23053 userInfo = sUserManager.getUserInfo(userId); 23054 } finally { 23055 Binder.restoreCallingIdentity(token); 23056 } 23057 final boolean b; 23058 if (userInfo != null && userInfo.isManagedProfile()) { 23059 b = true; 23060 } else { 23061 b = false; 23062 } 23063 mUserNeedsBadging.put(userId, b); 23064 return b; 23065 } 23066 return mUserNeedsBadging.valueAt(index); 23067 } 23068 23069 @Override 23070 public KeySet getKeySetByAlias(String packageName, String alias) { 23071 if (packageName == null || alias == null) { 23072 return null; 23073 } 23074 synchronized(mPackages) { 23075 final PackageParser.Package pkg = mPackages.get(packageName); 23076 if (pkg == null) { 23077 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23078 throw new IllegalArgumentException("Unknown package: " + packageName); 23079 } 23080 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23081 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23082 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23083 throw new IllegalArgumentException("Unknown package: " + packageName); 23084 } 23085 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23086 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23087 } 23088 } 23089 23090 @Override 23091 public KeySet getSigningKeySet(String packageName) { 23092 if (packageName == null) { 23093 return null; 23094 } 23095 synchronized(mPackages) { 23096 final int callingUid = Binder.getCallingUid(); 23097 final int callingUserId = UserHandle.getUserId(callingUid); 23098 final PackageParser.Package pkg = mPackages.get(packageName); 23099 if (pkg == null) { 23100 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23101 throw new IllegalArgumentException("Unknown package: " + packageName); 23102 } 23103 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23104 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23105 // filter and pretend the package doesn't exist 23106 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23107 + ", uid:" + callingUid); 23108 throw new IllegalArgumentException("Unknown package: " + packageName); 23109 } 23110 if (pkg.applicationInfo.uid != callingUid 23111 && Process.SYSTEM_UID != callingUid) { 23112 throw new SecurityException("May not access signing KeySet of other apps."); 23113 } 23114 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23115 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23116 } 23117 } 23118 23119 @Override 23120 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23121 final int callingUid = Binder.getCallingUid(); 23122 if (getInstantAppPackageName(callingUid) != null) { 23123 return false; 23124 } 23125 if (packageName == null || ks == null) { 23126 return false; 23127 } 23128 synchronized(mPackages) { 23129 final PackageParser.Package pkg = mPackages.get(packageName); 23130 if (pkg == null 23131 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23132 UserHandle.getUserId(callingUid))) { 23133 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23134 throw new IllegalArgumentException("Unknown package: " + packageName); 23135 } 23136 IBinder ksh = ks.getToken(); 23137 if (ksh instanceof KeySetHandle) { 23138 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23139 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23140 } 23141 return false; 23142 } 23143 } 23144 23145 @Override 23146 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23147 final int callingUid = Binder.getCallingUid(); 23148 if (getInstantAppPackageName(callingUid) != null) { 23149 return false; 23150 } 23151 if (packageName == null || ks == null) { 23152 return false; 23153 } 23154 synchronized(mPackages) { 23155 final PackageParser.Package pkg = mPackages.get(packageName); 23156 if (pkg == null 23157 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23158 UserHandle.getUserId(callingUid))) { 23159 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23160 throw new IllegalArgumentException("Unknown package: " + packageName); 23161 } 23162 IBinder ksh = ks.getToken(); 23163 if (ksh instanceof KeySetHandle) { 23164 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23165 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23166 } 23167 return false; 23168 } 23169 } 23170 23171 private void deletePackageIfUnusedLPr(final String packageName) { 23172 PackageSetting ps = mSettings.mPackages.get(packageName); 23173 if (ps == null) { 23174 return; 23175 } 23176 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23177 // TODO Implement atomic delete if package is unused 23178 // It is currently possible that the package will be deleted even if it is installed 23179 // after this method returns. 23180 mHandler.post(new Runnable() { 23181 public void run() { 23182 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23183 0, PackageManager.DELETE_ALL_USERS); 23184 } 23185 }); 23186 } 23187 } 23188 23189 /** 23190 * Check and throw if the given before/after packages would be considered a 23191 * downgrade. 23192 */ 23193 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23194 throws PackageManagerException { 23195 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23196 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23197 "Update version code " + after.versionCode + " is older than current " 23198 + before.getLongVersionCode()); 23199 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23200 if (after.baseRevisionCode < before.baseRevisionCode) { 23201 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23202 "Update base revision code " + after.baseRevisionCode 23203 + " is older than current " + before.baseRevisionCode); 23204 } 23205 23206 if (!ArrayUtils.isEmpty(after.splitNames)) { 23207 for (int i = 0; i < after.splitNames.length; i++) { 23208 final String splitName = after.splitNames[i]; 23209 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23210 if (j != -1) { 23211 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23212 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23213 "Update split " + splitName + " revision code " 23214 + after.splitRevisionCodes[i] + " is older than current " 23215 + before.splitRevisionCodes[j]); 23216 } 23217 } 23218 } 23219 } 23220 } 23221 } 23222 23223 private static class MoveCallbacks extends Handler { 23224 private static final int MSG_CREATED = 1; 23225 private static final int MSG_STATUS_CHANGED = 2; 23226 23227 private final RemoteCallbackList<IPackageMoveObserver> 23228 mCallbacks = new RemoteCallbackList<>(); 23229 23230 private final SparseIntArray mLastStatus = new SparseIntArray(); 23231 23232 public MoveCallbacks(Looper looper) { 23233 super(looper); 23234 } 23235 23236 public void register(IPackageMoveObserver callback) { 23237 mCallbacks.register(callback); 23238 } 23239 23240 public void unregister(IPackageMoveObserver callback) { 23241 mCallbacks.unregister(callback); 23242 } 23243 23244 @Override 23245 public void handleMessage(Message msg) { 23246 final SomeArgs args = (SomeArgs) msg.obj; 23247 final int n = mCallbacks.beginBroadcast(); 23248 for (int i = 0; i < n; i++) { 23249 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23250 try { 23251 invokeCallback(callback, msg.what, args); 23252 } catch (RemoteException ignored) { 23253 } 23254 } 23255 mCallbacks.finishBroadcast(); 23256 args.recycle(); 23257 } 23258 23259 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23260 throws RemoteException { 23261 switch (what) { 23262 case MSG_CREATED: { 23263 callback.onCreated(args.argi1, (Bundle) args.arg2); 23264 break; 23265 } 23266 case MSG_STATUS_CHANGED: { 23267 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23268 break; 23269 } 23270 } 23271 } 23272 23273 private void notifyCreated(int moveId, Bundle extras) { 23274 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23275 23276 final SomeArgs args = SomeArgs.obtain(); 23277 args.argi1 = moveId; 23278 args.arg2 = extras; 23279 obtainMessage(MSG_CREATED, args).sendToTarget(); 23280 } 23281 23282 private void notifyStatusChanged(int moveId, int status) { 23283 notifyStatusChanged(moveId, status, -1); 23284 } 23285 23286 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23287 Slog.v(TAG, "Move " + moveId + " status " + status); 23288 23289 final SomeArgs args = SomeArgs.obtain(); 23290 args.argi1 = moveId; 23291 args.argi2 = status; 23292 args.arg3 = estMillis; 23293 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23294 23295 synchronized (mLastStatus) { 23296 mLastStatus.put(moveId, status); 23297 } 23298 } 23299 } 23300 23301 private final static class OnPermissionChangeListeners extends Handler { 23302 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23303 23304 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23305 new RemoteCallbackList<>(); 23306 23307 public OnPermissionChangeListeners(Looper looper) { 23308 super(looper); 23309 } 23310 23311 @Override 23312 public void handleMessage(Message msg) { 23313 switch (msg.what) { 23314 case MSG_ON_PERMISSIONS_CHANGED: { 23315 final int uid = msg.arg1; 23316 handleOnPermissionsChanged(uid); 23317 } break; 23318 } 23319 } 23320 23321 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23322 mPermissionListeners.register(listener); 23323 23324 } 23325 23326 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23327 mPermissionListeners.unregister(listener); 23328 } 23329 23330 public void onPermissionsChanged(int uid) { 23331 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23332 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23333 } 23334 } 23335 23336 private void handleOnPermissionsChanged(int uid) { 23337 final int count = mPermissionListeners.beginBroadcast(); 23338 try { 23339 for (int i = 0; i < count; i++) { 23340 IOnPermissionsChangeListener callback = mPermissionListeners 23341 .getBroadcastItem(i); 23342 try { 23343 callback.onPermissionsChanged(uid); 23344 } catch (RemoteException e) { 23345 Log.e(TAG, "Permission listener is dead", e); 23346 } 23347 } 23348 } finally { 23349 mPermissionListeners.finishBroadcast(); 23350 } 23351 } 23352 } 23353 23354 private class PackageManagerNative extends IPackageManagerNative.Stub { 23355 @Override 23356 public String[] getNamesForUids(int[] uids) throws RemoteException { 23357 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23358 // massage results so they can be parsed by the native binder 23359 for (int i = results.length - 1; i >= 0; --i) { 23360 if (results[i] == null) { 23361 results[i] = ""; 23362 } 23363 } 23364 return results; 23365 } 23366 23367 // NB: this differentiates between preloads and sideloads 23368 @Override 23369 public String getInstallerForPackage(String packageName) throws RemoteException { 23370 final String installerName = getInstallerPackageName(packageName); 23371 if (!TextUtils.isEmpty(installerName)) { 23372 return installerName; 23373 } 23374 // differentiate between preload and sideload 23375 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23376 ApplicationInfo appInfo = getApplicationInfo(packageName, 23377 /*flags*/ 0, 23378 /*userId*/ callingUser); 23379 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23380 return "preload"; 23381 } 23382 return ""; 23383 } 23384 23385 @Override 23386 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23387 try { 23388 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23389 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23390 if (pInfo != null) { 23391 return pInfo.getLongVersionCode(); 23392 } 23393 } catch (Exception e) { 23394 } 23395 return 0; 23396 } 23397 } 23398 23399 private class PackageManagerInternalImpl extends PackageManagerInternal { 23400 @Override 23401 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23402 int flagValues, int userId) { 23403 PackageManagerService.this.updatePermissionFlags( 23404 permName, packageName, flagMask, flagValues, userId); 23405 } 23406 23407 @Override 23408 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 23409 SigningDetails sd = getSigningDetails(packageName); 23410 if (sd == null) { 23411 return false; 23412 } 23413 return sd.hasSha256Certificate(restoringFromSigHash, 23414 SigningDetails.CertCapabilities.INSTALLED_DATA); 23415 } 23416 23417 @Override 23418 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 23419 SigningDetails sd = getSigningDetails(packageName); 23420 if (sd == null) { 23421 return false; 23422 } 23423 return sd.hasCertificate(restoringFromSig, 23424 SigningDetails.CertCapabilities.INSTALLED_DATA); 23425 } 23426 23427 private SigningDetails getSigningDetails(@NonNull String packageName) { 23428 synchronized (mPackages) { 23429 PackageParser.Package p = mPackages.get(packageName); 23430 if (p == null) { 23431 return null; 23432 } 23433 return p.mSigningDetails; 23434 } 23435 } 23436 23437 @Override 23438 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23439 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23440 } 23441 23442 @Override 23443 public boolean isInstantApp(String packageName, int userId) { 23444 return PackageManagerService.this.isInstantApp(packageName, userId); 23445 } 23446 23447 @Override 23448 public String getInstantAppPackageName(int uid) { 23449 return PackageManagerService.this.getInstantAppPackageName(uid); 23450 } 23451 23452 @Override 23453 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23454 synchronized (mPackages) { 23455 return PackageManagerService.this.filterAppAccessLPr( 23456 (PackageSetting) pkg.mExtras, callingUid, userId); 23457 } 23458 } 23459 23460 @Override 23461 public PackageParser.Package getPackage(String packageName) { 23462 synchronized (mPackages) { 23463 packageName = resolveInternalPackageNameLPr( 23464 packageName, PackageManager.VERSION_CODE_HIGHEST); 23465 return mPackages.get(packageName); 23466 } 23467 } 23468 23469 @Override 23470 public PackageList getPackageList(PackageListObserver observer) { 23471 synchronized (mPackages) { 23472 final int N = mPackages.size(); 23473 final ArrayList<String> list = new ArrayList<>(N); 23474 for (int i = 0; i < N; i++) { 23475 list.add(mPackages.keyAt(i)); 23476 } 23477 final PackageList packageList = new PackageList(list, observer); 23478 if (observer != null) { 23479 mPackageListObservers.add(packageList); 23480 } 23481 return packageList; 23482 } 23483 } 23484 23485 @Override 23486 public void removePackageListObserver(PackageListObserver observer) { 23487 synchronized (mPackages) { 23488 mPackageListObservers.remove(observer); 23489 } 23490 } 23491 23492 @Override 23493 public PackageParser.Package getDisabledPackage(String packageName) { 23494 synchronized (mPackages) { 23495 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23496 return (ps != null) ? ps.pkg : null; 23497 } 23498 } 23499 23500 @Override 23501 public String getKnownPackageName(int knownPackage, int userId) { 23502 switch(knownPackage) { 23503 case PackageManagerInternal.PACKAGE_BROWSER: 23504 return getDefaultBrowserPackageName(userId); 23505 case PackageManagerInternal.PACKAGE_INSTALLER: 23506 return mRequiredInstallerPackage; 23507 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23508 return mSetupWizardPackage; 23509 case PackageManagerInternal.PACKAGE_SYSTEM: 23510 return "android"; 23511 case PackageManagerInternal.PACKAGE_VERIFIER: 23512 return mRequiredVerifierPackage; 23513 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23514 return mSystemTextClassifierPackage; 23515 } 23516 return null; 23517 } 23518 23519 @Override 23520 public boolean isResolveActivityComponent(ComponentInfo component) { 23521 return mResolveActivity.packageName.equals(component.packageName) 23522 && mResolveActivity.name.equals(component.name); 23523 } 23524 23525 @Override 23526 public void setLocationPackagesProvider(PackagesProvider provider) { 23527 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23528 } 23529 23530 @Override 23531 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23532 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23533 } 23534 23535 @Override 23536 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23537 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23538 } 23539 23540 @Override 23541 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23542 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23543 } 23544 23545 @Override 23546 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23547 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23548 } 23549 23550 @Override 23551 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23552 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23553 } 23554 23555 @Override 23556 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23557 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23558 } 23559 23560 @Override 23561 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23562 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23563 } 23564 23565 @Override 23566 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23567 synchronized (mPackages) { 23568 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23569 } 23570 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23571 } 23572 23573 @Override 23574 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23575 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23576 packageName, userId); 23577 } 23578 23579 @Override 23580 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23581 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23582 packageName, userId); 23583 } 23584 23585 @Override 23586 public void setKeepUninstalledPackages(final List<String> packageList) { 23587 Preconditions.checkNotNull(packageList); 23588 List<String> removedFromList = null; 23589 synchronized (mPackages) { 23590 if (mKeepUninstalledPackages != null) { 23591 final int packagesCount = mKeepUninstalledPackages.size(); 23592 for (int i = 0; i < packagesCount; i++) { 23593 String oldPackage = mKeepUninstalledPackages.get(i); 23594 if (packageList != null && packageList.contains(oldPackage)) { 23595 continue; 23596 } 23597 if (removedFromList == null) { 23598 removedFromList = new ArrayList<>(); 23599 } 23600 removedFromList.add(oldPackage); 23601 } 23602 } 23603 mKeepUninstalledPackages = new ArrayList<>(packageList); 23604 if (removedFromList != null) { 23605 final int removedCount = removedFromList.size(); 23606 for (int i = 0; i < removedCount; i++) { 23607 deletePackageIfUnusedLPr(removedFromList.get(i)); 23608 } 23609 } 23610 } 23611 } 23612 23613 @Override 23614 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23615 synchronized (mPackages) { 23616 return mPermissionManager.isPermissionsReviewRequired( 23617 mPackages.get(packageName), userId); 23618 } 23619 } 23620 23621 @Override 23622 public PackageInfo getPackageInfo( 23623 String packageName, int flags, int filterCallingUid, int userId) { 23624 return PackageManagerService.this 23625 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23626 flags, filterCallingUid, userId); 23627 } 23628 23629 @Override 23630 public int getPackageUid(String packageName, int flags, int userId) { 23631 return PackageManagerService.this 23632 .getPackageUid(packageName, flags, userId); 23633 } 23634 23635 @Override 23636 public ApplicationInfo getApplicationInfo( 23637 String packageName, int flags, int filterCallingUid, int userId) { 23638 return PackageManagerService.this 23639 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23640 } 23641 23642 @Override 23643 public ActivityInfo getActivityInfo( 23644 ComponentName component, int flags, int filterCallingUid, int userId) { 23645 return PackageManagerService.this 23646 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23647 } 23648 23649 @Override 23650 public List<ResolveInfo> queryIntentActivities( 23651 Intent intent, int flags, int filterCallingUid, int userId) { 23652 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23653 return PackageManagerService.this 23654 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23655 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23656 } 23657 23658 @Override 23659 public List<ResolveInfo> queryIntentServices( 23660 Intent intent, int flags, int callingUid, int userId) { 23661 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23662 return PackageManagerService.this 23663 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23664 false); 23665 } 23666 23667 @Override 23668 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23669 int userId) { 23670 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23671 } 23672 23673 @Override 23674 public ComponentName getDefaultHomeActivity(int userId) { 23675 return PackageManagerService.this.getDefaultHomeActivity(userId); 23676 } 23677 23678 @Override 23679 public void setDeviceAndProfileOwnerPackages( 23680 int deviceOwnerUserId, String deviceOwnerPackage, 23681 SparseArray<String> profileOwnerPackages) { 23682 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23683 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23684 } 23685 23686 @Override 23687 public boolean isPackageDataProtected(int userId, String packageName) { 23688 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23689 } 23690 23691 @Override 23692 public boolean isPackageEphemeral(int userId, String packageName) { 23693 synchronized (mPackages) { 23694 final PackageSetting ps = mSettings.mPackages.get(packageName); 23695 return ps != null ? ps.getInstantApp(userId) : false; 23696 } 23697 } 23698 23699 @Override 23700 public boolean wasPackageEverLaunched(String packageName, int userId) { 23701 synchronized (mPackages) { 23702 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23703 } 23704 } 23705 23706 @Override 23707 public void grantRuntimePermission(String packageName, String permName, int userId, 23708 boolean overridePolicy) { 23709 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23710 permName, packageName, overridePolicy, getCallingUid(), userId, 23711 mPermissionCallback); 23712 } 23713 23714 @Override 23715 public void revokeRuntimePermission(String packageName, String permName, int userId, 23716 boolean overridePolicy) { 23717 mPermissionManager.revokeRuntimePermission( 23718 permName, packageName, overridePolicy, getCallingUid(), userId, 23719 mPermissionCallback); 23720 } 23721 23722 @Override 23723 public String getNameForUid(int uid) { 23724 return PackageManagerService.this.getNameForUid(uid); 23725 } 23726 23727 @Override 23728 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23729 Intent origIntent, String resolvedType, String callingPackage, 23730 Bundle verificationBundle, int userId) { 23731 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23732 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23733 userId); 23734 } 23735 23736 @Override 23737 public void grantEphemeralAccess(int userId, Intent intent, 23738 int targetAppId, int ephemeralAppId) { 23739 synchronized (mPackages) { 23740 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23741 targetAppId, ephemeralAppId); 23742 } 23743 } 23744 23745 @Override 23746 public boolean isInstantAppInstallerComponent(ComponentName component) { 23747 synchronized (mPackages) { 23748 return mInstantAppInstallerActivity != null 23749 && mInstantAppInstallerActivity.getComponentName().equals(component); 23750 } 23751 } 23752 23753 @Override 23754 public void pruneInstantApps() { 23755 mInstantAppRegistry.pruneInstantApps(); 23756 } 23757 23758 @Override 23759 public String getSetupWizardPackageName() { 23760 return mSetupWizardPackage; 23761 } 23762 23763 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23764 if (policy != null) { 23765 mExternalSourcesPolicy = policy; 23766 } 23767 } 23768 23769 @Override 23770 public boolean isPackagePersistent(String packageName) { 23771 synchronized (mPackages) { 23772 PackageParser.Package pkg = mPackages.get(packageName); 23773 return pkg != null 23774 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23775 | ApplicationInfo.FLAG_PERSISTENT)) == 23776 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23777 : false; 23778 } 23779 } 23780 23781 @Override 23782 public boolean isLegacySystemApp(Package pkg) { 23783 synchronized (mPackages) { 23784 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23785 return mPromoteSystemApps 23786 && ps.isSystem() 23787 && mExistingSystemPackages.contains(ps.name); 23788 } 23789 } 23790 23791 @Override 23792 public List<PackageInfo> getOverlayPackages(int userId) { 23793 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23794 synchronized (mPackages) { 23795 for (PackageParser.Package p : mPackages.values()) { 23796 if (p.mOverlayTarget != null) { 23797 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23798 if (pkg != null) { 23799 overlayPackages.add(pkg); 23800 } 23801 } 23802 } 23803 } 23804 return overlayPackages; 23805 } 23806 23807 @Override 23808 public List<String> getTargetPackageNames(int userId) { 23809 List<String> targetPackages = new ArrayList<>(); 23810 synchronized (mPackages) { 23811 for (PackageParser.Package p : mPackages.values()) { 23812 if (p.mOverlayTarget == null) { 23813 targetPackages.add(p.packageName); 23814 } 23815 } 23816 } 23817 return targetPackages; 23818 } 23819 23820 @Override 23821 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23822 @Nullable List<String> overlayPackageNames) { 23823 synchronized (mPackages) { 23824 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23825 Slog.e(TAG, "failed to find package " + targetPackageName); 23826 return false; 23827 } 23828 ArrayList<String> overlayPaths = null; 23829 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23830 final int N = overlayPackageNames.size(); 23831 overlayPaths = new ArrayList<>(N); 23832 for (int i = 0; i < N; i++) { 23833 final String packageName = overlayPackageNames.get(i); 23834 final PackageParser.Package pkg = mPackages.get(packageName); 23835 if (pkg == null) { 23836 Slog.e(TAG, "failed to find package " + packageName); 23837 return false; 23838 } 23839 overlayPaths.add(pkg.baseCodePath); 23840 } 23841 } 23842 23843 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23844 ps.setOverlayPaths(overlayPaths, userId); 23845 return true; 23846 } 23847 } 23848 23849 @Override 23850 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23851 int flags, int userId, boolean resolveForStart) { 23852 return resolveIntentInternal( 23853 intent, resolvedType, flags, userId, resolveForStart); 23854 } 23855 23856 @Override 23857 public ResolveInfo resolveService(Intent intent, String resolvedType, 23858 int flags, int userId, int callingUid) { 23859 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23860 } 23861 23862 @Override 23863 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23864 return PackageManagerService.this.resolveContentProviderInternal( 23865 name, flags, userId); 23866 } 23867 23868 @Override 23869 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23870 synchronized (mPackages) { 23871 mIsolatedOwners.put(isolatedUid, ownerUid); 23872 } 23873 } 23874 23875 @Override 23876 public void removeIsolatedUid(int isolatedUid) { 23877 synchronized (mPackages) { 23878 mIsolatedOwners.delete(isolatedUid); 23879 } 23880 } 23881 23882 @Override 23883 public int getUidTargetSdkVersion(int uid) { 23884 synchronized (mPackages) { 23885 return getUidTargetSdkVersionLockedLPr(uid); 23886 } 23887 } 23888 23889 @Override 23890 public int getPackageTargetSdkVersion(String packageName) { 23891 synchronized (mPackages) { 23892 return getPackageTargetSdkVersionLockedLPr(packageName); 23893 } 23894 } 23895 23896 @Override 23897 public boolean canAccessInstantApps(int callingUid, int userId) { 23898 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23899 } 23900 23901 @Override 23902 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 23903 synchronized (mPackages) { 23904 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 23905 return !PackageManagerService.this.filterAppAccessLPr( 23906 ps, callingUid, component, TYPE_UNKNOWN, userId); 23907 } 23908 } 23909 23910 @Override 23911 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23912 synchronized (mPackages) { 23913 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23914 } 23915 } 23916 23917 @Override 23918 public void notifyPackageUse(String packageName, int reason) { 23919 synchronized (mPackages) { 23920 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23921 } 23922 } 23923 } 23924 23925 @Override 23926 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23927 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23928 synchronized (mPackages) { 23929 final long identity = Binder.clearCallingIdentity(); 23930 try { 23931 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23932 packageNames, userId); 23933 } finally { 23934 Binder.restoreCallingIdentity(identity); 23935 } 23936 } 23937 } 23938 23939 @Override 23940 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23941 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23942 synchronized (mPackages) { 23943 final long identity = Binder.clearCallingIdentity(); 23944 try { 23945 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23946 packageNames, userId); 23947 } finally { 23948 Binder.restoreCallingIdentity(identity); 23949 } 23950 } 23951 } 23952 23953 private static void enforceSystemOrPhoneCaller(String tag) { 23954 int callingUid = Binder.getCallingUid(); 23955 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23956 throw new SecurityException( 23957 "Cannot call " + tag + " from UID " + callingUid); 23958 } 23959 } 23960 23961 boolean isHistoricalPackageUsageAvailable() { 23962 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23963 } 23964 23965 /** 23966 * Return a <b>copy</b> of the collection of packages known to the package manager. 23967 * @return A copy of the values of mPackages. 23968 */ 23969 Collection<PackageParser.Package> getPackages() { 23970 synchronized (mPackages) { 23971 return new ArrayList<>(mPackages.values()); 23972 } 23973 } 23974 23975 /** 23976 * Logs process start information (including base APK hash) to the security log. 23977 * @hide 23978 */ 23979 @Override 23980 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23981 String apkFile, int pid) { 23982 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23983 return; 23984 } 23985 if (!SecurityLog.isLoggingEnabled()) { 23986 return; 23987 } 23988 Bundle data = new Bundle(); 23989 data.putLong("startTimestamp", System.currentTimeMillis()); 23990 data.putString("processName", processName); 23991 data.putInt("uid", uid); 23992 data.putString("seinfo", seinfo); 23993 data.putString("apkFile", apkFile); 23994 data.putInt("pid", pid); 23995 Message msg = mProcessLoggingHandler.obtainMessage( 23996 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23997 msg.setData(data); 23998 mProcessLoggingHandler.sendMessage(msg); 23999 } 24000 24001 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24002 return mCompilerStats.getPackageStats(pkgName); 24003 } 24004 24005 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24006 return getOrCreateCompilerPackageStats(pkg.packageName); 24007 } 24008 24009 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24010 return mCompilerStats.getOrCreatePackageStats(pkgName); 24011 } 24012 24013 public void deleteCompilerPackageStats(String pkgName) { 24014 mCompilerStats.deletePackageStats(pkgName); 24015 } 24016 24017 @Override 24018 public int getInstallReason(String packageName, int userId) { 24019 final int callingUid = Binder.getCallingUid(); 24020 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24021 true /* requireFullPermission */, false /* checkShell */, 24022 "get install reason"); 24023 synchronized (mPackages) { 24024 final PackageSetting ps = mSettings.mPackages.get(packageName); 24025 if (filterAppAccessLPr(ps, callingUid, userId)) { 24026 return PackageManager.INSTALL_REASON_UNKNOWN; 24027 } 24028 if (ps != null) { 24029 return ps.getInstallReason(userId); 24030 } 24031 } 24032 return PackageManager.INSTALL_REASON_UNKNOWN; 24033 } 24034 24035 @Override 24036 public boolean canRequestPackageInstalls(String packageName, int userId) { 24037 return canRequestPackageInstallsInternal(packageName, 0, userId, 24038 true /* throwIfPermNotDeclared*/); 24039 } 24040 24041 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24042 boolean throwIfPermNotDeclared) { 24043 int callingUid = Binder.getCallingUid(); 24044 int uid = getPackageUid(packageName, 0, userId); 24045 if (callingUid != uid && callingUid != Process.ROOT_UID 24046 && callingUid != Process.SYSTEM_UID) { 24047 throw new SecurityException( 24048 "Caller uid " + callingUid + " does not own package " + packageName); 24049 } 24050 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24051 if (info == null) { 24052 return false; 24053 } 24054 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24055 return false; 24056 } 24057 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24058 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24059 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24060 if (throwIfPermNotDeclared) { 24061 throw new SecurityException("Need to declare " + appOpPermission 24062 + " to call this api"); 24063 } else { 24064 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24065 return false; 24066 } 24067 } 24068 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 24069 return false; 24070 } 24071 if (mExternalSourcesPolicy != null) { 24072 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24073 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 24074 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24075 } 24076 } 24077 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 24078 } 24079 24080 @Override 24081 public ComponentName getInstantAppResolverSettingsComponent() { 24082 return mInstantAppResolverSettingsComponent; 24083 } 24084 24085 @Override 24086 public ComponentName getInstantAppInstallerComponent() { 24087 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24088 return null; 24089 } 24090 return mInstantAppInstallerActivity == null 24091 ? null : mInstantAppInstallerActivity.getComponentName(); 24092 } 24093 24094 @Override 24095 public String getInstantAppAndroidId(String packageName, int userId) { 24096 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24097 "getInstantAppAndroidId"); 24098 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 24099 true /* requireFullPermission */, false /* checkShell */, 24100 "getInstantAppAndroidId"); 24101 // Make sure the target is an Instant App. 24102 if (!isInstantApp(packageName, userId)) { 24103 return null; 24104 } 24105 synchronized (mPackages) { 24106 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24107 } 24108 } 24109 24110 boolean canHaveOatDir(String packageName) { 24111 synchronized (mPackages) { 24112 PackageParser.Package p = mPackages.get(packageName); 24113 if (p == null) { 24114 return false; 24115 } 24116 return p.canHaveOatDir(); 24117 } 24118 } 24119 24120 private String getOatDir(PackageParser.Package pkg) { 24121 if (!pkg.canHaveOatDir()) { 24122 return null; 24123 } 24124 File codePath = new File(pkg.codePath); 24125 if (codePath.isDirectory()) { 24126 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24127 } 24128 return null; 24129 } 24130 24131 void deleteOatArtifactsOfPackage(String packageName) { 24132 final String[] instructionSets; 24133 final List<String> codePaths; 24134 final String oatDir; 24135 final PackageParser.Package pkg; 24136 synchronized (mPackages) { 24137 pkg = mPackages.get(packageName); 24138 } 24139 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24140 codePaths = pkg.getAllCodePaths(); 24141 oatDir = getOatDir(pkg); 24142 24143 for (String codePath : codePaths) { 24144 for (String isa : instructionSets) { 24145 try { 24146 mInstaller.deleteOdex(codePath, isa, oatDir); 24147 } catch (InstallerException e) { 24148 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24149 } 24150 } 24151 } 24152 } 24153 24154 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24155 Set<String> unusedPackages = new HashSet<>(); 24156 long currentTimeInMillis = System.currentTimeMillis(); 24157 synchronized (mPackages) { 24158 for (PackageParser.Package pkg : mPackages.values()) { 24159 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24160 if (ps == null) { 24161 continue; 24162 } 24163 PackageDexUsage.PackageUseInfo packageUseInfo = 24164 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24165 if (PackageManagerServiceUtils 24166 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24167 downgradeTimeThresholdMillis, packageUseInfo, 24168 pkg.getLatestPackageUseTimeInMills(), 24169 pkg.getLatestForegroundPackageUseTimeInMills())) { 24170 unusedPackages.add(pkg.packageName); 24171 } 24172 } 24173 } 24174 return unusedPackages; 24175 } 24176 24177 @Override 24178 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24179 int userId) { 24180 final int callingUid = Binder.getCallingUid(); 24181 final int callingAppId = UserHandle.getAppId(callingUid); 24182 24183 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24184 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24185 24186 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24187 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24188 throw new SecurityException("Caller must have the " 24189 + SET_HARMFUL_APP_WARNINGS + " permission."); 24190 } 24191 24192 synchronized(mPackages) { 24193 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24194 scheduleWritePackageRestrictionsLocked(userId); 24195 } 24196 } 24197 24198 @Nullable 24199 @Override 24200 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24201 final int callingUid = Binder.getCallingUid(); 24202 final int callingAppId = UserHandle.getAppId(callingUid); 24203 24204 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24205 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24206 24207 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24208 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24209 throw new SecurityException("Caller must have the " 24210 + SET_HARMFUL_APP_WARNINGS + " permission."); 24211 } 24212 24213 synchronized(mPackages) { 24214 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24215 } 24216 } 24217 24218 @Override 24219 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 24220 final int callingUid = Binder.getCallingUid(); 24221 final int callingAppId = UserHandle.getAppId(callingUid); 24222 24223 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24224 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected"); 24225 24226 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID 24227 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) { 24228 throw new SecurityException("Caller must have the " 24229 + MANAGE_DEVICE_ADMINS + " permission."); 24230 } 24231 24232 return mProtectedPackages.isPackageStateProtected(userId, packageName); 24233 } 24234} 24235 24236interface PackageSender { 24237 /** 24238 * @param userIds User IDs where the action occurred on a full application 24239 * @param instantUserIds User IDs where the action occurred on an instant application 24240 */ 24241 void sendPackageBroadcast(final String action, final String pkg, 24242 final Bundle extras, final int flags, final String targetPkg, 24243 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24244 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24245 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24246 void notifyPackageAdded(String packageName); 24247 void notifyPackageRemoved(String packageName); 24248} 24249