PackageManagerService.java revision 1713d9e97aada3dc695800c18b1025238a11629d
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.DELETE_PACKAGES; 20import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 21import static android.Manifest.permission.INSTALL_PACKAGES; 22import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 26import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 27import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 32import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 33import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 34import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 40import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 41import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 42import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 43import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 44import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 45import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 46import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 50import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 51import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 52import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 53import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 54import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 111import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasCertificate; 112import static com.android.server.pm.PackageManagerServiceUtils.signingDetailsHasSha256Certificate; 113import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 116import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 117 118import android.Manifest; 119import android.annotation.IntDef; 120import android.annotation.NonNull; 121import android.annotation.Nullable; 122import android.app.ActivityManager; 123import android.app.ActivityManagerInternal; 124import android.app.AppOpsManager; 125import android.app.IActivityManager; 126import android.app.ResourcesManager; 127import android.app.admin.IDevicePolicyManager; 128import android.app.admin.SecurityLog; 129import android.app.backup.IBackupManager; 130import android.content.BroadcastReceiver; 131import android.content.ComponentName; 132import android.content.ContentResolver; 133import android.content.Context; 134import android.content.IIntentReceiver; 135import android.content.Intent; 136import android.content.IntentFilter; 137import android.content.IntentSender; 138import android.content.IntentSender.SendIntentException; 139import android.content.ServiceConnection; 140import android.content.pm.ActivityInfo; 141import android.content.pm.ApplicationInfo; 142import android.content.pm.AppsQueryHelper; 143import android.content.pm.AuxiliaryResolveInfo; 144import android.content.pm.ChangedPackages; 145import android.content.pm.ComponentInfo; 146import android.content.pm.FallbackCategoryProvider; 147import android.content.pm.FeatureInfo; 148import android.content.pm.IDexModuleRegisterCallback; 149import android.content.pm.IOnPermissionsChangeListener; 150import android.content.pm.IPackageDataObserver; 151import android.content.pm.IPackageDeleteObserver; 152import android.content.pm.IPackageDeleteObserver2; 153import android.content.pm.IPackageInstallObserver2; 154import android.content.pm.IPackageInstaller; 155import android.content.pm.IPackageManager; 156import android.content.pm.IPackageManagerNative; 157import android.content.pm.IPackageMoveObserver; 158import android.content.pm.IPackageStatsObserver; 159import android.content.pm.InstantAppInfo; 160import android.content.pm.InstantAppRequest; 161import android.content.pm.InstantAppResolveInfo; 162import android.content.pm.InstrumentationInfo; 163import android.content.pm.IntentFilterVerificationInfo; 164import android.content.pm.KeySet; 165import android.content.pm.PackageCleanItem; 166import android.content.pm.PackageInfo; 167import android.content.pm.PackageInfoLite; 168import android.content.pm.PackageInstaller; 169import android.content.pm.PackageList; 170import android.content.pm.PackageManager; 171import android.content.pm.PackageManagerInternal; 172import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 173import android.content.pm.PackageManagerInternal.PackageListObserver; 174import android.content.pm.PackageParser; 175import android.content.pm.PackageParser.ActivityIntentInfo; 176import android.content.pm.PackageParser.Package; 177import android.content.pm.PackageParser.PackageLite; 178import android.content.pm.PackageParser.PackageParserException; 179import android.content.pm.PackageParser.ParseFlags; 180import android.content.pm.PackageParser.ServiceIntentInfo; 181import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 182import android.content.pm.PackageStats; 183import android.content.pm.PackageUserState; 184import android.content.pm.ParceledListSlice; 185import android.content.pm.PermissionGroupInfo; 186import android.content.pm.PermissionInfo; 187import android.content.pm.ProviderInfo; 188import android.content.pm.ResolveInfo; 189import android.content.pm.ServiceInfo; 190import android.content.pm.SharedLibraryInfo; 191import android.content.pm.Signature; 192import android.content.pm.UserInfo; 193import android.content.pm.VerifierDeviceIdentity; 194import android.content.pm.VerifierInfo; 195import android.content.pm.VersionedPackage; 196import android.content.pm.dex.DexMetadataHelper; 197import android.content.pm.dex.IArtManager; 198import android.content.res.Resources; 199import android.database.ContentObserver; 200import android.graphics.Bitmap; 201import android.hardware.display.DisplayManager; 202import android.net.Uri; 203import android.os.Binder; 204import android.os.Build; 205import android.os.Bundle; 206import android.os.Debug; 207import android.os.Environment; 208import android.os.Environment.UserEnvironment; 209import android.os.FileUtils; 210import android.os.Handler; 211import android.os.IBinder; 212import android.os.Looper; 213import android.os.Message; 214import android.os.Parcel; 215import android.os.ParcelFileDescriptor; 216import android.os.PatternMatcher; 217import android.os.Process; 218import android.os.RemoteCallbackList; 219import android.os.RemoteException; 220import android.os.ResultReceiver; 221import android.os.SELinux; 222import android.os.ServiceManager; 223import android.os.ShellCallback; 224import android.os.SystemClock; 225import android.os.SystemProperties; 226import android.os.Trace; 227import android.os.UserHandle; 228import android.os.UserManager; 229import android.os.UserManagerInternal; 230import android.os.storage.IStorageManager; 231import android.os.storage.StorageEventListener; 232import android.os.storage.StorageManager; 233import android.os.storage.StorageManagerInternal; 234import android.os.storage.VolumeInfo; 235import android.os.storage.VolumeRecord; 236import android.provider.Settings.Global; 237import android.provider.Settings.Secure; 238import android.security.KeyStore; 239import android.security.SystemKeyStore; 240import android.service.pm.PackageServiceDumpProto; 241import android.system.ErrnoException; 242import android.system.Os; 243import android.text.TextUtils; 244import android.text.format.DateUtils; 245import android.util.ArrayMap; 246import android.util.ArraySet; 247import android.util.Base64; 248import android.util.DisplayMetrics; 249import android.util.EventLog; 250import android.util.ExceptionUtils; 251import android.util.Log; 252import android.util.LogPrinter; 253import android.util.LongSparseArray; 254import android.util.LongSparseLongArray; 255import android.util.MathUtils; 256import android.util.PackageUtils; 257import android.util.Pair; 258import android.util.PrintStreamPrinter; 259import android.util.Slog; 260import android.util.SparseArray; 261import android.util.SparseBooleanArray; 262import android.util.SparseIntArray; 263import android.util.TimingsTraceLog; 264import android.util.Xml; 265import android.util.jar.StrictJarFile; 266import android.util.proto.ProtoOutputStream; 267import android.view.Display; 268 269import com.android.internal.R; 270import com.android.internal.annotations.GuardedBy; 271import com.android.internal.app.IMediaContainerService; 272import com.android.internal.app.ResolverActivity; 273import com.android.internal.content.NativeLibraryHelper; 274import com.android.internal.content.PackageHelper; 275import com.android.internal.logging.MetricsLogger; 276import com.android.internal.os.IParcelFileDescriptorFactory; 277import com.android.internal.os.SomeArgs; 278import com.android.internal.os.Zygote; 279import com.android.internal.telephony.CarrierAppUtils; 280import com.android.internal.util.ArrayUtils; 281import com.android.internal.util.ConcurrentUtils; 282import com.android.internal.util.DumpUtils; 283import com.android.internal.util.FastXmlSerializer; 284import com.android.internal.util.IndentingPrintWriter; 285import com.android.internal.util.Preconditions; 286import com.android.internal.util.XmlUtils; 287import com.android.server.AttributeCache; 288import com.android.server.DeviceIdleController; 289import com.android.server.EventLogTags; 290import com.android.server.FgThread; 291import com.android.server.IntentResolver; 292import com.android.server.LocalServices; 293import com.android.server.LockGuard; 294import com.android.server.ServiceThread; 295import com.android.server.SystemConfig; 296import com.android.server.SystemServerInitThreadPool; 297import com.android.server.Watchdog; 298import com.android.server.net.NetworkPolicyManagerInternal; 299import com.android.server.pm.Installer.InstallerException; 300import com.android.server.pm.Settings.DatabaseVersion; 301import com.android.server.pm.Settings.VersionInfo; 302import com.android.server.pm.dex.ArtManagerService; 303import com.android.server.pm.dex.DexLogger; 304import com.android.server.pm.dex.DexManager; 305import com.android.server.pm.dex.DexoptOptions; 306import com.android.server.pm.dex.PackageDexUsage; 307import com.android.server.pm.permission.BasePermission; 308import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 309import com.android.server.pm.permission.PermissionManagerService; 310import com.android.server.pm.permission.PermissionManagerInternal; 311import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 312import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 313import com.android.server.pm.permission.PermissionsState; 314import com.android.server.pm.permission.PermissionsState.PermissionState; 315import com.android.server.security.VerityUtils; 316import com.android.server.storage.DeviceStorageMonitorInternal; 317 318import dalvik.system.CloseGuard; 319import dalvik.system.VMRuntime; 320 321import libcore.io.IoUtils; 322 323import org.xmlpull.v1.XmlPullParser; 324import org.xmlpull.v1.XmlPullParserException; 325import org.xmlpull.v1.XmlSerializer; 326 327import java.io.BufferedOutputStream; 328import java.io.ByteArrayInputStream; 329import java.io.ByteArrayOutputStream; 330import java.io.File; 331import java.io.FileDescriptor; 332import java.io.FileInputStream; 333import java.io.FileOutputStream; 334import java.io.FilenameFilter; 335import java.io.IOException; 336import java.io.PrintWriter; 337import java.lang.annotation.Retention; 338import java.lang.annotation.RetentionPolicy; 339import java.nio.charset.StandardCharsets; 340import java.security.DigestInputStream; 341import java.security.MessageDigest; 342import java.security.NoSuchAlgorithmException; 343import java.security.PublicKey; 344import java.security.SecureRandom; 345import java.security.cert.CertificateException; 346import java.util.ArrayList; 347import java.util.Arrays; 348import java.util.Collection; 349import java.util.Collections; 350import java.util.Comparator; 351import java.util.HashMap; 352import java.util.HashSet; 353import java.util.Iterator; 354import java.util.LinkedHashSet; 355import java.util.List; 356import java.util.Map; 357import java.util.Objects; 358import java.util.Set; 359import java.util.concurrent.CountDownLatch; 360import java.util.concurrent.Future; 361import java.util.concurrent.TimeUnit; 362import java.util.concurrent.atomic.AtomicBoolean; 363import java.util.concurrent.atomic.AtomicInteger; 364 365/** 366 * Keep track of all those APKs everywhere. 367 * <p> 368 * Internally there are two important locks: 369 * <ul> 370 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 371 * and other related state. It is a fine-grained lock that should only be held 372 * momentarily, as it's one of the most contended locks in the system. 373 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 374 * operations typically involve heavy lifting of application data on disk. Since 375 * {@code installd} is single-threaded, and it's operations can often be slow, 376 * this lock should never be acquired while already holding {@link #mPackages}. 377 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 378 * holding {@link #mInstallLock}. 379 * </ul> 380 * Many internal methods rely on the caller to hold the appropriate locks, and 381 * this contract is expressed through method name suffixes: 382 * <ul> 383 * <li>fooLI(): the caller must hold {@link #mInstallLock} 384 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 385 * being modified must be frozen 386 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 387 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 388 * </ul> 389 * <p> 390 * Because this class is very central to the platform's security; please run all 391 * CTS and unit tests whenever making modifications: 392 * 393 * <pre> 394 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 395 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 396 * </pre> 397 */ 398public class PackageManagerService extends IPackageManager.Stub 399 implements PackageSender { 400 static final String TAG = "PackageManager"; 401 public static final boolean DEBUG_SETTINGS = false; 402 static final boolean DEBUG_PREFERRED = false; 403 static final boolean DEBUG_UPGRADE = false; 404 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 405 private static final boolean DEBUG_BACKUP = false; 406 public static final boolean DEBUG_INSTALL = false; 407 public static final boolean DEBUG_REMOVE = false; 408 private static final boolean DEBUG_BROADCASTS = false; 409 private static final boolean DEBUG_SHOW_INFO = false; 410 private static final boolean DEBUG_PACKAGE_INFO = false; 411 private static final boolean DEBUG_INTENT_MATCHING = false; 412 public static final boolean DEBUG_PACKAGE_SCANNING = false; 413 private static final boolean DEBUG_VERIFY = false; 414 private static final boolean DEBUG_FILTERS = false; 415 public static final boolean DEBUG_PERMISSIONS = false; 416 private static final boolean DEBUG_SHARED_LIBRARIES = false; 417 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 418 419 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 420 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 421 // user, but by default initialize to this. 422 public static final boolean DEBUG_DEXOPT = false; 423 424 private static final boolean DEBUG_ABI_SELECTION = false; 425 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 426 private static final boolean DEBUG_TRIAGED_MISSING = false; 427 private static final boolean DEBUG_APP_DATA = false; 428 429 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 430 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 431 432 private static final boolean HIDE_EPHEMERAL_APIS = false; 433 434 private static final boolean ENABLE_FREE_CACHE_V2 = 435 SystemProperties.getBoolean("fw.free_cache_v2", true); 436 437 private static final int RADIO_UID = Process.PHONE_UID; 438 private static final int LOG_UID = Process.LOG_UID; 439 private static final int NFC_UID = Process.NFC_UID; 440 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 441 private static final int SHELL_UID = Process.SHELL_UID; 442 443 // Suffix used during package installation when copying/moving 444 // package apks to install directory. 445 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 446 447 static final int SCAN_NO_DEX = 1<<0; 448 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 449 static final int SCAN_NEW_INSTALL = 1<<2; 450 static final int SCAN_UPDATE_TIME = 1<<3; 451 static final int SCAN_BOOTING = 1<<4; 452 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 453 static final int SCAN_REQUIRE_KNOWN = 1<<7; 454 static final int SCAN_MOVE = 1<<8; 455 static final int SCAN_INITIAL = 1<<9; 456 static final int SCAN_CHECK_ONLY = 1<<10; 457 static final int SCAN_DONT_KILL_APP = 1<<11; 458 static final int SCAN_IGNORE_FROZEN = 1<<12; 459 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 460 static final int SCAN_AS_INSTANT_APP = 1<<14; 461 static final int SCAN_AS_FULL_APP = 1<<15; 462 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 463 static final int SCAN_AS_SYSTEM = 1<<17; 464 static final int SCAN_AS_PRIVILEGED = 1<<18; 465 static final int SCAN_AS_OEM = 1<<19; 466 static final int SCAN_AS_VENDOR = 1<<20; 467 static final int SCAN_AS_PRODUCT = 1<<21; 468 469 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 470 SCAN_NO_DEX, 471 SCAN_UPDATE_SIGNATURE, 472 SCAN_NEW_INSTALL, 473 SCAN_UPDATE_TIME, 474 SCAN_BOOTING, 475 SCAN_DELETE_DATA_ON_FAILURES, 476 SCAN_REQUIRE_KNOWN, 477 SCAN_MOVE, 478 SCAN_INITIAL, 479 SCAN_CHECK_ONLY, 480 SCAN_DONT_KILL_APP, 481 SCAN_IGNORE_FROZEN, 482 SCAN_FIRST_BOOT_OR_UPGRADE, 483 SCAN_AS_INSTANT_APP, 484 SCAN_AS_FULL_APP, 485 SCAN_AS_VIRTUAL_PRELOAD, 486 }) 487 @Retention(RetentionPolicy.SOURCE) 488 public @interface ScanFlags {} 489 490 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 491 /** Extension of the compressed packages */ 492 public final static String COMPRESSED_EXTENSION = ".gz"; 493 /** Suffix of stub packages on the system partition */ 494 public final static String STUB_SUFFIX = "-Stub"; 495 496 private static final int[] EMPTY_INT_ARRAY = new int[0]; 497 498 private static final int TYPE_UNKNOWN = 0; 499 private static final int TYPE_ACTIVITY = 1; 500 private static final int TYPE_RECEIVER = 2; 501 private static final int TYPE_SERVICE = 3; 502 private static final int TYPE_PROVIDER = 4; 503 @IntDef(prefix = { "TYPE_" }, value = { 504 TYPE_UNKNOWN, 505 TYPE_ACTIVITY, 506 TYPE_RECEIVER, 507 TYPE_SERVICE, 508 TYPE_PROVIDER, 509 }) 510 @Retention(RetentionPolicy.SOURCE) 511 public @interface ComponentType {} 512 513 /** 514 * Timeout (in milliseconds) after which the watchdog should declare that 515 * our handler thread is wedged. The usual default for such things is one 516 * minute but we sometimes do very lengthy I/O operations on this thread, 517 * such as installing multi-gigabyte applications, so ours needs to be longer. 518 */ 519 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 520 521 /** 522 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 523 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 524 * settings entry if available, otherwise we use the hardcoded default. If it's been 525 * more than this long since the last fstrim, we force one during the boot sequence. 526 * 527 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 528 * one gets run at the next available charging+idle time. This final mandatory 529 * no-fstrim check kicks in only of the other scheduling criteria is never met. 530 */ 531 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 532 533 /** 534 * Whether verification is enabled by default. 535 */ 536 private static final boolean DEFAULT_VERIFY_ENABLE = true; 537 538 /** 539 * The default maximum time to wait for the verification agent to return in 540 * milliseconds. 541 */ 542 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 543 544 /** 545 * The default response for package verification timeout. 546 * 547 * This can be either PackageManager.VERIFICATION_ALLOW or 548 * PackageManager.VERIFICATION_REJECT. 549 */ 550 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 551 552 public static final String PLATFORM_PACKAGE_NAME = "android"; 553 554 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 555 556 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 557 DEFAULT_CONTAINER_PACKAGE, 558 "com.android.defcontainer.DefaultContainerService"); 559 560 private static final String KILL_APP_REASON_GIDS_CHANGED = 561 "permission grant or revoke changed gids"; 562 563 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 564 "permissions revoked"; 565 566 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 567 568 private static final String PACKAGE_SCHEME = "package"; 569 570 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 571 572 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 573 574 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 575 576 /** Canonical intent used to identify what counts as a "web browser" app */ 577 private static final Intent sBrowserIntent; 578 static { 579 sBrowserIntent = new Intent(); 580 sBrowserIntent.setAction(Intent.ACTION_VIEW); 581 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 582 sBrowserIntent.setData(Uri.parse("http:")); 583 } 584 585 /** 586 * The set of all protected actions [i.e. those actions for which a high priority 587 * intent filter is disallowed]. 588 */ 589 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 590 static { 591 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 592 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 593 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 594 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 595 } 596 597 // Compilation reasons. 598 public static final int REASON_FIRST_BOOT = 0; 599 public static final int REASON_BOOT = 1; 600 public static final int REASON_INSTALL = 2; 601 public static final int REASON_BACKGROUND_DEXOPT = 3; 602 public static final int REASON_AB_OTA = 4; 603 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 604 public static final int REASON_SHARED = 6; 605 606 public static final int REASON_LAST = REASON_SHARED; 607 608 /** 609 * Version number for the package parser cache. Increment this whenever the format or 610 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 611 */ 612 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 613 614 /** 615 * Whether the package parser cache is enabled. 616 */ 617 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 618 619 /** 620 * Permissions required in order to receive instant application lifecycle broadcasts. 621 */ 622 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 623 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 624 625 final ServiceThread mHandlerThread; 626 627 final PackageHandler mHandler; 628 629 private final ProcessLoggingHandler mProcessLoggingHandler; 630 631 /** 632 * Messages for {@link #mHandler} that need to wait for system ready before 633 * being dispatched. 634 */ 635 private ArrayList<Message> mPostSystemReadyMessages; 636 637 final int mSdkVersion = Build.VERSION.SDK_INT; 638 639 final Context mContext; 640 final boolean mFactoryTest; 641 final boolean mOnlyCore; 642 final DisplayMetrics mMetrics; 643 final int mDefParseFlags; 644 final String[] mSeparateProcesses; 645 final boolean mIsUpgrade; 646 final boolean mIsPreNUpgrade; 647 final boolean mIsPreNMR1Upgrade; 648 649 // Have we told the Activity Manager to whitelist the default container service by uid yet? 650 @GuardedBy("mPackages") 651 boolean mDefaultContainerWhitelisted = false; 652 653 @GuardedBy("mPackages") 654 private boolean mDexOptDialogShown; 655 656 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 657 // LOCK HELD. Can be called with mInstallLock held. 658 @GuardedBy("mInstallLock") 659 final Installer mInstaller; 660 661 /** Directory where installed applications are stored */ 662 private static final File sAppInstallDir = 663 new File(Environment.getDataDirectory(), "app"); 664 /** Directory where installed application's 32-bit native libraries are copied. */ 665 private static final File sAppLib32InstallDir = 666 new File(Environment.getDataDirectory(), "app-lib"); 667 /** Directory where code and non-resource assets of forward-locked applications are stored */ 668 private static final File sDrmAppPrivateInstallDir = 669 new File(Environment.getDataDirectory(), "app-private"); 670 671 // ---------------------------------------------------------------- 672 673 // Lock for state used when installing and doing other long running 674 // operations. Methods that must be called with this lock held have 675 // the suffix "LI". 676 final Object mInstallLock = new Object(); 677 678 // ---------------------------------------------------------------- 679 680 // Keys are String (package name), values are Package. This also serves 681 // as the lock for the global state. Methods that must be called with 682 // this lock held have the prefix "LP". 683 @GuardedBy("mPackages") 684 final ArrayMap<String, PackageParser.Package> mPackages = 685 new ArrayMap<String, PackageParser.Package>(); 686 687 final ArrayMap<String, Set<String>> mKnownCodebase = 688 new ArrayMap<String, Set<String>>(); 689 690 // Keys are isolated uids and values are the uid of the application 691 // that created the isolated proccess. 692 @GuardedBy("mPackages") 693 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 694 695 /** 696 * Tracks new system packages [received in an OTA] that we expect to 697 * find updated user-installed versions. Keys are package name, values 698 * are package location. 699 */ 700 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 701 /** 702 * Tracks high priority intent filters for protected actions. During boot, certain 703 * filter actions are protected and should never be allowed to have a high priority 704 * intent filter for them. However, there is one, and only one exception -- the 705 * setup wizard. It must be able to define a high priority intent filter for these 706 * actions to ensure there are no escapes from the wizard. We need to delay processing 707 * of these during boot as we need to look at all of the system packages in order 708 * to know which component is the setup wizard. 709 */ 710 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 711 /** 712 * Whether or not processing protected filters should be deferred. 713 */ 714 private boolean mDeferProtectedFilters = true; 715 716 /** 717 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 718 */ 719 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 720 /** 721 * Whether or not system app permissions should be promoted from install to runtime. 722 */ 723 boolean mPromoteSystemApps; 724 725 @GuardedBy("mPackages") 726 final Settings mSettings; 727 728 /** 729 * Set of package names that are currently "frozen", which means active 730 * surgery is being done on the code/data for that package. The platform 731 * will refuse to launch frozen packages to avoid race conditions. 732 * 733 * @see PackageFreezer 734 */ 735 @GuardedBy("mPackages") 736 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 737 738 final ProtectedPackages mProtectedPackages; 739 740 @GuardedBy("mLoadedVolumes") 741 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 742 743 boolean mFirstBoot; 744 745 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 746 747 @GuardedBy("mAvailableFeatures") 748 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 749 750 private final InstantAppRegistry mInstantAppRegistry; 751 752 @GuardedBy("mPackages") 753 int mChangedPackagesSequenceNumber; 754 /** 755 * List of changed [installed, removed or updated] packages. 756 * mapping from user id -> sequence number -> package name 757 */ 758 @GuardedBy("mPackages") 759 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 760 /** 761 * The sequence number of the last change to a package. 762 * mapping from user id -> package name -> sequence number 763 */ 764 @GuardedBy("mPackages") 765 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 766 767 @GuardedBy("mPackages") 768 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 769 770 class PackageParserCallback implements PackageParser.Callback { 771 @Override public final boolean hasFeature(String feature) { 772 return PackageManagerService.this.hasSystemFeature(feature, 0); 773 } 774 775 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 776 Collection<PackageParser.Package> allPackages, String targetPackageName) { 777 List<PackageParser.Package> overlayPackages = null; 778 for (PackageParser.Package p : allPackages) { 779 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 780 if (overlayPackages == null) { 781 overlayPackages = new ArrayList<PackageParser.Package>(); 782 } 783 overlayPackages.add(p); 784 } 785 } 786 if (overlayPackages != null) { 787 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 788 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 789 return p1.mOverlayPriority - p2.mOverlayPriority; 790 } 791 }; 792 Collections.sort(overlayPackages, cmp); 793 } 794 return overlayPackages; 795 } 796 797 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 798 String targetPackageName, String targetPath) { 799 if ("android".equals(targetPackageName)) { 800 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 801 // native AssetManager. 802 return null; 803 } 804 List<PackageParser.Package> overlayPackages = 805 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 806 if (overlayPackages == null || overlayPackages.isEmpty()) { 807 return null; 808 } 809 List<String> overlayPathList = null; 810 for (PackageParser.Package overlayPackage : overlayPackages) { 811 if (targetPath == null) { 812 if (overlayPathList == null) { 813 overlayPathList = new ArrayList<String>(); 814 } 815 overlayPathList.add(overlayPackage.baseCodePath); 816 continue; 817 } 818 819 try { 820 // Creates idmaps for system to parse correctly the Android manifest of the 821 // target package. 822 // 823 // OverlayManagerService will update each of them with a correct gid from its 824 // target package app id. 825 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 826 UserHandle.getSharedAppGid( 827 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 828 if (overlayPathList == null) { 829 overlayPathList = new ArrayList<String>(); 830 } 831 overlayPathList.add(overlayPackage.baseCodePath); 832 } catch (InstallerException e) { 833 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 834 overlayPackage.baseCodePath); 835 } 836 } 837 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 838 } 839 840 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 841 synchronized (mPackages) { 842 return getStaticOverlayPathsLocked( 843 mPackages.values(), targetPackageName, targetPath); 844 } 845 } 846 847 @Override public final String[] getOverlayApks(String targetPackageName) { 848 return getStaticOverlayPaths(targetPackageName, null); 849 } 850 851 @Override public final String[] getOverlayPaths(String targetPackageName, 852 String targetPath) { 853 return getStaticOverlayPaths(targetPackageName, targetPath); 854 } 855 } 856 857 class ParallelPackageParserCallback extends PackageParserCallback { 858 List<PackageParser.Package> mOverlayPackages = null; 859 860 void findStaticOverlayPackages() { 861 synchronized (mPackages) { 862 for (PackageParser.Package p : mPackages.values()) { 863 if (p.mOverlayIsStatic) { 864 if (mOverlayPackages == null) { 865 mOverlayPackages = new ArrayList<PackageParser.Package>(); 866 } 867 mOverlayPackages.add(p); 868 } 869 } 870 } 871 } 872 873 @Override 874 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 875 // We can trust mOverlayPackages without holding mPackages because package uninstall 876 // can't happen while running parallel parsing. 877 // Moreover holding mPackages on each parsing thread causes dead-lock. 878 return mOverlayPackages == null ? null : 879 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 880 } 881 } 882 883 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 884 final ParallelPackageParserCallback mParallelPackageParserCallback = 885 new ParallelPackageParserCallback(); 886 887 public static final class SharedLibraryEntry { 888 public final @Nullable String path; 889 public final @Nullable String apk; 890 public final @NonNull SharedLibraryInfo info; 891 892 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 893 String declaringPackageName, long declaringPackageVersionCode) { 894 path = _path; 895 apk = _apk; 896 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 897 declaringPackageName, declaringPackageVersionCode), null); 898 } 899 } 900 901 // Currently known shared libraries. 902 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 903 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 904 new ArrayMap<>(); 905 906 // All available activities, for your resolving pleasure. 907 final ActivityIntentResolver mActivities = 908 new ActivityIntentResolver(); 909 910 // All available receivers, for your resolving pleasure. 911 final ActivityIntentResolver mReceivers = 912 new ActivityIntentResolver(); 913 914 // All available services, for your resolving pleasure. 915 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 916 917 // All available providers, for your resolving pleasure. 918 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 919 920 // Mapping from provider base names (first directory in content URI codePath) 921 // to the provider information. 922 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 923 new ArrayMap<String, PackageParser.Provider>(); 924 925 // Mapping from instrumentation class names to info about them. 926 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 927 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 928 929 // Packages whose data we have transfered into another package, thus 930 // should no longer exist. 931 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 932 933 // Broadcast actions that are only available to the system. 934 @GuardedBy("mProtectedBroadcasts") 935 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 936 937 /** List of packages waiting for verification. */ 938 final SparseArray<PackageVerificationState> mPendingVerification 939 = new SparseArray<PackageVerificationState>(); 940 941 final PackageInstallerService mInstallerService; 942 943 final ArtManagerService mArtManagerService; 944 945 private final PackageDexOptimizer mPackageDexOptimizer; 946 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 947 // is used by other apps). 948 private final DexManager mDexManager; 949 950 private AtomicInteger mNextMoveId = new AtomicInteger(); 951 private final MoveCallbacks mMoveCallbacks; 952 953 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 954 955 // Cache of users who need badging. 956 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 957 958 /** Token for keys in mPendingVerification. */ 959 private int mPendingVerificationToken = 0; 960 961 volatile boolean mSystemReady; 962 volatile boolean mSafeMode; 963 volatile boolean mHasSystemUidErrors; 964 private volatile boolean mEphemeralAppsDisabled; 965 966 ApplicationInfo mAndroidApplication; 967 final ActivityInfo mResolveActivity = new ActivityInfo(); 968 final ResolveInfo mResolveInfo = new ResolveInfo(); 969 ComponentName mResolveComponentName; 970 PackageParser.Package mPlatformPackage; 971 ComponentName mCustomResolverComponentName; 972 973 boolean mResolverReplaced = false; 974 975 private final @Nullable ComponentName mIntentFilterVerifierComponent; 976 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 977 978 private int mIntentFilterVerificationToken = 0; 979 980 /** The service connection to the ephemeral resolver */ 981 final EphemeralResolverConnection mInstantAppResolverConnection; 982 /** Component used to show resolver settings for Instant Apps */ 983 final ComponentName mInstantAppResolverSettingsComponent; 984 985 /** Activity used to install instant applications */ 986 ActivityInfo mInstantAppInstallerActivity; 987 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 988 989 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 990 = new SparseArray<IntentFilterVerificationState>(); 991 992 // TODO remove this and go through mPermissonManager directly 993 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 994 private final PermissionManagerInternal mPermissionManager; 995 996 // List of packages names to keep cached, even if they are uninstalled for all users 997 private List<String> mKeepUninstalledPackages; 998 999 private UserManagerInternal mUserManagerInternal; 1000 private ActivityManagerInternal mActivityManagerInternal; 1001 1002 private DeviceIdleController.LocalService mDeviceIdleController; 1003 1004 private File mCacheDir; 1005 1006 private Future<?> mPrepareAppDataFuture; 1007 1008 private static class IFVerificationParams { 1009 PackageParser.Package pkg; 1010 boolean replacing; 1011 int userId; 1012 int verifierUid; 1013 1014 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1015 int _userId, int _verifierUid) { 1016 pkg = _pkg; 1017 replacing = _replacing; 1018 userId = _userId; 1019 replacing = _replacing; 1020 verifierUid = _verifierUid; 1021 } 1022 } 1023 1024 private interface IntentFilterVerifier<T extends IntentFilter> { 1025 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1026 T filter, String packageName); 1027 void startVerifications(int userId); 1028 void receiveVerificationResponse(int verificationId); 1029 } 1030 1031 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1032 private Context mContext; 1033 private ComponentName mIntentFilterVerifierComponent; 1034 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1035 1036 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1037 mContext = context; 1038 mIntentFilterVerifierComponent = verifierComponent; 1039 } 1040 1041 private String getDefaultScheme() { 1042 return IntentFilter.SCHEME_HTTPS; 1043 } 1044 1045 @Override 1046 public void startVerifications(int userId) { 1047 // Launch verifications requests 1048 int count = mCurrentIntentFilterVerifications.size(); 1049 for (int n=0; n<count; n++) { 1050 int verificationId = mCurrentIntentFilterVerifications.get(n); 1051 final IntentFilterVerificationState ivs = 1052 mIntentFilterVerificationStates.get(verificationId); 1053 1054 String packageName = ivs.getPackageName(); 1055 1056 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1057 final int filterCount = filters.size(); 1058 ArraySet<String> domainsSet = new ArraySet<>(); 1059 for (int m=0; m<filterCount; m++) { 1060 PackageParser.ActivityIntentInfo filter = filters.get(m); 1061 domainsSet.addAll(filter.getHostsList()); 1062 } 1063 synchronized (mPackages) { 1064 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1065 packageName, domainsSet) != null) { 1066 scheduleWriteSettingsLocked(); 1067 } 1068 } 1069 sendVerificationRequest(verificationId, ivs); 1070 } 1071 mCurrentIntentFilterVerifications.clear(); 1072 } 1073 1074 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1075 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1076 verificationIntent.putExtra( 1077 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1078 verificationId); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1081 getDefaultScheme()); 1082 verificationIntent.putExtra( 1083 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1084 ivs.getHostsString()); 1085 verificationIntent.putExtra( 1086 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1087 ivs.getPackageName()); 1088 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1089 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1090 1091 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1092 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1093 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1094 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1095 1096 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1097 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1098 "Sending IntentFilter verification broadcast"); 1099 } 1100 1101 public void receiveVerificationResponse(int verificationId) { 1102 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1103 1104 final boolean verified = ivs.isVerified(); 1105 1106 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1107 final int count = filters.size(); 1108 if (DEBUG_DOMAIN_VERIFICATION) { 1109 Slog.i(TAG, "Received verification response " + verificationId 1110 + " for " + count + " filters, verified=" + verified); 1111 } 1112 for (int n=0; n<count; n++) { 1113 PackageParser.ActivityIntentInfo filter = filters.get(n); 1114 filter.setVerified(verified); 1115 1116 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1117 + " verified with result:" + verified + " and hosts:" 1118 + ivs.getHostsString()); 1119 } 1120 1121 mIntentFilterVerificationStates.remove(verificationId); 1122 1123 final String packageName = ivs.getPackageName(); 1124 IntentFilterVerificationInfo ivi = null; 1125 1126 synchronized (mPackages) { 1127 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1128 } 1129 if (ivi == null) { 1130 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1131 + verificationId + " packageName:" + packageName); 1132 return; 1133 } 1134 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1135 "Updating IntentFilterVerificationInfo for package " + packageName 1136 +" verificationId:" + verificationId); 1137 1138 synchronized (mPackages) { 1139 if (verified) { 1140 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1141 } else { 1142 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1143 } 1144 scheduleWriteSettingsLocked(); 1145 1146 final int userId = ivs.getUserId(); 1147 if (userId != UserHandle.USER_ALL) { 1148 final int userStatus = 1149 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1150 1151 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1152 boolean needUpdate = false; 1153 1154 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1155 // already been set by the User thru the Disambiguation dialog 1156 switch (userStatus) { 1157 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1158 if (verified) { 1159 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1160 } else { 1161 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1162 } 1163 needUpdate = true; 1164 break; 1165 1166 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1167 if (verified) { 1168 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1169 needUpdate = true; 1170 } 1171 break; 1172 1173 default: 1174 // Nothing to do 1175 } 1176 1177 if (needUpdate) { 1178 mSettings.updateIntentFilterVerificationStatusLPw( 1179 packageName, updatedStatus, userId); 1180 scheduleWritePackageRestrictionsLocked(userId); 1181 } 1182 } 1183 } 1184 } 1185 1186 @Override 1187 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1188 ActivityIntentInfo filter, String packageName) { 1189 if (!hasValidDomains(filter)) { 1190 return false; 1191 } 1192 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1193 if (ivs == null) { 1194 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1195 packageName); 1196 } 1197 if (DEBUG_DOMAIN_VERIFICATION) { 1198 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1199 } 1200 ivs.addFilter(filter); 1201 return true; 1202 } 1203 1204 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1205 int userId, int verificationId, String packageName) { 1206 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1207 verifierUid, userId, packageName); 1208 ivs.setPendingState(); 1209 synchronized (mPackages) { 1210 mIntentFilterVerificationStates.append(verificationId, ivs); 1211 mCurrentIntentFilterVerifications.add(verificationId); 1212 } 1213 return ivs; 1214 } 1215 } 1216 1217 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1218 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1219 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1220 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1221 } 1222 1223 // Set of pending broadcasts for aggregating enable/disable of components. 1224 static class PendingPackageBroadcasts { 1225 // for each user id, a map of <package name -> components within that package> 1226 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1227 1228 public PendingPackageBroadcasts() { 1229 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1230 } 1231 1232 public ArrayList<String> get(int userId, String packageName) { 1233 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1234 return packages.get(packageName); 1235 } 1236 1237 public void put(int userId, String packageName, ArrayList<String> components) { 1238 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1239 packages.put(packageName, components); 1240 } 1241 1242 public void remove(int userId, String packageName) { 1243 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1244 if (packages != null) { 1245 packages.remove(packageName); 1246 } 1247 } 1248 1249 public void remove(int userId) { 1250 mUidMap.remove(userId); 1251 } 1252 1253 public int userIdCount() { 1254 return mUidMap.size(); 1255 } 1256 1257 public int userIdAt(int n) { 1258 return mUidMap.keyAt(n); 1259 } 1260 1261 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1262 return mUidMap.get(userId); 1263 } 1264 1265 public int size() { 1266 // total number of pending broadcast entries across all userIds 1267 int num = 0; 1268 for (int i = 0; i< mUidMap.size(); i++) { 1269 num += mUidMap.valueAt(i).size(); 1270 } 1271 return num; 1272 } 1273 1274 public void clear() { 1275 mUidMap.clear(); 1276 } 1277 1278 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1279 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1280 if (map == null) { 1281 map = new ArrayMap<String, ArrayList<String>>(); 1282 mUidMap.put(userId, map); 1283 } 1284 return map; 1285 } 1286 } 1287 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1288 1289 // Service Connection to remote media container service to copy 1290 // package uri's from external media onto secure containers 1291 // or internal storage. 1292 private IMediaContainerService mContainerService = null; 1293 1294 static final int SEND_PENDING_BROADCAST = 1; 1295 static final int MCS_BOUND = 3; 1296 static final int END_COPY = 4; 1297 static final int INIT_COPY = 5; 1298 static final int MCS_UNBIND = 6; 1299 static final int START_CLEANING_PACKAGE = 7; 1300 static final int FIND_INSTALL_LOC = 8; 1301 static final int POST_INSTALL = 9; 1302 static final int MCS_RECONNECT = 10; 1303 static final int MCS_GIVE_UP = 11; 1304 static final int WRITE_SETTINGS = 13; 1305 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1306 static final int PACKAGE_VERIFIED = 15; 1307 static final int CHECK_PENDING_VERIFICATION = 16; 1308 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1309 static final int INTENT_FILTER_VERIFIED = 18; 1310 static final int WRITE_PACKAGE_LIST = 19; 1311 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1312 1313 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1314 1315 // Delay time in millisecs 1316 static final int BROADCAST_DELAY = 10 * 1000; 1317 1318 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1319 2 * 60 * 60 * 1000L; /* two hours */ 1320 1321 static UserManagerService sUserManager; 1322 1323 // Stores a list of users whose package restrictions file needs to be updated 1324 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1325 1326 final private DefaultContainerConnection mDefContainerConn = 1327 new DefaultContainerConnection(); 1328 class DefaultContainerConnection implements ServiceConnection { 1329 public void onServiceConnected(ComponentName name, IBinder service) { 1330 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1331 final IMediaContainerService imcs = IMediaContainerService.Stub 1332 .asInterface(Binder.allowBlocking(service)); 1333 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1334 } 1335 1336 public void onServiceDisconnected(ComponentName name) { 1337 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1338 } 1339 } 1340 1341 // Recordkeeping of restore-after-install operations that are currently in flight 1342 // between the Package Manager and the Backup Manager 1343 static class PostInstallData { 1344 public InstallArgs args; 1345 public PackageInstalledInfo res; 1346 1347 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1348 args = _a; 1349 res = _r; 1350 } 1351 } 1352 1353 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1354 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1355 1356 // XML tags for backup/restore of various bits of state 1357 private static final String TAG_PREFERRED_BACKUP = "pa"; 1358 private static final String TAG_DEFAULT_APPS = "da"; 1359 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1360 1361 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1362 private static final String TAG_ALL_GRANTS = "rt-grants"; 1363 private static final String TAG_GRANT = "grant"; 1364 private static final String ATTR_PACKAGE_NAME = "pkg"; 1365 1366 private static final String TAG_PERMISSION = "perm"; 1367 private static final String ATTR_PERMISSION_NAME = "name"; 1368 private static final String ATTR_IS_GRANTED = "g"; 1369 private static final String ATTR_USER_SET = "set"; 1370 private static final String ATTR_USER_FIXED = "fixed"; 1371 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1372 1373 // System/policy permission grants are not backed up 1374 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1375 FLAG_PERMISSION_POLICY_FIXED 1376 | FLAG_PERMISSION_SYSTEM_FIXED 1377 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1378 1379 // And we back up these user-adjusted states 1380 private static final int USER_RUNTIME_GRANT_MASK = 1381 FLAG_PERMISSION_USER_SET 1382 | FLAG_PERMISSION_USER_FIXED 1383 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1384 1385 final @Nullable String mRequiredVerifierPackage; 1386 final @NonNull String mRequiredInstallerPackage; 1387 final @NonNull String mRequiredUninstallerPackage; 1388 final @Nullable String mSetupWizardPackage; 1389 final @Nullable String mStorageManagerPackage; 1390 final @NonNull String mServicesSystemSharedLibraryPackageName; 1391 final @NonNull String mSharedSystemSharedLibraryPackageName; 1392 1393 private final PackageUsage mPackageUsage = new PackageUsage(); 1394 private final CompilerStats mCompilerStats = new CompilerStats(); 1395 1396 class PackageHandler extends Handler { 1397 private boolean mBound = false; 1398 final ArrayList<HandlerParams> mPendingInstalls = 1399 new ArrayList<HandlerParams>(); 1400 1401 private boolean connectToService() { 1402 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1403 " DefaultContainerService"); 1404 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1405 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1406 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1407 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1408 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1409 mBound = true; 1410 return true; 1411 } 1412 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1413 return false; 1414 } 1415 1416 private void disconnectService() { 1417 mContainerService = null; 1418 mBound = false; 1419 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1420 mContext.unbindService(mDefContainerConn); 1421 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1422 } 1423 1424 PackageHandler(Looper looper) { 1425 super(looper); 1426 } 1427 1428 public void handleMessage(Message msg) { 1429 try { 1430 doHandleMessage(msg); 1431 } finally { 1432 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1433 } 1434 } 1435 1436 void doHandleMessage(Message msg) { 1437 switch (msg.what) { 1438 case INIT_COPY: { 1439 HandlerParams params = (HandlerParams) msg.obj; 1440 int idx = mPendingInstalls.size(); 1441 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1442 // If a bind was already initiated we dont really 1443 // need to do anything. The pending install 1444 // will be processed later on. 1445 if (!mBound) { 1446 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1447 System.identityHashCode(mHandler)); 1448 // If this is the only one pending we might 1449 // have to bind to the service again. 1450 if (!connectToService()) { 1451 Slog.e(TAG, "Failed to bind to media container service"); 1452 params.serviceError(); 1453 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1454 System.identityHashCode(mHandler)); 1455 if (params.traceMethod != null) { 1456 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1457 params.traceCookie); 1458 } 1459 return; 1460 } else { 1461 // Once we bind to the service, the first 1462 // pending request will be processed. 1463 mPendingInstalls.add(idx, params); 1464 } 1465 } else { 1466 mPendingInstalls.add(idx, params); 1467 // Already bound to the service. Just make 1468 // sure we trigger off processing the first request. 1469 if (idx == 0) { 1470 mHandler.sendEmptyMessage(MCS_BOUND); 1471 } 1472 } 1473 break; 1474 } 1475 case MCS_BOUND: { 1476 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1477 if (msg.obj != null) { 1478 mContainerService = (IMediaContainerService) msg.obj; 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1480 System.identityHashCode(mHandler)); 1481 } 1482 if (mContainerService == null) { 1483 if (!mBound) { 1484 // Something seriously wrong since we are not bound and we are not 1485 // waiting for connection. Bail out. 1486 Slog.e(TAG, "Cannot bind to media container service"); 1487 for (HandlerParams params : mPendingInstalls) { 1488 // Indicate service bind error 1489 params.serviceError(); 1490 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1491 System.identityHashCode(params)); 1492 if (params.traceMethod != null) { 1493 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1494 params.traceMethod, params.traceCookie); 1495 } 1496 return; 1497 } 1498 mPendingInstalls.clear(); 1499 } else { 1500 Slog.w(TAG, "Waiting to connect to media container service"); 1501 } 1502 } else if (mPendingInstalls.size() > 0) { 1503 HandlerParams params = mPendingInstalls.get(0); 1504 if (params != null) { 1505 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1506 System.identityHashCode(params)); 1507 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1508 if (params.startCopy()) { 1509 // We are done... look for more work or to 1510 // go idle. 1511 if (DEBUG_SD_INSTALL) Log.i(TAG, 1512 "Checking for more work or unbind..."); 1513 // Delete pending install 1514 if (mPendingInstalls.size() > 0) { 1515 mPendingInstalls.remove(0); 1516 } 1517 if (mPendingInstalls.size() == 0) { 1518 if (mBound) { 1519 if (DEBUG_SD_INSTALL) Log.i(TAG, 1520 "Posting delayed MCS_UNBIND"); 1521 removeMessages(MCS_UNBIND); 1522 Message ubmsg = obtainMessage(MCS_UNBIND); 1523 // Unbind after a little delay, to avoid 1524 // continual thrashing. 1525 sendMessageDelayed(ubmsg, 10000); 1526 } 1527 } else { 1528 // There are more pending requests in queue. 1529 // Just post MCS_BOUND message to trigger processing 1530 // of next pending install. 1531 if (DEBUG_SD_INSTALL) Log.i(TAG, 1532 "Posting MCS_BOUND for next work"); 1533 mHandler.sendEmptyMessage(MCS_BOUND); 1534 } 1535 } 1536 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1537 } 1538 } else { 1539 // Should never happen ideally. 1540 Slog.w(TAG, "Empty queue"); 1541 } 1542 break; 1543 } 1544 case MCS_RECONNECT: { 1545 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1546 if (mPendingInstalls.size() > 0) { 1547 if (mBound) { 1548 disconnectService(); 1549 } 1550 if (!connectToService()) { 1551 Slog.e(TAG, "Failed to bind to media container service"); 1552 for (HandlerParams params : mPendingInstalls) { 1553 // Indicate service bind error 1554 params.serviceError(); 1555 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1556 System.identityHashCode(params)); 1557 } 1558 mPendingInstalls.clear(); 1559 } 1560 } 1561 break; 1562 } 1563 case MCS_UNBIND: { 1564 // If there is no actual work left, then time to unbind. 1565 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1566 1567 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1568 if (mBound) { 1569 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1570 1571 disconnectService(); 1572 } 1573 } else if (mPendingInstalls.size() > 0) { 1574 // There are more pending requests in queue. 1575 // Just post MCS_BOUND message to trigger processing 1576 // of next pending install. 1577 mHandler.sendEmptyMessage(MCS_BOUND); 1578 } 1579 1580 break; 1581 } 1582 case MCS_GIVE_UP: { 1583 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1584 HandlerParams params = mPendingInstalls.remove(0); 1585 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1586 System.identityHashCode(params)); 1587 break; 1588 } 1589 case SEND_PENDING_BROADCAST: { 1590 String packages[]; 1591 ArrayList<String> components[]; 1592 int size = 0; 1593 int uids[]; 1594 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1595 synchronized (mPackages) { 1596 if (mPendingBroadcasts == null) { 1597 return; 1598 } 1599 size = mPendingBroadcasts.size(); 1600 if (size <= 0) { 1601 // Nothing to be done. Just return 1602 return; 1603 } 1604 packages = new String[size]; 1605 components = new ArrayList[size]; 1606 uids = new int[size]; 1607 int i = 0; // filling out the above arrays 1608 1609 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1610 int packageUserId = mPendingBroadcasts.userIdAt(n); 1611 Iterator<Map.Entry<String, ArrayList<String>>> it 1612 = mPendingBroadcasts.packagesForUserId(packageUserId) 1613 .entrySet().iterator(); 1614 while (it.hasNext() && i < size) { 1615 Map.Entry<String, ArrayList<String>> ent = it.next(); 1616 packages[i] = ent.getKey(); 1617 components[i] = ent.getValue(); 1618 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1619 uids[i] = (ps != null) 1620 ? UserHandle.getUid(packageUserId, ps.appId) 1621 : -1; 1622 i++; 1623 } 1624 } 1625 size = i; 1626 mPendingBroadcasts.clear(); 1627 } 1628 // Send broadcasts 1629 for (int i = 0; i < size; i++) { 1630 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1631 } 1632 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1633 break; 1634 } 1635 case START_CLEANING_PACKAGE: { 1636 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1637 final String packageName = (String)msg.obj; 1638 final int userId = msg.arg1; 1639 final boolean andCode = msg.arg2 != 0; 1640 synchronized (mPackages) { 1641 if (userId == UserHandle.USER_ALL) { 1642 int[] users = sUserManager.getUserIds(); 1643 for (int user : users) { 1644 mSettings.addPackageToCleanLPw( 1645 new PackageCleanItem(user, packageName, andCode)); 1646 } 1647 } else { 1648 mSettings.addPackageToCleanLPw( 1649 new PackageCleanItem(userId, packageName, andCode)); 1650 } 1651 } 1652 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1653 startCleaningPackages(); 1654 } break; 1655 case POST_INSTALL: { 1656 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1657 1658 PostInstallData data = mRunningInstalls.get(msg.arg1); 1659 final boolean didRestore = (msg.arg2 != 0); 1660 mRunningInstalls.delete(msg.arg1); 1661 1662 if (data != null) { 1663 InstallArgs args = data.args; 1664 PackageInstalledInfo parentRes = data.res; 1665 1666 final boolean grantPermissions = (args.installFlags 1667 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1668 final boolean killApp = (args.installFlags 1669 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1670 final boolean virtualPreload = ((args.installFlags 1671 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1672 final String[] grantedPermissions = args.installGrantPermissions; 1673 1674 // Handle the parent package 1675 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1676 virtualPreload, grantedPermissions, didRestore, 1677 args.installerPackageName, args.observer); 1678 1679 // Handle the child packages 1680 final int childCount = (parentRes.addedChildPackages != null) 1681 ? parentRes.addedChildPackages.size() : 0; 1682 for (int i = 0; i < childCount; i++) { 1683 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1684 handlePackagePostInstall(childRes, grantPermissions, killApp, 1685 virtualPreload, grantedPermissions, false /*didRestore*/, 1686 args.installerPackageName, args.observer); 1687 } 1688 1689 // Log tracing if needed 1690 if (args.traceMethod != null) { 1691 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1692 args.traceCookie); 1693 } 1694 } else { 1695 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1696 } 1697 1698 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1699 } break; 1700 case WRITE_SETTINGS: { 1701 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1702 synchronized (mPackages) { 1703 removeMessages(WRITE_SETTINGS); 1704 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1705 mSettings.writeLPr(); 1706 mDirtyUsers.clear(); 1707 } 1708 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1709 } break; 1710 case WRITE_PACKAGE_RESTRICTIONS: { 1711 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1712 synchronized (mPackages) { 1713 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1714 for (int userId : mDirtyUsers) { 1715 mSettings.writePackageRestrictionsLPr(userId); 1716 } 1717 mDirtyUsers.clear(); 1718 } 1719 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1720 } break; 1721 case WRITE_PACKAGE_LIST: { 1722 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1723 synchronized (mPackages) { 1724 removeMessages(WRITE_PACKAGE_LIST); 1725 mSettings.writePackageListLPr(msg.arg1); 1726 } 1727 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1728 } break; 1729 case CHECK_PENDING_VERIFICATION: { 1730 final int verificationId = msg.arg1; 1731 final PackageVerificationState state = mPendingVerification.get(verificationId); 1732 1733 if ((state != null) && !state.timeoutExtended()) { 1734 final InstallArgs args = state.getInstallArgs(); 1735 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1736 1737 Slog.i(TAG, "Verification timed out for " + originUri); 1738 mPendingVerification.remove(verificationId); 1739 1740 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1741 1742 final UserHandle user = args.getUser(); 1743 if (getDefaultVerificationResponse(user) 1744 == PackageManager.VERIFICATION_ALLOW) { 1745 Slog.i(TAG, "Continuing with installation of " + originUri); 1746 state.setVerifierResponse(Binder.getCallingUid(), 1747 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1748 broadcastPackageVerified(verificationId, originUri, 1749 PackageManager.VERIFICATION_ALLOW, user); 1750 try { 1751 ret = args.copyApk(mContainerService, true); 1752 } catch (RemoteException e) { 1753 Slog.e(TAG, "Could not contact the ContainerService"); 1754 } 1755 } else { 1756 broadcastPackageVerified(verificationId, originUri, 1757 PackageManager.VERIFICATION_REJECT, user); 1758 } 1759 1760 Trace.asyncTraceEnd( 1761 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1762 1763 processPendingInstall(args, ret); 1764 mHandler.sendEmptyMessage(MCS_UNBIND); 1765 } 1766 break; 1767 } 1768 case PACKAGE_VERIFIED: { 1769 final int verificationId = msg.arg1; 1770 1771 final PackageVerificationState state = mPendingVerification.get(verificationId); 1772 if (state == null) { 1773 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1774 break; 1775 } 1776 1777 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1778 1779 state.setVerifierResponse(response.callerUid, response.code); 1780 1781 if (state.isVerificationComplete()) { 1782 mPendingVerification.remove(verificationId); 1783 1784 final InstallArgs args = state.getInstallArgs(); 1785 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1786 1787 int ret; 1788 if (state.isInstallAllowed()) { 1789 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1790 broadcastPackageVerified(verificationId, originUri, 1791 response.code, state.getInstallArgs().getUser()); 1792 try { 1793 ret = args.copyApk(mContainerService, true); 1794 } catch (RemoteException e) { 1795 Slog.e(TAG, "Could not contact the ContainerService"); 1796 } 1797 } else { 1798 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1799 } 1800 1801 Trace.asyncTraceEnd( 1802 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1803 1804 processPendingInstall(args, ret); 1805 mHandler.sendEmptyMessage(MCS_UNBIND); 1806 } 1807 1808 break; 1809 } 1810 case START_INTENT_FILTER_VERIFICATIONS: { 1811 IFVerificationParams params = (IFVerificationParams) msg.obj; 1812 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1813 params.replacing, params.pkg); 1814 break; 1815 } 1816 case INTENT_FILTER_VERIFIED: { 1817 final int verificationId = msg.arg1; 1818 1819 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1820 verificationId); 1821 if (state == null) { 1822 Slog.w(TAG, "Invalid IntentFilter verification token " 1823 + verificationId + " received"); 1824 break; 1825 } 1826 1827 final int userId = state.getUserId(); 1828 1829 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1830 "Processing IntentFilter verification with token:" 1831 + verificationId + " and userId:" + userId); 1832 1833 final IntentFilterVerificationResponse response = 1834 (IntentFilterVerificationResponse) msg.obj; 1835 1836 state.setVerifierResponse(response.callerUid, response.code); 1837 1838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1839 "IntentFilter verification with token:" + verificationId 1840 + " and userId:" + userId 1841 + " is settings verifier response with response code:" 1842 + response.code); 1843 1844 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1845 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1846 + response.getFailedDomainsString()); 1847 } 1848 1849 if (state.isVerificationComplete()) { 1850 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1851 } else { 1852 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1853 "IntentFilter verification with token:" + verificationId 1854 + " was not said to be complete"); 1855 } 1856 1857 break; 1858 } 1859 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1860 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1861 mInstantAppResolverConnection, 1862 (InstantAppRequest) msg.obj, 1863 mInstantAppInstallerActivity, 1864 mHandler); 1865 } 1866 } 1867 } 1868 } 1869 1870 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1871 @Override 1872 public void onGidsChanged(int appId, int userId) { 1873 mHandler.post(new Runnable() { 1874 @Override 1875 public void run() { 1876 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1877 } 1878 }); 1879 } 1880 @Override 1881 public void onPermissionGranted(int uid, int userId) { 1882 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1883 1884 // Not critical; if this is lost, the application has to request again. 1885 synchronized (mPackages) { 1886 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1887 } 1888 } 1889 @Override 1890 public void onInstallPermissionGranted() { 1891 synchronized (mPackages) { 1892 scheduleWriteSettingsLocked(); 1893 } 1894 } 1895 @Override 1896 public void onPermissionRevoked(int uid, int userId) { 1897 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1898 1899 synchronized (mPackages) { 1900 // Critical; after this call the application should never have the permission 1901 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1902 } 1903 1904 final int appId = UserHandle.getAppId(uid); 1905 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1906 } 1907 @Override 1908 public void onInstallPermissionRevoked() { 1909 synchronized (mPackages) { 1910 scheduleWriteSettingsLocked(); 1911 } 1912 } 1913 @Override 1914 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1915 synchronized (mPackages) { 1916 for (int userId : updatedUserIds) { 1917 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1918 } 1919 } 1920 } 1921 @Override 1922 public void onInstallPermissionUpdated() { 1923 synchronized (mPackages) { 1924 scheduleWriteSettingsLocked(); 1925 } 1926 } 1927 @Override 1928 public void onPermissionRemoved() { 1929 synchronized (mPackages) { 1930 mSettings.writeLPr(); 1931 } 1932 } 1933 }; 1934 1935 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1936 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1937 boolean launchedForRestore, String installerPackage, 1938 IPackageInstallObserver2 installObserver) { 1939 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1940 // Send the removed broadcasts 1941 if (res.removedInfo != null) { 1942 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1943 } 1944 1945 // Now that we successfully installed the package, grant runtime 1946 // permissions if requested before broadcasting the install. Also 1947 // for legacy apps in permission review mode we clear the permission 1948 // review flag which is used to emulate runtime permissions for 1949 // legacy apps. 1950 if (grantPermissions) { 1951 final int callingUid = Binder.getCallingUid(); 1952 mPermissionManager.grantRequestedRuntimePermissions( 1953 res.pkg, res.newUsers, grantedPermissions, callingUid, 1954 mPermissionCallback); 1955 } 1956 1957 final boolean update = res.removedInfo != null 1958 && res.removedInfo.removedPackage != null; 1959 final String installerPackageName = 1960 res.installerPackageName != null 1961 ? res.installerPackageName 1962 : res.removedInfo != null 1963 ? res.removedInfo.installerPackageName 1964 : null; 1965 1966 // If this is the first time we have child packages for a disabled privileged 1967 // app that had no children, we grant requested runtime permissions to the new 1968 // children if the parent on the system image had them already granted. 1969 if (res.pkg.parentPackage != null) { 1970 final int callingUid = Binder.getCallingUid(); 1971 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1972 res.pkg, callingUid, mPermissionCallback); 1973 } 1974 1975 synchronized (mPackages) { 1976 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1977 } 1978 1979 final String packageName = res.pkg.applicationInfo.packageName; 1980 1981 // Determine the set of users who are adding this package for 1982 // the first time vs. those who are seeing an update. 1983 int[] firstUserIds = EMPTY_INT_ARRAY; 1984 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1985 int[] updateUserIds = EMPTY_INT_ARRAY; 1986 int[] instantUserIds = EMPTY_INT_ARRAY; 1987 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1988 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1989 for (int newUser : res.newUsers) { 1990 final boolean isInstantApp = ps.getInstantApp(newUser); 1991 if (allNewUsers) { 1992 if (isInstantApp) { 1993 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1994 } else { 1995 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1996 } 1997 continue; 1998 } 1999 boolean isNew = true; 2000 for (int origUser : res.origUsers) { 2001 if (origUser == newUser) { 2002 isNew = false; 2003 break; 2004 } 2005 } 2006 if (isNew) { 2007 if (isInstantApp) { 2008 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2009 } else { 2010 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2011 } 2012 } else { 2013 if (isInstantApp) { 2014 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2015 } else { 2016 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2017 } 2018 } 2019 } 2020 2021 // Send installed broadcasts if the package is not a static shared lib. 2022 if (res.pkg.staticSharedLibName == null) { 2023 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2024 2025 // Send added for users that see the package for the first time 2026 // sendPackageAddedForNewUsers also deals with system apps 2027 int appId = UserHandle.getAppId(res.uid); 2028 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2029 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2030 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2031 2032 // Send added for users that don't see the package for the first time 2033 Bundle extras = new Bundle(1); 2034 extras.putInt(Intent.EXTRA_UID, res.uid); 2035 if (update) { 2036 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2037 } 2038 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2039 extras, 0 /*flags*/, 2040 null /*targetPackage*/, null /*finishedReceiver*/, 2041 updateUserIds, instantUserIds); 2042 if (installerPackageName != null) { 2043 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2044 extras, 0 /*flags*/, 2045 installerPackageName, null /*finishedReceiver*/, 2046 updateUserIds, instantUserIds); 2047 } 2048 2049 // Send replaced for users that don't see the package for the first time 2050 if (update) { 2051 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2052 packageName, extras, 0 /*flags*/, 2053 null /*targetPackage*/, null /*finishedReceiver*/, 2054 updateUserIds, instantUserIds); 2055 if (installerPackageName != null) { 2056 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2057 extras, 0 /*flags*/, 2058 installerPackageName, null /*finishedReceiver*/, 2059 updateUserIds, instantUserIds); 2060 } 2061 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2062 null /*package*/, null /*extras*/, 0 /*flags*/, 2063 packageName /*targetPackage*/, 2064 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2065 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2066 // First-install and we did a restore, so we're responsible for the 2067 // first-launch broadcast. 2068 if (DEBUG_BACKUP) { 2069 Slog.i(TAG, "Post-restore of " + packageName 2070 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2071 } 2072 sendFirstLaunchBroadcast(packageName, installerPackage, 2073 firstUserIds, firstInstantUserIds); 2074 } 2075 2076 // Send broadcast package appeared if forward locked/external for all users 2077 // treat asec-hosted packages like removable media on upgrade 2078 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2079 if (DEBUG_INSTALL) { 2080 Slog.i(TAG, "upgrading pkg " + res.pkg 2081 + " is ASEC-hosted -> AVAILABLE"); 2082 } 2083 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2084 ArrayList<String> pkgList = new ArrayList<>(1); 2085 pkgList.add(packageName); 2086 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2087 } 2088 } 2089 2090 // Work that needs to happen on first install within each user 2091 if (firstUserIds != null && firstUserIds.length > 0) { 2092 synchronized (mPackages) { 2093 for (int userId : firstUserIds) { 2094 // If this app is a browser and it's newly-installed for some 2095 // users, clear any default-browser state in those users. The 2096 // app's nature doesn't depend on the user, so we can just check 2097 // its browser nature in any user and generalize. 2098 if (packageIsBrowser(packageName, userId)) { 2099 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2100 } 2101 2102 // We may also need to apply pending (restored) runtime 2103 // permission grants within these users. 2104 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2105 } 2106 } 2107 } 2108 2109 if (allNewUsers && !update) { 2110 notifyPackageAdded(packageName); 2111 } 2112 2113 // Log current value of "unknown sources" setting 2114 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2115 getUnknownSourcesSettings()); 2116 2117 // Remove the replaced package's older resources safely now 2118 // We delete after a gc for applications on sdcard. 2119 if (res.removedInfo != null && res.removedInfo.args != null) { 2120 Runtime.getRuntime().gc(); 2121 synchronized (mInstallLock) { 2122 res.removedInfo.args.doPostDeleteLI(true); 2123 } 2124 } else { 2125 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2126 // and not block here. 2127 VMRuntime.getRuntime().requestConcurrentGC(); 2128 } 2129 2130 // Notify DexManager that the package was installed for new users. 2131 // The updated users should already be indexed and the package code paths 2132 // should not change. 2133 // Don't notify the manager for ephemeral apps as they are not expected to 2134 // survive long enough to benefit of background optimizations. 2135 for (int userId : firstUserIds) { 2136 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2137 // There's a race currently where some install events may interleave with an uninstall. 2138 // This can lead to package info being null (b/36642664). 2139 if (info != null) { 2140 mDexManager.notifyPackageInstalled(info, userId); 2141 } 2142 } 2143 } 2144 2145 // If someone is watching installs - notify them 2146 if (installObserver != null) { 2147 try { 2148 Bundle extras = extrasForInstallResult(res); 2149 installObserver.onPackageInstalled(res.name, res.returnCode, 2150 res.returnMsg, extras); 2151 } catch (RemoteException e) { 2152 Slog.i(TAG, "Observer no longer exists."); 2153 } 2154 } 2155 } 2156 2157 private StorageEventListener mStorageListener = new StorageEventListener() { 2158 @Override 2159 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2160 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2161 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2162 final String volumeUuid = vol.getFsUuid(); 2163 2164 // Clean up any users or apps that were removed or recreated 2165 // while this volume was missing 2166 sUserManager.reconcileUsers(volumeUuid); 2167 reconcileApps(volumeUuid); 2168 2169 // Clean up any install sessions that expired or were 2170 // cancelled while this volume was missing 2171 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2172 2173 loadPrivatePackages(vol); 2174 2175 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2176 unloadPrivatePackages(vol); 2177 } 2178 } 2179 } 2180 2181 @Override 2182 public void onVolumeForgotten(String fsUuid) { 2183 if (TextUtils.isEmpty(fsUuid)) { 2184 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2185 return; 2186 } 2187 2188 // Remove any apps installed on the forgotten volume 2189 synchronized (mPackages) { 2190 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2191 for (PackageSetting ps : packages) { 2192 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2193 deletePackageVersioned(new VersionedPackage(ps.name, 2194 PackageManager.VERSION_CODE_HIGHEST), 2195 new LegacyPackageDeleteObserver(null).getBinder(), 2196 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2197 // Try very hard to release any references to this package 2198 // so we don't risk the system server being killed due to 2199 // open FDs 2200 AttributeCache.instance().removePackage(ps.name); 2201 } 2202 2203 mSettings.onVolumeForgotten(fsUuid); 2204 mSettings.writeLPr(); 2205 } 2206 } 2207 }; 2208 2209 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2210 Bundle extras = null; 2211 switch (res.returnCode) { 2212 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2213 extras = new Bundle(); 2214 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2215 res.origPermission); 2216 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2217 res.origPackage); 2218 break; 2219 } 2220 case PackageManager.INSTALL_SUCCEEDED: { 2221 extras = new Bundle(); 2222 extras.putBoolean(Intent.EXTRA_REPLACING, 2223 res.removedInfo != null && res.removedInfo.removedPackage != null); 2224 break; 2225 } 2226 } 2227 return extras; 2228 } 2229 2230 void scheduleWriteSettingsLocked() { 2231 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2232 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2233 } 2234 } 2235 2236 void scheduleWritePackageListLocked(int userId) { 2237 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2238 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2239 msg.arg1 = userId; 2240 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2241 } 2242 } 2243 2244 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2245 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2246 scheduleWritePackageRestrictionsLocked(userId); 2247 } 2248 2249 void scheduleWritePackageRestrictionsLocked(int userId) { 2250 final int[] userIds = (userId == UserHandle.USER_ALL) 2251 ? sUserManager.getUserIds() : new int[]{userId}; 2252 for (int nextUserId : userIds) { 2253 if (!sUserManager.exists(nextUserId)) return; 2254 mDirtyUsers.add(nextUserId); 2255 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2256 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2257 } 2258 } 2259 } 2260 2261 public static PackageManagerService main(Context context, Installer installer, 2262 boolean factoryTest, boolean onlyCore) { 2263 // Self-check for initial settings. 2264 PackageManagerServiceCompilerMapping.checkProperties(); 2265 2266 PackageManagerService m = new PackageManagerService(context, installer, 2267 factoryTest, onlyCore); 2268 m.enableSystemUserPackages(); 2269 ServiceManager.addService("package", m); 2270 final PackageManagerNative pmn = m.new PackageManagerNative(); 2271 ServiceManager.addService("package_native", pmn); 2272 return m; 2273 } 2274 2275 private void enableSystemUserPackages() { 2276 if (!UserManager.isSplitSystemUser()) { 2277 return; 2278 } 2279 // For system user, enable apps based on the following conditions: 2280 // - app is whitelisted or belong to one of these groups: 2281 // -- system app which has no launcher icons 2282 // -- system app which has INTERACT_ACROSS_USERS permission 2283 // -- system IME app 2284 // - app is not in the blacklist 2285 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2286 Set<String> enableApps = new ArraySet<>(); 2287 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2288 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2289 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2290 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2291 enableApps.addAll(wlApps); 2292 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2293 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2294 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2295 enableApps.removeAll(blApps); 2296 Log.i(TAG, "Applications installed for system user: " + enableApps); 2297 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2298 UserHandle.SYSTEM); 2299 final int allAppsSize = allAps.size(); 2300 synchronized (mPackages) { 2301 for (int i = 0; i < allAppsSize; i++) { 2302 String pName = allAps.get(i); 2303 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2304 // Should not happen, but we shouldn't be failing if it does 2305 if (pkgSetting == null) { 2306 continue; 2307 } 2308 boolean install = enableApps.contains(pName); 2309 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2310 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2311 + " for system user"); 2312 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2313 } 2314 } 2315 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2316 } 2317 } 2318 2319 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2320 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2321 Context.DISPLAY_SERVICE); 2322 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2323 } 2324 2325 /** 2326 * Requests that files preopted on a secondary system partition be copied to the data partition 2327 * if possible. Note that the actual copying of the files is accomplished by init for security 2328 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2329 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2330 */ 2331 private static void requestCopyPreoptedFiles() { 2332 final int WAIT_TIME_MS = 100; 2333 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2334 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2335 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2336 // We will wait for up to 100 seconds. 2337 final long timeStart = SystemClock.uptimeMillis(); 2338 final long timeEnd = timeStart + 100 * 1000; 2339 long timeNow = timeStart; 2340 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2341 try { 2342 Thread.sleep(WAIT_TIME_MS); 2343 } catch (InterruptedException e) { 2344 // Do nothing 2345 } 2346 timeNow = SystemClock.uptimeMillis(); 2347 if (timeNow > timeEnd) { 2348 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2349 Slog.wtf(TAG, "cppreopt did not finish!"); 2350 break; 2351 } 2352 } 2353 2354 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2355 } 2356 } 2357 2358 public PackageManagerService(Context context, Installer installer, 2359 boolean factoryTest, boolean onlyCore) { 2360 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2361 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2362 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2363 SystemClock.uptimeMillis()); 2364 2365 if (mSdkVersion <= 0) { 2366 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2367 } 2368 2369 mContext = context; 2370 2371 mFactoryTest = factoryTest; 2372 mOnlyCore = onlyCore; 2373 mMetrics = new DisplayMetrics(); 2374 mInstaller = installer; 2375 2376 // Create sub-components that provide services / data. Order here is important. 2377 synchronized (mInstallLock) { 2378 synchronized (mPackages) { 2379 // Expose private service for system components to use. 2380 LocalServices.addService( 2381 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2382 sUserManager = new UserManagerService(context, this, 2383 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2384 mPermissionManager = PermissionManagerService.create(context, 2385 new DefaultPermissionGrantedCallback() { 2386 @Override 2387 public void onDefaultRuntimePermissionsGranted(int userId) { 2388 synchronized(mPackages) { 2389 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2390 } 2391 } 2392 }, mPackages /*externalLock*/); 2393 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2394 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2395 } 2396 } 2397 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2398 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2399 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2400 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2401 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2402 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2403 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2404 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2405 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2406 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2407 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2408 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2409 2410 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2411 if (separateProcesses != null && separateProcesses.length() > 0) { 2412 if ("*".equals(separateProcesses)) { 2413 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2414 mSeparateProcesses = null; 2415 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2416 } else { 2417 mDefParseFlags = 0; 2418 mSeparateProcesses = separateProcesses.split(","); 2419 Slog.w(TAG, "Running with debug.separate_processes: " 2420 + separateProcesses); 2421 } 2422 } else { 2423 mDefParseFlags = 0; 2424 mSeparateProcesses = null; 2425 } 2426 2427 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2428 "*dexopt*"); 2429 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2430 installer, mInstallLock); 2431 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2432 dexManagerListener); 2433 mArtManagerService = new ArtManagerService(this, installer, mInstallLock); 2434 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2435 2436 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2437 FgThread.get().getLooper()); 2438 2439 getDefaultDisplayMetrics(context, mMetrics); 2440 2441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2442 SystemConfig systemConfig = SystemConfig.getInstance(); 2443 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2444 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2445 2446 mProtectedPackages = new ProtectedPackages(mContext); 2447 2448 synchronized (mInstallLock) { 2449 // writer 2450 synchronized (mPackages) { 2451 mHandlerThread = new ServiceThread(TAG, 2452 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2453 mHandlerThread.start(); 2454 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2455 mProcessLoggingHandler = new ProcessLoggingHandler(); 2456 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2457 mInstantAppRegistry = new InstantAppRegistry(this); 2458 2459 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2460 final int builtInLibCount = libConfig.size(); 2461 for (int i = 0; i < builtInLibCount; i++) { 2462 String name = libConfig.keyAt(i); 2463 String path = libConfig.valueAt(i); 2464 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2465 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2466 } 2467 2468 SELinuxMMAC.readInstallPolicy(); 2469 2470 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2471 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2473 2474 // Clean up orphaned packages for which the code path doesn't exist 2475 // and they are an update to a system app - caused by bug/32321269 2476 final int packageSettingCount = mSettings.mPackages.size(); 2477 for (int i = packageSettingCount - 1; i >= 0; i--) { 2478 PackageSetting ps = mSettings.mPackages.valueAt(i); 2479 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2480 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2481 mSettings.mPackages.removeAt(i); 2482 mSettings.enableSystemPackageLPw(ps.name); 2483 } 2484 } 2485 2486 if (mFirstBoot) { 2487 requestCopyPreoptedFiles(); 2488 } 2489 2490 String customResolverActivity = Resources.getSystem().getString( 2491 R.string.config_customResolverActivity); 2492 if (TextUtils.isEmpty(customResolverActivity)) { 2493 customResolverActivity = null; 2494 } else { 2495 mCustomResolverComponentName = ComponentName.unflattenFromString( 2496 customResolverActivity); 2497 } 2498 2499 long startTime = SystemClock.uptimeMillis(); 2500 2501 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2502 startTime); 2503 2504 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2505 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2506 2507 if (bootClassPath == null) { 2508 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2509 } 2510 2511 if (systemServerClassPath == null) { 2512 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2513 } 2514 2515 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2516 2517 final VersionInfo ver = mSettings.getInternalVersion(); 2518 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2519 if (mIsUpgrade) { 2520 logCriticalInfo(Log.INFO, 2521 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2522 } 2523 2524 // when upgrading from pre-M, promote system app permissions from install to runtime 2525 mPromoteSystemApps = 2526 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2527 2528 // When upgrading from pre-N, we need to handle package extraction like first boot, 2529 // as there is no profiling data available. 2530 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2531 2532 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2533 2534 // save off the names of pre-existing system packages prior to scanning; we don't 2535 // want to automatically grant runtime permissions for new system apps 2536 if (mPromoteSystemApps) { 2537 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2538 while (pkgSettingIter.hasNext()) { 2539 PackageSetting ps = pkgSettingIter.next(); 2540 if (isSystemApp(ps)) { 2541 mExistingSystemPackages.add(ps.name); 2542 } 2543 } 2544 } 2545 2546 mCacheDir = preparePackageParserCache(mIsUpgrade); 2547 2548 // Set flag to monitor and not change apk file paths when 2549 // scanning install directories. 2550 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2551 2552 if (mIsUpgrade || mFirstBoot) { 2553 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2554 } 2555 2556 // Collect vendor/product overlay packages. (Do this before scanning any apps.) 2557 // For security and version matching reason, only consider 2558 // overlay packages if they reside in the right directory. 2559 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2560 mDefParseFlags 2561 | PackageParser.PARSE_IS_SYSTEM_DIR, 2562 scanFlags 2563 | SCAN_AS_SYSTEM 2564 | SCAN_AS_VENDOR, 2565 0); 2566 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2567 mDefParseFlags 2568 | PackageParser.PARSE_IS_SYSTEM_DIR, 2569 scanFlags 2570 | SCAN_AS_SYSTEM 2571 | SCAN_AS_PRODUCT, 2572 0); 2573 2574 mParallelPackageParserCallback.findStaticOverlayPackages(); 2575 2576 // Find base frameworks (resource packages without code). 2577 scanDirTracedLI(frameworkDir, 2578 mDefParseFlags 2579 | PackageParser.PARSE_IS_SYSTEM_DIR, 2580 scanFlags 2581 | SCAN_NO_DEX 2582 | SCAN_AS_SYSTEM 2583 | SCAN_AS_PRIVILEGED, 2584 0); 2585 2586 // Collected privileged system packages. 2587 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2588 scanDirTracedLI(privilegedAppDir, 2589 mDefParseFlags 2590 | PackageParser.PARSE_IS_SYSTEM_DIR, 2591 scanFlags 2592 | SCAN_AS_SYSTEM 2593 | SCAN_AS_PRIVILEGED, 2594 0); 2595 2596 // Collect ordinary system packages. 2597 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2598 scanDirTracedLI(systemAppDir, 2599 mDefParseFlags 2600 | PackageParser.PARSE_IS_SYSTEM_DIR, 2601 scanFlags 2602 | SCAN_AS_SYSTEM, 2603 0); 2604 2605 // Collected privileged vendor packages. 2606 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2607 try { 2608 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2609 } catch (IOException e) { 2610 // failed to look up canonical path, continue with original one 2611 } 2612 scanDirTracedLI(privilegedVendorAppDir, 2613 mDefParseFlags 2614 | PackageParser.PARSE_IS_SYSTEM_DIR, 2615 scanFlags 2616 | SCAN_AS_SYSTEM 2617 | SCAN_AS_VENDOR 2618 | SCAN_AS_PRIVILEGED, 2619 0); 2620 2621 // Collect ordinary vendor packages. 2622 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2623 try { 2624 vendorAppDir = vendorAppDir.getCanonicalFile(); 2625 } catch (IOException e) { 2626 // failed to look up canonical path, continue with original one 2627 } 2628 scanDirTracedLI(vendorAppDir, 2629 mDefParseFlags 2630 | PackageParser.PARSE_IS_SYSTEM_DIR, 2631 scanFlags 2632 | SCAN_AS_SYSTEM 2633 | SCAN_AS_VENDOR, 2634 0); 2635 2636 // Collect all OEM packages. 2637 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2638 scanDirTracedLI(oemAppDir, 2639 mDefParseFlags 2640 | PackageParser.PARSE_IS_SYSTEM_DIR, 2641 scanFlags 2642 | SCAN_AS_SYSTEM 2643 | SCAN_AS_OEM, 2644 0); 2645 2646 // Collected privileged product packages. 2647 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2648 try { 2649 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2650 } catch (IOException e) { 2651 // failed to look up canonical path, continue with original one 2652 } 2653 scanDirTracedLI(privilegedProductAppDir, 2654 mDefParseFlags 2655 | PackageParser.PARSE_IS_SYSTEM_DIR, 2656 scanFlags 2657 | SCAN_AS_SYSTEM 2658 | SCAN_AS_PRODUCT 2659 | SCAN_AS_PRIVILEGED, 2660 0); 2661 2662 // Collect ordinary product packages. 2663 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2664 try { 2665 productAppDir = productAppDir.getCanonicalFile(); 2666 } catch (IOException e) { 2667 // failed to look up canonical path, continue with original one 2668 } 2669 scanDirTracedLI(productAppDir, 2670 mDefParseFlags 2671 | PackageParser.PARSE_IS_SYSTEM_DIR, 2672 scanFlags 2673 | SCAN_AS_SYSTEM 2674 | SCAN_AS_PRODUCT, 2675 0); 2676 2677 // Prune any system packages that no longer exist. 2678 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2679 // Stub packages must either be replaced with full versions in the /data 2680 // partition or be disabled. 2681 final List<String> stubSystemApps = new ArrayList<>(); 2682 if (!mOnlyCore) { 2683 // do this first before mucking with mPackages for the "expecting better" case 2684 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2685 while (pkgIterator.hasNext()) { 2686 final PackageParser.Package pkg = pkgIterator.next(); 2687 if (pkg.isStub) { 2688 stubSystemApps.add(pkg.packageName); 2689 } 2690 } 2691 2692 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2693 while (psit.hasNext()) { 2694 PackageSetting ps = psit.next(); 2695 2696 /* 2697 * If this is not a system app, it can't be a 2698 * disable system app. 2699 */ 2700 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2701 continue; 2702 } 2703 2704 /* 2705 * If the package is scanned, it's not erased. 2706 */ 2707 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2708 if (scannedPkg != null) { 2709 /* 2710 * If the system app is both scanned and in the 2711 * disabled packages list, then it must have been 2712 * added via OTA. Remove it from the currently 2713 * scanned package so the previously user-installed 2714 * application can be scanned. 2715 */ 2716 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2717 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2718 + ps.name + "; removing system app. Last known codePath=" 2719 + ps.codePathString + ", installStatus=" + ps.installStatus 2720 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2721 + scannedPkg.getLongVersionCode()); 2722 removePackageLI(scannedPkg, true); 2723 mExpectingBetter.put(ps.name, ps.codePath); 2724 } 2725 2726 continue; 2727 } 2728 2729 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2730 psit.remove(); 2731 logCriticalInfo(Log.WARN, "System package " + ps.name 2732 + " no longer exists; it's data will be wiped"); 2733 // Actual deletion of code and data will be handled by later 2734 // reconciliation step 2735 } else { 2736 // we still have a disabled system package, but, it still might have 2737 // been removed. check the code path still exists and check there's 2738 // still a package. the latter can happen if an OTA keeps the same 2739 // code path, but, changes the package name. 2740 final PackageSetting disabledPs = 2741 mSettings.getDisabledSystemPkgLPr(ps.name); 2742 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2743 || disabledPs.pkg == null) { 2744if (REFACTOR_DEBUG) { 2745Slog.e("TODD", 2746 "Possibly deleted app: " + ps.dumpState_temp() 2747 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2748 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2749} 2750 possiblyDeletedUpdatedSystemApps.add(ps.name); 2751 } 2752 } 2753 } 2754 } 2755 2756 //look for any incomplete package installations 2757 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2758 for (int i = 0; i < deletePkgsList.size(); i++) { 2759 // Actual deletion of code and data will be handled by later 2760 // reconciliation step 2761 final String packageName = deletePkgsList.get(i).name; 2762 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2763 synchronized (mPackages) { 2764 mSettings.removePackageLPw(packageName); 2765 } 2766 } 2767 2768 //delete tmp files 2769 deleteTempPackageFiles(); 2770 2771 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2772 2773 // Remove any shared userIDs that have no associated packages 2774 mSettings.pruneSharedUsersLPw(); 2775 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2776 final int systemPackagesCount = mPackages.size(); 2777 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2778 + " ms, packageCount: " + systemPackagesCount 2779 + " , timePerPackage: " 2780 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2781 + " , cached: " + cachedSystemApps); 2782 if (mIsUpgrade && systemPackagesCount > 0) { 2783 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2784 ((int) systemScanTime) / systemPackagesCount); 2785 } 2786 if (!mOnlyCore) { 2787 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2788 SystemClock.uptimeMillis()); 2789 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2790 2791 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2792 | PackageParser.PARSE_FORWARD_LOCK, 2793 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2794 2795 // Remove disable package settings for updated system apps that were 2796 // removed via an OTA. If the update is no longer present, remove the 2797 // app completely. Otherwise, revoke their system privileges. 2798 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2799 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2800 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2801if (REFACTOR_DEBUG) { 2802Slog.e("TODD", 2803 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2804} 2805 final String msg; 2806 if (deletedPkg == null) { 2807 // should have found an update, but, we didn't; remove everything 2808 msg = "Updated system package " + deletedAppName 2809 + " no longer exists; removing its data"; 2810 // Actual deletion of code and data will be handled by later 2811 // reconciliation step 2812 } else { 2813 // found an update; revoke system privileges 2814 msg = "Updated system package + " + deletedAppName 2815 + " no longer exists; revoking system privileges"; 2816 2817 // Don't do anything if a stub is removed from the system image. If 2818 // we were to remove the uncompressed version from the /data partition, 2819 // this is where it'd be done. 2820 2821 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2822 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2823 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2824 } 2825 logCriticalInfo(Log.WARN, msg); 2826 } 2827 2828 /* 2829 * Make sure all system apps that we expected to appear on 2830 * the userdata partition actually showed up. If they never 2831 * appeared, crawl back and revive the system version. 2832 */ 2833 for (int i = 0; i < mExpectingBetter.size(); i++) { 2834 final String packageName = mExpectingBetter.keyAt(i); 2835 if (!mPackages.containsKey(packageName)) { 2836 final File scanFile = mExpectingBetter.valueAt(i); 2837 2838 logCriticalInfo(Log.WARN, "Expected better " + packageName 2839 + " but never showed up; reverting to system"); 2840 2841 final @ParseFlags int reparseFlags; 2842 final @ScanFlags int rescanFlags; 2843 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2844 reparseFlags = 2845 mDefParseFlags | 2846 PackageParser.PARSE_IS_SYSTEM_DIR; 2847 rescanFlags = 2848 scanFlags 2849 | SCAN_AS_SYSTEM 2850 | SCAN_AS_PRIVILEGED; 2851 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2852 reparseFlags = 2853 mDefParseFlags | 2854 PackageParser.PARSE_IS_SYSTEM_DIR; 2855 rescanFlags = 2856 scanFlags 2857 | SCAN_AS_SYSTEM; 2858 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2859 reparseFlags = 2860 mDefParseFlags | 2861 PackageParser.PARSE_IS_SYSTEM_DIR; 2862 rescanFlags = 2863 scanFlags 2864 | SCAN_AS_SYSTEM 2865 | SCAN_AS_VENDOR 2866 | SCAN_AS_PRIVILEGED; 2867 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2868 reparseFlags = 2869 mDefParseFlags | 2870 PackageParser.PARSE_IS_SYSTEM_DIR; 2871 rescanFlags = 2872 scanFlags 2873 | SCAN_AS_SYSTEM 2874 | SCAN_AS_VENDOR; 2875 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2876 reparseFlags = 2877 mDefParseFlags | 2878 PackageParser.PARSE_IS_SYSTEM_DIR; 2879 rescanFlags = 2880 scanFlags 2881 | SCAN_AS_SYSTEM 2882 | SCAN_AS_OEM; 2883 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 2884 reparseFlags = 2885 mDefParseFlags | 2886 PackageParser.PARSE_IS_SYSTEM_DIR; 2887 rescanFlags = 2888 scanFlags 2889 | SCAN_AS_SYSTEM 2890 | SCAN_AS_PRODUCT 2891 | SCAN_AS_PRIVILEGED; 2892 } else if (FileUtils.contains(productAppDir, scanFile)) { 2893 reparseFlags = 2894 mDefParseFlags | 2895 PackageParser.PARSE_IS_SYSTEM_DIR; 2896 rescanFlags = 2897 scanFlags 2898 | SCAN_AS_SYSTEM 2899 | SCAN_AS_PRODUCT; 2900 } else { 2901 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2902 continue; 2903 } 2904 2905 mSettings.enableSystemPackageLPw(packageName); 2906 2907 try { 2908 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2909 } catch (PackageManagerException e) { 2910 Slog.e(TAG, "Failed to parse original system package: " 2911 + e.getMessage()); 2912 } 2913 } 2914 } 2915 2916 // Uncompress and install any stubbed system applications. 2917 // This must be done last to ensure all stubs are replaced or disabled. 2918 decompressSystemApplications(stubSystemApps, scanFlags); 2919 2920 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2921 - cachedSystemApps; 2922 2923 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2924 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2925 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2926 + " ms, packageCount: " + dataPackagesCount 2927 + " , timePerPackage: " 2928 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2929 + " , cached: " + cachedNonSystemApps); 2930 if (mIsUpgrade && dataPackagesCount > 0) { 2931 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2932 ((int) dataScanTime) / dataPackagesCount); 2933 } 2934 } 2935 mExpectingBetter.clear(); 2936 2937 // Resolve the storage manager. 2938 mStorageManagerPackage = getStorageManagerPackageName(); 2939 2940 // Resolve protected action filters. Only the setup wizard is allowed to 2941 // have a high priority filter for these actions. 2942 mSetupWizardPackage = getSetupWizardPackageName(); 2943 if (mProtectedFilters.size() > 0) { 2944 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2945 Slog.i(TAG, "No setup wizard;" 2946 + " All protected intents capped to priority 0"); 2947 } 2948 for (ActivityIntentInfo filter : mProtectedFilters) { 2949 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2950 if (DEBUG_FILTERS) { 2951 Slog.i(TAG, "Found setup wizard;" 2952 + " allow priority " + filter.getPriority() + ";" 2953 + " package: " + filter.activity.info.packageName 2954 + " activity: " + filter.activity.className 2955 + " priority: " + filter.getPriority()); 2956 } 2957 // skip setup wizard; allow it to keep the high priority filter 2958 continue; 2959 } 2960 if (DEBUG_FILTERS) { 2961 Slog.i(TAG, "Protected action; cap priority to 0;" 2962 + " package: " + filter.activity.info.packageName 2963 + " activity: " + filter.activity.className 2964 + " origPrio: " + filter.getPriority()); 2965 } 2966 filter.setPriority(0); 2967 } 2968 } 2969 mDeferProtectedFilters = false; 2970 mProtectedFilters.clear(); 2971 2972 // Now that we know all of the shared libraries, update all clients to have 2973 // the correct library paths. 2974 updateAllSharedLibrariesLPw(null); 2975 2976 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2977 // NOTE: We ignore potential failures here during a system scan (like 2978 // the rest of the commands above) because there's precious little we 2979 // can do about it. A settings error is reported, though. 2980 final List<String> changedAbiCodePath = 2981 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2982 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2983 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2984 final String codePathString = changedAbiCodePath.get(i); 2985 try { 2986 mInstaller.rmdex(codePathString, 2987 getDexCodeInstructionSet(getPreferredInstructionSet())); 2988 } catch (InstallerException ignored) { 2989 } 2990 } 2991 } 2992 } 2993 2994 // Now that we know all the packages we are keeping, 2995 // read and update their last usage times. 2996 mPackageUsage.read(mPackages); 2997 mCompilerStats.read(); 2998 2999 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3000 SystemClock.uptimeMillis()); 3001 Slog.i(TAG, "Time to scan packages: " 3002 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3003 + " seconds"); 3004 3005 // If the platform SDK has changed since the last time we booted, 3006 // we need to re-grant app permission to catch any new ones that 3007 // appear. This is really a hack, and means that apps can in some 3008 // cases get permissions that the user didn't initially explicitly 3009 // allow... it would be nice to have some better way to handle 3010 // this situation. 3011 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3012 if (sdkUpdated) { 3013 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3014 + mSdkVersion + "; regranting permissions for internal storage"); 3015 } 3016 mPermissionManager.updateAllPermissions( 3017 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3018 mPermissionCallback); 3019 ver.sdkVersion = mSdkVersion; 3020 3021 // If this is the first boot or an update from pre-M, and it is a normal 3022 // boot, then we need to initialize the default preferred apps across 3023 // all defined users. 3024 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3025 for (UserInfo user : sUserManager.getUsers(true)) { 3026 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 3027 applyFactoryDefaultBrowserLPw(user.id); 3028 primeDomainVerificationsLPw(user.id); 3029 } 3030 } 3031 3032 // Prepare storage for system user really early during boot, 3033 // since core system apps like SettingsProvider and SystemUI 3034 // can't wait for user to start 3035 final int storageFlags; 3036 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3037 storageFlags = StorageManager.FLAG_STORAGE_DE; 3038 } else { 3039 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3040 } 3041 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3042 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3043 true /* onlyCoreApps */); 3044 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3045 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3046 Trace.TRACE_TAG_PACKAGE_MANAGER); 3047 traceLog.traceBegin("AppDataFixup"); 3048 try { 3049 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3050 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3051 } catch (InstallerException e) { 3052 Slog.w(TAG, "Trouble fixing GIDs", e); 3053 } 3054 traceLog.traceEnd(); 3055 3056 traceLog.traceBegin("AppDataPrepare"); 3057 if (deferPackages == null || deferPackages.isEmpty()) { 3058 return; 3059 } 3060 int count = 0; 3061 for (String pkgName : deferPackages) { 3062 PackageParser.Package pkg = null; 3063 synchronized (mPackages) { 3064 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3065 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3066 pkg = ps.pkg; 3067 } 3068 } 3069 if (pkg != null) { 3070 synchronized (mInstallLock) { 3071 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3072 true /* maybeMigrateAppData */); 3073 } 3074 count++; 3075 } 3076 } 3077 traceLog.traceEnd(); 3078 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3079 }, "prepareAppData"); 3080 3081 // If this is first boot after an OTA, and a normal boot, then 3082 // we need to clear code cache directories. 3083 // Note that we do *not* clear the application profiles. These remain valid 3084 // across OTAs and are used to drive profile verification (post OTA) and 3085 // profile compilation (without waiting to collect a fresh set of profiles). 3086 if (mIsUpgrade && !onlyCore) { 3087 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3088 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3089 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3090 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3091 // No apps are running this early, so no need to freeze 3092 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3093 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3094 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3095 } 3096 } 3097 ver.fingerprint = Build.FINGERPRINT; 3098 } 3099 3100 checkDefaultBrowser(); 3101 3102 // clear only after permissions and other defaults have been updated 3103 mExistingSystemPackages.clear(); 3104 mPromoteSystemApps = false; 3105 3106 // All the changes are done during package scanning. 3107 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3108 3109 // can downgrade to reader 3110 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3111 mSettings.writeLPr(); 3112 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3114 SystemClock.uptimeMillis()); 3115 3116 if (!mOnlyCore) { 3117 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3118 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3119 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3120 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3121 if (mIntentFilterVerifierComponent != null) { 3122 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3123 mIntentFilterVerifierComponent); 3124 } else { 3125 mIntentFilterVerifier = null; 3126 } 3127 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3128 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3129 SharedLibraryInfo.VERSION_UNDEFINED); 3130 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3131 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3132 SharedLibraryInfo.VERSION_UNDEFINED); 3133 } else { 3134 mRequiredVerifierPackage = null; 3135 mRequiredInstallerPackage = null; 3136 mRequiredUninstallerPackage = null; 3137 mIntentFilterVerifierComponent = null; 3138 mIntentFilterVerifier = null; 3139 mServicesSystemSharedLibraryPackageName = null; 3140 mSharedSystemSharedLibraryPackageName = null; 3141 } 3142 3143 mInstallerService = new PackageInstallerService(context, this); 3144 final Pair<ComponentName, String> instantAppResolverComponent = 3145 getInstantAppResolverLPr(); 3146 if (instantAppResolverComponent != null) { 3147 if (DEBUG_EPHEMERAL) { 3148 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3149 } 3150 mInstantAppResolverConnection = new EphemeralResolverConnection( 3151 mContext, instantAppResolverComponent.first, 3152 instantAppResolverComponent.second); 3153 mInstantAppResolverSettingsComponent = 3154 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3155 } else { 3156 mInstantAppResolverConnection = null; 3157 mInstantAppResolverSettingsComponent = null; 3158 } 3159 updateInstantAppInstallerLocked(null); 3160 3161 // Read and update the usage of dex files. 3162 // Do this at the end of PM init so that all the packages have their 3163 // data directory reconciled. 3164 // At this point we know the code paths of the packages, so we can validate 3165 // the disk file and build the internal cache. 3166 // The usage file is expected to be small so loading and verifying it 3167 // should take a fairly small time compare to the other activities (e.g. package 3168 // scanning). 3169 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3170 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3171 for (int userId : currentUserIds) { 3172 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3173 } 3174 mDexManager.load(userPackages); 3175 if (mIsUpgrade) { 3176 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3177 (int) (SystemClock.uptimeMillis() - startTime)); 3178 } 3179 } // synchronized (mPackages) 3180 } // synchronized (mInstallLock) 3181 3182 // Now after opening every single application zip, make sure they 3183 // are all flushed. Not really needed, but keeps things nice and 3184 // tidy. 3185 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3186 Runtime.getRuntime().gc(); 3187 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3188 3189 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3190 FallbackCategoryProvider.loadFallbacks(); 3191 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3192 3193 // The initial scanning above does many calls into installd while 3194 // holding the mPackages lock, but we're mostly interested in yelling 3195 // once we have a booted system. 3196 mInstaller.setWarnIfHeld(mPackages); 3197 3198 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3199 } 3200 3201 /** 3202 * Uncompress and install stub applications. 3203 * <p>In order to save space on the system partition, some applications are shipped in a 3204 * compressed form. In addition the compressed bits for the full application, the 3205 * system image contains a tiny stub comprised of only the Android manifest. 3206 * <p>During the first boot, attempt to uncompress and install the full application. If 3207 * the application can't be installed for any reason, disable the stub and prevent 3208 * uncompressing the full application during future boots. 3209 * <p>In order to forcefully attempt an installation of a full application, go to app 3210 * settings and enable the application. 3211 */ 3212 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3213 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3214 final String pkgName = stubSystemApps.get(i); 3215 // skip if the system package is already disabled 3216 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3217 stubSystemApps.remove(i); 3218 continue; 3219 } 3220 // skip if the package isn't installed (?!); this should never happen 3221 final PackageParser.Package pkg = mPackages.get(pkgName); 3222 if (pkg == null) { 3223 stubSystemApps.remove(i); 3224 continue; 3225 } 3226 // skip if the package has been disabled by the user 3227 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3228 if (ps != null) { 3229 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3230 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3231 stubSystemApps.remove(i); 3232 continue; 3233 } 3234 } 3235 3236 if (DEBUG_COMPRESSION) { 3237 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3238 } 3239 3240 // uncompress the binary to its eventual destination on /data 3241 final File scanFile = decompressPackage(pkg); 3242 if (scanFile == null) { 3243 continue; 3244 } 3245 3246 // install the package to replace the stub on /system 3247 try { 3248 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3249 removePackageLI(pkg, true /*chatty*/); 3250 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3251 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3252 UserHandle.USER_SYSTEM, "android"); 3253 stubSystemApps.remove(i); 3254 continue; 3255 } catch (PackageManagerException e) { 3256 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3257 } 3258 3259 // any failed attempt to install the package will be cleaned up later 3260 } 3261 3262 // disable any stub still left; these failed to install the full application 3263 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3264 final String pkgName = stubSystemApps.get(i); 3265 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3266 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3267 UserHandle.USER_SYSTEM, "android"); 3268 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3269 } 3270 } 3271 3272 /** 3273 * Decompresses the given package on the system image onto 3274 * the /data partition. 3275 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3276 */ 3277 private File decompressPackage(PackageParser.Package pkg) { 3278 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3279 if (compressedFiles == null || compressedFiles.length == 0) { 3280 if (DEBUG_COMPRESSION) { 3281 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3282 } 3283 return null; 3284 } 3285 final File dstCodePath = 3286 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3287 int ret = PackageManager.INSTALL_SUCCEEDED; 3288 try { 3289 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3290 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3291 for (File srcFile : compressedFiles) { 3292 final String srcFileName = srcFile.getName(); 3293 final String dstFileName = srcFileName.substring( 3294 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3295 final File dstFile = new File(dstCodePath, dstFileName); 3296 ret = decompressFile(srcFile, dstFile); 3297 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3298 logCriticalInfo(Log.ERROR, "Failed to decompress" 3299 + "; pkg: " + pkg.packageName 3300 + ", file: " + dstFileName); 3301 break; 3302 } 3303 } 3304 } catch (ErrnoException e) { 3305 logCriticalInfo(Log.ERROR, "Failed to decompress" 3306 + "; pkg: " + pkg.packageName 3307 + ", err: " + e.errno); 3308 } 3309 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3310 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3311 NativeLibraryHelper.Handle handle = null; 3312 try { 3313 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3314 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3315 null /*abiOverride*/); 3316 } catch (IOException e) { 3317 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3318 + "; pkg: " + pkg.packageName); 3319 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3320 } finally { 3321 IoUtils.closeQuietly(handle); 3322 } 3323 } 3324 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3325 if (dstCodePath == null || !dstCodePath.exists()) { 3326 return null; 3327 } 3328 removeCodePathLI(dstCodePath); 3329 return null; 3330 } 3331 3332 return dstCodePath; 3333 } 3334 3335 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3336 // we're only interested in updating the installer appliction when 1) it's not 3337 // already set or 2) the modified package is the installer 3338 if (mInstantAppInstallerActivity != null 3339 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3340 .equals(modifiedPackage)) { 3341 return; 3342 } 3343 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3344 } 3345 3346 private static File preparePackageParserCache(boolean isUpgrade) { 3347 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3348 return null; 3349 } 3350 3351 // Disable package parsing on eng builds to allow for faster incremental development. 3352 if (Build.IS_ENG) { 3353 return null; 3354 } 3355 3356 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3357 Slog.i(TAG, "Disabling package parser cache due to system property."); 3358 return null; 3359 } 3360 3361 // The base directory for the package parser cache lives under /data/system/. 3362 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3363 "package_cache"); 3364 if (cacheBaseDir == null) { 3365 return null; 3366 } 3367 3368 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3369 // This also serves to "GC" unused entries when the package cache version changes (which 3370 // can only happen during upgrades). 3371 if (isUpgrade) { 3372 FileUtils.deleteContents(cacheBaseDir); 3373 } 3374 3375 3376 // Return the versioned package cache directory. This is something like 3377 // "/data/system/package_cache/1" 3378 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3379 3380 // The following is a workaround to aid development on non-numbered userdebug 3381 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3382 // the system partition is newer. 3383 // 3384 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3385 // that starts with "eng." to signify that this is an engineering build and not 3386 // destined for release. 3387 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3388 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3389 3390 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3391 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3392 // in general and should not be used for production changes. In this specific case, 3393 // we know that they will work. 3394 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3395 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3396 FileUtils.deleteContents(cacheBaseDir); 3397 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3398 } 3399 } 3400 3401 return cacheDir; 3402 } 3403 3404 @Override 3405 public boolean isFirstBoot() { 3406 // allow instant applications 3407 return mFirstBoot; 3408 } 3409 3410 @Override 3411 public boolean isOnlyCoreApps() { 3412 // allow instant applications 3413 return mOnlyCore; 3414 } 3415 3416 @Override 3417 public boolean isUpgrade() { 3418 // allow instant applications 3419 // The system property allows testing ota flow when upgraded to the same image. 3420 return mIsUpgrade || SystemProperties.getBoolean( 3421 "persist.pm.mock-upgrade", false /* default */); 3422 } 3423 3424 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3425 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3426 3427 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3428 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3429 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3430 if (matches.size() == 1) { 3431 return matches.get(0).getComponentInfo().packageName; 3432 } else if (matches.size() == 0) { 3433 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3434 return null; 3435 } 3436 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3437 } 3438 3439 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3440 synchronized (mPackages) { 3441 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3442 if (libraryEntry == null) { 3443 throw new IllegalStateException("Missing required shared library:" + name); 3444 } 3445 return libraryEntry.apk; 3446 } 3447 } 3448 3449 private @NonNull String getRequiredInstallerLPr() { 3450 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3451 intent.addCategory(Intent.CATEGORY_DEFAULT); 3452 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3453 3454 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3455 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3456 UserHandle.USER_SYSTEM); 3457 if (matches.size() == 1) { 3458 ResolveInfo resolveInfo = matches.get(0); 3459 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3460 throw new RuntimeException("The installer must be a privileged app"); 3461 } 3462 return matches.get(0).getComponentInfo().packageName; 3463 } else { 3464 throw new RuntimeException("There must be exactly one installer; found " + matches); 3465 } 3466 } 3467 3468 private @NonNull String getRequiredUninstallerLPr() { 3469 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3470 intent.addCategory(Intent.CATEGORY_DEFAULT); 3471 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3472 3473 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3474 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3475 UserHandle.USER_SYSTEM); 3476 if (resolveInfo == null || 3477 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3478 throw new RuntimeException("There must be exactly one uninstaller; found " 3479 + resolveInfo); 3480 } 3481 return resolveInfo.getComponentInfo().packageName; 3482 } 3483 3484 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3485 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3486 3487 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3488 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3489 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3490 ResolveInfo best = null; 3491 final int N = matches.size(); 3492 for (int i = 0; i < N; i++) { 3493 final ResolveInfo cur = matches.get(i); 3494 final String packageName = cur.getComponentInfo().packageName; 3495 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3496 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3497 continue; 3498 } 3499 3500 if (best == null || cur.priority > best.priority) { 3501 best = cur; 3502 } 3503 } 3504 3505 if (best != null) { 3506 return best.getComponentInfo().getComponentName(); 3507 } 3508 Slog.w(TAG, "Intent filter verifier not found"); 3509 return null; 3510 } 3511 3512 @Override 3513 public @Nullable ComponentName getInstantAppResolverComponent() { 3514 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3515 return null; 3516 } 3517 synchronized (mPackages) { 3518 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3519 if (instantAppResolver == null) { 3520 return null; 3521 } 3522 return instantAppResolver.first; 3523 } 3524 } 3525 3526 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3527 final String[] packageArray = 3528 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3529 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3530 if (DEBUG_EPHEMERAL) { 3531 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3532 } 3533 return null; 3534 } 3535 3536 final int callingUid = Binder.getCallingUid(); 3537 final int resolveFlags = 3538 MATCH_DIRECT_BOOT_AWARE 3539 | MATCH_DIRECT_BOOT_UNAWARE 3540 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3541 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3542 final Intent resolverIntent = new Intent(actionName); 3543 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3544 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3545 // temporarily look for the old action 3546 if (resolvers.size() == 0) { 3547 if (DEBUG_EPHEMERAL) { 3548 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3549 } 3550 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3551 resolverIntent.setAction(actionName); 3552 resolvers = queryIntentServicesInternal(resolverIntent, null, 3553 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3554 } 3555 final int N = resolvers.size(); 3556 if (N == 0) { 3557 if (DEBUG_EPHEMERAL) { 3558 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3559 } 3560 return null; 3561 } 3562 3563 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3564 for (int i = 0; i < N; i++) { 3565 final ResolveInfo info = resolvers.get(i); 3566 3567 if (info.serviceInfo == null) { 3568 continue; 3569 } 3570 3571 final String packageName = info.serviceInfo.packageName; 3572 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3573 if (DEBUG_EPHEMERAL) { 3574 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3575 + " pkg: " + packageName + ", info:" + info); 3576 } 3577 continue; 3578 } 3579 3580 if (DEBUG_EPHEMERAL) { 3581 Slog.v(TAG, "Ephemeral resolver found;" 3582 + " pkg: " + packageName + ", info:" + info); 3583 } 3584 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3585 } 3586 if (DEBUG_EPHEMERAL) { 3587 Slog.v(TAG, "Ephemeral resolver NOT found"); 3588 } 3589 return null; 3590 } 3591 3592 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3593 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3594 intent.addCategory(Intent.CATEGORY_DEFAULT); 3595 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3596 3597 final int resolveFlags = 3598 MATCH_DIRECT_BOOT_AWARE 3599 | MATCH_DIRECT_BOOT_UNAWARE 3600 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3601 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3602 resolveFlags, UserHandle.USER_SYSTEM); 3603 // temporarily look for the old action 3604 if (matches.isEmpty()) { 3605 if (DEBUG_EPHEMERAL) { 3606 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3607 } 3608 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3609 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3610 resolveFlags, UserHandle.USER_SYSTEM); 3611 } 3612 Iterator<ResolveInfo> iter = matches.iterator(); 3613 while (iter.hasNext()) { 3614 final ResolveInfo rInfo = iter.next(); 3615 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3616 if (ps != null) { 3617 final PermissionsState permissionsState = ps.getPermissionsState(); 3618 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3619 continue; 3620 } 3621 } 3622 iter.remove(); 3623 } 3624 if (matches.size() == 0) { 3625 return null; 3626 } else if (matches.size() == 1) { 3627 return (ActivityInfo) matches.get(0).getComponentInfo(); 3628 } else { 3629 throw new RuntimeException( 3630 "There must be at most one ephemeral installer; found " + matches); 3631 } 3632 } 3633 3634 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3635 @NonNull ComponentName resolver) { 3636 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3637 .addCategory(Intent.CATEGORY_DEFAULT) 3638 .setPackage(resolver.getPackageName()); 3639 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3640 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3641 UserHandle.USER_SYSTEM); 3642 // temporarily look for the old action 3643 if (matches.isEmpty()) { 3644 if (DEBUG_EPHEMERAL) { 3645 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3646 } 3647 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3648 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3649 UserHandle.USER_SYSTEM); 3650 } 3651 if (matches.isEmpty()) { 3652 return null; 3653 } 3654 return matches.get(0).getComponentInfo().getComponentName(); 3655 } 3656 3657 private void primeDomainVerificationsLPw(int userId) { 3658 if (DEBUG_DOMAIN_VERIFICATION) { 3659 Slog.d(TAG, "Priming domain verifications in user " + userId); 3660 } 3661 3662 SystemConfig systemConfig = SystemConfig.getInstance(); 3663 ArraySet<String> packages = systemConfig.getLinkedApps(); 3664 3665 for (String packageName : packages) { 3666 PackageParser.Package pkg = mPackages.get(packageName); 3667 if (pkg != null) { 3668 if (!pkg.isSystem()) { 3669 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3670 continue; 3671 } 3672 3673 ArraySet<String> domains = null; 3674 for (PackageParser.Activity a : pkg.activities) { 3675 for (ActivityIntentInfo filter : a.intents) { 3676 if (hasValidDomains(filter)) { 3677 if (domains == null) { 3678 domains = new ArraySet<String>(); 3679 } 3680 domains.addAll(filter.getHostsList()); 3681 } 3682 } 3683 } 3684 3685 if (domains != null && domains.size() > 0) { 3686 if (DEBUG_DOMAIN_VERIFICATION) { 3687 Slog.v(TAG, " + " + packageName); 3688 } 3689 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3690 // state w.r.t. the formal app-linkage "no verification attempted" state; 3691 // and then 'always' in the per-user state actually used for intent resolution. 3692 final IntentFilterVerificationInfo ivi; 3693 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3694 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3695 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3696 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3697 } else { 3698 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3699 + "' does not handle web links"); 3700 } 3701 } else { 3702 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3703 } 3704 } 3705 3706 scheduleWritePackageRestrictionsLocked(userId); 3707 scheduleWriteSettingsLocked(); 3708 } 3709 3710 private void applyFactoryDefaultBrowserLPw(int userId) { 3711 // The default browser app's package name is stored in a string resource, 3712 // with a product-specific overlay used for vendor customization. 3713 String browserPkg = mContext.getResources().getString( 3714 com.android.internal.R.string.default_browser); 3715 if (!TextUtils.isEmpty(browserPkg)) { 3716 // non-empty string => required to be a known package 3717 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3718 if (ps == null) { 3719 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3720 browserPkg = null; 3721 } else { 3722 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3723 } 3724 } 3725 3726 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3727 // default. If there's more than one, just leave everything alone. 3728 if (browserPkg == null) { 3729 calculateDefaultBrowserLPw(userId); 3730 } 3731 } 3732 3733 private void calculateDefaultBrowserLPw(int userId) { 3734 List<String> allBrowsers = resolveAllBrowserApps(userId); 3735 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3736 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3737 } 3738 3739 private List<String> resolveAllBrowserApps(int userId) { 3740 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3741 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3742 PackageManager.MATCH_ALL, userId); 3743 3744 final int count = list.size(); 3745 List<String> result = new ArrayList<String>(count); 3746 for (int i=0; i<count; i++) { 3747 ResolveInfo info = list.get(i); 3748 if (info.activityInfo == null 3749 || !info.handleAllWebDataURI 3750 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3751 || result.contains(info.activityInfo.packageName)) { 3752 continue; 3753 } 3754 result.add(info.activityInfo.packageName); 3755 } 3756 3757 return result; 3758 } 3759 3760 private boolean packageIsBrowser(String packageName, int userId) { 3761 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3762 PackageManager.MATCH_ALL, userId); 3763 final int N = list.size(); 3764 for (int i = 0; i < N; i++) { 3765 ResolveInfo info = list.get(i); 3766 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3767 return true; 3768 } 3769 } 3770 return false; 3771 } 3772 3773 private void checkDefaultBrowser() { 3774 final int myUserId = UserHandle.myUserId(); 3775 final String packageName = getDefaultBrowserPackageName(myUserId); 3776 if (packageName != null) { 3777 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3778 if (info == null) { 3779 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3780 synchronized (mPackages) { 3781 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3782 } 3783 } 3784 } 3785 } 3786 3787 @Override 3788 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3789 throws RemoteException { 3790 try { 3791 return super.onTransact(code, data, reply, flags); 3792 } catch (RuntimeException e) { 3793 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3794 Slog.wtf(TAG, "Package Manager Crash", e); 3795 } 3796 throw e; 3797 } 3798 } 3799 3800 static int[] appendInts(int[] cur, int[] add) { 3801 if (add == null) return cur; 3802 if (cur == null) return add; 3803 final int N = add.length; 3804 for (int i=0; i<N; i++) { 3805 cur = appendInt(cur, add[i]); 3806 } 3807 return cur; 3808 } 3809 3810 /** 3811 * Returns whether or not a full application can see an instant application. 3812 * <p> 3813 * Currently, there are three cases in which this can occur: 3814 * <ol> 3815 * <li>The calling application is a "special" process. Special processes 3816 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3817 * <li>The calling application has the permission 3818 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3819 * <li>The calling application is the default launcher on the 3820 * system partition.</li> 3821 * </ol> 3822 */ 3823 private boolean canViewInstantApps(int callingUid, int userId) { 3824 if (callingUid < Process.FIRST_APPLICATION_UID) { 3825 return true; 3826 } 3827 if (mContext.checkCallingOrSelfPermission( 3828 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3829 return true; 3830 } 3831 if (mContext.checkCallingOrSelfPermission( 3832 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3833 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3834 if (homeComponent != null 3835 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3836 return true; 3837 } 3838 } 3839 return false; 3840 } 3841 3842 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3843 if (!sUserManager.exists(userId)) return null; 3844 if (ps == null) { 3845 return null; 3846 } 3847 PackageParser.Package p = ps.pkg; 3848 if (p == null) { 3849 return null; 3850 } 3851 final int callingUid = Binder.getCallingUid(); 3852 // Filter out ephemeral app metadata: 3853 // * The system/shell/root can see metadata for any app 3854 // * An installed app can see metadata for 1) other installed apps 3855 // and 2) ephemeral apps that have explicitly interacted with it 3856 // * Ephemeral apps can only see their own data and exposed installed apps 3857 // * Holding a signature permission allows seeing instant apps 3858 if (filterAppAccessLPr(ps, callingUid, userId)) { 3859 return null; 3860 } 3861 3862 final PermissionsState permissionsState = ps.getPermissionsState(); 3863 3864 // Compute GIDs only if requested 3865 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3866 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3867 // Compute granted permissions only if package has requested permissions 3868 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3869 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3870 final PackageUserState state = ps.readUserState(userId); 3871 3872 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3873 && ps.isSystem()) { 3874 flags |= MATCH_ANY_USER; 3875 } 3876 3877 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3878 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3879 3880 if (packageInfo == null) { 3881 return null; 3882 } 3883 3884 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3885 resolveExternalPackageNameLPr(p); 3886 3887 return packageInfo; 3888 } 3889 3890 @Override 3891 public void checkPackageStartable(String packageName, int userId) { 3892 final int callingUid = Binder.getCallingUid(); 3893 if (getInstantAppPackageName(callingUid) != null) { 3894 throw new SecurityException("Instant applications don't have access to this method"); 3895 } 3896 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3897 synchronized (mPackages) { 3898 final PackageSetting ps = mSettings.mPackages.get(packageName); 3899 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3900 throw new SecurityException("Package " + packageName + " was not found!"); 3901 } 3902 3903 if (!ps.getInstalled(userId)) { 3904 throw new SecurityException( 3905 "Package " + packageName + " was not installed for user " + userId + "!"); 3906 } 3907 3908 if (mSafeMode && !ps.isSystem()) { 3909 throw new SecurityException("Package " + packageName + " not a system app!"); 3910 } 3911 3912 if (mFrozenPackages.contains(packageName)) { 3913 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3914 } 3915 3916 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3917 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3918 } 3919 } 3920 } 3921 3922 @Override 3923 public boolean isPackageAvailable(String packageName, int userId) { 3924 if (!sUserManager.exists(userId)) return false; 3925 final int callingUid = Binder.getCallingUid(); 3926 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3927 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3928 synchronized (mPackages) { 3929 PackageParser.Package p = mPackages.get(packageName); 3930 if (p != null) { 3931 final PackageSetting ps = (PackageSetting) p.mExtras; 3932 if (filterAppAccessLPr(ps, callingUid, userId)) { 3933 return false; 3934 } 3935 if (ps != null) { 3936 final PackageUserState state = ps.readUserState(userId); 3937 if (state != null) { 3938 return PackageParser.isAvailable(state); 3939 } 3940 } 3941 } 3942 } 3943 return false; 3944 } 3945 3946 @Override 3947 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3948 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3949 flags, Binder.getCallingUid(), userId); 3950 } 3951 3952 @Override 3953 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3954 int flags, int userId) { 3955 return getPackageInfoInternal(versionedPackage.getPackageName(), 3956 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3957 } 3958 3959 /** 3960 * Important: The provided filterCallingUid is used exclusively to filter out packages 3961 * that can be seen based on user state. It's typically the original caller uid prior 3962 * to clearing. Because it can only be provided by trusted code, it's value can be 3963 * trusted and will be used as-is; unlike userId which will be validated by this method. 3964 */ 3965 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3966 int flags, int filterCallingUid, int userId) { 3967 if (!sUserManager.exists(userId)) return null; 3968 flags = updateFlagsForPackage(flags, userId, packageName); 3969 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3970 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3971 3972 // reader 3973 synchronized (mPackages) { 3974 // Normalize package name to handle renamed packages and static libs 3975 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3976 3977 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3978 if (matchFactoryOnly) { 3979 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3980 if (ps != null) { 3981 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3982 return null; 3983 } 3984 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3985 return null; 3986 } 3987 return generatePackageInfo(ps, flags, userId); 3988 } 3989 } 3990 3991 PackageParser.Package p = mPackages.get(packageName); 3992 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3993 return null; 3994 } 3995 if (DEBUG_PACKAGE_INFO) 3996 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3997 if (p != null) { 3998 final PackageSetting ps = (PackageSetting) p.mExtras; 3999 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4000 return null; 4001 } 4002 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4003 return null; 4004 } 4005 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4006 } 4007 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4008 final PackageSetting ps = mSettings.mPackages.get(packageName); 4009 if (ps == null) return null; 4010 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4011 return null; 4012 } 4013 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4014 return null; 4015 } 4016 return generatePackageInfo(ps, flags, userId); 4017 } 4018 } 4019 return null; 4020 } 4021 4022 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4023 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4024 return true; 4025 } 4026 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4027 return true; 4028 } 4029 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4030 return true; 4031 } 4032 return false; 4033 } 4034 4035 private boolean isComponentVisibleToInstantApp( 4036 @Nullable ComponentName component, @ComponentType int type) { 4037 if (type == TYPE_ACTIVITY) { 4038 final PackageParser.Activity activity = mActivities.mActivities.get(component); 4039 return activity != null 4040 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4041 : false; 4042 } else if (type == TYPE_RECEIVER) { 4043 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 4044 return activity != null 4045 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4046 : false; 4047 } else if (type == TYPE_SERVICE) { 4048 final PackageParser.Service service = mServices.mServices.get(component); 4049 return service != null 4050 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4051 : false; 4052 } else if (type == TYPE_PROVIDER) { 4053 final PackageParser.Provider provider = mProviders.mProviders.get(component); 4054 return provider != null 4055 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4056 : false; 4057 } else if (type == TYPE_UNKNOWN) { 4058 return isComponentVisibleToInstantApp(component); 4059 } 4060 return false; 4061 } 4062 4063 /** 4064 * Returns whether or not access to the application should be filtered. 4065 * <p> 4066 * Access may be limited based upon whether the calling or target applications 4067 * are instant applications. 4068 * 4069 * @see #canAccessInstantApps(int) 4070 */ 4071 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4072 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4073 // if we're in an isolated process, get the real calling UID 4074 if (Process.isIsolated(callingUid)) { 4075 callingUid = mIsolatedOwners.get(callingUid); 4076 } 4077 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4078 final boolean callerIsInstantApp = instantAppPkgName != null; 4079 if (ps == null) { 4080 if (callerIsInstantApp) { 4081 // pretend the application exists, but, needs to be filtered 4082 return true; 4083 } 4084 return false; 4085 } 4086 // if the target and caller are the same application, don't filter 4087 if (isCallerSameApp(ps.name, callingUid)) { 4088 return false; 4089 } 4090 if (callerIsInstantApp) { 4091 // request for a specific component; if it hasn't been explicitly exposed, filter 4092 if (component != null) { 4093 return !isComponentVisibleToInstantApp(component, componentType); 4094 } 4095 // request for application; if no components have been explicitly exposed, filter 4096 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4097 } 4098 if (ps.getInstantApp(userId)) { 4099 // caller can see all components of all instant applications, don't filter 4100 if (canViewInstantApps(callingUid, userId)) { 4101 return false; 4102 } 4103 // request for a specific instant application component, filter 4104 if (component != null) { 4105 return true; 4106 } 4107 // request for an instant application; if the caller hasn't been granted access, filter 4108 return !mInstantAppRegistry.isInstantAccessGranted( 4109 userId, UserHandle.getAppId(callingUid), ps.appId); 4110 } 4111 return false; 4112 } 4113 4114 /** 4115 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4116 */ 4117 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4118 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4119 } 4120 4121 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4122 int flags) { 4123 // Callers can access only the libs they depend on, otherwise they need to explicitly 4124 // ask for the shared libraries given the caller is allowed to access all static libs. 4125 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4126 // System/shell/root get to see all static libs 4127 final int appId = UserHandle.getAppId(uid); 4128 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4129 || appId == Process.ROOT_UID) { 4130 return false; 4131 } 4132 } 4133 4134 // No package means no static lib as it is always on internal storage 4135 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4136 return false; 4137 } 4138 4139 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4140 ps.pkg.staticSharedLibVersion); 4141 if (libEntry == null) { 4142 return false; 4143 } 4144 4145 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4146 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4147 if (uidPackageNames == null) { 4148 return true; 4149 } 4150 4151 for (String uidPackageName : uidPackageNames) { 4152 if (ps.name.equals(uidPackageName)) { 4153 return false; 4154 } 4155 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4156 if (uidPs != null) { 4157 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4158 libEntry.info.getName()); 4159 if (index < 0) { 4160 continue; 4161 } 4162 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4163 return false; 4164 } 4165 } 4166 } 4167 return true; 4168 } 4169 4170 @Override 4171 public String[] currentToCanonicalPackageNames(String[] names) { 4172 final int callingUid = Binder.getCallingUid(); 4173 if (getInstantAppPackageName(callingUid) != null) { 4174 return names; 4175 } 4176 final String[] out = new String[names.length]; 4177 // reader 4178 synchronized (mPackages) { 4179 final int callingUserId = UserHandle.getUserId(callingUid); 4180 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4181 for (int i=names.length-1; i>=0; i--) { 4182 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4183 boolean translateName = false; 4184 if (ps != null && ps.realName != null) { 4185 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4186 translateName = !targetIsInstantApp 4187 || canViewInstantApps 4188 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4189 UserHandle.getAppId(callingUid), ps.appId); 4190 } 4191 out[i] = translateName ? ps.realName : names[i]; 4192 } 4193 } 4194 return out; 4195 } 4196 4197 @Override 4198 public String[] canonicalToCurrentPackageNames(String[] names) { 4199 final int callingUid = Binder.getCallingUid(); 4200 if (getInstantAppPackageName(callingUid) != null) { 4201 return names; 4202 } 4203 final String[] out = new String[names.length]; 4204 // reader 4205 synchronized (mPackages) { 4206 final int callingUserId = UserHandle.getUserId(callingUid); 4207 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4208 for (int i=names.length-1; i>=0; i--) { 4209 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4210 boolean translateName = false; 4211 if (cur != null) { 4212 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4213 final boolean targetIsInstantApp = 4214 ps != null && ps.getInstantApp(callingUserId); 4215 translateName = !targetIsInstantApp 4216 || canViewInstantApps 4217 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4218 UserHandle.getAppId(callingUid), ps.appId); 4219 } 4220 out[i] = translateName ? cur : names[i]; 4221 } 4222 } 4223 return out; 4224 } 4225 4226 @Override 4227 public int getPackageUid(String packageName, int flags, int userId) { 4228 if (!sUserManager.exists(userId)) return -1; 4229 final int callingUid = Binder.getCallingUid(); 4230 flags = updateFlagsForPackage(flags, userId, packageName); 4231 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4232 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4233 4234 // reader 4235 synchronized (mPackages) { 4236 final PackageParser.Package p = mPackages.get(packageName); 4237 if (p != null && p.isMatch(flags)) { 4238 PackageSetting ps = (PackageSetting) p.mExtras; 4239 if (filterAppAccessLPr(ps, callingUid, userId)) { 4240 return -1; 4241 } 4242 return UserHandle.getUid(userId, p.applicationInfo.uid); 4243 } 4244 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4245 final PackageSetting ps = mSettings.mPackages.get(packageName); 4246 if (ps != null && ps.isMatch(flags) 4247 && !filterAppAccessLPr(ps, callingUid, userId)) { 4248 return UserHandle.getUid(userId, ps.appId); 4249 } 4250 } 4251 } 4252 4253 return -1; 4254 } 4255 4256 @Override 4257 public int[] getPackageGids(String packageName, int flags, int userId) { 4258 if (!sUserManager.exists(userId)) return null; 4259 final int callingUid = Binder.getCallingUid(); 4260 flags = updateFlagsForPackage(flags, userId, packageName); 4261 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4262 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4263 4264 // reader 4265 synchronized (mPackages) { 4266 final PackageParser.Package p = mPackages.get(packageName); 4267 if (p != null && p.isMatch(flags)) { 4268 PackageSetting ps = (PackageSetting) p.mExtras; 4269 if (filterAppAccessLPr(ps, callingUid, userId)) { 4270 return null; 4271 } 4272 // TODO: Shouldn't this be checking for package installed state for userId and 4273 // return null? 4274 return ps.getPermissionsState().computeGids(userId); 4275 } 4276 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4277 final PackageSetting ps = mSettings.mPackages.get(packageName); 4278 if (ps != null && ps.isMatch(flags) 4279 && !filterAppAccessLPr(ps, callingUid, userId)) { 4280 return ps.getPermissionsState().computeGids(userId); 4281 } 4282 } 4283 } 4284 4285 return null; 4286 } 4287 4288 @Override 4289 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4290 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4291 } 4292 4293 @Override 4294 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4295 int flags) { 4296 final List<PermissionInfo> permissionList = 4297 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4298 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4299 } 4300 4301 @Override 4302 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4303 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4304 } 4305 4306 @Override 4307 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4308 final List<PermissionGroupInfo> permissionList = 4309 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4310 return (permissionList == null) 4311 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4312 } 4313 4314 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4315 int filterCallingUid, int userId) { 4316 if (!sUserManager.exists(userId)) return null; 4317 PackageSetting ps = mSettings.mPackages.get(packageName); 4318 if (ps != null) { 4319 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4320 return null; 4321 } 4322 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4323 return null; 4324 } 4325 if (ps.pkg == null) { 4326 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4327 if (pInfo != null) { 4328 return pInfo.applicationInfo; 4329 } 4330 return null; 4331 } 4332 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4333 ps.readUserState(userId), userId); 4334 if (ai != null) { 4335 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4336 } 4337 return ai; 4338 } 4339 return null; 4340 } 4341 4342 @Override 4343 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4344 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4345 } 4346 4347 /** 4348 * Important: The provided filterCallingUid is used exclusively to filter out applications 4349 * that can be seen based on user state. It's typically the original caller uid prior 4350 * to clearing. Because it can only be provided by trusted code, it's value can be 4351 * trusted and will be used as-is; unlike userId which will be validated by this method. 4352 */ 4353 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4354 int filterCallingUid, int userId) { 4355 if (!sUserManager.exists(userId)) return null; 4356 flags = updateFlagsForApplication(flags, userId, packageName); 4357 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4358 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4359 4360 // writer 4361 synchronized (mPackages) { 4362 // Normalize package name to handle renamed packages and static libs 4363 packageName = resolveInternalPackageNameLPr(packageName, 4364 PackageManager.VERSION_CODE_HIGHEST); 4365 4366 PackageParser.Package p = mPackages.get(packageName); 4367 if (DEBUG_PACKAGE_INFO) Log.v( 4368 TAG, "getApplicationInfo " + packageName 4369 + ": " + p); 4370 if (p != null) { 4371 PackageSetting ps = mSettings.mPackages.get(packageName); 4372 if (ps == null) return null; 4373 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4374 return null; 4375 } 4376 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4377 return null; 4378 } 4379 // Note: isEnabledLP() does not apply here - always return info 4380 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4381 p, flags, ps.readUserState(userId), userId); 4382 if (ai != null) { 4383 ai.packageName = resolveExternalPackageNameLPr(p); 4384 } 4385 return ai; 4386 } 4387 if ("android".equals(packageName)||"system".equals(packageName)) { 4388 return mAndroidApplication; 4389 } 4390 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4391 // Already generates the external package name 4392 return generateApplicationInfoFromSettingsLPw(packageName, 4393 flags, filterCallingUid, userId); 4394 } 4395 } 4396 return null; 4397 } 4398 4399 private String normalizePackageNameLPr(String packageName) { 4400 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4401 return normalizedPackageName != null ? normalizedPackageName : packageName; 4402 } 4403 4404 @Override 4405 public void deletePreloadsFileCache() { 4406 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4407 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4408 } 4409 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4410 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4411 FileUtils.deleteContents(dir); 4412 } 4413 4414 @Override 4415 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4416 final int storageFlags, final IPackageDataObserver observer) { 4417 mContext.enforceCallingOrSelfPermission( 4418 android.Manifest.permission.CLEAR_APP_CACHE, null); 4419 mHandler.post(() -> { 4420 boolean success = false; 4421 try { 4422 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4423 success = true; 4424 } catch (IOException e) { 4425 Slog.w(TAG, e); 4426 } 4427 if (observer != null) { 4428 try { 4429 observer.onRemoveCompleted(null, success); 4430 } catch (RemoteException e) { 4431 Slog.w(TAG, e); 4432 } 4433 } 4434 }); 4435 } 4436 4437 @Override 4438 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4439 final int storageFlags, final IntentSender pi) { 4440 mContext.enforceCallingOrSelfPermission( 4441 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4442 mHandler.post(() -> { 4443 boolean success = false; 4444 try { 4445 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4446 success = true; 4447 } catch (IOException e) { 4448 Slog.w(TAG, e); 4449 } 4450 if (pi != null) { 4451 try { 4452 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4453 } catch (SendIntentException e) { 4454 Slog.w(TAG, e); 4455 } 4456 } 4457 }); 4458 } 4459 4460 /** 4461 * Blocking call to clear various types of cached data across the system 4462 * until the requested bytes are available. 4463 */ 4464 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4465 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4466 final File file = storage.findPathForUuid(volumeUuid); 4467 if (file.getUsableSpace() >= bytes) return; 4468 4469 if (ENABLE_FREE_CACHE_V2) { 4470 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4471 volumeUuid); 4472 final boolean aggressive = (storageFlags 4473 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4474 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4475 4476 // 1. Pre-flight to determine if we have any chance to succeed 4477 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4478 if (internalVolume && (aggressive || SystemProperties 4479 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4480 deletePreloadsFileCache(); 4481 if (file.getUsableSpace() >= bytes) return; 4482 } 4483 4484 // 3. Consider parsed APK data (aggressive only) 4485 if (internalVolume && aggressive) { 4486 FileUtils.deleteContents(mCacheDir); 4487 if (file.getUsableSpace() >= bytes) return; 4488 } 4489 4490 // 4. Consider cached app data (above quotas) 4491 try { 4492 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4493 Installer.FLAG_FREE_CACHE_V2); 4494 } catch (InstallerException ignored) { 4495 } 4496 if (file.getUsableSpace() >= bytes) return; 4497 4498 // 5. Consider shared libraries with refcount=0 and age>min cache period 4499 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4500 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4501 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4502 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4503 return; 4504 } 4505 4506 // 6. Consider dexopt output (aggressive only) 4507 // TODO: Implement 4508 4509 // 7. Consider installed instant apps unused longer than min cache period 4510 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4511 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4512 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4513 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4514 return; 4515 } 4516 4517 // 8. Consider cached app data (below quotas) 4518 try { 4519 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4520 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4521 } catch (InstallerException ignored) { 4522 } 4523 if (file.getUsableSpace() >= bytes) return; 4524 4525 // 9. Consider DropBox entries 4526 // TODO: Implement 4527 4528 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4529 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4530 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4531 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4532 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4533 return; 4534 } 4535 } else { 4536 try { 4537 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4538 } catch (InstallerException ignored) { 4539 } 4540 if (file.getUsableSpace() >= bytes) return; 4541 } 4542 4543 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4544 } 4545 4546 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4547 throws IOException { 4548 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4549 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4550 4551 List<VersionedPackage> packagesToDelete = null; 4552 final long now = System.currentTimeMillis(); 4553 4554 synchronized (mPackages) { 4555 final int[] allUsers = sUserManager.getUserIds(); 4556 final int libCount = mSharedLibraries.size(); 4557 for (int i = 0; i < libCount; i++) { 4558 final LongSparseArray<SharedLibraryEntry> versionedLib 4559 = mSharedLibraries.valueAt(i); 4560 if (versionedLib == null) { 4561 continue; 4562 } 4563 final int versionCount = versionedLib.size(); 4564 for (int j = 0; j < versionCount; j++) { 4565 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4566 // Skip packages that are not static shared libs. 4567 if (!libInfo.isStatic()) { 4568 break; 4569 } 4570 // Important: We skip static shared libs used for some user since 4571 // in such a case we need to keep the APK on the device. The check for 4572 // a lib being used for any user is performed by the uninstall call. 4573 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4574 // Resolve the package name - we use synthetic package names internally 4575 final String internalPackageName = resolveInternalPackageNameLPr( 4576 declaringPackage.getPackageName(), 4577 declaringPackage.getLongVersionCode()); 4578 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4579 // Skip unused static shared libs cached less than the min period 4580 // to prevent pruning a lib needed by a subsequently installed package. 4581 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4582 continue; 4583 } 4584 if (packagesToDelete == null) { 4585 packagesToDelete = new ArrayList<>(); 4586 } 4587 packagesToDelete.add(new VersionedPackage(internalPackageName, 4588 declaringPackage.getLongVersionCode())); 4589 } 4590 } 4591 } 4592 4593 if (packagesToDelete != null) { 4594 final int packageCount = packagesToDelete.size(); 4595 for (int i = 0; i < packageCount; i++) { 4596 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4597 // Delete the package synchronously (will fail of the lib used for any user). 4598 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4599 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4600 == PackageManager.DELETE_SUCCEEDED) { 4601 if (volume.getUsableSpace() >= neededSpace) { 4602 return true; 4603 } 4604 } 4605 } 4606 } 4607 4608 return false; 4609 } 4610 4611 /** 4612 * Update given flags based on encryption status of current user. 4613 */ 4614 private int updateFlags(int flags, int userId) { 4615 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4616 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4617 // Caller expressed an explicit opinion about what encryption 4618 // aware/unaware components they want to see, so fall through and 4619 // give them what they want 4620 } else { 4621 // Caller expressed no opinion, so match based on user state 4622 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4623 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4624 } else { 4625 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4626 } 4627 } 4628 return flags; 4629 } 4630 4631 private UserManagerInternal getUserManagerInternal() { 4632 if (mUserManagerInternal == null) { 4633 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4634 } 4635 return mUserManagerInternal; 4636 } 4637 4638 private ActivityManagerInternal getActivityManagerInternal() { 4639 if (mActivityManagerInternal == null) { 4640 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4641 } 4642 return mActivityManagerInternal; 4643 } 4644 4645 4646 private DeviceIdleController.LocalService getDeviceIdleController() { 4647 if (mDeviceIdleController == null) { 4648 mDeviceIdleController = 4649 LocalServices.getService(DeviceIdleController.LocalService.class); 4650 } 4651 return mDeviceIdleController; 4652 } 4653 4654 /** 4655 * Update given flags when being used to request {@link PackageInfo}. 4656 */ 4657 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4658 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4659 boolean triaged = true; 4660 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4661 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4662 // Caller is asking for component details, so they'd better be 4663 // asking for specific encryption matching behavior, or be triaged 4664 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4665 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4666 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4667 triaged = false; 4668 } 4669 } 4670 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4671 | PackageManager.MATCH_SYSTEM_ONLY 4672 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4673 triaged = false; 4674 } 4675 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4676 mPermissionManager.enforceCrossUserPermission( 4677 Binder.getCallingUid(), userId, false, false, 4678 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4679 + Debug.getCallers(5)); 4680 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4681 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4682 // If the caller wants all packages and has a restricted profile associated with it, 4683 // then match all users. This is to make sure that launchers that need to access work 4684 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4685 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4686 flags |= PackageManager.MATCH_ANY_USER; 4687 } 4688 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4689 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4690 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4691 } 4692 return updateFlags(flags, userId); 4693 } 4694 4695 /** 4696 * Update given flags when being used to request {@link ApplicationInfo}. 4697 */ 4698 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4699 return updateFlagsForPackage(flags, userId, cookie); 4700 } 4701 4702 /** 4703 * Update given flags when being used to request {@link ComponentInfo}. 4704 */ 4705 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4706 if (cookie instanceof Intent) { 4707 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4708 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4709 } 4710 } 4711 4712 boolean triaged = true; 4713 // Caller is asking for component details, so they'd better be 4714 // asking for specific encryption matching behavior, or be triaged 4715 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4716 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4717 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4718 triaged = false; 4719 } 4720 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4721 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4722 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4723 } 4724 4725 return updateFlags(flags, userId); 4726 } 4727 4728 /** 4729 * Update given intent when being used to request {@link ResolveInfo}. 4730 */ 4731 private Intent updateIntentForResolve(Intent intent) { 4732 if (intent.getSelector() != null) { 4733 intent = intent.getSelector(); 4734 } 4735 if (DEBUG_PREFERRED) { 4736 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4737 } 4738 return intent; 4739 } 4740 4741 /** 4742 * Update given flags when being used to request {@link ResolveInfo}. 4743 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4744 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4745 * flag set. However, this flag is only honoured in three circumstances: 4746 * <ul> 4747 * <li>when called from a system process</li> 4748 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4749 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4750 * action and a {@code android.intent.category.BROWSABLE} category</li> 4751 * </ul> 4752 */ 4753 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4754 return updateFlagsForResolve(flags, userId, intent, callingUid, 4755 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4756 } 4757 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4758 boolean wantInstantApps) { 4759 return updateFlagsForResolve(flags, userId, intent, callingUid, 4760 wantInstantApps, false /*onlyExposedExplicitly*/); 4761 } 4762 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4763 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4764 // Safe mode means we shouldn't match any third-party components 4765 if (mSafeMode) { 4766 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4767 } 4768 if (getInstantAppPackageName(callingUid) != null) { 4769 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4770 if (onlyExposedExplicitly) { 4771 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4772 } 4773 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4774 flags |= PackageManager.MATCH_INSTANT; 4775 } else { 4776 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4777 final boolean allowMatchInstant = 4778 (wantInstantApps 4779 && Intent.ACTION_VIEW.equals(intent.getAction()) 4780 && hasWebURI(intent)) 4781 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4782 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4783 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4784 if (!allowMatchInstant) { 4785 flags &= ~PackageManager.MATCH_INSTANT; 4786 } 4787 } 4788 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4789 } 4790 4791 @Override 4792 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4793 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4794 } 4795 4796 /** 4797 * Important: The provided filterCallingUid is used exclusively to filter out activities 4798 * that can be seen based on user state. It's typically the original caller uid prior 4799 * to clearing. Because it can only be provided by trusted code, it's value can be 4800 * trusted and will be used as-is; unlike userId which will be validated by this method. 4801 */ 4802 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4803 int filterCallingUid, int userId) { 4804 if (!sUserManager.exists(userId)) return null; 4805 flags = updateFlagsForComponent(flags, userId, component); 4806 4807 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4808 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4809 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4810 } 4811 4812 synchronized (mPackages) { 4813 PackageParser.Activity a = mActivities.mActivities.get(component); 4814 4815 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4816 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4817 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4818 if (ps == null) return null; 4819 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4820 return null; 4821 } 4822 return PackageParser.generateActivityInfo( 4823 a, flags, ps.readUserState(userId), userId); 4824 } 4825 if (mResolveComponentName.equals(component)) { 4826 return PackageParser.generateActivityInfo( 4827 mResolveActivity, flags, new PackageUserState(), userId); 4828 } 4829 } 4830 return null; 4831 } 4832 4833 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 4834 if (!getActivityManagerInternal().isCallerRecents(callingUid)) { 4835 return false; 4836 } 4837 final long token = Binder.clearCallingIdentity(); 4838 try { 4839 final int callingUserId = UserHandle.getUserId(callingUid); 4840 if (ActivityManager.getCurrentUser() != callingUserId) { 4841 return false; 4842 } 4843 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 4844 } finally { 4845 Binder.restoreCallingIdentity(token); 4846 } 4847 } 4848 4849 @Override 4850 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4851 String resolvedType) { 4852 synchronized (mPackages) { 4853 if (component.equals(mResolveComponentName)) { 4854 // The resolver supports EVERYTHING! 4855 return true; 4856 } 4857 final int callingUid = Binder.getCallingUid(); 4858 final int callingUserId = UserHandle.getUserId(callingUid); 4859 PackageParser.Activity a = mActivities.mActivities.get(component); 4860 if (a == null) { 4861 return false; 4862 } 4863 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4864 if (ps == null) { 4865 return false; 4866 } 4867 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4868 return false; 4869 } 4870 for (int i=0; i<a.intents.size(); i++) { 4871 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4872 intent.getData(), intent.getCategories(), TAG) >= 0) { 4873 return true; 4874 } 4875 } 4876 return false; 4877 } 4878 } 4879 4880 @Override 4881 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4882 if (!sUserManager.exists(userId)) return null; 4883 final int callingUid = Binder.getCallingUid(); 4884 flags = updateFlagsForComponent(flags, userId, component); 4885 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4886 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4887 synchronized (mPackages) { 4888 PackageParser.Activity a = mReceivers.mActivities.get(component); 4889 if (DEBUG_PACKAGE_INFO) Log.v( 4890 TAG, "getReceiverInfo " + component + ": " + a); 4891 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4892 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4893 if (ps == null) return null; 4894 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4895 return null; 4896 } 4897 return PackageParser.generateActivityInfo( 4898 a, flags, ps.readUserState(userId), userId); 4899 } 4900 } 4901 return null; 4902 } 4903 4904 @Override 4905 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4906 int flags, int userId) { 4907 if (!sUserManager.exists(userId)) return null; 4908 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4909 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4910 return null; 4911 } 4912 4913 flags = updateFlagsForPackage(flags, userId, null); 4914 4915 final boolean canSeeStaticLibraries = 4916 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4917 == PERMISSION_GRANTED 4918 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4919 == PERMISSION_GRANTED 4920 || canRequestPackageInstallsInternal(packageName, 4921 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4922 false /* throwIfPermNotDeclared*/) 4923 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4924 == PERMISSION_GRANTED; 4925 4926 synchronized (mPackages) { 4927 List<SharedLibraryInfo> result = null; 4928 4929 final int libCount = mSharedLibraries.size(); 4930 for (int i = 0; i < libCount; i++) { 4931 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4932 if (versionedLib == null) { 4933 continue; 4934 } 4935 4936 final int versionCount = versionedLib.size(); 4937 for (int j = 0; j < versionCount; j++) { 4938 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4939 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4940 break; 4941 } 4942 final long identity = Binder.clearCallingIdentity(); 4943 try { 4944 PackageInfo packageInfo = getPackageInfoVersioned( 4945 libInfo.getDeclaringPackage(), flags 4946 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4947 if (packageInfo == null) { 4948 continue; 4949 } 4950 } finally { 4951 Binder.restoreCallingIdentity(identity); 4952 } 4953 4954 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4955 libInfo.getLongVersion(), libInfo.getType(), 4956 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4957 flags, userId)); 4958 4959 if (result == null) { 4960 result = new ArrayList<>(); 4961 } 4962 result.add(resLibInfo); 4963 } 4964 } 4965 4966 return result != null ? new ParceledListSlice<>(result) : null; 4967 } 4968 } 4969 4970 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4971 SharedLibraryInfo libInfo, int flags, int userId) { 4972 List<VersionedPackage> versionedPackages = null; 4973 final int packageCount = mSettings.mPackages.size(); 4974 for (int i = 0; i < packageCount; i++) { 4975 PackageSetting ps = mSettings.mPackages.valueAt(i); 4976 4977 if (ps == null) { 4978 continue; 4979 } 4980 4981 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4982 continue; 4983 } 4984 4985 final String libName = libInfo.getName(); 4986 if (libInfo.isStatic()) { 4987 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4988 if (libIdx < 0) { 4989 continue; 4990 } 4991 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4992 continue; 4993 } 4994 if (versionedPackages == null) { 4995 versionedPackages = new ArrayList<>(); 4996 } 4997 // If the dependent is a static shared lib, use the public package name 4998 String dependentPackageName = ps.name; 4999 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5000 dependentPackageName = ps.pkg.manifestPackageName; 5001 } 5002 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5003 } else if (ps.pkg != null) { 5004 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5005 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5006 if (versionedPackages == null) { 5007 versionedPackages = new ArrayList<>(); 5008 } 5009 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5010 } 5011 } 5012 } 5013 5014 return versionedPackages; 5015 } 5016 5017 @Override 5018 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5019 if (!sUserManager.exists(userId)) return null; 5020 final int callingUid = Binder.getCallingUid(); 5021 flags = updateFlagsForComponent(flags, userId, component); 5022 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5023 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5024 synchronized (mPackages) { 5025 PackageParser.Service s = mServices.mServices.get(component); 5026 if (DEBUG_PACKAGE_INFO) Log.v( 5027 TAG, "getServiceInfo " + component + ": " + s); 5028 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5029 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5030 if (ps == null) return null; 5031 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5032 return null; 5033 } 5034 return PackageParser.generateServiceInfo( 5035 s, flags, ps.readUserState(userId), userId); 5036 } 5037 } 5038 return null; 5039 } 5040 5041 @Override 5042 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5043 if (!sUserManager.exists(userId)) return null; 5044 final int callingUid = Binder.getCallingUid(); 5045 flags = updateFlagsForComponent(flags, userId, component); 5046 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5047 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5048 synchronized (mPackages) { 5049 PackageParser.Provider p = mProviders.mProviders.get(component); 5050 if (DEBUG_PACKAGE_INFO) Log.v( 5051 TAG, "getProviderInfo " + component + ": " + p); 5052 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5053 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5054 if (ps == null) return null; 5055 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5056 return null; 5057 } 5058 return PackageParser.generateProviderInfo( 5059 p, flags, ps.readUserState(userId), userId); 5060 } 5061 } 5062 return null; 5063 } 5064 5065 @Override 5066 public String[] getSystemSharedLibraryNames() { 5067 // allow instant applications 5068 synchronized (mPackages) { 5069 Set<String> libs = null; 5070 final int libCount = mSharedLibraries.size(); 5071 for (int i = 0; i < libCount; i++) { 5072 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 5073 if (versionedLib == null) { 5074 continue; 5075 } 5076 final int versionCount = versionedLib.size(); 5077 for (int j = 0; j < versionCount; j++) { 5078 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 5079 if (!libEntry.info.isStatic()) { 5080 if (libs == null) { 5081 libs = new ArraySet<>(); 5082 } 5083 libs.add(libEntry.info.getName()); 5084 break; 5085 } 5086 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 5087 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5088 UserHandle.getUserId(Binder.getCallingUid()), 5089 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5090 if (libs == null) { 5091 libs = new ArraySet<>(); 5092 } 5093 libs.add(libEntry.info.getName()); 5094 break; 5095 } 5096 } 5097 } 5098 5099 if (libs != null) { 5100 String[] libsArray = new String[libs.size()]; 5101 libs.toArray(libsArray); 5102 return libsArray; 5103 } 5104 5105 return null; 5106 } 5107 } 5108 5109 @Override 5110 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5111 // allow instant applications 5112 synchronized (mPackages) { 5113 return mServicesSystemSharedLibraryPackageName; 5114 } 5115 } 5116 5117 @Override 5118 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5119 // allow instant applications 5120 synchronized (mPackages) { 5121 return mSharedSystemSharedLibraryPackageName; 5122 } 5123 } 5124 5125 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5126 for (int i = userList.length - 1; i >= 0; --i) { 5127 final int userId = userList[i]; 5128 // don't add instant app to the list of updates 5129 if (pkgSetting.getInstantApp(userId)) { 5130 continue; 5131 } 5132 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5133 if (changedPackages == null) { 5134 changedPackages = new SparseArray<>(); 5135 mChangedPackages.put(userId, changedPackages); 5136 } 5137 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5138 if (sequenceNumbers == null) { 5139 sequenceNumbers = new HashMap<>(); 5140 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5141 } 5142 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5143 if (sequenceNumber != null) { 5144 changedPackages.remove(sequenceNumber); 5145 } 5146 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5147 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5148 } 5149 mChangedPackagesSequenceNumber++; 5150 } 5151 5152 @Override 5153 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5154 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5155 return null; 5156 } 5157 synchronized (mPackages) { 5158 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5159 return null; 5160 } 5161 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5162 if (changedPackages == null) { 5163 return null; 5164 } 5165 final List<String> packageNames = 5166 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5167 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5168 final String packageName = changedPackages.get(i); 5169 if (packageName != null) { 5170 packageNames.add(packageName); 5171 } 5172 } 5173 return packageNames.isEmpty() 5174 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5175 } 5176 } 5177 5178 @Override 5179 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5180 // allow instant applications 5181 ArrayList<FeatureInfo> res; 5182 synchronized (mAvailableFeatures) { 5183 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5184 res.addAll(mAvailableFeatures.values()); 5185 } 5186 final FeatureInfo fi = new FeatureInfo(); 5187 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5188 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5189 res.add(fi); 5190 5191 return new ParceledListSlice<>(res); 5192 } 5193 5194 @Override 5195 public boolean hasSystemFeature(String name, int version) { 5196 // allow instant applications 5197 synchronized (mAvailableFeatures) { 5198 final FeatureInfo feat = mAvailableFeatures.get(name); 5199 if (feat == null) { 5200 return false; 5201 } else { 5202 return feat.version >= version; 5203 } 5204 } 5205 } 5206 5207 @Override 5208 public int checkPermission(String permName, String pkgName, int userId) { 5209 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5210 } 5211 5212 @Override 5213 public int checkUidPermission(String permName, int uid) { 5214 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5215 } 5216 5217 @Override 5218 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5219 if (UserHandle.getCallingUserId() != userId) { 5220 mContext.enforceCallingPermission( 5221 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5222 "isPermissionRevokedByPolicy for user " + userId); 5223 } 5224 5225 if (checkPermission(permission, packageName, userId) 5226 == PackageManager.PERMISSION_GRANTED) { 5227 return false; 5228 } 5229 5230 final int callingUid = Binder.getCallingUid(); 5231 if (getInstantAppPackageName(callingUid) != null) { 5232 if (!isCallerSameApp(packageName, callingUid)) { 5233 return false; 5234 } 5235 } else { 5236 if (isInstantApp(packageName, userId)) { 5237 return false; 5238 } 5239 } 5240 5241 final long identity = Binder.clearCallingIdentity(); 5242 try { 5243 final int flags = getPermissionFlags(permission, packageName, userId); 5244 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5245 } finally { 5246 Binder.restoreCallingIdentity(identity); 5247 } 5248 } 5249 5250 @Override 5251 public String getPermissionControllerPackageName() { 5252 synchronized (mPackages) { 5253 return mRequiredInstallerPackage; 5254 } 5255 } 5256 5257 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5258 return mPermissionManager.addDynamicPermission( 5259 info, async, getCallingUid(), new PermissionCallback() { 5260 @Override 5261 public void onPermissionChanged() { 5262 if (!async) { 5263 mSettings.writeLPr(); 5264 } else { 5265 scheduleWriteSettingsLocked(); 5266 } 5267 } 5268 }); 5269 } 5270 5271 @Override 5272 public boolean addPermission(PermissionInfo info) { 5273 synchronized (mPackages) { 5274 return addDynamicPermission(info, false); 5275 } 5276 } 5277 5278 @Override 5279 public boolean addPermissionAsync(PermissionInfo info) { 5280 synchronized (mPackages) { 5281 return addDynamicPermission(info, true); 5282 } 5283 } 5284 5285 @Override 5286 public void removePermission(String permName) { 5287 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5288 } 5289 5290 @Override 5291 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5292 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5293 getCallingUid(), userId, mPermissionCallback); 5294 } 5295 5296 @Override 5297 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5298 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5299 getCallingUid(), userId, mPermissionCallback); 5300 } 5301 5302 @Override 5303 public void resetRuntimePermissions() { 5304 mContext.enforceCallingOrSelfPermission( 5305 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5306 "revokeRuntimePermission"); 5307 5308 int callingUid = Binder.getCallingUid(); 5309 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5310 mContext.enforceCallingOrSelfPermission( 5311 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5312 "resetRuntimePermissions"); 5313 } 5314 5315 synchronized (mPackages) { 5316 mPermissionManager.updateAllPermissions( 5317 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5318 mPermissionCallback); 5319 for (int userId : UserManagerService.getInstance().getUserIds()) { 5320 final int packageCount = mPackages.size(); 5321 for (int i = 0; i < packageCount; i++) { 5322 PackageParser.Package pkg = mPackages.valueAt(i); 5323 if (!(pkg.mExtras instanceof PackageSetting)) { 5324 continue; 5325 } 5326 PackageSetting ps = (PackageSetting) pkg.mExtras; 5327 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5328 } 5329 } 5330 } 5331 } 5332 5333 @Override 5334 public int getPermissionFlags(String permName, String packageName, int userId) { 5335 return mPermissionManager.getPermissionFlags( 5336 permName, packageName, getCallingUid(), userId); 5337 } 5338 5339 @Override 5340 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5341 int flagValues, int userId) { 5342 mPermissionManager.updatePermissionFlags( 5343 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5344 mPermissionCallback); 5345 } 5346 5347 /** 5348 * Update the permission flags for all packages and runtime permissions of a user in order 5349 * to allow device or profile owner to remove POLICY_FIXED. 5350 */ 5351 @Override 5352 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5353 synchronized (mPackages) { 5354 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5355 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5356 mPermissionCallback); 5357 if (changed) { 5358 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5359 } 5360 } 5361 } 5362 5363 @Override 5364 public boolean shouldShowRequestPermissionRationale(String permissionName, 5365 String packageName, int userId) { 5366 if (UserHandle.getCallingUserId() != userId) { 5367 mContext.enforceCallingPermission( 5368 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5369 "canShowRequestPermissionRationale for user " + userId); 5370 } 5371 5372 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5373 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5374 return false; 5375 } 5376 5377 if (checkPermission(permissionName, packageName, userId) 5378 == PackageManager.PERMISSION_GRANTED) { 5379 return false; 5380 } 5381 5382 final int flags; 5383 5384 final long identity = Binder.clearCallingIdentity(); 5385 try { 5386 flags = getPermissionFlags(permissionName, 5387 packageName, userId); 5388 } finally { 5389 Binder.restoreCallingIdentity(identity); 5390 } 5391 5392 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5393 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5394 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5395 5396 if ((flags & fixedFlags) != 0) { 5397 return false; 5398 } 5399 5400 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5401 } 5402 5403 @Override 5404 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5405 mContext.enforceCallingOrSelfPermission( 5406 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5407 "addOnPermissionsChangeListener"); 5408 5409 synchronized (mPackages) { 5410 mOnPermissionChangeListeners.addListenerLocked(listener); 5411 } 5412 } 5413 5414 @Override 5415 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5416 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5417 throw new SecurityException("Instant applications don't have access to this method"); 5418 } 5419 synchronized (mPackages) { 5420 mOnPermissionChangeListeners.removeListenerLocked(listener); 5421 } 5422 } 5423 5424 @Override 5425 public boolean isProtectedBroadcast(String actionName) { 5426 // allow instant applications 5427 synchronized (mProtectedBroadcasts) { 5428 if (mProtectedBroadcasts.contains(actionName)) { 5429 return true; 5430 } else if (actionName != null) { 5431 // TODO: remove these terrible hacks 5432 if (actionName.startsWith("android.net.netmon.lingerExpired") 5433 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5434 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5435 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5436 return true; 5437 } 5438 } 5439 } 5440 return false; 5441 } 5442 5443 @Override 5444 public int checkSignatures(String pkg1, String pkg2) { 5445 synchronized (mPackages) { 5446 final PackageParser.Package p1 = mPackages.get(pkg1); 5447 final PackageParser.Package p2 = mPackages.get(pkg2); 5448 if (p1 == null || p1.mExtras == null 5449 || p2 == null || p2.mExtras == null) { 5450 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5451 } 5452 final int callingUid = Binder.getCallingUid(); 5453 final int callingUserId = UserHandle.getUserId(callingUid); 5454 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5455 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5456 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5457 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5458 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5459 } 5460 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5461 } 5462 } 5463 5464 @Override 5465 public int checkUidSignatures(int uid1, int uid2) { 5466 final int callingUid = Binder.getCallingUid(); 5467 final int callingUserId = UserHandle.getUserId(callingUid); 5468 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5469 // Map to base uids. 5470 uid1 = UserHandle.getAppId(uid1); 5471 uid2 = UserHandle.getAppId(uid2); 5472 // reader 5473 synchronized (mPackages) { 5474 Signature[] s1; 5475 Signature[] s2; 5476 Object obj = mSettings.getUserIdLPr(uid1); 5477 if (obj != null) { 5478 if (obj instanceof SharedUserSetting) { 5479 if (isCallerInstantApp) { 5480 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5481 } 5482 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5483 } else if (obj instanceof PackageSetting) { 5484 final PackageSetting ps = (PackageSetting) obj; 5485 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5487 } 5488 s1 = ps.signatures.mSigningDetails.signatures; 5489 } else { 5490 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5491 } 5492 } else { 5493 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5494 } 5495 obj = mSettings.getUserIdLPr(uid2); 5496 if (obj != null) { 5497 if (obj instanceof SharedUserSetting) { 5498 if (isCallerInstantApp) { 5499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5500 } 5501 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 5502 } else if (obj instanceof PackageSetting) { 5503 final PackageSetting ps = (PackageSetting) obj; 5504 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5505 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5506 } 5507 s2 = ps.signatures.mSigningDetails.signatures; 5508 } else { 5509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5510 } 5511 } else { 5512 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5513 } 5514 return compareSignatures(s1, s2); 5515 } 5516 } 5517 5518 @Override 5519 public boolean hasSigningCertificate( 5520 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 5521 5522 synchronized (mPackages) { 5523 final PackageParser.Package p = mPackages.get(packageName); 5524 if (p == null || p.mExtras == null) { 5525 return false; 5526 } 5527 final int callingUid = Binder.getCallingUid(); 5528 final int callingUserId = UserHandle.getUserId(callingUid); 5529 final PackageSetting ps = (PackageSetting) p.mExtras; 5530 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5531 return false; 5532 } 5533 switch (type) { 5534 case CERT_INPUT_RAW_X509: 5535 return signingDetailsHasCertificate(certificate, p.mSigningDetails); 5536 case CERT_INPUT_SHA256: 5537 return signingDetailsHasSha256Certificate(certificate, p.mSigningDetails); 5538 default: 5539 return false; 5540 } 5541 } 5542 } 5543 5544 @Override 5545 public boolean hasUidSigningCertificate( 5546 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 5547 final int callingUid = Binder.getCallingUid(); 5548 final int callingUserId = UserHandle.getUserId(callingUid); 5549 // Map to base uids. 5550 uid = UserHandle.getAppId(uid); 5551 // reader 5552 synchronized (mPackages) { 5553 final PackageParser.SigningDetails signingDetails; 5554 final Object obj = mSettings.getUserIdLPr(uid); 5555 if (obj != null) { 5556 if (obj instanceof SharedUserSetting) { 5557 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5558 if (isCallerInstantApp) { 5559 return false; 5560 } 5561 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 5562 } else if (obj instanceof PackageSetting) { 5563 final PackageSetting ps = (PackageSetting) obj; 5564 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5565 return false; 5566 } 5567 signingDetails = ps.signatures.mSigningDetails; 5568 } else { 5569 return false; 5570 } 5571 } else { 5572 return false; 5573 } 5574 switch (type) { 5575 case CERT_INPUT_RAW_X509: 5576 return signingDetailsHasCertificate(certificate, signingDetails); 5577 case CERT_INPUT_SHA256: 5578 return signingDetailsHasSha256Certificate(certificate, signingDetails); 5579 default: 5580 return false; 5581 } 5582 } 5583 } 5584 5585 /** 5586 * This method should typically only be used when granting or revoking 5587 * permissions, since the app may immediately restart after this call. 5588 * <p> 5589 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5590 * guard your work against the app being relaunched. 5591 */ 5592 private void killUid(int appId, int userId, String reason) { 5593 final long identity = Binder.clearCallingIdentity(); 5594 try { 5595 IActivityManager am = ActivityManager.getService(); 5596 if (am != null) { 5597 try { 5598 am.killUid(appId, userId, reason); 5599 } catch (RemoteException e) { 5600 /* ignore - same process */ 5601 } 5602 } 5603 } finally { 5604 Binder.restoreCallingIdentity(identity); 5605 } 5606 } 5607 5608 /** 5609 * If the database version for this type of package (internal storage or 5610 * external storage) is less than the version where package signatures 5611 * were updated, return true. 5612 */ 5613 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5614 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5615 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5616 } 5617 5618 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5619 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5620 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5621 } 5622 5623 @Override 5624 public List<String> getAllPackages() { 5625 final int callingUid = Binder.getCallingUid(); 5626 final int callingUserId = UserHandle.getUserId(callingUid); 5627 synchronized (mPackages) { 5628 if (canViewInstantApps(callingUid, callingUserId)) { 5629 return new ArrayList<String>(mPackages.keySet()); 5630 } 5631 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5632 final List<String> result = new ArrayList<>(); 5633 if (instantAppPkgName != null) { 5634 // caller is an instant application; filter unexposed applications 5635 for (PackageParser.Package pkg : mPackages.values()) { 5636 if (!pkg.visibleToInstantApps) { 5637 continue; 5638 } 5639 result.add(pkg.packageName); 5640 } 5641 } else { 5642 // caller is a normal application; filter instant applications 5643 for (PackageParser.Package pkg : mPackages.values()) { 5644 final PackageSetting ps = 5645 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5646 if (ps != null 5647 && ps.getInstantApp(callingUserId) 5648 && !mInstantAppRegistry.isInstantAccessGranted( 5649 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5650 continue; 5651 } 5652 result.add(pkg.packageName); 5653 } 5654 } 5655 return result; 5656 } 5657 } 5658 5659 @Override 5660 public String[] getPackagesForUid(int uid) { 5661 final int callingUid = Binder.getCallingUid(); 5662 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5663 final int userId = UserHandle.getUserId(uid); 5664 uid = UserHandle.getAppId(uid); 5665 // reader 5666 synchronized (mPackages) { 5667 Object obj = mSettings.getUserIdLPr(uid); 5668 if (obj instanceof SharedUserSetting) { 5669 if (isCallerInstantApp) { 5670 return null; 5671 } 5672 final SharedUserSetting sus = (SharedUserSetting) obj; 5673 final int N = sus.packages.size(); 5674 String[] res = new String[N]; 5675 final Iterator<PackageSetting> it = sus.packages.iterator(); 5676 int i = 0; 5677 while (it.hasNext()) { 5678 PackageSetting ps = it.next(); 5679 if (ps.getInstalled(userId)) { 5680 res[i++] = ps.name; 5681 } else { 5682 res = ArrayUtils.removeElement(String.class, res, res[i]); 5683 } 5684 } 5685 return res; 5686 } else if (obj instanceof PackageSetting) { 5687 final PackageSetting ps = (PackageSetting) obj; 5688 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5689 return new String[]{ps.name}; 5690 } 5691 } 5692 } 5693 return null; 5694 } 5695 5696 @Override 5697 public String getNameForUid(int uid) { 5698 final int callingUid = Binder.getCallingUid(); 5699 if (getInstantAppPackageName(callingUid) != null) { 5700 return null; 5701 } 5702 synchronized (mPackages) { 5703 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5704 if (obj instanceof SharedUserSetting) { 5705 final SharedUserSetting sus = (SharedUserSetting) obj; 5706 return sus.name + ":" + sus.userId; 5707 } else if (obj instanceof PackageSetting) { 5708 final PackageSetting ps = (PackageSetting) obj; 5709 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5710 return null; 5711 } 5712 return ps.name; 5713 } 5714 return null; 5715 } 5716 } 5717 5718 @Override 5719 public String[] getNamesForUids(int[] uids) { 5720 if (uids == null || uids.length == 0) { 5721 return null; 5722 } 5723 final int callingUid = Binder.getCallingUid(); 5724 if (getInstantAppPackageName(callingUid) != null) { 5725 return null; 5726 } 5727 final String[] names = new String[uids.length]; 5728 synchronized (mPackages) { 5729 for (int i = uids.length - 1; i >= 0; i--) { 5730 final int uid = uids[i]; 5731 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5732 if (obj instanceof SharedUserSetting) { 5733 final SharedUserSetting sus = (SharedUserSetting) obj; 5734 names[i] = "shared:" + sus.name; 5735 } else if (obj instanceof PackageSetting) { 5736 final PackageSetting ps = (PackageSetting) obj; 5737 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5738 names[i] = null; 5739 } else { 5740 names[i] = ps.name; 5741 } 5742 } else { 5743 names[i] = null; 5744 } 5745 } 5746 } 5747 return names; 5748 } 5749 5750 @Override 5751 public int getUidForSharedUser(String sharedUserName) { 5752 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5753 return -1; 5754 } 5755 if (sharedUserName == null) { 5756 return -1; 5757 } 5758 // reader 5759 synchronized (mPackages) { 5760 SharedUserSetting suid; 5761 try { 5762 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5763 if (suid != null) { 5764 return suid.userId; 5765 } 5766 } catch (PackageManagerException ignore) { 5767 // can't happen, but, still need to catch it 5768 } 5769 return -1; 5770 } 5771 } 5772 5773 @Override 5774 public int getFlagsForUid(int uid) { 5775 final int callingUid = Binder.getCallingUid(); 5776 if (getInstantAppPackageName(callingUid) != null) { 5777 return 0; 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.pkgFlags; 5784 } else if (obj instanceof PackageSetting) { 5785 final PackageSetting ps = (PackageSetting) obj; 5786 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5787 return 0; 5788 } 5789 return ps.pkgFlags; 5790 } 5791 } 5792 return 0; 5793 } 5794 5795 @Override 5796 public int getPrivateFlagsForUid(int uid) { 5797 final int callingUid = Binder.getCallingUid(); 5798 if (getInstantAppPackageName(callingUid) != null) { 5799 return 0; 5800 } 5801 synchronized (mPackages) { 5802 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5803 if (obj instanceof SharedUserSetting) { 5804 final SharedUserSetting sus = (SharedUserSetting) obj; 5805 return sus.pkgPrivateFlags; 5806 } else if (obj instanceof PackageSetting) { 5807 final PackageSetting ps = (PackageSetting) obj; 5808 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5809 return 0; 5810 } 5811 return ps.pkgPrivateFlags; 5812 } 5813 } 5814 return 0; 5815 } 5816 5817 @Override 5818 public boolean isUidPrivileged(int uid) { 5819 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5820 return false; 5821 } 5822 uid = UserHandle.getAppId(uid); 5823 // reader 5824 synchronized (mPackages) { 5825 Object obj = mSettings.getUserIdLPr(uid); 5826 if (obj instanceof SharedUserSetting) { 5827 final SharedUserSetting sus = (SharedUserSetting) obj; 5828 final Iterator<PackageSetting> it = sus.packages.iterator(); 5829 while (it.hasNext()) { 5830 if (it.next().isPrivileged()) { 5831 return true; 5832 } 5833 } 5834 } else if (obj instanceof PackageSetting) { 5835 final PackageSetting ps = (PackageSetting) obj; 5836 return ps.isPrivileged(); 5837 } 5838 } 5839 return false; 5840 } 5841 5842 @Override 5843 public String[] getAppOpPermissionPackages(String permName) { 5844 return mPermissionManager.getAppOpPermissionPackages(permName); 5845 } 5846 5847 @Override 5848 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5849 int flags, int userId) { 5850 return resolveIntentInternal( 5851 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5852 } 5853 5854 /** 5855 * Normally instant apps can only be resolved when they're visible to the caller. 5856 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5857 * since we need to allow the system to start any installed application. 5858 */ 5859 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5860 int flags, int userId, boolean resolveForStart) { 5861 try { 5862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5863 5864 if (!sUserManager.exists(userId)) return null; 5865 final int callingUid = Binder.getCallingUid(); 5866 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5867 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5868 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5869 5870 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5871 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5872 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5873 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5874 5875 final ResolveInfo bestChoice = 5876 chooseBestActivity(intent, resolvedType, flags, query, userId); 5877 return bestChoice; 5878 } finally { 5879 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5880 } 5881 } 5882 5883 @Override 5884 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5885 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5886 throw new SecurityException( 5887 "findPersistentPreferredActivity can only be run by the system"); 5888 } 5889 if (!sUserManager.exists(userId)) { 5890 return null; 5891 } 5892 final int callingUid = Binder.getCallingUid(); 5893 intent = updateIntentForResolve(intent); 5894 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5895 final int flags = updateFlagsForResolve( 5896 0, userId, intent, callingUid, false /*includeInstantApps*/); 5897 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5898 userId); 5899 synchronized (mPackages) { 5900 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5901 userId); 5902 } 5903 } 5904 5905 @Override 5906 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5907 IntentFilter filter, int match, ComponentName activity) { 5908 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5909 return; 5910 } 5911 final int userId = UserHandle.getCallingUserId(); 5912 if (DEBUG_PREFERRED) { 5913 Log.v(TAG, "setLastChosenActivity intent=" + intent 5914 + " resolvedType=" + resolvedType 5915 + " flags=" + flags 5916 + " filter=" + filter 5917 + " match=" + match 5918 + " activity=" + activity); 5919 filter.dump(new PrintStreamPrinter(System.out), " "); 5920 } 5921 intent.setComponent(null); 5922 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5923 userId); 5924 // Find any earlier preferred or last chosen entries and nuke them 5925 findPreferredActivity(intent, resolvedType, 5926 flags, query, 0, false, true, false, userId); 5927 // Add the new activity as the last chosen for this filter 5928 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5929 "Setting last chosen"); 5930 } 5931 5932 @Override 5933 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5934 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5935 return null; 5936 } 5937 final int userId = UserHandle.getCallingUserId(); 5938 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5939 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5940 userId); 5941 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5942 false, false, false, userId); 5943 } 5944 5945 /** 5946 * Returns whether or not instant apps have been disabled remotely. 5947 */ 5948 private boolean isEphemeralDisabled() { 5949 return mEphemeralAppsDisabled; 5950 } 5951 5952 private boolean isInstantAppAllowed( 5953 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5954 boolean skipPackageCheck) { 5955 if (mInstantAppResolverConnection == null) { 5956 return false; 5957 } 5958 if (mInstantAppInstallerActivity == null) { 5959 return false; 5960 } 5961 if (intent.getComponent() != null) { 5962 return false; 5963 } 5964 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5965 return false; 5966 } 5967 if (!skipPackageCheck && intent.getPackage() != null) { 5968 return false; 5969 } 5970 final boolean isWebUri = hasWebURI(intent); 5971 if (!isWebUri || intent.getData().getHost() == null) { 5972 return false; 5973 } 5974 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5975 // Or if there's already an ephemeral app installed that handles the action 5976 synchronized (mPackages) { 5977 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5978 for (int n = 0; n < count; n++) { 5979 final ResolveInfo info = resolvedActivities.get(n); 5980 final String packageName = info.activityInfo.packageName; 5981 final PackageSetting ps = mSettings.mPackages.get(packageName); 5982 if (ps != null) { 5983 // only check domain verification status if the app is not a browser 5984 if (!info.handleAllWebDataURI) { 5985 // Try to get the status from User settings first 5986 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5987 final int status = (int) (packedStatus >> 32); 5988 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5989 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5990 if (DEBUG_EPHEMERAL) { 5991 Slog.v(TAG, "DENY instant app;" 5992 + " pkg: " + packageName + ", status: " + status); 5993 } 5994 return false; 5995 } 5996 } 5997 if (ps.getInstantApp(userId)) { 5998 if (DEBUG_EPHEMERAL) { 5999 Slog.v(TAG, "DENY instant app installed;" 6000 + " pkg: " + packageName); 6001 } 6002 return false; 6003 } 6004 } 6005 } 6006 } 6007 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6008 return true; 6009 } 6010 6011 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6012 Intent origIntent, String resolvedType, String callingPackage, 6013 Bundle verificationBundle, int userId) { 6014 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6015 new InstantAppRequest(responseObj, origIntent, resolvedType, 6016 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6017 mHandler.sendMessage(msg); 6018 } 6019 6020 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6021 int flags, List<ResolveInfo> query, int userId) { 6022 if (query != null) { 6023 final int N = query.size(); 6024 if (N == 1) { 6025 return query.get(0); 6026 } else if (N > 1) { 6027 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6028 // If there is more than one activity with the same priority, 6029 // then let the user decide between them. 6030 ResolveInfo r0 = query.get(0); 6031 ResolveInfo r1 = query.get(1); 6032 if (DEBUG_INTENT_MATCHING || debug) { 6033 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6034 + r1.activityInfo.name + "=" + r1.priority); 6035 } 6036 // If the first activity has a higher priority, or a different 6037 // default, then it is always desirable to pick it. 6038 if (r0.priority != r1.priority 6039 || r0.preferredOrder != r1.preferredOrder 6040 || r0.isDefault != r1.isDefault) { 6041 return query.get(0); 6042 } 6043 // If we have saved a preference for a preferred activity for 6044 // this Intent, use that. 6045 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 6046 flags, query, r0.priority, true, false, debug, userId); 6047 if (ri != null) { 6048 return ri; 6049 } 6050 // If we have an ephemeral app, use it 6051 for (int i = 0; i < N; i++) { 6052 ri = query.get(i); 6053 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6054 final String packageName = ri.activityInfo.packageName; 6055 final PackageSetting ps = mSettings.mPackages.get(packageName); 6056 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6057 final int status = (int)(packedStatus >> 32); 6058 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6059 return ri; 6060 } 6061 } 6062 } 6063 ri = new ResolveInfo(mResolveInfo); 6064 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6065 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6066 // If all of the options come from the same package, show the application's 6067 // label and icon instead of the generic resolver's. 6068 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6069 // and then throw away the ResolveInfo itself, meaning that the caller loses 6070 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6071 // a fallback for this case; we only set the target package's resources on 6072 // the ResolveInfo, not the ActivityInfo. 6073 final String intentPackage = intent.getPackage(); 6074 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6075 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6076 ri.resolvePackageName = intentPackage; 6077 if (userNeedsBadging(userId)) { 6078 ri.noResourceId = true; 6079 } else { 6080 ri.icon = appi.icon; 6081 } 6082 ri.iconResourceId = appi.icon; 6083 ri.labelRes = appi.labelRes; 6084 } 6085 ri.activityInfo.applicationInfo = new ApplicationInfo( 6086 ri.activityInfo.applicationInfo); 6087 if (userId != 0) { 6088 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6089 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6090 } 6091 // Make sure that the resolver is displayable in car mode 6092 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6093 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6094 return ri; 6095 } 6096 } 6097 return null; 6098 } 6099 6100 /** 6101 * Return true if the given list is not empty and all of its contents have 6102 * an activityInfo with the given package name. 6103 */ 6104 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6105 if (ArrayUtils.isEmpty(list)) { 6106 return false; 6107 } 6108 for (int i = 0, N = list.size(); i < N; i++) { 6109 final ResolveInfo ri = list.get(i); 6110 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6111 if (ai == null || !packageName.equals(ai.packageName)) { 6112 return false; 6113 } 6114 } 6115 return true; 6116 } 6117 6118 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6119 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6120 final int N = query.size(); 6121 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6122 .get(userId); 6123 // Get the list of persistent preferred activities that handle the intent 6124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6125 List<PersistentPreferredActivity> pprefs = ppir != null 6126 ? ppir.queryIntent(intent, resolvedType, 6127 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6128 userId) 6129 : null; 6130 if (pprefs != null && pprefs.size() > 0) { 6131 final int M = pprefs.size(); 6132 for (int i=0; i<M; i++) { 6133 final PersistentPreferredActivity ppa = pprefs.get(i); 6134 if (DEBUG_PREFERRED || debug) { 6135 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6136 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6137 + "\n component=" + ppa.mComponent); 6138 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6139 } 6140 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6141 flags | MATCH_DISABLED_COMPONENTS, userId); 6142 if (DEBUG_PREFERRED || debug) { 6143 Slog.v(TAG, "Found persistent preferred activity:"); 6144 if (ai != null) { 6145 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6146 } else { 6147 Slog.v(TAG, " null"); 6148 } 6149 } 6150 if (ai == null) { 6151 // This previously registered persistent preferred activity 6152 // component is no longer known. Ignore it and do NOT remove it. 6153 continue; 6154 } 6155 for (int j=0; j<N; j++) { 6156 final ResolveInfo ri = query.get(j); 6157 if (!ri.activityInfo.applicationInfo.packageName 6158 .equals(ai.applicationInfo.packageName)) { 6159 continue; 6160 } 6161 if (!ri.activityInfo.name.equals(ai.name)) { 6162 continue; 6163 } 6164 // Found a persistent preference that can handle the intent. 6165 if (DEBUG_PREFERRED || debug) { 6166 Slog.v(TAG, "Returning persistent preferred activity: " + 6167 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6168 } 6169 return ri; 6170 } 6171 } 6172 } 6173 return null; 6174 } 6175 6176 // TODO: handle preferred activities missing while user has amnesia 6177 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6178 List<ResolveInfo> query, int priority, boolean always, 6179 boolean removeMatches, boolean debug, int userId) { 6180 if (!sUserManager.exists(userId)) return null; 6181 final int callingUid = Binder.getCallingUid(); 6182 flags = updateFlagsForResolve( 6183 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6184 intent = updateIntentForResolve(intent); 6185 // writer 6186 synchronized (mPackages) { 6187 // Try to find a matching persistent preferred activity. 6188 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6189 debug, userId); 6190 6191 // If a persistent preferred activity matched, use it. 6192 if (pri != null) { 6193 return pri; 6194 } 6195 6196 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6197 // Get the list of preferred activities that handle the intent 6198 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6199 List<PreferredActivity> prefs = pir != null 6200 ? pir.queryIntent(intent, resolvedType, 6201 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6202 userId) 6203 : null; 6204 if (prefs != null && prefs.size() > 0) { 6205 boolean changed = false; 6206 try { 6207 // First figure out how good the original match set is. 6208 // We will only allow preferred activities that came 6209 // from the same match quality. 6210 int match = 0; 6211 6212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6213 6214 final int N = query.size(); 6215 for (int j=0; j<N; j++) { 6216 final ResolveInfo ri = query.get(j); 6217 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6218 + ": 0x" + Integer.toHexString(match)); 6219 if (ri.match > match) { 6220 match = ri.match; 6221 } 6222 } 6223 6224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6225 + Integer.toHexString(match)); 6226 6227 match &= IntentFilter.MATCH_CATEGORY_MASK; 6228 final int M = prefs.size(); 6229 for (int i=0; i<M; i++) { 6230 final PreferredActivity pa = prefs.get(i); 6231 if (DEBUG_PREFERRED || debug) { 6232 Slog.v(TAG, "Checking PreferredActivity ds=" 6233 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6234 + "\n component=" + pa.mPref.mComponent); 6235 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6236 } 6237 if (pa.mPref.mMatch != match) { 6238 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6239 + Integer.toHexString(pa.mPref.mMatch)); 6240 continue; 6241 } 6242 // If it's not an "always" type preferred activity and that's what we're 6243 // looking for, skip it. 6244 if (always && !pa.mPref.mAlways) { 6245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6246 continue; 6247 } 6248 final ActivityInfo ai = getActivityInfo( 6249 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6250 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6251 userId); 6252 if (DEBUG_PREFERRED || debug) { 6253 Slog.v(TAG, "Found preferred activity:"); 6254 if (ai != null) { 6255 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6256 } else { 6257 Slog.v(TAG, " null"); 6258 } 6259 } 6260 if (ai == null) { 6261 // This previously registered preferred activity 6262 // component is no longer known. Most likely an update 6263 // to the app was installed and in the new version this 6264 // component no longer exists. Clean it up by removing 6265 // it from the preferred activities list, and skip it. 6266 Slog.w(TAG, "Removing dangling preferred activity: " 6267 + pa.mPref.mComponent); 6268 pir.removeFilter(pa); 6269 changed = true; 6270 continue; 6271 } 6272 for (int j=0; j<N; j++) { 6273 final ResolveInfo ri = query.get(j); 6274 if (!ri.activityInfo.applicationInfo.packageName 6275 .equals(ai.applicationInfo.packageName)) { 6276 continue; 6277 } 6278 if (!ri.activityInfo.name.equals(ai.name)) { 6279 continue; 6280 } 6281 6282 if (removeMatches) { 6283 pir.removeFilter(pa); 6284 changed = true; 6285 if (DEBUG_PREFERRED) { 6286 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6287 } 6288 break; 6289 } 6290 6291 // Okay we found a previously set preferred or last chosen app. 6292 // If the result set is different from when this 6293 // was created, and is not a subset of the preferred set, we need to 6294 // clear it and re-ask the user their preference, if we're looking for 6295 // an "always" type entry. 6296 if (always && !pa.mPref.sameSet(query)) { 6297 if (pa.mPref.isSuperset(query)) { 6298 // some components of the set are no longer present in 6299 // the query, but the preferred activity can still be reused 6300 if (DEBUG_PREFERRED) { 6301 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6302 + " still valid as only non-preferred components" 6303 + " were removed for " + intent + " type " 6304 + resolvedType); 6305 } 6306 // remove obsolete components and re-add the up-to-date filter 6307 PreferredActivity freshPa = new PreferredActivity(pa, 6308 pa.mPref.mMatch, 6309 pa.mPref.discardObsoleteComponents(query), 6310 pa.mPref.mComponent, 6311 pa.mPref.mAlways); 6312 pir.removeFilter(pa); 6313 pir.addFilter(freshPa); 6314 changed = true; 6315 } else { 6316 Slog.i(TAG, 6317 "Result set changed, dropping preferred activity for " 6318 + intent + " type " + resolvedType); 6319 if (DEBUG_PREFERRED) { 6320 Slog.v(TAG, "Removing preferred activity since set changed " 6321 + pa.mPref.mComponent); 6322 } 6323 pir.removeFilter(pa); 6324 // Re-add the filter as a "last chosen" entry (!always) 6325 PreferredActivity lastChosen = new PreferredActivity( 6326 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6327 pir.addFilter(lastChosen); 6328 changed = true; 6329 return null; 6330 } 6331 } 6332 6333 // Yay! Either the set matched or we're looking for the last chosen 6334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6335 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6336 return ri; 6337 } 6338 } 6339 } finally { 6340 if (changed) { 6341 if (DEBUG_PREFERRED) { 6342 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6343 } 6344 scheduleWritePackageRestrictionsLocked(userId); 6345 } 6346 } 6347 } 6348 } 6349 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6350 return null; 6351 } 6352 6353 /* 6354 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6355 */ 6356 @Override 6357 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6358 int targetUserId) { 6359 mContext.enforceCallingOrSelfPermission( 6360 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6361 List<CrossProfileIntentFilter> matches = 6362 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6363 if (matches != null) { 6364 int size = matches.size(); 6365 for (int i = 0; i < size; i++) { 6366 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6367 } 6368 } 6369 if (hasWebURI(intent)) { 6370 // cross-profile app linking works only towards the parent. 6371 final int callingUid = Binder.getCallingUid(); 6372 final UserInfo parent = getProfileParent(sourceUserId); 6373 synchronized(mPackages) { 6374 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6375 false /*includeInstantApps*/); 6376 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6377 intent, resolvedType, flags, sourceUserId, parent.id); 6378 return xpDomainInfo != null; 6379 } 6380 } 6381 return false; 6382 } 6383 6384 private UserInfo getProfileParent(int userId) { 6385 final long identity = Binder.clearCallingIdentity(); 6386 try { 6387 return sUserManager.getProfileParent(userId); 6388 } finally { 6389 Binder.restoreCallingIdentity(identity); 6390 } 6391 } 6392 6393 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6394 String resolvedType, int userId) { 6395 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6396 if (resolver != null) { 6397 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6398 } 6399 return null; 6400 } 6401 6402 @Override 6403 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6404 String resolvedType, int flags, int userId) { 6405 try { 6406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6407 6408 return new ParceledListSlice<>( 6409 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6410 } finally { 6411 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6412 } 6413 } 6414 6415 /** 6416 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6417 * instant, returns {@code null}. 6418 */ 6419 private String getInstantAppPackageName(int callingUid) { 6420 synchronized (mPackages) { 6421 // If the caller is an isolated app use the owner's uid for the lookup. 6422 if (Process.isIsolated(callingUid)) { 6423 callingUid = mIsolatedOwners.get(callingUid); 6424 } 6425 final int appId = UserHandle.getAppId(callingUid); 6426 final Object obj = mSettings.getUserIdLPr(appId); 6427 if (obj instanceof PackageSetting) { 6428 final PackageSetting ps = (PackageSetting) obj; 6429 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6430 return isInstantApp ? ps.pkg.packageName : null; 6431 } 6432 } 6433 return null; 6434 } 6435 6436 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6437 String resolvedType, int flags, int userId) { 6438 return queryIntentActivitiesInternal( 6439 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6440 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6441 } 6442 6443 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6444 String resolvedType, int flags, int filterCallingUid, int userId, 6445 boolean resolveForStart, boolean allowDynamicSplits) { 6446 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6447 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6448 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6449 false /* requireFullPermission */, false /* checkShell */, 6450 "query intent activities"); 6451 final String pkgName = intent.getPackage(); 6452 ComponentName comp = intent.getComponent(); 6453 if (comp == null) { 6454 if (intent.getSelector() != null) { 6455 intent = intent.getSelector(); 6456 comp = intent.getComponent(); 6457 } 6458 } 6459 6460 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6461 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6462 if (comp != null) { 6463 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6464 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6465 if (ai != null) { 6466 // When specifying an explicit component, we prevent the activity from being 6467 // used when either 1) the calling package is normal and the activity is within 6468 // an ephemeral application or 2) the calling package is ephemeral and the 6469 // activity is not visible to ephemeral applications. 6470 final boolean matchInstantApp = 6471 (flags & PackageManager.MATCH_INSTANT) != 0; 6472 final boolean matchVisibleToInstantAppOnly = 6473 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6474 final boolean matchExplicitlyVisibleOnly = 6475 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6476 final boolean isCallerInstantApp = 6477 instantAppPkgName != null; 6478 final boolean isTargetSameInstantApp = 6479 comp.getPackageName().equals(instantAppPkgName); 6480 final boolean isTargetInstantApp = 6481 (ai.applicationInfo.privateFlags 6482 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6483 final boolean isTargetVisibleToInstantApp = 6484 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6485 final boolean isTargetExplicitlyVisibleToInstantApp = 6486 isTargetVisibleToInstantApp 6487 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6488 final boolean isTargetHiddenFromInstantApp = 6489 !isTargetVisibleToInstantApp 6490 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6491 final boolean blockResolution = 6492 !isTargetSameInstantApp 6493 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6494 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6495 && isTargetHiddenFromInstantApp)); 6496 if (!blockResolution) { 6497 final ResolveInfo ri = new ResolveInfo(); 6498 ri.activityInfo = ai; 6499 list.add(ri); 6500 } 6501 } 6502 return applyPostResolutionFilter( 6503 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6504 } 6505 6506 // reader 6507 boolean sortResult = false; 6508 boolean addEphemeral = false; 6509 List<ResolveInfo> result; 6510 final boolean ephemeralDisabled = isEphemeralDisabled(); 6511 synchronized (mPackages) { 6512 if (pkgName == null) { 6513 List<CrossProfileIntentFilter> matchingFilters = 6514 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6515 // Check for results that need to skip the current profile. 6516 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6517 resolvedType, flags, userId); 6518 if (xpResolveInfo != null) { 6519 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6520 xpResult.add(xpResolveInfo); 6521 return applyPostResolutionFilter( 6522 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6523 allowDynamicSplits, filterCallingUid, userId); 6524 } 6525 6526 // Check for results in the current profile. 6527 result = filterIfNotSystemUser(mActivities.queryIntent( 6528 intent, resolvedType, flags, userId), userId); 6529 addEphemeral = !ephemeralDisabled 6530 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6531 // Check for cross profile results. 6532 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6533 xpResolveInfo = queryCrossProfileIntents( 6534 matchingFilters, intent, resolvedType, flags, userId, 6535 hasNonNegativePriorityResult); 6536 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6537 boolean isVisibleToUser = filterIfNotSystemUser( 6538 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6539 if (isVisibleToUser) { 6540 result.add(xpResolveInfo); 6541 sortResult = true; 6542 } 6543 } 6544 if (hasWebURI(intent)) { 6545 CrossProfileDomainInfo xpDomainInfo = null; 6546 final UserInfo parent = getProfileParent(userId); 6547 if (parent != null) { 6548 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6549 flags, userId, parent.id); 6550 } 6551 if (xpDomainInfo != null) { 6552 if (xpResolveInfo != null) { 6553 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6554 // in the result. 6555 result.remove(xpResolveInfo); 6556 } 6557 if (result.size() == 0 && !addEphemeral) { 6558 // No result in current profile, but found candidate in parent user. 6559 // And we are not going to add emphemeral app, so we can return the 6560 // result straight away. 6561 result.add(xpDomainInfo.resolveInfo); 6562 return applyPostResolutionFilter(result, instantAppPkgName, 6563 allowDynamicSplits, filterCallingUid, userId); 6564 } 6565 } else if (result.size() <= 1 && !addEphemeral) { 6566 // No result in parent user and <= 1 result in current profile, and we 6567 // are not going to add emphemeral app, so we can return the result without 6568 // further processing. 6569 return applyPostResolutionFilter(result, instantAppPkgName, 6570 allowDynamicSplits, filterCallingUid, userId); 6571 } 6572 // We have more than one candidate (combining results from current and parent 6573 // profile), so we need filtering and sorting. 6574 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6575 intent, flags, result, xpDomainInfo, userId); 6576 sortResult = true; 6577 } 6578 } else { 6579 final PackageParser.Package pkg = mPackages.get(pkgName); 6580 result = null; 6581 if (pkg != null) { 6582 result = filterIfNotSystemUser( 6583 mActivities.queryIntentForPackage( 6584 intent, resolvedType, flags, pkg.activities, userId), 6585 userId); 6586 } 6587 if (result == null || result.size() == 0) { 6588 // the caller wants to resolve for a particular package; however, there 6589 // were no installed results, so, try to find an ephemeral result 6590 addEphemeral = !ephemeralDisabled 6591 && isInstantAppAllowed( 6592 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6593 if (result == null) { 6594 result = new ArrayList<>(); 6595 } 6596 } 6597 } 6598 } 6599 if (addEphemeral) { 6600 result = maybeAddInstantAppInstaller( 6601 result, intent, resolvedType, flags, userId, resolveForStart); 6602 } 6603 if (sortResult) { 6604 Collections.sort(result, mResolvePrioritySorter); 6605 } 6606 return applyPostResolutionFilter( 6607 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6608 } 6609 6610 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6611 String resolvedType, int flags, int userId, boolean resolveForStart) { 6612 // first, check to see if we've got an instant app already installed 6613 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6614 ResolveInfo localInstantApp = null; 6615 boolean blockResolution = false; 6616 if (!alreadyResolvedLocally) { 6617 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6618 flags 6619 | PackageManager.GET_RESOLVED_FILTER 6620 | PackageManager.MATCH_INSTANT 6621 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6622 userId); 6623 for (int i = instantApps.size() - 1; i >= 0; --i) { 6624 final ResolveInfo info = instantApps.get(i); 6625 final String packageName = info.activityInfo.packageName; 6626 final PackageSetting ps = mSettings.mPackages.get(packageName); 6627 if (ps.getInstantApp(userId)) { 6628 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6629 final int status = (int)(packedStatus >> 32); 6630 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6631 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6632 // there's a local instant application installed, but, the user has 6633 // chosen to never use it; skip resolution and don't acknowledge 6634 // an instant application is even available 6635 if (DEBUG_EPHEMERAL) { 6636 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6637 } 6638 blockResolution = true; 6639 break; 6640 } else { 6641 // we have a locally installed instant application; skip resolution 6642 // but acknowledge there's an instant application available 6643 if (DEBUG_EPHEMERAL) { 6644 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6645 } 6646 localInstantApp = info; 6647 break; 6648 } 6649 } 6650 } 6651 } 6652 // no app installed, let's see if one's available 6653 AuxiliaryResolveInfo auxiliaryResponse = null; 6654 if (!blockResolution) { 6655 if (localInstantApp == null) { 6656 // we don't have an instant app locally, resolve externally 6657 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6658 final InstantAppRequest requestObject = new InstantAppRequest( 6659 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6660 null /*callingPackage*/, userId, null /*verificationBundle*/, 6661 resolveForStart); 6662 auxiliaryResponse = 6663 InstantAppResolver.doInstantAppResolutionPhaseOne( 6664 mContext, mInstantAppResolverConnection, requestObject); 6665 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6666 } else { 6667 // we have an instant application locally, but, we can't admit that since 6668 // callers shouldn't be able to determine prior browsing. create a dummy 6669 // auxiliary response so the downstream code behaves as if there's an 6670 // instant application available externally. when it comes time to start 6671 // the instant application, we'll do the right thing. 6672 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6673 auxiliaryResponse = new AuxiliaryResolveInfo( 6674 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6675 ai.versionCode, null /*failureIntent*/); 6676 } 6677 } 6678 if (auxiliaryResponse != null) { 6679 if (DEBUG_EPHEMERAL) { 6680 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6681 } 6682 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6683 final PackageSetting ps = 6684 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6685 if (ps != null) { 6686 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6687 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6688 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6689 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6690 // make sure this resolver is the default 6691 ephemeralInstaller.isDefault = true; 6692 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6693 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6694 // add a non-generic filter 6695 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6696 ephemeralInstaller.filter.addDataPath( 6697 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6698 ephemeralInstaller.isInstantAppAvailable = true; 6699 result.add(ephemeralInstaller); 6700 } 6701 } 6702 return result; 6703 } 6704 6705 private static class CrossProfileDomainInfo { 6706 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6707 ResolveInfo resolveInfo; 6708 /* Best domain verification status of the activities found in the other profile */ 6709 int bestDomainVerificationStatus; 6710 } 6711 6712 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6713 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6714 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6715 sourceUserId)) { 6716 return null; 6717 } 6718 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6719 resolvedType, flags, parentUserId); 6720 6721 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6722 return null; 6723 } 6724 CrossProfileDomainInfo result = null; 6725 int size = resultTargetUser.size(); 6726 for (int i = 0; i < size; i++) { 6727 ResolveInfo riTargetUser = resultTargetUser.get(i); 6728 // Intent filter verification is only for filters that specify a host. So don't return 6729 // those that handle all web uris. 6730 if (riTargetUser.handleAllWebDataURI) { 6731 continue; 6732 } 6733 String packageName = riTargetUser.activityInfo.packageName; 6734 PackageSetting ps = mSettings.mPackages.get(packageName); 6735 if (ps == null) { 6736 continue; 6737 } 6738 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6739 int status = (int)(verificationState >> 32); 6740 if (result == null) { 6741 result = new CrossProfileDomainInfo(); 6742 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6743 sourceUserId, parentUserId); 6744 result.bestDomainVerificationStatus = status; 6745 } else { 6746 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6747 result.bestDomainVerificationStatus); 6748 } 6749 } 6750 // Don't consider matches with status NEVER across profiles. 6751 if (result != null && result.bestDomainVerificationStatus 6752 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6753 return null; 6754 } 6755 return result; 6756 } 6757 6758 /** 6759 * Verification statuses are ordered from the worse to the best, except for 6760 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6761 */ 6762 private int bestDomainVerificationStatus(int status1, int status2) { 6763 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6764 return status2; 6765 } 6766 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6767 return status1; 6768 } 6769 return (int) MathUtils.max(status1, status2); 6770 } 6771 6772 private boolean isUserEnabled(int userId) { 6773 long callingId = Binder.clearCallingIdentity(); 6774 try { 6775 UserInfo userInfo = sUserManager.getUserInfo(userId); 6776 return userInfo != null && userInfo.isEnabled(); 6777 } finally { 6778 Binder.restoreCallingIdentity(callingId); 6779 } 6780 } 6781 6782 /** 6783 * Filter out activities with systemUserOnly flag set, when current user is not System. 6784 * 6785 * @return filtered list 6786 */ 6787 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6788 if (userId == UserHandle.USER_SYSTEM) { 6789 return resolveInfos; 6790 } 6791 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6792 ResolveInfo info = resolveInfos.get(i); 6793 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6794 resolveInfos.remove(i); 6795 } 6796 } 6797 return resolveInfos; 6798 } 6799 6800 /** 6801 * Filters out ephemeral activities. 6802 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6803 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6804 * 6805 * @param resolveInfos The pre-filtered list of resolved activities 6806 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6807 * is performed. 6808 * @return A filtered list of resolved activities. 6809 */ 6810 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6811 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6812 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6813 final ResolveInfo info = resolveInfos.get(i); 6814 // allow activities that are defined in the provided package 6815 if (allowDynamicSplits 6816 && info.activityInfo.splitName != null 6817 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6818 info.activityInfo.splitName)) { 6819 if (mInstantAppInstallerInfo == null) { 6820 if (DEBUG_INSTALL) { 6821 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6822 } 6823 resolveInfos.remove(i); 6824 continue; 6825 } 6826 // requested activity is defined in a split that hasn't been installed yet. 6827 // add the installer to the resolve list 6828 if (DEBUG_INSTALL) { 6829 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6830 } 6831 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6832 final ComponentName installFailureActivity = findInstallFailureActivity( 6833 info.activityInfo.packageName, filterCallingUid, userId); 6834 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6835 info.activityInfo.packageName, info.activityInfo.splitName, 6836 installFailureActivity, 6837 info.activityInfo.applicationInfo.versionCode, 6838 null /*failureIntent*/); 6839 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6840 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6841 // add a non-generic filter 6842 installerInfo.filter = new IntentFilter(); 6843 6844 // This resolve info may appear in the chooser UI, so let us make it 6845 // look as the one it replaces as far as the user is concerned which 6846 // requires loading the correct label and icon for the resolve info. 6847 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6848 installerInfo.labelRes = info.resolveLabelResId(); 6849 installerInfo.icon = info.resolveIconResId(); 6850 6851 // propagate priority/preferred order/default 6852 installerInfo.priority = info.priority; 6853 installerInfo.preferredOrder = info.preferredOrder; 6854 installerInfo.isDefault = info.isDefault; 6855 resolveInfos.set(i, installerInfo); 6856 continue; 6857 } 6858 // caller is a full app, don't need to apply any other filtering 6859 if (ephemeralPkgName == null) { 6860 continue; 6861 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6862 // caller is same app; don't need to apply any other filtering 6863 continue; 6864 } 6865 // allow activities that have been explicitly exposed to ephemeral apps 6866 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6867 if (!isEphemeralApp 6868 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6869 continue; 6870 } 6871 resolveInfos.remove(i); 6872 } 6873 return resolveInfos; 6874 } 6875 6876 /** 6877 * Returns the activity component that can handle install failures. 6878 * <p>By default, the instant application installer handles failures. However, an 6879 * application may want to handle failures on its own. Applications do this by 6880 * creating an activity with an intent filter that handles the action 6881 * {@link Intent#ACTION_INSTALL_FAILURE}. 6882 */ 6883 private @Nullable ComponentName findInstallFailureActivity( 6884 String packageName, int filterCallingUid, int userId) { 6885 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6886 failureActivityIntent.setPackage(packageName); 6887 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6888 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6889 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6890 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6891 final int NR = result.size(); 6892 if (NR > 0) { 6893 for (int i = 0; i < NR; i++) { 6894 final ResolveInfo info = result.get(i); 6895 if (info.activityInfo.splitName != null) { 6896 continue; 6897 } 6898 return new ComponentName(packageName, info.activityInfo.name); 6899 } 6900 } 6901 return null; 6902 } 6903 6904 /** 6905 * @param resolveInfos list of resolve infos in descending priority order 6906 * @return if the list contains a resolve info with non-negative priority 6907 */ 6908 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6909 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6910 } 6911 6912 private static boolean hasWebURI(Intent intent) { 6913 if (intent.getData() == null) { 6914 return false; 6915 } 6916 final String scheme = intent.getScheme(); 6917 if (TextUtils.isEmpty(scheme)) { 6918 return false; 6919 } 6920 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6921 } 6922 6923 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6924 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6925 int userId) { 6926 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6927 6928 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6929 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6930 candidates.size()); 6931 } 6932 6933 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6934 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6935 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6936 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6937 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6938 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6939 6940 synchronized (mPackages) { 6941 final int count = candidates.size(); 6942 // First, try to use linked apps. Partition the candidates into four lists: 6943 // one for the final results, one for the "do not use ever", one for "undefined status" 6944 // and finally one for "browser app type". 6945 for (int n=0; n<count; n++) { 6946 ResolveInfo info = candidates.get(n); 6947 String packageName = info.activityInfo.packageName; 6948 PackageSetting ps = mSettings.mPackages.get(packageName); 6949 if (ps != null) { 6950 // Add to the special match all list (Browser use case) 6951 if (info.handleAllWebDataURI) { 6952 matchAllList.add(info); 6953 continue; 6954 } 6955 // Try to get the status from User settings first 6956 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6957 int status = (int)(packedStatus >> 32); 6958 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6959 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6960 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6961 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6962 + " : linkgen=" + linkGeneration); 6963 } 6964 // Use link-enabled generation as preferredOrder, i.e. 6965 // prefer newly-enabled over earlier-enabled. 6966 info.preferredOrder = linkGeneration; 6967 alwaysList.add(info); 6968 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6969 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6970 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6971 } 6972 neverList.add(info); 6973 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6974 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6975 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6976 } 6977 alwaysAskList.add(info); 6978 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6979 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6980 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6981 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6982 } 6983 undefinedList.add(info); 6984 } 6985 } 6986 } 6987 6988 // We'll want to include browser possibilities in a few cases 6989 boolean includeBrowser = false; 6990 6991 // First try to add the "always" resolution(s) for the current user, if any 6992 if (alwaysList.size() > 0) { 6993 result.addAll(alwaysList); 6994 } else { 6995 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6996 result.addAll(undefinedList); 6997 // Maybe add one for the other profile. 6998 if (xpDomainInfo != null && ( 6999 xpDomainInfo.bestDomainVerificationStatus 7000 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7001 result.add(xpDomainInfo.resolveInfo); 7002 } 7003 includeBrowser = true; 7004 } 7005 7006 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7007 // If there were 'always' entries their preferred order has been set, so we also 7008 // back that off to make the alternatives equivalent 7009 if (alwaysAskList.size() > 0) { 7010 for (ResolveInfo i : result) { 7011 i.preferredOrder = 0; 7012 } 7013 result.addAll(alwaysAskList); 7014 includeBrowser = true; 7015 } 7016 7017 if (includeBrowser) { 7018 // Also add browsers (all of them or only the default one) 7019 if (DEBUG_DOMAIN_VERIFICATION) { 7020 Slog.v(TAG, " ...including browsers in candidate set"); 7021 } 7022 if ((matchFlags & MATCH_ALL) != 0) { 7023 result.addAll(matchAllList); 7024 } else { 7025 // Browser/generic handling case. If there's a default browser, go straight 7026 // to that (but only if there is no other higher-priority match). 7027 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7028 int maxMatchPrio = 0; 7029 ResolveInfo defaultBrowserMatch = null; 7030 final int numCandidates = matchAllList.size(); 7031 for (int n = 0; n < numCandidates; n++) { 7032 ResolveInfo info = matchAllList.get(n); 7033 // track the highest overall match priority... 7034 if (info.priority > maxMatchPrio) { 7035 maxMatchPrio = info.priority; 7036 } 7037 // ...and the highest-priority default browser match 7038 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7039 if (defaultBrowserMatch == null 7040 || (defaultBrowserMatch.priority < info.priority)) { 7041 if (debug) { 7042 Slog.v(TAG, "Considering default browser match " + info); 7043 } 7044 defaultBrowserMatch = info; 7045 } 7046 } 7047 } 7048 if (defaultBrowserMatch != null 7049 && defaultBrowserMatch.priority >= maxMatchPrio 7050 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7051 { 7052 if (debug) { 7053 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7054 } 7055 result.add(defaultBrowserMatch); 7056 } else { 7057 result.addAll(matchAllList); 7058 } 7059 } 7060 7061 // If there is nothing selected, add all candidates and remove the ones that the user 7062 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7063 if (result.size() == 0) { 7064 result.addAll(candidates); 7065 result.removeAll(neverList); 7066 } 7067 } 7068 } 7069 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7070 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7071 result.size()); 7072 for (ResolveInfo info : result) { 7073 Slog.v(TAG, " + " + info.activityInfo); 7074 } 7075 } 7076 return result; 7077 } 7078 7079 // Returns a packed value as a long: 7080 // 7081 // high 'int'-sized word: link status: undefined/ask/never/always. 7082 // low 'int'-sized word: relative priority among 'always' results. 7083 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7084 long result = ps.getDomainVerificationStatusForUser(userId); 7085 // if none available, get the master status 7086 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7087 if (ps.getIntentFilterVerificationInfo() != null) { 7088 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7089 } 7090 } 7091 return result; 7092 } 7093 7094 private ResolveInfo querySkipCurrentProfileIntents( 7095 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7096 int flags, int sourceUserId) { 7097 if (matchingFilters != null) { 7098 int size = matchingFilters.size(); 7099 for (int i = 0; i < size; i ++) { 7100 CrossProfileIntentFilter filter = matchingFilters.get(i); 7101 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7102 // Checking if there are activities in the target user that can handle the 7103 // intent. 7104 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7105 resolvedType, flags, sourceUserId); 7106 if (resolveInfo != null) { 7107 return resolveInfo; 7108 } 7109 } 7110 } 7111 } 7112 return null; 7113 } 7114 7115 // Return matching ResolveInfo in target user if any. 7116 private ResolveInfo queryCrossProfileIntents( 7117 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7118 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7119 if (matchingFilters != null) { 7120 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7121 // match the same intent. For performance reasons, it is better not to 7122 // run queryIntent twice for the same userId 7123 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7124 int size = matchingFilters.size(); 7125 for (int i = 0; i < size; i++) { 7126 CrossProfileIntentFilter filter = matchingFilters.get(i); 7127 int targetUserId = filter.getTargetUserId(); 7128 boolean skipCurrentProfile = 7129 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7130 boolean skipCurrentProfileIfNoMatchFound = 7131 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7132 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7133 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7134 // Checking if there are activities in the target user that can handle the 7135 // intent. 7136 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7137 resolvedType, flags, sourceUserId); 7138 if (resolveInfo != null) return resolveInfo; 7139 alreadyTriedUserIds.put(targetUserId, true); 7140 } 7141 } 7142 } 7143 return null; 7144 } 7145 7146 /** 7147 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7148 * will forward the intent to the filter's target user. 7149 * Otherwise, returns null. 7150 */ 7151 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7152 String resolvedType, int flags, int sourceUserId) { 7153 int targetUserId = filter.getTargetUserId(); 7154 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7155 resolvedType, flags, targetUserId); 7156 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7157 // If all the matches in the target profile are suspended, return null. 7158 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7159 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7160 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7161 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7162 targetUserId); 7163 } 7164 } 7165 } 7166 return null; 7167 } 7168 7169 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7170 int sourceUserId, int targetUserId) { 7171 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7172 long ident = Binder.clearCallingIdentity(); 7173 boolean targetIsProfile; 7174 try { 7175 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7176 } finally { 7177 Binder.restoreCallingIdentity(ident); 7178 } 7179 String className; 7180 if (targetIsProfile) { 7181 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7182 } else { 7183 className = FORWARD_INTENT_TO_PARENT; 7184 } 7185 ComponentName forwardingActivityComponentName = new ComponentName( 7186 mAndroidApplication.packageName, className); 7187 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7188 sourceUserId); 7189 if (!targetIsProfile) { 7190 forwardingActivityInfo.showUserIcon = targetUserId; 7191 forwardingResolveInfo.noResourceId = true; 7192 } 7193 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7194 forwardingResolveInfo.priority = 0; 7195 forwardingResolveInfo.preferredOrder = 0; 7196 forwardingResolveInfo.match = 0; 7197 forwardingResolveInfo.isDefault = true; 7198 forwardingResolveInfo.filter = filter; 7199 forwardingResolveInfo.targetUserId = targetUserId; 7200 return forwardingResolveInfo; 7201 } 7202 7203 @Override 7204 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7205 Intent[] specifics, String[] specificTypes, Intent intent, 7206 String resolvedType, int flags, int userId) { 7207 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7208 specificTypes, intent, resolvedType, flags, userId)); 7209 } 7210 7211 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7212 Intent[] specifics, String[] specificTypes, Intent intent, 7213 String resolvedType, int flags, int userId) { 7214 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7215 final int callingUid = Binder.getCallingUid(); 7216 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7217 false /*includeInstantApps*/); 7218 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7219 false /*requireFullPermission*/, false /*checkShell*/, 7220 "query intent activity options"); 7221 final String resultsAction = intent.getAction(); 7222 7223 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7224 | PackageManager.GET_RESOLVED_FILTER, userId); 7225 7226 if (DEBUG_INTENT_MATCHING) { 7227 Log.v(TAG, "Query " + intent + ": " + results); 7228 } 7229 7230 int specificsPos = 0; 7231 int N; 7232 7233 // todo: note that the algorithm used here is O(N^2). This 7234 // isn't a problem in our current environment, but if we start running 7235 // into situations where we have more than 5 or 10 matches then this 7236 // should probably be changed to something smarter... 7237 7238 // First we go through and resolve each of the specific items 7239 // that were supplied, taking care of removing any corresponding 7240 // duplicate items in the generic resolve list. 7241 if (specifics != null) { 7242 for (int i=0; i<specifics.length; i++) { 7243 final Intent sintent = specifics[i]; 7244 if (sintent == null) { 7245 continue; 7246 } 7247 7248 if (DEBUG_INTENT_MATCHING) { 7249 Log.v(TAG, "Specific #" + i + ": " + sintent); 7250 } 7251 7252 String action = sintent.getAction(); 7253 if (resultsAction != null && resultsAction.equals(action)) { 7254 // If this action was explicitly requested, then don't 7255 // remove things that have it. 7256 action = null; 7257 } 7258 7259 ResolveInfo ri = null; 7260 ActivityInfo ai = null; 7261 7262 ComponentName comp = sintent.getComponent(); 7263 if (comp == null) { 7264 ri = resolveIntent( 7265 sintent, 7266 specificTypes != null ? specificTypes[i] : null, 7267 flags, userId); 7268 if (ri == null) { 7269 continue; 7270 } 7271 if (ri == mResolveInfo) { 7272 // ACK! Must do something better with this. 7273 } 7274 ai = ri.activityInfo; 7275 comp = new ComponentName(ai.applicationInfo.packageName, 7276 ai.name); 7277 } else { 7278 ai = getActivityInfo(comp, flags, userId); 7279 if (ai == null) { 7280 continue; 7281 } 7282 } 7283 7284 // Look for any generic query activities that are duplicates 7285 // of this specific one, and remove them from the results. 7286 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7287 N = results.size(); 7288 int j; 7289 for (j=specificsPos; j<N; j++) { 7290 ResolveInfo sri = results.get(j); 7291 if ((sri.activityInfo.name.equals(comp.getClassName()) 7292 && sri.activityInfo.applicationInfo.packageName.equals( 7293 comp.getPackageName())) 7294 || (action != null && sri.filter.matchAction(action))) { 7295 results.remove(j); 7296 if (DEBUG_INTENT_MATCHING) Log.v( 7297 TAG, "Removing duplicate item from " + j 7298 + " due to specific " + specificsPos); 7299 if (ri == null) { 7300 ri = sri; 7301 } 7302 j--; 7303 N--; 7304 } 7305 } 7306 7307 // Add this specific item to its proper place. 7308 if (ri == null) { 7309 ri = new ResolveInfo(); 7310 ri.activityInfo = ai; 7311 } 7312 results.add(specificsPos, ri); 7313 ri.specificIndex = i; 7314 specificsPos++; 7315 } 7316 } 7317 7318 // Now we go through the remaining generic results and remove any 7319 // duplicate actions that are found here. 7320 N = results.size(); 7321 for (int i=specificsPos; i<N-1; i++) { 7322 final ResolveInfo rii = results.get(i); 7323 if (rii.filter == null) { 7324 continue; 7325 } 7326 7327 // Iterate over all of the actions of this result's intent 7328 // filter... typically this should be just one. 7329 final Iterator<String> it = rii.filter.actionsIterator(); 7330 if (it == null) { 7331 continue; 7332 } 7333 while (it.hasNext()) { 7334 final String action = it.next(); 7335 if (resultsAction != null && resultsAction.equals(action)) { 7336 // If this action was explicitly requested, then don't 7337 // remove things that have it. 7338 continue; 7339 } 7340 for (int j=i+1; j<N; j++) { 7341 final ResolveInfo rij = results.get(j); 7342 if (rij.filter != null && rij.filter.hasAction(action)) { 7343 results.remove(j); 7344 if (DEBUG_INTENT_MATCHING) Log.v( 7345 TAG, "Removing duplicate item from " + j 7346 + " due to action " + action + " at " + i); 7347 j--; 7348 N--; 7349 } 7350 } 7351 } 7352 7353 // If the caller didn't request filter information, drop it now 7354 // so we don't have to marshall/unmarshall it. 7355 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7356 rii.filter = null; 7357 } 7358 } 7359 7360 // Filter out the caller activity if so requested. 7361 if (caller != null) { 7362 N = results.size(); 7363 for (int i=0; i<N; i++) { 7364 ActivityInfo ainfo = results.get(i).activityInfo; 7365 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7366 && caller.getClassName().equals(ainfo.name)) { 7367 results.remove(i); 7368 break; 7369 } 7370 } 7371 } 7372 7373 // If the caller didn't request filter information, 7374 // drop them now so we don't have to 7375 // marshall/unmarshall it. 7376 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7377 N = results.size(); 7378 for (int i=0; i<N; i++) { 7379 results.get(i).filter = null; 7380 } 7381 } 7382 7383 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7384 return results; 7385 } 7386 7387 @Override 7388 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7389 String resolvedType, int flags, int userId) { 7390 return new ParceledListSlice<>( 7391 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7392 false /*allowDynamicSplits*/)); 7393 } 7394 7395 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7396 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7397 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7398 final int callingUid = Binder.getCallingUid(); 7399 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7400 false /*requireFullPermission*/, false /*checkShell*/, 7401 "query intent receivers"); 7402 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7403 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7404 false /*includeInstantApps*/); 7405 ComponentName comp = intent.getComponent(); 7406 if (comp == null) { 7407 if (intent.getSelector() != null) { 7408 intent = intent.getSelector(); 7409 comp = intent.getComponent(); 7410 } 7411 } 7412 if (comp != null) { 7413 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7414 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7415 if (ai != null) { 7416 // When specifying an explicit component, we prevent the activity from being 7417 // used when either 1) the calling package is normal and the activity is within 7418 // an instant application or 2) the calling package is ephemeral and the 7419 // activity is not visible to instant applications. 7420 final boolean matchInstantApp = 7421 (flags & PackageManager.MATCH_INSTANT) != 0; 7422 final boolean matchVisibleToInstantAppOnly = 7423 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7424 final boolean matchExplicitlyVisibleOnly = 7425 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7426 final boolean isCallerInstantApp = 7427 instantAppPkgName != null; 7428 final boolean isTargetSameInstantApp = 7429 comp.getPackageName().equals(instantAppPkgName); 7430 final boolean isTargetInstantApp = 7431 (ai.applicationInfo.privateFlags 7432 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7433 final boolean isTargetVisibleToInstantApp = 7434 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7435 final boolean isTargetExplicitlyVisibleToInstantApp = 7436 isTargetVisibleToInstantApp 7437 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7438 final boolean isTargetHiddenFromInstantApp = 7439 !isTargetVisibleToInstantApp 7440 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7441 final boolean blockResolution = 7442 !isTargetSameInstantApp 7443 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7444 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7445 && isTargetHiddenFromInstantApp)); 7446 if (!blockResolution) { 7447 ResolveInfo ri = new ResolveInfo(); 7448 ri.activityInfo = ai; 7449 list.add(ri); 7450 } 7451 } 7452 return applyPostResolutionFilter( 7453 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7454 } 7455 7456 // reader 7457 synchronized (mPackages) { 7458 String pkgName = intent.getPackage(); 7459 if (pkgName == null) { 7460 final List<ResolveInfo> result = 7461 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7462 return applyPostResolutionFilter( 7463 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7464 } 7465 final PackageParser.Package pkg = mPackages.get(pkgName); 7466 if (pkg != null) { 7467 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7468 intent, resolvedType, flags, pkg.receivers, userId); 7469 return applyPostResolutionFilter( 7470 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7471 } 7472 return Collections.emptyList(); 7473 } 7474 } 7475 7476 @Override 7477 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7478 final int callingUid = Binder.getCallingUid(); 7479 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7480 } 7481 7482 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7483 int userId, int callingUid) { 7484 if (!sUserManager.exists(userId)) return null; 7485 flags = updateFlagsForResolve( 7486 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7487 List<ResolveInfo> query = queryIntentServicesInternal( 7488 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7489 if (query != null) { 7490 if (query.size() >= 1) { 7491 // If there is more than one service with the same priority, 7492 // just arbitrarily pick the first one. 7493 return query.get(0); 7494 } 7495 } 7496 return null; 7497 } 7498 7499 @Override 7500 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7501 String resolvedType, int flags, int userId) { 7502 final int callingUid = Binder.getCallingUid(); 7503 return new ParceledListSlice<>(queryIntentServicesInternal( 7504 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7505 } 7506 7507 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7508 String resolvedType, int flags, int userId, int callingUid, 7509 boolean includeInstantApps) { 7510 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7511 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7512 false /*requireFullPermission*/, false /*checkShell*/, 7513 "query intent receivers"); 7514 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7515 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7516 ComponentName comp = intent.getComponent(); 7517 if (comp == null) { 7518 if (intent.getSelector() != null) { 7519 intent = intent.getSelector(); 7520 comp = intent.getComponent(); 7521 } 7522 } 7523 if (comp != null) { 7524 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7525 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7526 if (si != null) { 7527 // When specifying an explicit component, we prevent the service from being 7528 // used when either 1) the service is in an instant application and the 7529 // caller is not the same instant application or 2) the calling package is 7530 // ephemeral and the activity is not visible to ephemeral applications. 7531 final boolean matchInstantApp = 7532 (flags & PackageManager.MATCH_INSTANT) != 0; 7533 final boolean matchVisibleToInstantAppOnly = 7534 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7535 final boolean isCallerInstantApp = 7536 instantAppPkgName != null; 7537 final boolean isTargetSameInstantApp = 7538 comp.getPackageName().equals(instantAppPkgName); 7539 final boolean isTargetInstantApp = 7540 (si.applicationInfo.privateFlags 7541 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7542 final boolean isTargetHiddenFromInstantApp = 7543 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7544 final boolean blockResolution = 7545 !isTargetSameInstantApp 7546 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7547 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7548 && isTargetHiddenFromInstantApp)); 7549 if (!blockResolution) { 7550 final ResolveInfo ri = new ResolveInfo(); 7551 ri.serviceInfo = si; 7552 list.add(ri); 7553 } 7554 } 7555 return list; 7556 } 7557 7558 // reader 7559 synchronized (mPackages) { 7560 String pkgName = intent.getPackage(); 7561 if (pkgName == null) { 7562 return applyPostServiceResolutionFilter( 7563 mServices.queryIntent(intent, resolvedType, flags, userId), 7564 instantAppPkgName); 7565 } 7566 final PackageParser.Package pkg = mPackages.get(pkgName); 7567 if (pkg != null) { 7568 return applyPostServiceResolutionFilter( 7569 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7570 userId), 7571 instantAppPkgName); 7572 } 7573 return Collections.emptyList(); 7574 } 7575 } 7576 7577 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7578 String instantAppPkgName) { 7579 if (instantAppPkgName == null) { 7580 return resolveInfos; 7581 } 7582 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7583 final ResolveInfo info = resolveInfos.get(i); 7584 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7585 // allow services that are defined in the provided package 7586 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7587 if (info.serviceInfo.splitName != null 7588 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7589 info.serviceInfo.splitName)) { 7590 // requested service is defined in a split that hasn't been installed yet. 7591 // add the installer to the resolve list 7592 if (DEBUG_EPHEMERAL) { 7593 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7594 } 7595 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7596 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7597 info.serviceInfo.packageName, info.serviceInfo.splitName, 7598 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7599 null /*failureIntent*/); 7600 // make sure this resolver is the default 7601 installerInfo.isDefault = true; 7602 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7603 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7604 // add a non-generic filter 7605 installerInfo.filter = new IntentFilter(); 7606 // load resources from the correct package 7607 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7608 resolveInfos.set(i, installerInfo); 7609 } 7610 continue; 7611 } 7612 // allow services that have been explicitly exposed to ephemeral apps 7613 if (!isEphemeralApp 7614 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7615 continue; 7616 } 7617 resolveInfos.remove(i); 7618 } 7619 return resolveInfos; 7620 } 7621 7622 @Override 7623 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7624 String resolvedType, int flags, int userId) { 7625 return new ParceledListSlice<>( 7626 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7627 } 7628 7629 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7630 Intent intent, String resolvedType, int flags, int userId) { 7631 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7632 final int callingUid = Binder.getCallingUid(); 7633 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7634 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7635 false /*includeInstantApps*/); 7636 ComponentName comp = intent.getComponent(); 7637 if (comp == null) { 7638 if (intent.getSelector() != null) { 7639 intent = intent.getSelector(); 7640 comp = intent.getComponent(); 7641 } 7642 } 7643 if (comp != null) { 7644 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7645 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7646 if (pi != null) { 7647 // When specifying an explicit component, we prevent the provider from being 7648 // used when either 1) the provider is in an instant application and the 7649 // caller is not the same instant application or 2) the calling package is an 7650 // instant application and the provider is not visible to instant applications. 7651 final boolean matchInstantApp = 7652 (flags & PackageManager.MATCH_INSTANT) != 0; 7653 final boolean matchVisibleToInstantAppOnly = 7654 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7655 final boolean isCallerInstantApp = 7656 instantAppPkgName != null; 7657 final boolean isTargetSameInstantApp = 7658 comp.getPackageName().equals(instantAppPkgName); 7659 final boolean isTargetInstantApp = 7660 (pi.applicationInfo.privateFlags 7661 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7662 final boolean isTargetHiddenFromInstantApp = 7663 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7664 final boolean blockResolution = 7665 !isTargetSameInstantApp 7666 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7667 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7668 && isTargetHiddenFromInstantApp)); 7669 if (!blockResolution) { 7670 final ResolveInfo ri = new ResolveInfo(); 7671 ri.providerInfo = pi; 7672 list.add(ri); 7673 } 7674 } 7675 return list; 7676 } 7677 7678 // reader 7679 synchronized (mPackages) { 7680 String pkgName = intent.getPackage(); 7681 if (pkgName == null) { 7682 return applyPostContentProviderResolutionFilter( 7683 mProviders.queryIntent(intent, resolvedType, flags, userId), 7684 instantAppPkgName); 7685 } 7686 final PackageParser.Package pkg = mPackages.get(pkgName); 7687 if (pkg != null) { 7688 return applyPostContentProviderResolutionFilter( 7689 mProviders.queryIntentForPackage( 7690 intent, resolvedType, flags, pkg.providers, userId), 7691 instantAppPkgName); 7692 } 7693 return Collections.emptyList(); 7694 } 7695 } 7696 7697 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7698 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7699 if (instantAppPkgName == null) { 7700 return resolveInfos; 7701 } 7702 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7703 final ResolveInfo info = resolveInfos.get(i); 7704 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7705 // allow providers that are defined in the provided package 7706 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7707 if (info.providerInfo.splitName != null 7708 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7709 info.providerInfo.splitName)) { 7710 // requested provider is defined in a split that hasn't been installed yet. 7711 // add the installer to the resolve list 7712 if (DEBUG_EPHEMERAL) { 7713 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7714 } 7715 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7716 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7717 info.providerInfo.packageName, info.providerInfo.splitName, 7718 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7719 null /*failureIntent*/); 7720 // make sure this resolver is the default 7721 installerInfo.isDefault = true; 7722 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7723 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7724 // add a non-generic filter 7725 installerInfo.filter = new IntentFilter(); 7726 // load resources from the correct package 7727 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7728 resolveInfos.set(i, installerInfo); 7729 } 7730 continue; 7731 } 7732 // allow providers that have been explicitly exposed to instant applications 7733 if (!isEphemeralApp 7734 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7735 continue; 7736 } 7737 resolveInfos.remove(i); 7738 } 7739 return resolveInfos; 7740 } 7741 7742 @Override 7743 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7744 final int callingUid = Binder.getCallingUid(); 7745 if (getInstantAppPackageName(callingUid) != null) { 7746 return ParceledListSlice.emptyList(); 7747 } 7748 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7749 flags = updateFlagsForPackage(flags, userId, null); 7750 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7751 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7752 true /* requireFullPermission */, false /* checkShell */, 7753 "get installed packages"); 7754 7755 // writer 7756 synchronized (mPackages) { 7757 ArrayList<PackageInfo> list; 7758 if (listUninstalled) { 7759 list = new ArrayList<>(mSettings.mPackages.size()); 7760 for (PackageSetting ps : mSettings.mPackages.values()) { 7761 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7762 continue; 7763 } 7764 if (filterAppAccessLPr(ps, callingUid, userId)) { 7765 continue; 7766 } 7767 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7768 if (pi != null) { 7769 list.add(pi); 7770 } 7771 } 7772 } else { 7773 list = new ArrayList<>(mPackages.size()); 7774 for (PackageParser.Package p : mPackages.values()) { 7775 final PackageSetting ps = (PackageSetting) p.mExtras; 7776 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7777 continue; 7778 } 7779 if (filterAppAccessLPr(ps, callingUid, userId)) { 7780 continue; 7781 } 7782 final PackageInfo pi = generatePackageInfo((PackageSetting) 7783 p.mExtras, flags, userId); 7784 if (pi != null) { 7785 list.add(pi); 7786 } 7787 } 7788 } 7789 7790 return new ParceledListSlice<>(list); 7791 } 7792 } 7793 7794 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7795 String[] permissions, boolean[] tmp, int flags, int userId) { 7796 int numMatch = 0; 7797 final PermissionsState permissionsState = ps.getPermissionsState(); 7798 for (int i=0; i<permissions.length; i++) { 7799 final String permission = permissions[i]; 7800 if (permissionsState.hasPermission(permission, userId)) { 7801 tmp[i] = true; 7802 numMatch++; 7803 } else { 7804 tmp[i] = false; 7805 } 7806 } 7807 if (numMatch == 0) { 7808 return; 7809 } 7810 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7811 7812 // The above might return null in cases of uninstalled apps or install-state 7813 // skew across users/profiles. 7814 if (pi != null) { 7815 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7816 if (numMatch == permissions.length) { 7817 pi.requestedPermissions = permissions; 7818 } else { 7819 pi.requestedPermissions = new String[numMatch]; 7820 numMatch = 0; 7821 for (int i=0; i<permissions.length; i++) { 7822 if (tmp[i]) { 7823 pi.requestedPermissions[numMatch] = permissions[i]; 7824 numMatch++; 7825 } 7826 } 7827 } 7828 } 7829 list.add(pi); 7830 } 7831 } 7832 7833 @Override 7834 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7835 String[] permissions, int flags, int userId) { 7836 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7837 flags = updateFlagsForPackage(flags, userId, permissions); 7838 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7839 true /* requireFullPermission */, false /* checkShell */, 7840 "get packages holding permissions"); 7841 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7842 7843 // writer 7844 synchronized (mPackages) { 7845 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7846 boolean[] tmpBools = new boolean[permissions.length]; 7847 if (listUninstalled) { 7848 for (PackageSetting ps : mSettings.mPackages.values()) { 7849 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7850 userId); 7851 } 7852 } else { 7853 for (PackageParser.Package pkg : mPackages.values()) { 7854 PackageSetting ps = (PackageSetting)pkg.mExtras; 7855 if (ps != null) { 7856 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7857 userId); 7858 } 7859 } 7860 } 7861 7862 return new ParceledListSlice<PackageInfo>(list); 7863 } 7864 } 7865 7866 @Override 7867 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7868 final int callingUid = Binder.getCallingUid(); 7869 if (getInstantAppPackageName(callingUid) != null) { 7870 return ParceledListSlice.emptyList(); 7871 } 7872 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7873 flags = updateFlagsForApplication(flags, userId, null); 7874 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7875 7876 // writer 7877 synchronized (mPackages) { 7878 ArrayList<ApplicationInfo> list; 7879 if (listUninstalled) { 7880 list = new ArrayList<>(mSettings.mPackages.size()); 7881 for (PackageSetting ps : mSettings.mPackages.values()) { 7882 ApplicationInfo ai; 7883 int effectiveFlags = flags; 7884 if (ps.isSystem()) { 7885 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7886 } 7887 if (ps.pkg != null) { 7888 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7889 continue; 7890 } 7891 if (filterAppAccessLPr(ps, callingUid, userId)) { 7892 continue; 7893 } 7894 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7895 ps.readUserState(userId), userId); 7896 if (ai != null) { 7897 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7898 } 7899 } else { 7900 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7901 // and already converts to externally visible package name 7902 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7903 callingUid, effectiveFlags, userId); 7904 } 7905 if (ai != null) { 7906 list.add(ai); 7907 } 7908 } 7909 } else { 7910 list = new ArrayList<>(mPackages.size()); 7911 for (PackageParser.Package p : mPackages.values()) { 7912 if (p.mExtras != null) { 7913 PackageSetting ps = (PackageSetting) p.mExtras; 7914 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7915 continue; 7916 } 7917 if (filterAppAccessLPr(ps, callingUid, userId)) { 7918 continue; 7919 } 7920 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7921 ps.readUserState(userId), userId); 7922 if (ai != null) { 7923 ai.packageName = resolveExternalPackageNameLPr(p); 7924 list.add(ai); 7925 } 7926 } 7927 } 7928 } 7929 7930 return new ParceledListSlice<>(list); 7931 } 7932 } 7933 7934 @Override 7935 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7936 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7937 return null; 7938 } 7939 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7940 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7941 "getEphemeralApplications"); 7942 } 7943 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7944 true /* requireFullPermission */, false /* checkShell */, 7945 "getEphemeralApplications"); 7946 synchronized (mPackages) { 7947 List<InstantAppInfo> instantApps = mInstantAppRegistry 7948 .getInstantAppsLPr(userId); 7949 if (instantApps != null) { 7950 return new ParceledListSlice<>(instantApps); 7951 } 7952 } 7953 return null; 7954 } 7955 7956 @Override 7957 public boolean isInstantApp(String packageName, int userId) { 7958 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7959 true /* requireFullPermission */, false /* checkShell */, 7960 "isInstantApp"); 7961 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7962 return false; 7963 } 7964 7965 synchronized (mPackages) { 7966 int callingUid = Binder.getCallingUid(); 7967 if (Process.isIsolated(callingUid)) { 7968 callingUid = mIsolatedOwners.get(callingUid); 7969 } 7970 final PackageSetting ps = mSettings.mPackages.get(packageName); 7971 PackageParser.Package pkg = mPackages.get(packageName); 7972 final boolean returnAllowed = 7973 ps != null 7974 && (isCallerSameApp(packageName, callingUid) 7975 || canViewInstantApps(callingUid, userId) 7976 || mInstantAppRegistry.isInstantAccessGranted( 7977 userId, UserHandle.getAppId(callingUid), ps.appId)); 7978 if (returnAllowed) { 7979 return ps.getInstantApp(userId); 7980 } 7981 } 7982 return false; 7983 } 7984 7985 @Override 7986 public byte[] getInstantAppCookie(String packageName, int userId) { 7987 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7988 return null; 7989 } 7990 7991 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7992 true /* requireFullPermission */, false /* checkShell */, 7993 "getInstantAppCookie"); 7994 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7995 return null; 7996 } 7997 synchronized (mPackages) { 7998 return mInstantAppRegistry.getInstantAppCookieLPw( 7999 packageName, userId); 8000 } 8001 } 8002 8003 @Override 8004 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8005 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8006 return true; 8007 } 8008 8009 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8010 true /* requireFullPermission */, true /* checkShell */, 8011 "setInstantAppCookie"); 8012 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8013 return false; 8014 } 8015 synchronized (mPackages) { 8016 return mInstantAppRegistry.setInstantAppCookieLPw( 8017 packageName, cookie, userId); 8018 } 8019 } 8020 8021 @Override 8022 public Bitmap getInstantAppIcon(String packageName, int userId) { 8023 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 8024 return null; 8025 } 8026 8027 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8028 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8029 "getInstantAppIcon"); 8030 } 8031 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8032 true /* requireFullPermission */, false /* checkShell */, 8033 "getInstantAppIcon"); 8034 8035 synchronized (mPackages) { 8036 return mInstantAppRegistry.getInstantAppIconLPw( 8037 packageName, userId); 8038 } 8039 } 8040 8041 private boolean isCallerSameApp(String packageName, int uid) { 8042 PackageParser.Package pkg = mPackages.get(packageName); 8043 return pkg != null 8044 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8045 } 8046 8047 @Override 8048 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8049 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8050 return ParceledListSlice.emptyList(); 8051 } 8052 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8053 } 8054 8055 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8056 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 8057 8058 // reader 8059 synchronized (mPackages) { 8060 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8061 final int userId = UserHandle.getCallingUserId(); 8062 while (i.hasNext()) { 8063 final PackageParser.Package p = i.next(); 8064 if (p.applicationInfo == null) continue; 8065 8066 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8067 && !p.applicationInfo.isDirectBootAware(); 8068 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8069 && p.applicationInfo.isDirectBootAware(); 8070 8071 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8072 && (!mSafeMode || isSystemApp(p)) 8073 && (matchesUnaware || matchesAware)) { 8074 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8075 if (ps != null) { 8076 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8077 ps.readUserState(userId), userId); 8078 if (ai != null) { 8079 finalList.add(ai); 8080 } 8081 } 8082 } 8083 } 8084 } 8085 8086 return finalList; 8087 } 8088 8089 @Override 8090 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8091 return resolveContentProviderInternal(name, flags, userId); 8092 } 8093 8094 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8095 if (!sUserManager.exists(userId)) return null; 8096 flags = updateFlagsForComponent(flags, userId, name); 8097 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 8098 // reader 8099 synchronized (mPackages) { 8100 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 8101 PackageSetting ps = provider != null 8102 ? mSettings.mPackages.get(provider.owner.packageName) 8103 : null; 8104 if (ps != null) { 8105 final boolean isInstantApp = ps.getInstantApp(userId); 8106 // normal application; filter out instant application provider 8107 if (instantAppPkgName == null && isInstantApp) { 8108 return null; 8109 } 8110 // instant application; filter out other instant applications 8111 if (instantAppPkgName != null 8112 && isInstantApp 8113 && !provider.owner.packageName.equals(instantAppPkgName)) { 8114 return null; 8115 } 8116 // instant application; filter out non-exposed provider 8117 if (instantAppPkgName != null 8118 && !isInstantApp 8119 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 8120 return null; 8121 } 8122 // provider not enabled 8123 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 8124 return null; 8125 } 8126 return PackageParser.generateProviderInfo( 8127 provider, flags, ps.readUserState(userId), userId); 8128 } 8129 return null; 8130 } 8131 } 8132 8133 /** 8134 * @deprecated 8135 */ 8136 @Deprecated 8137 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8138 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8139 return; 8140 } 8141 // reader 8142 synchronized (mPackages) { 8143 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 8144 .entrySet().iterator(); 8145 final int userId = UserHandle.getCallingUserId(); 8146 while (i.hasNext()) { 8147 Map.Entry<String, PackageParser.Provider> entry = i.next(); 8148 PackageParser.Provider p = entry.getValue(); 8149 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8150 8151 if (ps != null && p.syncable 8152 && (!mSafeMode || (p.info.applicationInfo.flags 8153 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 8154 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8155 ps.readUserState(userId), userId); 8156 if (info != null) { 8157 outNames.add(entry.getKey()); 8158 outInfo.add(info); 8159 } 8160 } 8161 } 8162 } 8163 } 8164 8165 @Override 8166 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8167 int uid, int flags, String metaDataKey) { 8168 final int callingUid = Binder.getCallingUid(); 8169 final int userId = processName != null ? UserHandle.getUserId(uid) 8170 : UserHandle.getCallingUserId(); 8171 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8172 flags = updateFlagsForComponent(flags, userId, processName); 8173 ArrayList<ProviderInfo> finalList = null; 8174 // reader 8175 synchronized (mPackages) { 8176 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8177 while (i.hasNext()) { 8178 final PackageParser.Provider p = i.next(); 8179 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8180 if (ps != null && p.info.authority != null 8181 && (processName == null 8182 || (p.info.processName.equals(processName) 8183 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8184 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8185 8186 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8187 // parameter. 8188 if (metaDataKey != null 8189 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8190 continue; 8191 } 8192 final ComponentName component = 8193 new ComponentName(p.info.packageName, p.info.name); 8194 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8195 continue; 8196 } 8197 if (finalList == null) { 8198 finalList = new ArrayList<ProviderInfo>(3); 8199 } 8200 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8201 ps.readUserState(userId), userId); 8202 if (info != null) { 8203 finalList.add(info); 8204 } 8205 } 8206 } 8207 } 8208 8209 if (finalList != null) { 8210 Collections.sort(finalList, mProviderInitOrderSorter); 8211 return new ParceledListSlice<ProviderInfo>(finalList); 8212 } 8213 8214 return ParceledListSlice.emptyList(); 8215 } 8216 8217 @Override 8218 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8219 // reader 8220 synchronized (mPackages) { 8221 final int callingUid = Binder.getCallingUid(); 8222 final int callingUserId = UserHandle.getUserId(callingUid); 8223 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8224 if (ps == null) return null; 8225 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8226 return null; 8227 } 8228 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8229 return PackageParser.generateInstrumentationInfo(i, flags); 8230 } 8231 } 8232 8233 @Override 8234 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8235 String targetPackage, int flags) { 8236 final int callingUid = Binder.getCallingUid(); 8237 final int callingUserId = UserHandle.getUserId(callingUid); 8238 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8239 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8240 return ParceledListSlice.emptyList(); 8241 } 8242 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8243 } 8244 8245 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8246 int flags) { 8247 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8248 8249 // reader 8250 synchronized (mPackages) { 8251 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8252 while (i.hasNext()) { 8253 final PackageParser.Instrumentation p = i.next(); 8254 if (targetPackage == null 8255 || targetPackage.equals(p.info.targetPackage)) { 8256 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8257 flags); 8258 if (ii != null) { 8259 finalList.add(ii); 8260 } 8261 } 8262 } 8263 } 8264 8265 return finalList; 8266 } 8267 8268 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8269 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8270 try { 8271 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8272 } finally { 8273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8274 } 8275 } 8276 8277 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8278 final File[] files = scanDir.listFiles(); 8279 if (ArrayUtils.isEmpty(files)) { 8280 Log.d(TAG, "No files in app dir " + scanDir); 8281 return; 8282 } 8283 8284 if (DEBUG_PACKAGE_SCANNING) { 8285 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8286 + " flags=0x" + Integer.toHexString(parseFlags)); 8287 } 8288 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8289 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8290 mParallelPackageParserCallback)) { 8291 // Submit files for parsing in parallel 8292 int fileCount = 0; 8293 for (File file : files) { 8294 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8295 && !PackageInstallerService.isStageName(file.getName()); 8296 if (!isPackage) { 8297 // Ignore entries which are not packages 8298 continue; 8299 } 8300 parallelPackageParser.submit(file, parseFlags); 8301 fileCount++; 8302 } 8303 8304 // Process results one by one 8305 for (; fileCount > 0; fileCount--) { 8306 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8307 Throwable throwable = parseResult.throwable; 8308 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8309 8310 if (throwable == null) { 8311 // TODO(toddke): move lower in the scan chain 8312 // Static shared libraries have synthetic package names 8313 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8314 renameStaticSharedLibraryPackage(parseResult.pkg); 8315 } 8316 try { 8317 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8318 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8319 currentTime, null); 8320 } 8321 } catch (PackageManagerException e) { 8322 errorCode = e.error; 8323 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8324 } 8325 } else if (throwable instanceof PackageParser.PackageParserException) { 8326 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8327 throwable; 8328 errorCode = e.error; 8329 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8330 } else { 8331 throw new IllegalStateException("Unexpected exception occurred while parsing " 8332 + parseResult.scanFile, throwable); 8333 } 8334 8335 // Delete invalid userdata apps 8336 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8337 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8338 logCriticalInfo(Log.WARN, 8339 "Deleting invalid package at " + parseResult.scanFile); 8340 removeCodePathLI(parseResult.scanFile); 8341 } 8342 } 8343 } 8344 } 8345 8346 public static void reportSettingsProblem(int priority, String msg) { 8347 logCriticalInfo(priority, msg); 8348 } 8349 8350 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8351 final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException { 8352 // When upgrading from pre-N MR1, verify the package time stamp using the package 8353 // directory and not the APK file. 8354 final long lastModifiedTime = mIsPreNMR1Upgrade 8355 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8356 if (ps != null && !forceCollect 8357 && ps.codePathString.equals(pkg.codePath) 8358 && ps.timeStamp == lastModifiedTime 8359 && !isCompatSignatureUpdateNeeded(pkg) 8360 && !isRecoverSignatureUpdateNeeded(pkg)) { 8361 if (ps.signatures.mSigningDetails.signatures != null 8362 && ps.signatures.mSigningDetails.signatures.length != 0 8363 && ps.signatures.mSigningDetails.signatureSchemeVersion 8364 != SignatureSchemeVersion.UNKNOWN) { 8365 // Optimization: reuse the existing cached signing data 8366 // if the package appears to be unchanged. 8367 pkg.mSigningDetails = 8368 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 8369 return; 8370 } 8371 8372 Slog.w(TAG, "PackageSetting for " + ps.name 8373 + " is missing signatures. Collecting certs again to recover them."); 8374 } else { 8375 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8376 (forceCollect ? " (forced)" : "")); 8377 } 8378 8379 try { 8380 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8381 PackageParser.collectCertificates(pkg, parseFlags); 8382 } catch (PackageParserException e) { 8383 throw PackageManagerException.from(e); 8384 } finally { 8385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8386 } 8387 } 8388 8389 /** 8390 * Traces a package scan. 8391 * @see #scanPackageLI(File, int, int, long, UserHandle) 8392 */ 8393 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8394 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8395 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8396 try { 8397 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8398 } finally { 8399 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8400 } 8401 } 8402 8403 /** 8404 * Scans a package and returns the newly parsed package. 8405 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8406 */ 8407 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8408 long currentTime, UserHandle user) throws PackageManagerException { 8409 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8410 PackageParser pp = new PackageParser(); 8411 pp.setSeparateProcesses(mSeparateProcesses); 8412 pp.setOnlyCoreApps(mOnlyCore); 8413 pp.setDisplayMetrics(mMetrics); 8414 pp.setCallback(mPackageParserCallback); 8415 8416 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8417 final PackageParser.Package pkg; 8418 try { 8419 pkg = pp.parsePackage(scanFile, parseFlags); 8420 } catch (PackageParserException e) { 8421 throw PackageManagerException.from(e); 8422 } finally { 8423 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8424 } 8425 8426 // Static shared libraries have synthetic package names 8427 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8428 renameStaticSharedLibraryPackage(pkg); 8429 } 8430 8431 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8432 } 8433 8434 /** 8435 * Scans a package and returns the newly parsed package. 8436 * @throws PackageManagerException on a parse error. 8437 */ 8438 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8439 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8440 @Nullable UserHandle user) 8441 throws PackageManagerException { 8442 // If the package has children and this is the first dive in the function 8443 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8444 // packages (parent and children) would be successfully scanned before the 8445 // actual scan since scanning mutates internal state and we want to atomically 8446 // install the package and its children. 8447 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8448 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8449 scanFlags |= SCAN_CHECK_ONLY; 8450 } 8451 } else { 8452 scanFlags &= ~SCAN_CHECK_ONLY; 8453 } 8454 8455 // Scan the parent 8456 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8457 scanFlags, currentTime, user); 8458 8459 // Scan the children 8460 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8461 for (int i = 0; i < childCount; i++) { 8462 PackageParser.Package childPackage = pkg.childPackages.get(i); 8463 addForInitLI(childPackage, parseFlags, scanFlags, 8464 currentTime, user); 8465 } 8466 8467 8468 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8469 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8470 } 8471 8472 return scannedPkg; 8473 } 8474 8475 // Temporary to catch potential issues with refactoring 8476 private static boolean REFACTOR_DEBUG = true; 8477 /** 8478 * Adds a new package to the internal data structures during platform initialization. 8479 * <p>After adding, the package is known to the system and available for querying. 8480 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8481 * etc...], additional checks are performed. Basic verification [such as ensuring 8482 * matching signatures, checking version codes, etc...] occurs if the package is 8483 * identical to a previously known package. If the package fails a signature check, 8484 * the version installed on /data will be removed. If the version of the new package 8485 * is less than or equal than the version on /data, it will be ignored. 8486 * <p>Regardless of the package location, the results are applied to the internal 8487 * structures and the package is made available to the rest of the system. 8488 * <p>NOTE: The return value should be removed. It's the passed in package object. 8489 */ 8490 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8491 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8492 @Nullable UserHandle user) 8493 throws PackageManagerException { 8494 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8495 final String renamedPkgName; 8496 final PackageSetting disabledPkgSetting; 8497 final boolean isSystemPkgUpdated; 8498 final boolean pkgAlreadyExists; 8499 PackageSetting pkgSetting; 8500 8501 // NOTE: installPackageLI() has the same code to setup the package's 8502 // application info. This probably should be done lower in the call 8503 // stack [such as scanPackageOnly()]. However, we verify the application 8504 // info prior to that [in scanPackageNew()] and thus have to setup 8505 // the application info early. 8506 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8507 pkg.setApplicationInfoCodePath(pkg.codePath); 8508 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8509 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8510 pkg.setApplicationInfoResourcePath(pkg.codePath); 8511 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8512 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8513 8514 synchronized (mPackages) { 8515 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8516 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8517if (REFACTOR_DEBUG) { 8518Slog.e("TODD", 8519 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8520} 8521 if (realPkgName != null) { 8522 ensurePackageRenamed(pkg, renamedPkgName); 8523 } 8524 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8525 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8526 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8527 pkgAlreadyExists = pkgSetting != null; 8528 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8529 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8530 isSystemPkgUpdated = disabledPkgSetting != null; 8531 8532 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8533 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8534 } 8535if (REFACTOR_DEBUG) { 8536Slog.e("TODD", 8537 "SSP? " + scanSystemPartition 8538 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8539 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8540} 8541 8542 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8543 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8544 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8545 : null; 8546 if (DEBUG_PACKAGE_SCANNING 8547 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8548 && sharedUserSetting != null) { 8549 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8550 + " (uid=" + sharedUserSetting.userId + "):" 8551 + " packages=" + sharedUserSetting.packages); 8552if (REFACTOR_DEBUG) { 8553Slog.e("TODD", 8554 "Shared UserID " + pkg.mSharedUserId 8555 + " (uid=" + sharedUserSetting.userId + "):" 8556 + " packages=" + sharedUserSetting.packages); 8557} 8558 } 8559 8560 if (scanSystemPartition) { 8561 // Potentially prune child packages. If the application on the /system 8562 // partition has been updated via OTA, but, is still disabled by a 8563 // version on /data, cycle through all of its children packages and 8564 // remove children that are no longer defined. 8565 if (isSystemPkgUpdated) { 8566if (REFACTOR_DEBUG) { 8567Slog.e("TODD", 8568 "Disable child packages"); 8569} 8570 final int scannedChildCount = (pkg.childPackages != null) 8571 ? pkg.childPackages.size() : 0; 8572 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8573 ? disabledPkgSetting.childPackageNames.size() : 0; 8574 for (int i = 0; i < disabledChildCount; i++) { 8575 String disabledChildPackageName = 8576 disabledPkgSetting.childPackageNames.get(i); 8577 boolean disabledPackageAvailable = false; 8578 for (int j = 0; j < scannedChildCount; j++) { 8579 PackageParser.Package childPkg = pkg.childPackages.get(j); 8580 if (childPkg.packageName.equals(disabledChildPackageName)) { 8581if (REFACTOR_DEBUG) { 8582Slog.e("TODD", 8583 "Ignore " + disabledChildPackageName); 8584} 8585 disabledPackageAvailable = true; 8586 break; 8587 } 8588 } 8589 if (!disabledPackageAvailable) { 8590if (REFACTOR_DEBUG) { 8591Slog.e("TODD", 8592 "Disable " + disabledChildPackageName); 8593} 8594 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8595 } 8596 } 8597 // we're updating the disabled package, so, scan it as the package setting 8598 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8599 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8600 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8601 (pkg == mPlatformPackage), user); 8602if (REFACTOR_DEBUG) { 8603Slog.e("TODD", 8604 "Scan disabled system package"); 8605Slog.e("TODD", 8606 "Pre: " + request.pkgSetting.dumpState_temp()); 8607} 8608final ScanResult result = 8609 scanPackageOnlyLI(request, mFactoryTest, -1L); 8610if (REFACTOR_DEBUG) { 8611Slog.e("TODD", 8612 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8613} 8614 } 8615 } 8616 } 8617 8618 final boolean newPkgChangedPaths = 8619 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8620if (REFACTOR_DEBUG) { 8621Slog.e("TODD", 8622 "paths changed? " + newPkgChangedPaths 8623 + "; old: " + pkg.codePath 8624 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8625} 8626 final boolean newPkgVersionGreater = 8627 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8628if (REFACTOR_DEBUG) { 8629Slog.e("TODD", 8630 "version greater? " + newPkgVersionGreater 8631 + "; old: " + pkg.getLongVersionCode() 8632 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8633} 8634 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8635 && newPkgChangedPaths && newPkgVersionGreater; 8636if (REFACTOR_DEBUG) { 8637 Slog.e("TODD", 8638 "system better? " + isSystemPkgBetter); 8639} 8640 if (isSystemPkgBetter) { 8641 // The version of the application on /system is greater than the version on 8642 // /data. Switch back to the application on /system. 8643 // It's safe to assume the application on /system will correctly scan. If not, 8644 // there won't be a working copy of the application. 8645 synchronized (mPackages) { 8646 // just remove the loaded entries from package lists 8647 mPackages.remove(pkgSetting.name); 8648 } 8649 8650 logCriticalInfo(Log.WARN, 8651 "System package updated;" 8652 + " name: " + pkgSetting.name 8653 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8654 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8655if (REFACTOR_DEBUG) { 8656Slog.e("TODD", 8657 "System package changed;" 8658 + " name: " + pkgSetting.name 8659 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8660 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8661} 8662 8663 final InstallArgs args = createInstallArgsForExisting( 8664 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8665 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8666 args.cleanUpResourcesLI(); 8667 synchronized (mPackages) { 8668 mSettings.enableSystemPackageLPw(pkgSetting.name); 8669 } 8670 } 8671 8672 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8673if (REFACTOR_DEBUG) { 8674Slog.e("TODD", 8675 "THROW exception; system pkg version not good enough"); 8676} 8677 // The version of the application on the /system partition is less than or 8678 // equal to the version on the /data partition. Throw an exception and use 8679 // the application already installed on the /data partition. 8680 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8681 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8682 + " better than this " + pkg.getLongVersionCode()); 8683 } 8684 8685 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8686 // force the verification. Full apk verification will happen unless apk verity is set up for 8687 // the file. In that case, only small part of the apk is verified upfront. 8688 collectCertificatesLI(pkgSetting, pkg, parseFlags, 8689 PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting)); 8690 8691 boolean shouldHideSystemApp = false; 8692 // A new application appeared on /system, but, we already have a copy of 8693 // the application installed on /data. 8694 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8695 && !pkgSetting.isSystem()) { 8696 // if the signatures don't match, wipe the installed application and its data 8697 if (compareSignatures(pkgSetting.signatures.mSigningDetails.signatures, 8698 pkg.mSigningDetails.signatures) 8699 != PackageManager.SIGNATURE_MATCH) { 8700 logCriticalInfo(Log.WARN, 8701 "System package signature mismatch;" 8702 + " name: " + pkgSetting.name); 8703if (REFACTOR_DEBUG) { 8704Slog.e("TODD", 8705 "System package signature mismatch;" 8706 + " name: " + pkgSetting.name); 8707} 8708 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8709 "scanPackageInternalLI")) { 8710 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8711 } 8712 pkgSetting = null; 8713 } else if (newPkgVersionGreater) { 8714 // The application on /system is newer than the application on /data. 8715 // Simply remove the application on /data [keeping application data] 8716 // and replace it with the version on /system. 8717 logCriticalInfo(Log.WARN, 8718 "System package enabled;" 8719 + " name: " + pkgSetting.name 8720 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8721 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8722if (REFACTOR_DEBUG) { 8723Slog.e("TODD", 8724 "System package enabled;" 8725 + " name: " + pkgSetting.name 8726 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8727 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8728} 8729 InstallArgs args = createInstallArgsForExisting( 8730 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8731 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8732 synchronized (mInstallLock) { 8733 args.cleanUpResourcesLI(); 8734 } 8735 } else { 8736 // The application on /system is older than the application on /data. Hide 8737 // the application on /system and the version on /data will be scanned later 8738 // and re-added like an update. 8739 shouldHideSystemApp = true; 8740 logCriticalInfo(Log.INFO, 8741 "System package disabled;" 8742 + " name: " + pkgSetting.name 8743 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8744 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8745if (REFACTOR_DEBUG) { 8746Slog.e("TODD", 8747 "System package disabled;" 8748 + " name: " + pkgSetting.name 8749 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8750 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8751} 8752 } 8753 } 8754 8755if (REFACTOR_DEBUG) { 8756Slog.e("TODD", 8757 "Scan package"); 8758Slog.e("TODD", 8759 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8760} 8761 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8762 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8763if (REFACTOR_DEBUG) { 8764pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8765Slog.e("TODD", 8766 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8767} 8768 8769 if (shouldHideSystemApp) { 8770if (REFACTOR_DEBUG) { 8771Slog.e("TODD", 8772 "Disable package: " + pkg.packageName); 8773} 8774 synchronized (mPackages) { 8775 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8776 } 8777 } 8778 return scannedPkg; 8779 } 8780 8781 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8782 // Derive the new package synthetic package name 8783 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8784 + pkg.staticSharedLibVersion); 8785 } 8786 8787 private static String fixProcessName(String defProcessName, 8788 String processName) { 8789 if (processName == null) { 8790 return defProcessName; 8791 } 8792 return processName; 8793 } 8794 8795 /** 8796 * Enforces that only the system UID or root's UID can call a method exposed 8797 * via Binder. 8798 * 8799 * @param message used as message if SecurityException is thrown 8800 * @throws SecurityException if the caller is not system or root 8801 */ 8802 private static final void enforceSystemOrRoot(String message) { 8803 final int uid = Binder.getCallingUid(); 8804 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8805 throw new SecurityException(message); 8806 } 8807 } 8808 8809 @Override 8810 public void performFstrimIfNeeded() { 8811 enforceSystemOrRoot("Only the system can request fstrim"); 8812 8813 // Before everything else, see whether we need to fstrim. 8814 try { 8815 IStorageManager sm = PackageHelper.getStorageManager(); 8816 if (sm != null) { 8817 boolean doTrim = false; 8818 final long interval = android.provider.Settings.Global.getLong( 8819 mContext.getContentResolver(), 8820 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8821 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8822 if (interval > 0) { 8823 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8824 if (timeSinceLast > interval) { 8825 doTrim = true; 8826 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8827 + "; running immediately"); 8828 } 8829 } 8830 if (doTrim) { 8831 final boolean dexOptDialogShown; 8832 synchronized (mPackages) { 8833 dexOptDialogShown = mDexOptDialogShown; 8834 } 8835 if (!isFirstBoot() && dexOptDialogShown) { 8836 try { 8837 ActivityManager.getService().showBootMessage( 8838 mContext.getResources().getString( 8839 R.string.android_upgrading_fstrim), true); 8840 } catch (RemoteException e) { 8841 } 8842 } 8843 sm.runMaintenance(); 8844 } 8845 } else { 8846 Slog.e(TAG, "storageManager service unavailable!"); 8847 } 8848 } catch (RemoteException e) { 8849 // Can't happen; StorageManagerService is local 8850 } 8851 } 8852 8853 @Override 8854 public void updatePackagesIfNeeded() { 8855 enforceSystemOrRoot("Only the system can request package update"); 8856 8857 // We need to re-extract after an OTA. 8858 boolean causeUpgrade = isUpgrade(); 8859 8860 // First boot or factory reset. 8861 // Note: we also handle devices that are upgrading to N right now as if it is their 8862 // first boot, as they do not have profile data. 8863 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8864 8865 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8866 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8867 8868 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8869 return; 8870 } 8871 8872 List<PackageParser.Package> pkgs; 8873 synchronized (mPackages) { 8874 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8875 } 8876 8877 final long startTime = System.nanoTime(); 8878 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8879 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8880 false /* bootComplete */); 8881 8882 final int elapsedTimeSeconds = 8883 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8884 8885 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8886 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8887 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8888 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8889 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8890 } 8891 8892 /* 8893 * Return the prebuilt profile path given a package base code path. 8894 */ 8895 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8896 return pkg.baseCodePath + ".prof"; 8897 } 8898 8899 /** 8900 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8901 * containing statistics about the invocation. The array consists of three elements, 8902 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8903 * and {@code numberOfPackagesFailed}. 8904 */ 8905 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8906 final String compilerFilter, boolean bootComplete) { 8907 8908 int numberOfPackagesVisited = 0; 8909 int numberOfPackagesOptimized = 0; 8910 int numberOfPackagesSkipped = 0; 8911 int numberOfPackagesFailed = 0; 8912 final int numberOfPackagesToDexopt = pkgs.size(); 8913 8914 for (PackageParser.Package pkg : pkgs) { 8915 numberOfPackagesVisited++; 8916 8917 boolean useProfileForDexopt = false; 8918 8919 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8920 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8921 // that are already compiled. 8922 File profileFile = new File(getPrebuildProfilePath(pkg)); 8923 // Copy profile if it exists. 8924 if (profileFile.exists()) { 8925 try { 8926 // We could also do this lazily before calling dexopt in 8927 // PackageDexOptimizer to prevent this happening on first boot. The issue 8928 // is that we don't have a good way to say "do this only once". 8929 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8930 pkg.applicationInfo.uid, pkg.packageName)) { 8931 Log.e(TAG, "Installer failed to copy system profile!"); 8932 } else { 8933 // Disabled as this causes speed-profile compilation during first boot 8934 // even if things are already compiled. 8935 // useProfileForDexopt = true; 8936 } 8937 } catch (Exception e) { 8938 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8939 e); 8940 } 8941 } else { 8942 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8943 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8944 // minimize the number off apps being speed-profile compiled during first boot. 8945 // The other paths will not change the filter. 8946 if (disabledPs != null && disabledPs.pkg.isStub) { 8947 // The package is the stub one, remove the stub suffix to get the normal 8948 // package and APK names. 8949 String systemProfilePath = 8950 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8951 profileFile = new File(systemProfilePath); 8952 // If we have a profile for a compressed APK, copy it to the reference 8953 // location. 8954 // Note that copying the profile here will cause it to override the 8955 // reference profile every OTA even though the existing reference profile 8956 // may have more data. We can't copy during decompression since the 8957 // directories are not set up at that point. 8958 if (profileFile.exists()) { 8959 try { 8960 // We could also do this lazily before calling dexopt in 8961 // PackageDexOptimizer to prevent this happening on first boot. The 8962 // issue is that we don't have a good way to say "do this only 8963 // once". 8964 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8965 pkg.applicationInfo.uid, pkg.packageName)) { 8966 Log.e(TAG, "Failed to copy system profile for stub package!"); 8967 } else { 8968 useProfileForDexopt = true; 8969 } 8970 } catch (Exception e) { 8971 Log.e(TAG, "Failed to copy profile " + 8972 profileFile.getAbsolutePath() + " ", e); 8973 } 8974 } 8975 } 8976 } 8977 } 8978 8979 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8980 if (DEBUG_DEXOPT) { 8981 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8982 } 8983 numberOfPackagesSkipped++; 8984 continue; 8985 } 8986 8987 if (DEBUG_DEXOPT) { 8988 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8989 numberOfPackagesToDexopt + ": " + pkg.packageName); 8990 } 8991 8992 if (showDialog) { 8993 try { 8994 ActivityManager.getService().showBootMessage( 8995 mContext.getResources().getString(R.string.android_upgrading_apk, 8996 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8997 } catch (RemoteException e) { 8998 } 8999 synchronized (mPackages) { 9000 mDexOptDialogShown = true; 9001 } 9002 } 9003 9004 String pkgCompilerFilter = compilerFilter; 9005 if (useProfileForDexopt) { 9006 // Use background dexopt mode to try and use the profile. Note that this does not 9007 // guarantee usage of the profile. 9008 pkgCompilerFilter = 9009 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 9010 PackageManagerService.REASON_BACKGROUND_DEXOPT); 9011 } 9012 9013 // checkProfiles is false to avoid merging profiles during boot which 9014 // might interfere with background compilation (b/28612421). 9015 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9016 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9017 // trade-off worth doing to save boot time work. 9018 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9019 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9020 pkg.packageName, 9021 pkgCompilerFilter, 9022 dexoptFlags)); 9023 9024 switch (primaryDexOptStaus) { 9025 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9026 numberOfPackagesOptimized++; 9027 break; 9028 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9029 numberOfPackagesSkipped++; 9030 break; 9031 case PackageDexOptimizer.DEX_OPT_FAILED: 9032 numberOfPackagesFailed++; 9033 break; 9034 default: 9035 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9036 break; 9037 } 9038 } 9039 9040 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9041 numberOfPackagesFailed }; 9042 } 9043 9044 @Override 9045 public void notifyPackageUse(String packageName, int reason) { 9046 synchronized (mPackages) { 9047 final int callingUid = Binder.getCallingUid(); 9048 final int callingUserId = UserHandle.getUserId(callingUid); 9049 if (getInstantAppPackageName(callingUid) != null) { 9050 if (!isCallerSameApp(packageName, callingUid)) { 9051 return; 9052 } 9053 } else { 9054 if (isInstantApp(packageName, callingUserId)) { 9055 return; 9056 } 9057 } 9058 notifyPackageUseLocked(packageName, reason); 9059 } 9060 } 9061 9062 private void notifyPackageUseLocked(String packageName, int reason) { 9063 final PackageParser.Package p = mPackages.get(packageName); 9064 if (p == null) { 9065 return; 9066 } 9067 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9068 } 9069 9070 @Override 9071 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9072 List<String> classPaths, String loaderIsa) { 9073 int userId = UserHandle.getCallingUserId(); 9074 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9075 if (ai == null) { 9076 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9077 + loadingPackageName + ", user=" + userId); 9078 return; 9079 } 9080 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9081 } 9082 9083 @Override 9084 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9085 IDexModuleRegisterCallback callback) { 9086 int userId = UserHandle.getCallingUserId(); 9087 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9088 DexManager.RegisterDexModuleResult result; 9089 if (ai == null) { 9090 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9091 " calling user. package=" + packageName + ", user=" + userId); 9092 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9093 } else { 9094 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9095 } 9096 9097 if (callback != null) { 9098 mHandler.post(() -> { 9099 try { 9100 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9101 } catch (RemoteException e) { 9102 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9103 } 9104 }); 9105 } 9106 } 9107 9108 /** 9109 * Ask the package manager to perform a dex-opt with the given compiler filter. 9110 * 9111 * Note: exposed only for the shell command to allow moving packages explicitly to a 9112 * definite state. 9113 */ 9114 @Override 9115 public boolean performDexOptMode(String packageName, 9116 boolean checkProfiles, String targetCompilerFilter, boolean force, 9117 boolean bootComplete, String splitName) { 9118 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9119 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9120 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9121 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 9122 splitName, flags)); 9123 } 9124 9125 /** 9126 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9127 * secondary dex files belonging to the given package. 9128 * 9129 * Note: exposed only for the shell command to allow moving packages explicitly to a 9130 * definite state. 9131 */ 9132 @Override 9133 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9134 boolean force) { 9135 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9136 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9137 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9138 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9139 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9140 } 9141 9142 /*package*/ boolean performDexOpt(DexoptOptions options) { 9143 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9144 return false; 9145 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9146 return false; 9147 } 9148 9149 if (options.isDexoptOnlySecondaryDex()) { 9150 return mDexManager.dexoptSecondaryDex(options); 9151 } else { 9152 int dexoptStatus = performDexOptWithStatus(options); 9153 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9154 } 9155 } 9156 9157 /** 9158 * Perform dexopt on the given package and return one of following result: 9159 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9160 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9161 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9162 */ 9163 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9164 return performDexOptTraced(options); 9165 } 9166 9167 private int performDexOptTraced(DexoptOptions options) { 9168 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9169 try { 9170 return performDexOptInternal(options); 9171 } finally { 9172 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9173 } 9174 } 9175 9176 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9177 // if the package can now be considered up to date for the given filter. 9178 private int performDexOptInternal(DexoptOptions options) { 9179 PackageParser.Package p; 9180 synchronized (mPackages) { 9181 p = mPackages.get(options.getPackageName()); 9182 if (p == null) { 9183 // Package could not be found. Report failure. 9184 return PackageDexOptimizer.DEX_OPT_FAILED; 9185 } 9186 mPackageUsage.maybeWriteAsync(mPackages); 9187 mCompilerStats.maybeWriteAsync(); 9188 } 9189 long callingId = Binder.clearCallingIdentity(); 9190 try { 9191 synchronized (mInstallLock) { 9192 return performDexOptInternalWithDependenciesLI(p, options); 9193 } 9194 } finally { 9195 Binder.restoreCallingIdentity(callingId); 9196 } 9197 } 9198 9199 public ArraySet<String> getOptimizablePackages() { 9200 ArraySet<String> pkgs = new ArraySet<String>(); 9201 synchronized (mPackages) { 9202 for (PackageParser.Package p : mPackages.values()) { 9203 if (PackageDexOptimizer.canOptimizePackage(p)) { 9204 pkgs.add(p.packageName); 9205 } 9206 } 9207 } 9208 return pkgs; 9209 } 9210 9211 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9212 DexoptOptions options) { 9213 // Select the dex optimizer based on the force parameter. 9214 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9215 // allocate an object here. 9216 PackageDexOptimizer pdo = options.isForce() 9217 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9218 : mPackageDexOptimizer; 9219 9220 // Dexopt all dependencies first. Note: we ignore the return value and march on 9221 // on errors. 9222 // Note that we are going to call performDexOpt on those libraries as many times as 9223 // they are referenced in packages. When we do a batch of performDexOpt (for example 9224 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9225 // and the first package that uses the library will dexopt it. The 9226 // others will see that the compiled code for the library is up to date. 9227 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9228 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9229 if (!deps.isEmpty()) { 9230 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9231 options.getCompilerFilter(), options.getSplitName(), 9232 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9233 for (PackageParser.Package depPackage : deps) { 9234 // TODO: Analyze and investigate if we (should) profile libraries. 9235 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9236 getOrCreateCompilerPackageStats(depPackage), 9237 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9238 } 9239 } 9240 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9241 getOrCreateCompilerPackageStats(p), 9242 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9243 } 9244 9245 /** 9246 * Reconcile the information we have about the secondary dex files belonging to 9247 * {@code packagName} and the actual dex files. For all dex files that were 9248 * deleted, update the internal records and delete the generated oat files. 9249 */ 9250 @Override 9251 public void reconcileSecondaryDexFiles(String packageName) { 9252 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9253 return; 9254 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9255 return; 9256 } 9257 mDexManager.reconcileSecondaryDexFiles(packageName); 9258 } 9259 9260 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9261 // a reference there. 9262 /*package*/ DexManager getDexManager() { 9263 return mDexManager; 9264 } 9265 9266 /** 9267 * Execute the background dexopt job immediately. 9268 */ 9269 @Override 9270 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9271 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9272 return false; 9273 } 9274 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9275 } 9276 9277 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9278 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9279 || p.usesStaticLibraries != null) { 9280 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9281 Set<String> collectedNames = new HashSet<>(); 9282 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9283 9284 retValue.remove(p); 9285 9286 return retValue; 9287 } else { 9288 return Collections.emptyList(); 9289 } 9290 } 9291 9292 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9293 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9294 if (!collectedNames.contains(p.packageName)) { 9295 collectedNames.add(p.packageName); 9296 collected.add(p); 9297 9298 if (p.usesLibraries != null) { 9299 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9300 null, collected, collectedNames); 9301 } 9302 if (p.usesOptionalLibraries != null) { 9303 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9304 null, collected, collectedNames); 9305 } 9306 if (p.usesStaticLibraries != null) { 9307 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9308 p.usesStaticLibrariesVersions, collected, collectedNames); 9309 } 9310 } 9311 } 9312 9313 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9314 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9315 final int libNameCount = libs.size(); 9316 for (int i = 0; i < libNameCount; i++) { 9317 String libName = libs.get(i); 9318 long version = (versions != null && versions.length == libNameCount) 9319 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9320 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9321 if (libPkg != null) { 9322 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9323 } 9324 } 9325 } 9326 9327 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9328 synchronized (mPackages) { 9329 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9330 if (libEntry != null) { 9331 return mPackages.get(libEntry.apk); 9332 } 9333 return null; 9334 } 9335 } 9336 9337 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9338 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9339 if (versionedLib == null) { 9340 return null; 9341 } 9342 return versionedLib.get(version); 9343 } 9344 9345 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9346 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9347 pkg.staticSharedLibName); 9348 if (versionedLib == null) { 9349 return null; 9350 } 9351 long previousLibVersion = -1; 9352 final int versionCount = versionedLib.size(); 9353 for (int i = 0; i < versionCount; i++) { 9354 final long libVersion = versionedLib.keyAt(i); 9355 if (libVersion < pkg.staticSharedLibVersion) { 9356 previousLibVersion = Math.max(previousLibVersion, libVersion); 9357 } 9358 } 9359 if (previousLibVersion >= 0) { 9360 return versionedLib.get(previousLibVersion); 9361 } 9362 return null; 9363 } 9364 9365 public void shutdown() { 9366 mPackageUsage.writeNow(mPackages); 9367 mCompilerStats.writeNow(); 9368 mDexManager.writePackageDexUsageNow(); 9369 } 9370 9371 @Override 9372 public void dumpProfiles(String packageName) { 9373 PackageParser.Package pkg; 9374 synchronized (mPackages) { 9375 pkg = mPackages.get(packageName); 9376 if (pkg == null) { 9377 throw new IllegalArgumentException("Unknown package: " + packageName); 9378 } 9379 } 9380 /* Only the shell, root, or the app user should be able to dump profiles. */ 9381 int callingUid = Binder.getCallingUid(); 9382 if (callingUid != Process.SHELL_UID && 9383 callingUid != Process.ROOT_UID && 9384 callingUid != pkg.applicationInfo.uid) { 9385 throw new SecurityException("dumpProfiles"); 9386 } 9387 9388 synchronized (mInstallLock) { 9389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9390 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9391 try { 9392 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9393 String codePaths = TextUtils.join(";", allCodePaths); 9394 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9395 } catch (InstallerException e) { 9396 Slog.w(TAG, "Failed to dump profiles", e); 9397 } 9398 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9399 } 9400 } 9401 9402 @Override 9403 public void forceDexOpt(String packageName) { 9404 enforceSystemOrRoot("forceDexOpt"); 9405 9406 PackageParser.Package pkg; 9407 synchronized (mPackages) { 9408 pkg = mPackages.get(packageName); 9409 if (pkg == null) { 9410 throw new IllegalArgumentException("Unknown package: " + packageName); 9411 } 9412 } 9413 9414 synchronized (mInstallLock) { 9415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9416 9417 // Whoever is calling forceDexOpt wants a compiled package. 9418 // Don't use profiles since that may cause compilation to be skipped. 9419 final int res = performDexOptInternalWithDependenciesLI( 9420 pkg, 9421 new DexoptOptions(packageName, 9422 getDefaultCompilerFilter(), 9423 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9424 9425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9426 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9427 throw new IllegalStateException("Failed to dexopt: " + res); 9428 } 9429 } 9430 } 9431 9432 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9433 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9434 Slog.w(TAG, "Unable to update from " + oldPkg.name 9435 + " to " + newPkg.packageName 9436 + ": old package not in system partition"); 9437 return false; 9438 } else if (mPackages.get(oldPkg.name) != null) { 9439 Slog.w(TAG, "Unable to update from " + oldPkg.name 9440 + " to " + newPkg.packageName 9441 + ": old package still exists"); 9442 return false; 9443 } 9444 return true; 9445 } 9446 9447 void removeCodePathLI(File codePath) { 9448 if (codePath.isDirectory()) { 9449 try { 9450 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9451 } catch (InstallerException e) { 9452 Slog.w(TAG, "Failed to remove code path", e); 9453 } 9454 } else { 9455 codePath.delete(); 9456 } 9457 } 9458 9459 private int[] resolveUserIds(int userId) { 9460 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9461 } 9462 9463 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9464 if (pkg == null) { 9465 Slog.wtf(TAG, "Package was null!", new Throwable()); 9466 return; 9467 } 9468 clearAppDataLeafLIF(pkg, userId, flags); 9469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9470 for (int i = 0; i < childCount; i++) { 9471 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9472 } 9473 } 9474 9475 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9476 final PackageSetting ps; 9477 synchronized (mPackages) { 9478 ps = mSettings.mPackages.get(pkg.packageName); 9479 } 9480 for (int realUserId : resolveUserIds(userId)) { 9481 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9482 try { 9483 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9484 ceDataInode); 9485 } catch (InstallerException e) { 9486 Slog.w(TAG, String.valueOf(e)); 9487 } 9488 } 9489 } 9490 9491 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9492 if (pkg == null) { 9493 Slog.wtf(TAG, "Package was null!", new Throwable()); 9494 return; 9495 } 9496 destroyAppDataLeafLIF(pkg, userId, flags); 9497 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9498 for (int i = 0; i < childCount; i++) { 9499 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9500 } 9501 } 9502 9503 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9504 final PackageSetting ps; 9505 synchronized (mPackages) { 9506 ps = mSettings.mPackages.get(pkg.packageName); 9507 } 9508 for (int realUserId : resolveUserIds(userId)) { 9509 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9510 try { 9511 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9512 ceDataInode); 9513 } catch (InstallerException e) { 9514 Slog.w(TAG, String.valueOf(e)); 9515 } 9516 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9517 } 9518 } 9519 9520 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9521 if (pkg == null) { 9522 Slog.wtf(TAG, "Package was null!", new Throwable()); 9523 return; 9524 } 9525 destroyAppProfilesLeafLIF(pkg); 9526 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9527 for (int i = 0; i < childCount; i++) { 9528 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9529 } 9530 } 9531 9532 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9533 try { 9534 mInstaller.destroyAppProfiles(pkg.packageName); 9535 } catch (InstallerException e) { 9536 Slog.w(TAG, String.valueOf(e)); 9537 } 9538 } 9539 9540 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9541 if (pkg == null) { 9542 Slog.wtf(TAG, "Package was null!", new Throwable()); 9543 return; 9544 } 9545 clearAppProfilesLeafLIF(pkg); 9546 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9547 for (int i = 0; i < childCount; i++) { 9548 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9549 } 9550 } 9551 9552 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9553 try { 9554 mInstaller.clearAppProfiles(pkg.packageName); 9555 } catch (InstallerException e) { 9556 Slog.w(TAG, String.valueOf(e)); 9557 } 9558 } 9559 9560 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9561 long lastUpdateTime) { 9562 // Set parent install/update time 9563 PackageSetting ps = (PackageSetting) pkg.mExtras; 9564 if (ps != null) { 9565 ps.firstInstallTime = firstInstallTime; 9566 ps.lastUpdateTime = lastUpdateTime; 9567 } 9568 // Set children install/update time 9569 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9570 for (int i = 0; i < childCount; i++) { 9571 PackageParser.Package childPkg = pkg.childPackages.get(i); 9572 ps = (PackageSetting) childPkg.mExtras; 9573 if (ps != null) { 9574 ps.firstInstallTime = firstInstallTime; 9575 ps.lastUpdateTime = lastUpdateTime; 9576 } 9577 } 9578 } 9579 9580 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9581 SharedLibraryEntry file, 9582 PackageParser.Package changingLib) { 9583 if (file.path != null) { 9584 usesLibraryFiles.add(file.path); 9585 return; 9586 } 9587 PackageParser.Package p = mPackages.get(file.apk); 9588 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9589 // If we are doing this while in the middle of updating a library apk, 9590 // then we need to make sure to use that new apk for determining the 9591 // dependencies here. (We haven't yet finished committing the new apk 9592 // to the package manager state.) 9593 if (p == null || p.packageName.equals(changingLib.packageName)) { 9594 p = changingLib; 9595 } 9596 } 9597 if (p != null) { 9598 usesLibraryFiles.addAll(p.getAllCodePaths()); 9599 if (p.usesLibraryFiles != null) { 9600 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9601 } 9602 } 9603 } 9604 9605 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9606 PackageParser.Package changingLib) throws PackageManagerException { 9607 if (pkg == null) { 9608 return; 9609 } 9610 // The collection used here must maintain the order of addition (so 9611 // that libraries are searched in the correct order) and must have no 9612 // duplicates. 9613 Set<String> usesLibraryFiles = null; 9614 if (pkg.usesLibraries != null) { 9615 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9616 null, null, pkg.packageName, changingLib, true, 9617 pkg.applicationInfo.targetSdkVersion, null); 9618 } 9619 if (pkg.usesStaticLibraries != null) { 9620 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9621 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9622 pkg.packageName, changingLib, true, 9623 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9624 } 9625 if (pkg.usesOptionalLibraries != null) { 9626 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9627 null, null, pkg.packageName, changingLib, false, 9628 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9629 } 9630 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9631 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9632 } else { 9633 pkg.usesLibraryFiles = null; 9634 } 9635 } 9636 9637 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9638 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9639 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9640 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9641 throws PackageManagerException { 9642 final int libCount = requestedLibraries.size(); 9643 for (int i = 0; i < libCount; i++) { 9644 final String libName = requestedLibraries.get(i); 9645 final long libVersion = requiredVersions != null ? requiredVersions[i] 9646 : SharedLibraryInfo.VERSION_UNDEFINED; 9647 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9648 if (libEntry == null) { 9649 if (required) { 9650 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9651 "Package " + packageName + " requires unavailable shared library " 9652 + libName + "; failing!"); 9653 } else if (DEBUG_SHARED_LIBRARIES) { 9654 Slog.i(TAG, "Package " + packageName 9655 + " desires unavailable shared library " 9656 + libName + "; ignoring!"); 9657 } 9658 } else { 9659 if (requiredVersions != null && requiredCertDigests != null) { 9660 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9661 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9662 "Package " + packageName + " requires unavailable static shared" 9663 + " library " + libName + " version " 9664 + libEntry.info.getLongVersion() + "; failing!"); 9665 } 9666 9667 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9668 if (libPkg == null) { 9669 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9670 "Package " + packageName + " requires unavailable static shared" 9671 + " library; failing!"); 9672 } 9673 9674 final String[] expectedCertDigests = requiredCertDigests[i]; 9675 // For apps targeting O MR1 we require explicit enumeration of all certs. 9676 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9677 ? PackageUtils.computeSignaturesSha256Digests( 9678 libPkg.mSigningDetails.signatures) 9679 : PackageUtils.computeSignaturesSha256Digests( 9680 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9681 9682 // Take a shortcut if sizes don't match. Note that if an app doesn't 9683 // target O we don't parse the "additional-certificate" tags similarly 9684 // how we only consider all certs only for apps targeting O (see above). 9685 // Therefore, the size check is safe to make. 9686 if (expectedCertDigests.length != libCertDigests.length) { 9687 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9688 "Package " + packageName + " requires differently signed" + 9689 " static shared library; failing!"); 9690 } 9691 9692 // Use a predictable order as signature order may vary 9693 Arrays.sort(libCertDigests); 9694 Arrays.sort(expectedCertDigests); 9695 9696 final int certCount = libCertDigests.length; 9697 for (int j = 0; j < certCount; j++) { 9698 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9699 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9700 "Package " + packageName + " requires differently signed" + 9701 " static shared library; failing!"); 9702 } 9703 } 9704 } 9705 9706 if (outUsedLibraries == null) { 9707 // Use LinkedHashSet to preserve the order of files added to 9708 // usesLibraryFiles while eliminating duplicates. 9709 outUsedLibraries = new LinkedHashSet<>(); 9710 } 9711 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9712 } 9713 } 9714 return outUsedLibraries; 9715 } 9716 9717 private static boolean hasString(List<String> list, List<String> which) { 9718 if (list == null) { 9719 return false; 9720 } 9721 for (int i=list.size()-1; i>=0; i--) { 9722 for (int j=which.size()-1; j>=0; j--) { 9723 if (which.get(j).equals(list.get(i))) { 9724 return true; 9725 } 9726 } 9727 } 9728 return false; 9729 } 9730 9731 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9732 PackageParser.Package changingPkg) { 9733 ArrayList<PackageParser.Package> res = null; 9734 for (PackageParser.Package pkg : mPackages.values()) { 9735 if (changingPkg != null 9736 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9737 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9738 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9739 changingPkg.staticSharedLibName)) { 9740 return null; 9741 } 9742 if (res == null) { 9743 res = new ArrayList<>(); 9744 } 9745 res.add(pkg); 9746 try { 9747 updateSharedLibrariesLPr(pkg, changingPkg); 9748 } catch (PackageManagerException e) { 9749 // If a system app update or an app and a required lib missing we 9750 // delete the package and for updated system apps keep the data as 9751 // it is better for the user to reinstall than to be in an limbo 9752 // state. Also libs disappearing under an app should never happen 9753 // - just in case. 9754 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9755 final int flags = pkg.isUpdatedSystemApp() 9756 ? PackageManager.DELETE_KEEP_DATA : 0; 9757 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9758 flags , null, true, null); 9759 } 9760 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9761 } 9762 } 9763 return res; 9764 } 9765 9766 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9767 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9768 @Nullable UserHandle user) throws PackageManagerException { 9769 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9770 // If the package has children and this is the first dive in the function 9771 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9772 // whether all packages (parent and children) would be successfully scanned 9773 // before the actual scan since scanning mutates internal state and we want 9774 // to atomically install the package and its children. 9775 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9776 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9777 scanFlags |= SCAN_CHECK_ONLY; 9778 } 9779 } else { 9780 scanFlags &= ~SCAN_CHECK_ONLY; 9781 } 9782 9783 final PackageParser.Package scannedPkg; 9784 try { 9785 // Scan the parent 9786 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9787 // Scan the children 9788 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9789 for (int i = 0; i < childCount; i++) { 9790 PackageParser.Package childPkg = pkg.childPackages.get(i); 9791 scanPackageNewLI(childPkg, parseFlags, 9792 scanFlags, currentTime, user); 9793 } 9794 } finally { 9795 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9796 } 9797 9798 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9799 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9800 } 9801 9802 return scannedPkg; 9803 } 9804 9805 /** The result of a package scan. */ 9806 private static class ScanResult { 9807 /** Whether or not the package scan was successful */ 9808 public final boolean success; 9809 /** 9810 * The final package settings. This may be the same object passed in 9811 * the {@link ScanRequest}, but, with modified values. 9812 */ 9813 @Nullable public final PackageSetting pkgSetting; 9814 /** ABI code paths that have changed in the package scan */ 9815 @Nullable public final List<String> changedAbiCodePath; 9816 public ScanResult( 9817 boolean success, 9818 @Nullable PackageSetting pkgSetting, 9819 @Nullable List<String> changedAbiCodePath) { 9820 this.success = success; 9821 this.pkgSetting = pkgSetting; 9822 this.changedAbiCodePath = changedAbiCodePath; 9823 } 9824 } 9825 9826 /** A package to be scanned */ 9827 private static class ScanRequest { 9828 /** The parsed package */ 9829 @NonNull public final PackageParser.Package pkg; 9830 /** Shared user settings, if the package has a shared user */ 9831 @Nullable public final SharedUserSetting sharedUserSetting; 9832 /** 9833 * Package settings of the currently installed version. 9834 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9835 * during scan. 9836 */ 9837 @Nullable public final PackageSetting pkgSetting; 9838 /** A copy of the settings for the currently installed version */ 9839 @Nullable public final PackageSetting oldPkgSetting; 9840 /** Package settings for the disabled version on the /system partition */ 9841 @Nullable public final PackageSetting disabledPkgSetting; 9842 /** Package settings for the installed version under its original package name */ 9843 @Nullable public final PackageSetting originalPkgSetting; 9844 /** The real package name of a renamed application */ 9845 @Nullable public final String realPkgName; 9846 public final @ParseFlags int parseFlags; 9847 public final @ScanFlags int scanFlags; 9848 /** The user for which the package is being scanned */ 9849 @Nullable public final UserHandle user; 9850 /** Whether or not the platform package is being scanned */ 9851 public final boolean isPlatformPackage; 9852 public ScanRequest( 9853 @NonNull PackageParser.Package pkg, 9854 @Nullable SharedUserSetting sharedUserSetting, 9855 @Nullable PackageSetting pkgSetting, 9856 @Nullable PackageSetting disabledPkgSetting, 9857 @Nullable PackageSetting originalPkgSetting, 9858 @Nullable String realPkgName, 9859 @ParseFlags int parseFlags, 9860 @ScanFlags int scanFlags, 9861 boolean isPlatformPackage, 9862 @Nullable UserHandle user) { 9863 this.pkg = pkg; 9864 this.pkgSetting = pkgSetting; 9865 this.sharedUserSetting = sharedUserSetting; 9866 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9867 this.disabledPkgSetting = disabledPkgSetting; 9868 this.originalPkgSetting = originalPkgSetting; 9869 this.realPkgName = realPkgName; 9870 this.parseFlags = parseFlags; 9871 this.scanFlags = scanFlags; 9872 this.isPlatformPackage = isPlatformPackage; 9873 this.user = user; 9874 } 9875 } 9876 9877 /** 9878 * Returns the actual scan flags depending upon the state of the other settings. 9879 * <p>Updated system applications will not have the following flags set 9880 * by default and need to be adjusted after the fact: 9881 * <ul> 9882 * <li>{@link #SCAN_AS_SYSTEM}</li> 9883 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9884 * <li>{@link #SCAN_AS_OEM}</li> 9885 * <li>{@link #SCAN_AS_VENDOR}</li> 9886 * <li>{@link #SCAN_AS_PRODUCT}</li> 9887 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9888 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9889 * </ul> 9890 */ 9891 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9892 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 9893 PackageParser.Package pkg) { 9894 if (disabledPkgSetting != null) { 9895 // updated system application, must at least have SCAN_AS_SYSTEM 9896 scanFlags |= SCAN_AS_SYSTEM; 9897 if ((disabledPkgSetting.pkgPrivateFlags 9898 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9899 scanFlags |= SCAN_AS_PRIVILEGED; 9900 } 9901 if ((disabledPkgSetting.pkgPrivateFlags 9902 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9903 scanFlags |= SCAN_AS_OEM; 9904 } 9905 if ((disabledPkgSetting.pkgPrivateFlags 9906 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9907 scanFlags |= SCAN_AS_VENDOR; 9908 } 9909 if ((disabledPkgSetting.pkgPrivateFlags 9910 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 9911 scanFlags |= SCAN_AS_PRODUCT; 9912 } 9913 } 9914 if (pkgSetting != null) { 9915 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9916 if (pkgSetting.getInstantApp(userId)) { 9917 scanFlags |= SCAN_AS_INSTANT_APP; 9918 } 9919 if (pkgSetting.getVirtulalPreload(userId)) { 9920 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9921 } 9922 } 9923 9924 // Scan as privileged apps that share a user with a priv-app. 9925 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) && !pkg.isPrivileged() 9926 && (pkg.mSharedUserId != null)) { 9927 SharedUserSetting sharedUserSetting = null; 9928 try { 9929 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 9930 } catch (PackageManagerException ignore) {} 9931 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 9932 // Exempt SharedUsers signed with the platform key. 9933 // TODO(b/72378145) Fix this exemption. Force signature apps 9934 // to whitelist their privileged permissions just like other 9935 // priv-apps. 9936 synchronized (mPackages) { 9937 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 9938 if (!pkg.packageName.equals("android") 9939 && (compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 9940 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 9941 scanFlags |= SCAN_AS_PRIVILEGED; 9942 } 9943 } 9944 } 9945 } 9946 9947 return scanFlags; 9948 } 9949 9950 @GuardedBy("mInstallLock") 9951 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9952 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9953 @Nullable UserHandle user) throws PackageManagerException { 9954 9955 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9956 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9957 if (realPkgName != null) { 9958 ensurePackageRenamed(pkg, renamedPkgName); 9959 } 9960 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9961 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9962 final PackageSetting disabledPkgSetting = 9963 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9964 9965 if (mTransferedPackages.contains(pkg.packageName)) { 9966 Slog.w(TAG, "Package " + pkg.packageName 9967 + " was transferred to another, but its .apk remains"); 9968 } 9969 9970 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 9971 synchronized (mPackages) { 9972 applyPolicy(pkg, parseFlags, scanFlags); 9973 assertPackageIsValid(pkg, parseFlags, scanFlags); 9974 9975 SharedUserSetting sharedUserSetting = null; 9976 if (pkg.mSharedUserId != null) { 9977 // SIDE EFFECTS; may potentially allocate a new shared user 9978 sharedUserSetting = mSettings.getSharedUserLPw( 9979 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9980 if (DEBUG_PACKAGE_SCANNING) { 9981 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9982 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9983 + " (uid=" + sharedUserSetting.userId + "):" 9984 + " packages=" + sharedUserSetting.packages); 9985 } 9986 } 9987 9988 boolean scanSucceeded = false; 9989 try { 9990 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9991 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9992 (pkg == mPlatformPackage), user); 9993 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9994 if (result.success) { 9995 commitScanResultsLocked(request, result); 9996 } 9997 scanSucceeded = true; 9998 } finally { 9999 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 10000 // DELETE_DATA_ON_FAILURES is only used by frozen paths 10001 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 10002 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 10003 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 10004 } 10005 } 10006 } 10007 return pkg; 10008 } 10009 10010 /** 10011 * Commits the package scan and modifies system state. 10012 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10013 * of committing the package, leaving the system in an inconsistent state. 10014 * This needs to be fixed so, once we get to this point, no errors are 10015 * possible and the system is not left in an inconsistent state. 10016 */ 10017 @GuardedBy("mPackages") 10018 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 10019 throws PackageManagerException { 10020 final PackageParser.Package pkg = request.pkg; 10021 final @ParseFlags int parseFlags = request.parseFlags; 10022 final @ScanFlags int scanFlags = request.scanFlags; 10023 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10024 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10025 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10026 final UserHandle user = request.user; 10027 final String realPkgName = request.realPkgName; 10028 final PackageSetting pkgSetting = result.pkgSetting; 10029 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10030 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 10031 10032 if (newPkgSettingCreated) { 10033 if (originalPkgSetting != null) { 10034 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10035 } 10036 // THROWS: when we can't allocate a user id. add call to check if there's 10037 // enough space to ensure we won't throw; otherwise, don't modify state 10038 mSettings.addUserToSettingLPw(pkgSetting); 10039 10040 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10041 mTransferedPackages.add(originalPkgSetting.name); 10042 } 10043 } 10044 // TODO(toddke): Consider a method specifically for modifying the Package object 10045 // post scan; or, moving this stuff out of the Package object since it has nothing 10046 // to do with the package on disk. 10047 // We need to have this here because addUserToSettingLPw() is sometimes responsible 10048 // for creating the application ID. If we did this earlier, we would be saving the 10049 // correct ID. 10050 pkg.applicationInfo.uid = pkgSetting.appId; 10051 10052 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 10053 10054 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 10055 mTransferedPackages.add(pkg.packageName); 10056 } 10057 10058 // THROWS: when requested libraries that can't be found. it only changes 10059 // the state of the passed in pkg object, so, move to the top of the method 10060 // and allow it to abort 10061 if ((scanFlags & SCAN_BOOTING) == 0 10062 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10063 // Check all shared libraries and map to their actual file path. 10064 // We only do this here for apps not on a system dir, because those 10065 // are the only ones that can fail an install due to this. We 10066 // will take care of the system apps by updating all of their 10067 // library paths after the scan is done. Also during the initial 10068 // scan don't update any libs as we do this wholesale after all 10069 // apps are scanned to avoid dependency based scanning. 10070 updateSharedLibrariesLPr(pkg, null); 10071 } 10072 10073 // All versions of a static shared library are referenced with the same 10074 // package name. Internally, we use a synthetic package name to allow 10075 // multiple versions of the same shared library to be installed. So, 10076 // we need to generate the synthetic package name of the latest shared 10077 // library in order to compare signatures. 10078 PackageSetting signatureCheckPs = pkgSetting; 10079 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10080 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 10081 if (libraryEntry != null) { 10082 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 10083 } 10084 } 10085 10086 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10087 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 10088 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 10089 // We just determined the app is signed correctly, so bring 10090 // over the latest parsed certs. 10091 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10092 } else { 10093 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10094 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 10095 "Package " + pkg.packageName + " upgrade keys do not match the " 10096 + "previously installed version"); 10097 } else { 10098 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10099 String msg = "System package " + pkg.packageName 10100 + " signature changed; retaining data."; 10101 reportSettingsProblem(Log.WARN, msg); 10102 } 10103 } 10104 } else { 10105 try { 10106 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 10107 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 10108 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 10109 pkg.mSigningDetails, compareCompat, compareRecover); 10110 // The new KeySets will be re-added later in the scanning process. 10111 if (compatMatch) { 10112 synchronized (mPackages) { 10113 ksms.removeAppKeySetDataLPw(pkg.packageName); 10114 } 10115 } 10116 // We just determined the app is signed correctly, so bring 10117 // over the latest parsed certs. 10118 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10119 } catch (PackageManagerException e) { 10120 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10121 throw e; 10122 } 10123 // The signature has changed, but this package is in the system 10124 // image... let's recover! 10125 pkgSetting.signatures.mSigningDetails = pkg.mSigningDetails; 10126 // However... if this package is part of a shared user, but it 10127 // doesn't match the signature of the shared user, let's fail. 10128 // What this means is that you can't change the signatures 10129 // associated with an overall shared user, which doesn't seem all 10130 // that unreasonable. 10131 if (signatureCheckPs.sharedUser != null) { 10132 if (compareSignatures( 10133 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures, 10134 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 10135 throw new PackageManagerException( 10136 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 10137 "Signature mismatch for shared user: " 10138 + pkgSetting.sharedUser); 10139 } 10140 } 10141 // File a report about this. 10142 String msg = "System package " + pkg.packageName 10143 + " signature changed; retaining data."; 10144 reportSettingsProblem(Log.WARN, msg); 10145 } 10146 } 10147 10148 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 10149 // This package wants to adopt ownership of permissions from 10150 // another package. 10151 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 10152 final String origName = pkg.mAdoptPermissions.get(i); 10153 final PackageSetting orig = mSettings.getPackageLPr(origName); 10154 if (orig != null) { 10155 if (verifyPackageUpdateLPr(orig, pkg)) { 10156 Slog.i(TAG, "Adopting permissions from " + origName + " to " 10157 + pkg.packageName); 10158 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 10159 } 10160 } 10161 } 10162 } 10163 10164 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 10165 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 10166 final String codePathString = changedAbiCodePath.get(i); 10167 try { 10168 mInstaller.rmdex(codePathString, 10169 getDexCodeInstructionSet(getPreferredInstructionSet())); 10170 } catch (InstallerException ignored) { 10171 } 10172 } 10173 } 10174 10175 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10176 if (oldPkgSetting != null) { 10177 synchronized (mPackages) { 10178 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 10179 } 10180 } 10181 } else { 10182 final int userId = user == null ? 0 : user.getIdentifier(); 10183 // Modify state for the given package setting 10184 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10185 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10186 if (pkgSetting.getInstantApp(userId)) { 10187 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10188 } 10189 } 10190 } 10191 10192 /** 10193 * Returns the "real" name of the package. 10194 * <p>This may differ from the package's actual name if the application has already 10195 * been installed under one of this package's original names. 10196 */ 10197 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10198 @Nullable String renamedPkgName) { 10199 if (isPackageRenamed(pkg, renamedPkgName)) { 10200 return pkg.mRealPackage; 10201 } 10202 return null; 10203 } 10204 10205 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10206 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10207 @Nullable String renamedPkgName) { 10208 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10209 } 10210 10211 /** 10212 * Returns the original package setting. 10213 * <p>A package can migrate its name during an update. In this scenario, a package 10214 * designates a set of names that it considers as one of its original names. 10215 * <p>An original package must be signed identically and it must have the same 10216 * shared user [if any]. 10217 */ 10218 @GuardedBy("mPackages") 10219 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10220 @Nullable String renamedPkgName) { 10221 if (!isPackageRenamed(pkg, renamedPkgName)) { 10222 return null; 10223 } 10224 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10225 final PackageSetting originalPs = 10226 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10227 if (originalPs != null) { 10228 // the package is already installed under its original name... 10229 // but, should we use it? 10230 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10231 // the new package is incompatible with the original 10232 continue; 10233 } else if (originalPs.sharedUser != null) { 10234 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10235 // the shared user id is incompatible with the original 10236 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10237 + " to " + pkg.packageName + ": old uid " 10238 + originalPs.sharedUser.name 10239 + " differs from " + pkg.mSharedUserId); 10240 continue; 10241 } 10242 // TODO: Add case when shared user id is added [b/28144775] 10243 } else { 10244 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10245 + pkg.packageName + " to old name " + originalPs.name); 10246 } 10247 return originalPs; 10248 } 10249 } 10250 return null; 10251 } 10252 10253 /** 10254 * Renames the package if it was installed under a different name. 10255 * <p>When we've already installed the package under an original name, update 10256 * the new package so we can continue to have the old name. 10257 */ 10258 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10259 @NonNull String renamedPackageName) { 10260 if (pkg.mOriginalPackages == null 10261 || !pkg.mOriginalPackages.contains(renamedPackageName) 10262 || pkg.packageName.equals(renamedPackageName)) { 10263 return; 10264 } 10265 pkg.setPackageName(renamedPackageName); 10266 } 10267 10268 /** 10269 * Just scans the package without any side effects. 10270 * <p>Not entirely true at the moment. There is still one side effect -- this 10271 * method potentially modifies a live {@link PackageSetting} object representing 10272 * the package being scanned. This will be resolved in the future. 10273 * 10274 * @param request Information about the package to be scanned 10275 * @param isUnderFactoryTest Whether or not the device is under factory test 10276 * @param currentTime The current time, in millis 10277 * @return The results of the scan 10278 */ 10279 @GuardedBy("mInstallLock") 10280 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10281 boolean isUnderFactoryTest, long currentTime) 10282 throws PackageManagerException { 10283 final PackageParser.Package pkg = request.pkg; 10284 PackageSetting pkgSetting = request.pkgSetting; 10285 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10286 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10287 final @ParseFlags int parseFlags = request.parseFlags; 10288 final @ScanFlags int scanFlags = request.scanFlags; 10289 final String realPkgName = request.realPkgName; 10290 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10291 final UserHandle user = request.user; 10292 final boolean isPlatformPackage = request.isPlatformPackage; 10293 10294 List<String> changedAbiCodePath = null; 10295 10296 if (DEBUG_PACKAGE_SCANNING) { 10297 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10298 Log.d(TAG, "Scanning package " + pkg.packageName); 10299 } 10300 10301 if (Build.IS_DEBUGGABLE && 10302 pkg.isPrivileged() && 10303 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10304 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10305 } 10306 10307 // Initialize package source and resource directories 10308 final File scanFile = new File(pkg.codePath); 10309 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10310 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10311 10312 // We keep references to the derived CPU Abis from settings in oder to reuse 10313 // them in the case where we're not upgrading or booting for the first time. 10314 String primaryCpuAbiFromSettings = null; 10315 String secondaryCpuAbiFromSettings = null; 10316 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10317 10318 if (!needToDeriveAbi) { 10319 if (pkgSetting != null) { 10320 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10321 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10322 } else { 10323 // Re-scanning a system package after uninstalling updates; need to derive ABI 10324 needToDeriveAbi = true; 10325 } 10326 } 10327 10328 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10329 PackageManagerService.reportSettingsProblem(Log.WARN, 10330 "Package " + pkg.packageName + " shared user changed from " 10331 + (pkgSetting.sharedUser != null 10332 ? pkgSetting.sharedUser.name : "<nothing>") 10333 + " to " 10334 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10335 + "; replacing with new"); 10336 pkgSetting = null; 10337 } 10338 10339 String[] usesStaticLibraries = null; 10340 if (pkg.usesStaticLibraries != null) { 10341 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10342 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10343 } 10344 final boolean createNewPackage = (pkgSetting == null); 10345 if (createNewPackage) { 10346 final String parentPackageName = (pkg.parentPackage != null) 10347 ? pkg.parentPackage.packageName : null; 10348 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10349 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10350 // REMOVE SharedUserSetting from method; update in a separate call 10351 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10352 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10353 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10354 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10355 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10356 user, true /*allowInstall*/, instantApp, virtualPreload, 10357 parentPackageName, pkg.getChildPackageNames(), 10358 UserManagerService.getInstance(), usesStaticLibraries, 10359 pkg.usesStaticLibrariesVersions); 10360 } else { 10361 // REMOVE SharedUserSetting from method; update in a separate call. 10362 // 10363 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10364 // secondaryCpuAbi are not known at this point so we always update them 10365 // to null here, only to reset them at a later point. 10366 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10367 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10368 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10369 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10370 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10371 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10372 } 10373 if (createNewPackage && originalPkgSetting != null) { 10374 // This is the initial transition from the original package, so, 10375 // fix up the new package's name now. We must do this after looking 10376 // up the package under its new name, so getPackageLP takes care of 10377 // fiddling things correctly. 10378 pkg.setPackageName(originalPkgSetting.name); 10379 10380 // File a report about this. 10381 String msg = "New package " + pkgSetting.realName 10382 + " renamed to replace old package " + pkgSetting.name; 10383 reportSettingsProblem(Log.WARN, msg); 10384 } 10385 10386 if (disabledPkgSetting != null) { 10387 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10388 } 10389 10390 SELinuxMMAC.assignSeInfoValue(pkg); 10391 10392 pkg.mExtras = pkgSetting; 10393 pkg.applicationInfo.processName = fixProcessName( 10394 pkg.applicationInfo.packageName, 10395 pkg.applicationInfo.processName); 10396 10397 if (!isPlatformPackage) { 10398 // Get all of our default paths setup 10399 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10400 } 10401 10402 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10403 10404 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10405 if (needToDeriveAbi) { 10406 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10407 final boolean extractNativeLibs = !pkg.isLibrary(); 10408 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10409 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10410 10411 // Some system apps still use directory structure for native libraries 10412 // in which case we might end up not detecting abi solely based on apk 10413 // structure. Try to detect abi based on directory structure. 10414 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10415 pkg.applicationInfo.primaryCpuAbi == null) { 10416 setBundledAppAbisAndRoots(pkg, pkgSetting); 10417 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10418 } 10419 } else { 10420 // This is not a first boot or an upgrade, don't bother deriving the 10421 // ABI during the scan. Instead, trust the value that was stored in the 10422 // package setting. 10423 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10424 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10425 10426 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10427 10428 if (DEBUG_ABI_SELECTION) { 10429 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10430 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10431 pkg.applicationInfo.secondaryCpuAbi); 10432 } 10433 } 10434 } else { 10435 if ((scanFlags & SCAN_MOVE) != 0) { 10436 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10437 // but we already have this packages package info in the PackageSetting. We just 10438 // use that and derive the native library path based on the new codepath. 10439 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10440 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10441 } 10442 10443 // Set native library paths again. For moves, the path will be updated based on the 10444 // ABIs we've determined above. For non-moves, the path will be updated based on the 10445 // ABIs we determined during compilation, but the path will depend on the final 10446 // package path (after the rename away from the stage path). 10447 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10448 } 10449 10450 // This is a special case for the "system" package, where the ABI is 10451 // dictated by the zygote configuration (and init.rc). We should keep track 10452 // of this ABI so that we can deal with "normal" applications that run under 10453 // the same UID correctly. 10454 if (isPlatformPackage) { 10455 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10456 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10457 } 10458 10459 // If there's a mismatch between the abi-override in the package setting 10460 // and the abiOverride specified for the install. Warn about this because we 10461 // would've already compiled the app without taking the package setting into 10462 // account. 10463 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10464 if (cpuAbiOverride == null && pkg.packageName != null) { 10465 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10466 " for package " + pkg.packageName); 10467 } 10468 } 10469 10470 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10471 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10472 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10473 10474 // Copy the derived override back to the parsed package, so that we can 10475 // update the package settings accordingly. 10476 pkg.cpuAbiOverride = cpuAbiOverride; 10477 10478 if (DEBUG_ABI_SELECTION) { 10479 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10480 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10481 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10482 } 10483 10484 // Push the derived path down into PackageSettings so we know what to 10485 // clean up at uninstall time. 10486 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10487 10488 if (DEBUG_ABI_SELECTION) { 10489 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10490 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10491 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10492 } 10493 10494 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10495 // We don't do this here during boot because we can do it all 10496 // at once after scanning all existing packages. 10497 // 10498 // We also do this *before* we perform dexopt on this package, so that 10499 // we can avoid redundant dexopts, and also to make sure we've got the 10500 // code and package path correct. 10501 changedAbiCodePath = 10502 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10503 } 10504 10505 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10506 android.Manifest.permission.FACTORY_TEST)) { 10507 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10508 } 10509 10510 if (isSystemApp(pkg)) { 10511 pkgSetting.isOrphaned = true; 10512 } 10513 10514 // Take care of first install / last update times. 10515 final long scanFileTime = getLastModifiedTime(pkg); 10516 if (currentTime != 0) { 10517 if (pkgSetting.firstInstallTime == 0) { 10518 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10519 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10520 pkgSetting.lastUpdateTime = currentTime; 10521 } 10522 } else if (pkgSetting.firstInstallTime == 0) { 10523 // We need *something*. Take time time stamp of the file. 10524 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10525 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10526 if (scanFileTime != pkgSetting.timeStamp) { 10527 // A package on the system image has changed; consider this 10528 // to be an update. 10529 pkgSetting.lastUpdateTime = scanFileTime; 10530 } 10531 } 10532 pkgSetting.setTimeStamp(scanFileTime); 10533 10534 pkgSetting.pkg = pkg; 10535 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10536 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10537 pkgSetting.versionCode = pkg.getLongVersionCode(); 10538 } 10539 // Update volume if needed 10540 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10541 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10542 Slog.i(PackageManagerService.TAG, 10543 "Update" + (pkgSetting.isSystem() ? " system" : "") 10544 + " package " + pkg.packageName 10545 + " volume from " + pkgSetting.volumeUuid 10546 + " to " + volumeUuid); 10547 pkgSetting.volumeUuid = volumeUuid; 10548 } 10549 10550 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10551 } 10552 10553 /** 10554 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10555 */ 10556 private static boolean apkHasCode(String fileName) { 10557 StrictJarFile jarFile = null; 10558 try { 10559 jarFile = new StrictJarFile(fileName, 10560 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10561 return jarFile.findEntry("classes.dex") != null; 10562 } catch (IOException ignore) { 10563 } finally { 10564 try { 10565 if (jarFile != null) { 10566 jarFile.close(); 10567 } 10568 } catch (IOException ignore) {} 10569 } 10570 return false; 10571 } 10572 10573 /** 10574 * Enforces code policy for the package. This ensures that if an APK has 10575 * declared hasCode="true" in its manifest that the APK actually contains 10576 * code. 10577 * 10578 * @throws PackageManagerException If bytecode could not be found when it should exist 10579 */ 10580 private static void assertCodePolicy(PackageParser.Package pkg) 10581 throws PackageManagerException { 10582 final boolean shouldHaveCode = 10583 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10584 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10585 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10586 "Package " + pkg.baseCodePath + " code is missing"); 10587 } 10588 10589 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10590 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10591 final boolean splitShouldHaveCode = 10592 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10593 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10594 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10595 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10596 } 10597 } 10598 } 10599 } 10600 10601 /** 10602 * Applies policy to the parsed package based upon the given policy flags. 10603 * Ensures the package is in a good state. 10604 * <p> 10605 * Implementation detail: This method must NOT have any side effect. It would 10606 * ideally be static, but, it requires locks to read system state. 10607 */ 10608 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10609 final @ScanFlags int scanFlags) { 10610 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10611 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10612 if (pkg.applicationInfo.isDirectBootAware()) { 10613 // we're direct boot aware; set for all components 10614 for (PackageParser.Service s : pkg.services) { 10615 s.info.encryptionAware = s.info.directBootAware = true; 10616 } 10617 for (PackageParser.Provider p : pkg.providers) { 10618 p.info.encryptionAware = p.info.directBootAware = true; 10619 } 10620 for (PackageParser.Activity a : pkg.activities) { 10621 a.info.encryptionAware = a.info.directBootAware = true; 10622 } 10623 for (PackageParser.Activity r : pkg.receivers) { 10624 r.info.encryptionAware = r.info.directBootAware = true; 10625 } 10626 } 10627 if (compressedFileExists(pkg.codePath)) { 10628 pkg.isStub = true; 10629 } 10630 } else { 10631 // non system apps can't be flagged as core 10632 pkg.coreApp = false; 10633 // clear flags not applicable to regular apps 10634 pkg.applicationInfo.flags &= 10635 ~ApplicationInfo.FLAG_PERSISTENT; 10636 pkg.applicationInfo.privateFlags &= 10637 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10638 pkg.applicationInfo.privateFlags &= 10639 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10640 // clear protected broadcasts 10641 pkg.protectedBroadcasts = null; 10642 // cap permission priorities 10643 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10644 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10645 pkg.permissionGroups.get(i).info.priority = 0; 10646 } 10647 } 10648 } 10649 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10650 // ignore export request for single user receivers 10651 if (pkg.receivers != null) { 10652 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10653 final PackageParser.Activity receiver = pkg.receivers.get(i); 10654 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10655 receiver.info.exported = false; 10656 } 10657 } 10658 } 10659 // ignore export request for single user services 10660 if (pkg.services != null) { 10661 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10662 final PackageParser.Service service = pkg.services.get(i); 10663 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10664 service.info.exported = false; 10665 } 10666 } 10667 } 10668 // ignore export request for single user providers 10669 if (pkg.providers != null) { 10670 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10671 final PackageParser.Provider provider = pkg.providers.get(i); 10672 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10673 provider.info.exported = false; 10674 } 10675 } 10676 } 10677 } 10678 10679 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10680 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10681 } 10682 10683 if ((scanFlags & SCAN_AS_OEM) != 0) { 10684 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10685 } 10686 10687 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10688 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10689 } 10690 10691 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 10692 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 10693 } 10694 10695 if (!isSystemApp(pkg)) { 10696 // Only system apps can use these features. 10697 pkg.mOriginalPackages = null; 10698 pkg.mRealPackage = null; 10699 pkg.mAdoptPermissions = null; 10700 } 10701 } 10702 10703 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 10704 throws PackageManagerException { 10705 if (object == null) { 10706 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 10707 } 10708 return object; 10709 } 10710 10711 /** 10712 * Asserts the parsed package is valid according to the given policy. If the 10713 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10714 * <p> 10715 * Implementation detail: This method must NOT have any side effects. It would 10716 * ideally be static, but, it requires locks to read system state. 10717 * 10718 * @throws PackageManagerException If the package fails any of the validation checks 10719 */ 10720 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10721 final @ScanFlags int scanFlags) 10722 throws PackageManagerException { 10723 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10724 assertCodePolicy(pkg); 10725 } 10726 10727 if (pkg.applicationInfo.getCodePath() == null || 10728 pkg.applicationInfo.getResourcePath() == null) { 10729 // Bail out. The resource and code paths haven't been set. 10730 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10731 "Code and resource paths haven't been set correctly"); 10732 } 10733 10734 // Make sure we're not adding any bogus keyset info 10735 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10736 ksms.assertScannedPackageValid(pkg); 10737 10738 synchronized (mPackages) { 10739 // The special "android" package can only be defined once 10740 if (pkg.packageName.equals("android")) { 10741 if (mAndroidApplication != null) { 10742 Slog.w(TAG, "*************************************************"); 10743 Slog.w(TAG, "Core android package being redefined. Skipping."); 10744 Slog.w(TAG, " codePath=" + pkg.codePath); 10745 Slog.w(TAG, "*************************************************"); 10746 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10747 "Core android package being redefined. Skipping."); 10748 } 10749 } 10750 10751 // A package name must be unique; don't allow duplicates 10752 if (mPackages.containsKey(pkg.packageName)) { 10753 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10754 "Application package " + pkg.packageName 10755 + " already installed. Skipping duplicate."); 10756 } 10757 10758 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10759 // Static libs have a synthetic package name containing the version 10760 // but we still want the base name to be unique. 10761 if (mPackages.containsKey(pkg.manifestPackageName)) { 10762 throw new PackageManagerException( 10763 "Duplicate static shared lib provider package"); 10764 } 10765 10766 // Static shared libraries should have at least O target SDK 10767 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10768 throw new PackageManagerException( 10769 "Packages declaring static-shared libs must target O SDK or higher"); 10770 } 10771 10772 // Package declaring static a shared lib cannot be instant apps 10773 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10774 throw new PackageManagerException( 10775 "Packages declaring static-shared libs cannot be instant apps"); 10776 } 10777 10778 // Package declaring static a shared lib cannot be renamed since the package 10779 // name is synthetic and apps can't code around package manager internals. 10780 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10781 throw new PackageManagerException( 10782 "Packages declaring static-shared libs cannot be renamed"); 10783 } 10784 10785 // Package declaring static a shared lib cannot declare child packages 10786 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10787 throw new PackageManagerException( 10788 "Packages declaring static-shared libs cannot have child packages"); 10789 } 10790 10791 // Package declaring static a shared lib cannot declare dynamic libs 10792 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10793 throw new PackageManagerException( 10794 "Packages declaring static-shared libs cannot declare dynamic libs"); 10795 } 10796 10797 // Package declaring static a shared lib cannot declare shared users 10798 if (pkg.mSharedUserId != null) { 10799 throw new PackageManagerException( 10800 "Packages declaring static-shared libs cannot declare shared users"); 10801 } 10802 10803 // Static shared libs cannot declare activities 10804 if (!pkg.activities.isEmpty()) { 10805 throw new PackageManagerException( 10806 "Static shared libs cannot declare activities"); 10807 } 10808 10809 // Static shared libs cannot declare services 10810 if (!pkg.services.isEmpty()) { 10811 throw new PackageManagerException( 10812 "Static shared libs cannot declare services"); 10813 } 10814 10815 // Static shared libs cannot declare providers 10816 if (!pkg.providers.isEmpty()) { 10817 throw new PackageManagerException( 10818 "Static shared libs cannot declare content providers"); 10819 } 10820 10821 // Static shared libs cannot declare receivers 10822 if (!pkg.receivers.isEmpty()) { 10823 throw new PackageManagerException( 10824 "Static shared libs cannot declare broadcast receivers"); 10825 } 10826 10827 // Static shared libs cannot declare permission groups 10828 if (!pkg.permissionGroups.isEmpty()) { 10829 throw new PackageManagerException( 10830 "Static shared libs cannot declare permission groups"); 10831 } 10832 10833 // Static shared libs cannot declare permissions 10834 if (!pkg.permissions.isEmpty()) { 10835 throw new PackageManagerException( 10836 "Static shared libs cannot declare permissions"); 10837 } 10838 10839 // Static shared libs cannot declare protected broadcasts 10840 if (pkg.protectedBroadcasts != null) { 10841 throw new PackageManagerException( 10842 "Static shared libs cannot declare protected broadcasts"); 10843 } 10844 10845 // Static shared libs cannot be overlay targets 10846 if (pkg.mOverlayTarget != null) { 10847 throw new PackageManagerException( 10848 "Static shared libs cannot be overlay targets"); 10849 } 10850 10851 // The version codes must be ordered as lib versions 10852 long minVersionCode = Long.MIN_VALUE; 10853 long maxVersionCode = Long.MAX_VALUE; 10854 10855 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10856 pkg.staticSharedLibName); 10857 if (versionedLib != null) { 10858 final int versionCount = versionedLib.size(); 10859 for (int i = 0; i < versionCount; i++) { 10860 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10861 final long libVersionCode = libInfo.getDeclaringPackage() 10862 .getLongVersionCode(); 10863 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10864 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10865 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10866 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10867 } else { 10868 minVersionCode = maxVersionCode = libVersionCode; 10869 break; 10870 } 10871 } 10872 } 10873 if (pkg.getLongVersionCode() < minVersionCode 10874 || pkg.getLongVersionCode() > maxVersionCode) { 10875 throw new PackageManagerException("Static shared" 10876 + " lib version codes must be ordered as lib versions"); 10877 } 10878 } 10879 10880 // Only privileged apps and updated privileged apps can add child packages. 10881 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10882 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10883 throw new PackageManagerException("Only privileged apps can add child " 10884 + "packages. Ignoring package " + pkg.packageName); 10885 } 10886 final int childCount = pkg.childPackages.size(); 10887 for (int i = 0; i < childCount; i++) { 10888 PackageParser.Package childPkg = pkg.childPackages.get(i); 10889 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10890 childPkg.packageName)) { 10891 throw new PackageManagerException("Can't override child of " 10892 + "another disabled app. Ignoring package " + pkg.packageName); 10893 } 10894 } 10895 } 10896 10897 // If we're only installing presumed-existing packages, require that the 10898 // scanned APK is both already known and at the path previously established 10899 // for it. Previously unknown packages we pick up normally, but if we have an 10900 // a priori expectation about this package's install presence, enforce it. 10901 // With a singular exception for new system packages. When an OTA contains 10902 // a new system package, we allow the codepath to change from a system location 10903 // to the user-installed location. If we don't allow this change, any newer, 10904 // user-installed version of the application will be ignored. 10905 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10906 if (mExpectingBetter.containsKey(pkg.packageName)) { 10907 logCriticalInfo(Log.WARN, 10908 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10909 } else { 10910 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10911 if (known != null) { 10912 if (DEBUG_PACKAGE_SCANNING) { 10913 Log.d(TAG, "Examining " + pkg.codePath 10914 + " and requiring known paths " + known.codePathString 10915 + " & " + known.resourcePathString); 10916 } 10917 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10918 || !pkg.applicationInfo.getResourcePath().equals( 10919 known.resourcePathString)) { 10920 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10921 "Application package " + pkg.packageName 10922 + " found at " + pkg.applicationInfo.getCodePath() 10923 + " but expected at " + known.codePathString 10924 + "; ignoring."); 10925 } 10926 } else { 10927 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10928 "Application package " + pkg.packageName 10929 + " not found; ignoring."); 10930 } 10931 } 10932 } 10933 10934 // Verify that this new package doesn't have any content providers 10935 // that conflict with existing packages. Only do this if the 10936 // package isn't already installed, since we don't want to break 10937 // things that are installed. 10938 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10939 final int N = pkg.providers.size(); 10940 int i; 10941 for (i=0; i<N; i++) { 10942 PackageParser.Provider p = pkg.providers.get(i); 10943 if (p.info.authority != null) { 10944 String names[] = p.info.authority.split(";"); 10945 for (int j = 0; j < names.length; j++) { 10946 if (mProvidersByAuthority.containsKey(names[j])) { 10947 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10948 final String otherPackageName = 10949 ((other != null && other.getComponentName() != null) ? 10950 other.getComponentName().getPackageName() : "?"); 10951 throw new PackageManagerException( 10952 INSTALL_FAILED_CONFLICTING_PROVIDER, 10953 "Can't install because provider name " + names[j] 10954 + " (in package " + pkg.applicationInfo.packageName 10955 + ") is already used by " + otherPackageName); 10956 } 10957 } 10958 } 10959 } 10960 } 10961 10962 // Verify that packages sharing a user with a privileged app are marked as privileged. 10963 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 10964 SharedUserSetting sharedUserSetting = null; 10965 try { 10966 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10967 } catch (PackageManagerException ignore) {} 10968 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10969 // Exempt SharedUsers signed with the platform key. 10970 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10971 if ((platformPkgSetting.signatures.mSigningDetails 10972 != PackageParser.SigningDetails.UNKNOWN) 10973 && (compareSignatures( 10974 platformPkgSetting.signatures.mSigningDetails.signatures, 10975 pkg.mSigningDetails.signatures) 10976 != PackageManager.SIGNATURE_MATCH)) { 10977 throw new PackageManagerException("Apps that share a user with a " + 10978 "privileged app must themselves be marked as privileged. " + 10979 pkg.packageName + " shares privileged user " + 10980 pkg.mSharedUserId + "."); 10981 } 10982 } 10983 } 10984 10985 // Apply policies specific for runtime resource overlays (RROs). 10986 if (pkg.mOverlayTarget != null) { 10987 // System overlays have some restrictions on their use of the 'static' state. 10988 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10989 // We are scanning a system overlay. This can be the first scan of the 10990 // system/vendor/oem partition, or an update to the system overlay. 10991 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 10992 // This must be an update to a system overlay. 10993 final PackageSetting previousPkg = assertNotNull( 10994 mSettings.getPackageLPr(pkg.packageName), 10995 "previous package state not present"); 10996 10997 // Static overlays cannot be updated. 10998 if (previousPkg.pkg.mOverlayIsStatic) { 10999 throw new PackageManagerException("Overlay " + pkg.packageName + 11000 " is static and cannot be upgraded."); 11001 // Non-static overlays cannot be converted to static overlays. 11002 } else if (pkg.mOverlayIsStatic) { 11003 throw new PackageManagerException("Overlay " + pkg.packageName + 11004 " cannot be upgraded into a static overlay."); 11005 } 11006 } 11007 } else { 11008 // The overlay is a non-system overlay. Non-system overlays cannot be static. 11009 if (pkg.mOverlayIsStatic) { 11010 throw new PackageManagerException("Overlay " + pkg.packageName + 11011 " is static but not pre-installed."); 11012 } 11013 11014 // The only case where we allow installation of a non-system overlay is when 11015 // its signature is signed with the platform certificate. 11016 PackageSetting platformPkgSetting = mSettings.getPackageLPr("android"); 11017 if ((platformPkgSetting.signatures.mSigningDetails 11018 != PackageParser.SigningDetails.UNKNOWN) 11019 && (compareSignatures( 11020 platformPkgSetting.signatures.mSigningDetails.signatures, 11021 pkg.mSigningDetails.signatures) 11022 != PackageManager.SIGNATURE_MATCH)) { 11023 throw new PackageManagerException("Overlay " + pkg.packageName + 11024 " must be signed with the platform certificate."); 11025 } 11026 } 11027 } 11028 } 11029 } 11030 11031 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 11032 int type, String declaringPackageName, long declaringVersionCode) { 11033 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11034 if (versionedLib == null) { 11035 versionedLib = new LongSparseArray<>(); 11036 mSharedLibraries.put(name, versionedLib); 11037 if (type == SharedLibraryInfo.TYPE_STATIC) { 11038 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 11039 } 11040 } else if (versionedLib.indexOfKey(version) >= 0) { 11041 return false; 11042 } 11043 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 11044 version, type, declaringPackageName, declaringVersionCode); 11045 versionedLib.put(version, libEntry); 11046 return true; 11047 } 11048 11049 private boolean removeSharedLibraryLPw(String name, long version) { 11050 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 11051 if (versionedLib == null) { 11052 return false; 11053 } 11054 final int libIdx = versionedLib.indexOfKey(version); 11055 if (libIdx < 0) { 11056 return false; 11057 } 11058 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 11059 versionedLib.remove(version); 11060 if (versionedLib.size() <= 0) { 11061 mSharedLibraries.remove(name); 11062 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 11063 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 11064 .getPackageName()); 11065 } 11066 } 11067 return true; 11068 } 11069 11070 /** 11071 * Adds a scanned package to the system. When this method is finished, the package will 11072 * be available for query, resolution, etc... 11073 */ 11074 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 11075 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 11076 final String pkgName = pkg.packageName; 11077 if (mCustomResolverComponentName != null && 11078 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 11079 setUpCustomResolverActivity(pkg); 11080 } 11081 11082 if (pkg.packageName.equals("android")) { 11083 synchronized (mPackages) { 11084 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 11085 // Set up information for our fall-back user intent resolution activity. 11086 mPlatformPackage = pkg; 11087 pkg.mVersionCode = mSdkVersion; 11088 pkg.mVersionCodeMajor = 0; 11089 mAndroidApplication = pkg.applicationInfo; 11090 if (!mResolverReplaced) { 11091 mResolveActivity.applicationInfo = mAndroidApplication; 11092 mResolveActivity.name = ResolverActivity.class.getName(); 11093 mResolveActivity.packageName = mAndroidApplication.packageName; 11094 mResolveActivity.processName = "system:ui"; 11095 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11096 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 11097 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 11098 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 11099 mResolveActivity.exported = true; 11100 mResolveActivity.enabled = true; 11101 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 11102 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 11103 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 11104 | ActivityInfo.CONFIG_SCREEN_LAYOUT 11105 | ActivityInfo.CONFIG_ORIENTATION 11106 | ActivityInfo.CONFIG_KEYBOARD 11107 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 11108 mResolveInfo.activityInfo = mResolveActivity; 11109 mResolveInfo.priority = 0; 11110 mResolveInfo.preferredOrder = 0; 11111 mResolveInfo.match = 0; 11112 mResolveComponentName = new ComponentName( 11113 mAndroidApplication.packageName, mResolveActivity.name); 11114 } 11115 } 11116 } 11117 } 11118 11119 ArrayList<PackageParser.Package> clientLibPkgs = null; 11120 // writer 11121 synchronized (mPackages) { 11122 boolean hasStaticSharedLibs = false; 11123 11124 // Any app can add new static shared libraries 11125 if (pkg.staticSharedLibName != null) { 11126 // Static shared libs don't allow renaming as they have synthetic package 11127 // names to allow install of multiple versions, so use name from manifest. 11128 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 11129 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 11130 pkg.manifestPackageName, pkg.getLongVersionCode())) { 11131 hasStaticSharedLibs = true; 11132 } else { 11133 Slog.w(TAG, "Package " + pkg.packageName + " library " 11134 + pkg.staticSharedLibName + " already exists; skipping"); 11135 } 11136 // Static shared libs cannot be updated once installed since they 11137 // use synthetic package name which includes the version code, so 11138 // not need to update other packages's shared lib dependencies. 11139 } 11140 11141 if (!hasStaticSharedLibs 11142 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 11143 // Only system apps can add new dynamic shared libraries. 11144 if (pkg.libraryNames != null) { 11145 for (int i = 0; i < pkg.libraryNames.size(); i++) { 11146 String name = pkg.libraryNames.get(i); 11147 boolean allowed = false; 11148 if (pkg.isUpdatedSystemApp()) { 11149 // New library entries can only be added through the 11150 // system image. This is important to get rid of a lot 11151 // of nasty edge cases: for example if we allowed a non- 11152 // system update of the app to add a library, then uninstalling 11153 // the update would make the library go away, and assumptions 11154 // we made such as through app install filtering would now 11155 // have allowed apps on the device which aren't compatible 11156 // with it. Better to just have the restriction here, be 11157 // conservative, and create many fewer cases that can negatively 11158 // impact the user experience. 11159 final PackageSetting sysPs = mSettings 11160 .getDisabledSystemPkgLPr(pkg.packageName); 11161 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 11162 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 11163 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 11164 allowed = true; 11165 break; 11166 } 11167 } 11168 } 11169 } else { 11170 allowed = true; 11171 } 11172 if (allowed) { 11173 if (!addSharedLibraryLPw(null, pkg.packageName, name, 11174 SharedLibraryInfo.VERSION_UNDEFINED, 11175 SharedLibraryInfo.TYPE_DYNAMIC, 11176 pkg.packageName, pkg.getLongVersionCode())) { 11177 Slog.w(TAG, "Package " + pkg.packageName + " library " 11178 + name + " already exists; skipping"); 11179 } 11180 } else { 11181 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 11182 + name + " that is not declared on system image; skipping"); 11183 } 11184 } 11185 11186 if ((scanFlags & SCAN_BOOTING) == 0) { 11187 // If we are not booting, we need to update any applications 11188 // that are clients of our shared library. If we are booting, 11189 // this will all be done once the scan is complete. 11190 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 11191 } 11192 } 11193 } 11194 } 11195 11196 if ((scanFlags & SCAN_BOOTING) != 0) { 11197 // No apps can run during boot scan, so they don't need to be frozen 11198 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 11199 // Caller asked to not kill app, so it's probably not frozen 11200 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 11201 // Caller asked us to ignore frozen check for some reason; they 11202 // probably didn't know the package name 11203 } else { 11204 // We're doing major surgery on this package, so it better be frozen 11205 // right now to keep it from launching 11206 checkPackageFrozen(pkgName); 11207 } 11208 11209 // Also need to kill any apps that are dependent on the library. 11210 if (clientLibPkgs != null) { 11211 for (int i=0; i<clientLibPkgs.size(); i++) { 11212 PackageParser.Package clientPkg = clientLibPkgs.get(i); 11213 killApplication(clientPkg.applicationInfo.packageName, 11214 clientPkg.applicationInfo.uid, "update lib"); 11215 } 11216 } 11217 11218 // writer 11219 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 11220 11221 synchronized (mPackages) { 11222 // We don't expect installation to fail beyond this point 11223 11224 // Add the new setting to mSettings 11225 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 11226 // Add the new setting to mPackages 11227 mPackages.put(pkg.applicationInfo.packageName, pkg); 11228 // Make sure we don't accidentally delete its data. 11229 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 11230 while (iter.hasNext()) { 11231 PackageCleanItem item = iter.next(); 11232 if (pkgName.equals(item.packageName)) { 11233 iter.remove(); 11234 } 11235 } 11236 11237 // Add the package's KeySets to the global KeySetManagerService 11238 KeySetManagerService ksms = mSettings.mKeySetManagerService; 11239 ksms.addScannedPackageLPw(pkg); 11240 11241 int N = pkg.providers.size(); 11242 StringBuilder r = null; 11243 int i; 11244 for (i=0; i<N; i++) { 11245 PackageParser.Provider p = pkg.providers.get(i); 11246 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11247 p.info.processName); 11248 mProviders.addProvider(p); 11249 p.syncable = p.info.isSyncable; 11250 if (p.info.authority != null) { 11251 String names[] = p.info.authority.split(";"); 11252 p.info.authority = null; 11253 for (int j = 0; j < names.length; j++) { 11254 if (j == 1 && p.syncable) { 11255 // We only want the first authority for a provider to possibly be 11256 // syncable, so if we already added this provider using a different 11257 // authority clear the syncable flag. We copy the provider before 11258 // changing it because the mProviders object contains a reference 11259 // to a provider that we don't want to change. 11260 // Only do this for the second authority since the resulting provider 11261 // object can be the same for all future authorities for this provider. 11262 p = new PackageParser.Provider(p); 11263 p.syncable = false; 11264 } 11265 if (!mProvidersByAuthority.containsKey(names[j])) { 11266 mProvidersByAuthority.put(names[j], p); 11267 if (p.info.authority == null) { 11268 p.info.authority = names[j]; 11269 } else { 11270 p.info.authority = p.info.authority + ";" + names[j]; 11271 } 11272 if (DEBUG_PACKAGE_SCANNING) { 11273 if (chatty) 11274 Log.d(TAG, "Registered content provider: " + names[j] 11275 + ", className = " + p.info.name + ", isSyncable = " 11276 + p.info.isSyncable); 11277 } 11278 } else { 11279 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11280 Slog.w(TAG, "Skipping provider name " + names[j] + 11281 " (in package " + pkg.applicationInfo.packageName + 11282 "): name already used by " 11283 + ((other != null && other.getComponentName() != null) 11284 ? other.getComponentName().getPackageName() : "?")); 11285 } 11286 } 11287 } 11288 if (chatty) { 11289 if (r == null) { 11290 r = new StringBuilder(256); 11291 } else { 11292 r.append(' '); 11293 } 11294 r.append(p.info.name); 11295 } 11296 } 11297 if (r != null) { 11298 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11299 } 11300 11301 N = pkg.services.size(); 11302 r = null; 11303 for (i=0; i<N; i++) { 11304 PackageParser.Service s = pkg.services.get(i); 11305 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11306 s.info.processName); 11307 mServices.addService(s); 11308 if (chatty) { 11309 if (r == null) { 11310 r = new StringBuilder(256); 11311 } else { 11312 r.append(' '); 11313 } 11314 r.append(s.info.name); 11315 } 11316 } 11317 if (r != null) { 11318 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11319 } 11320 11321 N = pkg.receivers.size(); 11322 r = null; 11323 for (i=0; i<N; i++) { 11324 PackageParser.Activity a = pkg.receivers.get(i); 11325 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11326 a.info.processName); 11327 mReceivers.addActivity(a, "receiver"); 11328 if (chatty) { 11329 if (r == null) { 11330 r = new StringBuilder(256); 11331 } else { 11332 r.append(' '); 11333 } 11334 r.append(a.info.name); 11335 } 11336 } 11337 if (r != null) { 11338 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11339 } 11340 11341 N = pkg.activities.size(); 11342 r = null; 11343 for (i=0; i<N; i++) { 11344 PackageParser.Activity a = pkg.activities.get(i); 11345 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11346 a.info.processName); 11347 mActivities.addActivity(a, "activity"); 11348 if (chatty) { 11349 if (r == null) { 11350 r = new StringBuilder(256); 11351 } else { 11352 r.append(' '); 11353 } 11354 r.append(a.info.name); 11355 } 11356 } 11357 if (r != null) { 11358 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11359 } 11360 11361 // Don't allow ephemeral applications to define new permissions groups. 11362 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11363 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11364 + " ignored: instant apps cannot define new permission groups."); 11365 } else { 11366 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11367 } 11368 11369 // Don't allow ephemeral applications to define new permissions. 11370 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11371 Slog.w(TAG, "Permissions from package " + pkg.packageName 11372 + " ignored: instant apps cannot define new permissions."); 11373 } else { 11374 mPermissionManager.addAllPermissions(pkg, chatty); 11375 } 11376 11377 N = pkg.instrumentation.size(); 11378 r = null; 11379 for (i=0; i<N; i++) { 11380 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11381 a.info.packageName = pkg.applicationInfo.packageName; 11382 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11383 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11384 a.info.splitNames = pkg.splitNames; 11385 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11386 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11387 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11388 a.info.dataDir = pkg.applicationInfo.dataDir; 11389 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11390 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11391 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11392 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11393 mInstrumentation.put(a.getComponentName(), a); 11394 if (chatty) { 11395 if (r == null) { 11396 r = new StringBuilder(256); 11397 } else { 11398 r.append(' '); 11399 } 11400 r.append(a.info.name); 11401 } 11402 } 11403 if (r != null) { 11404 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11405 } 11406 11407 if (pkg.protectedBroadcasts != null) { 11408 N = pkg.protectedBroadcasts.size(); 11409 synchronized (mProtectedBroadcasts) { 11410 for (i = 0; i < N; i++) { 11411 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11412 } 11413 } 11414 } 11415 } 11416 11417 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11418 } 11419 11420 /** 11421 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11422 * is derived purely on the basis of the contents of {@code scanFile} and 11423 * {@code cpuAbiOverride}. 11424 * 11425 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11426 */ 11427 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11428 boolean extractLibs) 11429 throws PackageManagerException { 11430 // Give ourselves some initial paths; we'll come back for another 11431 // pass once we've determined ABI below. 11432 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11433 11434 // We would never need to extract libs for forward-locked and external packages, 11435 // since the container service will do it for us. We shouldn't attempt to 11436 // extract libs from system app when it was not updated. 11437 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11438 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11439 extractLibs = false; 11440 } 11441 11442 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11443 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11444 11445 NativeLibraryHelper.Handle handle = null; 11446 try { 11447 handle = NativeLibraryHelper.Handle.create(pkg); 11448 // TODO(multiArch): This can be null for apps that didn't go through the 11449 // usual installation process. We can calculate it again, like we 11450 // do during install time. 11451 // 11452 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11453 // unnecessary. 11454 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11455 11456 // Null out the abis so that they can be recalculated. 11457 pkg.applicationInfo.primaryCpuAbi = null; 11458 pkg.applicationInfo.secondaryCpuAbi = null; 11459 if (isMultiArch(pkg.applicationInfo)) { 11460 // Warn if we've set an abiOverride for multi-lib packages.. 11461 // By definition, we need to copy both 32 and 64 bit libraries for 11462 // such packages. 11463 if (pkg.cpuAbiOverride != null 11464 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11465 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11466 } 11467 11468 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11469 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11470 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11471 if (extractLibs) { 11472 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11473 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11474 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11475 useIsaSpecificSubdirs); 11476 } else { 11477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11478 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11479 } 11480 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11481 } 11482 11483 // Shared library native code should be in the APK zip aligned 11484 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11485 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11486 "Shared library native lib extraction not supported"); 11487 } 11488 11489 maybeThrowExceptionForMultiArchCopy( 11490 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11491 11492 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11493 if (extractLibs) { 11494 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11495 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11496 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11497 useIsaSpecificSubdirs); 11498 } else { 11499 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11500 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11501 } 11502 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11503 } 11504 11505 maybeThrowExceptionForMultiArchCopy( 11506 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11507 11508 if (abi64 >= 0) { 11509 // Shared library native libs should be in the APK zip aligned 11510 if (extractLibs && pkg.isLibrary()) { 11511 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11512 "Shared library native lib extraction not supported"); 11513 } 11514 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11515 } 11516 11517 if (abi32 >= 0) { 11518 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11519 if (abi64 >= 0) { 11520 if (pkg.use32bitAbi) { 11521 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11522 pkg.applicationInfo.primaryCpuAbi = abi; 11523 } else { 11524 pkg.applicationInfo.secondaryCpuAbi = abi; 11525 } 11526 } else { 11527 pkg.applicationInfo.primaryCpuAbi = abi; 11528 } 11529 } 11530 } else { 11531 String[] abiList = (cpuAbiOverride != null) ? 11532 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11533 11534 // Enable gross and lame hacks for apps that are built with old 11535 // SDK tools. We must scan their APKs for renderscript bitcode and 11536 // not launch them if it's present. Don't bother checking on devices 11537 // that don't have 64 bit support. 11538 boolean needsRenderScriptOverride = false; 11539 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11540 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11541 abiList = Build.SUPPORTED_32_BIT_ABIS; 11542 needsRenderScriptOverride = true; 11543 } 11544 11545 final int copyRet; 11546 if (extractLibs) { 11547 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11548 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11549 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11550 } else { 11551 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11552 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11553 } 11554 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11555 11556 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11557 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11558 "Error unpackaging native libs for app, errorCode=" + copyRet); 11559 } 11560 11561 if (copyRet >= 0) { 11562 // Shared libraries that have native libs must be multi-architecture 11563 if (pkg.isLibrary()) { 11564 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11565 "Shared library with native libs must be multiarch"); 11566 } 11567 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11568 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11569 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11570 } else if (needsRenderScriptOverride) { 11571 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11572 } 11573 } 11574 } catch (IOException ioe) { 11575 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11576 } finally { 11577 IoUtils.closeQuietly(handle); 11578 } 11579 11580 // Now that we've calculated the ABIs and determined if it's an internal app, 11581 // we will go ahead and populate the nativeLibraryPath. 11582 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11583 } 11584 11585 /** 11586 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11587 * i.e, so that all packages can be run inside a single process if required. 11588 * 11589 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11590 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11591 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11592 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11593 * updating a package that belongs to a shared user. 11594 * 11595 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11596 * adds unnecessary complexity. 11597 */ 11598 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11599 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11600 List<String> changedAbiCodePath = null; 11601 String requiredInstructionSet = null; 11602 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11603 requiredInstructionSet = VMRuntime.getInstructionSet( 11604 scannedPackage.applicationInfo.primaryCpuAbi); 11605 } 11606 11607 PackageSetting requirer = null; 11608 for (PackageSetting ps : packagesForUser) { 11609 // If packagesForUser contains scannedPackage, we skip it. This will happen 11610 // when scannedPackage is an update of an existing package. Without this check, 11611 // we will never be able to change the ABI of any package belonging to a shared 11612 // user, even if it's compatible with other packages. 11613 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11614 if (ps.primaryCpuAbiString == null) { 11615 continue; 11616 } 11617 11618 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11619 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11620 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11621 // this but there's not much we can do. 11622 String errorMessage = "Instruction set mismatch, " 11623 + ((requirer == null) ? "[caller]" : requirer) 11624 + " requires " + requiredInstructionSet + " whereas " + ps 11625 + " requires " + instructionSet; 11626 Slog.w(TAG, errorMessage); 11627 } 11628 11629 if (requiredInstructionSet == null) { 11630 requiredInstructionSet = instructionSet; 11631 requirer = ps; 11632 } 11633 } 11634 } 11635 11636 if (requiredInstructionSet != null) { 11637 String adjustedAbi; 11638 if (requirer != null) { 11639 // requirer != null implies that either scannedPackage was null or that scannedPackage 11640 // did not require an ABI, in which case we have to adjust scannedPackage to match 11641 // the ABI of the set (which is the same as requirer's ABI) 11642 adjustedAbi = requirer.primaryCpuAbiString; 11643 if (scannedPackage != null) { 11644 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11645 } 11646 } else { 11647 // requirer == null implies that we're updating all ABIs in the set to 11648 // match scannedPackage. 11649 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11650 } 11651 11652 for (PackageSetting ps : packagesForUser) { 11653 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11654 if (ps.primaryCpuAbiString != null) { 11655 continue; 11656 } 11657 11658 ps.primaryCpuAbiString = adjustedAbi; 11659 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11660 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11661 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11662 if (DEBUG_ABI_SELECTION) { 11663 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11664 + " (requirer=" 11665 + (requirer != null ? requirer.pkg : "null") 11666 + ", scannedPackage=" 11667 + (scannedPackage != null ? scannedPackage : "null") 11668 + ")"); 11669 } 11670 if (changedAbiCodePath == null) { 11671 changedAbiCodePath = new ArrayList<>(); 11672 } 11673 changedAbiCodePath.add(ps.codePathString); 11674 } 11675 } 11676 } 11677 } 11678 return changedAbiCodePath; 11679 } 11680 11681 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11682 synchronized (mPackages) { 11683 mResolverReplaced = true; 11684 // Set up information for custom user intent resolution activity. 11685 mResolveActivity.applicationInfo = pkg.applicationInfo; 11686 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11687 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11688 mResolveActivity.processName = pkg.applicationInfo.packageName; 11689 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11690 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11691 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11692 mResolveActivity.theme = 0; 11693 mResolveActivity.exported = true; 11694 mResolveActivity.enabled = true; 11695 mResolveInfo.activityInfo = mResolveActivity; 11696 mResolveInfo.priority = 0; 11697 mResolveInfo.preferredOrder = 0; 11698 mResolveInfo.match = 0; 11699 mResolveComponentName = mCustomResolverComponentName; 11700 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11701 mResolveComponentName); 11702 } 11703 } 11704 11705 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11706 if (installerActivity == null) { 11707 if (DEBUG_EPHEMERAL) { 11708 Slog.d(TAG, "Clear ephemeral installer activity"); 11709 } 11710 mInstantAppInstallerActivity = null; 11711 return; 11712 } 11713 11714 if (DEBUG_EPHEMERAL) { 11715 Slog.d(TAG, "Set ephemeral installer activity: " 11716 + installerActivity.getComponentName()); 11717 } 11718 // Set up information for ephemeral installer activity 11719 mInstantAppInstallerActivity = installerActivity; 11720 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11721 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11722 mInstantAppInstallerActivity.exported = true; 11723 mInstantAppInstallerActivity.enabled = true; 11724 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11725 mInstantAppInstallerInfo.priority = 0; 11726 mInstantAppInstallerInfo.preferredOrder = 1; 11727 mInstantAppInstallerInfo.isDefault = true; 11728 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11729 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11730 } 11731 11732 private static String calculateBundledApkRoot(final String codePathString) { 11733 final File codePath = new File(codePathString); 11734 final File codeRoot; 11735 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11736 codeRoot = Environment.getRootDirectory(); 11737 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11738 codeRoot = Environment.getOemDirectory(); 11739 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11740 codeRoot = Environment.getVendorDirectory(); 11741 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 11742 codeRoot = Environment.getProductDirectory(); 11743 } else { 11744 // Unrecognized code path; take its top real segment as the apk root: 11745 // e.g. /something/app/blah.apk => /something 11746 try { 11747 File f = codePath.getCanonicalFile(); 11748 File parent = f.getParentFile(); // non-null because codePath is a file 11749 File tmp; 11750 while ((tmp = parent.getParentFile()) != null) { 11751 f = parent; 11752 parent = tmp; 11753 } 11754 codeRoot = f; 11755 Slog.w(TAG, "Unrecognized code path " 11756 + codePath + " - using " + codeRoot); 11757 } catch (IOException e) { 11758 // Can't canonicalize the code path -- shenanigans? 11759 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11760 return Environment.getRootDirectory().getPath(); 11761 } 11762 } 11763 return codeRoot.getPath(); 11764 } 11765 11766 /** 11767 * Derive and set the location of native libraries for the given package, 11768 * which varies depending on where and how the package was installed. 11769 */ 11770 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11771 final ApplicationInfo info = pkg.applicationInfo; 11772 final String codePath = pkg.codePath; 11773 final File codeFile = new File(codePath); 11774 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11775 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11776 11777 info.nativeLibraryRootDir = null; 11778 info.nativeLibraryRootRequiresIsa = false; 11779 info.nativeLibraryDir = null; 11780 info.secondaryNativeLibraryDir = null; 11781 11782 if (isApkFile(codeFile)) { 11783 // Monolithic install 11784 if (bundledApp) { 11785 // If "/system/lib64/apkname" exists, assume that is the per-package 11786 // native library directory to use; otherwise use "/system/lib/apkname". 11787 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11788 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11789 getPrimaryInstructionSet(info)); 11790 11791 // This is a bundled system app so choose the path based on the ABI. 11792 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11793 // is just the default path. 11794 final String apkName = deriveCodePathName(codePath); 11795 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11796 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11797 apkName).getAbsolutePath(); 11798 11799 if (info.secondaryCpuAbi != null) { 11800 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11801 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11802 secondaryLibDir, apkName).getAbsolutePath(); 11803 } 11804 } else if (asecApp) { 11805 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11806 .getAbsolutePath(); 11807 } else { 11808 final String apkName = deriveCodePathName(codePath); 11809 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11810 .getAbsolutePath(); 11811 } 11812 11813 info.nativeLibraryRootRequiresIsa = false; 11814 info.nativeLibraryDir = info.nativeLibraryRootDir; 11815 } else { 11816 // Cluster install 11817 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11818 info.nativeLibraryRootRequiresIsa = true; 11819 11820 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11821 getPrimaryInstructionSet(info)).getAbsolutePath(); 11822 11823 if (info.secondaryCpuAbi != null) { 11824 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11825 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11826 } 11827 } 11828 } 11829 11830 /** 11831 * Calculate the abis and roots for a bundled app. These can uniquely 11832 * be determined from the contents of the system partition, i.e whether 11833 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11834 * of this information, and instead assume that the system was built 11835 * sensibly. 11836 */ 11837 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11838 PackageSetting pkgSetting) { 11839 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11840 11841 // If "/system/lib64/apkname" exists, assume that is the per-package 11842 // native library directory to use; otherwise use "/system/lib/apkname". 11843 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11844 setBundledAppAbi(pkg, apkRoot, apkName); 11845 // pkgSetting might be null during rescan following uninstall of updates 11846 // to a bundled app, so accommodate that possibility. The settings in 11847 // that case will be established later from the parsed package. 11848 // 11849 // If the settings aren't null, sync them up with what we've just derived. 11850 // note that apkRoot isn't stored in the package settings. 11851 if (pkgSetting != null) { 11852 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11853 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11854 } 11855 } 11856 11857 /** 11858 * Deduces the ABI of a bundled app and sets the relevant fields on the 11859 * parsed pkg object. 11860 * 11861 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11862 * under which system libraries are installed. 11863 * @param apkName the name of the installed package. 11864 */ 11865 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11866 final File codeFile = new File(pkg.codePath); 11867 11868 final boolean has64BitLibs; 11869 final boolean has32BitLibs; 11870 if (isApkFile(codeFile)) { 11871 // Monolithic install 11872 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11873 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11874 } else { 11875 // Cluster install 11876 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11877 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11878 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11879 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11880 has64BitLibs = (new File(rootDir, isa)).exists(); 11881 } else { 11882 has64BitLibs = false; 11883 } 11884 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11885 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11886 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11887 has32BitLibs = (new File(rootDir, isa)).exists(); 11888 } else { 11889 has32BitLibs = false; 11890 } 11891 } 11892 11893 if (has64BitLibs && !has32BitLibs) { 11894 // The package has 64 bit libs, but not 32 bit libs. Its primary 11895 // ABI should be 64 bit. We can safely assume here that the bundled 11896 // native libraries correspond to the most preferred ABI in the list. 11897 11898 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11899 pkg.applicationInfo.secondaryCpuAbi = null; 11900 } else if (has32BitLibs && !has64BitLibs) { 11901 // The package has 32 bit libs but not 64 bit libs. Its primary 11902 // ABI should be 32 bit. 11903 11904 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11905 pkg.applicationInfo.secondaryCpuAbi = null; 11906 } else if (has32BitLibs && has64BitLibs) { 11907 // The application has both 64 and 32 bit bundled libraries. We check 11908 // here that the app declares multiArch support, and warn if it doesn't. 11909 // 11910 // We will be lenient here and record both ABIs. The primary will be the 11911 // ABI that's higher on the list, i.e, a device that's configured to prefer 11912 // 64 bit apps will see a 64 bit primary ABI, 11913 11914 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11915 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11916 } 11917 11918 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11919 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11920 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11921 } else { 11922 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11923 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11924 } 11925 } else { 11926 pkg.applicationInfo.primaryCpuAbi = null; 11927 pkg.applicationInfo.secondaryCpuAbi = null; 11928 } 11929 } 11930 11931 private void killApplication(String pkgName, int appId, String reason) { 11932 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11933 } 11934 11935 private void killApplication(String pkgName, int appId, int userId, String reason) { 11936 // Request the ActivityManager to kill the process(only for existing packages) 11937 // so that we do not end up in a confused state while the user is still using the older 11938 // version of the application while the new one gets installed. 11939 final long token = Binder.clearCallingIdentity(); 11940 try { 11941 IActivityManager am = ActivityManager.getService(); 11942 if (am != null) { 11943 try { 11944 am.killApplication(pkgName, appId, userId, reason); 11945 } catch (RemoteException e) { 11946 } 11947 } 11948 } finally { 11949 Binder.restoreCallingIdentity(token); 11950 } 11951 } 11952 11953 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11954 // Remove the parent package setting 11955 PackageSetting ps = (PackageSetting) pkg.mExtras; 11956 if (ps != null) { 11957 removePackageLI(ps, chatty); 11958 } 11959 // Remove the child package setting 11960 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11961 for (int i = 0; i < childCount; i++) { 11962 PackageParser.Package childPkg = pkg.childPackages.get(i); 11963 ps = (PackageSetting) childPkg.mExtras; 11964 if (ps != null) { 11965 removePackageLI(ps, chatty); 11966 } 11967 } 11968 } 11969 11970 void removePackageLI(PackageSetting ps, boolean chatty) { 11971 if (DEBUG_INSTALL) { 11972 if (chatty) 11973 Log.d(TAG, "Removing package " + ps.name); 11974 } 11975 11976 // writer 11977 synchronized (mPackages) { 11978 mPackages.remove(ps.name); 11979 final PackageParser.Package pkg = ps.pkg; 11980 if (pkg != null) { 11981 cleanPackageDataStructuresLILPw(pkg, chatty); 11982 } 11983 } 11984 } 11985 11986 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11987 if (DEBUG_INSTALL) { 11988 if (chatty) 11989 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11990 } 11991 11992 // writer 11993 synchronized (mPackages) { 11994 // Remove the parent package 11995 mPackages.remove(pkg.applicationInfo.packageName); 11996 cleanPackageDataStructuresLILPw(pkg, chatty); 11997 11998 // Remove the child packages 11999 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12000 for (int i = 0; i < childCount; i++) { 12001 PackageParser.Package childPkg = pkg.childPackages.get(i); 12002 mPackages.remove(childPkg.applicationInfo.packageName); 12003 cleanPackageDataStructuresLILPw(childPkg, chatty); 12004 } 12005 } 12006 } 12007 12008 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12009 int N = pkg.providers.size(); 12010 StringBuilder r = null; 12011 int i; 12012 for (i=0; i<N; i++) { 12013 PackageParser.Provider p = pkg.providers.get(i); 12014 mProviders.removeProvider(p); 12015 if (p.info.authority == null) { 12016 12017 /* There was another ContentProvider with this authority when 12018 * this app was installed so this authority is null, 12019 * Ignore it as we don't have to unregister the provider. 12020 */ 12021 continue; 12022 } 12023 String names[] = p.info.authority.split(";"); 12024 for (int j = 0; j < names.length; j++) { 12025 if (mProvidersByAuthority.get(names[j]) == p) { 12026 mProvidersByAuthority.remove(names[j]); 12027 if (DEBUG_REMOVE) { 12028 if (chatty) 12029 Log.d(TAG, "Unregistered content provider: " + names[j] 12030 + ", className = " + p.info.name + ", isSyncable = " 12031 + p.info.isSyncable); 12032 } 12033 } 12034 } 12035 if (DEBUG_REMOVE && chatty) { 12036 if (r == null) { 12037 r = new StringBuilder(256); 12038 } else { 12039 r.append(' '); 12040 } 12041 r.append(p.info.name); 12042 } 12043 } 12044 if (r != null) { 12045 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 12046 } 12047 12048 N = pkg.services.size(); 12049 r = null; 12050 for (i=0; i<N; i++) { 12051 PackageParser.Service s = pkg.services.get(i); 12052 mServices.removeService(s); 12053 if (chatty) { 12054 if (r == null) { 12055 r = new StringBuilder(256); 12056 } else { 12057 r.append(' '); 12058 } 12059 r.append(s.info.name); 12060 } 12061 } 12062 if (r != null) { 12063 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 12064 } 12065 12066 N = pkg.receivers.size(); 12067 r = null; 12068 for (i=0; i<N; i++) { 12069 PackageParser.Activity a = pkg.receivers.get(i); 12070 mReceivers.removeActivity(a, "receiver"); 12071 if (DEBUG_REMOVE && chatty) { 12072 if (r == null) { 12073 r = new StringBuilder(256); 12074 } else { 12075 r.append(' '); 12076 } 12077 r.append(a.info.name); 12078 } 12079 } 12080 if (r != null) { 12081 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 12082 } 12083 12084 N = pkg.activities.size(); 12085 r = null; 12086 for (i=0; i<N; i++) { 12087 PackageParser.Activity a = pkg.activities.get(i); 12088 mActivities.removeActivity(a, "activity"); 12089 if (DEBUG_REMOVE && chatty) { 12090 if (r == null) { 12091 r = new StringBuilder(256); 12092 } else { 12093 r.append(' '); 12094 } 12095 r.append(a.info.name); 12096 } 12097 } 12098 if (r != null) { 12099 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 12100 } 12101 12102 mPermissionManager.removeAllPermissions(pkg, chatty); 12103 12104 N = pkg.instrumentation.size(); 12105 r = null; 12106 for (i=0; i<N; i++) { 12107 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12108 mInstrumentation.remove(a.getComponentName()); 12109 if (DEBUG_REMOVE && chatty) { 12110 if (r == null) { 12111 r = new StringBuilder(256); 12112 } else { 12113 r.append(' '); 12114 } 12115 r.append(a.info.name); 12116 } 12117 } 12118 if (r != null) { 12119 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12120 } 12121 12122 r = null; 12123 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12124 // Only system apps can hold shared libraries. 12125 if (pkg.libraryNames != null) { 12126 for (i = 0; i < pkg.libraryNames.size(); i++) { 12127 String name = pkg.libraryNames.get(i); 12128 if (removeSharedLibraryLPw(name, 0)) { 12129 if (DEBUG_REMOVE && chatty) { 12130 if (r == null) { 12131 r = new StringBuilder(256); 12132 } else { 12133 r.append(' '); 12134 } 12135 r.append(name); 12136 } 12137 } 12138 } 12139 } 12140 } 12141 12142 r = null; 12143 12144 // Any package can hold static shared libraries. 12145 if (pkg.staticSharedLibName != null) { 12146 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12147 if (DEBUG_REMOVE && chatty) { 12148 if (r == null) { 12149 r = new StringBuilder(256); 12150 } else { 12151 r.append(' '); 12152 } 12153 r.append(pkg.staticSharedLibName); 12154 } 12155 } 12156 } 12157 12158 if (r != null) { 12159 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12160 } 12161 } 12162 12163 12164 final class ActivityIntentResolver 12165 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 12166 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12167 boolean defaultOnly, int userId) { 12168 if (!sUserManager.exists(userId)) return null; 12169 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 12170 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12171 } 12172 12173 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12174 int userId) { 12175 if (!sUserManager.exists(userId)) return null; 12176 mFlags = flags; 12177 return super.queryIntent(intent, resolvedType, 12178 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12179 userId); 12180 } 12181 12182 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12183 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 12184 if (!sUserManager.exists(userId)) return null; 12185 if (packageActivities == null) { 12186 return null; 12187 } 12188 mFlags = flags; 12189 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12190 final int N = packageActivities.size(); 12191 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 12192 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 12193 12194 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 12195 for (int i = 0; i < N; ++i) { 12196 intentFilters = packageActivities.get(i).intents; 12197 if (intentFilters != null && intentFilters.size() > 0) { 12198 PackageParser.ActivityIntentInfo[] array = 12199 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 12200 intentFilters.toArray(array); 12201 listCut.add(array); 12202 } 12203 } 12204 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12205 } 12206 12207 /** 12208 * Finds a privileged activity that matches the specified activity names. 12209 */ 12210 private PackageParser.Activity findMatchingActivity( 12211 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 12212 for (PackageParser.Activity sysActivity : activityList) { 12213 if (sysActivity.info.name.equals(activityInfo.name)) { 12214 return sysActivity; 12215 } 12216 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 12217 return sysActivity; 12218 } 12219 if (sysActivity.info.targetActivity != null) { 12220 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 12221 return sysActivity; 12222 } 12223 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 12224 return sysActivity; 12225 } 12226 } 12227 } 12228 return null; 12229 } 12230 12231 public class IterGenerator<E> { 12232 public Iterator<E> generate(ActivityIntentInfo info) { 12233 return null; 12234 } 12235 } 12236 12237 public class ActionIterGenerator extends IterGenerator<String> { 12238 @Override 12239 public Iterator<String> generate(ActivityIntentInfo info) { 12240 return info.actionsIterator(); 12241 } 12242 } 12243 12244 public class CategoriesIterGenerator extends IterGenerator<String> { 12245 @Override 12246 public Iterator<String> generate(ActivityIntentInfo info) { 12247 return info.categoriesIterator(); 12248 } 12249 } 12250 12251 public class SchemesIterGenerator extends IterGenerator<String> { 12252 @Override 12253 public Iterator<String> generate(ActivityIntentInfo info) { 12254 return info.schemesIterator(); 12255 } 12256 } 12257 12258 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12259 @Override 12260 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12261 return info.authoritiesIterator(); 12262 } 12263 } 12264 12265 /** 12266 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12267 * MODIFIED. Do not pass in a list that should not be changed. 12268 */ 12269 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12270 IterGenerator<T> generator, Iterator<T> searchIterator) { 12271 // loop through the set of actions; every one must be found in the intent filter 12272 while (searchIterator.hasNext()) { 12273 // we must have at least one filter in the list to consider a match 12274 if (intentList.size() == 0) { 12275 break; 12276 } 12277 12278 final T searchAction = searchIterator.next(); 12279 12280 // loop through the set of intent filters 12281 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12282 while (intentIter.hasNext()) { 12283 final ActivityIntentInfo intentInfo = intentIter.next(); 12284 boolean selectionFound = false; 12285 12286 // loop through the intent filter's selection criteria; at least one 12287 // of them must match the searched criteria 12288 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12289 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12290 final T intentSelection = intentSelectionIter.next(); 12291 if (intentSelection != null && intentSelection.equals(searchAction)) { 12292 selectionFound = true; 12293 break; 12294 } 12295 } 12296 12297 // the selection criteria wasn't found in this filter's set; this filter 12298 // is not a potential match 12299 if (!selectionFound) { 12300 intentIter.remove(); 12301 } 12302 } 12303 } 12304 } 12305 12306 private boolean isProtectedAction(ActivityIntentInfo filter) { 12307 final Iterator<String> actionsIter = filter.actionsIterator(); 12308 while (actionsIter != null && actionsIter.hasNext()) { 12309 final String filterAction = actionsIter.next(); 12310 if (PROTECTED_ACTIONS.contains(filterAction)) { 12311 return true; 12312 } 12313 } 12314 return false; 12315 } 12316 12317 /** 12318 * Adjusts the priority of the given intent filter according to policy. 12319 * <p> 12320 * <ul> 12321 * <li>The priority for non privileged applications is capped to '0'</li> 12322 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12323 * <li>The priority for unbundled updates to privileged applications is capped to the 12324 * priority defined on the system partition</li> 12325 * </ul> 12326 * <p> 12327 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12328 * allowed to obtain any priority on any action. 12329 */ 12330 private void adjustPriority( 12331 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12332 // nothing to do; priority is fine as-is 12333 if (intent.getPriority() <= 0) { 12334 return; 12335 } 12336 12337 final ActivityInfo activityInfo = intent.activity.info; 12338 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12339 12340 final boolean privilegedApp = 12341 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12342 if (!privilegedApp) { 12343 // non-privileged applications can never define a priority >0 12344 if (DEBUG_FILTERS) { 12345 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12346 + " package: " + applicationInfo.packageName 12347 + " activity: " + intent.activity.className 12348 + " origPrio: " + intent.getPriority()); 12349 } 12350 intent.setPriority(0); 12351 return; 12352 } 12353 12354 if (systemActivities == null) { 12355 // the system package is not disabled; we're parsing the system partition 12356 if (isProtectedAction(intent)) { 12357 if (mDeferProtectedFilters) { 12358 // We can't deal with these just yet. No component should ever obtain a 12359 // >0 priority for a protected actions, with ONE exception -- the setup 12360 // wizard. The setup wizard, however, cannot be known until we're able to 12361 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12362 // until all intent filters have been processed. Chicken, meet egg. 12363 // Let the filter temporarily have a high priority and rectify the 12364 // priorities after all system packages have been scanned. 12365 mProtectedFilters.add(intent); 12366 if (DEBUG_FILTERS) { 12367 Slog.i(TAG, "Protected action; save for later;" 12368 + " package: " + applicationInfo.packageName 12369 + " activity: " + intent.activity.className 12370 + " origPrio: " + intent.getPriority()); 12371 } 12372 return; 12373 } else { 12374 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12375 Slog.i(TAG, "No setup wizard;" 12376 + " All protected intents capped to priority 0"); 12377 } 12378 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12379 if (DEBUG_FILTERS) { 12380 Slog.i(TAG, "Found setup wizard;" 12381 + " allow priority " + intent.getPriority() + ";" 12382 + " package: " + intent.activity.info.packageName 12383 + " activity: " + intent.activity.className 12384 + " priority: " + intent.getPriority()); 12385 } 12386 // setup wizard gets whatever it wants 12387 return; 12388 } 12389 if (DEBUG_FILTERS) { 12390 Slog.i(TAG, "Protected action; cap priority to 0;" 12391 + " package: " + intent.activity.info.packageName 12392 + " activity: " + intent.activity.className 12393 + " origPrio: " + intent.getPriority()); 12394 } 12395 intent.setPriority(0); 12396 return; 12397 } 12398 } 12399 // privileged apps on the system image get whatever priority they request 12400 return; 12401 } 12402 12403 // privileged app unbundled update ... try to find the same activity 12404 final PackageParser.Activity foundActivity = 12405 findMatchingActivity(systemActivities, activityInfo); 12406 if (foundActivity == null) { 12407 // this is a new activity; it cannot obtain >0 priority 12408 if (DEBUG_FILTERS) { 12409 Slog.i(TAG, "New activity; cap priority to 0;" 12410 + " package: " + applicationInfo.packageName 12411 + " activity: " + intent.activity.className 12412 + " origPrio: " + intent.getPriority()); 12413 } 12414 intent.setPriority(0); 12415 return; 12416 } 12417 12418 // found activity, now check for filter equivalence 12419 12420 // a shallow copy is enough; we modify the list, not its contents 12421 final List<ActivityIntentInfo> intentListCopy = 12422 new ArrayList<>(foundActivity.intents); 12423 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12424 12425 // find matching action subsets 12426 final Iterator<String> actionsIterator = intent.actionsIterator(); 12427 if (actionsIterator != null) { 12428 getIntentListSubset( 12429 intentListCopy, new ActionIterGenerator(), actionsIterator); 12430 if (intentListCopy.size() == 0) { 12431 // no more intents to match; we're not equivalent 12432 if (DEBUG_FILTERS) { 12433 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12434 + " package: " + applicationInfo.packageName 12435 + " activity: " + intent.activity.className 12436 + " origPrio: " + intent.getPriority()); 12437 } 12438 intent.setPriority(0); 12439 return; 12440 } 12441 } 12442 12443 // find matching category subsets 12444 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12445 if (categoriesIterator != null) { 12446 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12447 categoriesIterator); 12448 if (intentListCopy.size() == 0) { 12449 // no more intents to match; we're not equivalent 12450 if (DEBUG_FILTERS) { 12451 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12452 + " package: " + applicationInfo.packageName 12453 + " activity: " + intent.activity.className 12454 + " origPrio: " + intent.getPriority()); 12455 } 12456 intent.setPriority(0); 12457 return; 12458 } 12459 } 12460 12461 // find matching schemes subsets 12462 final Iterator<String> schemesIterator = intent.schemesIterator(); 12463 if (schemesIterator != null) { 12464 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12465 schemesIterator); 12466 if (intentListCopy.size() == 0) { 12467 // no more intents to match; we're not equivalent 12468 if (DEBUG_FILTERS) { 12469 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12470 + " package: " + applicationInfo.packageName 12471 + " activity: " + intent.activity.className 12472 + " origPrio: " + intent.getPriority()); 12473 } 12474 intent.setPriority(0); 12475 return; 12476 } 12477 } 12478 12479 // find matching authorities subsets 12480 final Iterator<IntentFilter.AuthorityEntry> 12481 authoritiesIterator = intent.authoritiesIterator(); 12482 if (authoritiesIterator != null) { 12483 getIntentListSubset(intentListCopy, 12484 new AuthoritiesIterGenerator(), 12485 authoritiesIterator); 12486 if (intentListCopy.size() == 0) { 12487 // no more intents to match; we're not equivalent 12488 if (DEBUG_FILTERS) { 12489 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12490 + " package: " + applicationInfo.packageName 12491 + " activity: " + intent.activity.className 12492 + " origPrio: " + intent.getPriority()); 12493 } 12494 intent.setPriority(0); 12495 return; 12496 } 12497 } 12498 12499 // we found matching filter(s); app gets the max priority of all intents 12500 int cappedPriority = 0; 12501 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12502 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12503 } 12504 if (intent.getPriority() > cappedPriority) { 12505 if (DEBUG_FILTERS) { 12506 Slog.i(TAG, "Found matching filter(s);" 12507 + " cap priority to " + cappedPriority + ";" 12508 + " package: " + applicationInfo.packageName 12509 + " activity: " + intent.activity.className 12510 + " origPrio: " + intent.getPriority()); 12511 } 12512 intent.setPriority(cappedPriority); 12513 return; 12514 } 12515 // all this for nothing; the requested priority was <= what was on the system 12516 } 12517 12518 public final void addActivity(PackageParser.Activity a, String type) { 12519 mActivities.put(a.getComponentName(), a); 12520 if (DEBUG_SHOW_INFO) 12521 Log.v( 12522 TAG, " " + type + " " + 12523 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12524 if (DEBUG_SHOW_INFO) 12525 Log.v(TAG, " Class=" + a.info.name); 12526 final int NI = a.intents.size(); 12527 for (int j=0; j<NI; j++) { 12528 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12529 if ("activity".equals(type)) { 12530 final PackageSetting ps = 12531 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12532 final List<PackageParser.Activity> systemActivities = 12533 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12534 adjustPriority(systemActivities, intent); 12535 } 12536 if (DEBUG_SHOW_INFO) { 12537 Log.v(TAG, " IntentFilter:"); 12538 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12539 } 12540 if (!intent.debugCheck()) { 12541 Log.w(TAG, "==> For Activity " + a.info.name); 12542 } 12543 addFilter(intent); 12544 } 12545 } 12546 12547 public final void removeActivity(PackageParser.Activity a, String type) { 12548 mActivities.remove(a.getComponentName()); 12549 if (DEBUG_SHOW_INFO) { 12550 Log.v(TAG, " " + type + " " 12551 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12552 : a.info.name) + ":"); 12553 Log.v(TAG, " Class=" + a.info.name); 12554 } 12555 final int NI = a.intents.size(); 12556 for (int j=0; j<NI; j++) { 12557 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12558 if (DEBUG_SHOW_INFO) { 12559 Log.v(TAG, " IntentFilter:"); 12560 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12561 } 12562 removeFilter(intent); 12563 } 12564 } 12565 12566 @Override 12567 protected boolean allowFilterResult( 12568 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12569 ActivityInfo filterAi = filter.activity.info; 12570 for (int i=dest.size()-1; i>=0; i--) { 12571 ActivityInfo destAi = dest.get(i).activityInfo; 12572 if (destAi.name == filterAi.name 12573 && destAi.packageName == filterAi.packageName) { 12574 return false; 12575 } 12576 } 12577 return true; 12578 } 12579 12580 @Override 12581 protected ActivityIntentInfo[] newArray(int size) { 12582 return new ActivityIntentInfo[size]; 12583 } 12584 12585 @Override 12586 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12587 if (!sUserManager.exists(userId)) return true; 12588 PackageParser.Package p = filter.activity.owner; 12589 if (p != null) { 12590 PackageSetting ps = (PackageSetting)p.mExtras; 12591 if (ps != null) { 12592 // System apps are never considered stopped for purposes of 12593 // filtering, because there may be no way for the user to 12594 // actually re-launch them. 12595 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12596 && ps.getStopped(userId); 12597 } 12598 } 12599 return false; 12600 } 12601 12602 @Override 12603 protected boolean isPackageForFilter(String packageName, 12604 PackageParser.ActivityIntentInfo info) { 12605 return packageName.equals(info.activity.owner.packageName); 12606 } 12607 12608 @Override 12609 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12610 int match, int userId) { 12611 if (!sUserManager.exists(userId)) return null; 12612 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12613 return null; 12614 } 12615 final PackageParser.Activity activity = info.activity; 12616 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12617 if (ps == null) { 12618 return null; 12619 } 12620 final PackageUserState userState = ps.readUserState(userId); 12621 ActivityInfo ai = 12622 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12623 if (ai == null) { 12624 return null; 12625 } 12626 final boolean matchExplicitlyVisibleOnly = 12627 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12628 final boolean matchVisibleToInstantApp = 12629 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12630 final boolean componentVisible = 12631 matchVisibleToInstantApp 12632 && info.isVisibleToInstantApp() 12633 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12634 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12635 // throw out filters that aren't visible to ephemeral apps 12636 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12637 return null; 12638 } 12639 // throw out instant app filters if we're not explicitly requesting them 12640 if (!matchInstantApp && userState.instantApp) { 12641 return null; 12642 } 12643 // throw out instant app filters if updates are available; will trigger 12644 // instant app resolution 12645 if (userState.instantApp && ps.isUpdateAvailable()) { 12646 return null; 12647 } 12648 final ResolveInfo res = new ResolveInfo(); 12649 res.activityInfo = ai; 12650 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12651 res.filter = info; 12652 } 12653 if (info != null) { 12654 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12655 } 12656 res.priority = info.getPriority(); 12657 res.preferredOrder = activity.owner.mPreferredOrder; 12658 //System.out.println("Result: " + res.activityInfo.className + 12659 // " = " + res.priority); 12660 res.match = match; 12661 res.isDefault = info.hasDefault; 12662 res.labelRes = info.labelRes; 12663 res.nonLocalizedLabel = info.nonLocalizedLabel; 12664 if (userNeedsBadging(userId)) { 12665 res.noResourceId = true; 12666 } else { 12667 res.icon = info.icon; 12668 } 12669 res.iconResourceId = info.icon; 12670 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12671 res.isInstantAppAvailable = userState.instantApp; 12672 return res; 12673 } 12674 12675 @Override 12676 protected void sortResults(List<ResolveInfo> results) { 12677 Collections.sort(results, mResolvePrioritySorter); 12678 } 12679 12680 @Override 12681 protected void dumpFilter(PrintWriter out, String prefix, 12682 PackageParser.ActivityIntentInfo filter) { 12683 out.print(prefix); out.print( 12684 Integer.toHexString(System.identityHashCode(filter.activity))); 12685 out.print(' '); 12686 filter.activity.printComponentShortName(out); 12687 out.print(" filter "); 12688 out.println(Integer.toHexString(System.identityHashCode(filter))); 12689 } 12690 12691 @Override 12692 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12693 return filter.activity; 12694 } 12695 12696 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12697 PackageParser.Activity activity = (PackageParser.Activity)label; 12698 out.print(prefix); out.print( 12699 Integer.toHexString(System.identityHashCode(activity))); 12700 out.print(' '); 12701 activity.printComponentShortName(out); 12702 if (count > 1) { 12703 out.print(" ("); out.print(count); out.print(" filters)"); 12704 } 12705 out.println(); 12706 } 12707 12708 // Keys are String (activity class name), values are Activity. 12709 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12710 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12711 private int mFlags; 12712 } 12713 12714 private final class ServiceIntentResolver 12715 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12716 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12717 boolean defaultOnly, int userId) { 12718 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12719 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12720 } 12721 12722 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12723 int userId) { 12724 if (!sUserManager.exists(userId)) return null; 12725 mFlags = flags; 12726 return super.queryIntent(intent, resolvedType, 12727 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12728 userId); 12729 } 12730 12731 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12732 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12733 if (!sUserManager.exists(userId)) return null; 12734 if (packageServices == null) { 12735 return null; 12736 } 12737 mFlags = flags; 12738 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12739 final int N = packageServices.size(); 12740 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12741 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12742 12743 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12744 for (int i = 0; i < N; ++i) { 12745 intentFilters = packageServices.get(i).intents; 12746 if (intentFilters != null && intentFilters.size() > 0) { 12747 PackageParser.ServiceIntentInfo[] array = 12748 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12749 intentFilters.toArray(array); 12750 listCut.add(array); 12751 } 12752 } 12753 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12754 } 12755 12756 public final void addService(PackageParser.Service s) { 12757 mServices.put(s.getComponentName(), s); 12758 if (DEBUG_SHOW_INFO) { 12759 Log.v(TAG, " " 12760 + (s.info.nonLocalizedLabel != null 12761 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12762 Log.v(TAG, " Class=" + s.info.name); 12763 } 12764 final int NI = s.intents.size(); 12765 int j; 12766 for (j=0; j<NI; j++) { 12767 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12768 if (DEBUG_SHOW_INFO) { 12769 Log.v(TAG, " IntentFilter:"); 12770 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12771 } 12772 if (!intent.debugCheck()) { 12773 Log.w(TAG, "==> For Service " + s.info.name); 12774 } 12775 addFilter(intent); 12776 } 12777 } 12778 12779 public final void removeService(PackageParser.Service s) { 12780 mServices.remove(s.getComponentName()); 12781 if (DEBUG_SHOW_INFO) { 12782 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12783 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12784 Log.v(TAG, " Class=" + s.info.name); 12785 } 12786 final int NI = s.intents.size(); 12787 int j; 12788 for (j=0; j<NI; j++) { 12789 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12790 if (DEBUG_SHOW_INFO) { 12791 Log.v(TAG, " IntentFilter:"); 12792 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12793 } 12794 removeFilter(intent); 12795 } 12796 } 12797 12798 @Override 12799 protected boolean allowFilterResult( 12800 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12801 ServiceInfo filterSi = filter.service.info; 12802 for (int i=dest.size()-1; i>=0; i--) { 12803 ServiceInfo destAi = dest.get(i).serviceInfo; 12804 if (destAi.name == filterSi.name 12805 && destAi.packageName == filterSi.packageName) { 12806 return false; 12807 } 12808 } 12809 return true; 12810 } 12811 12812 @Override 12813 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12814 return new PackageParser.ServiceIntentInfo[size]; 12815 } 12816 12817 @Override 12818 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12819 if (!sUserManager.exists(userId)) return true; 12820 PackageParser.Package p = filter.service.owner; 12821 if (p != null) { 12822 PackageSetting ps = (PackageSetting)p.mExtras; 12823 if (ps != null) { 12824 // System apps are never considered stopped for purposes of 12825 // filtering, because there may be no way for the user to 12826 // actually re-launch them. 12827 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12828 && ps.getStopped(userId); 12829 } 12830 } 12831 return false; 12832 } 12833 12834 @Override 12835 protected boolean isPackageForFilter(String packageName, 12836 PackageParser.ServiceIntentInfo info) { 12837 return packageName.equals(info.service.owner.packageName); 12838 } 12839 12840 @Override 12841 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12842 int match, int userId) { 12843 if (!sUserManager.exists(userId)) return null; 12844 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12845 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12846 return null; 12847 } 12848 final PackageParser.Service service = info.service; 12849 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12850 if (ps == null) { 12851 return null; 12852 } 12853 final PackageUserState userState = ps.readUserState(userId); 12854 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12855 userState, userId); 12856 if (si == null) { 12857 return null; 12858 } 12859 final boolean matchVisibleToInstantApp = 12860 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12861 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12862 // throw out filters that aren't visible to ephemeral apps 12863 if (matchVisibleToInstantApp 12864 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12865 return null; 12866 } 12867 // throw out ephemeral filters if we're not explicitly requesting them 12868 if (!isInstantApp && userState.instantApp) { 12869 return null; 12870 } 12871 // throw out instant app filters if updates are available; will trigger 12872 // instant app resolution 12873 if (userState.instantApp && ps.isUpdateAvailable()) { 12874 return null; 12875 } 12876 final ResolveInfo res = new ResolveInfo(); 12877 res.serviceInfo = si; 12878 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12879 res.filter = filter; 12880 } 12881 res.priority = info.getPriority(); 12882 res.preferredOrder = service.owner.mPreferredOrder; 12883 res.match = match; 12884 res.isDefault = info.hasDefault; 12885 res.labelRes = info.labelRes; 12886 res.nonLocalizedLabel = info.nonLocalizedLabel; 12887 res.icon = info.icon; 12888 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12889 return res; 12890 } 12891 12892 @Override 12893 protected void sortResults(List<ResolveInfo> results) { 12894 Collections.sort(results, mResolvePrioritySorter); 12895 } 12896 12897 @Override 12898 protected void dumpFilter(PrintWriter out, String prefix, 12899 PackageParser.ServiceIntentInfo filter) { 12900 out.print(prefix); out.print( 12901 Integer.toHexString(System.identityHashCode(filter.service))); 12902 out.print(' '); 12903 filter.service.printComponentShortName(out); 12904 out.print(" filter "); 12905 out.print(Integer.toHexString(System.identityHashCode(filter))); 12906 if (filter.service.info.permission != null) { 12907 out.print(" permission "); out.println(filter.service.info.permission); 12908 } else { 12909 out.println(); 12910 } 12911 } 12912 12913 @Override 12914 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12915 return filter.service; 12916 } 12917 12918 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12919 PackageParser.Service service = (PackageParser.Service)label; 12920 out.print(prefix); out.print( 12921 Integer.toHexString(System.identityHashCode(service))); 12922 out.print(' '); 12923 service.printComponentShortName(out); 12924 if (count > 1) { 12925 out.print(" ("); out.print(count); out.print(" filters)"); 12926 } 12927 out.println(); 12928 } 12929 12930// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12931// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12932// final List<ResolveInfo> retList = Lists.newArrayList(); 12933// while (i.hasNext()) { 12934// final ResolveInfo resolveInfo = (ResolveInfo) i; 12935// if (isEnabledLP(resolveInfo.serviceInfo)) { 12936// retList.add(resolveInfo); 12937// } 12938// } 12939// return retList; 12940// } 12941 12942 // Keys are String (activity class name), values are Activity. 12943 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12944 = new ArrayMap<ComponentName, PackageParser.Service>(); 12945 private int mFlags; 12946 } 12947 12948 private final class ProviderIntentResolver 12949 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12950 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12951 boolean defaultOnly, int userId) { 12952 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12953 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12954 } 12955 12956 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12957 int userId) { 12958 if (!sUserManager.exists(userId)) 12959 return null; 12960 mFlags = flags; 12961 return super.queryIntent(intent, resolvedType, 12962 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12963 userId); 12964 } 12965 12966 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12967 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12968 if (!sUserManager.exists(userId)) 12969 return null; 12970 if (packageProviders == null) { 12971 return null; 12972 } 12973 mFlags = flags; 12974 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12975 final int N = packageProviders.size(); 12976 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12977 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12978 12979 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12980 for (int i = 0; i < N; ++i) { 12981 intentFilters = packageProviders.get(i).intents; 12982 if (intentFilters != null && intentFilters.size() > 0) { 12983 PackageParser.ProviderIntentInfo[] array = 12984 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12985 intentFilters.toArray(array); 12986 listCut.add(array); 12987 } 12988 } 12989 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12990 } 12991 12992 public final void addProvider(PackageParser.Provider p) { 12993 if (mProviders.containsKey(p.getComponentName())) { 12994 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12995 return; 12996 } 12997 12998 mProviders.put(p.getComponentName(), p); 12999 if (DEBUG_SHOW_INFO) { 13000 Log.v(TAG, " " 13001 + (p.info.nonLocalizedLabel != null 13002 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13003 Log.v(TAG, " Class=" + p.info.name); 13004 } 13005 final int NI = p.intents.size(); 13006 int j; 13007 for (j = 0; j < NI; j++) { 13008 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13009 if (DEBUG_SHOW_INFO) { 13010 Log.v(TAG, " IntentFilter:"); 13011 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13012 } 13013 if (!intent.debugCheck()) { 13014 Log.w(TAG, "==> For Provider " + p.info.name); 13015 } 13016 addFilter(intent); 13017 } 13018 } 13019 13020 public final void removeProvider(PackageParser.Provider p) { 13021 mProviders.remove(p.getComponentName()); 13022 if (DEBUG_SHOW_INFO) { 13023 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 13024 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 13025 Log.v(TAG, " Class=" + p.info.name); 13026 } 13027 final int NI = p.intents.size(); 13028 int j; 13029 for (j = 0; j < NI; j++) { 13030 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 13031 if (DEBUG_SHOW_INFO) { 13032 Log.v(TAG, " IntentFilter:"); 13033 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 13034 } 13035 removeFilter(intent); 13036 } 13037 } 13038 13039 @Override 13040 protected boolean allowFilterResult( 13041 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 13042 ProviderInfo filterPi = filter.provider.info; 13043 for (int i = dest.size() - 1; i >= 0; i--) { 13044 ProviderInfo destPi = dest.get(i).providerInfo; 13045 if (destPi.name == filterPi.name 13046 && destPi.packageName == filterPi.packageName) { 13047 return false; 13048 } 13049 } 13050 return true; 13051 } 13052 13053 @Override 13054 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 13055 return new PackageParser.ProviderIntentInfo[size]; 13056 } 13057 13058 @Override 13059 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 13060 if (!sUserManager.exists(userId)) 13061 return true; 13062 PackageParser.Package p = filter.provider.owner; 13063 if (p != null) { 13064 PackageSetting ps = (PackageSetting) p.mExtras; 13065 if (ps != null) { 13066 // System apps are never considered stopped for purposes of 13067 // filtering, because there may be no way for the user to 13068 // actually re-launch them. 13069 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 13070 && ps.getStopped(userId); 13071 } 13072 } 13073 return false; 13074 } 13075 13076 @Override 13077 protected boolean isPackageForFilter(String packageName, 13078 PackageParser.ProviderIntentInfo info) { 13079 return packageName.equals(info.provider.owner.packageName); 13080 } 13081 13082 @Override 13083 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 13084 int match, int userId) { 13085 if (!sUserManager.exists(userId)) 13086 return null; 13087 final PackageParser.ProviderIntentInfo info = filter; 13088 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 13089 return null; 13090 } 13091 final PackageParser.Provider provider = info.provider; 13092 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 13093 if (ps == null) { 13094 return null; 13095 } 13096 final PackageUserState userState = ps.readUserState(userId); 13097 final boolean matchVisibleToInstantApp = 13098 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 13099 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 13100 // throw out filters that aren't visible to instant applications 13101 if (matchVisibleToInstantApp 13102 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 13103 return null; 13104 } 13105 // throw out instant application filters if we're not explicitly requesting them 13106 if (!isInstantApp && userState.instantApp) { 13107 return null; 13108 } 13109 // throw out instant application filters if updates are available; will trigger 13110 // instant application resolution 13111 if (userState.instantApp && ps.isUpdateAvailable()) { 13112 return null; 13113 } 13114 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 13115 userState, userId); 13116 if (pi == null) { 13117 return null; 13118 } 13119 final ResolveInfo res = new ResolveInfo(); 13120 res.providerInfo = pi; 13121 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 13122 res.filter = filter; 13123 } 13124 res.priority = info.getPriority(); 13125 res.preferredOrder = provider.owner.mPreferredOrder; 13126 res.match = match; 13127 res.isDefault = info.hasDefault; 13128 res.labelRes = info.labelRes; 13129 res.nonLocalizedLabel = info.nonLocalizedLabel; 13130 res.icon = info.icon; 13131 res.system = res.providerInfo.applicationInfo.isSystemApp(); 13132 return res; 13133 } 13134 13135 @Override 13136 protected void sortResults(List<ResolveInfo> results) { 13137 Collections.sort(results, mResolvePrioritySorter); 13138 } 13139 13140 @Override 13141 protected void dumpFilter(PrintWriter out, String prefix, 13142 PackageParser.ProviderIntentInfo filter) { 13143 out.print(prefix); 13144 out.print( 13145 Integer.toHexString(System.identityHashCode(filter.provider))); 13146 out.print(' '); 13147 filter.provider.printComponentShortName(out); 13148 out.print(" filter "); 13149 out.println(Integer.toHexString(System.identityHashCode(filter))); 13150 } 13151 13152 @Override 13153 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 13154 return filter.provider; 13155 } 13156 13157 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 13158 PackageParser.Provider provider = (PackageParser.Provider)label; 13159 out.print(prefix); out.print( 13160 Integer.toHexString(System.identityHashCode(provider))); 13161 out.print(' '); 13162 provider.printComponentShortName(out); 13163 if (count > 1) { 13164 out.print(" ("); out.print(count); out.print(" filters)"); 13165 } 13166 out.println(); 13167 } 13168 13169 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 13170 = new ArrayMap<ComponentName, PackageParser.Provider>(); 13171 private int mFlags; 13172 } 13173 13174 static final class EphemeralIntentResolver 13175 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 13176 /** 13177 * The result that has the highest defined order. Ordering applies on a 13178 * per-package basis. Mapping is from package name to Pair of order and 13179 * EphemeralResolveInfo. 13180 * <p> 13181 * NOTE: This is implemented as a field variable for convenience and efficiency. 13182 * By having a field variable, we're able to track filter ordering as soon as 13183 * a non-zero order is defined. Otherwise, multiple loops across the result set 13184 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 13185 * this needs to be contained entirely within {@link #filterResults}. 13186 */ 13187 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 13188 13189 @Override 13190 protected AuxiliaryResolveInfo[] newArray(int size) { 13191 return new AuxiliaryResolveInfo[size]; 13192 } 13193 13194 @Override 13195 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 13196 return true; 13197 } 13198 13199 @Override 13200 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 13201 int userId) { 13202 if (!sUserManager.exists(userId)) { 13203 return null; 13204 } 13205 final String packageName = responseObj.resolveInfo.getPackageName(); 13206 final Integer order = responseObj.getOrder(); 13207 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 13208 mOrderResult.get(packageName); 13209 // ordering is enabled and this item's order isn't high enough 13210 if (lastOrderResult != null && lastOrderResult.first >= order) { 13211 return null; 13212 } 13213 final InstantAppResolveInfo res = responseObj.resolveInfo; 13214 if (order > 0) { 13215 // non-zero order, enable ordering 13216 mOrderResult.put(packageName, new Pair<>(order, res)); 13217 } 13218 return responseObj; 13219 } 13220 13221 @Override 13222 protected void filterResults(List<AuxiliaryResolveInfo> results) { 13223 // only do work if ordering is enabled [most of the time it won't be] 13224 if (mOrderResult.size() == 0) { 13225 return; 13226 } 13227 int resultSize = results.size(); 13228 for (int i = 0; i < resultSize; i++) { 13229 final InstantAppResolveInfo info = results.get(i).resolveInfo; 13230 final String packageName = info.getPackageName(); 13231 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 13232 if (savedInfo == null) { 13233 // package doesn't having ordering 13234 continue; 13235 } 13236 if (savedInfo.second == info) { 13237 // circled back to the highest ordered item; remove from order list 13238 mOrderResult.remove(packageName); 13239 if (mOrderResult.size() == 0) { 13240 // no more ordered items 13241 break; 13242 } 13243 continue; 13244 } 13245 // item has a worse order, remove it from the result list 13246 results.remove(i); 13247 resultSize--; 13248 i--; 13249 } 13250 } 13251 } 13252 13253 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13254 new Comparator<ResolveInfo>() { 13255 public int compare(ResolveInfo r1, ResolveInfo r2) { 13256 int v1 = r1.priority; 13257 int v2 = r2.priority; 13258 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13259 if (v1 != v2) { 13260 return (v1 > v2) ? -1 : 1; 13261 } 13262 v1 = r1.preferredOrder; 13263 v2 = r2.preferredOrder; 13264 if (v1 != v2) { 13265 return (v1 > v2) ? -1 : 1; 13266 } 13267 if (r1.isDefault != r2.isDefault) { 13268 return r1.isDefault ? -1 : 1; 13269 } 13270 v1 = r1.match; 13271 v2 = r2.match; 13272 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13273 if (v1 != v2) { 13274 return (v1 > v2) ? -1 : 1; 13275 } 13276 if (r1.system != r2.system) { 13277 return r1.system ? -1 : 1; 13278 } 13279 if (r1.activityInfo != null) { 13280 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13281 } 13282 if (r1.serviceInfo != null) { 13283 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13284 } 13285 if (r1.providerInfo != null) { 13286 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13287 } 13288 return 0; 13289 } 13290 }; 13291 13292 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13293 new Comparator<ProviderInfo>() { 13294 public int compare(ProviderInfo p1, ProviderInfo p2) { 13295 final int v1 = p1.initOrder; 13296 final int v2 = p2.initOrder; 13297 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13298 } 13299 }; 13300 13301 @Override 13302 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13303 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13304 final int[] userIds, int[] instantUserIds) { 13305 mHandler.post(new Runnable() { 13306 @Override 13307 public void run() { 13308 try { 13309 final IActivityManager am = ActivityManager.getService(); 13310 if (am == null) return; 13311 final int[] resolvedUserIds; 13312 if (userIds == null) { 13313 resolvedUserIds = am.getRunningUserIds(); 13314 } else { 13315 resolvedUserIds = userIds; 13316 } 13317 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13318 resolvedUserIds, false); 13319 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13320 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13321 instantUserIds, true); 13322 } 13323 } catch (RemoteException ex) { 13324 } 13325 } 13326 }); 13327 } 13328 13329 @Override 13330 public void notifyPackageAdded(String packageName) { 13331 final PackageListObserver[] observers; 13332 synchronized (mPackages) { 13333 if (mPackageListObservers.size() == 0) { 13334 return; 13335 } 13336 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13337 } 13338 for (int i = observers.length - 1; i >= 0; --i) { 13339 observers[i].onPackageAdded(packageName); 13340 } 13341 } 13342 13343 @Override 13344 public void notifyPackageRemoved(String packageName) { 13345 final PackageListObserver[] observers; 13346 synchronized (mPackages) { 13347 if (mPackageListObservers.size() == 0) { 13348 return; 13349 } 13350 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13351 } 13352 for (int i = observers.length - 1; i >= 0; --i) { 13353 observers[i].onPackageRemoved(packageName); 13354 } 13355 } 13356 13357 /** 13358 * Sends a broadcast for the given action. 13359 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13360 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13361 * the system and applications allowed to see instant applications to receive package 13362 * lifecycle events for instant applications. 13363 */ 13364 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13365 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13366 int[] userIds, boolean isInstantApp) 13367 throws RemoteException { 13368 for (int id : userIds) { 13369 final Intent intent = new Intent(action, 13370 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13371 final String[] requiredPermissions = 13372 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13373 if (extras != null) { 13374 intent.putExtras(extras); 13375 } 13376 if (targetPkg != null) { 13377 intent.setPackage(targetPkg); 13378 } 13379 // Modify the UID when posting to other users 13380 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13381 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13382 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13383 intent.putExtra(Intent.EXTRA_UID, uid); 13384 } 13385 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13386 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13387 if (DEBUG_BROADCASTS) { 13388 RuntimeException here = new RuntimeException("here"); 13389 here.fillInStackTrace(); 13390 Slog.d(TAG, "Sending to user " + id + ": " 13391 + intent.toShortString(false, true, false, false) 13392 + " " + intent.getExtras(), here); 13393 } 13394 am.broadcastIntent(null, intent, null, finishedReceiver, 13395 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13396 null, finishedReceiver != null, false, id); 13397 } 13398 } 13399 13400 /** 13401 * Check if the external storage media is available. This is true if there 13402 * is a mounted external storage medium or if the external storage is 13403 * emulated. 13404 */ 13405 private boolean isExternalMediaAvailable() { 13406 return mMediaMounted || Environment.isExternalStorageEmulated(); 13407 } 13408 13409 @Override 13410 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13411 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13412 return null; 13413 } 13414 if (!isExternalMediaAvailable()) { 13415 // If the external storage is no longer mounted at this point, 13416 // the caller may not have been able to delete all of this 13417 // packages files and can not delete any more. Bail. 13418 return null; 13419 } 13420 synchronized (mPackages) { 13421 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13422 if (lastPackage != null) { 13423 pkgs.remove(lastPackage); 13424 } 13425 if (pkgs.size() > 0) { 13426 return pkgs.get(0); 13427 } 13428 } 13429 return null; 13430 } 13431 13432 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13433 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13434 userId, andCode ? 1 : 0, packageName); 13435 if (mSystemReady) { 13436 msg.sendToTarget(); 13437 } else { 13438 if (mPostSystemReadyMessages == null) { 13439 mPostSystemReadyMessages = new ArrayList<>(); 13440 } 13441 mPostSystemReadyMessages.add(msg); 13442 } 13443 } 13444 13445 void startCleaningPackages() { 13446 // reader 13447 if (!isExternalMediaAvailable()) { 13448 return; 13449 } 13450 synchronized (mPackages) { 13451 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13452 return; 13453 } 13454 } 13455 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13456 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13457 IActivityManager am = ActivityManager.getService(); 13458 if (am != null) { 13459 int dcsUid = -1; 13460 synchronized (mPackages) { 13461 if (!mDefaultContainerWhitelisted) { 13462 mDefaultContainerWhitelisted = true; 13463 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13464 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13465 } 13466 } 13467 try { 13468 if (dcsUid > 0) { 13469 am.backgroundWhitelistUid(dcsUid); 13470 } 13471 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13472 UserHandle.USER_SYSTEM); 13473 } catch (RemoteException e) { 13474 } 13475 } 13476 } 13477 13478 /** 13479 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13480 * it is acting on behalf on an enterprise or the user). 13481 * 13482 * Note that the ordering of the conditionals in this method is important. The checks we perform 13483 * are as follows, in this order: 13484 * 13485 * 1) If the install is being performed by a system app, we can trust the app to have set the 13486 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13487 * what it is. 13488 * 2) If the install is being performed by a device or profile owner app, the install reason 13489 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13490 * set the install reason correctly. If the app targets an older SDK version where install 13491 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13492 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13493 * 3) In all other cases, the install is being performed by a regular app that is neither part 13494 * of the system nor a device or profile owner. We have no reason to believe that this app is 13495 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13496 * set to enterprise policy and if so, change it to unknown instead. 13497 */ 13498 private int fixUpInstallReason(String installerPackageName, int installerUid, 13499 int installReason) { 13500 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13501 == PERMISSION_GRANTED) { 13502 // If the install is being performed by a system app, we trust that app to have set the 13503 // install reason correctly. 13504 return installReason; 13505 } 13506 13507 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13508 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13509 if (dpm != null) { 13510 ComponentName owner = null; 13511 try { 13512 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13513 if (owner == null) { 13514 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13515 } 13516 } catch (RemoteException e) { 13517 } 13518 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13519 // If the install is being performed by a device or profile owner, the install 13520 // reason should be enterprise policy. 13521 return PackageManager.INSTALL_REASON_POLICY; 13522 } 13523 } 13524 13525 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13526 // If the install is being performed by a regular app (i.e. neither system app nor 13527 // device or profile owner), we have no reason to believe that the app is acting on 13528 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13529 // change it to unknown instead. 13530 return PackageManager.INSTALL_REASON_UNKNOWN; 13531 } 13532 13533 // If the install is being performed by a regular app and the install reason was set to any 13534 // value but enterprise policy, leave the install reason unchanged. 13535 return installReason; 13536 } 13537 13538 void installStage(String packageName, File stagedDir, 13539 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13540 String installerPackageName, int installerUid, UserHandle user, 13541 PackageParser.SigningDetails signingDetails) { 13542 if (DEBUG_EPHEMERAL) { 13543 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13544 Slog.d(TAG, "Ephemeral install of " + packageName); 13545 } 13546 } 13547 final VerificationInfo verificationInfo = new VerificationInfo( 13548 sessionParams.originatingUri, sessionParams.referrerUri, 13549 sessionParams.originatingUid, installerUid); 13550 13551 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13552 13553 final Message msg = mHandler.obtainMessage(INIT_COPY); 13554 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13555 sessionParams.installReason); 13556 final InstallParams params = new InstallParams(origin, null, observer, 13557 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13558 verificationInfo, user, sessionParams.abiOverride, 13559 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13560 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13561 msg.obj = params; 13562 13563 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13564 System.identityHashCode(msg.obj)); 13565 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13566 System.identityHashCode(msg.obj)); 13567 13568 mHandler.sendMessage(msg); 13569 } 13570 13571 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13572 int userId) { 13573 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13574 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13575 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13576 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13577 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13578 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13579 13580 // Send a session commit broadcast 13581 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13582 info.installReason = pkgSetting.getInstallReason(userId); 13583 info.appPackageName = packageName; 13584 sendSessionCommitBroadcast(info, userId); 13585 } 13586 13587 @Override 13588 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13589 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13590 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13591 return; 13592 } 13593 Bundle extras = new Bundle(1); 13594 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13595 final int uid = UserHandle.getUid( 13596 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13597 extras.putInt(Intent.EXTRA_UID, uid); 13598 13599 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13600 packageName, extras, 0, null, null, userIds, instantUserIds); 13601 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13602 mHandler.post(() -> { 13603 for (int userId : userIds) { 13604 sendBootCompletedBroadcastToSystemApp( 13605 packageName, includeStopped, userId); 13606 } 13607 } 13608 ); 13609 } 13610 } 13611 13612 /** 13613 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13614 * automatically without needing an explicit launch. 13615 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13616 */ 13617 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13618 int userId) { 13619 // If user is not running, the app didn't miss any broadcast 13620 if (!mUserManagerInternal.isUserRunning(userId)) { 13621 return; 13622 } 13623 final IActivityManager am = ActivityManager.getService(); 13624 try { 13625 // Deliver LOCKED_BOOT_COMPLETED first 13626 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13627 .setPackage(packageName); 13628 if (includeStopped) { 13629 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13630 } 13631 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13632 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13633 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13634 13635 // Deliver BOOT_COMPLETED only if user is unlocked 13636 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13637 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13638 if (includeStopped) { 13639 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13640 } 13641 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13642 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13643 } 13644 } catch (RemoteException e) { 13645 throw e.rethrowFromSystemServer(); 13646 } 13647 } 13648 13649 @Override 13650 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13651 int userId) { 13652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13653 PackageSetting pkgSetting; 13654 final int callingUid = Binder.getCallingUid(); 13655 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13656 true /* requireFullPermission */, true /* checkShell */, 13657 "setApplicationHiddenSetting for user " + userId); 13658 13659 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13660 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13661 return false; 13662 } 13663 13664 long callingId = Binder.clearCallingIdentity(); 13665 try { 13666 boolean sendAdded = false; 13667 boolean sendRemoved = false; 13668 // writer 13669 synchronized (mPackages) { 13670 pkgSetting = mSettings.mPackages.get(packageName); 13671 if (pkgSetting == null) { 13672 return false; 13673 } 13674 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13675 return false; 13676 } 13677 // Do not allow "android" is being disabled 13678 if ("android".equals(packageName)) { 13679 Slog.w(TAG, "Cannot hide package: android"); 13680 return false; 13681 } 13682 // Cannot hide static shared libs as they are considered 13683 // a part of the using app (emulating static linking). Also 13684 // static libs are installed always on internal storage. 13685 PackageParser.Package pkg = mPackages.get(packageName); 13686 if (pkg != null && pkg.staticSharedLibName != null) { 13687 Slog.w(TAG, "Cannot hide package: " + packageName 13688 + " providing static shared library: " 13689 + pkg.staticSharedLibName); 13690 return false; 13691 } 13692 // Only allow protected packages to hide themselves. 13693 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13694 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13695 Slog.w(TAG, "Not hiding protected package: " + packageName); 13696 return false; 13697 } 13698 13699 if (pkgSetting.getHidden(userId) != hidden) { 13700 pkgSetting.setHidden(hidden, userId); 13701 mSettings.writePackageRestrictionsLPr(userId); 13702 if (hidden) { 13703 sendRemoved = true; 13704 } else { 13705 sendAdded = true; 13706 } 13707 } 13708 } 13709 if (sendAdded) { 13710 sendPackageAddedForUser(packageName, pkgSetting, userId); 13711 return true; 13712 } 13713 if (sendRemoved) { 13714 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13715 "hiding pkg"); 13716 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13717 return true; 13718 } 13719 } finally { 13720 Binder.restoreCallingIdentity(callingId); 13721 } 13722 return false; 13723 } 13724 13725 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13726 int userId) { 13727 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13728 info.removedPackage = packageName; 13729 info.installerPackageName = pkgSetting.installerPackageName; 13730 info.removedUsers = new int[] {userId}; 13731 info.broadcastUsers = new int[] {userId}; 13732 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13733 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13734 } 13735 13736 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13737 if (pkgList.length > 0) { 13738 Bundle extras = new Bundle(1); 13739 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13740 13741 sendPackageBroadcast( 13742 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13743 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13744 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13745 new int[] {userId}, null); 13746 } 13747 } 13748 13749 /** 13750 * Returns true if application is not found or there was an error. Otherwise it returns 13751 * the hidden state of the package for the given user. 13752 */ 13753 @Override 13754 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13755 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13756 final int callingUid = Binder.getCallingUid(); 13757 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13758 true /* requireFullPermission */, false /* checkShell */, 13759 "getApplicationHidden for user " + userId); 13760 PackageSetting ps; 13761 long callingId = Binder.clearCallingIdentity(); 13762 try { 13763 // writer 13764 synchronized (mPackages) { 13765 ps = mSettings.mPackages.get(packageName); 13766 if (ps == null) { 13767 return true; 13768 } 13769 if (filterAppAccessLPr(ps, callingUid, userId)) { 13770 return true; 13771 } 13772 return ps.getHidden(userId); 13773 } 13774 } finally { 13775 Binder.restoreCallingIdentity(callingId); 13776 } 13777 } 13778 13779 /** 13780 * @hide 13781 */ 13782 @Override 13783 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13784 int installReason) { 13785 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13786 null); 13787 PackageSetting pkgSetting; 13788 final int callingUid = Binder.getCallingUid(); 13789 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13790 true /* requireFullPermission */, true /* checkShell */, 13791 "installExistingPackage for user " + userId); 13792 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13793 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13794 } 13795 13796 long callingId = Binder.clearCallingIdentity(); 13797 try { 13798 boolean installed = false; 13799 final boolean instantApp = 13800 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13801 final boolean fullApp = 13802 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13803 13804 // writer 13805 synchronized (mPackages) { 13806 pkgSetting = mSettings.mPackages.get(packageName); 13807 if (pkgSetting == null) { 13808 return PackageManager.INSTALL_FAILED_INVALID_URI; 13809 } 13810 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13811 // only allow the existing package to be used if it's installed as a full 13812 // application for at least one user 13813 boolean installAllowed = false; 13814 for (int checkUserId : sUserManager.getUserIds()) { 13815 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13816 if (installAllowed) { 13817 break; 13818 } 13819 } 13820 if (!installAllowed) { 13821 return PackageManager.INSTALL_FAILED_INVALID_URI; 13822 } 13823 } 13824 if (!pkgSetting.getInstalled(userId)) { 13825 pkgSetting.setInstalled(true, userId); 13826 pkgSetting.setHidden(false, userId); 13827 pkgSetting.setInstallReason(installReason, userId); 13828 mSettings.writePackageRestrictionsLPr(userId); 13829 mSettings.writeKernelMappingLPr(pkgSetting); 13830 installed = true; 13831 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13832 // upgrade app from instant to full; we don't allow app downgrade 13833 installed = true; 13834 } 13835 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13836 } 13837 13838 if (installed) { 13839 if (pkgSetting.pkg != null) { 13840 synchronized (mInstallLock) { 13841 // We don't need to freeze for a brand new install 13842 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13843 } 13844 } 13845 sendPackageAddedForUser(packageName, pkgSetting, userId); 13846 synchronized (mPackages) { 13847 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13848 } 13849 } 13850 } finally { 13851 Binder.restoreCallingIdentity(callingId); 13852 } 13853 13854 return PackageManager.INSTALL_SUCCEEDED; 13855 } 13856 13857 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13858 boolean instantApp, boolean fullApp) { 13859 // no state specified; do nothing 13860 if (!instantApp && !fullApp) { 13861 return; 13862 } 13863 if (userId != UserHandle.USER_ALL) { 13864 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13865 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13866 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13867 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13868 } 13869 } else { 13870 for (int currentUserId : sUserManager.getUserIds()) { 13871 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13872 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13873 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13874 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13875 } 13876 } 13877 } 13878 } 13879 13880 boolean isUserRestricted(int userId, String restrictionKey) { 13881 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13882 if (restrictions.getBoolean(restrictionKey, false)) { 13883 Log.w(TAG, "User is restricted: " + restrictionKey); 13884 return true; 13885 } 13886 return false; 13887 } 13888 13889 @Override 13890 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13891 int userId) { 13892 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13893 final int callingUid = Binder.getCallingUid(); 13894 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13895 true /* requireFullPermission */, true /* checkShell */, 13896 "setPackagesSuspended for user " + userId); 13897 13898 if (ArrayUtils.isEmpty(packageNames)) { 13899 return packageNames; 13900 } 13901 13902 // List of package names for whom the suspended state has changed. 13903 List<String> changedPackages = new ArrayList<>(packageNames.length); 13904 // List of package names for whom the suspended state is not set as requested in this 13905 // method. 13906 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13907 long callingId = Binder.clearCallingIdentity(); 13908 try { 13909 for (int i = 0; i < packageNames.length; i++) { 13910 String packageName = packageNames[i]; 13911 boolean changed = false; 13912 final int appId; 13913 synchronized (mPackages) { 13914 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13915 if (pkgSetting == null 13916 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13917 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13918 + "\". Skipping suspending/un-suspending."); 13919 unactionedPackages.add(packageName); 13920 continue; 13921 } 13922 appId = pkgSetting.appId; 13923 if (pkgSetting.getSuspended(userId) != suspended) { 13924 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13925 unactionedPackages.add(packageName); 13926 continue; 13927 } 13928 pkgSetting.setSuspended(suspended, userId); 13929 mSettings.writePackageRestrictionsLPr(userId); 13930 changed = true; 13931 changedPackages.add(packageName); 13932 } 13933 } 13934 13935 if (changed && suspended) { 13936 killApplication(packageName, UserHandle.getUid(userId, appId), 13937 "suspending package"); 13938 } 13939 } 13940 } finally { 13941 Binder.restoreCallingIdentity(callingId); 13942 } 13943 13944 if (!changedPackages.isEmpty()) { 13945 sendPackagesSuspendedForUser(changedPackages.toArray( 13946 new String[changedPackages.size()]), userId, suspended); 13947 } 13948 13949 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13950 } 13951 13952 @Override 13953 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13954 final int callingUid = Binder.getCallingUid(); 13955 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13956 true /* requireFullPermission */, false /* checkShell */, 13957 "isPackageSuspendedForUser for user " + userId); 13958 synchronized (mPackages) { 13959 final PackageSetting ps = mSettings.mPackages.get(packageName); 13960 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13961 throw new IllegalArgumentException("Unknown target package: " + packageName); 13962 } 13963 return ps.getSuspended(userId); 13964 } 13965 } 13966 13967 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13968 if (isPackageDeviceAdmin(packageName, userId)) { 13969 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13970 + "\": has an active device admin"); 13971 return false; 13972 } 13973 13974 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13975 if (packageName.equals(activeLauncherPackageName)) { 13976 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13977 + "\": contains the active launcher"); 13978 return false; 13979 } 13980 13981 if (packageName.equals(mRequiredInstallerPackage)) { 13982 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13983 + "\": required for package installation"); 13984 return false; 13985 } 13986 13987 if (packageName.equals(mRequiredUninstallerPackage)) { 13988 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13989 + "\": required for package uninstallation"); 13990 return false; 13991 } 13992 13993 if (packageName.equals(mRequiredVerifierPackage)) { 13994 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13995 + "\": required for package verification"); 13996 return false; 13997 } 13998 13999 if (packageName.equals(getDefaultDialerPackageName(userId))) { 14000 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14001 + "\": is the default dialer"); 14002 return false; 14003 } 14004 14005 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 14006 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 14007 + "\": protected package"); 14008 return false; 14009 } 14010 14011 // Cannot suspend static shared libs as they are considered 14012 // a part of the using app (emulating static linking). Also 14013 // static libs are installed always on internal storage. 14014 PackageParser.Package pkg = mPackages.get(packageName); 14015 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 14016 Slog.w(TAG, "Cannot suspend package: " + packageName 14017 + " providing static shared library: " 14018 + pkg.staticSharedLibName); 14019 return false; 14020 } 14021 14022 return true; 14023 } 14024 14025 private String getActiveLauncherPackageName(int userId) { 14026 Intent intent = new Intent(Intent.ACTION_MAIN); 14027 intent.addCategory(Intent.CATEGORY_HOME); 14028 ResolveInfo resolveInfo = resolveIntent( 14029 intent, 14030 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14031 PackageManager.MATCH_DEFAULT_ONLY, 14032 userId); 14033 14034 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14035 } 14036 14037 private String getDefaultDialerPackageName(int userId) { 14038 synchronized (mPackages) { 14039 return mSettings.getDefaultDialerPackageNameLPw(userId); 14040 } 14041 } 14042 14043 @Override 14044 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14045 mContext.enforceCallingOrSelfPermission( 14046 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14047 "Only package verification agents can verify applications"); 14048 14049 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14050 final PackageVerificationResponse response = new PackageVerificationResponse( 14051 verificationCode, Binder.getCallingUid()); 14052 msg.arg1 = id; 14053 msg.obj = response; 14054 mHandler.sendMessage(msg); 14055 } 14056 14057 @Override 14058 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14059 long millisecondsToDelay) { 14060 mContext.enforceCallingOrSelfPermission( 14061 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14062 "Only package verification agents can extend verification timeouts"); 14063 14064 final PackageVerificationState state = mPendingVerification.get(id); 14065 final PackageVerificationResponse response = new PackageVerificationResponse( 14066 verificationCodeAtTimeout, Binder.getCallingUid()); 14067 14068 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14069 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14070 } 14071 if (millisecondsToDelay < 0) { 14072 millisecondsToDelay = 0; 14073 } 14074 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14075 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14076 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14077 } 14078 14079 if ((state != null) && !state.timeoutExtended()) { 14080 state.extendTimeout(); 14081 14082 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14083 msg.arg1 = id; 14084 msg.obj = response; 14085 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14086 } 14087 } 14088 14089 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14090 int verificationCode, UserHandle user) { 14091 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14092 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14093 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14094 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14095 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14096 14097 mContext.sendBroadcastAsUser(intent, user, 14098 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14099 } 14100 14101 private ComponentName matchComponentForVerifier(String packageName, 14102 List<ResolveInfo> receivers) { 14103 ActivityInfo targetReceiver = null; 14104 14105 final int NR = receivers.size(); 14106 for (int i = 0; i < NR; i++) { 14107 final ResolveInfo info = receivers.get(i); 14108 if (info.activityInfo == null) { 14109 continue; 14110 } 14111 14112 if (packageName.equals(info.activityInfo.packageName)) { 14113 targetReceiver = info.activityInfo; 14114 break; 14115 } 14116 } 14117 14118 if (targetReceiver == null) { 14119 return null; 14120 } 14121 14122 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14123 } 14124 14125 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14126 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14127 if (pkgInfo.verifiers.length == 0) { 14128 return null; 14129 } 14130 14131 final int N = pkgInfo.verifiers.length; 14132 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 14133 for (int i = 0; i < N; i++) { 14134 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14135 14136 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14137 receivers); 14138 if (comp == null) { 14139 continue; 14140 } 14141 14142 final int verifierUid = getUidForVerifier(verifierInfo); 14143 if (verifierUid == -1) { 14144 continue; 14145 } 14146 14147 if (DEBUG_VERIFY) { 14148 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14149 + " with the correct signature"); 14150 } 14151 sufficientVerifiers.add(comp); 14152 verificationState.addSufficientVerifier(verifierUid); 14153 } 14154 14155 return sufficientVerifiers; 14156 } 14157 14158 private int getUidForVerifier(VerifierInfo verifierInfo) { 14159 synchronized (mPackages) { 14160 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14161 if (pkg == null) { 14162 return -1; 14163 } else if (pkg.mSigningDetails.signatures.length != 1) { 14164 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14165 + " has more than one signature; ignoring"); 14166 return -1; 14167 } 14168 14169 /* 14170 * If the public key of the package's signature does not match 14171 * our expected public key, then this is a different package and 14172 * we should skip. 14173 */ 14174 14175 final byte[] expectedPublicKey; 14176 try { 14177 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14178 final PublicKey publicKey = verifierSig.getPublicKey(); 14179 expectedPublicKey = publicKey.getEncoded(); 14180 } catch (CertificateException e) { 14181 return -1; 14182 } 14183 14184 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14185 14186 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14187 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14188 + " does not have the expected public key; ignoring"); 14189 return -1; 14190 } 14191 14192 return pkg.applicationInfo.uid; 14193 } 14194 } 14195 14196 @Override 14197 public void finishPackageInstall(int token, boolean didLaunch) { 14198 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14199 14200 if (DEBUG_INSTALL) { 14201 Slog.v(TAG, "BM finishing package install for " + token); 14202 } 14203 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14204 14205 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14206 mHandler.sendMessage(msg); 14207 } 14208 14209 /** 14210 * Get the verification agent timeout. Used for both the APK verifier and the 14211 * intent filter verifier. 14212 * 14213 * @return verification timeout in milliseconds 14214 */ 14215 private long getVerificationTimeout() { 14216 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14217 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14218 DEFAULT_VERIFICATION_TIMEOUT); 14219 } 14220 14221 /** 14222 * Get the default verification agent response code. 14223 * 14224 * @return default verification response code 14225 */ 14226 private int getDefaultVerificationResponse(UserHandle user) { 14227 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14228 return PackageManager.VERIFICATION_REJECT; 14229 } 14230 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14231 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14232 DEFAULT_VERIFICATION_RESPONSE); 14233 } 14234 14235 /** 14236 * Check whether or not package verification has been enabled. 14237 * 14238 * @return true if verification should be performed 14239 */ 14240 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14241 if (!DEFAULT_VERIFY_ENABLE) { 14242 return false; 14243 } 14244 14245 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14246 14247 // Check if installing from ADB 14248 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14249 // Do not run verification in a test harness environment 14250 if (ActivityManager.isRunningInTestHarness()) { 14251 return false; 14252 } 14253 if (ensureVerifyAppsEnabled) { 14254 return true; 14255 } 14256 // Check if the developer does not want package verification for ADB installs 14257 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14258 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14259 return false; 14260 } 14261 } else { 14262 // only when not installed from ADB, skip verification for instant apps when 14263 // the installer and verifier are the same. 14264 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14265 if (mInstantAppInstallerActivity != null 14266 && mInstantAppInstallerActivity.packageName.equals( 14267 mRequiredVerifierPackage)) { 14268 try { 14269 mContext.getSystemService(AppOpsManager.class) 14270 .checkPackage(installerUid, mRequiredVerifierPackage); 14271 if (DEBUG_VERIFY) { 14272 Slog.i(TAG, "disable verification for instant app"); 14273 } 14274 return false; 14275 } catch (SecurityException ignore) { } 14276 } 14277 } 14278 } 14279 14280 if (ensureVerifyAppsEnabled) { 14281 return true; 14282 } 14283 14284 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14285 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14286 } 14287 14288 @Override 14289 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14290 throws RemoteException { 14291 mContext.enforceCallingOrSelfPermission( 14292 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14293 "Only intentfilter verification agents can verify applications"); 14294 14295 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14296 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14297 Binder.getCallingUid(), verificationCode, failedDomains); 14298 msg.arg1 = id; 14299 msg.obj = response; 14300 mHandler.sendMessage(msg); 14301 } 14302 14303 @Override 14304 public int getIntentVerificationStatus(String packageName, int userId) { 14305 final int callingUid = Binder.getCallingUid(); 14306 if (UserHandle.getUserId(callingUid) != userId) { 14307 mContext.enforceCallingOrSelfPermission( 14308 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14309 "getIntentVerificationStatus" + userId); 14310 } 14311 if (getInstantAppPackageName(callingUid) != null) { 14312 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14313 } 14314 synchronized (mPackages) { 14315 final PackageSetting ps = mSettings.mPackages.get(packageName); 14316 if (ps == null 14317 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14318 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14319 } 14320 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14321 } 14322 } 14323 14324 @Override 14325 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14326 mContext.enforceCallingOrSelfPermission( 14327 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14328 14329 boolean result = false; 14330 synchronized (mPackages) { 14331 final PackageSetting ps = mSettings.mPackages.get(packageName); 14332 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14333 return false; 14334 } 14335 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14336 } 14337 if (result) { 14338 scheduleWritePackageRestrictionsLocked(userId); 14339 } 14340 return result; 14341 } 14342 14343 @Override 14344 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14345 String packageName) { 14346 final int callingUid = Binder.getCallingUid(); 14347 if (getInstantAppPackageName(callingUid) != null) { 14348 return ParceledListSlice.emptyList(); 14349 } 14350 synchronized (mPackages) { 14351 final PackageSetting ps = mSettings.mPackages.get(packageName); 14352 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14353 return ParceledListSlice.emptyList(); 14354 } 14355 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14356 } 14357 } 14358 14359 @Override 14360 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14361 if (TextUtils.isEmpty(packageName)) { 14362 return ParceledListSlice.emptyList(); 14363 } 14364 final int callingUid = Binder.getCallingUid(); 14365 final int callingUserId = UserHandle.getUserId(callingUid); 14366 synchronized (mPackages) { 14367 PackageParser.Package pkg = mPackages.get(packageName); 14368 if (pkg == null || pkg.activities == null) { 14369 return ParceledListSlice.emptyList(); 14370 } 14371 if (pkg.mExtras == null) { 14372 return ParceledListSlice.emptyList(); 14373 } 14374 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14375 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14376 return ParceledListSlice.emptyList(); 14377 } 14378 final int count = pkg.activities.size(); 14379 ArrayList<IntentFilter> result = new ArrayList<>(); 14380 for (int n=0; n<count; n++) { 14381 PackageParser.Activity activity = pkg.activities.get(n); 14382 if (activity.intents != null && activity.intents.size() > 0) { 14383 result.addAll(activity.intents); 14384 } 14385 } 14386 return new ParceledListSlice<>(result); 14387 } 14388 } 14389 14390 @Override 14391 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14392 mContext.enforceCallingOrSelfPermission( 14393 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14394 if (UserHandle.getCallingUserId() != userId) { 14395 mContext.enforceCallingOrSelfPermission( 14396 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14397 } 14398 14399 synchronized (mPackages) { 14400 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14401 if (packageName != null) { 14402 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14403 packageName, userId); 14404 } 14405 return result; 14406 } 14407 } 14408 14409 @Override 14410 public String getDefaultBrowserPackageName(int userId) { 14411 if (UserHandle.getCallingUserId() != userId) { 14412 mContext.enforceCallingOrSelfPermission( 14413 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14414 } 14415 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14416 return null; 14417 } 14418 synchronized (mPackages) { 14419 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14420 } 14421 } 14422 14423 /** 14424 * Get the "allow unknown sources" setting. 14425 * 14426 * @return the current "allow unknown sources" setting 14427 */ 14428 private int getUnknownSourcesSettings() { 14429 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14430 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14431 -1); 14432 } 14433 14434 @Override 14435 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14436 final int callingUid = Binder.getCallingUid(); 14437 if (getInstantAppPackageName(callingUid) != null) { 14438 return; 14439 } 14440 // writer 14441 synchronized (mPackages) { 14442 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14443 if (targetPackageSetting == null 14444 || filterAppAccessLPr( 14445 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14446 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14447 } 14448 14449 PackageSetting installerPackageSetting; 14450 if (installerPackageName != null) { 14451 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14452 if (installerPackageSetting == null) { 14453 throw new IllegalArgumentException("Unknown installer package: " 14454 + installerPackageName); 14455 } 14456 } else { 14457 installerPackageSetting = null; 14458 } 14459 14460 Signature[] callerSignature; 14461 Object obj = mSettings.getUserIdLPr(callingUid); 14462 if (obj != null) { 14463 if (obj instanceof SharedUserSetting) { 14464 callerSignature = 14465 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14466 } else if (obj instanceof PackageSetting) { 14467 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14468 } else { 14469 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14470 } 14471 } else { 14472 throw new SecurityException("Unknown calling UID: " + callingUid); 14473 } 14474 14475 // Verify: can't set installerPackageName to a package that is 14476 // not signed with the same cert as the caller. 14477 if (installerPackageSetting != null) { 14478 if (compareSignatures(callerSignature, 14479 installerPackageSetting.signatures.mSigningDetails.signatures) 14480 != PackageManager.SIGNATURE_MATCH) { 14481 throw new SecurityException( 14482 "Caller does not have same cert as new installer package " 14483 + installerPackageName); 14484 } 14485 } 14486 14487 // Verify: if target already has an installer package, it must 14488 // be signed with the same cert as the caller. 14489 if (targetPackageSetting.installerPackageName != null) { 14490 PackageSetting setting = mSettings.mPackages.get( 14491 targetPackageSetting.installerPackageName); 14492 // If the currently set package isn't valid, then it's always 14493 // okay to change it. 14494 if (setting != null) { 14495 if (compareSignatures(callerSignature, 14496 setting.signatures.mSigningDetails.signatures) 14497 != PackageManager.SIGNATURE_MATCH) { 14498 throw new SecurityException( 14499 "Caller does not have same cert as old installer package " 14500 + targetPackageSetting.installerPackageName); 14501 } 14502 } 14503 } 14504 14505 // Okay! 14506 targetPackageSetting.installerPackageName = installerPackageName; 14507 if (installerPackageName != null) { 14508 mSettings.mInstallerPackages.add(installerPackageName); 14509 } 14510 scheduleWriteSettingsLocked(); 14511 } 14512 } 14513 14514 @Override 14515 public void setApplicationCategoryHint(String packageName, int categoryHint, 14516 String callerPackageName) { 14517 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14518 throw new SecurityException("Instant applications don't have access to this method"); 14519 } 14520 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14521 callerPackageName); 14522 synchronized (mPackages) { 14523 PackageSetting ps = mSettings.mPackages.get(packageName); 14524 if (ps == null) { 14525 throw new IllegalArgumentException("Unknown target package " + packageName); 14526 } 14527 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14528 throw new IllegalArgumentException("Unknown target package " + packageName); 14529 } 14530 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14531 throw new IllegalArgumentException("Calling package " + callerPackageName 14532 + " is not installer for " + packageName); 14533 } 14534 14535 if (ps.categoryHint != categoryHint) { 14536 ps.categoryHint = categoryHint; 14537 scheduleWriteSettingsLocked(); 14538 } 14539 } 14540 } 14541 14542 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14543 // Queue up an async operation since the package installation may take a little while. 14544 mHandler.post(new Runnable() { 14545 public void run() { 14546 mHandler.removeCallbacks(this); 14547 // Result object to be returned 14548 PackageInstalledInfo res = new PackageInstalledInfo(); 14549 res.setReturnCode(currentStatus); 14550 res.uid = -1; 14551 res.pkg = null; 14552 res.removedInfo = null; 14553 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14554 args.doPreInstall(res.returnCode); 14555 synchronized (mInstallLock) { 14556 installPackageTracedLI(args, res); 14557 } 14558 args.doPostInstall(res.returnCode, res.uid); 14559 } 14560 14561 // A restore should be performed at this point if (a) the install 14562 // succeeded, (b) the operation is not an update, and (c) the new 14563 // package has not opted out of backup participation. 14564 final boolean update = res.removedInfo != null 14565 && res.removedInfo.removedPackage != null; 14566 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14567 boolean doRestore = !update 14568 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14569 14570 // Set up the post-install work request bookkeeping. This will be used 14571 // and cleaned up by the post-install event handling regardless of whether 14572 // there's a restore pass performed. Token values are >= 1. 14573 int token; 14574 if (mNextInstallToken < 0) mNextInstallToken = 1; 14575 token = mNextInstallToken++; 14576 14577 PostInstallData data = new PostInstallData(args, res); 14578 mRunningInstalls.put(token, data); 14579 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14580 14581 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14582 // Pass responsibility to the Backup Manager. It will perform a 14583 // restore if appropriate, then pass responsibility back to the 14584 // Package Manager to run the post-install observer callbacks 14585 // and broadcasts. 14586 IBackupManager bm = IBackupManager.Stub.asInterface( 14587 ServiceManager.getService(Context.BACKUP_SERVICE)); 14588 if (bm != null) { 14589 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14590 + " to BM for possible restore"); 14591 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14592 try { 14593 // TODO: http://b/22388012 14594 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14595 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14596 } else { 14597 doRestore = false; 14598 } 14599 } catch (RemoteException e) { 14600 // can't happen; the backup manager is local 14601 } catch (Exception e) { 14602 Slog.e(TAG, "Exception trying to enqueue restore", e); 14603 doRestore = false; 14604 } 14605 } else { 14606 Slog.e(TAG, "Backup Manager not found!"); 14607 doRestore = false; 14608 } 14609 } 14610 14611 if (!doRestore) { 14612 // No restore possible, or the Backup Manager was mysteriously not 14613 // available -- just fire the post-install work request directly. 14614 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14615 14616 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14617 14618 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14619 mHandler.sendMessage(msg); 14620 } 14621 } 14622 }); 14623 } 14624 14625 /** 14626 * Callback from PackageSettings whenever an app is first transitioned out of the 14627 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14628 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14629 * here whether the app is the target of an ongoing install, and only send the 14630 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14631 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14632 * handling. 14633 */ 14634 void notifyFirstLaunch(final String packageName, final String installerPackage, 14635 final int userId) { 14636 // Serialize this with the rest of the install-process message chain. In the 14637 // restore-at-install case, this Runnable will necessarily run before the 14638 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14639 // are coherent. In the non-restore case, the app has already completed install 14640 // and been launched through some other means, so it is not in a problematic 14641 // state for observers to see the FIRST_LAUNCH signal. 14642 mHandler.post(new Runnable() { 14643 @Override 14644 public void run() { 14645 for (int i = 0; i < mRunningInstalls.size(); i++) { 14646 final PostInstallData data = mRunningInstalls.valueAt(i); 14647 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14648 continue; 14649 } 14650 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14651 // right package; but is it for the right user? 14652 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14653 if (userId == data.res.newUsers[uIndex]) { 14654 if (DEBUG_BACKUP) { 14655 Slog.i(TAG, "Package " + packageName 14656 + " being restored so deferring FIRST_LAUNCH"); 14657 } 14658 return; 14659 } 14660 } 14661 } 14662 } 14663 // didn't find it, so not being restored 14664 if (DEBUG_BACKUP) { 14665 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14666 } 14667 final boolean isInstantApp = isInstantApp(packageName, userId); 14668 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14669 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14670 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14671 } 14672 }); 14673 } 14674 14675 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14676 int[] userIds, int[] instantUserIds) { 14677 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14678 installerPkg, null, userIds, instantUserIds); 14679 } 14680 14681 private abstract class HandlerParams { 14682 private static final int MAX_RETRIES = 4; 14683 14684 /** 14685 * Number of times startCopy() has been attempted and had a non-fatal 14686 * error. 14687 */ 14688 private int mRetries = 0; 14689 14690 /** User handle for the user requesting the information or installation. */ 14691 private final UserHandle mUser; 14692 String traceMethod; 14693 int traceCookie; 14694 14695 HandlerParams(UserHandle user) { 14696 mUser = user; 14697 } 14698 14699 UserHandle getUser() { 14700 return mUser; 14701 } 14702 14703 HandlerParams setTraceMethod(String traceMethod) { 14704 this.traceMethod = traceMethod; 14705 return this; 14706 } 14707 14708 HandlerParams setTraceCookie(int traceCookie) { 14709 this.traceCookie = traceCookie; 14710 return this; 14711 } 14712 14713 final boolean startCopy() { 14714 boolean res; 14715 try { 14716 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14717 14718 if (++mRetries > MAX_RETRIES) { 14719 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14720 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14721 handleServiceError(); 14722 return false; 14723 } else { 14724 handleStartCopy(); 14725 res = true; 14726 } 14727 } catch (RemoteException e) { 14728 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14729 mHandler.sendEmptyMessage(MCS_RECONNECT); 14730 res = false; 14731 } 14732 handleReturnCode(); 14733 return res; 14734 } 14735 14736 final void serviceError() { 14737 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14738 handleServiceError(); 14739 handleReturnCode(); 14740 } 14741 14742 abstract void handleStartCopy() throws RemoteException; 14743 abstract void handleServiceError(); 14744 abstract void handleReturnCode(); 14745 } 14746 14747 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14748 for (File path : paths) { 14749 try { 14750 mcs.clearDirectory(path.getAbsolutePath()); 14751 } catch (RemoteException e) { 14752 } 14753 } 14754 } 14755 14756 static class OriginInfo { 14757 /** 14758 * Location where install is coming from, before it has been 14759 * copied/renamed into place. This could be a single monolithic APK 14760 * file, or a cluster directory. This location may be untrusted. 14761 */ 14762 final File file; 14763 14764 /** 14765 * Flag indicating that {@link #file} or {@link #cid} has already been 14766 * staged, meaning downstream users don't need to defensively copy the 14767 * contents. 14768 */ 14769 final boolean staged; 14770 14771 /** 14772 * Flag indicating that {@link #file} or {@link #cid} is an already 14773 * installed app that is being moved. 14774 */ 14775 final boolean existing; 14776 14777 final String resolvedPath; 14778 final File resolvedFile; 14779 14780 static OriginInfo fromNothing() { 14781 return new OriginInfo(null, false, false); 14782 } 14783 14784 static OriginInfo fromUntrustedFile(File file) { 14785 return new OriginInfo(file, false, false); 14786 } 14787 14788 static OriginInfo fromExistingFile(File file) { 14789 return new OriginInfo(file, false, true); 14790 } 14791 14792 static OriginInfo fromStagedFile(File file) { 14793 return new OriginInfo(file, true, false); 14794 } 14795 14796 private OriginInfo(File file, boolean staged, boolean existing) { 14797 this.file = file; 14798 this.staged = staged; 14799 this.existing = existing; 14800 14801 if (file != null) { 14802 resolvedPath = file.getAbsolutePath(); 14803 resolvedFile = file; 14804 } else { 14805 resolvedPath = null; 14806 resolvedFile = null; 14807 } 14808 } 14809 } 14810 14811 static class MoveInfo { 14812 final int moveId; 14813 final String fromUuid; 14814 final String toUuid; 14815 final String packageName; 14816 final String dataAppName; 14817 final int appId; 14818 final String seinfo; 14819 final int targetSdkVersion; 14820 14821 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14822 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14823 this.moveId = moveId; 14824 this.fromUuid = fromUuid; 14825 this.toUuid = toUuid; 14826 this.packageName = packageName; 14827 this.dataAppName = dataAppName; 14828 this.appId = appId; 14829 this.seinfo = seinfo; 14830 this.targetSdkVersion = targetSdkVersion; 14831 } 14832 } 14833 14834 static class VerificationInfo { 14835 /** A constant used to indicate that a uid value is not present. */ 14836 public static final int NO_UID = -1; 14837 14838 /** URI referencing where the package was downloaded from. */ 14839 final Uri originatingUri; 14840 14841 /** HTTP referrer URI associated with the originatingURI. */ 14842 final Uri referrer; 14843 14844 /** UID of the application that the install request originated from. */ 14845 final int originatingUid; 14846 14847 /** UID of application requesting the install */ 14848 final int installerUid; 14849 14850 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14851 this.originatingUri = originatingUri; 14852 this.referrer = referrer; 14853 this.originatingUid = originatingUid; 14854 this.installerUid = installerUid; 14855 } 14856 } 14857 14858 class InstallParams extends HandlerParams { 14859 final OriginInfo origin; 14860 final MoveInfo move; 14861 final IPackageInstallObserver2 observer; 14862 int installFlags; 14863 final String installerPackageName; 14864 final String volumeUuid; 14865 private InstallArgs mArgs; 14866 private int mRet; 14867 final String packageAbiOverride; 14868 final String[] grantedRuntimePermissions; 14869 final VerificationInfo verificationInfo; 14870 final PackageParser.SigningDetails signingDetails; 14871 final int installReason; 14872 14873 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14874 int installFlags, String installerPackageName, String volumeUuid, 14875 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14876 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14877 super(user); 14878 this.origin = origin; 14879 this.move = move; 14880 this.observer = observer; 14881 this.installFlags = installFlags; 14882 this.installerPackageName = installerPackageName; 14883 this.volumeUuid = volumeUuid; 14884 this.verificationInfo = verificationInfo; 14885 this.packageAbiOverride = packageAbiOverride; 14886 this.grantedRuntimePermissions = grantedPermissions; 14887 this.signingDetails = signingDetails; 14888 this.installReason = installReason; 14889 } 14890 14891 @Override 14892 public String toString() { 14893 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14894 + " file=" + origin.file + "}"; 14895 } 14896 14897 private int installLocationPolicy(PackageInfoLite pkgLite) { 14898 String packageName = pkgLite.packageName; 14899 int installLocation = pkgLite.installLocation; 14900 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14901 // reader 14902 synchronized (mPackages) { 14903 // Currently installed package which the new package is attempting to replace or 14904 // null if no such package is installed. 14905 PackageParser.Package installedPkg = mPackages.get(packageName); 14906 // Package which currently owns the data which the new package will own if installed. 14907 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14908 // will be null whereas dataOwnerPkg will contain information about the package 14909 // which was uninstalled while keeping its data. 14910 PackageParser.Package dataOwnerPkg = installedPkg; 14911 if (dataOwnerPkg == null) { 14912 PackageSetting ps = mSettings.mPackages.get(packageName); 14913 if (ps != null) { 14914 dataOwnerPkg = ps.pkg; 14915 } 14916 } 14917 14918 if (dataOwnerPkg != null) { 14919 // If installed, the package will get access to data left on the device by its 14920 // predecessor. As a security measure, this is permited only if this is not a 14921 // version downgrade or if the predecessor package is marked as debuggable and 14922 // a downgrade is explicitly requested. 14923 // 14924 // On debuggable platform builds, downgrades are permitted even for 14925 // non-debuggable packages to make testing easier. Debuggable platform builds do 14926 // not offer security guarantees and thus it's OK to disable some security 14927 // mechanisms to make debugging/testing easier on those builds. However, even on 14928 // debuggable builds downgrades of packages are permitted only if requested via 14929 // installFlags. This is because we aim to keep the behavior of debuggable 14930 // platform builds as close as possible to the behavior of non-debuggable 14931 // platform builds. 14932 final boolean downgradeRequested = 14933 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14934 final boolean packageDebuggable = 14935 (dataOwnerPkg.applicationInfo.flags 14936 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14937 final boolean downgradePermitted = 14938 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14939 if (!downgradePermitted) { 14940 try { 14941 checkDowngrade(dataOwnerPkg, pkgLite); 14942 } catch (PackageManagerException e) { 14943 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14944 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14945 } 14946 } 14947 } 14948 14949 if (installedPkg != null) { 14950 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14951 // Check for updated system application. 14952 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14953 if (onSd) { 14954 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14955 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14956 } 14957 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14958 } else { 14959 if (onSd) { 14960 // Install flag overrides everything. 14961 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14962 } 14963 // If current upgrade specifies particular preference 14964 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14965 // Application explicitly specified internal. 14966 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14967 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14968 // App explictly prefers external. Let policy decide 14969 } else { 14970 // Prefer previous location 14971 if (isExternal(installedPkg)) { 14972 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14973 } 14974 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14975 } 14976 } 14977 } else { 14978 // Invalid install. Return error code 14979 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14980 } 14981 } 14982 } 14983 // All the special cases have been taken care of. 14984 // Return result based on recommended install location. 14985 if (onSd) { 14986 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14987 } 14988 return pkgLite.recommendedInstallLocation; 14989 } 14990 14991 /* 14992 * Invoke remote method to get package information and install 14993 * location values. Override install location based on default 14994 * policy if needed and then create install arguments based 14995 * on the install location. 14996 */ 14997 public void handleStartCopy() throws RemoteException { 14998 int ret = PackageManager.INSTALL_SUCCEEDED; 14999 15000 // If we're already staged, we've firmly committed to an install location 15001 if (origin.staged) { 15002 if (origin.file != null) { 15003 installFlags |= PackageManager.INSTALL_INTERNAL; 15004 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15005 } else { 15006 throw new IllegalStateException("Invalid stage location"); 15007 } 15008 } 15009 15010 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15011 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15012 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15013 PackageInfoLite pkgLite = null; 15014 15015 if (onInt && onSd) { 15016 // Check if both bits are set. 15017 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 15018 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15019 } else if (onSd && ephemeral) { 15020 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 15021 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15022 } else { 15023 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 15024 packageAbiOverride); 15025 15026 if (DEBUG_EPHEMERAL && ephemeral) { 15027 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15028 } 15029 15030 /* 15031 * If we have too little free space, try to free cache 15032 * before giving up. 15033 */ 15034 if (!origin.staged && pkgLite.recommendedInstallLocation 15035 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15036 // TODO: focus freeing disk space on the target device 15037 final StorageManager storage = StorageManager.from(mContext); 15038 final long lowThreshold = storage.getStorageLowBytes( 15039 Environment.getDataDirectory()); 15040 15041 final long sizeBytes = mContainerService.calculateInstalledSize( 15042 origin.resolvedPath, packageAbiOverride); 15043 15044 try { 15045 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15046 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 15047 installFlags, packageAbiOverride); 15048 } catch (InstallerException e) { 15049 Slog.w(TAG, "Failed to free cache", e); 15050 } 15051 15052 /* 15053 * The cache free must have deleted the file we 15054 * downloaded to install. 15055 * 15056 * TODO: fix the "freeCache" call to not delete 15057 * the file we care about. 15058 */ 15059 if (pkgLite.recommendedInstallLocation 15060 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15061 pkgLite.recommendedInstallLocation 15062 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15063 } 15064 } 15065 } 15066 15067 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15068 int loc = pkgLite.recommendedInstallLocation; 15069 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15070 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15071 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15072 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15073 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15074 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15075 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15076 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15077 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15078 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15079 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15080 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15081 } else { 15082 // Override with defaults if needed. 15083 loc = installLocationPolicy(pkgLite); 15084 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15085 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15086 } else if (!onSd && !onInt) { 15087 // Override install location with flags 15088 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15089 // Set the flag to install on external media. 15090 installFlags |= PackageManager.INSTALL_EXTERNAL; 15091 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15092 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15093 if (DEBUG_EPHEMERAL) { 15094 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15095 } 15096 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15097 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 15098 |PackageManager.INSTALL_INTERNAL); 15099 } else { 15100 // Make sure the flag for installing on external 15101 // media is unset 15102 installFlags |= PackageManager.INSTALL_INTERNAL; 15103 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 15104 } 15105 } 15106 } 15107 } 15108 15109 final InstallArgs args = createInstallArgs(this); 15110 mArgs = args; 15111 15112 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15113 // TODO: http://b/22976637 15114 // Apps installed for "all" users use the device owner to verify the app 15115 UserHandle verifierUser = getUser(); 15116 if (verifierUser == UserHandle.ALL) { 15117 verifierUser = UserHandle.SYSTEM; 15118 } 15119 15120 /* 15121 * Determine if we have any installed package verifiers. If we 15122 * do, then we'll defer to them to verify the packages. 15123 */ 15124 final int requiredUid = mRequiredVerifierPackage == null ? -1 15125 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15126 verifierUser.getIdentifier()); 15127 final int installerUid = 15128 verificationInfo == null ? -1 : verificationInfo.installerUid; 15129 if (!origin.existing && requiredUid != -1 15130 && isVerificationEnabled( 15131 verifierUser.getIdentifier(), installFlags, installerUid)) { 15132 final Intent verification = new Intent( 15133 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15134 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15135 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15136 PACKAGE_MIME_TYPE); 15137 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15138 15139 // Query all live verifiers based on current user state 15140 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15141 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15142 false /*allowDynamicSplits*/); 15143 15144 if (DEBUG_VERIFY) { 15145 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15146 + verification.toString() + " with " + pkgLite.verifiers.length 15147 + " optional verifiers"); 15148 } 15149 15150 final int verificationId = mPendingVerificationToken++; 15151 15152 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15153 15154 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15155 installerPackageName); 15156 15157 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15158 installFlags); 15159 15160 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15161 pkgLite.packageName); 15162 15163 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15164 pkgLite.versionCode); 15165 15166 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15167 pkgLite.getLongVersionCode()); 15168 15169 if (verificationInfo != null) { 15170 if (verificationInfo.originatingUri != null) { 15171 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15172 verificationInfo.originatingUri); 15173 } 15174 if (verificationInfo.referrer != null) { 15175 verification.putExtra(Intent.EXTRA_REFERRER, 15176 verificationInfo.referrer); 15177 } 15178 if (verificationInfo.originatingUid >= 0) { 15179 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15180 verificationInfo.originatingUid); 15181 } 15182 if (verificationInfo.installerUid >= 0) { 15183 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15184 verificationInfo.installerUid); 15185 } 15186 } 15187 15188 final PackageVerificationState verificationState = new PackageVerificationState( 15189 requiredUid, args); 15190 15191 mPendingVerification.append(verificationId, verificationState); 15192 15193 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15194 receivers, verificationState); 15195 15196 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15197 final long idleDuration = getVerificationTimeout(); 15198 15199 /* 15200 * If any sufficient verifiers were listed in the package 15201 * manifest, attempt to ask them. 15202 */ 15203 if (sufficientVerifiers != null) { 15204 final int N = sufficientVerifiers.size(); 15205 if (N == 0) { 15206 Slog.i(TAG, "Additional verifiers required, but none installed."); 15207 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15208 } else { 15209 for (int i = 0; i < N; i++) { 15210 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15211 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15212 verifierComponent.getPackageName(), idleDuration, 15213 verifierUser.getIdentifier(), false, "package verifier"); 15214 15215 final Intent sufficientIntent = new Intent(verification); 15216 sufficientIntent.setComponent(verifierComponent); 15217 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15218 } 15219 } 15220 } 15221 15222 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15223 mRequiredVerifierPackage, receivers); 15224 if (ret == PackageManager.INSTALL_SUCCEEDED 15225 && mRequiredVerifierPackage != null) { 15226 Trace.asyncTraceBegin( 15227 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15228 /* 15229 * Send the intent to the required verification agent, 15230 * but only start the verification timeout after the 15231 * target BroadcastReceivers have run. 15232 */ 15233 verification.setComponent(requiredVerifierComponent); 15234 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15235 mRequiredVerifierPackage, idleDuration, 15236 verifierUser.getIdentifier(), false, "package verifier"); 15237 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15238 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15239 new BroadcastReceiver() { 15240 @Override 15241 public void onReceive(Context context, Intent intent) { 15242 final Message msg = mHandler 15243 .obtainMessage(CHECK_PENDING_VERIFICATION); 15244 msg.arg1 = verificationId; 15245 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15246 } 15247 }, null, 0, null, null); 15248 15249 /* 15250 * We don't want the copy to proceed until verification 15251 * succeeds, so null out this field. 15252 */ 15253 mArgs = null; 15254 } 15255 } else { 15256 /* 15257 * No package verification is enabled, so immediately start 15258 * the remote call to initiate copy using temporary file. 15259 */ 15260 ret = args.copyApk(mContainerService, true); 15261 } 15262 } 15263 15264 mRet = ret; 15265 } 15266 15267 @Override 15268 void handleReturnCode() { 15269 // If mArgs is null, then MCS couldn't be reached. When it 15270 // reconnects, it will try again to install. At that point, this 15271 // will succeed. 15272 if (mArgs != null) { 15273 processPendingInstall(mArgs, mRet); 15274 } 15275 } 15276 15277 @Override 15278 void handleServiceError() { 15279 mArgs = createInstallArgs(this); 15280 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15281 } 15282 } 15283 15284 private InstallArgs createInstallArgs(InstallParams params) { 15285 if (params.move != null) { 15286 return new MoveInstallArgs(params); 15287 } else { 15288 return new FileInstallArgs(params); 15289 } 15290 } 15291 15292 /** 15293 * Create args that describe an existing installed package. Typically used 15294 * when cleaning up old installs, or used as a move source. 15295 */ 15296 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15297 String resourcePath, String[] instructionSets) { 15298 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15299 } 15300 15301 static abstract class InstallArgs { 15302 /** @see InstallParams#origin */ 15303 final OriginInfo origin; 15304 /** @see InstallParams#move */ 15305 final MoveInfo move; 15306 15307 final IPackageInstallObserver2 observer; 15308 // Always refers to PackageManager flags only 15309 final int installFlags; 15310 final String installerPackageName; 15311 final String volumeUuid; 15312 final UserHandle user; 15313 final String abiOverride; 15314 final String[] installGrantPermissions; 15315 /** If non-null, drop an async trace when the install completes */ 15316 final String traceMethod; 15317 final int traceCookie; 15318 final PackageParser.SigningDetails signingDetails; 15319 final int installReason; 15320 15321 // The list of instruction sets supported by this app. This is currently 15322 // only used during the rmdex() phase to clean up resources. We can get rid of this 15323 // if we move dex files under the common app path. 15324 /* nullable */ String[] instructionSets; 15325 15326 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15327 int installFlags, String installerPackageName, String volumeUuid, 15328 UserHandle user, String[] instructionSets, 15329 String abiOverride, String[] installGrantPermissions, 15330 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15331 int installReason) { 15332 this.origin = origin; 15333 this.move = move; 15334 this.installFlags = installFlags; 15335 this.observer = observer; 15336 this.installerPackageName = installerPackageName; 15337 this.volumeUuid = volumeUuid; 15338 this.user = user; 15339 this.instructionSets = instructionSets; 15340 this.abiOverride = abiOverride; 15341 this.installGrantPermissions = installGrantPermissions; 15342 this.traceMethod = traceMethod; 15343 this.traceCookie = traceCookie; 15344 this.signingDetails = signingDetails; 15345 this.installReason = installReason; 15346 } 15347 15348 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15349 abstract int doPreInstall(int status); 15350 15351 /** 15352 * Rename package into final resting place. All paths on the given 15353 * scanned package should be updated to reflect the rename. 15354 */ 15355 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15356 abstract int doPostInstall(int status, int uid); 15357 15358 /** @see PackageSettingBase#codePathString */ 15359 abstract String getCodePath(); 15360 /** @see PackageSettingBase#resourcePathString */ 15361 abstract String getResourcePath(); 15362 15363 // Need installer lock especially for dex file removal. 15364 abstract void cleanUpResourcesLI(); 15365 abstract boolean doPostDeleteLI(boolean delete); 15366 15367 /** 15368 * Called before the source arguments are copied. This is used mostly 15369 * for MoveParams when it needs to read the source file to put it in the 15370 * destination. 15371 */ 15372 int doPreCopy() { 15373 return PackageManager.INSTALL_SUCCEEDED; 15374 } 15375 15376 /** 15377 * Called after the source arguments are copied. This is used mostly for 15378 * MoveParams when it needs to read the source file to put it in the 15379 * destination. 15380 */ 15381 int doPostCopy(int uid) { 15382 return PackageManager.INSTALL_SUCCEEDED; 15383 } 15384 15385 protected boolean isFwdLocked() { 15386 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15387 } 15388 15389 protected boolean isExternalAsec() { 15390 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15391 } 15392 15393 protected boolean isEphemeral() { 15394 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15395 } 15396 15397 UserHandle getUser() { 15398 return user; 15399 } 15400 } 15401 15402 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15403 if (!allCodePaths.isEmpty()) { 15404 if (instructionSets == null) { 15405 throw new IllegalStateException("instructionSet == null"); 15406 } 15407 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15408 for (String codePath : allCodePaths) { 15409 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15410 try { 15411 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15412 } catch (InstallerException ignored) { 15413 } 15414 } 15415 } 15416 } 15417 } 15418 15419 /** 15420 * Logic to handle installation of non-ASEC applications, including copying 15421 * and renaming logic. 15422 */ 15423 class FileInstallArgs extends InstallArgs { 15424 private File codeFile; 15425 private File resourceFile; 15426 15427 // Example topology: 15428 // /data/app/com.example/base.apk 15429 // /data/app/com.example/split_foo.apk 15430 // /data/app/com.example/lib/arm/libfoo.so 15431 // /data/app/com.example/lib/arm64/libfoo.so 15432 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15433 15434 /** New install */ 15435 FileInstallArgs(InstallParams params) { 15436 super(params.origin, params.move, params.observer, params.installFlags, 15437 params.installerPackageName, params.volumeUuid, 15438 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15439 params.grantedRuntimePermissions, 15440 params.traceMethod, params.traceCookie, params.signingDetails, 15441 params.installReason); 15442 if (isFwdLocked()) { 15443 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15444 } 15445 } 15446 15447 /** Existing install */ 15448 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15449 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15450 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15451 PackageManager.INSTALL_REASON_UNKNOWN); 15452 this.codeFile = (codePath != null) ? new File(codePath) : null; 15453 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15454 } 15455 15456 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15457 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15458 try { 15459 return doCopyApk(imcs, temp); 15460 } finally { 15461 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15462 } 15463 } 15464 15465 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15466 if (origin.staged) { 15467 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15468 codeFile = origin.file; 15469 resourceFile = origin.file; 15470 return PackageManager.INSTALL_SUCCEEDED; 15471 } 15472 15473 try { 15474 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15475 final File tempDir = 15476 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15477 codeFile = tempDir; 15478 resourceFile = tempDir; 15479 } catch (IOException e) { 15480 Slog.w(TAG, "Failed to create copy file: " + e); 15481 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15482 } 15483 15484 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15485 @Override 15486 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15487 if (!FileUtils.isValidExtFilename(name)) { 15488 throw new IllegalArgumentException("Invalid filename: " + name); 15489 } 15490 try { 15491 final File file = new File(codeFile, name); 15492 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15493 O_RDWR | O_CREAT, 0644); 15494 Os.chmod(file.getAbsolutePath(), 0644); 15495 return new ParcelFileDescriptor(fd); 15496 } catch (ErrnoException e) { 15497 throw new RemoteException("Failed to open: " + e.getMessage()); 15498 } 15499 } 15500 }; 15501 15502 int ret = PackageManager.INSTALL_SUCCEEDED; 15503 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15504 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15505 Slog.e(TAG, "Failed to copy package"); 15506 return ret; 15507 } 15508 15509 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15510 NativeLibraryHelper.Handle handle = null; 15511 try { 15512 handle = NativeLibraryHelper.Handle.create(codeFile); 15513 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15514 abiOverride); 15515 } catch (IOException e) { 15516 Slog.e(TAG, "Copying native libraries failed", e); 15517 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15518 } finally { 15519 IoUtils.closeQuietly(handle); 15520 } 15521 15522 return ret; 15523 } 15524 15525 int doPreInstall(int status) { 15526 if (status != PackageManager.INSTALL_SUCCEEDED) { 15527 cleanUp(); 15528 } 15529 return status; 15530 } 15531 15532 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15533 if (status != PackageManager.INSTALL_SUCCEEDED) { 15534 cleanUp(); 15535 return false; 15536 } 15537 15538 final File targetDir = codeFile.getParentFile(); 15539 final File beforeCodeFile = codeFile; 15540 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15541 15542 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15543 try { 15544 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15545 } catch (ErrnoException e) { 15546 Slog.w(TAG, "Failed to rename", e); 15547 return false; 15548 } 15549 15550 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15551 Slog.w(TAG, "Failed to restorecon"); 15552 return false; 15553 } 15554 15555 // Reflect the rename internally 15556 codeFile = afterCodeFile; 15557 resourceFile = afterCodeFile; 15558 15559 // Reflect the rename in scanned details 15560 try { 15561 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15562 } catch (IOException e) { 15563 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15564 return false; 15565 } 15566 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15567 afterCodeFile, pkg.baseCodePath)); 15568 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15569 afterCodeFile, pkg.splitCodePaths)); 15570 15571 // Reflect the rename in app info 15572 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15573 pkg.setApplicationInfoCodePath(pkg.codePath); 15574 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15575 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15576 pkg.setApplicationInfoResourcePath(pkg.codePath); 15577 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15578 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15579 15580 return true; 15581 } 15582 15583 int doPostInstall(int status, int uid) { 15584 if (status != PackageManager.INSTALL_SUCCEEDED) { 15585 cleanUp(); 15586 } 15587 return status; 15588 } 15589 15590 @Override 15591 String getCodePath() { 15592 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15593 } 15594 15595 @Override 15596 String getResourcePath() { 15597 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15598 } 15599 15600 private boolean cleanUp() { 15601 if (codeFile == null || !codeFile.exists()) { 15602 return false; 15603 } 15604 15605 removeCodePathLI(codeFile); 15606 15607 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15608 resourceFile.delete(); 15609 } 15610 15611 return true; 15612 } 15613 15614 void cleanUpResourcesLI() { 15615 // Try enumerating all code paths before deleting 15616 List<String> allCodePaths = Collections.EMPTY_LIST; 15617 if (codeFile != null && codeFile.exists()) { 15618 try { 15619 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15620 allCodePaths = pkg.getAllCodePaths(); 15621 } catch (PackageParserException e) { 15622 // Ignored; we tried our best 15623 } 15624 } 15625 15626 cleanUp(); 15627 removeDexFiles(allCodePaths, instructionSets); 15628 } 15629 15630 boolean doPostDeleteLI(boolean delete) { 15631 // XXX err, shouldn't we respect the delete flag? 15632 cleanUpResourcesLI(); 15633 return true; 15634 } 15635 } 15636 15637 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15638 PackageManagerException { 15639 if (copyRet < 0) { 15640 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15641 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15642 throw new PackageManagerException(copyRet, message); 15643 } 15644 } 15645 } 15646 15647 /** 15648 * Extract the StorageManagerService "container ID" from the full code path of an 15649 * .apk. 15650 */ 15651 static String cidFromCodePath(String fullCodePath) { 15652 int eidx = fullCodePath.lastIndexOf("/"); 15653 String subStr1 = fullCodePath.substring(0, eidx); 15654 int sidx = subStr1.lastIndexOf("/"); 15655 return subStr1.substring(sidx+1, eidx); 15656 } 15657 15658 /** 15659 * Logic to handle movement of existing installed applications. 15660 */ 15661 class MoveInstallArgs extends InstallArgs { 15662 private File codeFile; 15663 private File resourceFile; 15664 15665 /** New install */ 15666 MoveInstallArgs(InstallParams params) { 15667 super(params.origin, params.move, params.observer, params.installFlags, 15668 params.installerPackageName, params.volumeUuid, 15669 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15670 params.grantedRuntimePermissions, 15671 params.traceMethod, params.traceCookie, params.signingDetails, 15672 params.installReason); 15673 } 15674 15675 int copyApk(IMediaContainerService imcs, boolean temp) { 15676 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15677 + move.fromUuid + " to " + move.toUuid); 15678 synchronized (mInstaller) { 15679 try { 15680 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15681 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15682 } catch (InstallerException e) { 15683 Slog.w(TAG, "Failed to move app", e); 15684 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15685 } 15686 } 15687 15688 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15689 resourceFile = codeFile; 15690 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15691 15692 return PackageManager.INSTALL_SUCCEEDED; 15693 } 15694 15695 int doPreInstall(int status) { 15696 if (status != PackageManager.INSTALL_SUCCEEDED) { 15697 cleanUp(move.toUuid); 15698 } 15699 return status; 15700 } 15701 15702 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15703 if (status != PackageManager.INSTALL_SUCCEEDED) { 15704 cleanUp(move.toUuid); 15705 return false; 15706 } 15707 15708 // Reflect the move in app info 15709 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15710 pkg.setApplicationInfoCodePath(pkg.codePath); 15711 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15712 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15713 pkg.setApplicationInfoResourcePath(pkg.codePath); 15714 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15715 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15716 15717 return true; 15718 } 15719 15720 int doPostInstall(int status, int uid) { 15721 if (status == PackageManager.INSTALL_SUCCEEDED) { 15722 cleanUp(move.fromUuid); 15723 } else { 15724 cleanUp(move.toUuid); 15725 } 15726 return status; 15727 } 15728 15729 @Override 15730 String getCodePath() { 15731 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15732 } 15733 15734 @Override 15735 String getResourcePath() { 15736 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15737 } 15738 15739 private boolean cleanUp(String volumeUuid) { 15740 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15741 move.dataAppName); 15742 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15743 final int[] userIds = sUserManager.getUserIds(); 15744 synchronized (mInstallLock) { 15745 // Clean up both app data and code 15746 // All package moves are frozen until finished 15747 for (int userId : userIds) { 15748 try { 15749 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15750 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15751 } catch (InstallerException e) { 15752 Slog.w(TAG, String.valueOf(e)); 15753 } 15754 } 15755 removeCodePathLI(codeFile); 15756 } 15757 return true; 15758 } 15759 15760 void cleanUpResourcesLI() { 15761 throw new UnsupportedOperationException(); 15762 } 15763 15764 boolean doPostDeleteLI(boolean delete) { 15765 throw new UnsupportedOperationException(); 15766 } 15767 } 15768 15769 static String getAsecPackageName(String packageCid) { 15770 int idx = packageCid.lastIndexOf("-"); 15771 if (idx == -1) { 15772 return packageCid; 15773 } 15774 return packageCid.substring(0, idx); 15775 } 15776 15777 // Utility method used to create code paths based on package name and available index. 15778 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15779 String idxStr = ""; 15780 int idx = 1; 15781 // Fall back to default value of idx=1 if prefix is not 15782 // part of oldCodePath 15783 if (oldCodePath != null) { 15784 String subStr = oldCodePath; 15785 // Drop the suffix right away 15786 if (suffix != null && subStr.endsWith(suffix)) { 15787 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15788 } 15789 // If oldCodePath already contains prefix find out the 15790 // ending index to either increment or decrement. 15791 int sidx = subStr.lastIndexOf(prefix); 15792 if (sidx != -1) { 15793 subStr = subStr.substring(sidx + prefix.length()); 15794 if (subStr != null) { 15795 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15796 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15797 } 15798 try { 15799 idx = Integer.parseInt(subStr); 15800 if (idx <= 1) { 15801 idx++; 15802 } else { 15803 idx--; 15804 } 15805 } catch(NumberFormatException e) { 15806 } 15807 } 15808 } 15809 } 15810 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15811 return prefix + idxStr; 15812 } 15813 15814 private File getNextCodePath(File targetDir, String packageName) { 15815 File result; 15816 SecureRandom random = new SecureRandom(); 15817 byte[] bytes = new byte[16]; 15818 do { 15819 random.nextBytes(bytes); 15820 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15821 result = new File(targetDir, packageName + "-" + suffix); 15822 } while (result.exists()); 15823 return result; 15824 } 15825 15826 // Utility method that returns the relative package path with respect 15827 // to the installation directory. Like say for /data/data/com.test-1.apk 15828 // string com.test-1 is returned. 15829 static String deriveCodePathName(String codePath) { 15830 if (codePath == null) { 15831 return null; 15832 } 15833 final File codeFile = new File(codePath); 15834 final String name = codeFile.getName(); 15835 if (codeFile.isDirectory()) { 15836 return name; 15837 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15838 final int lastDot = name.lastIndexOf('.'); 15839 return name.substring(0, lastDot); 15840 } else { 15841 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15842 return null; 15843 } 15844 } 15845 15846 static class PackageInstalledInfo { 15847 String name; 15848 int uid; 15849 // The set of users that originally had this package installed. 15850 int[] origUsers; 15851 // The set of users that now have this package installed. 15852 int[] newUsers; 15853 PackageParser.Package pkg; 15854 int returnCode; 15855 String returnMsg; 15856 String installerPackageName; 15857 PackageRemovedInfo removedInfo; 15858 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15859 15860 public void setError(int code, String msg) { 15861 setReturnCode(code); 15862 setReturnMessage(msg); 15863 Slog.w(TAG, msg); 15864 } 15865 15866 public void setError(String msg, PackageParserException e) { 15867 setReturnCode(e.error); 15868 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15869 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15870 for (int i = 0; i < childCount; i++) { 15871 addedChildPackages.valueAt(i).setError(msg, e); 15872 } 15873 Slog.w(TAG, msg, e); 15874 } 15875 15876 public void setError(String msg, PackageManagerException e) { 15877 returnCode = e.error; 15878 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15879 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15880 for (int i = 0; i < childCount; i++) { 15881 addedChildPackages.valueAt(i).setError(msg, e); 15882 } 15883 Slog.w(TAG, msg, e); 15884 } 15885 15886 public void setReturnCode(int returnCode) { 15887 this.returnCode = returnCode; 15888 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15889 for (int i = 0; i < childCount; i++) { 15890 addedChildPackages.valueAt(i).returnCode = returnCode; 15891 } 15892 } 15893 15894 private void setReturnMessage(String returnMsg) { 15895 this.returnMsg = returnMsg; 15896 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15897 for (int i = 0; i < childCount; i++) { 15898 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15899 } 15900 } 15901 15902 // In some error cases we want to convey more info back to the observer 15903 String origPackage; 15904 String origPermission; 15905 } 15906 15907 /* 15908 * Install a non-existing package. 15909 */ 15910 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15911 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15912 String volumeUuid, PackageInstalledInfo res, int installReason) { 15913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15914 15915 // Remember this for later, in case we need to rollback this install 15916 String pkgName = pkg.packageName; 15917 15918 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15919 15920 synchronized(mPackages) { 15921 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15922 if (renamedPackage != null) { 15923 // A package with the same name is already installed, though 15924 // it has been renamed to an older name. The package we 15925 // are trying to install should be installed as an update to 15926 // the existing one, but that has not been requested, so bail. 15927 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15928 + " without first uninstalling package running as " 15929 + renamedPackage); 15930 return; 15931 } 15932 if (mPackages.containsKey(pkgName)) { 15933 // Don't allow installation over an existing package with the same name. 15934 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15935 + " without first uninstalling."); 15936 return; 15937 } 15938 } 15939 15940 try { 15941 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15942 System.currentTimeMillis(), user); 15943 15944 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15945 15946 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15947 prepareAppDataAfterInstallLIF(newPackage); 15948 15949 } else { 15950 // Remove package from internal structures, but keep around any 15951 // data that might have already existed 15952 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15953 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15954 } 15955 } catch (PackageManagerException e) { 15956 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15957 } 15958 15959 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15960 } 15961 15962 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15963 try (DigestInputStream digestStream = 15964 new DigestInputStream(new FileInputStream(file), digest)) { 15965 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15966 } 15967 } 15968 15969 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15970 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15971 PackageInstalledInfo res, int installReason) { 15972 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15973 15974 final PackageParser.Package oldPackage; 15975 final PackageSetting ps; 15976 final String pkgName = pkg.packageName; 15977 final int[] allUsers; 15978 final int[] installedUsers; 15979 15980 synchronized(mPackages) { 15981 oldPackage = mPackages.get(pkgName); 15982 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15983 15984 // don't allow upgrade to target a release SDK from a pre-release SDK 15985 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15986 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15987 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15988 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15989 if (oldTargetsPreRelease 15990 && !newTargetsPreRelease 15991 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15992 Slog.w(TAG, "Can't install package targeting released sdk"); 15993 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15994 return; 15995 } 15996 15997 ps = mSettings.mPackages.get(pkgName); 15998 15999 // verify signatures are valid 16000 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16001 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 16002 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 16003 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16004 "New package not signed by keys specified by upgrade-keysets: " 16005 + pkgName); 16006 return; 16007 } 16008 } else { 16009 // default to original signature matching 16010 if (compareSignatures(oldPackage.mSigningDetails.signatures, 16011 pkg.mSigningDetails.signatures) 16012 != PackageManager.SIGNATURE_MATCH) { 16013 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16014 "New package has a different signature: " + pkgName); 16015 return; 16016 } 16017 } 16018 16019 // don't allow a system upgrade unless the upgrade hash matches 16020 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 16021 byte[] digestBytes = null; 16022 try { 16023 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 16024 updateDigest(digest, new File(pkg.baseCodePath)); 16025 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 16026 for (String path : pkg.splitCodePaths) { 16027 updateDigest(digest, new File(path)); 16028 } 16029 } 16030 digestBytes = digest.digest(); 16031 } catch (NoSuchAlgorithmException | IOException e) { 16032 res.setError(INSTALL_FAILED_INVALID_APK, 16033 "Could not compute hash: " + pkgName); 16034 return; 16035 } 16036 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 16037 res.setError(INSTALL_FAILED_INVALID_APK, 16038 "New package fails restrict-update check: " + pkgName); 16039 return; 16040 } 16041 // retain upgrade restriction 16042 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 16043 } 16044 16045 // Check for shared user id changes 16046 String invalidPackageName = 16047 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 16048 if (invalidPackageName != null) { 16049 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 16050 "Package " + invalidPackageName + " tried to change user " 16051 + oldPackage.mSharedUserId); 16052 return; 16053 } 16054 16055 // check if the new package supports all of the abis which the old package supports 16056 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 16057 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 16058 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 16059 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16060 "Update to package " + pkgName + " doesn't support multi arch"); 16061 return; 16062 } 16063 16064 // In case of rollback, remember per-user/profile install state 16065 allUsers = sUserManager.getUserIds(); 16066 installedUsers = ps.queryInstalledUsers(allUsers, true); 16067 16068 // don't allow an upgrade from full to ephemeral 16069 if (isInstantApp) { 16070 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 16071 for (int currentUser : allUsers) { 16072 if (!ps.getInstantApp(currentUser)) { 16073 // can't downgrade from full to instant 16074 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16075 + " for user: " + currentUser); 16076 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16077 return; 16078 } 16079 } 16080 } else if (!ps.getInstantApp(user.getIdentifier())) { 16081 // can't downgrade from full to instant 16082 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 16083 + " for user: " + user.getIdentifier()); 16084 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16085 return; 16086 } 16087 } 16088 } 16089 16090 // Update what is removed 16091 res.removedInfo = new PackageRemovedInfo(this); 16092 res.removedInfo.uid = oldPackage.applicationInfo.uid; 16093 res.removedInfo.removedPackage = oldPackage.packageName; 16094 res.removedInfo.installerPackageName = ps.installerPackageName; 16095 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 16096 res.removedInfo.isUpdate = true; 16097 res.removedInfo.origUsers = installedUsers; 16098 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 16099 for (int i = 0; i < installedUsers.length; i++) { 16100 final int userId = installedUsers[i]; 16101 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 16102 } 16103 16104 final int childCount = (oldPackage.childPackages != null) 16105 ? oldPackage.childPackages.size() : 0; 16106 for (int i = 0; i < childCount; i++) { 16107 boolean childPackageUpdated = false; 16108 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 16109 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16110 if (res.addedChildPackages != null) { 16111 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16112 if (childRes != null) { 16113 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 16114 childRes.removedInfo.removedPackage = childPkg.packageName; 16115 if (childPs != null) { 16116 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16117 } 16118 childRes.removedInfo.isUpdate = true; 16119 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 16120 childPackageUpdated = true; 16121 } 16122 } 16123 if (!childPackageUpdated) { 16124 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 16125 childRemovedRes.removedPackage = childPkg.packageName; 16126 if (childPs != null) { 16127 childRemovedRes.installerPackageName = childPs.installerPackageName; 16128 } 16129 childRemovedRes.isUpdate = false; 16130 childRemovedRes.dataRemoved = true; 16131 synchronized (mPackages) { 16132 if (childPs != null) { 16133 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 16134 } 16135 } 16136 if (res.removedInfo.removedChildPackages == null) { 16137 res.removedInfo.removedChildPackages = new ArrayMap<>(); 16138 } 16139 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 16140 } 16141 } 16142 16143 boolean sysPkg = (isSystemApp(oldPackage)); 16144 if (sysPkg) { 16145 // Set the system/privileged/oem/vendor/product flags as needed 16146 final boolean privileged = 16147 (oldPackage.applicationInfo.privateFlags 16148 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 16149 final boolean oem = 16150 (oldPackage.applicationInfo.privateFlags 16151 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 16152 final boolean vendor = 16153 (oldPackage.applicationInfo.privateFlags 16154 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 16155 final boolean product = 16156 (oldPackage.applicationInfo.privateFlags 16157 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 16158 final @ParseFlags int systemParseFlags = parseFlags; 16159 final @ScanFlags int systemScanFlags = scanFlags 16160 | SCAN_AS_SYSTEM 16161 | (privileged ? SCAN_AS_PRIVILEGED : 0) 16162 | (oem ? SCAN_AS_OEM : 0) 16163 | (vendor ? SCAN_AS_VENDOR : 0) 16164 | (product ? SCAN_AS_PRODUCT : 0); 16165 16166 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 16167 user, allUsers, installerPackageName, res, installReason); 16168 } else { 16169 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 16170 user, allUsers, installerPackageName, res, installReason); 16171 } 16172 } 16173 16174 @Override 16175 public List<String> getPreviousCodePaths(String packageName) { 16176 final int callingUid = Binder.getCallingUid(); 16177 final List<String> result = new ArrayList<>(); 16178 if (getInstantAppPackageName(callingUid) != null) { 16179 return result; 16180 } 16181 final PackageSetting ps = mSettings.mPackages.get(packageName); 16182 if (ps != null 16183 && ps.oldCodePaths != null 16184 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 16185 result.addAll(ps.oldCodePaths); 16186 } 16187 return result; 16188 } 16189 16190 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 16191 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16192 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 16193 String installerPackageName, PackageInstalledInfo res, int installReason) { 16194 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 16195 + deletedPackage); 16196 16197 String pkgName = deletedPackage.packageName; 16198 boolean deletedPkg = true; 16199 boolean addedPkg = false; 16200 boolean updatedSettings = false; 16201 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 16202 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16203 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16204 16205 final long origUpdateTime = (pkg.mExtras != null) 16206 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 16207 16208 // First delete the existing package while retaining the data directory 16209 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16210 res.removedInfo, true, pkg)) { 16211 // If the existing package wasn't successfully deleted 16212 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 16213 deletedPkg = false; 16214 } else { 16215 // Successfully deleted the old package; proceed with replace. 16216 16217 // If deleted package lived in a container, give users a chance to 16218 // relinquish resources before killing. 16219 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 16220 if (DEBUG_INSTALL) { 16221 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 16222 } 16223 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 16224 final ArrayList<String> pkgList = new ArrayList<String>(1); 16225 pkgList.add(deletedPackage.applicationInfo.packageName); 16226 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16227 } 16228 16229 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16230 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16231 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16232 16233 try { 16234 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 16235 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 16236 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16237 installReason); 16238 16239 // Update the in-memory copy of the previous code paths. 16240 PackageSetting ps = mSettings.mPackages.get(pkgName); 16241 if (!killApp) { 16242 if (ps.oldCodePaths == null) { 16243 ps.oldCodePaths = new ArraySet<>(); 16244 } 16245 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 16246 if (deletedPackage.splitCodePaths != null) { 16247 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16248 } 16249 } else { 16250 ps.oldCodePaths = null; 16251 } 16252 if (ps.childPackageNames != null) { 16253 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16254 final String childPkgName = ps.childPackageNames.get(i); 16255 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16256 childPs.oldCodePaths = ps.oldCodePaths; 16257 } 16258 } 16259 // set instant app status, but, only if it's explicitly specified 16260 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16261 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16262 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16263 prepareAppDataAfterInstallLIF(newPackage); 16264 addedPkg = true; 16265 mDexManager.notifyPackageUpdated(newPackage.packageName, 16266 newPackage.baseCodePath, newPackage.splitCodePaths); 16267 } catch (PackageManagerException e) { 16268 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16269 } 16270 } 16271 16272 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16273 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16274 16275 // Revert all internal state mutations and added folders for the failed install 16276 if (addedPkg) { 16277 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16278 res.removedInfo, true, null); 16279 } 16280 16281 // Restore the old package 16282 if (deletedPkg) { 16283 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16284 File restoreFile = new File(deletedPackage.codePath); 16285 // Parse old package 16286 boolean oldExternal = isExternal(deletedPackage); 16287 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16288 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16289 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16290 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16291 try { 16292 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16293 null); 16294 } catch (PackageManagerException e) { 16295 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16296 + e.getMessage()); 16297 return; 16298 } 16299 16300 synchronized (mPackages) { 16301 // Ensure the installer package name up to date 16302 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16303 16304 // Update permissions for restored package 16305 mPermissionManager.updatePermissions( 16306 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16307 mPermissionCallback); 16308 16309 mSettings.writeLPr(); 16310 } 16311 16312 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16313 } 16314 } else { 16315 synchronized (mPackages) { 16316 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16317 if (ps != null) { 16318 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16319 if (res.removedInfo.removedChildPackages != null) { 16320 final int childCount = res.removedInfo.removedChildPackages.size(); 16321 // Iterate in reverse as we may modify the collection 16322 for (int i = childCount - 1; i >= 0; i--) { 16323 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16324 if (res.addedChildPackages.containsKey(childPackageName)) { 16325 res.removedInfo.removedChildPackages.removeAt(i); 16326 } else { 16327 PackageRemovedInfo childInfo = res.removedInfo 16328 .removedChildPackages.valueAt(i); 16329 childInfo.removedForAllUsers = mPackages.get( 16330 childInfo.removedPackage) == null; 16331 } 16332 } 16333 } 16334 } 16335 } 16336 } 16337 } 16338 16339 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16340 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16341 final @ScanFlags int scanFlags, UserHandle user, 16342 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16343 int installReason) { 16344 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16345 + ", old=" + deletedPackage); 16346 16347 final boolean disabledSystem; 16348 16349 // Remove existing system package 16350 removePackageLI(deletedPackage, true); 16351 16352 synchronized (mPackages) { 16353 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16354 } 16355 if (!disabledSystem) { 16356 // We didn't need to disable the .apk as a current system package, 16357 // which means we are replacing another update that is already 16358 // installed. We need to make sure to delete the older one's .apk. 16359 res.removedInfo.args = createInstallArgsForExisting(0, 16360 deletedPackage.applicationInfo.getCodePath(), 16361 deletedPackage.applicationInfo.getResourcePath(), 16362 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16363 } else { 16364 res.removedInfo.args = null; 16365 } 16366 16367 // Successfully disabled the old package. Now proceed with re-installation 16368 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16369 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16370 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16371 16372 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16373 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16374 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16375 16376 PackageParser.Package newPackage = null; 16377 try { 16378 // Add the package to the internal data structures 16379 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16380 16381 // Set the update and install times 16382 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16383 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16384 System.currentTimeMillis()); 16385 16386 // Update the package dynamic state if succeeded 16387 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16388 // Now that the install succeeded make sure we remove data 16389 // directories for any child package the update removed. 16390 final int deletedChildCount = (deletedPackage.childPackages != null) 16391 ? deletedPackage.childPackages.size() : 0; 16392 final int newChildCount = (newPackage.childPackages != null) 16393 ? newPackage.childPackages.size() : 0; 16394 for (int i = 0; i < deletedChildCount; i++) { 16395 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16396 boolean childPackageDeleted = true; 16397 for (int j = 0; j < newChildCount; j++) { 16398 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16399 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16400 childPackageDeleted = false; 16401 break; 16402 } 16403 } 16404 if (childPackageDeleted) { 16405 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16406 deletedChildPkg.packageName); 16407 if (ps != null && res.removedInfo.removedChildPackages != null) { 16408 PackageRemovedInfo removedChildRes = res.removedInfo 16409 .removedChildPackages.get(deletedChildPkg.packageName); 16410 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16411 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16412 } 16413 } 16414 } 16415 16416 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16417 installReason); 16418 prepareAppDataAfterInstallLIF(newPackage); 16419 16420 mDexManager.notifyPackageUpdated(newPackage.packageName, 16421 newPackage.baseCodePath, newPackage.splitCodePaths); 16422 } 16423 } catch (PackageManagerException e) { 16424 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16425 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16426 } 16427 16428 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16429 // Re installation failed. Restore old information 16430 // Remove new pkg information 16431 if (newPackage != null) { 16432 removeInstalledPackageLI(newPackage, true); 16433 } 16434 // Add back the old system package 16435 try { 16436 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16437 } catch (PackageManagerException e) { 16438 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16439 } 16440 16441 synchronized (mPackages) { 16442 if (disabledSystem) { 16443 enableSystemPackageLPw(deletedPackage); 16444 } 16445 16446 // Ensure the installer package name up to date 16447 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16448 16449 // Update permissions for restored package 16450 mPermissionManager.updatePermissions( 16451 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16452 mPermissionCallback); 16453 16454 mSettings.writeLPr(); 16455 } 16456 16457 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16458 + " after failed upgrade"); 16459 } 16460 } 16461 16462 /** 16463 * Checks whether the parent or any of the child packages have a change shared 16464 * user. For a package to be a valid update the shred users of the parent and 16465 * the children should match. We may later support changing child shared users. 16466 * @param oldPkg The updated package. 16467 * @param newPkg The update package. 16468 * @return The shared user that change between the versions. 16469 */ 16470 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16471 PackageParser.Package newPkg) { 16472 // Check parent shared user 16473 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16474 return newPkg.packageName; 16475 } 16476 // Check child shared users 16477 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16478 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16479 for (int i = 0; i < newChildCount; i++) { 16480 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16481 // If this child was present, did it have the same shared user? 16482 for (int j = 0; j < oldChildCount; j++) { 16483 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16484 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16485 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16486 return newChildPkg.packageName; 16487 } 16488 } 16489 } 16490 return null; 16491 } 16492 16493 private void removeNativeBinariesLI(PackageSetting ps) { 16494 // Remove the lib path for the parent package 16495 if (ps != null) { 16496 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16497 // Remove the lib path for the child packages 16498 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16499 for (int i = 0; i < childCount; i++) { 16500 PackageSetting childPs = null; 16501 synchronized (mPackages) { 16502 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16503 } 16504 if (childPs != null) { 16505 NativeLibraryHelper.removeNativeBinariesLI(childPs 16506 .legacyNativeLibraryPathString); 16507 } 16508 } 16509 } 16510 } 16511 16512 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16513 // Enable the parent package 16514 mSettings.enableSystemPackageLPw(pkg.packageName); 16515 // Enable the child packages 16516 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16517 for (int i = 0; i < childCount; i++) { 16518 PackageParser.Package childPkg = pkg.childPackages.get(i); 16519 mSettings.enableSystemPackageLPw(childPkg.packageName); 16520 } 16521 } 16522 16523 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16524 PackageParser.Package newPkg) { 16525 // Disable the parent package (parent always replaced) 16526 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16527 // Disable the child packages 16528 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16529 for (int i = 0; i < childCount; i++) { 16530 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16531 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16532 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16533 } 16534 return disabled; 16535 } 16536 16537 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16538 String installerPackageName) { 16539 // Enable the parent package 16540 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16541 // Enable the child packages 16542 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16543 for (int i = 0; i < childCount; i++) { 16544 PackageParser.Package childPkg = pkg.childPackages.get(i); 16545 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16546 } 16547 } 16548 16549 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16550 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16551 // Update the parent package setting 16552 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16553 res, user, installReason); 16554 // Update the child packages setting 16555 final int childCount = (newPackage.childPackages != null) 16556 ? newPackage.childPackages.size() : 0; 16557 for (int i = 0; i < childCount; i++) { 16558 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16559 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16560 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16561 childRes.origUsers, childRes, user, installReason); 16562 } 16563 } 16564 16565 private void updateSettingsInternalLI(PackageParser.Package pkg, 16566 String installerPackageName, int[] allUsers, int[] installedForUsers, 16567 PackageInstalledInfo res, UserHandle user, int installReason) { 16568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16569 16570 String pkgName = pkg.packageName; 16571 synchronized (mPackages) { 16572 //write settings. the installStatus will be incomplete at this stage. 16573 //note that the new package setting would have already been 16574 //added to mPackages. It hasn't been persisted yet. 16575 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16576 // TODO: Remove this write? It's also written at the end of this method 16577 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16578 mSettings.writeLPr(); 16579 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16580 } 16581 16582 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16583 synchronized (mPackages) { 16584// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16585 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16586 mPermissionCallback); 16587 // For system-bundled packages, we assume that installing an upgraded version 16588 // of the package implies that the user actually wants to run that new code, 16589 // so we enable the package. 16590 PackageSetting ps = mSettings.mPackages.get(pkgName); 16591 final int userId = user.getIdentifier(); 16592 if (ps != null) { 16593 if (isSystemApp(pkg)) { 16594 if (DEBUG_INSTALL) { 16595 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16596 } 16597 // Enable system package for requested users 16598 if (res.origUsers != null) { 16599 for (int origUserId : res.origUsers) { 16600 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16601 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16602 origUserId, installerPackageName); 16603 } 16604 } 16605 } 16606 // Also convey the prior install/uninstall state 16607 if (allUsers != null && installedForUsers != null) { 16608 for (int currentUserId : allUsers) { 16609 final boolean installed = ArrayUtils.contains( 16610 installedForUsers, currentUserId); 16611 if (DEBUG_INSTALL) { 16612 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16613 } 16614 ps.setInstalled(installed, currentUserId); 16615 } 16616 // these install state changes will be persisted in the 16617 // upcoming call to mSettings.writeLPr(). 16618 } 16619 } 16620 // It's implied that when a user requests installation, they want the app to be 16621 // installed and enabled. 16622 if (userId != UserHandle.USER_ALL) { 16623 ps.setInstalled(true, userId); 16624 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16625 } 16626 16627 // When replacing an existing package, preserve the original install reason for all 16628 // users that had the package installed before. 16629 final Set<Integer> previousUserIds = new ArraySet<>(); 16630 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16631 final int installReasonCount = res.removedInfo.installReasons.size(); 16632 for (int i = 0; i < installReasonCount; i++) { 16633 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16634 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16635 ps.setInstallReason(previousInstallReason, previousUserId); 16636 previousUserIds.add(previousUserId); 16637 } 16638 } 16639 16640 // Set install reason for users that are having the package newly installed. 16641 if (userId == UserHandle.USER_ALL) { 16642 for (int currentUserId : sUserManager.getUserIds()) { 16643 if (!previousUserIds.contains(currentUserId)) { 16644 ps.setInstallReason(installReason, currentUserId); 16645 } 16646 } 16647 } else if (!previousUserIds.contains(userId)) { 16648 ps.setInstallReason(installReason, userId); 16649 } 16650 mSettings.writeKernelMappingLPr(ps); 16651 } 16652 res.name = pkgName; 16653 res.uid = pkg.applicationInfo.uid; 16654 res.pkg = pkg; 16655 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16656 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16657 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16658 //to update install status 16659 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16660 mSettings.writeLPr(); 16661 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16662 } 16663 16664 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16665 } 16666 16667 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16668 try { 16669 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16670 installPackageLI(args, res); 16671 } finally { 16672 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16673 } 16674 } 16675 16676 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16677 final int installFlags = args.installFlags; 16678 final String installerPackageName = args.installerPackageName; 16679 final String volumeUuid = args.volumeUuid; 16680 final File tmpPackageFile = new File(args.getCodePath()); 16681 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16682 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16683 || (args.volumeUuid != null)); 16684 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16685 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16686 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16687 final boolean virtualPreload = 16688 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16689 boolean replace = false; 16690 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16691 if (args.move != null) { 16692 // moving a complete application; perform an initial scan on the new install location 16693 scanFlags |= SCAN_INITIAL; 16694 } 16695 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16696 scanFlags |= SCAN_DONT_KILL_APP; 16697 } 16698 if (instantApp) { 16699 scanFlags |= SCAN_AS_INSTANT_APP; 16700 } 16701 if (fullApp) { 16702 scanFlags |= SCAN_AS_FULL_APP; 16703 } 16704 if (virtualPreload) { 16705 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16706 } 16707 16708 // Result object to be returned 16709 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16710 res.installerPackageName = installerPackageName; 16711 16712 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16713 16714 // Sanity check 16715 if (instantApp && (forwardLocked || onExternal)) { 16716 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16717 + " external=" + onExternal); 16718 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16719 return; 16720 } 16721 16722 // Retrieve PackageSettings and parse package 16723 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16724 | PackageParser.PARSE_ENFORCE_CODE 16725 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16726 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16727 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16728 PackageParser pp = new PackageParser(); 16729 pp.setSeparateProcesses(mSeparateProcesses); 16730 pp.setDisplayMetrics(mMetrics); 16731 pp.setCallback(mPackageParserCallback); 16732 16733 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16734 final PackageParser.Package pkg; 16735 try { 16736 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16737 DexMetadataHelper.validatePackageDexMetadata(pkg); 16738 } catch (PackageParserException e) { 16739 res.setError("Failed parse during installPackageLI", e); 16740 return; 16741 } finally { 16742 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16743 } 16744 16745 // Instant apps have several additional install-time checks. 16746 if (instantApp) { 16747 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16748 Slog.w(TAG, 16749 "Instant app package " + pkg.packageName + " does not target at least O"); 16750 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16751 "Instant app package must target at least O"); 16752 return; 16753 } 16754 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16755 Slog.w(TAG, "Instant app package " + pkg.packageName 16756 + " does not target targetSandboxVersion 2"); 16757 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16758 "Instant app package must use targetSandboxVersion 2"); 16759 return; 16760 } 16761 if (pkg.mSharedUserId != null) { 16762 Slog.w(TAG, "Instant app package " + pkg.packageName 16763 + " may not declare sharedUserId."); 16764 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16765 "Instant app package may not declare a sharedUserId"); 16766 return; 16767 } 16768 } 16769 16770 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16771 // Static shared libraries have synthetic package names 16772 renameStaticSharedLibraryPackage(pkg); 16773 16774 // No static shared libs on external storage 16775 if (onExternal) { 16776 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16777 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16778 "Packages declaring static-shared libs cannot be updated"); 16779 return; 16780 } 16781 } 16782 16783 // If we are installing a clustered package add results for the children 16784 if (pkg.childPackages != null) { 16785 synchronized (mPackages) { 16786 final int childCount = pkg.childPackages.size(); 16787 for (int i = 0; i < childCount; i++) { 16788 PackageParser.Package childPkg = pkg.childPackages.get(i); 16789 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16790 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16791 childRes.pkg = childPkg; 16792 childRes.name = childPkg.packageName; 16793 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16794 if (childPs != null) { 16795 childRes.origUsers = childPs.queryInstalledUsers( 16796 sUserManager.getUserIds(), true); 16797 } 16798 if ((mPackages.containsKey(childPkg.packageName))) { 16799 childRes.removedInfo = new PackageRemovedInfo(this); 16800 childRes.removedInfo.removedPackage = childPkg.packageName; 16801 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16802 } 16803 if (res.addedChildPackages == null) { 16804 res.addedChildPackages = new ArrayMap<>(); 16805 } 16806 res.addedChildPackages.put(childPkg.packageName, childRes); 16807 } 16808 } 16809 } 16810 16811 // If package doesn't declare API override, mark that we have an install 16812 // time CPU ABI override. 16813 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16814 pkg.cpuAbiOverride = args.abiOverride; 16815 } 16816 16817 String pkgName = res.name = pkg.packageName; 16818 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16819 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16820 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16821 return; 16822 } 16823 } 16824 16825 try { 16826 // either use what we've been given or parse directly from the APK 16827 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16828 pkg.setSigningDetails(args.signingDetails); 16829 } else { 16830 PackageParser.collectCertificates(pkg, parseFlags); 16831 } 16832 } catch (PackageParserException e) { 16833 res.setError("Failed collect during installPackageLI", e); 16834 return; 16835 } 16836 16837 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16838 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16839 Slog.w(TAG, "Instant app package " + pkg.packageName 16840 + " is not signed with at least APK Signature Scheme v2"); 16841 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16842 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16843 return; 16844 } 16845 16846 // Get rid of all references to package scan path via parser. 16847 pp = null; 16848 String oldCodePath = null; 16849 boolean systemApp = false; 16850 synchronized (mPackages) { 16851 // Check if installing already existing package 16852 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16853 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16854 if (pkg.mOriginalPackages != null 16855 && pkg.mOriginalPackages.contains(oldName) 16856 && mPackages.containsKey(oldName)) { 16857 // This package is derived from an original package, 16858 // and this device has been updating from that original 16859 // name. We must continue using the original name, so 16860 // rename the new package here. 16861 pkg.setPackageName(oldName); 16862 pkgName = pkg.packageName; 16863 replace = true; 16864 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16865 + oldName + " pkgName=" + pkgName); 16866 } else if (mPackages.containsKey(pkgName)) { 16867 // This package, under its official name, already exists 16868 // on the device; we should replace it. 16869 replace = true; 16870 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16871 } 16872 16873 // Child packages are installed through the parent package 16874 if (pkg.parentPackage != null) { 16875 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16876 "Package " + pkg.packageName + " is child of package " 16877 + pkg.parentPackage.parentPackage + ". Child packages " 16878 + "can be updated only through the parent package."); 16879 return; 16880 } 16881 16882 if (replace) { 16883 // Prevent apps opting out from runtime permissions 16884 PackageParser.Package oldPackage = mPackages.get(pkgName); 16885 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16886 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16887 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16888 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16889 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16890 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16891 + " doesn't support runtime permissions but the old" 16892 + " target SDK " + oldTargetSdk + " does."); 16893 return; 16894 } 16895 // Prevent persistent apps from being updated 16896 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16897 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16898 "Package " + oldPackage.packageName + " is a persistent app. " 16899 + "Persistent apps are not updateable."); 16900 return; 16901 } 16902 // Prevent apps from downgrading their targetSandbox. 16903 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16904 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16905 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16906 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16907 "Package " + pkg.packageName + " new target sandbox " 16908 + newTargetSandbox + " is incompatible with the previous value of" 16909 + oldTargetSandbox + "."); 16910 return; 16911 } 16912 16913 // Prevent installing of child packages 16914 if (oldPackage.parentPackage != null) { 16915 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16916 "Package " + pkg.packageName + " is child of package " 16917 + oldPackage.parentPackage + ". Child packages " 16918 + "can be updated only through the parent package."); 16919 return; 16920 } 16921 } 16922 } 16923 16924 PackageSetting ps = mSettings.mPackages.get(pkgName); 16925 if (ps != null) { 16926 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16927 16928 // Static shared libs have same package with different versions where 16929 // we internally use a synthetic package name to allow multiple versions 16930 // of the same package, therefore we need to compare signatures against 16931 // the package setting for the latest library version. 16932 PackageSetting signatureCheckPs = ps; 16933 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16934 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16935 if (libraryEntry != null) { 16936 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16937 } 16938 } 16939 16940 // Quick sanity check that we're signed correctly if updating; 16941 // we'll check this again later when scanning, but we want to 16942 // bail early here before tripping over redefined permissions. 16943 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16944 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16945 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16946 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16947 + pkg.packageName + " upgrade keys do not match the " 16948 + "previously installed version"); 16949 return; 16950 } 16951 } else { 16952 try { 16953 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16954 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16955 // We don't care about disabledPkgSetting on install for now. 16956 final boolean compatMatch = verifySignatures( 16957 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16958 compareRecover); 16959 // The new KeySets will be re-added later in the scanning process. 16960 if (compatMatch) { 16961 synchronized (mPackages) { 16962 ksms.removeAppKeySetDataLPw(pkg.packageName); 16963 } 16964 } 16965 } catch (PackageManagerException e) { 16966 res.setError(e.error, e.getMessage()); 16967 return; 16968 } 16969 } 16970 16971 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16972 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16973 systemApp = (ps.pkg.applicationInfo.flags & 16974 ApplicationInfo.FLAG_SYSTEM) != 0; 16975 } 16976 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16977 } 16978 16979 int N = pkg.permissions.size(); 16980 for (int i = N-1; i >= 0; i--) { 16981 final PackageParser.Permission perm = pkg.permissions.get(i); 16982 final BasePermission bp = 16983 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16984 16985 // Don't allow anyone but the system to define ephemeral permissions. 16986 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16987 && !systemApp) { 16988 Slog.w(TAG, "Non-System package " + pkg.packageName 16989 + " attempting to delcare ephemeral permission " 16990 + perm.info.name + "; Removing ephemeral."); 16991 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16992 } 16993 16994 // Check whether the newly-scanned package wants to define an already-defined perm 16995 if (bp != null) { 16996 // If the defining package is signed with our cert, it's okay. This 16997 // also includes the "updating the same package" case, of course. 16998 // "updating same package" could also involve key-rotation. 16999 final boolean sigsOk; 17000 final String sourcePackageName = bp.getSourcePackageName(); 17001 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17002 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17003 if (sourcePackageName.equals(pkg.packageName) 17004 && (ksms.shouldCheckUpgradeKeySetLocked( 17005 sourcePackageSetting, scanFlags))) { 17006 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17007 } else { 17008 sigsOk = compareSignatures( 17009 sourcePackageSetting.signatures.mSigningDetails.signatures, 17010 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 17011 } 17012 if (!sigsOk) { 17013 // If the owning package is the system itself, we log but allow 17014 // install to proceed; we fail the install on all other permission 17015 // redefinitions. 17016 if (!sourcePackageName.equals("android")) { 17017 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17018 + pkg.packageName + " attempting to redeclare permission " 17019 + perm.info.name + " already owned by " + sourcePackageName); 17020 res.origPermission = perm.info.name; 17021 res.origPackage = sourcePackageName; 17022 return; 17023 } else { 17024 Slog.w(TAG, "Package " + pkg.packageName 17025 + " attempting to redeclare system permission " 17026 + perm.info.name + "; ignoring new declaration"); 17027 pkg.permissions.remove(i); 17028 } 17029 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17030 // Prevent apps to change protection level to dangerous from any other 17031 // type as this would allow a privilege escalation where an app adds a 17032 // normal/signature permission in other app's group and later redefines 17033 // it as dangerous leading to the group auto-grant. 17034 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17035 == PermissionInfo.PROTECTION_DANGEROUS) { 17036 if (bp != null && !bp.isRuntime()) { 17037 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17038 + "non-runtime permission " + perm.info.name 17039 + " to runtime; keeping old protection level"); 17040 perm.info.protectionLevel = bp.getProtectionLevel(); 17041 } 17042 } 17043 } 17044 } 17045 } 17046 } 17047 17048 if (systemApp) { 17049 if (onExternal) { 17050 // Abort update; system app can't be replaced with app on sdcard 17051 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17052 "Cannot install updates to system apps on sdcard"); 17053 return; 17054 } else if (instantApp) { 17055 // Abort update; system app can't be replaced with an instant app 17056 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 17057 "Cannot update a system app with an instant app"); 17058 return; 17059 } 17060 } 17061 17062 if (args.move != null) { 17063 // We did an in-place move, so dex is ready to roll 17064 scanFlags |= SCAN_NO_DEX; 17065 scanFlags |= SCAN_MOVE; 17066 17067 synchronized (mPackages) { 17068 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17069 if (ps == null) { 17070 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17071 "Missing settings for moved package " + pkgName); 17072 } 17073 17074 // We moved the entire application as-is, so bring over the 17075 // previously derived ABI information. 17076 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17077 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17078 } 17079 17080 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 17081 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17082 scanFlags |= SCAN_NO_DEX; 17083 17084 try { 17085 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17086 args.abiOverride : pkg.cpuAbiOverride); 17087 final boolean extractNativeLibs = !pkg.isLibrary(); 17088 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17089 } catch (PackageManagerException pme) { 17090 Slog.e(TAG, "Error deriving application ABI", pme); 17091 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 17092 return; 17093 } 17094 17095 // Shared libraries for the package need to be updated. 17096 synchronized (mPackages) { 17097 try { 17098 updateSharedLibrariesLPr(pkg, null); 17099 } catch (PackageManagerException e) { 17100 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 17101 } 17102 } 17103 } 17104 17105 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 17106 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17107 return; 17108 } 17109 17110 if (PackageManagerServiceUtils.isApkVerityEnabled()) { 17111 String apkPath = null; 17112 synchronized (mPackages) { 17113 // Note that if the attacker managed to skip verify setup, for example by tampering 17114 // with the package settings, upon reboot we will do full apk verification when 17115 // verity is not detected. 17116 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17117 if (ps != null && ps.isPrivileged()) { 17118 apkPath = pkg.baseCodePath; 17119 } 17120 } 17121 17122 if (apkPath != null) { 17123 final VerityUtils.SetupResult result = 17124 VerityUtils.generateApkVeritySetupData(apkPath); 17125 if (result.isOk()) { 17126 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling apk verity to " + apkPath); 17127 FileDescriptor fd = result.getUnownedFileDescriptor(); 17128 try { 17129 mInstaller.installApkVerity(apkPath, fd); 17130 } catch (InstallerException e) { 17131 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17132 "Failed to set up verity: " + e); 17133 return; 17134 } finally { 17135 IoUtils.closeQuietly(fd); 17136 } 17137 } else if (result.isFailed()) { 17138 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Failed to generate verity"); 17139 return; 17140 } else { 17141 // Do nothing if verity is skipped. Will fall back to full apk verification on 17142 // reboot. 17143 } 17144 } 17145 } 17146 17147 if (!instantApp) { 17148 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17149 } else { 17150 if (DEBUG_DOMAIN_VERIFICATION) { 17151 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17152 } 17153 } 17154 17155 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 17156 "installPackageLI")) { 17157 if (replace) { 17158 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17159 // Static libs have a synthetic package name containing the version 17160 // and cannot be updated as an update would get a new package name, 17161 // unless this is the exact same version code which is useful for 17162 // development. 17163 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17164 if (existingPkg != null && 17165 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17166 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 17167 + "static-shared libs cannot be updated"); 17168 return; 17169 } 17170 } 17171 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 17172 installerPackageName, res, args.installReason); 17173 } else { 17174 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 17175 args.user, installerPackageName, volumeUuid, res, args.installReason); 17176 } 17177 } 17178 17179 // Prepare the application profiles for the new code paths. 17180 // This needs to be done before invoking dexopt so that any install-time profile 17181 // can be used for optimizations. 17182 mArtManagerService.prepareAppProfiles(pkg, resolveUserIds(args.user.getIdentifier())); 17183 17184 // Check whether we need to dexopt the app. 17185 // 17186 // NOTE: it is IMPORTANT to call dexopt: 17187 // - after doRename which will sync the package data from PackageParser.Package and its 17188 // corresponding ApplicationInfo. 17189 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17190 // uid of the application (pkg.applicationInfo.uid). 17191 // This update happens in place! 17192 // 17193 // We only need to dexopt if the package meets ALL of the following conditions: 17194 // 1) it is not forward locked. 17195 // 2) it is not on on an external ASEC container. 17196 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 17197 // 17198 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17199 // complete, so we skip this step during installation. Instead, we'll take extra time 17200 // the first time the instant app starts. It's preferred to do it this way to provide 17201 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17202 // middle of running an instant app. The default behaviour can be overridden 17203 // via gservices. 17204 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 17205 && !forwardLocked 17206 && !pkg.applicationInfo.isExternalAsec() 17207 && (!instantApp || Global.getInt(mContext.getContentResolver(), 17208 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 17209 17210 if (performDexopt) { 17211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17212 // Do not run PackageDexOptimizer through the local performDexOpt 17213 // method because `pkg` may not be in `mPackages` yet. 17214 // 17215 // Also, don't fail application installs if the dexopt step fails. 17216 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 17217 REASON_INSTALL, 17218 DexoptOptions.DEXOPT_BOOT_COMPLETE); 17219 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 17220 null /* instructionSets */, 17221 getOrCreateCompilerPackageStats(pkg), 17222 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 17223 dexoptOptions); 17224 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17225 } 17226 17227 // Notify BackgroundDexOptService that the package has been changed. 17228 // If this is an update of a package which used to fail to compile, 17229 // BackgroundDexOptService will remove it from its blacklist. 17230 // TODO: Layering violation 17231 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 17232 17233 synchronized (mPackages) { 17234 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17235 if (ps != null) { 17236 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17237 ps.setUpdateAvailable(false /*updateAvailable*/); 17238 } 17239 17240 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17241 for (int i = 0; i < childCount; i++) { 17242 PackageParser.Package childPkg = pkg.childPackages.get(i); 17243 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 17244 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17245 if (childPs != null) { 17246 childRes.newUsers = childPs.queryInstalledUsers( 17247 sUserManager.getUserIds(), true); 17248 } 17249 } 17250 17251 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17252 updateSequenceNumberLP(ps, res.newUsers); 17253 updateInstantAppInstallerLocked(pkgName); 17254 } 17255 } 17256 } 17257 17258 private void startIntentFilterVerifications(int userId, boolean replacing, 17259 PackageParser.Package pkg) { 17260 if (mIntentFilterVerifierComponent == null) { 17261 Slog.w(TAG, "No IntentFilter verification will not be done as " 17262 + "there is no IntentFilterVerifier available!"); 17263 return; 17264 } 17265 17266 final int verifierUid = getPackageUid( 17267 mIntentFilterVerifierComponent.getPackageName(), 17268 MATCH_DEBUG_TRIAGED_MISSING, 17269 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17270 17271 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17272 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17273 mHandler.sendMessage(msg); 17274 17275 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17276 for (int i = 0; i < childCount; i++) { 17277 PackageParser.Package childPkg = pkg.childPackages.get(i); 17278 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17279 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17280 mHandler.sendMessage(msg); 17281 } 17282 } 17283 17284 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17285 PackageParser.Package pkg) { 17286 int size = pkg.activities.size(); 17287 if (size == 0) { 17288 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17289 "No activity, so no need to verify any IntentFilter!"); 17290 return; 17291 } 17292 17293 final boolean hasDomainURLs = hasDomainURLs(pkg); 17294 if (!hasDomainURLs) { 17295 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17296 "No domain URLs, so no need to verify any IntentFilter!"); 17297 return; 17298 } 17299 17300 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17301 + " if any IntentFilter from the " + size 17302 + " Activities needs verification ..."); 17303 17304 int count = 0; 17305 final String packageName = pkg.packageName; 17306 17307 synchronized (mPackages) { 17308 // If this is a new install and we see that we've already run verification for this 17309 // package, we have nothing to do: it means the state was restored from backup. 17310 if (!replacing) { 17311 IntentFilterVerificationInfo ivi = 17312 mSettings.getIntentFilterVerificationLPr(packageName); 17313 if (ivi != null) { 17314 if (DEBUG_DOMAIN_VERIFICATION) { 17315 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17316 + ivi.getStatusString()); 17317 } 17318 return; 17319 } 17320 } 17321 17322 // If any filters need to be verified, then all need to be. 17323 boolean needToVerify = false; 17324 for (PackageParser.Activity a : pkg.activities) { 17325 for (ActivityIntentInfo filter : a.intents) { 17326 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17327 if (DEBUG_DOMAIN_VERIFICATION) { 17328 Slog.d(TAG, 17329 "Intent filter needs verification, so processing all filters"); 17330 } 17331 needToVerify = true; 17332 break; 17333 } 17334 } 17335 } 17336 17337 if (needToVerify) { 17338 final int verificationId = mIntentFilterVerificationToken++; 17339 for (PackageParser.Activity a : pkg.activities) { 17340 for (ActivityIntentInfo filter : a.intents) { 17341 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17342 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17343 "Verification needed for IntentFilter:" + filter.toString()); 17344 mIntentFilterVerifier.addOneIntentFilterVerification( 17345 verifierUid, userId, verificationId, filter, packageName); 17346 count++; 17347 } 17348 } 17349 } 17350 } 17351 } 17352 17353 if (count > 0) { 17354 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17355 + " IntentFilter verification" + (count > 1 ? "s" : "") 17356 + " for userId:" + userId); 17357 mIntentFilterVerifier.startVerifications(userId); 17358 } else { 17359 if (DEBUG_DOMAIN_VERIFICATION) { 17360 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17361 } 17362 } 17363 } 17364 17365 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17366 final ComponentName cn = filter.activity.getComponentName(); 17367 final String packageName = cn.getPackageName(); 17368 17369 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17370 packageName); 17371 if (ivi == null) { 17372 return true; 17373 } 17374 int status = ivi.getStatus(); 17375 switch (status) { 17376 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17377 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17378 return true; 17379 17380 default: 17381 // Nothing to do 17382 return false; 17383 } 17384 } 17385 17386 private static boolean isMultiArch(ApplicationInfo info) { 17387 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17388 } 17389 17390 private static boolean isExternal(PackageParser.Package pkg) { 17391 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17392 } 17393 17394 private static boolean isExternal(PackageSetting ps) { 17395 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17396 } 17397 17398 private static boolean isSystemApp(PackageParser.Package pkg) { 17399 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17400 } 17401 17402 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17403 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17404 } 17405 17406 private static boolean isOemApp(PackageParser.Package pkg) { 17407 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17408 } 17409 17410 private static boolean isVendorApp(PackageParser.Package pkg) { 17411 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17412 } 17413 17414 private static boolean isProductApp(PackageParser.Package pkg) { 17415 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17416 } 17417 17418 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17419 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17420 } 17421 17422 private static boolean isSystemApp(PackageSetting ps) { 17423 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17424 } 17425 17426 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17427 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17428 } 17429 17430 private int packageFlagsToInstallFlags(PackageSetting ps) { 17431 int installFlags = 0; 17432 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17433 // This existing package was an external ASEC install when we have 17434 // the external flag without a UUID 17435 installFlags |= PackageManager.INSTALL_EXTERNAL; 17436 } 17437 if (ps.isForwardLocked()) { 17438 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17439 } 17440 return installFlags; 17441 } 17442 17443 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17444 if (isExternal(pkg)) { 17445 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17446 return mSettings.getExternalVersion(); 17447 } else { 17448 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17449 } 17450 } else { 17451 return mSettings.getInternalVersion(); 17452 } 17453 } 17454 17455 private void deleteTempPackageFiles() { 17456 final FilenameFilter filter = new FilenameFilter() { 17457 public boolean accept(File dir, String name) { 17458 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17459 } 17460 }; 17461 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17462 file.delete(); 17463 } 17464 } 17465 17466 @Override 17467 public void deletePackageAsUser(String packageName, int versionCode, 17468 IPackageDeleteObserver observer, int userId, int flags) { 17469 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17470 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17471 } 17472 17473 @Override 17474 public void deletePackageVersioned(VersionedPackage versionedPackage, 17475 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17476 final int callingUid = Binder.getCallingUid(); 17477 mContext.enforceCallingOrSelfPermission( 17478 android.Manifest.permission.DELETE_PACKAGES, null); 17479 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17480 Preconditions.checkNotNull(versionedPackage); 17481 Preconditions.checkNotNull(observer); 17482 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17483 PackageManager.VERSION_CODE_HIGHEST, 17484 Long.MAX_VALUE, "versionCode must be >= -1"); 17485 17486 final String packageName = versionedPackage.getPackageName(); 17487 final long versionCode = versionedPackage.getLongVersionCode(); 17488 final String internalPackageName; 17489 synchronized (mPackages) { 17490 // Normalize package name to handle renamed packages and static libs 17491 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17492 } 17493 17494 final int uid = Binder.getCallingUid(); 17495 if (!isOrphaned(internalPackageName) 17496 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17497 try { 17498 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17499 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17500 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17501 observer.onUserActionRequired(intent); 17502 } catch (RemoteException re) { 17503 } 17504 return; 17505 } 17506 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17507 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17508 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17509 mContext.enforceCallingOrSelfPermission( 17510 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17511 "deletePackage for user " + userId); 17512 } 17513 17514 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17515 try { 17516 observer.onPackageDeleted(packageName, 17517 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17518 } catch (RemoteException re) { 17519 } 17520 return; 17521 } 17522 17523 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17524 try { 17525 observer.onPackageDeleted(packageName, 17526 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17527 } catch (RemoteException re) { 17528 } 17529 return; 17530 } 17531 17532 if (DEBUG_REMOVE) { 17533 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17534 + " deleteAllUsers: " + deleteAllUsers + " version=" 17535 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17536 ? "VERSION_CODE_HIGHEST" : versionCode)); 17537 } 17538 // Queue up an async operation since the package deletion may take a little while. 17539 mHandler.post(new Runnable() { 17540 public void run() { 17541 mHandler.removeCallbacks(this); 17542 int returnCode; 17543 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17544 boolean doDeletePackage = true; 17545 if (ps != null) { 17546 final boolean targetIsInstantApp = 17547 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17548 doDeletePackage = !targetIsInstantApp 17549 || canViewInstantApps; 17550 } 17551 if (doDeletePackage) { 17552 if (!deleteAllUsers) { 17553 returnCode = deletePackageX(internalPackageName, versionCode, 17554 userId, deleteFlags); 17555 } else { 17556 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17557 internalPackageName, users); 17558 // If nobody is blocking uninstall, proceed with delete for all users 17559 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17560 returnCode = deletePackageX(internalPackageName, versionCode, 17561 userId, deleteFlags); 17562 } else { 17563 // Otherwise uninstall individually for users with blockUninstalls=false 17564 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17565 for (int userId : users) { 17566 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17567 returnCode = deletePackageX(internalPackageName, versionCode, 17568 userId, userFlags); 17569 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17570 Slog.w(TAG, "Package delete failed for user " + userId 17571 + ", returnCode " + returnCode); 17572 } 17573 } 17574 } 17575 // The app has only been marked uninstalled for certain users. 17576 // We still need to report that delete was blocked 17577 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17578 } 17579 } 17580 } else { 17581 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17582 } 17583 try { 17584 observer.onPackageDeleted(packageName, returnCode, null); 17585 } catch (RemoteException e) { 17586 Log.i(TAG, "Observer no longer exists."); 17587 } //end catch 17588 } //end run 17589 }); 17590 } 17591 17592 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17593 if (pkg.staticSharedLibName != null) { 17594 return pkg.manifestPackageName; 17595 } 17596 return pkg.packageName; 17597 } 17598 17599 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17600 // Handle renamed packages 17601 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17602 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17603 17604 // Is this a static library? 17605 LongSparseArray<SharedLibraryEntry> versionedLib = 17606 mStaticLibsByDeclaringPackage.get(packageName); 17607 if (versionedLib == null || versionedLib.size() <= 0) { 17608 return packageName; 17609 } 17610 17611 // Figure out which lib versions the caller can see 17612 LongSparseLongArray versionsCallerCanSee = null; 17613 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17614 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17615 && callingAppId != Process.ROOT_UID) { 17616 versionsCallerCanSee = new LongSparseLongArray(); 17617 String libName = versionedLib.valueAt(0).info.getName(); 17618 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17619 if (uidPackages != null) { 17620 for (String uidPackage : uidPackages) { 17621 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17622 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17623 if (libIdx >= 0) { 17624 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17625 versionsCallerCanSee.append(libVersion, libVersion); 17626 } 17627 } 17628 } 17629 } 17630 17631 // Caller can see nothing - done 17632 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17633 return packageName; 17634 } 17635 17636 // Find the version the caller can see and the app version code 17637 SharedLibraryEntry highestVersion = null; 17638 final int versionCount = versionedLib.size(); 17639 for (int i = 0; i < versionCount; i++) { 17640 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17641 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17642 libEntry.info.getLongVersion()) < 0) { 17643 continue; 17644 } 17645 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17646 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17647 if (libVersionCode == versionCode) { 17648 return libEntry.apk; 17649 } 17650 } else if (highestVersion == null) { 17651 highestVersion = libEntry; 17652 } else if (libVersionCode > highestVersion.info 17653 .getDeclaringPackage().getLongVersionCode()) { 17654 highestVersion = libEntry; 17655 } 17656 } 17657 17658 if (highestVersion != null) { 17659 return highestVersion.apk; 17660 } 17661 17662 return packageName; 17663 } 17664 17665 boolean isCallerVerifier(int callingUid) { 17666 final int callingUserId = UserHandle.getUserId(callingUid); 17667 return mRequiredVerifierPackage != null && 17668 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17669 } 17670 17671 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17672 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17673 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17674 return true; 17675 } 17676 final int callingUserId = UserHandle.getUserId(callingUid); 17677 // If the caller installed the pkgName, then allow it to silently uninstall. 17678 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17679 return true; 17680 } 17681 17682 // Allow package verifier to silently uninstall. 17683 if (mRequiredVerifierPackage != null && 17684 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17685 return true; 17686 } 17687 17688 // Allow package uninstaller to silently uninstall. 17689 if (mRequiredUninstallerPackage != null && 17690 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17691 return true; 17692 } 17693 17694 // Allow storage manager to silently uninstall. 17695 if (mStorageManagerPackage != null && 17696 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17697 return true; 17698 } 17699 17700 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17701 // uninstall for device owner provisioning. 17702 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17703 == PERMISSION_GRANTED) { 17704 return true; 17705 } 17706 17707 return false; 17708 } 17709 17710 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17711 int[] result = EMPTY_INT_ARRAY; 17712 for (int userId : userIds) { 17713 if (getBlockUninstallForUser(packageName, userId)) { 17714 result = ArrayUtils.appendInt(result, userId); 17715 } 17716 } 17717 return result; 17718 } 17719 17720 @Override 17721 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17722 final int callingUid = Binder.getCallingUid(); 17723 if (getInstantAppPackageName(callingUid) != null 17724 && !isCallerSameApp(packageName, callingUid)) { 17725 return false; 17726 } 17727 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17728 } 17729 17730 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17731 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17732 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17733 try { 17734 if (dpm != null) { 17735 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17736 /* callingUserOnly =*/ false); 17737 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17738 : deviceOwnerComponentName.getPackageName(); 17739 // Does the package contains the device owner? 17740 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17741 // this check is probably not needed, since DO should be registered as a device 17742 // admin on some user too. (Original bug for this: b/17657954) 17743 if (packageName.equals(deviceOwnerPackageName)) { 17744 return true; 17745 } 17746 // Does it contain a device admin for any user? 17747 int[] users; 17748 if (userId == UserHandle.USER_ALL) { 17749 users = sUserManager.getUserIds(); 17750 } else { 17751 users = new int[]{userId}; 17752 } 17753 for (int i = 0; i < users.length; ++i) { 17754 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17755 return true; 17756 } 17757 } 17758 } 17759 } catch (RemoteException e) { 17760 } 17761 return false; 17762 } 17763 17764 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17765 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17766 } 17767 17768 /** 17769 * This method is an internal method that could be get invoked either 17770 * to delete an installed package or to clean up a failed installation. 17771 * After deleting an installed package, a broadcast is sent to notify any 17772 * listeners that the package has been removed. For cleaning up a failed 17773 * installation, the broadcast is not necessary since the package's 17774 * installation wouldn't have sent the initial broadcast either 17775 * The key steps in deleting a package are 17776 * deleting the package information in internal structures like mPackages, 17777 * deleting the packages base directories through installd 17778 * updating mSettings to reflect current status 17779 * persisting settings for later use 17780 * sending a broadcast if necessary 17781 */ 17782 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17783 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17784 final boolean res; 17785 17786 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17787 ? UserHandle.USER_ALL : userId; 17788 17789 if (isPackageDeviceAdmin(packageName, removeUser)) { 17790 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17791 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17792 } 17793 17794 PackageSetting uninstalledPs = null; 17795 PackageParser.Package pkg = null; 17796 17797 // for the uninstall-updates case and restricted profiles, remember the per- 17798 // user handle installed state 17799 int[] allUsers; 17800 synchronized (mPackages) { 17801 uninstalledPs = mSettings.mPackages.get(packageName); 17802 if (uninstalledPs == null) { 17803 Slog.w(TAG, "Not removing non-existent package " + packageName); 17804 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17805 } 17806 17807 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17808 && uninstalledPs.versionCode != versionCode) { 17809 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17810 + uninstalledPs.versionCode + " != " + versionCode); 17811 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17812 } 17813 17814 // Static shared libs can be declared by any package, so let us not 17815 // allow removing a package if it provides a lib others depend on. 17816 pkg = mPackages.get(packageName); 17817 17818 allUsers = sUserManager.getUserIds(); 17819 17820 if (pkg != null && pkg.staticSharedLibName != null) { 17821 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17822 pkg.staticSharedLibVersion); 17823 if (libEntry != null) { 17824 for (int currUserId : allUsers) { 17825 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17826 continue; 17827 } 17828 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17829 libEntry.info, 0, currUserId); 17830 if (!ArrayUtils.isEmpty(libClientPackages)) { 17831 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17832 + " hosting lib " + libEntry.info.getName() + " version " 17833 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17834 + " for user " + currUserId); 17835 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17836 } 17837 } 17838 } 17839 } 17840 17841 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17842 } 17843 17844 final int freezeUser; 17845 if (isUpdatedSystemApp(uninstalledPs) 17846 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17847 // We're downgrading a system app, which will apply to all users, so 17848 // freeze them all during the downgrade 17849 freezeUser = UserHandle.USER_ALL; 17850 } else { 17851 freezeUser = removeUser; 17852 } 17853 17854 synchronized (mInstallLock) { 17855 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17856 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17857 deleteFlags, "deletePackageX")) { 17858 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17859 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17860 } 17861 synchronized (mPackages) { 17862 if (res) { 17863 if (pkg != null) { 17864 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17865 } 17866 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17867 updateInstantAppInstallerLocked(packageName); 17868 } 17869 } 17870 } 17871 17872 if (res) { 17873 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17874 info.sendPackageRemovedBroadcasts(killApp); 17875 info.sendSystemPackageUpdatedBroadcasts(); 17876 info.sendSystemPackageAppearedBroadcasts(); 17877 } 17878 // Force a gc here. 17879 Runtime.getRuntime().gc(); 17880 // Delete the resources here after sending the broadcast to let 17881 // other processes clean up before deleting resources. 17882 if (info.args != null) { 17883 synchronized (mInstallLock) { 17884 info.args.doPostDeleteLI(true); 17885 } 17886 } 17887 17888 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17889 } 17890 17891 static class PackageRemovedInfo { 17892 final PackageSender packageSender; 17893 String removedPackage; 17894 String installerPackageName; 17895 int uid = -1; 17896 int removedAppId = -1; 17897 int[] origUsers; 17898 int[] removedUsers = null; 17899 int[] broadcastUsers = null; 17900 int[] instantUserIds = null; 17901 SparseArray<Integer> installReasons; 17902 boolean isRemovedPackageSystemUpdate = false; 17903 boolean isUpdate; 17904 boolean dataRemoved; 17905 boolean removedForAllUsers; 17906 boolean isStaticSharedLib; 17907 // Clean up resources deleted packages. 17908 InstallArgs args = null; 17909 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17910 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17911 17912 PackageRemovedInfo(PackageSender packageSender) { 17913 this.packageSender = packageSender; 17914 } 17915 17916 void sendPackageRemovedBroadcasts(boolean killApp) { 17917 sendPackageRemovedBroadcastInternal(killApp); 17918 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17919 for (int i = 0; i < childCount; i++) { 17920 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17921 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17922 } 17923 } 17924 17925 void sendSystemPackageUpdatedBroadcasts() { 17926 if (isRemovedPackageSystemUpdate) { 17927 sendSystemPackageUpdatedBroadcastsInternal(); 17928 final int childCount = (removedChildPackages != null) 17929 ? removedChildPackages.size() : 0; 17930 for (int i = 0; i < childCount; i++) { 17931 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17932 if (childInfo.isRemovedPackageSystemUpdate) { 17933 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17934 } 17935 } 17936 } 17937 } 17938 17939 void sendSystemPackageAppearedBroadcasts() { 17940 final int packageCount = (appearedChildPackages != null) 17941 ? appearedChildPackages.size() : 0; 17942 for (int i = 0; i < packageCount; i++) { 17943 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17944 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17945 true /*sendBootCompleted*/, false /*startReceiver*/, 17946 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17947 } 17948 } 17949 17950 private void sendSystemPackageUpdatedBroadcastsInternal() { 17951 Bundle extras = new Bundle(2); 17952 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17953 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17954 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17955 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17956 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17957 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17958 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17959 null, null, 0, removedPackage, null, null, null); 17960 if (installerPackageName != null) { 17961 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17962 removedPackage, extras, 0 /*flags*/, 17963 installerPackageName, null, null, null); 17964 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17965 removedPackage, extras, 0 /*flags*/, 17966 installerPackageName, null, null, null); 17967 } 17968 } 17969 17970 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17971 // Don't send static shared library removal broadcasts as these 17972 // libs are visible only the the apps that depend on them an one 17973 // cannot remove the library if it has a dependency. 17974 if (isStaticSharedLib) { 17975 return; 17976 } 17977 Bundle extras = new Bundle(2); 17978 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17979 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17980 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17981 if (isUpdate || isRemovedPackageSystemUpdate) { 17982 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17983 } 17984 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17985 if (removedPackage != null) { 17986 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17987 removedPackage, extras, 0, null /*targetPackage*/, null, 17988 broadcastUsers, instantUserIds); 17989 if (installerPackageName != null) { 17990 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17991 removedPackage, extras, 0 /*flags*/, 17992 installerPackageName, null, broadcastUsers, instantUserIds); 17993 } 17994 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17995 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17996 removedPackage, extras, 17997 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17998 null, null, broadcastUsers, instantUserIds); 17999 packageSender.notifyPackageRemoved(removedPackage); 18000 } 18001 } 18002 if (removedAppId >= 0) { 18003 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18004 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18005 null, null, broadcastUsers, instantUserIds); 18006 } 18007 } 18008 18009 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18010 removedUsers = userIds; 18011 if (removedUsers == null) { 18012 broadcastUsers = null; 18013 return; 18014 } 18015 18016 broadcastUsers = EMPTY_INT_ARRAY; 18017 instantUserIds = EMPTY_INT_ARRAY; 18018 for (int i = userIds.length - 1; i >= 0; --i) { 18019 final int userId = userIds[i]; 18020 if (deletedPackageSetting.getInstantApp(userId)) { 18021 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18022 } else { 18023 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18024 } 18025 } 18026 } 18027 } 18028 18029 /* 18030 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18031 * flag is not set, the data directory is removed as well. 18032 * make sure this flag is set for partially installed apps. If not its meaningless to 18033 * delete a partially installed application. 18034 */ 18035 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 18036 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18037 String packageName = ps.name; 18038 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 18039 // Retrieve object to delete permissions for shared user later on 18040 final PackageParser.Package deletedPkg; 18041 final PackageSetting deletedPs; 18042 // reader 18043 synchronized (mPackages) { 18044 deletedPkg = mPackages.get(packageName); 18045 deletedPs = mSettings.mPackages.get(packageName); 18046 if (outInfo != null) { 18047 outInfo.removedPackage = packageName; 18048 outInfo.installerPackageName = ps.installerPackageName; 18049 outInfo.isStaticSharedLib = deletedPkg != null 18050 && deletedPkg.staticSharedLibName != null; 18051 outInfo.populateUsers(deletedPs == null ? null 18052 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18053 } 18054 } 18055 18056 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 18057 18058 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18059 final PackageParser.Package resolvedPkg; 18060 if (deletedPkg != null) { 18061 resolvedPkg = deletedPkg; 18062 } else { 18063 // We don't have a parsed package when it lives on an ejected 18064 // adopted storage device, so fake something together 18065 resolvedPkg = new PackageParser.Package(ps.name); 18066 resolvedPkg.setVolumeUuid(ps.volumeUuid); 18067 } 18068 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18069 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18070 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 18071 if (outInfo != null) { 18072 outInfo.dataRemoved = true; 18073 } 18074 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 18075 } 18076 18077 int removedAppId = -1; 18078 18079 // writer 18080 synchronized (mPackages) { 18081 boolean installedStateChanged = false; 18082 if (deletedPs != null) { 18083 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 18084 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18085 clearDefaultBrowserIfNeeded(packageName); 18086 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18087 removedAppId = mSettings.removePackageLPw(packageName); 18088 if (outInfo != null) { 18089 outInfo.removedAppId = removedAppId; 18090 } 18091 mPermissionManager.updatePermissions( 18092 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18093 if (deletedPs.sharedUser != null) { 18094 // Remove permissions associated with package. Since runtime 18095 // permissions are per user we have to kill the removed package 18096 // or packages running under the shared user of the removed 18097 // package if revoking the permissions requested only by the removed 18098 // package is successful and this causes a change in gids. 18099 for (int userId : UserManagerService.getInstance().getUserIds()) { 18100 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18101 userId); 18102 if (userIdToKill == UserHandle.USER_ALL 18103 || userIdToKill >= UserHandle.USER_SYSTEM) { 18104 // If gids changed for this user, kill all affected packages. 18105 mHandler.post(new Runnable() { 18106 @Override 18107 public void run() { 18108 // This has to happen with no lock held. 18109 killApplication(deletedPs.name, deletedPs.appId, 18110 KILL_APP_REASON_GIDS_CHANGED); 18111 } 18112 }); 18113 break; 18114 } 18115 } 18116 } 18117 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 18118 } 18119 // make sure to preserve per-user disabled state if this removal was just 18120 // a downgrade of a system app to the factory package 18121 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18122 if (DEBUG_REMOVE) { 18123 Slog.d(TAG, "Propagating install state across downgrade"); 18124 } 18125 for (int userId : allUserHandles) { 18126 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18127 if (DEBUG_REMOVE) { 18128 Slog.d(TAG, " user " + userId + " => " + installed); 18129 } 18130 if (installed != ps.getInstalled(userId)) { 18131 installedStateChanged = true; 18132 } 18133 ps.setInstalled(installed, userId); 18134 } 18135 } 18136 } 18137 // can downgrade to reader 18138 if (writeSettings) { 18139 // Save settings now 18140 mSettings.writeLPr(); 18141 } 18142 if (installedStateChanged) { 18143 mSettings.writeKernelMappingLPr(ps); 18144 } 18145 } 18146 if (removedAppId != -1) { 18147 // A user ID was deleted here. Go through all users and remove it 18148 // from KeyStore. 18149 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18150 } 18151 } 18152 18153 static boolean locationIsPrivileged(String path) { 18154 try { 18155 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 18156 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 18157 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 18158 return path.startsWith(privilegedAppDir.getCanonicalPath()) 18159 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()) 18160 || path.startsWith(privilegedProductAppDir.getCanonicalPath()); 18161 } catch (IOException e) { 18162 Slog.e(TAG, "Unable to access code path " + path); 18163 } 18164 return false; 18165 } 18166 18167 static boolean locationIsOem(String path) { 18168 try { 18169 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 18170 } catch (IOException e) { 18171 Slog.e(TAG, "Unable to access code path " + path); 18172 } 18173 return false; 18174 } 18175 18176 static boolean locationIsVendor(String path) { 18177 try { 18178 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 18179 } catch (IOException e) { 18180 Slog.e(TAG, "Unable to access code path " + path); 18181 } 18182 return false; 18183 } 18184 18185 static boolean locationIsProduct(String path) { 18186 try { 18187 return path.startsWith(Environment.getProductDirectory().getCanonicalPath()); 18188 } catch (IOException e) { 18189 Slog.e(TAG, "Unable to access code path " + path); 18190 } 18191 return false; 18192 } 18193 18194 /* 18195 * Tries to delete system package. 18196 */ 18197 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 18198 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 18199 boolean writeSettings) { 18200 if (deletedPs.parentPackageName != null) { 18201 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 18202 return false; 18203 } 18204 18205 final boolean applyUserRestrictions 18206 = (allUserHandles != null) && (outInfo.origUsers != null); 18207 final PackageSetting disabledPs; 18208 // Confirm if the system package has been updated 18209 // An updated system app can be deleted. This will also have to restore 18210 // the system pkg from system partition 18211 // reader 18212 synchronized (mPackages) { 18213 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 18214 } 18215 18216 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18217 + " disabledPs=" + disabledPs); 18218 18219 if (disabledPs == null) { 18220 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 18221 return false; 18222 } else if (DEBUG_REMOVE) { 18223 Slog.d(TAG, "Deleting system pkg from data partition"); 18224 } 18225 18226 if (DEBUG_REMOVE) { 18227 if (applyUserRestrictions) { 18228 Slog.d(TAG, "Remembering install states:"); 18229 for (int userId : allUserHandles) { 18230 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18231 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18232 } 18233 } 18234 } 18235 18236 // Delete the updated package 18237 outInfo.isRemovedPackageSystemUpdate = true; 18238 if (outInfo.removedChildPackages != null) { 18239 final int childCount = (deletedPs.childPackageNames != null) 18240 ? deletedPs.childPackageNames.size() : 0; 18241 for (int i = 0; i < childCount; i++) { 18242 String childPackageName = deletedPs.childPackageNames.get(i); 18243 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18244 .contains(childPackageName)) { 18245 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18246 childPackageName); 18247 if (childInfo != null) { 18248 childInfo.isRemovedPackageSystemUpdate = true; 18249 } 18250 } 18251 } 18252 } 18253 18254 if (disabledPs.versionCode < deletedPs.versionCode) { 18255 // Delete data for downgrades 18256 flags &= ~PackageManager.DELETE_KEEP_DATA; 18257 } else { 18258 // Preserve data by setting flag 18259 flags |= PackageManager.DELETE_KEEP_DATA; 18260 } 18261 18262 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18263 outInfo, writeSettings, disabledPs.pkg); 18264 if (!ret) { 18265 return false; 18266 } 18267 18268 // writer 18269 synchronized (mPackages) { 18270 // NOTE: The system package always needs to be enabled; even if it's for 18271 // a compressed stub. If we don't, installing the system package fails 18272 // during scan [scanning checks the disabled packages]. We will reverse 18273 // this later, after we've "installed" the stub. 18274 // Reinstate the old system package 18275 enableSystemPackageLPw(disabledPs.pkg); 18276 // Remove any native libraries from the upgraded package. 18277 removeNativeBinariesLI(deletedPs); 18278 } 18279 18280 // Install the system package 18281 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18282 try { 18283 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 18284 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 18285 } catch (PackageManagerException e) { 18286 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18287 + e.getMessage()); 18288 return false; 18289 } finally { 18290 if (disabledPs.pkg.isStub) { 18291 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 18292 } 18293 } 18294 return true; 18295 } 18296 18297 /** 18298 * Installs a package that's already on the system partition. 18299 */ 18300 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18301 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18302 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18303 throws PackageManagerException { 18304 @ParseFlags int parseFlags = 18305 mDefParseFlags 18306 | PackageParser.PARSE_MUST_BE_APK 18307 | PackageParser.PARSE_IS_SYSTEM_DIR; 18308 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18309 if (isPrivileged || locationIsPrivileged(codePathString)) { 18310 scanFlags |= SCAN_AS_PRIVILEGED; 18311 } 18312 if (locationIsOem(codePathString)) { 18313 scanFlags |= SCAN_AS_OEM; 18314 } 18315 if (locationIsVendor(codePathString)) { 18316 scanFlags |= SCAN_AS_VENDOR; 18317 } 18318 if (locationIsProduct(codePathString)) { 18319 scanFlags |= SCAN_AS_PRODUCT; 18320 } 18321 18322 final File codePath = new File(codePathString); 18323 final PackageParser.Package pkg = 18324 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18325 18326 try { 18327 // update shared libraries for the newly re-installed system package 18328 updateSharedLibrariesLPr(pkg, null); 18329 } catch (PackageManagerException e) { 18330 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18331 } 18332 18333 prepareAppDataAfterInstallLIF(pkg); 18334 18335 // writer 18336 synchronized (mPackages) { 18337 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18338 18339 // Propagate the permissions state as we do not want to drop on the floor 18340 // runtime permissions. The update permissions method below will take 18341 // care of removing obsolete permissions and grant install permissions. 18342 if (origPermissionState != null) { 18343 ps.getPermissionsState().copyFrom(origPermissionState); 18344 } 18345 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18346 mPermissionCallback); 18347 18348 final boolean applyUserRestrictions 18349 = (allUserHandles != null) && (origUserHandles != null); 18350 if (applyUserRestrictions) { 18351 boolean installedStateChanged = false; 18352 if (DEBUG_REMOVE) { 18353 Slog.d(TAG, "Propagating install state across reinstall"); 18354 } 18355 for (int userId : allUserHandles) { 18356 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18357 if (DEBUG_REMOVE) { 18358 Slog.d(TAG, " user " + userId + " => " + installed); 18359 } 18360 if (installed != ps.getInstalled(userId)) { 18361 installedStateChanged = true; 18362 } 18363 ps.setInstalled(installed, userId); 18364 18365 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18366 } 18367 // Regardless of writeSettings we need to ensure that this restriction 18368 // state propagation is persisted 18369 mSettings.writeAllUsersPackageRestrictionsLPr(); 18370 if (installedStateChanged) { 18371 mSettings.writeKernelMappingLPr(ps); 18372 } 18373 } 18374 // can downgrade to reader here 18375 if (writeSettings) { 18376 mSettings.writeLPr(); 18377 } 18378 } 18379 return pkg; 18380 } 18381 18382 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18383 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18384 PackageRemovedInfo outInfo, boolean writeSettings, 18385 PackageParser.Package replacingPackage) { 18386 synchronized (mPackages) { 18387 if (outInfo != null) { 18388 outInfo.uid = ps.appId; 18389 } 18390 18391 if (outInfo != null && outInfo.removedChildPackages != null) { 18392 final int childCount = (ps.childPackageNames != null) 18393 ? ps.childPackageNames.size() : 0; 18394 for (int i = 0; i < childCount; i++) { 18395 String childPackageName = ps.childPackageNames.get(i); 18396 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18397 if (childPs == null) { 18398 return false; 18399 } 18400 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18401 childPackageName); 18402 if (childInfo != null) { 18403 childInfo.uid = childPs.appId; 18404 } 18405 } 18406 } 18407 } 18408 18409 // Delete package data from internal structures and also remove data if flag is set 18410 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18411 18412 // Delete the child packages data 18413 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18414 for (int i = 0; i < childCount; i++) { 18415 PackageSetting childPs; 18416 synchronized (mPackages) { 18417 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18418 } 18419 if (childPs != null) { 18420 PackageRemovedInfo childOutInfo = (outInfo != null 18421 && outInfo.removedChildPackages != null) 18422 ? outInfo.removedChildPackages.get(childPs.name) : null; 18423 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18424 && (replacingPackage != null 18425 && !replacingPackage.hasChildPackage(childPs.name)) 18426 ? flags & ~DELETE_KEEP_DATA : flags; 18427 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18428 deleteFlags, writeSettings); 18429 } 18430 } 18431 18432 // Delete application code and resources only for parent packages 18433 if (ps.parentPackageName == null) { 18434 if (deleteCodeAndResources && (outInfo != null)) { 18435 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18436 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18437 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18438 } 18439 } 18440 18441 return true; 18442 } 18443 18444 @Override 18445 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18446 int userId) { 18447 mContext.enforceCallingOrSelfPermission( 18448 android.Manifest.permission.DELETE_PACKAGES, null); 18449 synchronized (mPackages) { 18450 // Cannot block uninstall of static shared libs as they are 18451 // considered a part of the using app (emulating static linking). 18452 // Also static libs are installed always on internal storage. 18453 PackageParser.Package pkg = mPackages.get(packageName); 18454 if (pkg != null && pkg.staticSharedLibName != null) { 18455 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18456 + " providing static shared library: " + pkg.staticSharedLibName); 18457 return false; 18458 } 18459 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18460 mSettings.writePackageRestrictionsLPr(userId); 18461 } 18462 return true; 18463 } 18464 18465 @Override 18466 public boolean getBlockUninstallForUser(String packageName, int userId) { 18467 synchronized (mPackages) { 18468 final PackageSetting ps = mSettings.mPackages.get(packageName); 18469 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18470 return false; 18471 } 18472 return mSettings.getBlockUninstallLPr(userId, packageName); 18473 } 18474 } 18475 18476 @Override 18477 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18478 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18479 synchronized (mPackages) { 18480 PackageSetting ps = mSettings.mPackages.get(packageName); 18481 if (ps == null) { 18482 Log.w(TAG, "Package doesn't exist: " + packageName); 18483 return false; 18484 } 18485 if (systemUserApp) { 18486 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18487 } else { 18488 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18489 } 18490 mSettings.writeLPr(); 18491 } 18492 return true; 18493 } 18494 18495 /* 18496 * This method handles package deletion in general 18497 */ 18498 private boolean deletePackageLIF(String packageName, UserHandle user, 18499 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18500 PackageRemovedInfo outInfo, boolean writeSettings, 18501 PackageParser.Package replacingPackage) { 18502 if (packageName == null) { 18503 Slog.w(TAG, "Attempt to delete null packageName."); 18504 return false; 18505 } 18506 18507 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18508 18509 PackageSetting ps; 18510 synchronized (mPackages) { 18511 ps = mSettings.mPackages.get(packageName); 18512 if (ps == null) { 18513 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18514 return false; 18515 } 18516 18517 if (ps.parentPackageName != null && (!isSystemApp(ps) 18518 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18519 if (DEBUG_REMOVE) { 18520 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18521 + ((user == null) ? UserHandle.USER_ALL : user)); 18522 } 18523 final int removedUserId = (user != null) ? user.getIdentifier() 18524 : UserHandle.USER_ALL; 18525 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18526 return false; 18527 } 18528 markPackageUninstalledForUserLPw(ps, user); 18529 scheduleWritePackageRestrictionsLocked(user); 18530 return true; 18531 } 18532 } 18533 18534 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18535 && user.getIdentifier() != UserHandle.USER_ALL)) { 18536 // The caller is asking that the package only be deleted for a single 18537 // user. To do this, we just mark its uninstalled state and delete 18538 // its data. If this is a system app, we only allow this to happen if 18539 // they have set the special DELETE_SYSTEM_APP which requests different 18540 // semantics than normal for uninstalling system apps. 18541 markPackageUninstalledForUserLPw(ps, user); 18542 18543 if (!isSystemApp(ps)) { 18544 // Do not uninstall the APK if an app should be cached 18545 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18546 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18547 // Other user still have this package installed, so all 18548 // we need to do is clear this user's data and save that 18549 // it is uninstalled. 18550 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18551 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18552 return false; 18553 } 18554 scheduleWritePackageRestrictionsLocked(user); 18555 return true; 18556 } else { 18557 // We need to set it back to 'installed' so the uninstall 18558 // broadcasts will be sent correctly. 18559 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18560 ps.setInstalled(true, user.getIdentifier()); 18561 mSettings.writeKernelMappingLPr(ps); 18562 } 18563 } else { 18564 // This is a system app, so we assume that the 18565 // other users still have this package installed, so all 18566 // we need to do is clear this user's data and save that 18567 // it is uninstalled. 18568 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18569 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18570 return false; 18571 } 18572 scheduleWritePackageRestrictionsLocked(user); 18573 return true; 18574 } 18575 } 18576 18577 // If we are deleting a composite package for all users, keep track 18578 // of result for each child. 18579 if (ps.childPackageNames != null && outInfo != null) { 18580 synchronized (mPackages) { 18581 final int childCount = ps.childPackageNames.size(); 18582 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18583 for (int i = 0; i < childCount; i++) { 18584 String childPackageName = ps.childPackageNames.get(i); 18585 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18586 childInfo.removedPackage = childPackageName; 18587 childInfo.installerPackageName = ps.installerPackageName; 18588 outInfo.removedChildPackages.put(childPackageName, childInfo); 18589 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18590 if (childPs != null) { 18591 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18592 } 18593 } 18594 } 18595 } 18596 18597 boolean ret = false; 18598 if (isSystemApp(ps)) { 18599 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18600 // When an updated system application is deleted we delete the existing resources 18601 // as well and fall back to existing code in system partition 18602 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18603 } else { 18604 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18605 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18606 outInfo, writeSettings, replacingPackage); 18607 } 18608 18609 // Take a note whether we deleted the package for all users 18610 if (outInfo != null) { 18611 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18612 if (outInfo.removedChildPackages != null) { 18613 synchronized (mPackages) { 18614 final int childCount = outInfo.removedChildPackages.size(); 18615 for (int i = 0; i < childCount; i++) { 18616 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18617 if (childInfo != null) { 18618 childInfo.removedForAllUsers = mPackages.get( 18619 childInfo.removedPackage) == null; 18620 } 18621 } 18622 } 18623 } 18624 // If we uninstalled an update to a system app there may be some 18625 // child packages that appeared as they are declared in the system 18626 // app but were not declared in the update. 18627 if (isSystemApp(ps)) { 18628 synchronized (mPackages) { 18629 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18630 final int childCount = (updatedPs.childPackageNames != null) 18631 ? updatedPs.childPackageNames.size() : 0; 18632 for (int i = 0; i < childCount; i++) { 18633 String childPackageName = updatedPs.childPackageNames.get(i); 18634 if (outInfo.removedChildPackages == null 18635 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18636 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18637 if (childPs == null) { 18638 continue; 18639 } 18640 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18641 installRes.name = childPackageName; 18642 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18643 installRes.pkg = mPackages.get(childPackageName); 18644 installRes.uid = childPs.pkg.applicationInfo.uid; 18645 if (outInfo.appearedChildPackages == null) { 18646 outInfo.appearedChildPackages = new ArrayMap<>(); 18647 } 18648 outInfo.appearedChildPackages.put(childPackageName, installRes); 18649 } 18650 } 18651 } 18652 } 18653 } 18654 18655 return ret; 18656 } 18657 18658 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18659 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18660 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18661 for (int nextUserId : userIds) { 18662 if (DEBUG_REMOVE) { 18663 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18664 } 18665 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18666 false /*installed*/, 18667 true /*stopped*/, 18668 true /*notLaunched*/, 18669 false /*hidden*/, 18670 false /*suspended*/, 18671 false /*instantApp*/, 18672 false /*virtualPreload*/, 18673 null /*lastDisableAppCaller*/, 18674 null /*enabledComponents*/, 18675 null /*disabledComponents*/, 18676 ps.readUserState(nextUserId).domainVerificationStatus, 18677 0, PackageManager.INSTALL_REASON_UNKNOWN, 18678 null /*harmfulAppWarning*/); 18679 } 18680 mSettings.writeKernelMappingLPr(ps); 18681 } 18682 18683 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18684 PackageRemovedInfo outInfo) { 18685 final PackageParser.Package pkg; 18686 synchronized (mPackages) { 18687 pkg = mPackages.get(ps.name); 18688 } 18689 18690 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18691 : new int[] {userId}; 18692 for (int nextUserId : userIds) { 18693 if (DEBUG_REMOVE) { 18694 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18695 + nextUserId); 18696 } 18697 18698 destroyAppDataLIF(pkg, userId, 18699 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18700 destroyAppProfilesLIF(pkg, userId); 18701 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18702 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18703 schedulePackageCleaning(ps.name, nextUserId, false); 18704 synchronized (mPackages) { 18705 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18706 scheduleWritePackageRestrictionsLocked(nextUserId); 18707 } 18708 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18709 } 18710 } 18711 18712 if (outInfo != null) { 18713 outInfo.removedPackage = ps.name; 18714 outInfo.installerPackageName = ps.installerPackageName; 18715 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18716 outInfo.removedAppId = ps.appId; 18717 outInfo.removedUsers = userIds; 18718 outInfo.broadcastUsers = userIds; 18719 } 18720 18721 return true; 18722 } 18723 18724 private final class ClearStorageConnection implements ServiceConnection { 18725 IMediaContainerService mContainerService; 18726 18727 @Override 18728 public void onServiceConnected(ComponentName name, IBinder service) { 18729 synchronized (this) { 18730 mContainerService = IMediaContainerService.Stub 18731 .asInterface(Binder.allowBlocking(service)); 18732 notifyAll(); 18733 } 18734 } 18735 18736 @Override 18737 public void onServiceDisconnected(ComponentName name) { 18738 } 18739 } 18740 18741 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18742 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18743 18744 final boolean mounted; 18745 if (Environment.isExternalStorageEmulated()) { 18746 mounted = true; 18747 } else { 18748 final String status = Environment.getExternalStorageState(); 18749 18750 mounted = status.equals(Environment.MEDIA_MOUNTED) 18751 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18752 } 18753 18754 if (!mounted) { 18755 return; 18756 } 18757 18758 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18759 int[] users; 18760 if (userId == UserHandle.USER_ALL) { 18761 users = sUserManager.getUserIds(); 18762 } else { 18763 users = new int[] { userId }; 18764 } 18765 final ClearStorageConnection conn = new ClearStorageConnection(); 18766 if (mContext.bindServiceAsUser( 18767 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18768 try { 18769 for (int curUser : users) { 18770 long timeout = SystemClock.uptimeMillis() + 5000; 18771 synchronized (conn) { 18772 long now; 18773 while (conn.mContainerService == null && 18774 (now = SystemClock.uptimeMillis()) < timeout) { 18775 try { 18776 conn.wait(timeout - now); 18777 } catch (InterruptedException e) { 18778 } 18779 } 18780 } 18781 if (conn.mContainerService == null) { 18782 return; 18783 } 18784 18785 final UserEnvironment userEnv = new UserEnvironment(curUser); 18786 clearDirectory(conn.mContainerService, 18787 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18788 if (allData) { 18789 clearDirectory(conn.mContainerService, 18790 userEnv.buildExternalStorageAppDataDirs(packageName)); 18791 clearDirectory(conn.mContainerService, 18792 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18793 } 18794 } 18795 } finally { 18796 mContext.unbindService(conn); 18797 } 18798 } 18799 } 18800 18801 @Override 18802 public void clearApplicationProfileData(String packageName) { 18803 enforceSystemOrRoot("Only the system can clear all profile data"); 18804 18805 final PackageParser.Package pkg; 18806 synchronized (mPackages) { 18807 pkg = mPackages.get(packageName); 18808 } 18809 18810 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18811 synchronized (mInstallLock) { 18812 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18813 } 18814 } 18815 } 18816 18817 @Override 18818 public void clearApplicationUserData(final String packageName, 18819 final IPackageDataObserver observer, final int userId) { 18820 mContext.enforceCallingOrSelfPermission( 18821 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18822 18823 final int callingUid = Binder.getCallingUid(); 18824 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18825 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18826 18827 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18828 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18829 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18830 throw new SecurityException("Cannot clear data for a protected package: " 18831 + packageName); 18832 } 18833 // Queue up an async operation since the package deletion may take a little while. 18834 mHandler.post(new Runnable() { 18835 public void run() { 18836 mHandler.removeCallbacks(this); 18837 final boolean succeeded; 18838 if (!filterApp) { 18839 try (PackageFreezer freezer = freezePackage(packageName, 18840 "clearApplicationUserData")) { 18841 synchronized (mInstallLock) { 18842 succeeded = clearApplicationUserDataLIF(packageName, userId); 18843 } 18844 clearExternalStorageDataSync(packageName, userId, true); 18845 synchronized (mPackages) { 18846 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18847 packageName, userId); 18848 } 18849 } 18850 if (succeeded) { 18851 // invoke DeviceStorageMonitor's update method to clear any notifications 18852 DeviceStorageMonitorInternal dsm = LocalServices 18853 .getService(DeviceStorageMonitorInternal.class); 18854 if (dsm != null) { 18855 dsm.checkMemory(); 18856 } 18857 } 18858 } else { 18859 succeeded = false; 18860 } 18861 if (observer != null) { 18862 try { 18863 observer.onRemoveCompleted(packageName, succeeded); 18864 } catch (RemoteException e) { 18865 Log.i(TAG, "Observer no longer exists."); 18866 } 18867 } //end if observer 18868 } //end run 18869 }); 18870 } 18871 18872 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18873 if (packageName == null) { 18874 Slog.w(TAG, "Attempt to delete null packageName."); 18875 return false; 18876 } 18877 18878 // Try finding details about the requested package 18879 PackageParser.Package pkg; 18880 synchronized (mPackages) { 18881 pkg = mPackages.get(packageName); 18882 if (pkg == null) { 18883 final PackageSetting ps = mSettings.mPackages.get(packageName); 18884 if (ps != null) { 18885 pkg = ps.pkg; 18886 } 18887 } 18888 18889 if (pkg == null) { 18890 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18891 return false; 18892 } 18893 18894 PackageSetting ps = (PackageSetting) pkg.mExtras; 18895 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18896 } 18897 18898 clearAppDataLIF(pkg, userId, 18899 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18900 18901 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18902 removeKeystoreDataIfNeeded(userId, appId); 18903 18904 UserManagerInternal umInternal = getUserManagerInternal(); 18905 final int flags; 18906 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18907 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18908 } else if (umInternal.isUserRunning(userId)) { 18909 flags = StorageManager.FLAG_STORAGE_DE; 18910 } else { 18911 flags = 0; 18912 } 18913 prepareAppDataContentsLIF(pkg, userId, flags); 18914 18915 return true; 18916 } 18917 18918 /** 18919 * Reverts user permission state changes (permissions and flags) in 18920 * all packages for a given user. 18921 * 18922 * @param userId The device user for which to do a reset. 18923 */ 18924 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18925 final int packageCount = mPackages.size(); 18926 for (int i = 0; i < packageCount; i++) { 18927 PackageParser.Package pkg = mPackages.valueAt(i); 18928 PackageSetting ps = (PackageSetting) pkg.mExtras; 18929 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18930 } 18931 } 18932 18933 private void resetNetworkPolicies(int userId) { 18934 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18935 } 18936 18937 /** 18938 * Reverts user permission state changes (permissions and flags). 18939 * 18940 * @param ps The package for which to reset. 18941 * @param userId The device user for which to do a reset. 18942 */ 18943 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18944 final PackageSetting ps, final int userId) { 18945 if (ps.pkg == null) { 18946 return; 18947 } 18948 18949 // These are flags that can change base on user actions. 18950 final int userSettableMask = FLAG_PERMISSION_USER_SET 18951 | FLAG_PERMISSION_USER_FIXED 18952 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18953 | FLAG_PERMISSION_REVIEW_REQUIRED; 18954 18955 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18956 | FLAG_PERMISSION_POLICY_FIXED; 18957 18958 boolean writeInstallPermissions = false; 18959 boolean writeRuntimePermissions = false; 18960 18961 final int permissionCount = ps.pkg.requestedPermissions.size(); 18962 for (int i = 0; i < permissionCount; i++) { 18963 final String permName = ps.pkg.requestedPermissions.get(i); 18964 final BasePermission bp = 18965 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18966 if (bp == null) { 18967 continue; 18968 } 18969 18970 // If shared user we just reset the state to which only this app contributed. 18971 if (ps.sharedUser != null) { 18972 boolean used = false; 18973 final int packageCount = ps.sharedUser.packages.size(); 18974 for (int j = 0; j < packageCount; j++) { 18975 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18976 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18977 && pkg.pkg.requestedPermissions.contains(permName)) { 18978 used = true; 18979 break; 18980 } 18981 } 18982 if (used) { 18983 continue; 18984 } 18985 } 18986 18987 final PermissionsState permissionsState = ps.getPermissionsState(); 18988 18989 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18990 18991 // Always clear the user settable flags. 18992 final boolean hasInstallState = 18993 permissionsState.getInstallPermissionState(permName) != null; 18994 // If permission review is enabled and this is a legacy app, mark the 18995 // permission as requiring a review as this is the initial state. 18996 int flags = 0; 18997 if (mSettings.mPermissions.mPermissionReviewRequired 18998 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18999 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 19000 } 19001 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 19002 if (hasInstallState) { 19003 writeInstallPermissions = true; 19004 } else { 19005 writeRuntimePermissions = true; 19006 } 19007 } 19008 19009 // Below is only runtime permission handling. 19010 if (!bp.isRuntime()) { 19011 continue; 19012 } 19013 19014 // Never clobber system or policy. 19015 if ((oldFlags & policyOrSystemFlags) != 0) { 19016 continue; 19017 } 19018 19019 // If this permission was granted by default, make sure it is. 19020 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19021 if (permissionsState.grantRuntimePermission(bp, userId) 19022 != PERMISSION_OPERATION_FAILURE) { 19023 writeRuntimePermissions = true; 19024 } 19025 // If permission review is enabled the permissions for a legacy apps 19026 // are represented as constantly granted runtime ones, so don't revoke. 19027 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19028 // Otherwise, reset the permission. 19029 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 19030 switch (revokeResult) { 19031 case PERMISSION_OPERATION_SUCCESS: 19032 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 19033 writeRuntimePermissions = true; 19034 final int appId = ps.appId; 19035 mHandler.post(new Runnable() { 19036 @Override 19037 public void run() { 19038 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 19039 } 19040 }); 19041 } break; 19042 } 19043 } 19044 } 19045 19046 // Synchronously write as we are taking permissions away. 19047 if (writeRuntimePermissions) { 19048 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 19049 } 19050 19051 // Synchronously write as we are taking permissions away. 19052 if (writeInstallPermissions) { 19053 mSettings.writeLPr(); 19054 } 19055 } 19056 19057 /** 19058 * Remove entries from the keystore daemon. Will only remove it if the 19059 * {@code appId} is valid. 19060 */ 19061 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19062 if (appId < 0) { 19063 return; 19064 } 19065 19066 final KeyStore keyStore = KeyStore.getInstance(); 19067 if (keyStore != null) { 19068 if (userId == UserHandle.USER_ALL) { 19069 for (final int individual : sUserManager.getUserIds()) { 19070 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19071 } 19072 } else { 19073 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19074 } 19075 } else { 19076 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19077 } 19078 } 19079 19080 @Override 19081 public void deleteApplicationCacheFiles(final String packageName, 19082 final IPackageDataObserver observer) { 19083 final int userId = UserHandle.getCallingUserId(); 19084 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19085 } 19086 19087 @Override 19088 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19089 final IPackageDataObserver observer) { 19090 final int callingUid = Binder.getCallingUid(); 19091 mContext.enforceCallingOrSelfPermission( 19092 android.Manifest.permission.DELETE_CACHE_FILES, null); 19093 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19094 /* requireFullPermission= */ true, /* checkShell= */ false, 19095 "delete application cache files"); 19096 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19097 android.Manifest.permission.ACCESS_INSTANT_APPS); 19098 19099 final PackageParser.Package pkg; 19100 synchronized (mPackages) { 19101 pkg = mPackages.get(packageName); 19102 } 19103 19104 // Queue up an async operation since the package deletion may take a little while. 19105 mHandler.post(new Runnable() { 19106 public void run() { 19107 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19108 boolean doClearData = true; 19109 if (ps != null) { 19110 final boolean targetIsInstantApp = 19111 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19112 doClearData = !targetIsInstantApp 19113 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19114 } 19115 if (doClearData) { 19116 synchronized (mInstallLock) { 19117 final int flags = StorageManager.FLAG_STORAGE_DE 19118 | StorageManager.FLAG_STORAGE_CE; 19119 // We're only clearing cache files, so we don't care if the 19120 // app is unfrozen and still able to run 19121 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19122 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19123 } 19124 clearExternalStorageDataSync(packageName, userId, false); 19125 } 19126 if (observer != null) { 19127 try { 19128 observer.onRemoveCompleted(packageName, true); 19129 } catch (RemoteException e) { 19130 Log.i(TAG, "Observer no longer exists."); 19131 } 19132 } 19133 } 19134 }); 19135 } 19136 19137 @Override 19138 public void getPackageSizeInfo(final String packageName, int userHandle, 19139 final IPackageStatsObserver observer) { 19140 throw new UnsupportedOperationException( 19141 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19142 } 19143 19144 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19145 final PackageSetting ps; 19146 synchronized (mPackages) { 19147 ps = mSettings.mPackages.get(packageName); 19148 if (ps == null) { 19149 Slog.w(TAG, "Failed to find settings for " + packageName); 19150 return false; 19151 } 19152 } 19153 19154 final String[] packageNames = { packageName }; 19155 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19156 final String[] codePaths = { ps.codePathString }; 19157 19158 try { 19159 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19160 ps.appId, ceDataInodes, codePaths, stats); 19161 19162 // For now, ignore code size of packages on system partition 19163 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19164 stats.codeSize = 0; 19165 } 19166 19167 // External clients expect these to be tracked separately 19168 stats.dataSize -= stats.cacheSize; 19169 19170 } catch (InstallerException e) { 19171 Slog.w(TAG, String.valueOf(e)); 19172 return false; 19173 } 19174 19175 return true; 19176 } 19177 19178 private int getUidTargetSdkVersionLockedLPr(int uid) { 19179 Object obj = mSettings.getUserIdLPr(uid); 19180 if (obj instanceof SharedUserSetting) { 19181 final SharedUserSetting sus = (SharedUserSetting) obj; 19182 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19183 final Iterator<PackageSetting> it = sus.packages.iterator(); 19184 while (it.hasNext()) { 19185 final PackageSetting ps = it.next(); 19186 if (ps.pkg != null) { 19187 int v = ps.pkg.applicationInfo.targetSdkVersion; 19188 if (v < vers) vers = v; 19189 } 19190 } 19191 return vers; 19192 } else if (obj instanceof PackageSetting) { 19193 final PackageSetting ps = (PackageSetting) obj; 19194 if (ps.pkg != null) { 19195 return ps.pkg.applicationInfo.targetSdkVersion; 19196 } 19197 } 19198 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19199 } 19200 19201 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19202 final PackageParser.Package p = mPackages.get(packageName); 19203 if (p != null) { 19204 return p.applicationInfo.targetSdkVersion; 19205 } 19206 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19207 } 19208 19209 @Override 19210 public void addPreferredActivity(IntentFilter filter, int match, 19211 ComponentName[] set, ComponentName activity, int userId) { 19212 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19213 "Adding preferred"); 19214 } 19215 19216 private void addPreferredActivityInternal(IntentFilter filter, int match, 19217 ComponentName[] set, ComponentName activity, boolean always, int userId, 19218 String opname) { 19219 // writer 19220 int callingUid = Binder.getCallingUid(); 19221 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19222 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19223 if (filter.countActions() == 0) { 19224 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19225 return; 19226 } 19227 synchronized (mPackages) { 19228 if (mContext.checkCallingOrSelfPermission( 19229 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19230 != PackageManager.PERMISSION_GRANTED) { 19231 if (getUidTargetSdkVersionLockedLPr(callingUid) 19232 < Build.VERSION_CODES.FROYO) { 19233 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19234 + callingUid); 19235 return; 19236 } 19237 mContext.enforceCallingOrSelfPermission( 19238 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19239 } 19240 19241 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19242 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19243 + userId + ":"); 19244 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19245 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19246 scheduleWritePackageRestrictionsLocked(userId); 19247 postPreferredActivityChangedBroadcast(userId); 19248 } 19249 } 19250 19251 private void postPreferredActivityChangedBroadcast(int userId) { 19252 mHandler.post(() -> { 19253 final IActivityManager am = ActivityManager.getService(); 19254 if (am == null) { 19255 return; 19256 } 19257 19258 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19259 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19260 try { 19261 am.broadcastIntent(null, intent, null, null, 19262 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19263 null, false, false, userId); 19264 } catch (RemoteException e) { 19265 } 19266 }); 19267 } 19268 19269 @Override 19270 public void replacePreferredActivity(IntentFilter filter, int match, 19271 ComponentName[] set, ComponentName activity, int userId) { 19272 if (filter.countActions() != 1) { 19273 throw new IllegalArgumentException( 19274 "replacePreferredActivity expects filter to have only 1 action."); 19275 } 19276 if (filter.countDataAuthorities() != 0 19277 || filter.countDataPaths() != 0 19278 || filter.countDataSchemes() > 1 19279 || filter.countDataTypes() != 0) { 19280 throw new IllegalArgumentException( 19281 "replacePreferredActivity expects filter to have no data authorities, " + 19282 "paths, or types; and at most one scheme."); 19283 } 19284 19285 final int callingUid = Binder.getCallingUid(); 19286 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19287 true /* requireFullPermission */, false /* checkShell */, 19288 "replace preferred activity"); 19289 synchronized (mPackages) { 19290 if (mContext.checkCallingOrSelfPermission( 19291 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19292 != PackageManager.PERMISSION_GRANTED) { 19293 if (getUidTargetSdkVersionLockedLPr(callingUid) 19294 < Build.VERSION_CODES.FROYO) { 19295 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19296 + Binder.getCallingUid()); 19297 return; 19298 } 19299 mContext.enforceCallingOrSelfPermission( 19300 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19301 } 19302 19303 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19304 if (pir != null) { 19305 // Get all of the existing entries that exactly match this filter. 19306 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19307 if (existing != null && existing.size() == 1) { 19308 PreferredActivity cur = existing.get(0); 19309 if (DEBUG_PREFERRED) { 19310 Slog.i(TAG, "Checking replace of preferred:"); 19311 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19312 if (!cur.mPref.mAlways) { 19313 Slog.i(TAG, " -- CUR; not mAlways!"); 19314 } else { 19315 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19316 Slog.i(TAG, " -- CUR: mSet=" 19317 + Arrays.toString(cur.mPref.mSetComponents)); 19318 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19319 Slog.i(TAG, " -- NEW: mMatch=" 19320 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19321 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19322 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19323 } 19324 } 19325 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19326 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19327 && cur.mPref.sameSet(set)) { 19328 // Setting the preferred activity to what it happens to be already 19329 if (DEBUG_PREFERRED) { 19330 Slog.i(TAG, "Replacing with same preferred activity " 19331 + cur.mPref.mShortComponent + " for user " 19332 + userId + ":"); 19333 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19334 } 19335 return; 19336 } 19337 } 19338 19339 if (existing != null) { 19340 if (DEBUG_PREFERRED) { 19341 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19342 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19343 } 19344 for (int i = 0; i < existing.size(); i++) { 19345 PreferredActivity pa = existing.get(i); 19346 if (DEBUG_PREFERRED) { 19347 Slog.i(TAG, "Removing existing preferred activity " 19348 + pa.mPref.mComponent + ":"); 19349 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19350 } 19351 pir.removeFilter(pa); 19352 } 19353 } 19354 } 19355 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19356 "Replacing preferred"); 19357 } 19358 } 19359 19360 @Override 19361 public void clearPackagePreferredActivities(String packageName) { 19362 final int callingUid = Binder.getCallingUid(); 19363 if (getInstantAppPackageName(callingUid) != null) { 19364 return; 19365 } 19366 // writer 19367 synchronized (mPackages) { 19368 PackageParser.Package pkg = mPackages.get(packageName); 19369 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19370 if (mContext.checkCallingOrSelfPermission( 19371 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19372 != PackageManager.PERMISSION_GRANTED) { 19373 if (getUidTargetSdkVersionLockedLPr(callingUid) 19374 < Build.VERSION_CODES.FROYO) { 19375 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19376 + callingUid); 19377 return; 19378 } 19379 mContext.enforceCallingOrSelfPermission( 19380 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19381 } 19382 } 19383 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19384 if (ps != null 19385 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19386 return; 19387 } 19388 int user = UserHandle.getCallingUserId(); 19389 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19390 scheduleWritePackageRestrictionsLocked(user); 19391 } 19392 } 19393 } 19394 19395 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19396 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19397 ArrayList<PreferredActivity> removed = null; 19398 boolean changed = false; 19399 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19400 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19401 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19402 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19403 continue; 19404 } 19405 Iterator<PreferredActivity> it = pir.filterIterator(); 19406 while (it.hasNext()) { 19407 PreferredActivity pa = it.next(); 19408 // Mark entry for removal only if it matches the package name 19409 // and the entry is of type "always". 19410 if (packageName == null || 19411 (pa.mPref.mComponent.getPackageName().equals(packageName) 19412 && pa.mPref.mAlways)) { 19413 if (removed == null) { 19414 removed = new ArrayList<PreferredActivity>(); 19415 } 19416 removed.add(pa); 19417 } 19418 } 19419 if (removed != null) { 19420 for (int j=0; j<removed.size(); j++) { 19421 PreferredActivity pa = removed.get(j); 19422 pir.removeFilter(pa); 19423 } 19424 changed = true; 19425 } 19426 } 19427 if (changed) { 19428 postPreferredActivityChangedBroadcast(userId); 19429 } 19430 return changed; 19431 } 19432 19433 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19434 private void clearIntentFilterVerificationsLPw(int userId) { 19435 final int packageCount = mPackages.size(); 19436 for (int i = 0; i < packageCount; i++) { 19437 PackageParser.Package pkg = mPackages.valueAt(i); 19438 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19439 } 19440 } 19441 19442 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19443 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19444 if (userId == UserHandle.USER_ALL) { 19445 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19446 sUserManager.getUserIds())) { 19447 for (int oneUserId : sUserManager.getUserIds()) { 19448 scheduleWritePackageRestrictionsLocked(oneUserId); 19449 } 19450 } 19451 } else { 19452 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19453 scheduleWritePackageRestrictionsLocked(userId); 19454 } 19455 } 19456 } 19457 19458 /** Clears state for all users, and touches intent filter verification policy */ 19459 void clearDefaultBrowserIfNeeded(String packageName) { 19460 for (int oneUserId : sUserManager.getUserIds()) { 19461 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19462 } 19463 } 19464 19465 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19466 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19467 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19468 if (packageName.equals(defaultBrowserPackageName)) { 19469 setDefaultBrowserPackageName(null, userId); 19470 } 19471 } 19472 } 19473 19474 @Override 19475 public void resetApplicationPreferences(int userId) { 19476 mContext.enforceCallingOrSelfPermission( 19477 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19478 final long identity = Binder.clearCallingIdentity(); 19479 // writer 19480 try { 19481 synchronized (mPackages) { 19482 clearPackagePreferredActivitiesLPw(null, userId); 19483 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19484 // TODO: We have to reset the default SMS and Phone. This requires 19485 // significant refactoring to keep all default apps in the package 19486 // manager (cleaner but more work) or have the services provide 19487 // callbacks to the package manager to request a default app reset. 19488 applyFactoryDefaultBrowserLPw(userId); 19489 clearIntentFilterVerificationsLPw(userId); 19490 primeDomainVerificationsLPw(userId); 19491 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19492 scheduleWritePackageRestrictionsLocked(userId); 19493 } 19494 resetNetworkPolicies(userId); 19495 } finally { 19496 Binder.restoreCallingIdentity(identity); 19497 } 19498 } 19499 19500 @Override 19501 public int getPreferredActivities(List<IntentFilter> outFilters, 19502 List<ComponentName> outActivities, String packageName) { 19503 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19504 return 0; 19505 } 19506 int num = 0; 19507 final int userId = UserHandle.getCallingUserId(); 19508 // reader 19509 synchronized (mPackages) { 19510 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19511 if (pir != null) { 19512 final Iterator<PreferredActivity> it = pir.filterIterator(); 19513 while (it.hasNext()) { 19514 final PreferredActivity pa = it.next(); 19515 if (packageName == null 19516 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19517 && pa.mPref.mAlways)) { 19518 if (outFilters != null) { 19519 outFilters.add(new IntentFilter(pa)); 19520 } 19521 if (outActivities != null) { 19522 outActivities.add(pa.mPref.mComponent); 19523 } 19524 } 19525 } 19526 } 19527 } 19528 19529 return num; 19530 } 19531 19532 @Override 19533 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19534 int userId) { 19535 int callingUid = Binder.getCallingUid(); 19536 if (callingUid != Process.SYSTEM_UID) { 19537 throw new SecurityException( 19538 "addPersistentPreferredActivity can only be run by the system"); 19539 } 19540 if (filter.countActions() == 0) { 19541 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19542 return; 19543 } 19544 synchronized (mPackages) { 19545 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19546 ":"); 19547 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19548 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19549 new PersistentPreferredActivity(filter, activity)); 19550 scheduleWritePackageRestrictionsLocked(userId); 19551 postPreferredActivityChangedBroadcast(userId); 19552 } 19553 } 19554 19555 @Override 19556 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19557 int callingUid = Binder.getCallingUid(); 19558 if (callingUid != Process.SYSTEM_UID) { 19559 throw new SecurityException( 19560 "clearPackagePersistentPreferredActivities can only be run by the system"); 19561 } 19562 ArrayList<PersistentPreferredActivity> removed = null; 19563 boolean changed = false; 19564 synchronized (mPackages) { 19565 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19566 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19567 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19568 .valueAt(i); 19569 if (userId != thisUserId) { 19570 continue; 19571 } 19572 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19573 while (it.hasNext()) { 19574 PersistentPreferredActivity ppa = it.next(); 19575 // Mark entry for removal only if it matches the package name. 19576 if (ppa.mComponent.getPackageName().equals(packageName)) { 19577 if (removed == null) { 19578 removed = new ArrayList<PersistentPreferredActivity>(); 19579 } 19580 removed.add(ppa); 19581 } 19582 } 19583 if (removed != null) { 19584 for (int j=0; j<removed.size(); j++) { 19585 PersistentPreferredActivity ppa = removed.get(j); 19586 ppir.removeFilter(ppa); 19587 } 19588 changed = true; 19589 } 19590 } 19591 19592 if (changed) { 19593 scheduleWritePackageRestrictionsLocked(userId); 19594 postPreferredActivityChangedBroadcast(userId); 19595 } 19596 } 19597 } 19598 19599 /** 19600 * Common machinery for picking apart a restored XML blob and passing 19601 * it to a caller-supplied functor to be applied to the running system. 19602 */ 19603 private void restoreFromXml(XmlPullParser parser, int userId, 19604 String expectedStartTag, BlobXmlRestorer functor) 19605 throws IOException, XmlPullParserException { 19606 int type; 19607 while ((type = parser.next()) != XmlPullParser.START_TAG 19608 && type != XmlPullParser.END_DOCUMENT) { 19609 } 19610 if (type != XmlPullParser.START_TAG) { 19611 // oops didn't find a start tag?! 19612 if (DEBUG_BACKUP) { 19613 Slog.e(TAG, "Didn't find start tag during restore"); 19614 } 19615 return; 19616 } 19617Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19618 // this is supposed to be TAG_PREFERRED_BACKUP 19619 if (!expectedStartTag.equals(parser.getName())) { 19620 if (DEBUG_BACKUP) { 19621 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19622 } 19623 return; 19624 } 19625 19626 // skip interfering stuff, then we're aligned with the backing implementation 19627 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19628Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19629 functor.apply(parser, userId); 19630 } 19631 19632 private interface BlobXmlRestorer { 19633 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19634 } 19635 19636 /** 19637 * Non-Binder method, support for the backup/restore mechanism: write the 19638 * full set of preferred activities in its canonical XML format. Returns the 19639 * XML output as a byte array, or null if there is none. 19640 */ 19641 @Override 19642 public byte[] getPreferredActivityBackup(int userId) { 19643 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19644 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19645 } 19646 19647 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19648 try { 19649 final XmlSerializer serializer = new FastXmlSerializer(); 19650 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19651 serializer.startDocument(null, true); 19652 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19653 19654 synchronized (mPackages) { 19655 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19656 } 19657 19658 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19659 serializer.endDocument(); 19660 serializer.flush(); 19661 } catch (Exception e) { 19662 if (DEBUG_BACKUP) { 19663 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19664 } 19665 return null; 19666 } 19667 19668 return dataStream.toByteArray(); 19669 } 19670 19671 @Override 19672 public void restorePreferredActivities(byte[] backup, int userId) { 19673 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19674 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19675 } 19676 19677 try { 19678 final XmlPullParser parser = Xml.newPullParser(); 19679 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19680 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19681 new BlobXmlRestorer() { 19682 @Override 19683 public void apply(XmlPullParser parser, int userId) 19684 throws XmlPullParserException, IOException { 19685 synchronized (mPackages) { 19686 mSettings.readPreferredActivitiesLPw(parser, userId); 19687 } 19688 } 19689 } ); 19690 } catch (Exception e) { 19691 if (DEBUG_BACKUP) { 19692 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19693 } 19694 } 19695 } 19696 19697 /** 19698 * Non-Binder method, support for the backup/restore mechanism: write the 19699 * default browser (etc) settings in its canonical XML format. Returns the default 19700 * browser XML representation as a byte array, or null if there is none. 19701 */ 19702 @Override 19703 public byte[] getDefaultAppsBackup(int userId) { 19704 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19705 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19706 } 19707 19708 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19709 try { 19710 final XmlSerializer serializer = new FastXmlSerializer(); 19711 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19712 serializer.startDocument(null, true); 19713 serializer.startTag(null, TAG_DEFAULT_APPS); 19714 19715 synchronized (mPackages) { 19716 mSettings.writeDefaultAppsLPr(serializer, userId); 19717 } 19718 19719 serializer.endTag(null, TAG_DEFAULT_APPS); 19720 serializer.endDocument(); 19721 serializer.flush(); 19722 } catch (Exception e) { 19723 if (DEBUG_BACKUP) { 19724 Slog.e(TAG, "Unable to write default apps for backup", e); 19725 } 19726 return null; 19727 } 19728 19729 return dataStream.toByteArray(); 19730 } 19731 19732 @Override 19733 public void restoreDefaultApps(byte[] backup, int userId) { 19734 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19735 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19736 } 19737 19738 try { 19739 final XmlPullParser parser = Xml.newPullParser(); 19740 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19741 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19742 new BlobXmlRestorer() { 19743 @Override 19744 public void apply(XmlPullParser parser, int userId) 19745 throws XmlPullParserException, IOException { 19746 synchronized (mPackages) { 19747 mSettings.readDefaultAppsLPw(parser, userId); 19748 } 19749 } 19750 } ); 19751 } catch (Exception e) { 19752 if (DEBUG_BACKUP) { 19753 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19754 } 19755 } 19756 } 19757 19758 @Override 19759 public byte[] getIntentFilterVerificationBackup(int userId) { 19760 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19761 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19762 } 19763 19764 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19765 try { 19766 final XmlSerializer serializer = new FastXmlSerializer(); 19767 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19768 serializer.startDocument(null, true); 19769 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19770 19771 synchronized (mPackages) { 19772 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19773 } 19774 19775 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19776 serializer.endDocument(); 19777 serializer.flush(); 19778 } catch (Exception e) { 19779 if (DEBUG_BACKUP) { 19780 Slog.e(TAG, "Unable to write default apps for backup", e); 19781 } 19782 return null; 19783 } 19784 19785 return dataStream.toByteArray(); 19786 } 19787 19788 @Override 19789 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19790 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19791 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19792 } 19793 19794 try { 19795 final XmlPullParser parser = Xml.newPullParser(); 19796 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19797 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19798 new BlobXmlRestorer() { 19799 @Override 19800 public void apply(XmlPullParser parser, int userId) 19801 throws XmlPullParserException, IOException { 19802 synchronized (mPackages) { 19803 mSettings.readAllDomainVerificationsLPr(parser, userId); 19804 mSettings.writeLPr(); 19805 } 19806 } 19807 } ); 19808 } catch (Exception e) { 19809 if (DEBUG_BACKUP) { 19810 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19811 } 19812 } 19813 } 19814 19815 @Override 19816 public byte[] getPermissionGrantBackup(int userId) { 19817 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19818 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19819 } 19820 19821 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19822 try { 19823 final XmlSerializer serializer = new FastXmlSerializer(); 19824 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19825 serializer.startDocument(null, true); 19826 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19827 19828 synchronized (mPackages) { 19829 serializeRuntimePermissionGrantsLPr(serializer, userId); 19830 } 19831 19832 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19833 serializer.endDocument(); 19834 serializer.flush(); 19835 } catch (Exception e) { 19836 if (DEBUG_BACKUP) { 19837 Slog.e(TAG, "Unable to write default apps for backup", e); 19838 } 19839 return null; 19840 } 19841 19842 return dataStream.toByteArray(); 19843 } 19844 19845 @Override 19846 public void restorePermissionGrants(byte[] backup, int userId) { 19847 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19848 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19849 } 19850 19851 try { 19852 final XmlPullParser parser = Xml.newPullParser(); 19853 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19854 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19855 new BlobXmlRestorer() { 19856 @Override 19857 public void apply(XmlPullParser parser, int userId) 19858 throws XmlPullParserException, IOException { 19859 synchronized (mPackages) { 19860 processRestoredPermissionGrantsLPr(parser, userId); 19861 } 19862 } 19863 } ); 19864 } catch (Exception e) { 19865 if (DEBUG_BACKUP) { 19866 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19867 } 19868 } 19869 } 19870 19871 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19872 throws IOException { 19873 serializer.startTag(null, TAG_ALL_GRANTS); 19874 19875 final int N = mSettings.mPackages.size(); 19876 for (int i = 0; i < N; i++) { 19877 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19878 boolean pkgGrantsKnown = false; 19879 19880 PermissionsState packagePerms = ps.getPermissionsState(); 19881 19882 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19883 final int grantFlags = state.getFlags(); 19884 // only look at grants that are not system/policy fixed 19885 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19886 final boolean isGranted = state.isGranted(); 19887 // And only back up the user-twiddled state bits 19888 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19889 final String packageName = mSettings.mPackages.keyAt(i); 19890 if (!pkgGrantsKnown) { 19891 serializer.startTag(null, TAG_GRANT); 19892 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19893 pkgGrantsKnown = true; 19894 } 19895 19896 final boolean userSet = 19897 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19898 final boolean userFixed = 19899 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19900 final boolean revoke = 19901 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19902 19903 serializer.startTag(null, TAG_PERMISSION); 19904 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19905 if (isGranted) { 19906 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19907 } 19908 if (userSet) { 19909 serializer.attribute(null, ATTR_USER_SET, "true"); 19910 } 19911 if (userFixed) { 19912 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19913 } 19914 if (revoke) { 19915 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19916 } 19917 serializer.endTag(null, TAG_PERMISSION); 19918 } 19919 } 19920 } 19921 19922 if (pkgGrantsKnown) { 19923 serializer.endTag(null, TAG_GRANT); 19924 } 19925 } 19926 19927 serializer.endTag(null, TAG_ALL_GRANTS); 19928 } 19929 19930 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19931 throws XmlPullParserException, IOException { 19932 String pkgName = null; 19933 int outerDepth = parser.getDepth(); 19934 int type; 19935 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19936 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19937 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19938 continue; 19939 } 19940 19941 final String tagName = parser.getName(); 19942 if (tagName.equals(TAG_GRANT)) { 19943 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19944 if (DEBUG_BACKUP) { 19945 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19946 } 19947 } else if (tagName.equals(TAG_PERMISSION)) { 19948 19949 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19950 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19951 19952 int newFlagSet = 0; 19953 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19954 newFlagSet |= FLAG_PERMISSION_USER_SET; 19955 } 19956 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19957 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19958 } 19959 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19960 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19961 } 19962 if (DEBUG_BACKUP) { 19963 Slog.v(TAG, " + Restoring grant:" 19964 + " pkg=" + pkgName 19965 + " perm=" + permName 19966 + " granted=" + isGranted 19967 + " bits=0x" + Integer.toHexString(newFlagSet)); 19968 } 19969 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19970 if (ps != null) { 19971 // Already installed so we apply the grant immediately 19972 if (DEBUG_BACKUP) { 19973 Slog.v(TAG, " + already installed; applying"); 19974 } 19975 PermissionsState perms = ps.getPermissionsState(); 19976 BasePermission bp = 19977 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19978 if (bp != null) { 19979 if (isGranted) { 19980 perms.grantRuntimePermission(bp, userId); 19981 } 19982 if (newFlagSet != 0) { 19983 perms.updatePermissionFlags( 19984 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19985 } 19986 } 19987 } else { 19988 // Need to wait for post-restore install to apply the grant 19989 if (DEBUG_BACKUP) { 19990 Slog.v(TAG, " - not yet installed; saving for later"); 19991 } 19992 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19993 isGranted, newFlagSet, userId); 19994 } 19995 } else { 19996 PackageManagerService.reportSettingsProblem(Log.WARN, 19997 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19998 XmlUtils.skipCurrentTag(parser); 19999 } 20000 } 20001 20002 scheduleWriteSettingsLocked(); 20003 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 20004 } 20005 20006 @Override 20007 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20008 int sourceUserId, int targetUserId, int flags) { 20009 mContext.enforceCallingOrSelfPermission( 20010 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20011 int callingUid = Binder.getCallingUid(); 20012 enforceOwnerRights(ownerPackage, callingUid); 20013 PackageManagerServiceUtils.enforceShellRestriction( 20014 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20015 if (intentFilter.countActions() == 0) { 20016 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20017 return; 20018 } 20019 synchronized (mPackages) { 20020 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20021 ownerPackage, targetUserId, flags); 20022 CrossProfileIntentResolver resolver = 20023 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20024 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20025 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20026 if (existing != null) { 20027 int size = existing.size(); 20028 for (int i = 0; i < size; i++) { 20029 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20030 return; 20031 } 20032 } 20033 } 20034 resolver.addFilter(newFilter); 20035 scheduleWritePackageRestrictionsLocked(sourceUserId); 20036 } 20037 } 20038 20039 @Override 20040 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20041 mContext.enforceCallingOrSelfPermission( 20042 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20043 final int callingUid = Binder.getCallingUid(); 20044 enforceOwnerRights(ownerPackage, callingUid); 20045 PackageManagerServiceUtils.enforceShellRestriction( 20046 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20047 synchronized (mPackages) { 20048 CrossProfileIntentResolver resolver = 20049 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20050 ArraySet<CrossProfileIntentFilter> set = 20051 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 20052 for (CrossProfileIntentFilter filter : set) { 20053 if (filter.getOwnerPackage().equals(ownerPackage)) { 20054 resolver.removeFilter(filter); 20055 } 20056 } 20057 scheduleWritePackageRestrictionsLocked(sourceUserId); 20058 } 20059 } 20060 20061 // Enforcing that callingUid is owning pkg on userId 20062 private void enforceOwnerRights(String pkg, int callingUid) { 20063 // The system owns everything. 20064 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20065 return; 20066 } 20067 final int callingUserId = UserHandle.getUserId(callingUid); 20068 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20069 if (pi == null) { 20070 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20071 + callingUserId); 20072 } 20073 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20074 throw new SecurityException("Calling uid " + callingUid 20075 + " does not own package " + pkg); 20076 } 20077 } 20078 20079 @Override 20080 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20081 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20082 return null; 20083 } 20084 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20085 } 20086 20087 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20088 UserManagerService ums = UserManagerService.getInstance(); 20089 if (ums != null) { 20090 final UserInfo parent = ums.getProfileParent(userId); 20091 final int launcherUid = (parent != null) ? parent.id : userId; 20092 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20093 if (launcherComponent != null) { 20094 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20095 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20096 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20097 .setPackage(launcherComponent.getPackageName()); 20098 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20099 } 20100 } 20101 } 20102 20103 /** 20104 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20105 * then reports the most likely home activity or null if there are more than one. 20106 */ 20107 private ComponentName getDefaultHomeActivity(int userId) { 20108 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20109 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20110 if (cn != null) { 20111 return cn; 20112 } 20113 20114 // Find the launcher with the highest priority and return that component if there are no 20115 // other home activity with the same priority. 20116 int lastPriority = Integer.MIN_VALUE; 20117 ComponentName lastComponent = null; 20118 final int size = allHomeCandidates.size(); 20119 for (int i = 0; i < size; i++) { 20120 final ResolveInfo ri = allHomeCandidates.get(i); 20121 if (ri.priority > lastPriority) { 20122 lastComponent = ri.activityInfo.getComponentName(); 20123 lastPriority = ri.priority; 20124 } else if (ri.priority == lastPriority) { 20125 // Two components found with same priority. 20126 lastComponent = null; 20127 } 20128 } 20129 return lastComponent; 20130 } 20131 20132 private Intent getHomeIntent() { 20133 Intent intent = new Intent(Intent.ACTION_MAIN); 20134 intent.addCategory(Intent.CATEGORY_HOME); 20135 intent.addCategory(Intent.CATEGORY_DEFAULT); 20136 return intent; 20137 } 20138 20139 private IntentFilter getHomeFilter() { 20140 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20141 filter.addCategory(Intent.CATEGORY_HOME); 20142 filter.addCategory(Intent.CATEGORY_DEFAULT); 20143 return filter; 20144 } 20145 20146 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20147 int userId) { 20148 Intent intent = getHomeIntent(); 20149 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 20150 PackageManager.GET_META_DATA, userId); 20151 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 20152 true, false, false, userId); 20153 20154 allHomeCandidates.clear(); 20155 if (list != null) { 20156 for (ResolveInfo ri : list) { 20157 allHomeCandidates.add(ri); 20158 } 20159 } 20160 return (preferred == null || preferred.activityInfo == null) 20161 ? null 20162 : new ComponentName(preferred.activityInfo.packageName, 20163 preferred.activityInfo.name); 20164 } 20165 20166 @Override 20167 public void setHomeActivity(ComponentName comp, int userId) { 20168 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20169 return; 20170 } 20171 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20172 getHomeActivitiesAsUser(homeActivities, userId); 20173 20174 boolean found = false; 20175 20176 final int size = homeActivities.size(); 20177 final ComponentName[] set = new ComponentName[size]; 20178 for (int i = 0; i < size; i++) { 20179 final ResolveInfo candidate = homeActivities.get(i); 20180 final ActivityInfo info = candidate.activityInfo; 20181 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20182 set[i] = activityName; 20183 if (!found && activityName.equals(comp)) { 20184 found = true; 20185 } 20186 } 20187 if (!found) { 20188 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20189 + userId); 20190 } 20191 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20192 set, comp, userId); 20193 } 20194 20195 private @Nullable String getSetupWizardPackageName() { 20196 final Intent intent = new Intent(Intent.ACTION_MAIN); 20197 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20198 20199 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20200 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20201 | MATCH_DISABLED_COMPONENTS, 20202 UserHandle.myUserId()); 20203 if (matches.size() == 1) { 20204 return matches.get(0).getComponentInfo().packageName; 20205 } else { 20206 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20207 + ": matches=" + matches); 20208 return null; 20209 } 20210 } 20211 20212 private @Nullable String getStorageManagerPackageName() { 20213 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20214 20215 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20216 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20217 | MATCH_DISABLED_COMPONENTS, 20218 UserHandle.myUserId()); 20219 if (matches.size() == 1) { 20220 return matches.get(0).getComponentInfo().packageName; 20221 } else { 20222 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20223 + matches.size() + ": matches=" + matches); 20224 return null; 20225 } 20226 } 20227 20228 @Override 20229 public void setApplicationEnabledSetting(String appPackageName, 20230 int newState, int flags, int userId, String callingPackage) { 20231 if (!sUserManager.exists(userId)) return; 20232 if (callingPackage == null) { 20233 callingPackage = Integer.toString(Binder.getCallingUid()); 20234 } 20235 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20236 } 20237 20238 @Override 20239 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20240 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20241 synchronized (mPackages) { 20242 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20243 if (pkgSetting != null) { 20244 pkgSetting.setUpdateAvailable(updateAvailable); 20245 } 20246 } 20247 } 20248 20249 @Override 20250 public void setComponentEnabledSetting(ComponentName componentName, 20251 int newState, int flags, int userId) { 20252 if (!sUserManager.exists(userId)) return; 20253 setEnabledSetting(componentName.getPackageName(), 20254 componentName.getClassName(), newState, flags, userId, null); 20255 } 20256 20257 private void setEnabledSetting(final String packageName, String className, int newState, 20258 final int flags, int userId, String callingPackage) { 20259 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20260 || newState == COMPONENT_ENABLED_STATE_ENABLED 20261 || newState == COMPONENT_ENABLED_STATE_DISABLED 20262 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20263 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20264 throw new IllegalArgumentException("Invalid new component state: " 20265 + newState); 20266 } 20267 PackageSetting pkgSetting; 20268 final int callingUid = Binder.getCallingUid(); 20269 final int permission; 20270 if (callingUid == Process.SYSTEM_UID) { 20271 permission = PackageManager.PERMISSION_GRANTED; 20272 } else { 20273 permission = mContext.checkCallingOrSelfPermission( 20274 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20275 } 20276 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20277 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20278 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20279 boolean sendNow = false; 20280 boolean isApp = (className == null); 20281 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20282 String componentName = isApp ? packageName : className; 20283 int packageUid = -1; 20284 ArrayList<String> components; 20285 20286 // reader 20287 synchronized (mPackages) { 20288 pkgSetting = mSettings.mPackages.get(packageName); 20289 if (pkgSetting == null) { 20290 if (!isCallerInstantApp) { 20291 if (className == null) { 20292 throw new IllegalArgumentException("Unknown package: " + packageName); 20293 } 20294 throw new IllegalArgumentException( 20295 "Unknown component: " + packageName + "/" + className); 20296 } else { 20297 // throw SecurityException to prevent leaking package information 20298 throw new SecurityException( 20299 "Attempt to change component state; " 20300 + "pid=" + Binder.getCallingPid() 20301 + ", uid=" + callingUid 20302 + (className == null 20303 ? ", package=" + packageName 20304 : ", component=" + packageName + "/" + className)); 20305 } 20306 } 20307 } 20308 20309 // Limit who can change which apps 20310 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20311 // Don't allow apps that don't have permission to modify other apps 20312 if (!allowedByPermission 20313 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20314 throw new SecurityException( 20315 "Attempt to change component state; " 20316 + "pid=" + Binder.getCallingPid() 20317 + ", uid=" + callingUid 20318 + (className == null 20319 ? ", package=" + packageName 20320 : ", component=" + packageName + "/" + className)); 20321 } 20322 // Don't allow changing protected packages. 20323 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20324 throw new SecurityException("Cannot disable a protected package: " + packageName); 20325 } 20326 } 20327 20328 synchronized (mPackages) { 20329 if (callingUid == Process.SHELL_UID 20330 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20331 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20332 // unless it is a test package. 20333 int oldState = pkgSetting.getEnabled(userId); 20334 if (className == null 20335 && 20336 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20337 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20338 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20339 && 20340 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20341 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20342 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20343 // ok 20344 } else { 20345 throw new SecurityException( 20346 "Shell cannot change component state for " + packageName + "/" 20347 + className + " to " + newState); 20348 } 20349 } 20350 } 20351 if (className == null) { 20352 // We're dealing with an application/package level state change 20353 synchronized (mPackages) { 20354 if (pkgSetting.getEnabled(userId) == newState) { 20355 // Nothing to do 20356 return; 20357 } 20358 } 20359 // If we're enabling a system stub, there's a little more work to do. 20360 // Prior to enabling the package, we need to decompress the APK(s) to the 20361 // data partition and then replace the version on the system partition. 20362 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20363 final boolean isSystemStub = deletedPkg.isStub 20364 && deletedPkg.isSystem(); 20365 if (isSystemStub 20366 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20367 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20368 final File codePath = decompressPackage(deletedPkg); 20369 if (codePath == null) { 20370 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20371 return; 20372 } 20373 // TODO remove direct parsing of the package object during internal cleanup 20374 // of scan package 20375 // We need to call parse directly here for no other reason than we need 20376 // the new package in order to disable the old one [we use the information 20377 // for some internal optimization to optionally create a new package setting 20378 // object on replace]. However, we can't get the package from the scan 20379 // because the scan modifies live structures and we need to remove the 20380 // old [system] package from the system before a scan can be attempted. 20381 // Once scan is indempotent we can remove this parse and use the package 20382 // object we scanned, prior to adding it to package settings. 20383 final PackageParser pp = new PackageParser(); 20384 pp.setSeparateProcesses(mSeparateProcesses); 20385 pp.setDisplayMetrics(mMetrics); 20386 pp.setCallback(mPackageParserCallback); 20387 final PackageParser.Package tmpPkg; 20388 try { 20389 final @ParseFlags int parseFlags = mDefParseFlags 20390 | PackageParser.PARSE_MUST_BE_APK 20391 | PackageParser.PARSE_IS_SYSTEM_DIR; 20392 tmpPkg = pp.parsePackage(codePath, parseFlags); 20393 } catch (PackageParserException e) { 20394 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20395 return; 20396 } 20397 synchronized (mInstallLock) { 20398 // Disable the stub and remove any package entries 20399 removePackageLI(deletedPkg, true); 20400 synchronized (mPackages) { 20401 disableSystemPackageLPw(deletedPkg, tmpPkg); 20402 } 20403 final PackageParser.Package pkg; 20404 try (PackageFreezer freezer = 20405 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20406 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20407 | PackageParser.PARSE_ENFORCE_CODE; 20408 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20409 0 /*currentTime*/, null /*user*/); 20410 prepareAppDataAfterInstallLIF(pkg); 20411 synchronized (mPackages) { 20412 try { 20413 updateSharedLibrariesLPr(pkg, null); 20414 } catch (PackageManagerException e) { 20415 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20416 } 20417 mPermissionManager.updatePermissions( 20418 pkg.packageName, pkg, true, mPackages.values(), 20419 mPermissionCallback); 20420 mSettings.writeLPr(); 20421 } 20422 } catch (PackageManagerException e) { 20423 // Whoops! Something went wrong; try to roll back to the stub 20424 Slog.w(TAG, "Failed to install compressed system package:" 20425 + pkgSetting.name, e); 20426 // Remove the failed install 20427 removeCodePathLI(codePath); 20428 20429 // Install the system package 20430 try (PackageFreezer freezer = 20431 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20432 synchronized (mPackages) { 20433 // NOTE: The system package always needs to be enabled; even 20434 // if it's for a compressed stub. If we don't, installing the 20435 // system package fails during scan [scanning checks the disabled 20436 // packages]. We will reverse this later, after we've "installed" 20437 // the stub. 20438 // This leaves us in a fragile state; the stub should never be 20439 // enabled, so, cross your fingers and hope nothing goes wrong 20440 // until we can disable the package later. 20441 enableSystemPackageLPw(deletedPkg); 20442 } 20443 installPackageFromSystemLIF(deletedPkg.codePath, 20444 false /*isPrivileged*/, null /*allUserHandles*/, 20445 null /*origUserHandles*/, null /*origPermissionsState*/, 20446 true /*writeSettings*/); 20447 } catch (PackageManagerException pme) { 20448 Slog.w(TAG, "Failed to restore system package:" 20449 + deletedPkg.packageName, pme); 20450 } finally { 20451 synchronized (mPackages) { 20452 mSettings.disableSystemPackageLPw( 20453 deletedPkg.packageName, true /*replaced*/); 20454 mSettings.writeLPr(); 20455 } 20456 } 20457 return; 20458 } 20459 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20460 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20461 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20462 mDexManager.notifyPackageUpdated(pkg.packageName, 20463 pkg.baseCodePath, pkg.splitCodePaths); 20464 } 20465 } 20466 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20467 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20468 // Don't care about who enables an app. 20469 callingPackage = null; 20470 } 20471 synchronized (mPackages) { 20472 pkgSetting.setEnabled(newState, userId, callingPackage); 20473 } 20474 } else { 20475 synchronized (mPackages) { 20476 // We're dealing with a component level state change 20477 // First, verify that this is a valid class name. 20478 PackageParser.Package pkg = pkgSetting.pkg; 20479 if (pkg == null || !pkg.hasComponentClassName(className)) { 20480 if (pkg != null && 20481 pkg.applicationInfo.targetSdkVersion >= 20482 Build.VERSION_CODES.JELLY_BEAN) { 20483 throw new IllegalArgumentException("Component class " + className 20484 + " does not exist in " + packageName); 20485 } else { 20486 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20487 + className + " does not exist in " + packageName); 20488 } 20489 } 20490 switch (newState) { 20491 case COMPONENT_ENABLED_STATE_ENABLED: 20492 if (!pkgSetting.enableComponentLPw(className, userId)) { 20493 return; 20494 } 20495 break; 20496 case COMPONENT_ENABLED_STATE_DISABLED: 20497 if (!pkgSetting.disableComponentLPw(className, userId)) { 20498 return; 20499 } 20500 break; 20501 case COMPONENT_ENABLED_STATE_DEFAULT: 20502 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20503 return; 20504 } 20505 break; 20506 default: 20507 Slog.e(TAG, "Invalid new component state: " + newState); 20508 return; 20509 } 20510 } 20511 } 20512 synchronized (mPackages) { 20513 scheduleWritePackageRestrictionsLocked(userId); 20514 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20515 final long callingId = Binder.clearCallingIdentity(); 20516 try { 20517 updateInstantAppInstallerLocked(packageName); 20518 } finally { 20519 Binder.restoreCallingIdentity(callingId); 20520 } 20521 components = mPendingBroadcasts.get(userId, packageName); 20522 final boolean newPackage = components == null; 20523 if (newPackage) { 20524 components = new ArrayList<String>(); 20525 } 20526 if (!components.contains(componentName)) { 20527 components.add(componentName); 20528 } 20529 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20530 sendNow = true; 20531 // Purge entry from pending broadcast list if another one exists already 20532 // since we are sending one right away. 20533 mPendingBroadcasts.remove(userId, packageName); 20534 } else { 20535 if (newPackage) { 20536 mPendingBroadcasts.put(userId, packageName, components); 20537 } 20538 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20539 // Schedule a message 20540 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20541 } 20542 } 20543 } 20544 20545 long callingId = Binder.clearCallingIdentity(); 20546 try { 20547 if (sendNow) { 20548 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20549 sendPackageChangedBroadcast(packageName, 20550 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20551 } 20552 } finally { 20553 Binder.restoreCallingIdentity(callingId); 20554 } 20555 } 20556 20557 @Override 20558 public void flushPackageRestrictionsAsUser(int userId) { 20559 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20560 return; 20561 } 20562 if (!sUserManager.exists(userId)) { 20563 return; 20564 } 20565 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20566 false /* checkShell */, "flushPackageRestrictions"); 20567 synchronized (mPackages) { 20568 mSettings.writePackageRestrictionsLPr(userId); 20569 mDirtyUsers.remove(userId); 20570 if (mDirtyUsers.isEmpty()) { 20571 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20572 } 20573 } 20574 } 20575 20576 private void sendPackageChangedBroadcast(String packageName, 20577 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20578 if (DEBUG_INSTALL) 20579 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20580 + componentNames); 20581 Bundle extras = new Bundle(4); 20582 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20583 String nameList[] = new String[componentNames.size()]; 20584 componentNames.toArray(nameList); 20585 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20586 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20587 extras.putInt(Intent.EXTRA_UID, packageUid); 20588 // If this is not reporting a change of the overall package, then only send it 20589 // to registered receivers. We don't want to launch a swath of apps for every 20590 // little component state change. 20591 final int flags = !componentNames.contains(packageName) 20592 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20593 final int userId = UserHandle.getUserId(packageUid); 20594 final boolean isInstantApp = isInstantApp(packageName, userId); 20595 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20596 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20597 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20598 userIds, instantUserIds); 20599 } 20600 20601 @Override 20602 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20603 if (!sUserManager.exists(userId)) return; 20604 final int callingUid = Binder.getCallingUid(); 20605 if (getInstantAppPackageName(callingUid) != null) { 20606 return; 20607 } 20608 final int permission = mContext.checkCallingOrSelfPermission( 20609 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20610 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20611 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20612 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20613 // writer 20614 synchronized (mPackages) { 20615 final PackageSetting ps = mSettings.mPackages.get(packageName); 20616 if (!filterAppAccessLPr(ps, callingUid, userId) 20617 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20618 allowedByPermission, callingUid, userId)) { 20619 scheduleWritePackageRestrictionsLocked(userId); 20620 } 20621 } 20622 } 20623 20624 @Override 20625 public String getInstallerPackageName(String packageName) { 20626 final int callingUid = Binder.getCallingUid(); 20627 if (getInstantAppPackageName(callingUid) != null) { 20628 return null; 20629 } 20630 // reader 20631 synchronized (mPackages) { 20632 final PackageSetting ps = mSettings.mPackages.get(packageName); 20633 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20634 return null; 20635 } 20636 return mSettings.getInstallerPackageNameLPr(packageName); 20637 } 20638 } 20639 20640 public boolean isOrphaned(String packageName) { 20641 // reader 20642 synchronized (mPackages) { 20643 return mSettings.isOrphaned(packageName); 20644 } 20645 } 20646 20647 @Override 20648 public int getApplicationEnabledSetting(String packageName, int userId) { 20649 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20650 int callingUid = Binder.getCallingUid(); 20651 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20652 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20653 // reader 20654 synchronized (mPackages) { 20655 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20656 return COMPONENT_ENABLED_STATE_DISABLED; 20657 } 20658 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20659 } 20660 } 20661 20662 @Override 20663 public int getComponentEnabledSetting(ComponentName component, int userId) { 20664 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20665 int callingUid = Binder.getCallingUid(); 20666 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20667 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20668 synchronized (mPackages) { 20669 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20670 component, TYPE_UNKNOWN, userId)) { 20671 return COMPONENT_ENABLED_STATE_DISABLED; 20672 } 20673 return mSettings.getComponentEnabledSettingLPr(component, userId); 20674 } 20675 } 20676 20677 @Override 20678 public void enterSafeMode() { 20679 enforceSystemOrRoot("Only the system can request entering safe mode"); 20680 20681 if (!mSystemReady) { 20682 mSafeMode = true; 20683 } 20684 } 20685 20686 @Override 20687 public void systemReady() { 20688 enforceSystemOrRoot("Only the system can claim the system is ready"); 20689 20690 mSystemReady = true; 20691 final ContentResolver resolver = mContext.getContentResolver(); 20692 ContentObserver co = new ContentObserver(mHandler) { 20693 @Override 20694 public void onChange(boolean selfChange) { 20695 mEphemeralAppsDisabled = 20696 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20697 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20698 } 20699 }; 20700 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20701 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20702 false, co, UserHandle.USER_SYSTEM); 20703 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20704 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20705 co.onChange(true); 20706 20707 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20708 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20709 // it is done. 20710 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20711 @Override 20712 public void onChange(boolean selfChange) { 20713 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20714 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20715 oobEnabled == 1 ? "true" : "false"); 20716 } 20717 }; 20718 mContext.getContentResolver().registerContentObserver( 20719 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20720 UserHandle.USER_SYSTEM); 20721 // At boot, restore the value from the setting, which persists across reboot. 20722 privAppOobObserver.onChange(true); 20723 20724 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20725 // disabled after already being started. 20726 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20727 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20728 20729 // Read the compatibilty setting when the system is ready. 20730 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20731 mContext.getContentResolver(), 20732 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20733 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20734 if (DEBUG_SETTINGS) { 20735 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20736 } 20737 20738 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20739 20740 synchronized (mPackages) { 20741 // Verify that all of the preferred activity components actually 20742 // exist. It is possible for applications to be updated and at 20743 // that point remove a previously declared activity component that 20744 // had been set as a preferred activity. We try to clean this up 20745 // the next time we encounter that preferred activity, but it is 20746 // possible for the user flow to never be able to return to that 20747 // situation so here we do a sanity check to make sure we haven't 20748 // left any junk around. 20749 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20750 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20751 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20752 removed.clear(); 20753 for (PreferredActivity pa : pir.filterSet()) { 20754 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20755 removed.add(pa); 20756 } 20757 } 20758 if (removed.size() > 0) { 20759 for (int r=0; r<removed.size(); r++) { 20760 PreferredActivity pa = removed.get(r); 20761 Slog.w(TAG, "Removing dangling preferred activity: " 20762 + pa.mPref.mComponent); 20763 pir.removeFilter(pa); 20764 } 20765 mSettings.writePackageRestrictionsLPr( 20766 mSettings.mPreferredActivities.keyAt(i)); 20767 } 20768 } 20769 20770 for (int userId : UserManagerService.getInstance().getUserIds()) { 20771 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20772 grantPermissionsUserIds = ArrayUtils.appendInt( 20773 grantPermissionsUserIds, userId); 20774 } 20775 } 20776 } 20777 sUserManager.systemReady(); 20778 // If we upgraded grant all default permissions before kicking off. 20779 for (int userId : grantPermissionsUserIds) { 20780 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20781 } 20782 20783 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20784 // If we did not grant default permissions, we preload from this the 20785 // default permission exceptions lazily to ensure we don't hit the 20786 // disk on a new user creation. 20787 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20788 } 20789 20790 // Now that we've scanned all packages, and granted any default 20791 // permissions, ensure permissions are updated. Beware of dragons if you 20792 // try optimizing this. 20793 synchronized (mPackages) { 20794 mPermissionManager.updateAllPermissions( 20795 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20796 mPermissionCallback); 20797 } 20798 20799 // Kick off any messages waiting for system ready 20800 if (mPostSystemReadyMessages != null) { 20801 for (Message msg : mPostSystemReadyMessages) { 20802 msg.sendToTarget(); 20803 } 20804 mPostSystemReadyMessages = null; 20805 } 20806 20807 // Watch for external volumes that come and go over time 20808 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20809 storage.registerListener(mStorageListener); 20810 20811 mInstallerService.systemReady(); 20812 mPackageDexOptimizer.systemReady(); 20813 20814 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20815 StorageManagerInternal.class); 20816 StorageManagerInternal.addExternalStoragePolicy( 20817 new StorageManagerInternal.ExternalStorageMountPolicy() { 20818 @Override 20819 public int getMountMode(int uid, String packageName) { 20820 if (Process.isIsolated(uid)) { 20821 return Zygote.MOUNT_EXTERNAL_NONE; 20822 } 20823 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20824 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20825 } 20826 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20827 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20828 } 20829 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20830 return Zygote.MOUNT_EXTERNAL_READ; 20831 } 20832 return Zygote.MOUNT_EXTERNAL_WRITE; 20833 } 20834 20835 @Override 20836 public boolean hasExternalStorage(int uid, String packageName) { 20837 return true; 20838 } 20839 }); 20840 20841 // Now that we're mostly running, clean up stale users and apps 20842 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20843 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20844 20845 mPermissionManager.systemReady(); 20846 } 20847 20848 public void waitForAppDataPrepared() { 20849 if (mPrepareAppDataFuture == null) { 20850 return; 20851 } 20852 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20853 mPrepareAppDataFuture = null; 20854 } 20855 20856 @Override 20857 public boolean isSafeMode() { 20858 // allow instant applications 20859 return mSafeMode; 20860 } 20861 20862 @Override 20863 public boolean hasSystemUidErrors() { 20864 // allow instant applications 20865 return mHasSystemUidErrors; 20866 } 20867 20868 static String arrayToString(int[] array) { 20869 StringBuffer buf = new StringBuffer(128); 20870 buf.append('['); 20871 if (array != null) { 20872 for (int i=0; i<array.length; i++) { 20873 if (i > 0) buf.append(", "); 20874 buf.append(array[i]); 20875 } 20876 } 20877 buf.append(']'); 20878 return buf.toString(); 20879 } 20880 20881 @Override 20882 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20883 FileDescriptor err, String[] args, ShellCallback callback, 20884 ResultReceiver resultReceiver) { 20885 (new PackageManagerShellCommand(this)).exec( 20886 this, in, out, err, args, callback, resultReceiver); 20887 } 20888 20889 @Override 20890 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20891 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20892 20893 DumpState dumpState = new DumpState(); 20894 boolean fullPreferred = false; 20895 boolean checkin = false; 20896 20897 String packageName = null; 20898 ArraySet<String> permissionNames = null; 20899 20900 int opti = 0; 20901 while (opti < args.length) { 20902 String opt = args[opti]; 20903 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20904 break; 20905 } 20906 opti++; 20907 20908 if ("-a".equals(opt)) { 20909 // Right now we only know how to print all. 20910 } else if ("-h".equals(opt)) { 20911 pw.println("Package manager dump options:"); 20912 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20913 pw.println(" --checkin: dump for a checkin"); 20914 pw.println(" -f: print details of intent filters"); 20915 pw.println(" -h: print this help"); 20916 pw.println(" cmd may be one of:"); 20917 pw.println(" l[ibraries]: list known shared libraries"); 20918 pw.println(" f[eatures]: list device features"); 20919 pw.println(" k[eysets]: print known keysets"); 20920 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20921 pw.println(" perm[issions]: dump permissions"); 20922 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20923 pw.println(" pref[erred]: print preferred package settings"); 20924 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20925 pw.println(" prov[iders]: dump content providers"); 20926 pw.println(" p[ackages]: dump installed packages"); 20927 pw.println(" s[hared-users]: dump shared user IDs"); 20928 pw.println(" m[essages]: print collected runtime messages"); 20929 pw.println(" v[erifiers]: print package verifier info"); 20930 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20931 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20932 pw.println(" version: print database version info"); 20933 pw.println(" write: write current settings now"); 20934 pw.println(" installs: details about install sessions"); 20935 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20936 pw.println(" dexopt: dump dexopt state"); 20937 pw.println(" compiler-stats: dump compiler statistics"); 20938 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20939 pw.println(" service-permissions: dump permissions required by services"); 20940 pw.println(" <package.name>: info about given package"); 20941 return; 20942 } else if ("--checkin".equals(opt)) { 20943 checkin = true; 20944 } else if ("-f".equals(opt)) { 20945 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20946 } else if ("--proto".equals(opt)) { 20947 dumpProto(fd); 20948 return; 20949 } else { 20950 pw.println("Unknown argument: " + opt + "; use -h for help"); 20951 } 20952 } 20953 20954 // Is the caller requesting to dump a particular piece of data? 20955 if (opti < args.length) { 20956 String cmd = args[opti]; 20957 opti++; 20958 // Is this a package name? 20959 if ("android".equals(cmd) || cmd.contains(".")) { 20960 packageName = cmd; 20961 // When dumping a single package, we always dump all of its 20962 // filter information since the amount of data will be reasonable. 20963 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20964 } else if ("check-permission".equals(cmd)) { 20965 if (opti >= args.length) { 20966 pw.println("Error: check-permission missing permission argument"); 20967 return; 20968 } 20969 String perm = args[opti]; 20970 opti++; 20971 if (opti >= args.length) { 20972 pw.println("Error: check-permission missing package argument"); 20973 return; 20974 } 20975 20976 String pkg = args[opti]; 20977 opti++; 20978 int user = UserHandle.getUserId(Binder.getCallingUid()); 20979 if (opti < args.length) { 20980 try { 20981 user = Integer.parseInt(args[opti]); 20982 } catch (NumberFormatException e) { 20983 pw.println("Error: check-permission user argument is not a number: " 20984 + args[opti]); 20985 return; 20986 } 20987 } 20988 20989 // Normalize package name to handle renamed packages and static libs 20990 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20991 20992 pw.println(checkPermission(perm, pkg, user)); 20993 return; 20994 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20995 dumpState.setDump(DumpState.DUMP_LIBS); 20996 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20997 dumpState.setDump(DumpState.DUMP_FEATURES); 20998 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20999 if (opti >= args.length) { 21000 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21001 | DumpState.DUMP_SERVICE_RESOLVERS 21002 | DumpState.DUMP_RECEIVER_RESOLVERS 21003 | DumpState.DUMP_CONTENT_RESOLVERS); 21004 } else { 21005 while (opti < args.length) { 21006 String name = args[opti]; 21007 if ("a".equals(name) || "activity".equals(name)) { 21008 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21009 } else if ("s".equals(name) || "service".equals(name)) { 21010 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21011 } else if ("r".equals(name) || "receiver".equals(name)) { 21012 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21013 } else if ("c".equals(name) || "content".equals(name)) { 21014 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21015 } else { 21016 pw.println("Error: unknown resolver table type: " + name); 21017 return; 21018 } 21019 opti++; 21020 } 21021 } 21022 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21023 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21024 } else if ("permission".equals(cmd)) { 21025 if (opti >= args.length) { 21026 pw.println("Error: permission requires permission name"); 21027 return; 21028 } 21029 permissionNames = new ArraySet<>(); 21030 while (opti < args.length) { 21031 permissionNames.add(args[opti]); 21032 opti++; 21033 } 21034 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21035 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21036 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21037 dumpState.setDump(DumpState.DUMP_PREFERRED); 21038 } else if ("preferred-xml".equals(cmd)) { 21039 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21040 if (opti < args.length && "--full".equals(args[opti])) { 21041 fullPreferred = true; 21042 opti++; 21043 } 21044 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21045 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21046 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21047 dumpState.setDump(DumpState.DUMP_PACKAGES); 21048 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21049 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21050 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21051 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21052 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21053 dumpState.setDump(DumpState.DUMP_MESSAGES); 21054 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21055 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21056 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21057 || "intent-filter-verifiers".equals(cmd)) { 21058 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21059 } else if ("version".equals(cmd)) { 21060 dumpState.setDump(DumpState.DUMP_VERSION); 21061 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21062 dumpState.setDump(DumpState.DUMP_KEYSETS); 21063 } else if ("installs".equals(cmd)) { 21064 dumpState.setDump(DumpState.DUMP_INSTALLS); 21065 } else if ("frozen".equals(cmd)) { 21066 dumpState.setDump(DumpState.DUMP_FROZEN); 21067 } else if ("volumes".equals(cmd)) { 21068 dumpState.setDump(DumpState.DUMP_VOLUMES); 21069 } else if ("dexopt".equals(cmd)) { 21070 dumpState.setDump(DumpState.DUMP_DEXOPT); 21071 } else if ("compiler-stats".equals(cmd)) { 21072 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21073 } else if ("changes".equals(cmd)) { 21074 dumpState.setDump(DumpState.DUMP_CHANGES); 21075 } else if ("service-permissions".equals(cmd)) { 21076 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21077 } else if ("write".equals(cmd)) { 21078 synchronized (mPackages) { 21079 mSettings.writeLPr(); 21080 pw.println("Settings written."); 21081 return; 21082 } 21083 } 21084 } 21085 21086 if (checkin) { 21087 pw.println("vers,1"); 21088 } 21089 21090 // reader 21091 synchronized (mPackages) { 21092 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21093 if (!checkin) { 21094 if (dumpState.onTitlePrinted()) 21095 pw.println(); 21096 pw.println("Database versions:"); 21097 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21098 } 21099 } 21100 21101 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21102 if (!checkin) { 21103 if (dumpState.onTitlePrinted()) 21104 pw.println(); 21105 pw.println("Verifiers:"); 21106 pw.print(" Required: "); 21107 pw.print(mRequiredVerifierPackage); 21108 pw.print(" (uid="); 21109 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21110 UserHandle.USER_SYSTEM)); 21111 pw.println(")"); 21112 } else if (mRequiredVerifierPackage != null) { 21113 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21114 pw.print(","); 21115 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21116 UserHandle.USER_SYSTEM)); 21117 } 21118 } 21119 21120 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21121 packageName == null) { 21122 if (mIntentFilterVerifierComponent != null) { 21123 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21124 if (!checkin) { 21125 if (dumpState.onTitlePrinted()) 21126 pw.println(); 21127 pw.println("Intent Filter Verifier:"); 21128 pw.print(" Using: "); 21129 pw.print(verifierPackageName); 21130 pw.print(" (uid="); 21131 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21132 UserHandle.USER_SYSTEM)); 21133 pw.println(")"); 21134 } else if (verifierPackageName != null) { 21135 pw.print("ifv,"); pw.print(verifierPackageName); 21136 pw.print(","); 21137 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21138 UserHandle.USER_SYSTEM)); 21139 } 21140 } else { 21141 pw.println(); 21142 pw.println("No Intent Filter Verifier available!"); 21143 } 21144 } 21145 21146 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21147 boolean printedHeader = false; 21148 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21149 while (it.hasNext()) { 21150 String libName = it.next(); 21151 LongSparseArray<SharedLibraryEntry> versionedLib 21152 = mSharedLibraries.get(libName); 21153 if (versionedLib == null) { 21154 continue; 21155 } 21156 final int versionCount = versionedLib.size(); 21157 for (int i = 0; i < versionCount; i++) { 21158 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 21159 if (!checkin) { 21160 if (!printedHeader) { 21161 if (dumpState.onTitlePrinted()) 21162 pw.println(); 21163 pw.println("Libraries:"); 21164 printedHeader = true; 21165 } 21166 pw.print(" "); 21167 } else { 21168 pw.print("lib,"); 21169 } 21170 pw.print(libEntry.info.getName()); 21171 if (libEntry.info.isStatic()) { 21172 pw.print(" version=" + libEntry.info.getLongVersion()); 21173 } 21174 if (!checkin) { 21175 pw.print(" -> "); 21176 } 21177 if (libEntry.path != null) { 21178 pw.print(" (jar) "); 21179 pw.print(libEntry.path); 21180 } else { 21181 pw.print(" (apk) "); 21182 pw.print(libEntry.apk); 21183 } 21184 pw.println(); 21185 } 21186 } 21187 } 21188 21189 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21190 if (dumpState.onTitlePrinted()) 21191 pw.println(); 21192 if (!checkin) { 21193 pw.println("Features:"); 21194 } 21195 21196 synchronized (mAvailableFeatures) { 21197 for (FeatureInfo feat : mAvailableFeatures.values()) { 21198 if (checkin) { 21199 pw.print("feat,"); 21200 pw.print(feat.name); 21201 pw.print(","); 21202 pw.println(feat.version); 21203 } else { 21204 pw.print(" "); 21205 pw.print(feat.name); 21206 if (feat.version > 0) { 21207 pw.print(" version="); 21208 pw.print(feat.version); 21209 } 21210 pw.println(); 21211 } 21212 } 21213 } 21214 } 21215 21216 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21217 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 21218 : "Activity Resolver Table:", " ", packageName, 21219 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21220 dumpState.setTitlePrinted(true); 21221 } 21222 } 21223 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21224 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 21225 : "Receiver Resolver Table:", " ", packageName, 21226 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21227 dumpState.setTitlePrinted(true); 21228 } 21229 } 21230 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21231 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 21232 : "Service Resolver Table:", " ", packageName, 21233 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21234 dumpState.setTitlePrinted(true); 21235 } 21236 } 21237 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21238 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 21239 : "Provider Resolver Table:", " ", packageName, 21240 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 21241 dumpState.setTitlePrinted(true); 21242 } 21243 } 21244 21245 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21246 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21247 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21248 int user = mSettings.mPreferredActivities.keyAt(i); 21249 if (pir.dump(pw, 21250 dumpState.getTitlePrinted() 21251 ? "\nPreferred Activities User " + user + ":" 21252 : "Preferred Activities User " + user + ":", " ", 21253 packageName, true, false)) { 21254 dumpState.setTitlePrinted(true); 21255 } 21256 } 21257 } 21258 21259 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21260 pw.flush(); 21261 FileOutputStream fout = new FileOutputStream(fd); 21262 BufferedOutputStream str = new BufferedOutputStream(fout); 21263 XmlSerializer serializer = new FastXmlSerializer(); 21264 try { 21265 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21266 serializer.startDocument(null, true); 21267 serializer.setFeature( 21268 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21269 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21270 serializer.endDocument(); 21271 serializer.flush(); 21272 } catch (IllegalArgumentException e) { 21273 pw.println("Failed writing: " + e); 21274 } catch (IllegalStateException e) { 21275 pw.println("Failed writing: " + e); 21276 } catch (IOException e) { 21277 pw.println("Failed writing: " + e); 21278 } 21279 } 21280 21281 if (!checkin 21282 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21283 && packageName == null) { 21284 pw.println(); 21285 int count = mSettings.mPackages.size(); 21286 if (count == 0) { 21287 pw.println("No applications!"); 21288 pw.println(); 21289 } else { 21290 final String prefix = " "; 21291 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21292 if (allPackageSettings.size() == 0) { 21293 pw.println("No domain preferred apps!"); 21294 pw.println(); 21295 } else { 21296 pw.println("App verification status:"); 21297 pw.println(); 21298 count = 0; 21299 for (PackageSetting ps : allPackageSettings) { 21300 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21301 if (ivi == null || ivi.getPackageName() == null) continue; 21302 pw.println(prefix + "Package: " + ivi.getPackageName()); 21303 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21304 pw.println(prefix + "Status: " + ivi.getStatusString()); 21305 pw.println(); 21306 count++; 21307 } 21308 if (count == 0) { 21309 pw.println(prefix + "No app verification established."); 21310 pw.println(); 21311 } 21312 for (int userId : sUserManager.getUserIds()) { 21313 pw.println("App linkages for user " + userId + ":"); 21314 pw.println(); 21315 count = 0; 21316 for (PackageSetting ps : allPackageSettings) { 21317 final long status = ps.getDomainVerificationStatusForUser(userId); 21318 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21319 && !DEBUG_DOMAIN_VERIFICATION) { 21320 continue; 21321 } 21322 pw.println(prefix + "Package: " + ps.name); 21323 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21324 String statusStr = IntentFilterVerificationInfo. 21325 getStatusStringFromValue(status); 21326 pw.println(prefix + "Status: " + statusStr); 21327 pw.println(); 21328 count++; 21329 } 21330 if (count == 0) { 21331 pw.println(prefix + "No configured app linkages."); 21332 pw.println(); 21333 } 21334 } 21335 } 21336 } 21337 } 21338 21339 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21340 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21341 } 21342 21343 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21344 boolean printedSomething = false; 21345 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21346 if (packageName != null && !packageName.equals(p.info.packageName)) { 21347 continue; 21348 } 21349 if (!printedSomething) { 21350 if (dumpState.onTitlePrinted()) 21351 pw.println(); 21352 pw.println("Registered ContentProviders:"); 21353 printedSomething = true; 21354 } 21355 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21356 pw.print(" "); pw.println(p.toString()); 21357 } 21358 printedSomething = false; 21359 for (Map.Entry<String, PackageParser.Provider> entry : 21360 mProvidersByAuthority.entrySet()) { 21361 PackageParser.Provider p = entry.getValue(); 21362 if (packageName != null && !packageName.equals(p.info.packageName)) { 21363 continue; 21364 } 21365 if (!printedSomething) { 21366 if (dumpState.onTitlePrinted()) 21367 pw.println(); 21368 pw.println("ContentProvider Authorities:"); 21369 printedSomething = true; 21370 } 21371 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21372 pw.print(" "); pw.println(p.toString()); 21373 if (p.info != null && p.info.applicationInfo != null) { 21374 final String appInfo = p.info.applicationInfo.toString(); 21375 pw.print(" applicationInfo="); pw.println(appInfo); 21376 } 21377 } 21378 } 21379 21380 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21381 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21382 } 21383 21384 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21385 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21386 } 21387 21388 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21389 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21390 } 21391 21392 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21393 if (dumpState.onTitlePrinted()) pw.println(); 21394 pw.println("Package Changes:"); 21395 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21396 final int K = mChangedPackages.size(); 21397 for (int i = 0; i < K; i++) { 21398 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21399 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21400 final int N = changes.size(); 21401 if (N == 0) { 21402 pw.print(" "); pw.println("No packages changed"); 21403 } else { 21404 for (int j = 0; j < N; j++) { 21405 final String pkgName = changes.valueAt(j); 21406 final int sequenceNumber = changes.keyAt(j); 21407 pw.print(" "); 21408 pw.print("seq="); 21409 pw.print(sequenceNumber); 21410 pw.print(", package="); 21411 pw.println(pkgName); 21412 } 21413 } 21414 } 21415 } 21416 21417 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21418 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21419 } 21420 21421 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21422 // XXX should handle packageName != null by dumping only install data that 21423 // the given package is involved with. 21424 if (dumpState.onTitlePrinted()) pw.println(); 21425 21426 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21427 ipw.println(); 21428 ipw.println("Frozen packages:"); 21429 ipw.increaseIndent(); 21430 if (mFrozenPackages.size() == 0) { 21431 ipw.println("(none)"); 21432 } else { 21433 for (int i = 0; i < mFrozenPackages.size(); i++) { 21434 ipw.println(mFrozenPackages.valueAt(i)); 21435 } 21436 } 21437 ipw.decreaseIndent(); 21438 } 21439 21440 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21441 if (dumpState.onTitlePrinted()) pw.println(); 21442 21443 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21444 ipw.println(); 21445 ipw.println("Loaded volumes:"); 21446 ipw.increaseIndent(); 21447 if (mLoadedVolumes.size() == 0) { 21448 ipw.println("(none)"); 21449 } else { 21450 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21451 ipw.println(mLoadedVolumes.valueAt(i)); 21452 } 21453 } 21454 ipw.decreaseIndent(); 21455 } 21456 21457 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21458 && packageName == null) { 21459 if (dumpState.onTitlePrinted()) pw.println(); 21460 pw.println("Service permissions:"); 21461 21462 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21463 while (filterIterator.hasNext()) { 21464 final ServiceIntentInfo info = filterIterator.next(); 21465 final ServiceInfo serviceInfo = info.service.info; 21466 final String permission = serviceInfo.permission; 21467 if (permission != null) { 21468 pw.print(" "); 21469 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21470 pw.print(": "); 21471 pw.println(permission); 21472 } 21473 } 21474 } 21475 21476 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21477 if (dumpState.onTitlePrinted()) pw.println(); 21478 dumpDexoptStateLPr(pw, packageName); 21479 } 21480 21481 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21482 if (dumpState.onTitlePrinted()) pw.println(); 21483 dumpCompilerStatsLPr(pw, packageName); 21484 } 21485 21486 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21487 if (dumpState.onTitlePrinted()) pw.println(); 21488 mSettings.dumpReadMessagesLPr(pw, dumpState); 21489 21490 pw.println(); 21491 pw.println("Package warning messages:"); 21492 dumpCriticalInfo(pw, null); 21493 } 21494 21495 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21496 dumpCriticalInfo(pw, "msg,"); 21497 } 21498 } 21499 21500 // PackageInstaller should be called outside of mPackages lock 21501 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21502 // XXX should handle packageName != null by dumping only install data that 21503 // the given package is involved with. 21504 if (dumpState.onTitlePrinted()) pw.println(); 21505 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21506 } 21507 } 21508 21509 private void dumpProto(FileDescriptor fd) { 21510 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21511 21512 synchronized (mPackages) { 21513 final long requiredVerifierPackageToken = 21514 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21515 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21516 proto.write( 21517 PackageServiceDumpProto.PackageShortProto.UID, 21518 getPackageUid( 21519 mRequiredVerifierPackage, 21520 MATCH_DEBUG_TRIAGED_MISSING, 21521 UserHandle.USER_SYSTEM)); 21522 proto.end(requiredVerifierPackageToken); 21523 21524 if (mIntentFilterVerifierComponent != null) { 21525 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21526 final long verifierPackageToken = 21527 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21528 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21529 proto.write( 21530 PackageServiceDumpProto.PackageShortProto.UID, 21531 getPackageUid( 21532 verifierPackageName, 21533 MATCH_DEBUG_TRIAGED_MISSING, 21534 UserHandle.USER_SYSTEM)); 21535 proto.end(verifierPackageToken); 21536 } 21537 21538 dumpSharedLibrariesProto(proto); 21539 dumpFeaturesProto(proto); 21540 mSettings.dumpPackagesProto(proto); 21541 mSettings.dumpSharedUsersProto(proto); 21542 dumpCriticalInfo(proto); 21543 } 21544 proto.flush(); 21545 } 21546 21547 private void dumpFeaturesProto(ProtoOutputStream proto) { 21548 synchronized (mAvailableFeatures) { 21549 final int count = mAvailableFeatures.size(); 21550 for (int i = 0; i < count; i++) { 21551 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21552 } 21553 } 21554 } 21555 21556 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21557 final int count = mSharedLibraries.size(); 21558 for (int i = 0; i < count; i++) { 21559 final String libName = mSharedLibraries.keyAt(i); 21560 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21561 if (versionedLib == null) { 21562 continue; 21563 } 21564 final int versionCount = versionedLib.size(); 21565 for (int j = 0; j < versionCount; j++) { 21566 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21567 final long sharedLibraryToken = 21568 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21569 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21570 final boolean isJar = (libEntry.path != null); 21571 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21572 if (isJar) { 21573 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21574 } else { 21575 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21576 } 21577 proto.end(sharedLibraryToken); 21578 } 21579 } 21580 } 21581 21582 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21583 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21584 ipw.println(); 21585 ipw.println("Dexopt state:"); 21586 ipw.increaseIndent(); 21587 Collection<PackageParser.Package> packages = null; 21588 if (packageName != null) { 21589 PackageParser.Package targetPackage = mPackages.get(packageName); 21590 if (targetPackage != null) { 21591 packages = Collections.singletonList(targetPackage); 21592 } else { 21593 ipw.println("Unable to find package: " + packageName); 21594 return; 21595 } 21596 } else { 21597 packages = mPackages.values(); 21598 } 21599 21600 for (PackageParser.Package pkg : packages) { 21601 ipw.println("[" + pkg.packageName + "]"); 21602 ipw.increaseIndent(); 21603 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21604 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21605 ipw.decreaseIndent(); 21606 } 21607 } 21608 21609 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21610 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21611 ipw.println(); 21612 ipw.println("Compiler stats:"); 21613 ipw.increaseIndent(); 21614 Collection<PackageParser.Package> packages = null; 21615 if (packageName != null) { 21616 PackageParser.Package targetPackage = mPackages.get(packageName); 21617 if (targetPackage != null) { 21618 packages = Collections.singletonList(targetPackage); 21619 } else { 21620 ipw.println("Unable to find package: " + packageName); 21621 return; 21622 } 21623 } else { 21624 packages = mPackages.values(); 21625 } 21626 21627 for (PackageParser.Package pkg : packages) { 21628 ipw.println("[" + pkg.packageName + "]"); 21629 ipw.increaseIndent(); 21630 21631 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21632 if (stats == null) { 21633 ipw.println("(No recorded stats)"); 21634 } else { 21635 stats.dump(ipw); 21636 } 21637 ipw.decreaseIndent(); 21638 } 21639 } 21640 21641 private String dumpDomainString(String packageName) { 21642 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21643 .getList(); 21644 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21645 21646 ArraySet<String> result = new ArraySet<>(); 21647 if (iviList.size() > 0) { 21648 for (IntentFilterVerificationInfo ivi : iviList) { 21649 for (String host : ivi.getDomains()) { 21650 result.add(host); 21651 } 21652 } 21653 } 21654 if (filters != null && filters.size() > 0) { 21655 for (IntentFilter filter : filters) { 21656 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21657 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21658 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21659 result.addAll(filter.getHostsList()); 21660 } 21661 } 21662 } 21663 21664 StringBuilder sb = new StringBuilder(result.size() * 16); 21665 for (String domain : result) { 21666 if (sb.length() > 0) sb.append(" "); 21667 sb.append(domain); 21668 } 21669 return sb.toString(); 21670 } 21671 21672 // ------- apps on sdcard specific code ------- 21673 static final boolean DEBUG_SD_INSTALL = false; 21674 21675 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21676 21677 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21678 21679 private boolean mMediaMounted = false; 21680 21681 static String getEncryptKey() { 21682 try { 21683 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21684 SD_ENCRYPTION_KEYSTORE_NAME); 21685 if (sdEncKey == null) { 21686 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21687 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21688 if (sdEncKey == null) { 21689 Slog.e(TAG, "Failed to create encryption keys"); 21690 return null; 21691 } 21692 } 21693 return sdEncKey; 21694 } catch (NoSuchAlgorithmException nsae) { 21695 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21696 return null; 21697 } catch (IOException ioe) { 21698 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21699 return null; 21700 } 21701 } 21702 21703 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21704 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21705 final int size = infos.size(); 21706 final String[] packageNames = new String[size]; 21707 final int[] packageUids = new int[size]; 21708 for (int i = 0; i < size; i++) { 21709 final ApplicationInfo info = infos.get(i); 21710 packageNames[i] = info.packageName; 21711 packageUids[i] = info.uid; 21712 } 21713 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21714 finishedReceiver); 21715 } 21716 21717 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21718 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21719 sendResourcesChangedBroadcast(mediaStatus, replacing, 21720 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21721 } 21722 21723 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21724 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21725 int size = pkgList.length; 21726 if (size > 0) { 21727 // Send broadcasts here 21728 Bundle extras = new Bundle(); 21729 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21730 if (uidArr != null) { 21731 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21732 } 21733 if (replacing) { 21734 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21735 } 21736 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21737 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21738 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21739 } 21740 } 21741 21742 private void loadPrivatePackages(final VolumeInfo vol) { 21743 mHandler.post(new Runnable() { 21744 @Override 21745 public void run() { 21746 loadPrivatePackagesInner(vol); 21747 } 21748 }); 21749 } 21750 21751 private void loadPrivatePackagesInner(VolumeInfo vol) { 21752 final String volumeUuid = vol.fsUuid; 21753 if (TextUtils.isEmpty(volumeUuid)) { 21754 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21755 return; 21756 } 21757 21758 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21759 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21760 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21761 21762 final VersionInfo ver; 21763 final List<PackageSetting> packages; 21764 synchronized (mPackages) { 21765 ver = mSettings.findOrCreateVersion(volumeUuid); 21766 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21767 } 21768 21769 for (PackageSetting ps : packages) { 21770 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21771 synchronized (mInstallLock) { 21772 final PackageParser.Package pkg; 21773 try { 21774 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21775 loaded.add(pkg.applicationInfo); 21776 21777 } catch (PackageManagerException e) { 21778 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21779 } 21780 21781 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21782 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21783 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21784 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21785 } 21786 } 21787 } 21788 21789 // Reconcile app data for all started/unlocked users 21790 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21791 final UserManager um = mContext.getSystemService(UserManager.class); 21792 UserManagerInternal umInternal = getUserManagerInternal(); 21793 for (UserInfo user : um.getUsers()) { 21794 final int flags; 21795 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21796 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21797 } else if (umInternal.isUserRunning(user.id)) { 21798 flags = StorageManager.FLAG_STORAGE_DE; 21799 } else { 21800 continue; 21801 } 21802 21803 try { 21804 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21805 synchronized (mInstallLock) { 21806 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21807 } 21808 } catch (IllegalStateException e) { 21809 // Device was probably ejected, and we'll process that event momentarily 21810 Slog.w(TAG, "Failed to prepare storage: " + e); 21811 } 21812 } 21813 21814 synchronized (mPackages) { 21815 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21816 if (sdkUpdated) { 21817 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21818 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21819 } 21820 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21821 mPermissionCallback); 21822 21823 // Yay, everything is now upgraded 21824 ver.forceCurrent(); 21825 21826 mSettings.writeLPr(); 21827 } 21828 21829 for (PackageFreezer freezer : freezers) { 21830 freezer.close(); 21831 } 21832 21833 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21834 sendResourcesChangedBroadcast(true, false, loaded, null); 21835 mLoadedVolumes.add(vol.getId()); 21836 } 21837 21838 private void unloadPrivatePackages(final VolumeInfo vol) { 21839 mHandler.post(new Runnable() { 21840 @Override 21841 public void run() { 21842 unloadPrivatePackagesInner(vol); 21843 } 21844 }); 21845 } 21846 21847 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21848 final String volumeUuid = vol.fsUuid; 21849 if (TextUtils.isEmpty(volumeUuid)) { 21850 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21851 return; 21852 } 21853 21854 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21855 synchronized (mInstallLock) { 21856 synchronized (mPackages) { 21857 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21858 for (PackageSetting ps : packages) { 21859 if (ps.pkg == null) continue; 21860 21861 final ApplicationInfo info = ps.pkg.applicationInfo; 21862 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21863 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21864 21865 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21866 "unloadPrivatePackagesInner")) { 21867 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21868 false, null)) { 21869 unloaded.add(info); 21870 } else { 21871 Slog.w(TAG, "Failed to unload " + ps.codePath); 21872 } 21873 } 21874 21875 // Try very hard to release any references to this package 21876 // so we don't risk the system server being killed due to 21877 // open FDs 21878 AttributeCache.instance().removePackage(ps.name); 21879 } 21880 21881 mSettings.writeLPr(); 21882 } 21883 } 21884 21885 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21886 sendResourcesChangedBroadcast(false, false, unloaded, null); 21887 mLoadedVolumes.remove(vol.getId()); 21888 21889 // Try very hard to release any references to this path so we don't risk 21890 // the system server being killed due to open FDs 21891 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21892 21893 for (int i = 0; i < 3; i++) { 21894 System.gc(); 21895 System.runFinalization(); 21896 } 21897 } 21898 21899 private void assertPackageKnown(String volumeUuid, String packageName) 21900 throws PackageManagerException { 21901 synchronized (mPackages) { 21902 // Normalize package name to handle renamed packages 21903 packageName = normalizePackageNameLPr(packageName); 21904 21905 final PackageSetting ps = mSettings.mPackages.get(packageName); 21906 if (ps == null) { 21907 throw new PackageManagerException("Package " + packageName + " is unknown"); 21908 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21909 throw new PackageManagerException( 21910 "Package " + packageName + " found on unknown volume " + volumeUuid 21911 + "; expected volume " + ps.volumeUuid); 21912 } 21913 } 21914 } 21915 21916 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21917 throws PackageManagerException { 21918 synchronized (mPackages) { 21919 // Normalize package name to handle renamed packages 21920 packageName = normalizePackageNameLPr(packageName); 21921 21922 final PackageSetting ps = mSettings.mPackages.get(packageName); 21923 if (ps == null) { 21924 throw new PackageManagerException("Package " + packageName + " is unknown"); 21925 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21926 throw new PackageManagerException( 21927 "Package " + packageName + " found on unknown volume " + volumeUuid 21928 + "; expected volume " + ps.volumeUuid); 21929 } else if (!ps.getInstalled(userId)) { 21930 throw new PackageManagerException( 21931 "Package " + packageName + " not installed for user " + userId); 21932 } 21933 } 21934 } 21935 21936 private List<String> collectAbsoluteCodePaths() { 21937 synchronized (mPackages) { 21938 List<String> codePaths = new ArrayList<>(); 21939 final int packageCount = mSettings.mPackages.size(); 21940 for (int i = 0; i < packageCount; i++) { 21941 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21942 codePaths.add(ps.codePath.getAbsolutePath()); 21943 } 21944 return codePaths; 21945 } 21946 } 21947 21948 /** 21949 * Examine all apps present on given mounted volume, and destroy apps that 21950 * aren't expected, either due to uninstallation or reinstallation on 21951 * another volume. 21952 */ 21953 private void reconcileApps(String volumeUuid) { 21954 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21955 List<File> filesToDelete = null; 21956 21957 final File[] files = FileUtils.listFilesOrEmpty( 21958 Environment.getDataAppDirectory(volumeUuid)); 21959 for (File file : files) { 21960 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21961 && !PackageInstallerService.isStageName(file.getName()); 21962 if (!isPackage) { 21963 // Ignore entries which are not packages 21964 continue; 21965 } 21966 21967 String absolutePath = file.getAbsolutePath(); 21968 21969 boolean pathValid = false; 21970 final int absoluteCodePathCount = absoluteCodePaths.size(); 21971 for (int i = 0; i < absoluteCodePathCount; i++) { 21972 String absoluteCodePath = absoluteCodePaths.get(i); 21973 if (absolutePath.startsWith(absoluteCodePath)) { 21974 pathValid = true; 21975 break; 21976 } 21977 } 21978 21979 if (!pathValid) { 21980 if (filesToDelete == null) { 21981 filesToDelete = new ArrayList<>(); 21982 } 21983 filesToDelete.add(file); 21984 } 21985 } 21986 21987 if (filesToDelete != null) { 21988 final int fileToDeleteCount = filesToDelete.size(); 21989 for (int i = 0; i < fileToDeleteCount; i++) { 21990 File fileToDelete = filesToDelete.get(i); 21991 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21992 synchronized (mInstallLock) { 21993 removeCodePathLI(fileToDelete); 21994 } 21995 } 21996 } 21997 } 21998 21999 /** 22000 * Reconcile all app data for the given user. 22001 * <p> 22002 * Verifies that directories exist and that ownership and labeling is 22003 * correct for all installed apps on all mounted volumes. 22004 */ 22005 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22006 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22007 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22008 final String volumeUuid = vol.getFsUuid(); 22009 synchronized (mInstallLock) { 22010 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22011 } 22012 } 22013 } 22014 22015 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22016 boolean migrateAppData) { 22017 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22018 } 22019 22020 /** 22021 * Reconcile all app data on given mounted volume. 22022 * <p> 22023 * Destroys app data that isn't expected, either due to uninstallation or 22024 * reinstallation on another volume. 22025 * <p> 22026 * Verifies that directories exist and that ownership and labeling is 22027 * correct for all installed apps. 22028 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 22029 */ 22030 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22031 boolean migrateAppData, boolean onlyCoreApps) { 22032 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22033 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22034 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22035 22036 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22037 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22038 22039 // First look for stale data that doesn't belong, and check if things 22040 // have changed since we did our last restorecon 22041 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22042 if (StorageManager.isFileEncryptedNativeOrEmulated() 22043 && !StorageManager.isUserKeyUnlocked(userId)) { 22044 throw new RuntimeException( 22045 "Yikes, someone asked us to reconcile CE storage while " + userId 22046 + " was still locked; this would have caused massive data loss!"); 22047 } 22048 22049 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22050 for (File file : files) { 22051 final String packageName = file.getName(); 22052 try { 22053 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22054 } catch (PackageManagerException e) { 22055 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22056 try { 22057 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22058 StorageManager.FLAG_STORAGE_CE, 0); 22059 } catch (InstallerException e2) { 22060 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22061 } 22062 } 22063 } 22064 } 22065 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22066 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22067 for (File file : files) { 22068 final String packageName = file.getName(); 22069 try { 22070 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22071 } catch (PackageManagerException e) { 22072 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22073 try { 22074 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22075 StorageManager.FLAG_STORAGE_DE, 0); 22076 } catch (InstallerException e2) { 22077 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22078 } 22079 } 22080 } 22081 } 22082 22083 // Ensure that data directories are ready to roll for all packages 22084 // installed for this volume and user 22085 final List<PackageSetting> packages; 22086 synchronized (mPackages) { 22087 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22088 } 22089 int preparedCount = 0; 22090 for (PackageSetting ps : packages) { 22091 final String packageName = ps.name; 22092 if (ps.pkg == null) { 22093 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22094 // TODO: might be due to legacy ASEC apps; we should circle back 22095 // and reconcile again once they're scanned 22096 continue; 22097 } 22098 // Skip non-core apps if requested 22099 if (onlyCoreApps && !ps.pkg.coreApp) { 22100 result.add(packageName); 22101 continue; 22102 } 22103 22104 if (ps.getInstalled(userId)) { 22105 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22106 preparedCount++; 22107 } 22108 } 22109 22110 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22111 return result; 22112 } 22113 22114 /** 22115 * Prepare app data for the given app just after it was installed or 22116 * upgraded. This method carefully only touches users that it's installed 22117 * for, and it forces a restorecon to handle any seinfo changes. 22118 * <p> 22119 * Verifies that directories exist and that ownership and labeling is 22120 * correct for all installed apps. If there is an ownership mismatch, it 22121 * will try recovering system apps by wiping data; third-party app data is 22122 * left intact. 22123 * <p> 22124 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22125 */ 22126 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22127 final PackageSetting ps; 22128 synchronized (mPackages) { 22129 ps = mSettings.mPackages.get(pkg.packageName); 22130 mSettings.writeKernelMappingLPr(ps); 22131 } 22132 22133 final UserManager um = mContext.getSystemService(UserManager.class); 22134 UserManagerInternal umInternal = getUserManagerInternal(); 22135 for (UserInfo user : um.getUsers()) { 22136 final int flags; 22137 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22138 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22139 } else if (umInternal.isUserRunning(user.id)) { 22140 flags = StorageManager.FLAG_STORAGE_DE; 22141 } else { 22142 continue; 22143 } 22144 22145 if (ps.getInstalled(user.id)) { 22146 // TODO: when user data is locked, mark that we're still dirty 22147 prepareAppDataLIF(pkg, user.id, flags); 22148 } 22149 } 22150 } 22151 22152 /** 22153 * Prepare app data for the given app. 22154 * <p> 22155 * Verifies that directories exist and that ownership and labeling is 22156 * correct for all installed apps. If there is an ownership mismatch, this 22157 * will try recovering system apps by wiping data; third-party app data is 22158 * left intact. 22159 */ 22160 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22161 if (pkg == null) { 22162 Slog.wtf(TAG, "Package was null!", new Throwable()); 22163 return; 22164 } 22165 prepareAppDataLeafLIF(pkg, userId, flags); 22166 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22167 for (int i = 0; i < childCount; i++) { 22168 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22169 } 22170 } 22171 22172 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22173 boolean maybeMigrateAppData) { 22174 prepareAppDataLIF(pkg, userId, flags); 22175 22176 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22177 // We may have just shuffled around app data directories, so 22178 // prepare them one more time 22179 prepareAppDataLIF(pkg, userId, flags); 22180 } 22181 } 22182 22183 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22184 if (DEBUG_APP_DATA) { 22185 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22186 + Integer.toHexString(flags)); 22187 } 22188 22189 final String volumeUuid = pkg.volumeUuid; 22190 final String packageName = pkg.packageName; 22191 final ApplicationInfo app = pkg.applicationInfo; 22192 final int appId = UserHandle.getAppId(app.uid); 22193 22194 Preconditions.checkNotNull(app.seInfo); 22195 22196 long ceDataInode = -1; 22197 try { 22198 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22199 appId, app.seInfo, app.targetSdkVersion); 22200 } catch (InstallerException e) { 22201 if (app.isSystemApp()) { 22202 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22203 + ", but trying to recover: " + e); 22204 destroyAppDataLeafLIF(pkg, userId, flags); 22205 try { 22206 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22207 appId, app.seInfo, app.targetSdkVersion); 22208 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22209 } catch (InstallerException e2) { 22210 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22211 } 22212 } else { 22213 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22214 } 22215 } 22216 // Prepare the application profiles. 22217 mArtManagerService.prepareAppProfiles(pkg, userId); 22218 22219 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22220 // TODO: mark this structure as dirty so we persist it! 22221 synchronized (mPackages) { 22222 final PackageSetting ps = mSettings.mPackages.get(packageName); 22223 if (ps != null) { 22224 ps.setCeDataInode(ceDataInode, userId); 22225 } 22226 } 22227 } 22228 22229 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22230 } 22231 22232 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22233 if (pkg == null) { 22234 Slog.wtf(TAG, "Package was null!", new Throwable()); 22235 return; 22236 } 22237 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22238 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22239 for (int i = 0; i < childCount; i++) { 22240 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22241 } 22242 } 22243 22244 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22245 final String volumeUuid = pkg.volumeUuid; 22246 final String packageName = pkg.packageName; 22247 final ApplicationInfo app = pkg.applicationInfo; 22248 22249 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22250 // Create a native library symlink only if we have native libraries 22251 // and if the native libraries are 32 bit libraries. We do not provide 22252 // this symlink for 64 bit libraries. 22253 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22254 final String nativeLibPath = app.nativeLibraryDir; 22255 try { 22256 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22257 nativeLibPath, userId); 22258 } catch (InstallerException e) { 22259 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22260 } 22261 } 22262 } 22263 } 22264 22265 /** 22266 * For system apps on non-FBE devices, this method migrates any existing 22267 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22268 * requested by the app. 22269 */ 22270 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22271 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22272 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22273 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22274 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22275 try { 22276 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22277 storageTarget); 22278 } catch (InstallerException e) { 22279 logCriticalInfo(Log.WARN, 22280 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22281 } 22282 return true; 22283 } else { 22284 return false; 22285 } 22286 } 22287 22288 public PackageFreezer freezePackage(String packageName, String killReason) { 22289 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22290 } 22291 22292 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22293 return new PackageFreezer(packageName, userId, killReason); 22294 } 22295 22296 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22297 String killReason) { 22298 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22299 } 22300 22301 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22302 String killReason) { 22303 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22304 return new PackageFreezer(); 22305 } else { 22306 return freezePackage(packageName, userId, killReason); 22307 } 22308 } 22309 22310 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22311 String killReason) { 22312 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22313 } 22314 22315 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22316 String killReason) { 22317 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22318 return new PackageFreezer(); 22319 } else { 22320 return freezePackage(packageName, userId, killReason); 22321 } 22322 } 22323 22324 /** 22325 * Class that freezes and kills the given package upon creation, and 22326 * unfreezes it upon closing. This is typically used when doing surgery on 22327 * app code/data to prevent the app from running while you're working. 22328 */ 22329 private class PackageFreezer implements AutoCloseable { 22330 private final String mPackageName; 22331 private final PackageFreezer[] mChildren; 22332 22333 private final boolean mWeFroze; 22334 22335 private final AtomicBoolean mClosed = new AtomicBoolean(); 22336 private final CloseGuard mCloseGuard = CloseGuard.get(); 22337 22338 /** 22339 * Create and return a stub freezer that doesn't actually do anything, 22340 * typically used when someone requested 22341 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22342 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22343 */ 22344 public PackageFreezer() { 22345 mPackageName = null; 22346 mChildren = null; 22347 mWeFroze = false; 22348 mCloseGuard.open("close"); 22349 } 22350 22351 public PackageFreezer(String packageName, int userId, String killReason) { 22352 synchronized (mPackages) { 22353 mPackageName = packageName; 22354 mWeFroze = mFrozenPackages.add(mPackageName); 22355 22356 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22357 if (ps != null) { 22358 killApplication(ps.name, ps.appId, userId, killReason); 22359 } 22360 22361 final PackageParser.Package p = mPackages.get(packageName); 22362 if (p != null && p.childPackages != null) { 22363 final int N = p.childPackages.size(); 22364 mChildren = new PackageFreezer[N]; 22365 for (int i = 0; i < N; i++) { 22366 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22367 userId, killReason); 22368 } 22369 } else { 22370 mChildren = null; 22371 } 22372 } 22373 mCloseGuard.open("close"); 22374 } 22375 22376 @Override 22377 protected void finalize() throws Throwable { 22378 try { 22379 if (mCloseGuard != null) { 22380 mCloseGuard.warnIfOpen(); 22381 } 22382 22383 close(); 22384 } finally { 22385 super.finalize(); 22386 } 22387 } 22388 22389 @Override 22390 public void close() { 22391 mCloseGuard.close(); 22392 if (mClosed.compareAndSet(false, true)) { 22393 synchronized (mPackages) { 22394 if (mWeFroze) { 22395 mFrozenPackages.remove(mPackageName); 22396 } 22397 22398 if (mChildren != null) { 22399 for (PackageFreezer freezer : mChildren) { 22400 freezer.close(); 22401 } 22402 } 22403 } 22404 } 22405 } 22406 } 22407 22408 /** 22409 * Verify that given package is currently frozen. 22410 */ 22411 private void checkPackageFrozen(String packageName) { 22412 synchronized (mPackages) { 22413 if (!mFrozenPackages.contains(packageName)) { 22414 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22415 } 22416 } 22417 } 22418 22419 @Override 22420 public int movePackage(final String packageName, final String volumeUuid) { 22421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22422 22423 final int callingUid = Binder.getCallingUid(); 22424 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22425 final int moveId = mNextMoveId.getAndIncrement(); 22426 mHandler.post(new Runnable() { 22427 @Override 22428 public void run() { 22429 try { 22430 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22431 } catch (PackageManagerException e) { 22432 Slog.w(TAG, "Failed to move " + packageName, e); 22433 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22434 } 22435 } 22436 }); 22437 return moveId; 22438 } 22439 22440 private void movePackageInternal(final String packageName, final String volumeUuid, 22441 final int moveId, final int callingUid, UserHandle user) 22442 throws PackageManagerException { 22443 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22444 final PackageManager pm = mContext.getPackageManager(); 22445 22446 final boolean currentAsec; 22447 final String currentVolumeUuid; 22448 final File codeFile; 22449 final String installerPackageName; 22450 final String packageAbiOverride; 22451 final int appId; 22452 final String seinfo; 22453 final String label; 22454 final int targetSdkVersion; 22455 final PackageFreezer freezer; 22456 final int[] installedUserIds; 22457 22458 // reader 22459 synchronized (mPackages) { 22460 final PackageParser.Package pkg = mPackages.get(packageName); 22461 final PackageSetting ps = mSettings.mPackages.get(packageName); 22462 if (pkg == null 22463 || ps == null 22464 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22465 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22466 } 22467 if (pkg.applicationInfo.isSystemApp()) { 22468 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22469 "Cannot move system application"); 22470 } 22471 22472 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22473 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22474 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22475 if (isInternalStorage && !allow3rdPartyOnInternal) { 22476 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22477 "3rd party apps are not allowed on internal storage"); 22478 } 22479 22480 if (pkg.applicationInfo.isExternalAsec()) { 22481 currentAsec = true; 22482 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22483 } else if (pkg.applicationInfo.isForwardLocked()) { 22484 currentAsec = true; 22485 currentVolumeUuid = "forward_locked"; 22486 } else { 22487 currentAsec = false; 22488 currentVolumeUuid = ps.volumeUuid; 22489 22490 final File probe = new File(pkg.codePath); 22491 final File probeOat = new File(probe, "oat"); 22492 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22493 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22494 "Move only supported for modern cluster style installs"); 22495 } 22496 } 22497 22498 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22499 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22500 "Package already moved to " + volumeUuid); 22501 } 22502 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22503 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22504 "Device admin cannot be moved"); 22505 } 22506 22507 if (mFrozenPackages.contains(packageName)) { 22508 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22509 "Failed to move already frozen package"); 22510 } 22511 22512 codeFile = new File(pkg.codePath); 22513 installerPackageName = ps.installerPackageName; 22514 packageAbiOverride = ps.cpuAbiOverrideString; 22515 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22516 seinfo = pkg.applicationInfo.seInfo; 22517 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22518 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22519 freezer = freezePackage(packageName, "movePackageInternal"); 22520 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22521 } 22522 22523 final Bundle extras = new Bundle(); 22524 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22525 extras.putString(Intent.EXTRA_TITLE, label); 22526 mMoveCallbacks.notifyCreated(moveId, extras); 22527 22528 int installFlags; 22529 final boolean moveCompleteApp; 22530 final File measurePath; 22531 22532 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22533 installFlags = INSTALL_INTERNAL; 22534 moveCompleteApp = !currentAsec; 22535 measurePath = Environment.getDataAppDirectory(volumeUuid); 22536 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22537 installFlags = INSTALL_EXTERNAL; 22538 moveCompleteApp = false; 22539 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22540 } else { 22541 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22542 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22543 || !volume.isMountedWritable()) { 22544 freezer.close(); 22545 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22546 "Move location not mounted private volume"); 22547 } 22548 22549 Preconditions.checkState(!currentAsec); 22550 22551 installFlags = INSTALL_INTERNAL; 22552 moveCompleteApp = true; 22553 measurePath = Environment.getDataAppDirectory(volumeUuid); 22554 } 22555 22556 // If we're moving app data around, we need all the users unlocked 22557 if (moveCompleteApp) { 22558 for (int userId : installedUserIds) { 22559 if (StorageManager.isFileEncryptedNativeOrEmulated() 22560 && !StorageManager.isUserKeyUnlocked(userId)) { 22561 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22562 "User " + userId + " must be unlocked"); 22563 } 22564 } 22565 } 22566 22567 final PackageStats stats = new PackageStats(null, -1); 22568 synchronized (mInstaller) { 22569 for (int userId : installedUserIds) { 22570 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22571 freezer.close(); 22572 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22573 "Failed to measure package size"); 22574 } 22575 } 22576 } 22577 22578 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22579 + stats.dataSize); 22580 22581 final long startFreeBytes = measurePath.getUsableSpace(); 22582 final long sizeBytes; 22583 if (moveCompleteApp) { 22584 sizeBytes = stats.codeSize + stats.dataSize; 22585 } else { 22586 sizeBytes = stats.codeSize; 22587 } 22588 22589 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22590 freezer.close(); 22591 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22592 "Not enough free space to move"); 22593 } 22594 22595 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22596 22597 final CountDownLatch installedLatch = new CountDownLatch(1); 22598 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22599 @Override 22600 public void onUserActionRequired(Intent intent) throws RemoteException { 22601 throw new IllegalStateException(); 22602 } 22603 22604 @Override 22605 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22606 Bundle extras) throws RemoteException { 22607 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22608 + PackageManager.installStatusToString(returnCode, msg)); 22609 22610 installedLatch.countDown(); 22611 freezer.close(); 22612 22613 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22614 switch (status) { 22615 case PackageInstaller.STATUS_SUCCESS: 22616 mMoveCallbacks.notifyStatusChanged(moveId, 22617 PackageManager.MOVE_SUCCEEDED); 22618 break; 22619 case PackageInstaller.STATUS_FAILURE_STORAGE: 22620 mMoveCallbacks.notifyStatusChanged(moveId, 22621 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22622 break; 22623 default: 22624 mMoveCallbacks.notifyStatusChanged(moveId, 22625 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22626 break; 22627 } 22628 } 22629 }; 22630 22631 final MoveInfo move; 22632 if (moveCompleteApp) { 22633 // Kick off a thread to report progress estimates 22634 new Thread() { 22635 @Override 22636 public void run() { 22637 while (true) { 22638 try { 22639 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22640 break; 22641 } 22642 } catch (InterruptedException ignored) { 22643 } 22644 22645 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22646 final int progress = 10 + (int) MathUtils.constrain( 22647 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22648 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22649 } 22650 } 22651 }.start(); 22652 22653 final String dataAppName = codeFile.getName(); 22654 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22655 dataAppName, appId, seinfo, targetSdkVersion); 22656 } else { 22657 move = null; 22658 } 22659 22660 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22661 22662 final Message msg = mHandler.obtainMessage(INIT_COPY); 22663 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22664 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22665 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22666 packageAbiOverride, null /*grantedPermissions*/, 22667 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22668 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22669 msg.obj = params; 22670 22671 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22672 System.identityHashCode(msg.obj)); 22673 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22674 System.identityHashCode(msg.obj)); 22675 22676 mHandler.sendMessage(msg); 22677 } 22678 22679 @Override 22680 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22681 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22682 22683 final int realMoveId = mNextMoveId.getAndIncrement(); 22684 final Bundle extras = new Bundle(); 22685 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22686 mMoveCallbacks.notifyCreated(realMoveId, extras); 22687 22688 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22689 @Override 22690 public void onCreated(int moveId, Bundle extras) { 22691 // Ignored 22692 } 22693 22694 @Override 22695 public void onStatusChanged(int moveId, int status, long estMillis) { 22696 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22697 } 22698 }; 22699 22700 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22701 storage.setPrimaryStorageUuid(volumeUuid, callback); 22702 return realMoveId; 22703 } 22704 22705 @Override 22706 public int getMoveStatus(int moveId) { 22707 mContext.enforceCallingOrSelfPermission( 22708 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22709 return mMoveCallbacks.mLastStatus.get(moveId); 22710 } 22711 22712 @Override 22713 public void registerMoveCallback(IPackageMoveObserver callback) { 22714 mContext.enforceCallingOrSelfPermission( 22715 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22716 mMoveCallbacks.register(callback); 22717 } 22718 22719 @Override 22720 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22721 mContext.enforceCallingOrSelfPermission( 22722 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22723 mMoveCallbacks.unregister(callback); 22724 } 22725 22726 @Override 22727 public boolean setInstallLocation(int loc) { 22728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22729 null); 22730 if (getInstallLocation() == loc) { 22731 return true; 22732 } 22733 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22734 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22735 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22736 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22737 return true; 22738 } 22739 return false; 22740 } 22741 22742 @Override 22743 public int getInstallLocation() { 22744 // allow instant app access 22745 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22746 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22747 PackageHelper.APP_INSTALL_AUTO); 22748 } 22749 22750 /** Called by UserManagerService */ 22751 void cleanUpUser(UserManagerService userManager, int userHandle) { 22752 synchronized (mPackages) { 22753 mDirtyUsers.remove(userHandle); 22754 mUserNeedsBadging.delete(userHandle); 22755 mSettings.removeUserLPw(userHandle); 22756 mPendingBroadcasts.remove(userHandle); 22757 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22758 removeUnusedPackagesLPw(userManager, userHandle); 22759 } 22760 } 22761 22762 /** 22763 * We're removing userHandle and would like to remove any downloaded packages 22764 * that are no longer in use by any other user. 22765 * @param userHandle the user being removed 22766 */ 22767 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22768 final boolean DEBUG_CLEAN_APKS = false; 22769 int [] users = userManager.getUserIds(); 22770 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22771 while (psit.hasNext()) { 22772 PackageSetting ps = psit.next(); 22773 if (ps.pkg == null) { 22774 continue; 22775 } 22776 final String packageName = ps.pkg.packageName; 22777 // Skip over if system app 22778 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22779 continue; 22780 } 22781 if (DEBUG_CLEAN_APKS) { 22782 Slog.i(TAG, "Checking package " + packageName); 22783 } 22784 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22785 if (keep) { 22786 if (DEBUG_CLEAN_APKS) { 22787 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22788 } 22789 } else { 22790 for (int i = 0; i < users.length; i++) { 22791 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22792 keep = true; 22793 if (DEBUG_CLEAN_APKS) { 22794 Slog.i(TAG, " Keeping package " + packageName + " for user " 22795 + users[i]); 22796 } 22797 break; 22798 } 22799 } 22800 } 22801 if (!keep) { 22802 if (DEBUG_CLEAN_APKS) { 22803 Slog.i(TAG, " Removing package " + packageName); 22804 } 22805 mHandler.post(new Runnable() { 22806 public void run() { 22807 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22808 userHandle, 0); 22809 } //end run 22810 }); 22811 } 22812 } 22813 } 22814 22815 /** Called by UserManagerService */ 22816 void createNewUser(int userId, String[] disallowedPackages) { 22817 synchronized (mInstallLock) { 22818 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22819 } 22820 synchronized (mPackages) { 22821 scheduleWritePackageRestrictionsLocked(userId); 22822 scheduleWritePackageListLocked(userId); 22823 applyFactoryDefaultBrowserLPw(userId); 22824 primeDomainVerificationsLPw(userId); 22825 } 22826 } 22827 22828 void onNewUserCreated(final int userId) { 22829 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22830 synchronized(mPackages) { 22831 // If permission review for legacy apps is required, we represent 22832 // dagerous permissions for such apps as always granted runtime 22833 // permissions to keep per user flag state whether review is needed. 22834 // Hence, if a new user is added we have to propagate dangerous 22835 // permission grants for these legacy apps. 22836 if (mSettings.mPermissions.mPermissionReviewRequired) { 22837// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22838 mPermissionManager.updateAllPermissions( 22839 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22840 mPermissionCallback); 22841 } 22842 } 22843 } 22844 22845 @Override 22846 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22847 mContext.enforceCallingOrSelfPermission( 22848 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22849 "Only package verification agents can read the verifier device identity"); 22850 22851 synchronized (mPackages) { 22852 return mSettings.getVerifierDeviceIdentityLPw(); 22853 } 22854 } 22855 22856 @Override 22857 public void setPermissionEnforced(String permission, boolean enforced) { 22858 // TODO: Now that we no longer change GID for storage, this should to away. 22859 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22860 "setPermissionEnforced"); 22861 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22862 synchronized (mPackages) { 22863 if (mSettings.mReadExternalStorageEnforced == null 22864 || mSettings.mReadExternalStorageEnforced != enforced) { 22865 mSettings.mReadExternalStorageEnforced = 22866 enforced ? Boolean.TRUE : Boolean.FALSE; 22867 mSettings.writeLPr(); 22868 } 22869 } 22870 // kill any non-foreground processes so we restart them and 22871 // grant/revoke the GID. 22872 final IActivityManager am = ActivityManager.getService(); 22873 if (am != null) { 22874 final long token = Binder.clearCallingIdentity(); 22875 try { 22876 am.killProcessesBelowForeground("setPermissionEnforcement"); 22877 } catch (RemoteException e) { 22878 } finally { 22879 Binder.restoreCallingIdentity(token); 22880 } 22881 } 22882 } else { 22883 throw new IllegalArgumentException("No selective enforcement for " + permission); 22884 } 22885 } 22886 22887 @Override 22888 @Deprecated 22889 public boolean isPermissionEnforced(String permission) { 22890 // allow instant applications 22891 return true; 22892 } 22893 22894 @Override 22895 public boolean isStorageLow() { 22896 // allow instant applications 22897 final long token = Binder.clearCallingIdentity(); 22898 try { 22899 final DeviceStorageMonitorInternal 22900 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22901 if (dsm != null) { 22902 return dsm.isMemoryLow(); 22903 } else { 22904 return false; 22905 } 22906 } finally { 22907 Binder.restoreCallingIdentity(token); 22908 } 22909 } 22910 22911 @Override 22912 public IPackageInstaller getPackageInstaller() { 22913 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22914 return null; 22915 } 22916 return mInstallerService; 22917 } 22918 22919 @Override 22920 public IArtManager getArtManager() { 22921 return mArtManagerService; 22922 } 22923 22924 private boolean userNeedsBadging(int userId) { 22925 int index = mUserNeedsBadging.indexOfKey(userId); 22926 if (index < 0) { 22927 final UserInfo userInfo; 22928 final long token = Binder.clearCallingIdentity(); 22929 try { 22930 userInfo = sUserManager.getUserInfo(userId); 22931 } finally { 22932 Binder.restoreCallingIdentity(token); 22933 } 22934 final boolean b; 22935 if (userInfo != null && userInfo.isManagedProfile()) { 22936 b = true; 22937 } else { 22938 b = false; 22939 } 22940 mUserNeedsBadging.put(userId, b); 22941 return b; 22942 } 22943 return mUserNeedsBadging.valueAt(index); 22944 } 22945 22946 @Override 22947 public KeySet getKeySetByAlias(String packageName, String alias) { 22948 if (packageName == null || alias == null) { 22949 return null; 22950 } 22951 synchronized(mPackages) { 22952 final PackageParser.Package pkg = mPackages.get(packageName); 22953 if (pkg == null) { 22954 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22955 throw new IllegalArgumentException("Unknown package: " + packageName); 22956 } 22957 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22958 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22959 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22960 throw new IllegalArgumentException("Unknown package: " + packageName); 22961 } 22962 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22963 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22964 } 22965 } 22966 22967 @Override 22968 public KeySet getSigningKeySet(String packageName) { 22969 if (packageName == null) { 22970 return null; 22971 } 22972 synchronized(mPackages) { 22973 final int callingUid = Binder.getCallingUid(); 22974 final int callingUserId = UserHandle.getUserId(callingUid); 22975 final PackageParser.Package pkg = mPackages.get(packageName); 22976 if (pkg == null) { 22977 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22978 throw new IllegalArgumentException("Unknown package: " + packageName); 22979 } 22980 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22981 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22982 // filter and pretend the package doesn't exist 22983 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22984 + ", uid:" + callingUid); 22985 throw new IllegalArgumentException("Unknown package: " + packageName); 22986 } 22987 if (pkg.applicationInfo.uid != callingUid 22988 && Process.SYSTEM_UID != callingUid) { 22989 throw new SecurityException("May not access signing KeySet of other apps."); 22990 } 22991 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22992 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22993 } 22994 } 22995 22996 @Override 22997 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22998 final int callingUid = Binder.getCallingUid(); 22999 if (getInstantAppPackageName(callingUid) != null) { 23000 return false; 23001 } 23002 if (packageName == null || ks == null) { 23003 return false; 23004 } 23005 synchronized(mPackages) { 23006 final PackageParser.Package pkg = mPackages.get(packageName); 23007 if (pkg == null 23008 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23009 UserHandle.getUserId(callingUid))) { 23010 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23011 throw new IllegalArgumentException("Unknown package: " + packageName); 23012 } 23013 IBinder ksh = ks.getToken(); 23014 if (ksh instanceof KeySetHandle) { 23015 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23016 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23017 } 23018 return false; 23019 } 23020 } 23021 23022 @Override 23023 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23024 final int callingUid = Binder.getCallingUid(); 23025 if (getInstantAppPackageName(callingUid) != null) { 23026 return false; 23027 } 23028 if (packageName == null || ks == null) { 23029 return false; 23030 } 23031 synchronized(mPackages) { 23032 final PackageParser.Package pkg = mPackages.get(packageName); 23033 if (pkg == null 23034 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23035 UserHandle.getUserId(callingUid))) { 23036 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23037 throw new IllegalArgumentException("Unknown package: " + packageName); 23038 } 23039 IBinder ksh = ks.getToken(); 23040 if (ksh instanceof KeySetHandle) { 23041 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23042 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23043 } 23044 return false; 23045 } 23046 } 23047 23048 private void deletePackageIfUnusedLPr(final String packageName) { 23049 PackageSetting ps = mSettings.mPackages.get(packageName); 23050 if (ps == null) { 23051 return; 23052 } 23053 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23054 // TODO Implement atomic delete if package is unused 23055 // It is currently possible that the package will be deleted even if it is installed 23056 // after this method returns. 23057 mHandler.post(new Runnable() { 23058 public void run() { 23059 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23060 0, PackageManager.DELETE_ALL_USERS); 23061 } 23062 }); 23063 } 23064 } 23065 23066 /** 23067 * Check and throw if the given before/after packages would be considered a 23068 * downgrade. 23069 */ 23070 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23071 throws PackageManagerException { 23072 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23073 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23074 "Update version code " + after.versionCode + " is older than current " 23075 + before.getLongVersionCode()); 23076 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23077 if (after.baseRevisionCode < before.baseRevisionCode) { 23078 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23079 "Update base revision code " + after.baseRevisionCode 23080 + " is older than current " + before.baseRevisionCode); 23081 } 23082 23083 if (!ArrayUtils.isEmpty(after.splitNames)) { 23084 for (int i = 0; i < after.splitNames.length; i++) { 23085 final String splitName = after.splitNames[i]; 23086 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23087 if (j != -1) { 23088 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23089 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23090 "Update split " + splitName + " revision code " 23091 + after.splitRevisionCodes[i] + " is older than current " 23092 + before.splitRevisionCodes[j]); 23093 } 23094 } 23095 } 23096 } 23097 } 23098 } 23099 23100 private static class MoveCallbacks extends Handler { 23101 private static final int MSG_CREATED = 1; 23102 private static final int MSG_STATUS_CHANGED = 2; 23103 23104 private final RemoteCallbackList<IPackageMoveObserver> 23105 mCallbacks = new RemoteCallbackList<>(); 23106 23107 private final SparseIntArray mLastStatus = new SparseIntArray(); 23108 23109 public MoveCallbacks(Looper looper) { 23110 super(looper); 23111 } 23112 23113 public void register(IPackageMoveObserver callback) { 23114 mCallbacks.register(callback); 23115 } 23116 23117 public void unregister(IPackageMoveObserver callback) { 23118 mCallbacks.unregister(callback); 23119 } 23120 23121 @Override 23122 public void handleMessage(Message msg) { 23123 final SomeArgs args = (SomeArgs) msg.obj; 23124 final int n = mCallbacks.beginBroadcast(); 23125 for (int i = 0; i < n; i++) { 23126 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23127 try { 23128 invokeCallback(callback, msg.what, args); 23129 } catch (RemoteException ignored) { 23130 } 23131 } 23132 mCallbacks.finishBroadcast(); 23133 args.recycle(); 23134 } 23135 23136 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23137 throws RemoteException { 23138 switch (what) { 23139 case MSG_CREATED: { 23140 callback.onCreated(args.argi1, (Bundle) args.arg2); 23141 break; 23142 } 23143 case MSG_STATUS_CHANGED: { 23144 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23145 break; 23146 } 23147 } 23148 } 23149 23150 private void notifyCreated(int moveId, Bundle extras) { 23151 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23152 23153 final SomeArgs args = SomeArgs.obtain(); 23154 args.argi1 = moveId; 23155 args.arg2 = extras; 23156 obtainMessage(MSG_CREATED, args).sendToTarget(); 23157 } 23158 23159 private void notifyStatusChanged(int moveId, int status) { 23160 notifyStatusChanged(moveId, status, -1); 23161 } 23162 23163 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23164 Slog.v(TAG, "Move " + moveId + " status " + status); 23165 23166 final SomeArgs args = SomeArgs.obtain(); 23167 args.argi1 = moveId; 23168 args.argi2 = status; 23169 args.arg3 = estMillis; 23170 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23171 23172 synchronized (mLastStatus) { 23173 mLastStatus.put(moveId, status); 23174 } 23175 } 23176 } 23177 23178 private final static class OnPermissionChangeListeners extends Handler { 23179 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23180 23181 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23182 new RemoteCallbackList<>(); 23183 23184 public OnPermissionChangeListeners(Looper looper) { 23185 super(looper); 23186 } 23187 23188 @Override 23189 public void handleMessage(Message msg) { 23190 switch (msg.what) { 23191 case MSG_ON_PERMISSIONS_CHANGED: { 23192 final int uid = msg.arg1; 23193 handleOnPermissionsChanged(uid); 23194 } break; 23195 } 23196 } 23197 23198 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23199 mPermissionListeners.register(listener); 23200 23201 } 23202 23203 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23204 mPermissionListeners.unregister(listener); 23205 } 23206 23207 public void onPermissionsChanged(int uid) { 23208 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23209 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23210 } 23211 } 23212 23213 private void handleOnPermissionsChanged(int uid) { 23214 final int count = mPermissionListeners.beginBroadcast(); 23215 try { 23216 for (int i = 0; i < count; i++) { 23217 IOnPermissionsChangeListener callback = mPermissionListeners 23218 .getBroadcastItem(i); 23219 try { 23220 callback.onPermissionsChanged(uid); 23221 } catch (RemoteException e) { 23222 Log.e(TAG, "Permission listener is dead", e); 23223 } 23224 } 23225 } finally { 23226 mPermissionListeners.finishBroadcast(); 23227 } 23228 } 23229 } 23230 23231 private class PackageManagerNative extends IPackageManagerNative.Stub { 23232 @Override 23233 public String[] getNamesForUids(int[] uids) throws RemoteException { 23234 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23235 // massage results so they can be parsed by the native binder 23236 for (int i = results.length - 1; i >= 0; --i) { 23237 if (results[i] == null) { 23238 results[i] = ""; 23239 } 23240 } 23241 return results; 23242 } 23243 23244 // NB: this differentiates between preloads and sideloads 23245 @Override 23246 public String getInstallerForPackage(String packageName) throws RemoteException { 23247 final String installerName = getInstallerPackageName(packageName); 23248 if (!TextUtils.isEmpty(installerName)) { 23249 return installerName; 23250 } 23251 // differentiate between preload and sideload 23252 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23253 ApplicationInfo appInfo = getApplicationInfo(packageName, 23254 /*flags*/ 0, 23255 /*userId*/ callingUser); 23256 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23257 return "preload"; 23258 } 23259 return ""; 23260 } 23261 23262 @Override 23263 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23264 try { 23265 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23266 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23267 if (pInfo != null) { 23268 return pInfo.getLongVersionCode(); 23269 } 23270 } catch (Exception e) { 23271 } 23272 return 0; 23273 } 23274 } 23275 23276 private class PackageManagerInternalImpl extends PackageManagerInternal { 23277 @Override 23278 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23279 int flagValues, int userId) { 23280 PackageManagerService.this.updatePermissionFlags( 23281 permName, packageName, flagMask, flagValues, userId); 23282 } 23283 23284 @Override 23285 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23286 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23287 } 23288 23289 @Override 23290 public boolean isInstantApp(String packageName, int userId) { 23291 return PackageManagerService.this.isInstantApp(packageName, userId); 23292 } 23293 23294 @Override 23295 public String getInstantAppPackageName(int uid) { 23296 return PackageManagerService.this.getInstantAppPackageName(uid); 23297 } 23298 23299 @Override 23300 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23301 synchronized (mPackages) { 23302 return PackageManagerService.this.filterAppAccessLPr( 23303 (PackageSetting) pkg.mExtras, callingUid, userId); 23304 } 23305 } 23306 23307 @Override 23308 public PackageParser.Package getPackage(String packageName) { 23309 synchronized (mPackages) { 23310 packageName = resolveInternalPackageNameLPr( 23311 packageName, PackageManager.VERSION_CODE_HIGHEST); 23312 return mPackages.get(packageName); 23313 } 23314 } 23315 23316 @Override 23317 public PackageList getPackageList(PackageListObserver observer) { 23318 synchronized (mPackages) { 23319 final int N = mPackages.size(); 23320 final ArrayList<String> list = new ArrayList<>(N); 23321 for (int i = 0; i < N; i++) { 23322 list.add(mPackages.keyAt(i)); 23323 } 23324 final PackageList packageList = new PackageList(list, observer); 23325 if (observer != null) { 23326 mPackageListObservers.add(packageList); 23327 } 23328 return packageList; 23329 } 23330 } 23331 23332 @Override 23333 public void removePackageListObserver(PackageListObserver observer) { 23334 synchronized (mPackages) { 23335 mPackageListObservers.remove(observer); 23336 } 23337 } 23338 23339 @Override 23340 public PackageParser.Package getDisabledPackage(String packageName) { 23341 synchronized (mPackages) { 23342 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23343 return (ps != null) ? ps.pkg : null; 23344 } 23345 } 23346 23347 @Override 23348 public String getKnownPackageName(int knownPackage, int userId) { 23349 switch(knownPackage) { 23350 case PackageManagerInternal.PACKAGE_BROWSER: 23351 return getDefaultBrowserPackageName(userId); 23352 case PackageManagerInternal.PACKAGE_INSTALLER: 23353 return mRequiredInstallerPackage; 23354 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23355 return mSetupWizardPackage; 23356 case PackageManagerInternal.PACKAGE_SYSTEM: 23357 return "android"; 23358 case PackageManagerInternal.PACKAGE_VERIFIER: 23359 return mRequiredVerifierPackage; 23360 } 23361 return null; 23362 } 23363 23364 @Override 23365 public boolean isResolveActivityComponent(ComponentInfo component) { 23366 return mResolveActivity.packageName.equals(component.packageName) 23367 && mResolveActivity.name.equals(component.name); 23368 } 23369 23370 @Override 23371 public void setLocationPackagesProvider(PackagesProvider provider) { 23372 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23373 } 23374 23375 @Override 23376 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23377 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23378 } 23379 23380 @Override 23381 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23382 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23383 } 23384 23385 @Override 23386 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23387 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23388 } 23389 23390 @Override 23391 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23392 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23393 } 23394 23395 @Override 23396 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23397 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23398 } 23399 23400 @Override 23401 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23402 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23403 } 23404 23405 @Override 23406 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23407 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23408 } 23409 23410 @Override 23411 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23412 synchronized (mPackages) { 23413 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23414 } 23415 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23416 } 23417 23418 @Override 23419 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23420 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23421 packageName, userId); 23422 } 23423 23424 @Override 23425 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23426 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23427 packageName, userId); 23428 } 23429 23430 @Override 23431 public void setKeepUninstalledPackages(final List<String> packageList) { 23432 Preconditions.checkNotNull(packageList); 23433 List<String> removedFromList = null; 23434 synchronized (mPackages) { 23435 if (mKeepUninstalledPackages != null) { 23436 final int packagesCount = mKeepUninstalledPackages.size(); 23437 for (int i = 0; i < packagesCount; i++) { 23438 String oldPackage = mKeepUninstalledPackages.get(i); 23439 if (packageList != null && packageList.contains(oldPackage)) { 23440 continue; 23441 } 23442 if (removedFromList == null) { 23443 removedFromList = new ArrayList<>(); 23444 } 23445 removedFromList.add(oldPackage); 23446 } 23447 } 23448 mKeepUninstalledPackages = new ArrayList<>(packageList); 23449 if (removedFromList != null) { 23450 final int removedCount = removedFromList.size(); 23451 for (int i = 0; i < removedCount; i++) { 23452 deletePackageIfUnusedLPr(removedFromList.get(i)); 23453 } 23454 } 23455 } 23456 } 23457 23458 @Override 23459 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23460 synchronized (mPackages) { 23461 return mPermissionManager.isPermissionsReviewRequired( 23462 mPackages.get(packageName), userId); 23463 } 23464 } 23465 23466 @Override 23467 public PackageInfo getPackageInfo( 23468 String packageName, int flags, int filterCallingUid, int userId) { 23469 return PackageManagerService.this 23470 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23471 flags, filterCallingUid, userId); 23472 } 23473 23474 @Override 23475 public int getPackageUid(String packageName, int flags, int userId) { 23476 return PackageManagerService.this 23477 .getPackageUid(packageName, flags, userId); 23478 } 23479 23480 @Override 23481 public ApplicationInfo getApplicationInfo( 23482 String packageName, int flags, int filterCallingUid, int userId) { 23483 return PackageManagerService.this 23484 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23485 } 23486 23487 @Override 23488 public ActivityInfo getActivityInfo( 23489 ComponentName component, int flags, int filterCallingUid, int userId) { 23490 return PackageManagerService.this 23491 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23492 } 23493 23494 @Override 23495 public List<ResolveInfo> queryIntentActivities( 23496 Intent intent, int flags, int filterCallingUid, int userId) { 23497 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23498 return PackageManagerService.this 23499 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23500 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23501 } 23502 23503 @Override 23504 public List<ResolveInfo> queryIntentServices( 23505 Intent intent, int flags, int callingUid, int userId) { 23506 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23507 return PackageManagerService.this 23508 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23509 false); 23510 } 23511 23512 @Override 23513 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23514 int userId) { 23515 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23516 } 23517 23518 @Override 23519 public void setDeviceAndProfileOwnerPackages( 23520 int deviceOwnerUserId, String deviceOwnerPackage, 23521 SparseArray<String> profileOwnerPackages) { 23522 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23523 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23524 } 23525 23526 @Override 23527 public boolean isPackageDataProtected(int userId, String packageName) { 23528 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23529 } 23530 23531 @Override 23532 public boolean isPackageEphemeral(int userId, String packageName) { 23533 synchronized (mPackages) { 23534 final PackageSetting ps = mSettings.mPackages.get(packageName); 23535 return ps != null ? ps.getInstantApp(userId) : false; 23536 } 23537 } 23538 23539 @Override 23540 public boolean wasPackageEverLaunched(String packageName, int userId) { 23541 synchronized (mPackages) { 23542 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23543 } 23544 } 23545 23546 @Override 23547 public void grantRuntimePermission(String packageName, String permName, int userId, 23548 boolean overridePolicy) { 23549 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23550 permName, packageName, overridePolicy, getCallingUid(), userId, 23551 mPermissionCallback); 23552 } 23553 23554 @Override 23555 public void revokeRuntimePermission(String packageName, String permName, int userId, 23556 boolean overridePolicy) { 23557 mPermissionManager.revokeRuntimePermission( 23558 permName, packageName, overridePolicy, getCallingUid(), userId, 23559 mPermissionCallback); 23560 } 23561 23562 @Override 23563 public String getNameForUid(int uid) { 23564 return PackageManagerService.this.getNameForUid(uid); 23565 } 23566 23567 @Override 23568 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23569 Intent origIntent, String resolvedType, String callingPackage, 23570 Bundle verificationBundle, int userId) { 23571 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23572 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23573 userId); 23574 } 23575 23576 @Override 23577 public void grantEphemeralAccess(int userId, Intent intent, 23578 int targetAppId, int ephemeralAppId) { 23579 synchronized (mPackages) { 23580 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23581 targetAppId, ephemeralAppId); 23582 } 23583 } 23584 23585 @Override 23586 public boolean isInstantAppInstallerComponent(ComponentName component) { 23587 synchronized (mPackages) { 23588 return mInstantAppInstallerActivity != null 23589 && mInstantAppInstallerActivity.getComponentName().equals(component); 23590 } 23591 } 23592 23593 @Override 23594 public void pruneInstantApps() { 23595 mInstantAppRegistry.pruneInstantApps(); 23596 } 23597 23598 @Override 23599 public String getSetupWizardPackageName() { 23600 return mSetupWizardPackage; 23601 } 23602 23603 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23604 if (policy != null) { 23605 mExternalSourcesPolicy = policy; 23606 } 23607 } 23608 23609 @Override 23610 public boolean isPackagePersistent(String packageName) { 23611 synchronized (mPackages) { 23612 PackageParser.Package pkg = mPackages.get(packageName); 23613 return pkg != null 23614 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23615 | ApplicationInfo.FLAG_PERSISTENT)) == 23616 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23617 : false; 23618 } 23619 } 23620 23621 @Override 23622 public boolean isLegacySystemApp(Package pkg) { 23623 synchronized (mPackages) { 23624 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23625 return mPromoteSystemApps 23626 && ps.isSystem() 23627 && mExistingSystemPackages.contains(ps.name); 23628 } 23629 } 23630 23631 @Override 23632 public List<PackageInfo> getOverlayPackages(int userId) { 23633 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23634 synchronized (mPackages) { 23635 for (PackageParser.Package p : mPackages.values()) { 23636 if (p.mOverlayTarget != null) { 23637 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23638 if (pkg != null) { 23639 overlayPackages.add(pkg); 23640 } 23641 } 23642 } 23643 } 23644 return overlayPackages; 23645 } 23646 23647 @Override 23648 public List<String> getTargetPackageNames(int userId) { 23649 List<String> targetPackages = new ArrayList<>(); 23650 synchronized (mPackages) { 23651 for (PackageParser.Package p : mPackages.values()) { 23652 if (p.mOverlayTarget == null) { 23653 targetPackages.add(p.packageName); 23654 } 23655 } 23656 } 23657 return targetPackages; 23658 } 23659 23660 @Override 23661 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23662 @Nullable List<String> overlayPackageNames) { 23663 synchronized (mPackages) { 23664 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23665 Slog.e(TAG, "failed to find package " + targetPackageName); 23666 return false; 23667 } 23668 ArrayList<String> overlayPaths = null; 23669 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23670 final int N = overlayPackageNames.size(); 23671 overlayPaths = new ArrayList<>(N); 23672 for (int i = 0; i < N; i++) { 23673 final String packageName = overlayPackageNames.get(i); 23674 final PackageParser.Package pkg = mPackages.get(packageName); 23675 if (pkg == null) { 23676 Slog.e(TAG, "failed to find package " + packageName); 23677 return false; 23678 } 23679 overlayPaths.add(pkg.baseCodePath); 23680 } 23681 } 23682 23683 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23684 ps.setOverlayPaths(overlayPaths, userId); 23685 return true; 23686 } 23687 } 23688 23689 @Override 23690 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23691 int flags, int userId, boolean resolveForStart) { 23692 return resolveIntentInternal( 23693 intent, resolvedType, flags, userId, resolveForStart); 23694 } 23695 23696 @Override 23697 public ResolveInfo resolveService(Intent intent, String resolvedType, 23698 int flags, int userId, int callingUid) { 23699 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23700 } 23701 23702 @Override 23703 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23704 return PackageManagerService.this.resolveContentProviderInternal( 23705 name, flags, userId); 23706 } 23707 23708 @Override 23709 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23710 synchronized (mPackages) { 23711 mIsolatedOwners.put(isolatedUid, ownerUid); 23712 } 23713 } 23714 23715 @Override 23716 public void removeIsolatedUid(int isolatedUid) { 23717 synchronized (mPackages) { 23718 mIsolatedOwners.delete(isolatedUid); 23719 } 23720 } 23721 23722 @Override 23723 public int getUidTargetSdkVersion(int uid) { 23724 synchronized (mPackages) { 23725 return getUidTargetSdkVersionLockedLPr(uid); 23726 } 23727 } 23728 23729 @Override 23730 public int getPackageTargetSdkVersion(String packageName) { 23731 synchronized (mPackages) { 23732 return getPackageTargetSdkVersionLockedLPr(packageName); 23733 } 23734 } 23735 23736 @Override 23737 public boolean canAccessInstantApps(int callingUid, int userId) { 23738 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23739 } 23740 23741 @Override 23742 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23743 synchronized (mPackages) { 23744 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23745 } 23746 } 23747 23748 @Override 23749 public void notifyPackageUse(String packageName, int reason) { 23750 synchronized (mPackages) { 23751 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23752 } 23753 } 23754 } 23755 23756 @Override 23757 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23758 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23759 synchronized (mPackages) { 23760 final long identity = Binder.clearCallingIdentity(); 23761 try { 23762 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23763 packageNames, userId); 23764 } finally { 23765 Binder.restoreCallingIdentity(identity); 23766 } 23767 } 23768 } 23769 23770 @Override 23771 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23772 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23773 synchronized (mPackages) { 23774 final long identity = Binder.clearCallingIdentity(); 23775 try { 23776 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23777 packageNames, userId); 23778 } finally { 23779 Binder.restoreCallingIdentity(identity); 23780 } 23781 } 23782 } 23783 23784 private static void enforceSystemOrPhoneCaller(String tag) { 23785 int callingUid = Binder.getCallingUid(); 23786 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23787 throw new SecurityException( 23788 "Cannot call " + tag + " from UID " + callingUid); 23789 } 23790 } 23791 23792 boolean isHistoricalPackageUsageAvailable() { 23793 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23794 } 23795 23796 /** 23797 * Return a <b>copy</b> of the collection of packages known to the package manager. 23798 * @return A copy of the values of mPackages. 23799 */ 23800 Collection<PackageParser.Package> getPackages() { 23801 synchronized (mPackages) { 23802 return new ArrayList<>(mPackages.values()); 23803 } 23804 } 23805 23806 /** 23807 * Logs process start information (including base APK hash) to the security log. 23808 * @hide 23809 */ 23810 @Override 23811 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23812 String apkFile, int pid) { 23813 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23814 return; 23815 } 23816 if (!SecurityLog.isLoggingEnabled()) { 23817 return; 23818 } 23819 Bundle data = new Bundle(); 23820 data.putLong("startTimestamp", System.currentTimeMillis()); 23821 data.putString("processName", processName); 23822 data.putInt("uid", uid); 23823 data.putString("seinfo", seinfo); 23824 data.putString("apkFile", apkFile); 23825 data.putInt("pid", pid); 23826 Message msg = mProcessLoggingHandler.obtainMessage( 23827 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23828 msg.setData(data); 23829 mProcessLoggingHandler.sendMessage(msg); 23830 } 23831 23832 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23833 return mCompilerStats.getPackageStats(pkgName); 23834 } 23835 23836 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23837 return getOrCreateCompilerPackageStats(pkg.packageName); 23838 } 23839 23840 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23841 return mCompilerStats.getOrCreatePackageStats(pkgName); 23842 } 23843 23844 public void deleteCompilerPackageStats(String pkgName) { 23845 mCompilerStats.deletePackageStats(pkgName); 23846 } 23847 23848 @Override 23849 public int getInstallReason(String packageName, int userId) { 23850 final int callingUid = Binder.getCallingUid(); 23851 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23852 true /* requireFullPermission */, false /* checkShell */, 23853 "get install reason"); 23854 synchronized (mPackages) { 23855 final PackageSetting ps = mSettings.mPackages.get(packageName); 23856 if (filterAppAccessLPr(ps, callingUid, userId)) { 23857 return PackageManager.INSTALL_REASON_UNKNOWN; 23858 } 23859 if (ps != null) { 23860 return ps.getInstallReason(userId); 23861 } 23862 } 23863 return PackageManager.INSTALL_REASON_UNKNOWN; 23864 } 23865 23866 @Override 23867 public boolean canRequestPackageInstalls(String packageName, int userId) { 23868 return canRequestPackageInstallsInternal(packageName, 0, userId, 23869 true /* throwIfPermNotDeclared*/); 23870 } 23871 23872 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23873 boolean throwIfPermNotDeclared) { 23874 int callingUid = Binder.getCallingUid(); 23875 int uid = getPackageUid(packageName, 0, userId); 23876 if (callingUid != uid && callingUid != Process.ROOT_UID 23877 && callingUid != Process.SYSTEM_UID) { 23878 throw new SecurityException( 23879 "Caller uid " + callingUid + " does not own package " + packageName); 23880 } 23881 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23882 if (info == null) { 23883 return false; 23884 } 23885 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23886 return false; 23887 } 23888 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23889 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23890 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23891 if (throwIfPermNotDeclared) { 23892 throw new SecurityException("Need to declare " + appOpPermission 23893 + " to call this api"); 23894 } else { 23895 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23896 return false; 23897 } 23898 } 23899 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23900 return false; 23901 } 23902 if (mExternalSourcesPolicy != null) { 23903 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23904 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23905 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23906 } 23907 } 23908 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23909 } 23910 23911 @Override 23912 public ComponentName getInstantAppResolverSettingsComponent() { 23913 return mInstantAppResolverSettingsComponent; 23914 } 23915 23916 @Override 23917 public ComponentName getInstantAppInstallerComponent() { 23918 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23919 return null; 23920 } 23921 return mInstantAppInstallerActivity == null 23922 ? null : mInstantAppInstallerActivity.getComponentName(); 23923 } 23924 23925 @Override 23926 public String getInstantAppAndroidId(String packageName, int userId) { 23927 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23928 "getInstantAppAndroidId"); 23929 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23930 true /* requireFullPermission */, false /* checkShell */, 23931 "getInstantAppAndroidId"); 23932 // Make sure the target is an Instant App. 23933 if (!isInstantApp(packageName, userId)) { 23934 return null; 23935 } 23936 synchronized (mPackages) { 23937 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23938 } 23939 } 23940 23941 boolean canHaveOatDir(String packageName) { 23942 synchronized (mPackages) { 23943 PackageParser.Package p = mPackages.get(packageName); 23944 if (p == null) { 23945 return false; 23946 } 23947 return p.canHaveOatDir(); 23948 } 23949 } 23950 23951 private String getOatDir(PackageParser.Package pkg) { 23952 if (!pkg.canHaveOatDir()) { 23953 return null; 23954 } 23955 File codePath = new File(pkg.codePath); 23956 if (codePath.isDirectory()) { 23957 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23958 } 23959 return null; 23960 } 23961 23962 void deleteOatArtifactsOfPackage(String packageName) { 23963 final String[] instructionSets; 23964 final List<String> codePaths; 23965 final String oatDir; 23966 final PackageParser.Package pkg; 23967 synchronized (mPackages) { 23968 pkg = mPackages.get(packageName); 23969 } 23970 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23971 codePaths = pkg.getAllCodePaths(); 23972 oatDir = getOatDir(pkg); 23973 23974 for (String codePath : codePaths) { 23975 for (String isa : instructionSets) { 23976 try { 23977 mInstaller.deleteOdex(codePath, isa, oatDir); 23978 } catch (InstallerException e) { 23979 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23980 } 23981 } 23982 } 23983 } 23984 23985 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23986 Set<String> unusedPackages = new HashSet<>(); 23987 long currentTimeInMillis = System.currentTimeMillis(); 23988 synchronized (mPackages) { 23989 for (PackageParser.Package pkg : mPackages.values()) { 23990 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23991 if (ps == null) { 23992 continue; 23993 } 23994 PackageDexUsage.PackageUseInfo packageUseInfo = 23995 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23996 if (PackageManagerServiceUtils 23997 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23998 downgradeTimeThresholdMillis, packageUseInfo, 23999 pkg.getLatestPackageUseTimeInMills(), 24000 pkg.getLatestForegroundPackageUseTimeInMills())) { 24001 unusedPackages.add(pkg.packageName); 24002 } 24003 } 24004 } 24005 return unusedPackages; 24006 } 24007 24008 @Override 24009 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24010 int userId) { 24011 final int callingUid = Binder.getCallingUid(); 24012 final int callingAppId = UserHandle.getAppId(callingUid); 24013 24014 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24015 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24016 24017 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24018 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24019 throw new SecurityException("Caller must have the " 24020 + SET_HARMFUL_APP_WARNINGS + " permission."); 24021 } 24022 24023 synchronized(mPackages) { 24024 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24025 scheduleWritePackageRestrictionsLocked(userId); 24026 } 24027 } 24028 24029 @Nullable 24030 @Override 24031 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24032 final int callingUid = Binder.getCallingUid(); 24033 final int callingAppId = UserHandle.getAppId(callingUid); 24034 24035 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24036 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24037 24038 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24039 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24040 throw new SecurityException("Caller must have the " 24041 + SET_HARMFUL_APP_WARNINGS + " permission."); 24042 } 24043 24044 synchronized(mPackages) { 24045 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 24046 } 24047 } 24048} 24049 24050interface PackageSender { 24051 /** 24052 * @param userIds User IDs where the action occurred on a full application 24053 * @param instantUserIds User IDs where the action occurred on an instant application 24054 */ 24055 void sendPackageBroadcast(final String action, final String pkg, 24056 final Bundle extras, final int flags, final String targetPkg, 24057 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 24058 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 24059 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 24060 void notifyPackageAdded(String packageName); 24061 void notifyPackageRemoved(String packageName); 24062} 24063