PackageManagerService.java revision f996b76623f2b6e958e76d40d17b17f673ed30b5
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.COMPONENT_ENABLED_STATE_DEFAULT; 28import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 29import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 30import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 31import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 32import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 35import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 36import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 37import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 38import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 39import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 40import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 41import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 42import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 43import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 44import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 46import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 47import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 48import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 49import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 50import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_NEWER_SDK; 52import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 54import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 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_USER_RESTRICTED; 59import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 60import static android.content.pm.PackageManager.INSTALL_INTERNAL; 61import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 66import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 67import static android.content.pm.PackageManager.MATCH_ALL; 68import static android.content.pm.PackageManager.MATCH_ANY_USER; 69import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 71import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 72import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 73import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 74import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 75import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 76import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 77import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 78import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 79import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 80import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 81import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 82import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 83import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 84import static android.content.pm.PackageManager.PERMISSION_DENIED; 85import static android.content.pm.PackageManager.PERMISSION_GRANTED; 86import static android.content.pm.PackageParser.isApkFile; 87import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 88import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 89import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 90import static android.system.OsConstants.O_CREAT; 91import static android.system.OsConstants.O_RDWR; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 93import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 94import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 95import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 96import static com.android.internal.util.ArrayUtils.appendInt; 97import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 99import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 100import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 101import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 103import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 104import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 105import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 106import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 107import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 108import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 109import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 110import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 111import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 112import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 115import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 116 117import android.Manifest; 118import android.annotation.IntDef; 119import android.annotation.NonNull; 120import android.annotation.Nullable; 121import android.app.ActivityManager; 122import android.app.AppOpsManager; 123import android.app.IActivityManager; 124import android.app.ResourcesManager; 125import android.app.admin.IDevicePolicyManager; 126import android.app.admin.SecurityLog; 127import android.app.backup.IBackupManager; 128import android.content.BroadcastReceiver; 129import android.content.ComponentName; 130import android.content.ContentResolver; 131import android.content.Context; 132import android.content.IIntentReceiver; 133import android.content.Intent; 134import android.content.IntentFilter; 135import android.content.IntentSender; 136import android.content.IntentSender.SendIntentException; 137import android.content.ServiceConnection; 138import android.content.pm.ActivityInfo; 139import android.content.pm.ApplicationInfo; 140import android.content.pm.AppsQueryHelper; 141import android.content.pm.AuxiliaryResolveInfo; 142import android.content.pm.ChangedPackages; 143import android.content.pm.ComponentInfo; 144import android.content.pm.FallbackCategoryProvider; 145import android.content.pm.FeatureInfo; 146import android.content.pm.IDexModuleRegisterCallback; 147import android.content.pm.IOnPermissionsChangeListener; 148import android.content.pm.IPackageDataObserver; 149import android.content.pm.IPackageDeleteObserver; 150import android.content.pm.IPackageDeleteObserver2; 151import android.content.pm.IPackageInstallObserver2; 152import android.content.pm.IPackageInstaller; 153import android.content.pm.IPackageManager; 154import android.content.pm.IPackageManagerNative; 155import android.content.pm.IPackageMoveObserver; 156import android.content.pm.IPackageStatsObserver; 157import android.content.pm.InstantAppInfo; 158import android.content.pm.InstantAppRequest; 159import android.content.pm.InstantAppResolveInfo; 160import android.content.pm.InstrumentationInfo; 161import android.content.pm.IntentFilterVerificationInfo; 162import android.content.pm.KeySet; 163import android.content.pm.PackageCleanItem; 164import android.content.pm.PackageInfo; 165import android.content.pm.PackageInfoLite; 166import android.content.pm.PackageInstaller; 167import android.content.pm.PackageList; 168import android.content.pm.PackageManager; 169import android.content.pm.PackageManagerInternal; 170import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 171import android.content.pm.PackageManagerInternal.PackageListObserver; 172import android.content.pm.PackageParser; 173import android.content.pm.PackageParser.ActivityIntentInfo; 174import android.content.pm.PackageParser.Package; 175import android.content.pm.PackageParser.PackageLite; 176import android.content.pm.PackageParser.PackageParserException; 177import android.content.pm.PackageParser.ParseFlags; 178import android.content.pm.PackageParser.ServiceIntentInfo; 179import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 180import android.content.pm.PackageStats; 181import android.content.pm.PackageUserState; 182import android.content.pm.ParceledListSlice; 183import android.content.pm.PermissionGroupInfo; 184import android.content.pm.PermissionInfo; 185import android.content.pm.ProviderInfo; 186import android.content.pm.ResolveInfo; 187import android.content.pm.ServiceInfo; 188import android.content.pm.SharedLibraryInfo; 189import android.content.pm.Signature; 190import android.content.pm.UserInfo; 191import android.content.pm.VerifierDeviceIdentity; 192import android.content.pm.VerifierInfo; 193import android.content.pm.VersionedPackage; 194import android.content.pm.dex.IArtManager; 195import android.content.res.Resources; 196import android.database.ContentObserver; 197import android.graphics.Bitmap; 198import android.hardware.display.DisplayManager; 199import android.net.Uri; 200import android.os.Binder; 201import android.os.Build; 202import android.os.Bundle; 203import android.os.Debug; 204import android.os.Environment; 205import android.os.Environment.UserEnvironment; 206import android.os.FileUtils; 207import android.os.Handler; 208import android.os.IBinder; 209import android.os.Looper; 210import android.os.Message; 211import android.os.Parcel; 212import android.os.ParcelFileDescriptor; 213import android.os.PatternMatcher; 214import android.os.Process; 215import android.os.RemoteCallbackList; 216import android.os.RemoteException; 217import android.os.ResultReceiver; 218import android.os.SELinux; 219import android.os.ServiceManager; 220import android.os.ShellCallback; 221import android.os.SystemClock; 222import android.os.SystemProperties; 223import android.os.Trace; 224import android.os.UserHandle; 225import android.os.UserManager; 226import android.os.UserManagerInternal; 227import android.os.storage.IStorageManager; 228import android.os.storage.StorageEventListener; 229import android.os.storage.StorageManager; 230import android.os.storage.StorageManagerInternal; 231import android.os.storage.VolumeInfo; 232import android.os.storage.VolumeRecord; 233import android.provider.Settings.Global; 234import android.provider.Settings.Secure; 235import android.security.KeyStore; 236import android.security.SystemKeyStore; 237import android.service.pm.PackageServiceDumpProto; 238import android.system.ErrnoException; 239import android.system.Os; 240import android.text.TextUtils; 241import android.text.format.DateUtils; 242import android.util.ArrayMap; 243import android.util.ArraySet; 244import android.util.Base64; 245import android.util.DisplayMetrics; 246import android.util.EventLog; 247import android.util.ExceptionUtils; 248import android.util.Log; 249import android.util.LogPrinter; 250import android.util.LongSparseArray; 251import android.util.LongSparseLongArray; 252import android.util.MathUtils; 253import android.util.PackageUtils; 254import android.util.Pair; 255import android.util.PrintStreamPrinter; 256import android.util.Slog; 257import android.util.SparseArray; 258import android.util.SparseBooleanArray; 259import android.util.SparseIntArray; 260import android.util.TimingsTraceLog; 261import android.util.Xml; 262import android.util.jar.StrictJarFile; 263import android.util.proto.ProtoOutputStream; 264import android.view.Display; 265 266import com.android.internal.R; 267import com.android.internal.annotations.GuardedBy; 268import com.android.internal.app.IMediaContainerService; 269import com.android.internal.app.ResolverActivity; 270import com.android.internal.content.NativeLibraryHelper; 271import com.android.internal.content.PackageHelper; 272import com.android.internal.logging.MetricsLogger; 273import com.android.internal.os.IParcelFileDescriptorFactory; 274import com.android.internal.os.SomeArgs; 275import com.android.internal.os.Zygote; 276import com.android.internal.telephony.CarrierAppUtils; 277import com.android.internal.util.ArrayUtils; 278import com.android.internal.util.ConcurrentUtils; 279import com.android.internal.util.DumpUtils; 280import com.android.internal.util.FastXmlSerializer; 281import com.android.internal.util.IndentingPrintWriter; 282import com.android.internal.util.Preconditions; 283import com.android.internal.util.XmlUtils; 284import com.android.server.AttributeCache; 285import com.android.server.DeviceIdleController; 286import com.android.server.EventLogTags; 287import com.android.server.FgThread; 288import com.android.server.IntentResolver; 289import com.android.server.LocalServices; 290import com.android.server.LockGuard; 291import com.android.server.ServiceThread; 292import com.android.server.SystemConfig; 293import com.android.server.SystemServerInitThreadPool; 294import com.android.server.Watchdog; 295import com.android.server.net.NetworkPolicyManagerInternal; 296import com.android.server.pm.Installer.InstallerException; 297import com.android.server.pm.Settings.DatabaseVersion; 298import com.android.server.pm.Settings.VersionInfo; 299import com.android.server.pm.dex.ArtManagerService; 300import com.android.server.pm.dex.DexLogger; 301import com.android.server.pm.dex.DexManager; 302import com.android.server.pm.dex.DexoptOptions; 303import com.android.server.pm.dex.PackageDexUsage; 304import com.android.server.pm.permission.BasePermission; 305import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 306import com.android.server.pm.permission.PermissionManagerService; 307import com.android.server.pm.permission.PermissionManagerInternal; 308import com.android.server.pm.permission.DefaultPermissionGrantPolicy.DefaultPermissionGrantedCallback; 309import com.android.server.pm.permission.PermissionManagerInternal.PermissionCallback; 310import com.android.server.pm.permission.PermissionsState; 311import com.android.server.pm.permission.PermissionsState.PermissionState; 312import com.android.server.storage.DeviceStorageMonitorInternal; 313 314import dalvik.system.CloseGuard; 315import dalvik.system.VMRuntime; 316 317import libcore.io.IoUtils; 318 319import org.xmlpull.v1.XmlPullParser; 320import org.xmlpull.v1.XmlPullParserException; 321import org.xmlpull.v1.XmlSerializer; 322 323import java.io.BufferedOutputStream; 324import java.io.ByteArrayInputStream; 325import java.io.ByteArrayOutputStream; 326import java.io.File; 327import java.io.FileDescriptor; 328import java.io.FileInputStream; 329import java.io.FileOutputStream; 330import java.io.FilenameFilter; 331import java.io.IOException; 332import java.io.PrintWriter; 333import java.lang.annotation.Retention; 334import java.lang.annotation.RetentionPolicy; 335import java.nio.charset.StandardCharsets; 336import java.security.DigestInputStream; 337import java.security.MessageDigest; 338import java.security.NoSuchAlgorithmException; 339import java.security.PublicKey; 340import java.security.SecureRandom; 341import java.security.cert.CertificateException; 342import java.util.ArrayList; 343import java.util.Arrays; 344import java.util.Collection; 345import java.util.Collections; 346import java.util.Comparator; 347import java.util.HashMap; 348import java.util.HashSet; 349import java.util.Iterator; 350import java.util.LinkedHashSet; 351import java.util.List; 352import java.util.Map; 353import java.util.Objects; 354import java.util.Set; 355import java.util.concurrent.CountDownLatch; 356import java.util.concurrent.Future; 357import java.util.concurrent.TimeUnit; 358import java.util.concurrent.atomic.AtomicBoolean; 359import java.util.concurrent.atomic.AtomicInteger; 360 361/** 362 * Keep track of all those APKs everywhere. 363 * <p> 364 * Internally there are two important locks: 365 * <ul> 366 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 367 * and other related state. It is a fine-grained lock that should only be held 368 * momentarily, as it's one of the most contended locks in the system. 369 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 370 * operations typically involve heavy lifting of application data on disk. Since 371 * {@code installd} is single-threaded, and it's operations can often be slow, 372 * this lock should never be acquired while already holding {@link #mPackages}. 373 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 374 * holding {@link #mInstallLock}. 375 * </ul> 376 * Many internal methods rely on the caller to hold the appropriate locks, and 377 * this contract is expressed through method name suffixes: 378 * <ul> 379 * <li>fooLI(): the caller must hold {@link #mInstallLock} 380 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 381 * being modified must be frozen 382 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 383 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 384 * </ul> 385 * <p> 386 * Because this class is very central to the platform's security; please run all 387 * CTS and unit tests whenever making modifications: 388 * 389 * <pre> 390 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 391 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 392 * </pre> 393 */ 394public class PackageManagerService extends IPackageManager.Stub 395 implements PackageSender { 396 static final String TAG = "PackageManager"; 397 public static final boolean DEBUG_SETTINGS = false; 398 static final boolean DEBUG_PREFERRED = false; 399 static final boolean DEBUG_UPGRADE = false; 400 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 401 private static final boolean DEBUG_BACKUP = false; 402 public static final boolean DEBUG_INSTALL = false; 403 public static final boolean DEBUG_REMOVE = false; 404 private static final boolean DEBUG_BROADCASTS = false; 405 private static final boolean DEBUG_SHOW_INFO = false; 406 private static final boolean DEBUG_PACKAGE_INFO = false; 407 private static final boolean DEBUG_INTENT_MATCHING = false; 408 public static final boolean DEBUG_PACKAGE_SCANNING = false; 409 private static final boolean DEBUG_VERIFY = false; 410 private static final boolean DEBUG_FILTERS = false; 411 public static final boolean DEBUG_PERMISSIONS = false; 412 private static final boolean DEBUG_SHARED_LIBRARIES = false; 413 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 414 415 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 416 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 417 // user, but by default initialize to this. 418 public static final boolean DEBUG_DEXOPT = false; 419 420 private static final boolean DEBUG_ABI_SELECTION = false; 421 private static final boolean DEBUG_EPHEMERAL = Build.IS_DEBUGGABLE; 422 private static final boolean DEBUG_TRIAGED_MISSING = false; 423 private static final boolean DEBUG_APP_DATA = false; 424 425 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 426 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 427 428 private static final boolean HIDE_EPHEMERAL_APIS = false; 429 430 private static final boolean ENABLE_FREE_CACHE_V2 = 431 SystemProperties.getBoolean("fw.free_cache_v2", true); 432 433 private static final int RADIO_UID = Process.PHONE_UID; 434 private static final int LOG_UID = Process.LOG_UID; 435 private static final int NFC_UID = Process.NFC_UID; 436 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 437 private static final int SHELL_UID = Process.SHELL_UID; 438 439 // Suffix used during package installation when copying/moving 440 // package apks to install directory. 441 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 442 443 static final int SCAN_NO_DEX = 1<<0; 444 static final int SCAN_UPDATE_SIGNATURE = 1<<1; 445 static final int SCAN_NEW_INSTALL = 1<<2; 446 static final int SCAN_UPDATE_TIME = 1<<3; 447 static final int SCAN_BOOTING = 1<<4; 448 static final int SCAN_TRUSTED_OVERLAY = 1<<5; 449 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<6; 450 static final int SCAN_REQUIRE_KNOWN = 1<<7; 451 static final int SCAN_MOVE = 1<<8; 452 static final int SCAN_INITIAL = 1<<9; 453 static final int SCAN_CHECK_ONLY = 1<<10; 454 static final int SCAN_DONT_KILL_APP = 1<<11; 455 static final int SCAN_IGNORE_FROZEN = 1<<12; 456 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1<<13; 457 static final int SCAN_AS_INSTANT_APP = 1<<14; 458 static final int SCAN_AS_FULL_APP = 1<<15; 459 static final int SCAN_AS_VIRTUAL_PRELOAD = 1<<16; 460 static final int SCAN_AS_SYSTEM = 1<<17; 461 static final int SCAN_AS_PRIVILEGED = 1<<18; 462 static final int SCAN_AS_OEM = 1<<19; 463 static final int SCAN_AS_VENDOR = 1<<20; 464 465 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 466 SCAN_NO_DEX, 467 SCAN_UPDATE_SIGNATURE, 468 SCAN_NEW_INSTALL, 469 SCAN_UPDATE_TIME, 470 SCAN_BOOTING, 471 SCAN_TRUSTED_OVERLAY, 472 SCAN_DELETE_DATA_ON_FAILURES, 473 SCAN_REQUIRE_KNOWN, 474 SCAN_MOVE, 475 SCAN_INITIAL, 476 SCAN_CHECK_ONLY, 477 SCAN_DONT_KILL_APP, 478 SCAN_IGNORE_FROZEN, 479 SCAN_FIRST_BOOT_OR_UPGRADE, 480 SCAN_AS_INSTANT_APP, 481 SCAN_AS_FULL_APP, 482 SCAN_AS_VIRTUAL_PRELOAD, 483 }) 484 @Retention(RetentionPolicy.SOURCE) 485 public @interface ScanFlags {} 486 487 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 488 /** Extension of the compressed packages */ 489 public final static String COMPRESSED_EXTENSION = ".gz"; 490 /** Suffix of stub packages on the system partition */ 491 public final static String STUB_SUFFIX = "-Stub"; 492 493 private static final int[] EMPTY_INT_ARRAY = new int[0]; 494 495 private static final int TYPE_UNKNOWN = 0; 496 private static final int TYPE_ACTIVITY = 1; 497 private static final int TYPE_RECEIVER = 2; 498 private static final int TYPE_SERVICE = 3; 499 private static final int TYPE_PROVIDER = 4; 500 @IntDef(prefix = { "TYPE_" }, value = { 501 TYPE_UNKNOWN, 502 TYPE_ACTIVITY, 503 TYPE_RECEIVER, 504 TYPE_SERVICE, 505 TYPE_PROVIDER, 506 }) 507 @Retention(RetentionPolicy.SOURCE) 508 public @interface ComponentType {} 509 510 /** 511 * Timeout (in milliseconds) after which the watchdog should declare that 512 * our handler thread is wedged. The usual default for such things is one 513 * minute but we sometimes do very lengthy I/O operations on this thread, 514 * such as installing multi-gigabyte applications, so ours needs to be longer. 515 */ 516 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 517 518 /** 519 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 520 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 521 * settings entry if available, otherwise we use the hardcoded default. If it's been 522 * more than this long since the last fstrim, we force one during the boot sequence. 523 * 524 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 525 * one gets run at the next available charging+idle time. This final mandatory 526 * no-fstrim check kicks in only of the other scheduling criteria is never met. 527 */ 528 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 529 530 /** 531 * Whether verification is enabled by default. 532 */ 533 private static final boolean DEFAULT_VERIFY_ENABLE = true; 534 535 /** 536 * The default maximum time to wait for the verification agent to return in 537 * milliseconds. 538 */ 539 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 540 541 /** 542 * The default response for package verification timeout. 543 * 544 * This can be either PackageManager.VERIFICATION_ALLOW or 545 * PackageManager.VERIFICATION_REJECT. 546 */ 547 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 548 549 public static final String PLATFORM_PACKAGE_NAME = "android"; 550 551 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 552 553 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 554 DEFAULT_CONTAINER_PACKAGE, 555 "com.android.defcontainer.DefaultContainerService"); 556 557 private static final String KILL_APP_REASON_GIDS_CHANGED = 558 "permission grant or revoke changed gids"; 559 560 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 561 "permissions revoked"; 562 563 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 564 565 private static final String PACKAGE_SCHEME = "package"; 566 567 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 568 569 private static final String PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB = "pm.dexopt.priv-apps-oob"; 570 571 /** Canonical intent used to identify what counts as a "web browser" app */ 572 private static final Intent sBrowserIntent; 573 static { 574 sBrowserIntent = new Intent(); 575 sBrowserIntent.setAction(Intent.ACTION_VIEW); 576 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 577 sBrowserIntent.setData(Uri.parse("http:")); 578 } 579 580 /** 581 * The set of all protected actions [i.e. those actions for which a high priority 582 * intent filter is disallowed]. 583 */ 584 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 585 static { 586 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 587 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 588 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 589 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 590 } 591 592 // Compilation reasons. 593 public static final int REASON_FIRST_BOOT = 0; 594 public static final int REASON_BOOT = 1; 595 public static final int REASON_INSTALL = 2; 596 public static final int REASON_BACKGROUND_DEXOPT = 3; 597 public static final int REASON_AB_OTA = 4; 598 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 599 public static final int REASON_SHARED = 6; 600 601 public static final int REASON_LAST = REASON_SHARED; 602 603 /** 604 * Version number for the package parser cache. Increment this whenever the format or 605 * extent of cached data changes. See {@code PackageParser#setCacheDir}. 606 */ 607 private static final String PACKAGE_PARSER_CACHE_VERSION = "1"; 608 609 /** 610 * Whether the package parser cache is enabled. 611 */ 612 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 613 614 /** 615 * Permissions required in order to receive instant application lifecycle broadcasts. 616 */ 617 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 618 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 619 620 final ServiceThread mHandlerThread; 621 622 final PackageHandler mHandler; 623 624 private final ProcessLoggingHandler mProcessLoggingHandler; 625 626 /** 627 * Messages for {@link #mHandler} that need to wait for system ready before 628 * being dispatched. 629 */ 630 private ArrayList<Message> mPostSystemReadyMessages; 631 632 final int mSdkVersion = Build.VERSION.SDK_INT; 633 634 final Context mContext; 635 final boolean mFactoryTest; 636 final boolean mOnlyCore; 637 final DisplayMetrics mMetrics; 638 final int mDefParseFlags; 639 final String[] mSeparateProcesses; 640 final boolean mIsUpgrade; 641 final boolean mIsPreNUpgrade; 642 final boolean mIsPreNMR1Upgrade; 643 644 // Have we told the Activity Manager to whitelist the default container service by uid yet? 645 @GuardedBy("mPackages") 646 boolean mDefaultContainerWhitelisted = false; 647 648 @GuardedBy("mPackages") 649 private boolean mDexOptDialogShown; 650 651 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 652 // LOCK HELD. Can be called with mInstallLock held. 653 @GuardedBy("mInstallLock") 654 final Installer mInstaller; 655 656 /** Directory where installed applications are stored */ 657 private static final File sAppInstallDir = 658 new File(Environment.getDataDirectory(), "app"); 659 /** Directory where installed application's 32-bit native libraries are copied. */ 660 private static final File sAppLib32InstallDir = 661 new File(Environment.getDataDirectory(), "app-lib"); 662 /** Directory where code and non-resource assets of forward-locked applications are stored */ 663 private static final File sDrmAppPrivateInstallDir = 664 new File(Environment.getDataDirectory(), "app-private"); 665 666 // ---------------------------------------------------------------- 667 668 // Lock for state used when installing and doing other long running 669 // operations. Methods that must be called with this lock held have 670 // the suffix "LI". 671 final Object mInstallLock = new Object(); 672 673 // ---------------------------------------------------------------- 674 675 // Keys are String (package name), values are Package. This also serves 676 // as the lock for the global state. Methods that must be called with 677 // this lock held have the prefix "LP". 678 @GuardedBy("mPackages") 679 final ArrayMap<String, PackageParser.Package> mPackages = 680 new ArrayMap<String, PackageParser.Package>(); 681 682 final ArrayMap<String, Set<String>> mKnownCodebase = 683 new ArrayMap<String, Set<String>>(); 684 685 // Keys are isolated uids and values are the uid of the application 686 // that created the isolated proccess. 687 @GuardedBy("mPackages") 688 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 689 690 /** 691 * Tracks new system packages [received in an OTA] that we expect to 692 * find updated user-installed versions. Keys are package name, values 693 * are package location. 694 */ 695 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 696 /** 697 * Tracks high priority intent filters for protected actions. During boot, certain 698 * filter actions are protected and should never be allowed to have a high priority 699 * intent filter for them. However, there is one, and only one exception -- the 700 * setup wizard. It must be able to define a high priority intent filter for these 701 * actions to ensure there are no escapes from the wizard. We need to delay processing 702 * of these during boot as we need to look at all of the system packages in order 703 * to know which component is the setup wizard. 704 */ 705 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 706 /** 707 * Whether or not processing protected filters should be deferred. 708 */ 709 private boolean mDeferProtectedFilters = true; 710 711 /** 712 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 713 */ 714 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 715 /** 716 * Whether or not system app permissions should be promoted from install to runtime. 717 */ 718 boolean mPromoteSystemApps; 719 720 @GuardedBy("mPackages") 721 final Settings mSettings; 722 723 /** 724 * Set of package names that are currently "frozen", which means active 725 * surgery is being done on the code/data for that package. The platform 726 * will refuse to launch frozen packages to avoid race conditions. 727 * 728 * @see PackageFreezer 729 */ 730 @GuardedBy("mPackages") 731 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 732 733 final ProtectedPackages mProtectedPackages; 734 735 @GuardedBy("mLoadedVolumes") 736 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 737 738 boolean mFirstBoot; 739 740 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 741 742 @GuardedBy("mAvailableFeatures") 743 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 744 745 private final InstantAppRegistry mInstantAppRegistry; 746 747 @GuardedBy("mPackages") 748 int mChangedPackagesSequenceNumber; 749 /** 750 * List of changed [installed, removed or updated] packages. 751 * mapping from user id -> sequence number -> package name 752 */ 753 @GuardedBy("mPackages") 754 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 755 /** 756 * The sequence number of the last change to a package. 757 * mapping from user id -> package name -> sequence number 758 */ 759 @GuardedBy("mPackages") 760 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 761 762 @GuardedBy("mPackages") 763 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 764 765 class PackageParserCallback implements PackageParser.Callback { 766 @Override public final boolean hasFeature(String feature) { 767 return PackageManagerService.this.hasSystemFeature(feature, 0); 768 } 769 770 final List<PackageParser.Package> getStaticOverlayPackagesLocked( 771 Collection<PackageParser.Package> allPackages, String targetPackageName) { 772 List<PackageParser.Package> overlayPackages = null; 773 for (PackageParser.Package p : allPackages) { 774 if (targetPackageName.equals(p.mOverlayTarget) && p.mIsStaticOverlay) { 775 if (overlayPackages == null) { 776 overlayPackages = new ArrayList<PackageParser.Package>(); 777 } 778 overlayPackages.add(p); 779 } 780 } 781 if (overlayPackages != null) { 782 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 783 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 784 return p1.mOverlayPriority - p2.mOverlayPriority; 785 } 786 }; 787 Collections.sort(overlayPackages, cmp); 788 } 789 return overlayPackages; 790 } 791 792 final String[] getStaticOverlayPathsLocked(Collection<PackageParser.Package> allPackages, 793 String targetPackageName, String targetPath) { 794 if ("android".equals(targetPackageName)) { 795 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 796 // native AssetManager. 797 return null; 798 } 799 List<PackageParser.Package> overlayPackages = 800 getStaticOverlayPackagesLocked(allPackages, targetPackageName); 801 if (overlayPackages == null || overlayPackages.isEmpty()) { 802 return null; 803 } 804 List<String> overlayPathList = null; 805 for (PackageParser.Package overlayPackage : overlayPackages) { 806 if (targetPath == null) { 807 if (overlayPathList == null) { 808 overlayPathList = new ArrayList<String>(); 809 } 810 overlayPathList.add(overlayPackage.baseCodePath); 811 continue; 812 } 813 814 try { 815 // Creates idmaps for system to parse correctly the Android manifest of the 816 // target package. 817 // 818 // OverlayManagerService will update each of them with a correct gid from its 819 // target package app id. 820 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 821 UserHandle.getSharedAppGid( 822 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 823 if (overlayPathList == null) { 824 overlayPathList = new ArrayList<String>(); 825 } 826 overlayPathList.add(overlayPackage.baseCodePath); 827 } catch (InstallerException e) { 828 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 829 overlayPackage.baseCodePath); 830 } 831 } 832 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 833 } 834 835 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 836 synchronized (mPackages) { 837 return getStaticOverlayPathsLocked( 838 mPackages.values(), targetPackageName, targetPath); 839 } 840 } 841 842 @Override public final String[] getOverlayApks(String targetPackageName) { 843 return getStaticOverlayPaths(targetPackageName, null); 844 } 845 846 @Override public final String[] getOverlayPaths(String targetPackageName, 847 String targetPath) { 848 return getStaticOverlayPaths(targetPackageName, targetPath); 849 } 850 } 851 852 class ParallelPackageParserCallback extends PackageParserCallback { 853 List<PackageParser.Package> mOverlayPackages = null; 854 855 void findStaticOverlayPackages() { 856 synchronized (mPackages) { 857 for (PackageParser.Package p : mPackages.values()) { 858 if (p.mIsStaticOverlay) { 859 if (mOverlayPackages == null) { 860 mOverlayPackages = new ArrayList<PackageParser.Package>(); 861 } 862 mOverlayPackages.add(p); 863 } 864 } 865 } 866 } 867 868 @Override 869 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 870 // We can trust mOverlayPackages without holding mPackages because package uninstall 871 // can't happen while running parallel parsing. 872 // Moreover holding mPackages on each parsing thread causes dead-lock. 873 return mOverlayPackages == null ? null : 874 getStaticOverlayPathsLocked(mOverlayPackages, targetPackageName, targetPath); 875 } 876 } 877 878 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 879 final ParallelPackageParserCallback mParallelPackageParserCallback = 880 new ParallelPackageParserCallback(); 881 882 public static final class SharedLibraryEntry { 883 public final @Nullable String path; 884 public final @Nullable String apk; 885 public final @NonNull SharedLibraryInfo info; 886 887 SharedLibraryEntry(String _path, String _apk, String name, long version, int type, 888 String declaringPackageName, long declaringPackageVersionCode) { 889 path = _path; 890 apk = _apk; 891 info = new SharedLibraryInfo(name, version, type, new VersionedPackage( 892 declaringPackageName, declaringPackageVersionCode), null); 893 } 894 } 895 896 // Currently known shared libraries. 897 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mSharedLibraries = new ArrayMap<>(); 898 final ArrayMap<String, LongSparseArray<SharedLibraryEntry>> mStaticLibsByDeclaringPackage = 899 new ArrayMap<>(); 900 901 // All available activities, for your resolving pleasure. 902 final ActivityIntentResolver mActivities = 903 new ActivityIntentResolver(); 904 905 // All available receivers, for your resolving pleasure. 906 final ActivityIntentResolver mReceivers = 907 new ActivityIntentResolver(); 908 909 // All available services, for your resolving pleasure. 910 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 911 912 // All available providers, for your resolving pleasure. 913 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 914 915 // Mapping from provider base names (first directory in content URI codePath) 916 // to the provider information. 917 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 918 new ArrayMap<String, PackageParser.Provider>(); 919 920 // Mapping from instrumentation class names to info about them. 921 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 922 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 923 924 // Packages whose data we have transfered into another package, thus 925 // should no longer exist. 926 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 927 928 // Broadcast actions that are only available to the system. 929 @GuardedBy("mProtectedBroadcasts") 930 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 931 932 /** List of packages waiting for verification. */ 933 final SparseArray<PackageVerificationState> mPendingVerification 934 = new SparseArray<PackageVerificationState>(); 935 936 final PackageInstallerService mInstallerService; 937 938 final ArtManagerService mArtManagerService; 939 940 private final PackageDexOptimizer mPackageDexOptimizer; 941 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 942 // is used by other apps). 943 private final DexManager mDexManager; 944 945 private AtomicInteger mNextMoveId = new AtomicInteger(); 946 private final MoveCallbacks mMoveCallbacks; 947 948 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 949 950 // Cache of users who need badging. 951 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 952 953 /** Token for keys in mPendingVerification. */ 954 private int mPendingVerificationToken = 0; 955 956 volatile boolean mSystemReady; 957 volatile boolean mSafeMode; 958 volatile boolean mHasSystemUidErrors; 959 private volatile boolean mEphemeralAppsDisabled; 960 961 ApplicationInfo mAndroidApplication; 962 final ActivityInfo mResolveActivity = new ActivityInfo(); 963 final ResolveInfo mResolveInfo = new ResolveInfo(); 964 ComponentName mResolveComponentName; 965 PackageParser.Package mPlatformPackage; 966 ComponentName mCustomResolverComponentName; 967 968 boolean mResolverReplaced = false; 969 970 private final @Nullable ComponentName mIntentFilterVerifierComponent; 971 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 972 973 private int mIntentFilterVerificationToken = 0; 974 975 /** The service connection to the ephemeral resolver */ 976 final EphemeralResolverConnection mInstantAppResolverConnection; 977 /** Component used to show resolver settings for Instant Apps */ 978 final ComponentName mInstantAppResolverSettingsComponent; 979 980 /** Activity used to install instant applications */ 981 ActivityInfo mInstantAppInstallerActivity; 982 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 983 984 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 985 = new SparseArray<IntentFilterVerificationState>(); 986 987 // TODO remove this and go through mPermissonManager directly 988 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 989 private final PermissionManagerInternal mPermissionManager; 990 991 // List of packages names to keep cached, even if they are uninstalled for all users 992 private List<String> mKeepUninstalledPackages; 993 994 private UserManagerInternal mUserManagerInternal; 995 996 private DeviceIdleController.LocalService mDeviceIdleController; 997 998 private File mCacheDir; 999 1000 private Future<?> mPrepareAppDataFuture; 1001 1002 private static class IFVerificationParams { 1003 PackageParser.Package pkg; 1004 boolean replacing; 1005 int userId; 1006 int verifierUid; 1007 1008 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1009 int _userId, int _verifierUid) { 1010 pkg = _pkg; 1011 replacing = _replacing; 1012 userId = _userId; 1013 replacing = _replacing; 1014 verifierUid = _verifierUid; 1015 } 1016 } 1017 1018 private interface IntentFilterVerifier<T extends IntentFilter> { 1019 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1020 T filter, String packageName); 1021 void startVerifications(int userId); 1022 void receiveVerificationResponse(int verificationId); 1023 } 1024 1025 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1026 private Context mContext; 1027 private ComponentName mIntentFilterVerifierComponent; 1028 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 1029 1030 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1031 mContext = context; 1032 mIntentFilterVerifierComponent = verifierComponent; 1033 } 1034 1035 private String getDefaultScheme() { 1036 return IntentFilter.SCHEME_HTTPS; 1037 } 1038 1039 @Override 1040 public void startVerifications(int userId) { 1041 // Launch verifications requests 1042 int count = mCurrentIntentFilterVerifications.size(); 1043 for (int n=0; n<count; n++) { 1044 int verificationId = mCurrentIntentFilterVerifications.get(n); 1045 final IntentFilterVerificationState ivs = 1046 mIntentFilterVerificationStates.get(verificationId); 1047 1048 String packageName = ivs.getPackageName(); 1049 1050 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1051 final int filterCount = filters.size(); 1052 ArraySet<String> domainsSet = new ArraySet<>(); 1053 for (int m=0; m<filterCount; m++) { 1054 PackageParser.ActivityIntentInfo filter = filters.get(m); 1055 domainsSet.addAll(filter.getHostsList()); 1056 } 1057 synchronized (mPackages) { 1058 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1059 packageName, domainsSet) != null) { 1060 scheduleWriteSettingsLocked(); 1061 } 1062 } 1063 sendVerificationRequest(verificationId, ivs); 1064 } 1065 mCurrentIntentFilterVerifications.clear(); 1066 } 1067 1068 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1069 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1070 verificationIntent.putExtra( 1071 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1072 verificationId); 1073 verificationIntent.putExtra( 1074 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1075 getDefaultScheme()); 1076 verificationIntent.putExtra( 1077 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1078 ivs.getHostsString()); 1079 verificationIntent.putExtra( 1080 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1081 ivs.getPackageName()); 1082 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1083 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1084 1085 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1086 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1087 mIntentFilterVerifierComponent.getPackageName(), getVerificationTimeout(), 1088 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1089 1090 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM); 1091 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1092 "Sending IntentFilter verification broadcast"); 1093 } 1094 1095 public void receiveVerificationResponse(int verificationId) { 1096 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1097 1098 final boolean verified = ivs.isVerified(); 1099 1100 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1101 final int count = filters.size(); 1102 if (DEBUG_DOMAIN_VERIFICATION) { 1103 Slog.i(TAG, "Received verification response " + verificationId 1104 + " for " + count + " filters, verified=" + verified); 1105 } 1106 for (int n=0; n<count; n++) { 1107 PackageParser.ActivityIntentInfo filter = filters.get(n); 1108 filter.setVerified(verified); 1109 1110 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1111 + " verified with result:" + verified + " and hosts:" 1112 + ivs.getHostsString()); 1113 } 1114 1115 mIntentFilterVerificationStates.remove(verificationId); 1116 1117 final String packageName = ivs.getPackageName(); 1118 IntentFilterVerificationInfo ivi = null; 1119 1120 synchronized (mPackages) { 1121 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1122 } 1123 if (ivi == null) { 1124 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1125 + verificationId + " packageName:" + packageName); 1126 return; 1127 } 1128 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1129 "Updating IntentFilterVerificationInfo for package " + packageName 1130 +" verificationId:" + verificationId); 1131 1132 synchronized (mPackages) { 1133 if (verified) { 1134 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1135 } else { 1136 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1137 } 1138 scheduleWriteSettingsLocked(); 1139 1140 final int userId = ivs.getUserId(); 1141 if (userId != UserHandle.USER_ALL) { 1142 final int userStatus = 1143 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1144 1145 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1146 boolean needUpdate = false; 1147 1148 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 1149 // already been set by the User thru the Disambiguation dialog 1150 switch (userStatus) { 1151 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1152 if (verified) { 1153 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1154 } else { 1155 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 1156 } 1157 needUpdate = true; 1158 break; 1159 1160 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1161 if (verified) { 1162 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1163 needUpdate = true; 1164 } 1165 break; 1166 1167 default: 1168 // Nothing to do 1169 } 1170 1171 if (needUpdate) { 1172 mSettings.updateIntentFilterVerificationStatusLPw( 1173 packageName, updatedStatus, userId); 1174 scheduleWritePackageRestrictionsLocked(userId); 1175 } 1176 } 1177 } 1178 } 1179 1180 @Override 1181 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1182 ActivityIntentInfo filter, String packageName) { 1183 if (!hasValidDomains(filter)) { 1184 return false; 1185 } 1186 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1187 if (ivs == null) { 1188 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1189 packageName); 1190 } 1191 if (DEBUG_DOMAIN_VERIFICATION) { 1192 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1193 } 1194 ivs.addFilter(filter); 1195 return true; 1196 } 1197 1198 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1199 int userId, int verificationId, String packageName) { 1200 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1201 verifierUid, userId, packageName); 1202 ivs.setPendingState(); 1203 synchronized (mPackages) { 1204 mIntentFilterVerificationStates.append(verificationId, ivs); 1205 mCurrentIntentFilterVerifications.add(verificationId); 1206 } 1207 return ivs; 1208 } 1209 } 1210 1211 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1212 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1213 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1214 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1215 } 1216 1217 // Set of pending broadcasts for aggregating enable/disable of components. 1218 static class PendingPackageBroadcasts { 1219 // for each user id, a map of <package name -> components within that package> 1220 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1221 1222 public PendingPackageBroadcasts() { 1223 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 1224 } 1225 1226 public ArrayList<String> get(int userId, String packageName) { 1227 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1228 return packages.get(packageName); 1229 } 1230 1231 public void put(int userId, String packageName, ArrayList<String> components) { 1232 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1233 packages.put(packageName, components); 1234 } 1235 1236 public void remove(int userId, String packageName) { 1237 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1238 if (packages != null) { 1239 packages.remove(packageName); 1240 } 1241 } 1242 1243 public void remove(int userId) { 1244 mUidMap.remove(userId); 1245 } 1246 1247 public int userIdCount() { 1248 return mUidMap.size(); 1249 } 1250 1251 public int userIdAt(int n) { 1252 return mUidMap.keyAt(n); 1253 } 1254 1255 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1256 return mUidMap.get(userId); 1257 } 1258 1259 public int size() { 1260 // total number of pending broadcast entries across all userIds 1261 int num = 0; 1262 for (int i = 0; i< mUidMap.size(); i++) { 1263 num += mUidMap.valueAt(i).size(); 1264 } 1265 return num; 1266 } 1267 1268 public void clear() { 1269 mUidMap.clear(); 1270 } 1271 1272 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1273 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1274 if (map == null) { 1275 map = new ArrayMap<String, ArrayList<String>>(); 1276 mUidMap.put(userId, map); 1277 } 1278 return map; 1279 } 1280 } 1281 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1282 1283 // Service Connection to remote media container service to copy 1284 // package uri's from external media onto secure containers 1285 // or internal storage. 1286 private IMediaContainerService mContainerService = null; 1287 1288 static final int SEND_PENDING_BROADCAST = 1; 1289 static final int MCS_BOUND = 3; 1290 static final int END_COPY = 4; 1291 static final int INIT_COPY = 5; 1292 static final int MCS_UNBIND = 6; 1293 static final int START_CLEANING_PACKAGE = 7; 1294 static final int FIND_INSTALL_LOC = 8; 1295 static final int POST_INSTALL = 9; 1296 static final int MCS_RECONNECT = 10; 1297 static final int MCS_GIVE_UP = 11; 1298 static final int WRITE_SETTINGS = 13; 1299 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1300 static final int PACKAGE_VERIFIED = 15; 1301 static final int CHECK_PENDING_VERIFICATION = 16; 1302 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1303 static final int INTENT_FILTER_VERIFIED = 18; 1304 static final int WRITE_PACKAGE_LIST = 19; 1305 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1306 1307 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1308 1309 // Delay time in millisecs 1310 static final int BROADCAST_DELAY = 10 * 1000; 1311 1312 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1313 2 * 60 * 60 * 1000L; /* two hours */ 1314 1315 static UserManagerService sUserManager; 1316 1317 // Stores a list of users whose package restrictions file needs to be updated 1318 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1319 1320 final private DefaultContainerConnection mDefContainerConn = 1321 new DefaultContainerConnection(); 1322 class DefaultContainerConnection implements ServiceConnection { 1323 public void onServiceConnected(ComponentName name, IBinder service) { 1324 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1325 final IMediaContainerService imcs = IMediaContainerService.Stub 1326 .asInterface(Binder.allowBlocking(service)); 1327 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1328 } 1329 1330 public void onServiceDisconnected(ComponentName name) { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1332 } 1333 } 1334 1335 // Recordkeeping of restore-after-install operations that are currently in flight 1336 // between the Package Manager and the Backup Manager 1337 static class PostInstallData { 1338 public InstallArgs args; 1339 public PackageInstalledInfo res; 1340 1341 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1342 args = _a; 1343 res = _r; 1344 } 1345 } 1346 1347 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1348 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1349 1350 // XML tags for backup/restore of various bits of state 1351 private static final String TAG_PREFERRED_BACKUP = "pa"; 1352 private static final String TAG_DEFAULT_APPS = "da"; 1353 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1354 1355 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1356 private static final String TAG_ALL_GRANTS = "rt-grants"; 1357 private static final String TAG_GRANT = "grant"; 1358 private static final String ATTR_PACKAGE_NAME = "pkg"; 1359 1360 private static final String TAG_PERMISSION = "perm"; 1361 private static final String ATTR_PERMISSION_NAME = "name"; 1362 private static final String ATTR_IS_GRANTED = "g"; 1363 private static final String ATTR_USER_SET = "set"; 1364 private static final String ATTR_USER_FIXED = "fixed"; 1365 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1366 1367 // System/policy permission grants are not backed up 1368 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1369 FLAG_PERMISSION_POLICY_FIXED 1370 | FLAG_PERMISSION_SYSTEM_FIXED 1371 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1372 1373 // And we back up these user-adjusted states 1374 private static final int USER_RUNTIME_GRANT_MASK = 1375 FLAG_PERMISSION_USER_SET 1376 | FLAG_PERMISSION_USER_FIXED 1377 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1378 1379 final @Nullable String mRequiredVerifierPackage; 1380 final @NonNull String mRequiredInstallerPackage; 1381 final @NonNull String mRequiredUninstallerPackage; 1382 final @Nullable String mSetupWizardPackage; 1383 final @Nullable String mStorageManagerPackage; 1384 final @NonNull String mServicesSystemSharedLibraryPackageName; 1385 final @NonNull String mSharedSystemSharedLibraryPackageName; 1386 1387 private final PackageUsage mPackageUsage = new PackageUsage(); 1388 private final CompilerStats mCompilerStats = new CompilerStats(); 1389 1390 class PackageHandler extends Handler { 1391 private boolean mBound = false; 1392 final ArrayList<HandlerParams> mPendingInstalls = 1393 new ArrayList<HandlerParams>(); 1394 1395 private boolean connectToService() { 1396 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1397 " DefaultContainerService"); 1398 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1399 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1400 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1401 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1402 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1403 mBound = true; 1404 return true; 1405 } 1406 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1407 return false; 1408 } 1409 1410 private void disconnectService() { 1411 mContainerService = null; 1412 mBound = false; 1413 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1414 mContext.unbindService(mDefContainerConn); 1415 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1416 } 1417 1418 PackageHandler(Looper looper) { 1419 super(looper); 1420 } 1421 1422 public void handleMessage(Message msg) { 1423 try { 1424 doHandleMessage(msg); 1425 } finally { 1426 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1427 } 1428 } 1429 1430 void doHandleMessage(Message msg) { 1431 switch (msg.what) { 1432 case INIT_COPY: { 1433 HandlerParams params = (HandlerParams) msg.obj; 1434 int idx = mPendingInstalls.size(); 1435 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1436 // If a bind was already initiated we dont really 1437 // need to do anything. The pending install 1438 // will be processed later on. 1439 if (!mBound) { 1440 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1441 System.identityHashCode(mHandler)); 1442 // If this is the only one pending we might 1443 // have to bind to the service again. 1444 if (!connectToService()) { 1445 Slog.e(TAG, "Failed to bind to media container service"); 1446 params.serviceError(); 1447 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1448 System.identityHashCode(mHandler)); 1449 if (params.traceMethod != null) { 1450 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1451 params.traceCookie); 1452 } 1453 return; 1454 } else { 1455 // Once we bind to the service, the first 1456 // pending request will be processed. 1457 mPendingInstalls.add(idx, params); 1458 } 1459 } else { 1460 mPendingInstalls.add(idx, params); 1461 // Already bound to the service. Just make 1462 // sure we trigger off processing the first request. 1463 if (idx == 0) { 1464 mHandler.sendEmptyMessage(MCS_BOUND); 1465 } 1466 } 1467 break; 1468 } 1469 case MCS_BOUND: { 1470 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1471 if (msg.obj != null) { 1472 mContainerService = (IMediaContainerService) msg.obj; 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1474 System.identityHashCode(mHandler)); 1475 } 1476 if (mContainerService == null) { 1477 if (!mBound) { 1478 // Something seriously wrong since we are not bound and we are not 1479 // waiting for connection. Bail out. 1480 Slog.e(TAG, "Cannot bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 if (params.traceMethod != null) { 1487 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1488 params.traceMethod, params.traceCookie); 1489 } 1490 return; 1491 } 1492 mPendingInstalls.clear(); 1493 } else { 1494 Slog.w(TAG, "Waiting to connect to media container service"); 1495 } 1496 } else if (mPendingInstalls.size() > 0) { 1497 HandlerParams params = mPendingInstalls.get(0); 1498 if (params != null) { 1499 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1500 System.identityHashCode(params)); 1501 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1502 if (params.startCopy()) { 1503 // We are done... look for more work or to 1504 // go idle. 1505 if (DEBUG_SD_INSTALL) Log.i(TAG, 1506 "Checking for more work or unbind..."); 1507 // Delete pending install 1508 if (mPendingInstalls.size() > 0) { 1509 mPendingInstalls.remove(0); 1510 } 1511 if (mPendingInstalls.size() == 0) { 1512 if (mBound) { 1513 if (DEBUG_SD_INSTALL) Log.i(TAG, 1514 "Posting delayed MCS_UNBIND"); 1515 removeMessages(MCS_UNBIND); 1516 Message ubmsg = obtainMessage(MCS_UNBIND); 1517 // Unbind after a little delay, to avoid 1518 // continual thrashing. 1519 sendMessageDelayed(ubmsg, 10000); 1520 } 1521 } else { 1522 // There are more pending requests in queue. 1523 // Just post MCS_BOUND message to trigger processing 1524 // of next pending install. 1525 if (DEBUG_SD_INSTALL) Log.i(TAG, 1526 "Posting MCS_BOUND for next work"); 1527 mHandler.sendEmptyMessage(MCS_BOUND); 1528 } 1529 } 1530 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1531 } 1532 } else { 1533 // Should never happen ideally. 1534 Slog.w(TAG, "Empty queue"); 1535 } 1536 break; 1537 } 1538 case MCS_RECONNECT: { 1539 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1540 if (mPendingInstalls.size() > 0) { 1541 if (mBound) { 1542 disconnectService(); 1543 } 1544 if (!connectToService()) { 1545 Slog.e(TAG, "Failed to bind to media container service"); 1546 for (HandlerParams params : mPendingInstalls) { 1547 // Indicate service bind error 1548 params.serviceError(); 1549 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1550 System.identityHashCode(params)); 1551 } 1552 mPendingInstalls.clear(); 1553 } 1554 } 1555 break; 1556 } 1557 case MCS_UNBIND: { 1558 // If there is no actual work left, then time to unbind. 1559 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1560 1561 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1562 if (mBound) { 1563 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1564 1565 disconnectService(); 1566 } 1567 } else if (mPendingInstalls.size() > 0) { 1568 // There are more pending requests in queue. 1569 // Just post MCS_BOUND message to trigger processing 1570 // of next pending install. 1571 mHandler.sendEmptyMessage(MCS_BOUND); 1572 } 1573 1574 break; 1575 } 1576 case MCS_GIVE_UP: { 1577 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1578 HandlerParams params = mPendingInstalls.remove(0); 1579 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1580 System.identityHashCode(params)); 1581 break; 1582 } 1583 case SEND_PENDING_BROADCAST: { 1584 String packages[]; 1585 ArrayList<String> components[]; 1586 int size = 0; 1587 int uids[]; 1588 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1589 synchronized (mPackages) { 1590 if (mPendingBroadcasts == null) { 1591 return; 1592 } 1593 size = mPendingBroadcasts.size(); 1594 if (size <= 0) { 1595 // Nothing to be done. Just return 1596 return; 1597 } 1598 packages = new String[size]; 1599 components = new ArrayList[size]; 1600 uids = new int[size]; 1601 int i = 0; // filling out the above arrays 1602 1603 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1604 int packageUserId = mPendingBroadcasts.userIdAt(n); 1605 Iterator<Map.Entry<String, ArrayList<String>>> it 1606 = mPendingBroadcasts.packagesForUserId(packageUserId) 1607 .entrySet().iterator(); 1608 while (it.hasNext() && i < size) { 1609 Map.Entry<String, ArrayList<String>> ent = it.next(); 1610 packages[i] = ent.getKey(); 1611 components[i] = ent.getValue(); 1612 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1613 uids[i] = (ps != null) 1614 ? UserHandle.getUid(packageUserId, ps.appId) 1615 : -1; 1616 i++; 1617 } 1618 } 1619 size = i; 1620 mPendingBroadcasts.clear(); 1621 } 1622 // Send broadcasts 1623 for (int i = 0; i < size; i++) { 1624 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1625 } 1626 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1627 break; 1628 } 1629 case START_CLEANING_PACKAGE: { 1630 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1631 final String packageName = (String)msg.obj; 1632 final int userId = msg.arg1; 1633 final boolean andCode = msg.arg2 != 0; 1634 synchronized (mPackages) { 1635 if (userId == UserHandle.USER_ALL) { 1636 int[] users = sUserManager.getUserIds(); 1637 for (int user : users) { 1638 mSettings.addPackageToCleanLPw( 1639 new PackageCleanItem(user, packageName, andCode)); 1640 } 1641 } else { 1642 mSettings.addPackageToCleanLPw( 1643 new PackageCleanItem(userId, packageName, andCode)); 1644 } 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 startCleaningPackages(); 1648 } break; 1649 case POST_INSTALL: { 1650 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1651 1652 PostInstallData data = mRunningInstalls.get(msg.arg1); 1653 final boolean didRestore = (msg.arg2 != 0); 1654 mRunningInstalls.delete(msg.arg1); 1655 1656 if (data != null) { 1657 InstallArgs args = data.args; 1658 PackageInstalledInfo parentRes = data.res; 1659 1660 final boolean grantPermissions = (args.installFlags 1661 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1662 final boolean killApp = (args.installFlags 1663 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1664 final boolean virtualPreload = ((args.installFlags 1665 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1666 final String[] grantedPermissions = args.installGrantPermissions; 1667 1668 // Handle the parent package 1669 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1670 virtualPreload, grantedPermissions, didRestore, 1671 args.installerPackageName, args.observer); 1672 1673 // Handle the child packages 1674 final int childCount = (parentRes.addedChildPackages != null) 1675 ? parentRes.addedChildPackages.size() : 0; 1676 for (int i = 0; i < childCount; i++) { 1677 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1678 handlePackagePostInstall(childRes, grantPermissions, killApp, 1679 virtualPreload, grantedPermissions, false /*didRestore*/, 1680 args.installerPackageName, args.observer); 1681 } 1682 1683 // Log tracing if needed 1684 if (args.traceMethod != null) { 1685 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1686 args.traceCookie); 1687 } 1688 } else { 1689 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1690 } 1691 1692 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1693 } break; 1694 case WRITE_SETTINGS: { 1695 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1696 synchronized (mPackages) { 1697 removeMessages(WRITE_SETTINGS); 1698 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1699 mSettings.writeLPr(); 1700 mDirtyUsers.clear(); 1701 } 1702 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1703 } break; 1704 case WRITE_PACKAGE_RESTRICTIONS: { 1705 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1706 synchronized (mPackages) { 1707 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1708 for (int userId : mDirtyUsers) { 1709 mSettings.writePackageRestrictionsLPr(userId); 1710 } 1711 mDirtyUsers.clear(); 1712 } 1713 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1714 } break; 1715 case WRITE_PACKAGE_LIST: { 1716 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1717 synchronized (mPackages) { 1718 removeMessages(WRITE_PACKAGE_LIST); 1719 mSettings.writePackageListLPr(msg.arg1); 1720 } 1721 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1722 } break; 1723 case CHECK_PENDING_VERIFICATION: { 1724 final int verificationId = msg.arg1; 1725 final PackageVerificationState state = mPendingVerification.get(verificationId); 1726 1727 if ((state != null) && !state.timeoutExtended()) { 1728 final InstallArgs args = state.getInstallArgs(); 1729 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1730 1731 Slog.i(TAG, "Verification timed out for " + originUri); 1732 mPendingVerification.remove(verificationId); 1733 1734 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1735 1736 final UserHandle user = args.getUser(); 1737 if (getDefaultVerificationResponse(user) 1738 == PackageManager.VERIFICATION_ALLOW) { 1739 Slog.i(TAG, "Continuing with installation of " + originUri); 1740 state.setVerifierResponse(Binder.getCallingUid(), 1741 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1742 broadcastPackageVerified(verificationId, originUri, 1743 PackageManager.VERIFICATION_ALLOW, user); 1744 try { 1745 ret = args.copyApk(mContainerService, true); 1746 } catch (RemoteException e) { 1747 Slog.e(TAG, "Could not contact the ContainerService"); 1748 } 1749 } else { 1750 broadcastPackageVerified(verificationId, originUri, 1751 PackageManager.VERIFICATION_REJECT, user); 1752 } 1753 1754 Trace.asyncTraceEnd( 1755 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1756 1757 processPendingInstall(args, ret); 1758 mHandler.sendEmptyMessage(MCS_UNBIND); 1759 } 1760 break; 1761 } 1762 case PACKAGE_VERIFIED: { 1763 final int verificationId = msg.arg1; 1764 1765 final PackageVerificationState state = mPendingVerification.get(verificationId); 1766 if (state == null) { 1767 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1768 break; 1769 } 1770 1771 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1772 1773 state.setVerifierResponse(response.callerUid, response.code); 1774 1775 if (state.isVerificationComplete()) { 1776 mPendingVerification.remove(verificationId); 1777 1778 final InstallArgs args = state.getInstallArgs(); 1779 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1780 1781 int ret; 1782 if (state.isInstallAllowed()) { 1783 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1784 broadcastPackageVerified(verificationId, originUri, 1785 response.code, state.getInstallArgs().getUser()); 1786 try { 1787 ret = args.copyApk(mContainerService, true); 1788 } catch (RemoteException e) { 1789 Slog.e(TAG, "Could not contact the ContainerService"); 1790 } 1791 } else { 1792 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1793 } 1794 1795 Trace.asyncTraceEnd( 1796 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1797 1798 processPendingInstall(args, ret); 1799 mHandler.sendEmptyMessage(MCS_UNBIND); 1800 } 1801 1802 break; 1803 } 1804 case START_INTENT_FILTER_VERIFICATIONS: { 1805 IFVerificationParams params = (IFVerificationParams) msg.obj; 1806 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1807 params.replacing, params.pkg); 1808 break; 1809 } 1810 case INTENT_FILTER_VERIFIED: { 1811 final int verificationId = msg.arg1; 1812 1813 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1814 verificationId); 1815 if (state == null) { 1816 Slog.w(TAG, "Invalid IntentFilter verification token " 1817 + verificationId + " received"); 1818 break; 1819 } 1820 1821 final int userId = state.getUserId(); 1822 1823 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1824 "Processing IntentFilter verification with token:" 1825 + verificationId + " and userId:" + userId); 1826 1827 final IntentFilterVerificationResponse response = 1828 (IntentFilterVerificationResponse) msg.obj; 1829 1830 state.setVerifierResponse(response.callerUid, response.code); 1831 1832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1833 "IntentFilter verification with token:" + verificationId 1834 + " and userId:" + userId 1835 + " is settings verifier response with response code:" 1836 + response.code); 1837 1838 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1839 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1840 + response.getFailedDomainsString()); 1841 } 1842 1843 if (state.isVerificationComplete()) { 1844 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1845 } else { 1846 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1847 "IntentFilter verification with token:" + verificationId 1848 + " was not said to be complete"); 1849 } 1850 1851 break; 1852 } 1853 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1854 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1855 mInstantAppResolverConnection, 1856 (InstantAppRequest) msg.obj, 1857 mInstantAppInstallerActivity, 1858 mHandler); 1859 } 1860 } 1861 } 1862 } 1863 1864 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1865 @Override 1866 public void onGidsChanged(int appId, int userId) { 1867 mHandler.post(new Runnable() { 1868 @Override 1869 public void run() { 1870 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 1871 } 1872 }); 1873 } 1874 @Override 1875 public void onPermissionGranted(int uid, int userId) { 1876 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1877 1878 // Not critical; if this is lost, the application has to request again. 1879 synchronized (mPackages) { 1880 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1881 } 1882 } 1883 @Override 1884 public void onInstallPermissionGranted() { 1885 synchronized (mPackages) { 1886 scheduleWriteSettingsLocked(); 1887 } 1888 } 1889 @Override 1890 public void onPermissionRevoked(int uid, int userId) { 1891 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1892 1893 synchronized (mPackages) { 1894 // Critical; after this call the application should never have the permission 1895 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1896 } 1897 1898 final int appId = UserHandle.getAppId(uid); 1899 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1900 } 1901 @Override 1902 public void onInstallPermissionRevoked() { 1903 synchronized (mPackages) { 1904 scheduleWriteSettingsLocked(); 1905 } 1906 } 1907 @Override 1908 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1909 synchronized (mPackages) { 1910 for (int userId : updatedUserIds) { 1911 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1912 } 1913 } 1914 } 1915 @Override 1916 public void onInstallPermissionUpdated() { 1917 synchronized (mPackages) { 1918 scheduleWriteSettingsLocked(); 1919 } 1920 } 1921 @Override 1922 public void onPermissionRemoved() { 1923 synchronized (mPackages) { 1924 mSettings.writeLPr(); 1925 } 1926 } 1927 }; 1928 1929 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1930 boolean killApp, boolean virtualPreload, String[] grantedPermissions, 1931 boolean launchedForRestore, String installerPackage, 1932 IPackageInstallObserver2 installObserver) { 1933 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1934 // Send the removed broadcasts 1935 if (res.removedInfo != null) { 1936 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1937 } 1938 1939 // Now that we successfully installed the package, grant runtime 1940 // permissions if requested before broadcasting the install. Also 1941 // for legacy apps in permission review mode we clear the permission 1942 // review flag which is used to emulate runtime permissions for 1943 // legacy apps. 1944 if (grantPermissions) { 1945 final int callingUid = Binder.getCallingUid(); 1946 mPermissionManager.grantRequestedRuntimePermissions( 1947 res.pkg, res.newUsers, grantedPermissions, callingUid, 1948 mPermissionCallback); 1949 } 1950 1951 final boolean update = res.removedInfo != null 1952 && res.removedInfo.removedPackage != null; 1953 final String installerPackageName = 1954 res.installerPackageName != null 1955 ? res.installerPackageName 1956 : res.removedInfo != null 1957 ? res.removedInfo.installerPackageName 1958 : null; 1959 1960 // If this is the first time we have child packages for a disabled privileged 1961 // app that had no children, we grant requested runtime permissions to the new 1962 // children if the parent on the system image had them already granted. 1963 if (res.pkg.parentPackage != null) { 1964 final int callingUid = Binder.getCallingUid(); 1965 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1966 res.pkg, callingUid, mPermissionCallback); 1967 } 1968 1969 synchronized (mPackages) { 1970 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1971 } 1972 1973 final String packageName = res.pkg.applicationInfo.packageName; 1974 1975 // Determine the set of users who are adding this package for 1976 // the first time vs. those who are seeing an update. 1977 int[] firstUserIds = EMPTY_INT_ARRAY; 1978 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1979 int[] updateUserIds = EMPTY_INT_ARRAY; 1980 int[] instantUserIds = EMPTY_INT_ARRAY; 1981 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1982 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1983 for (int newUser : res.newUsers) { 1984 final boolean isInstantApp = ps.getInstantApp(newUser); 1985 if (allNewUsers) { 1986 if (isInstantApp) { 1987 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1988 } else { 1989 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1990 } 1991 continue; 1992 } 1993 boolean isNew = true; 1994 for (int origUser : res.origUsers) { 1995 if (origUser == newUser) { 1996 isNew = false; 1997 break; 1998 } 1999 } 2000 if (isNew) { 2001 if (isInstantApp) { 2002 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 2003 } else { 2004 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 2005 } 2006 } else { 2007 if (isInstantApp) { 2008 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 2009 } else { 2010 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 2011 } 2012 } 2013 } 2014 2015 // Send installed broadcasts if the package is not a static shared lib. 2016 if (res.pkg.staticSharedLibName == null) { 2017 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 2018 2019 // Send added for users that see the package for the first time 2020 // sendPackageAddedForNewUsers also deals with system apps 2021 int appId = UserHandle.getAppId(res.uid); 2022 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 2023 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 2024 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 2025 2026 // Send added for users that don't see the package for the first time 2027 Bundle extras = new Bundle(1); 2028 extras.putInt(Intent.EXTRA_UID, res.uid); 2029 if (update) { 2030 extras.putBoolean(Intent.EXTRA_REPLACING, true); 2031 } 2032 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2033 extras, 0 /*flags*/, 2034 null /*targetPackage*/, null /*finishedReceiver*/, 2035 updateUserIds, instantUserIds); 2036 if (installerPackageName != null) { 2037 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2038 extras, 0 /*flags*/, 2039 installerPackageName, null /*finishedReceiver*/, 2040 updateUserIds, instantUserIds); 2041 } 2042 2043 // Send replaced for users that don't see the package for the first time 2044 if (update) { 2045 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2046 packageName, extras, 0 /*flags*/, 2047 null /*targetPackage*/, null /*finishedReceiver*/, 2048 updateUserIds, instantUserIds); 2049 if (installerPackageName != null) { 2050 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2051 extras, 0 /*flags*/, 2052 installerPackageName, null /*finishedReceiver*/, 2053 updateUserIds, instantUserIds); 2054 } 2055 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2056 null /*package*/, null /*extras*/, 0 /*flags*/, 2057 packageName /*targetPackage*/, 2058 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2059 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2060 // First-install and we did a restore, so we're responsible for the 2061 // first-launch broadcast. 2062 if (DEBUG_BACKUP) { 2063 Slog.i(TAG, "Post-restore of " + packageName 2064 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2065 } 2066 sendFirstLaunchBroadcast(packageName, installerPackage, 2067 firstUserIds, firstInstantUserIds); 2068 } 2069 2070 // Send broadcast package appeared if forward locked/external for all users 2071 // treat asec-hosted packages like removable media on upgrade 2072 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 2073 if (DEBUG_INSTALL) { 2074 Slog.i(TAG, "upgrading pkg " + res.pkg 2075 + " is ASEC-hosted -> AVAILABLE"); 2076 } 2077 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2078 ArrayList<String> pkgList = new ArrayList<>(1); 2079 pkgList.add(packageName); 2080 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2081 } 2082 } 2083 2084 // Work that needs to happen on first install within each user 2085 if (firstUserIds != null && firstUserIds.length > 0) { 2086 synchronized (mPackages) { 2087 for (int userId : firstUserIds) { 2088 // If this app is a browser and it's newly-installed for some 2089 // users, clear any default-browser state in those users. The 2090 // app's nature doesn't depend on the user, so we can just check 2091 // its browser nature in any user and generalize. 2092 if (packageIsBrowser(packageName, userId)) { 2093 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 2094 } 2095 2096 // We may also need to apply pending (restored) runtime 2097 // permission grants within these users. 2098 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 2099 } 2100 } 2101 } 2102 2103 if (allNewUsers && !update) { 2104 notifyPackageAdded(packageName); 2105 } 2106 2107 // Log current value of "unknown sources" setting 2108 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2109 getUnknownSourcesSettings()); 2110 2111 // Remove the replaced package's older resources safely now 2112 // We delete after a gc for applications on sdcard. 2113 if (res.removedInfo != null && res.removedInfo.args != null) { 2114 Runtime.getRuntime().gc(); 2115 synchronized (mInstallLock) { 2116 res.removedInfo.args.doPostDeleteLI(true); 2117 } 2118 } else { 2119 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2120 // and not block here. 2121 VMRuntime.getRuntime().requestConcurrentGC(); 2122 } 2123 2124 // Notify DexManager that the package was installed for new users. 2125 // The updated users should already be indexed and the package code paths 2126 // should not change. 2127 // Don't notify the manager for ephemeral apps as they are not expected to 2128 // survive long enough to benefit of background optimizations. 2129 for (int userId : firstUserIds) { 2130 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2131 // There's a race currently where some install events may interleave with an uninstall. 2132 // This can lead to package info being null (b/36642664). 2133 if (info != null) { 2134 mDexManager.notifyPackageInstalled(info, userId); 2135 } 2136 } 2137 } 2138 2139 // If someone is watching installs - notify them 2140 if (installObserver != null) { 2141 try { 2142 Bundle extras = extrasForInstallResult(res); 2143 installObserver.onPackageInstalled(res.name, res.returnCode, 2144 res.returnMsg, extras); 2145 } catch (RemoteException e) { 2146 Slog.i(TAG, "Observer no longer exists."); 2147 } 2148 } 2149 } 2150 2151 private StorageEventListener mStorageListener = new StorageEventListener() { 2152 @Override 2153 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2154 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2155 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2156 final String volumeUuid = vol.getFsUuid(); 2157 2158 // Clean up any users or apps that were removed or recreated 2159 // while this volume was missing 2160 sUserManager.reconcileUsers(volumeUuid); 2161 reconcileApps(volumeUuid); 2162 2163 // Clean up any install sessions that expired or were 2164 // cancelled while this volume was missing 2165 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2166 2167 loadPrivatePackages(vol); 2168 2169 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2170 unloadPrivatePackages(vol); 2171 } 2172 } 2173 } 2174 2175 @Override 2176 public void onVolumeForgotten(String fsUuid) { 2177 if (TextUtils.isEmpty(fsUuid)) { 2178 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2179 return; 2180 } 2181 2182 // Remove any apps installed on the forgotten volume 2183 synchronized (mPackages) { 2184 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2185 for (PackageSetting ps : packages) { 2186 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2187 deletePackageVersioned(new VersionedPackage(ps.name, 2188 PackageManager.VERSION_CODE_HIGHEST), 2189 new LegacyPackageDeleteObserver(null).getBinder(), 2190 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2191 // Try very hard to release any references to this package 2192 // so we don't risk the system server being killed due to 2193 // open FDs 2194 AttributeCache.instance().removePackage(ps.name); 2195 } 2196 2197 mSettings.onVolumeForgotten(fsUuid); 2198 mSettings.writeLPr(); 2199 } 2200 } 2201 }; 2202 2203 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2204 Bundle extras = null; 2205 switch (res.returnCode) { 2206 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2207 extras = new Bundle(); 2208 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2209 res.origPermission); 2210 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2211 res.origPackage); 2212 break; 2213 } 2214 case PackageManager.INSTALL_SUCCEEDED: { 2215 extras = new Bundle(); 2216 extras.putBoolean(Intent.EXTRA_REPLACING, 2217 res.removedInfo != null && res.removedInfo.removedPackage != null); 2218 break; 2219 } 2220 } 2221 return extras; 2222 } 2223 2224 void scheduleWriteSettingsLocked() { 2225 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2226 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2227 } 2228 } 2229 2230 void scheduleWritePackageListLocked(int userId) { 2231 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2232 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2233 msg.arg1 = userId; 2234 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2235 } 2236 } 2237 2238 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2239 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2240 scheduleWritePackageRestrictionsLocked(userId); 2241 } 2242 2243 void scheduleWritePackageRestrictionsLocked(int userId) { 2244 final int[] userIds = (userId == UserHandle.USER_ALL) 2245 ? sUserManager.getUserIds() : new int[]{userId}; 2246 for (int nextUserId : userIds) { 2247 if (!sUserManager.exists(nextUserId)) return; 2248 mDirtyUsers.add(nextUserId); 2249 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2250 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2251 } 2252 } 2253 } 2254 2255 public static PackageManagerService main(Context context, Installer installer, 2256 boolean factoryTest, boolean onlyCore) { 2257 // Self-check for initial settings. 2258 PackageManagerServiceCompilerMapping.checkProperties(); 2259 2260 PackageManagerService m = new PackageManagerService(context, installer, 2261 factoryTest, onlyCore); 2262 m.enableSystemUserPackages(); 2263 ServiceManager.addService("package", m); 2264 final PackageManagerNative pmn = m.new PackageManagerNative(); 2265 ServiceManager.addService("package_native", pmn); 2266 return m; 2267 } 2268 2269 private void enableSystemUserPackages() { 2270 if (!UserManager.isSplitSystemUser()) { 2271 return; 2272 } 2273 // For system user, enable apps based on the following conditions: 2274 // - app is whitelisted or belong to one of these groups: 2275 // -- system app which has no launcher icons 2276 // -- system app which has INTERACT_ACROSS_USERS permission 2277 // -- system IME app 2278 // - app is not in the blacklist 2279 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2280 Set<String> enableApps = new ArraySet<>(); 2281 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2282 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2283 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2284 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2285 enableApps.addAll(wlApps); 2286 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2287 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2288 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2289 enableApps.removeAll(blApps); 2290 Log.i(TAG, "Applications installed for system user: " + enableApps); 2291 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2292 UserHandle.SYSTEM); 2293 final int allAppsSize = allAps.size(); 2294 synchronized (mPackages) { 2295 for (int i = 0; i < allAppsSize; i++) { 2296 String pName = allAps.get(i); 2297 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2298 // Should not happen, but we shouldn't be failing if it does 2299 if (pkgSetting == null) { 2300 continue; 2301 } 2302 boolean install = enableApps.contains(pName); 2303 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2304 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2305 + " for system user"); 2306 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2307 } 2308 } 2309 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2310 } 2311 } 2312 2313 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2314 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2315 Context.DISPLAY_SERVICE); 2316 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2317 } 2318 2319 /** 2320 * Requests that files preopted on a secondary system partition be copied to the data partition 2321 * if possible. Note that the actual copying of the files is accomplished by init for security 2322 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2323 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2324 */ 2325 private static void requestCopyPreoptedFiles() { 2326 final int WAIT_TIME_MS = 100; 2327 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2328 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2329 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2330 // We will wait for up to 100 seconds. 2331 final long timeStart = SystemClock.uptimeMillis(); 2332 final long timeEnd = timeStart + 100 * 1000; 2333 long timeNow = timeStart; 2334 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2335 try { 2336 Thread.sleep(WAIT_TIME_MS); 2337 } catch (InterruptedException e) { 2338 // Do nothing 2339 } 2340 timeNow = SystemClock.uptimeMillis(); 2341 if (timeNow > timeEnd) { 2342 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2343 Slog.wtf(TAG, "cppreopt did not finish!"); 2344 break; 2345 } 2346 } 2347 2348 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2349 } 2350 } 2351 2352 public PackageManagerService(Context context, Installer installer, 2353 boolean factoryTest, boolean onlyCore) { 2354 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2356 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2357 SystemClock.uptimeMillis()); 2358 2359 if (mSdkVersion <= 0) { 2360 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2361 } 2362 2363 mContext = context; 2364 2365 mFactoryTest = factoryTest; 2366 mOnlyCore = onlyCore; 2367 mMetrics = new DisplayMetrics(); 2368 mInstaller = installer; 2369 2370 // Create sub-components that provide services / data. Order here is important. 2371 synchronized (mInstallLock) { 2372 synchronized (mPackages) { 2373 // Expose private service for system components to use. 2374 LocalServices.addService( 2375 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2376 sUserManager = new UserManagerService(context, this, 2377 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2378 mPermissionManager = PermissionManagerService.create(context, 2379 new DefaultPermissionGrantedCallback() { 2380 @Override 2381 public void onDefaultRuntimePermissionsGranted(int userId) { 2382 synchronized(mPackages) { 2383 mSettings.onDefaultRuntimePermissionsGrantedLPr(userId); 2384 } 2385 } 2386 }, mPackages /*externalLock*/); 2387 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2388 mSettings = new Settings(mPermissionManager.getPermissionSettings(), mPackages); 2389 } 2390 } 2391 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2392 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2393 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2394 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2395 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2396 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2397 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2398 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2399 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2400 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2401 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2402 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2403 2404 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2405 if (separateProcesses != null && separateProcesses.length() > 0) { 2406 if ("*".equals(separateProcesses)) { 2407 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2408 mSeparateProcesses = null; 2409 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2410 } else { 2411 mDefParseFlags = 0; 2412 mSeparateProcesses = separateProcesses.split(","); 2413 Slog.w(TAG, "Running with debug.separate_processes: " 2414 + separateProcesses); 2415 } 2416 } else { 2417 mDefParseFlags = 0; 2418 mSeparateProcesses = null; 2419 } 2420 2421 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2422 "*dexopt*"); 2423 DexManager.Listener dexManagerListener = DexLogger.getListener(this, 2424 installer, mInstallLock); 2425 mDexManager = new DexManager(this, mPackageDexOptimizer, installer, mInstallLock, 2426 dexManagerListener); 2427 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2428 2429 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2430 FgThread.get().getLooper()); 2431 2432 getDefaultDisplayMetrics(context, mMetrics); 2433 2434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2435 SystemConfig systemConfig = SystemConfig.getInstance(); 2436 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2438 2439 mProtectedPackages = new ProtectedPackages(mContext); 2440 2441 synchronized (mInstallLock) { 2442 // writer 2443 synchronized (mPackages) { 2444 mHandlerThread = new ServiceThread(TAG, 2445 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2446 mHandlerThread.start(); 2447 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2448 mProcessLoggingHandler = new ProcessLoggingHandler(); 2449 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2450 mInstantAppRegistry = new InstantAppRegistry(this); 2451 2452 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2453 final int builtInLibCount = libConfig.size(); 2454 for (int i = 0; i < builtInLibCount; i++) { 2455 String name = libConfig.keyAt(i); 2456 String path = libConfig.valueAt(i); 2457 addSharedLibraryLPw(path, null, name, SharedLibraryInfo.VERSION_UNDEFINED, 2458 SharedLibraryInfo.TYPE_BUILTIN, PLATFORM_PACKAGE_NAME, 0); 2459 } 2460 2461 SELinuxMMAC.readInstallPolicy(); 2462 2463 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2464 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2466 2467 // Clean up orphaned packages for which the code path doesn't exist 2468 // and they are an update to a system app - caused by bug/32321269 2469 final int packageSettingCount = mSettings.mPackages.size(); 2470 for (int i = packageSettingCount - 1; i >= 0; i--) { 2471 PackageSetting ps = mSettings.mPackages.valueAt(i); 2472 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2473 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2474 mSettings.mPackages.removeAt(i); 2475 mSettings.enableSystemPackageLPw(ps.name); 2476 } 2477 } 2478 2479 if (mFirstBoot) { 2480 requestCopyPreoptedFiles(); 2481 } 2482 2483 String customResolverActivity = Resources.getSystem().getString( 2484 R.string.config_customResolverActivity); 2485 if (TextUtils.isEmpty(customResolverActivity)) { 2486 customResolverActivity = null; 2487 } else { 2488 mCustomResolverComponentName = ComponentName.unflattenFromString( 2489 customResolverActivity); 2490 } 2491 2492 long startTime = SystemClock.uptimeMillis(); 2493 2494 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2495 startTime); 2496 2497 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2498 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2499 2500 if (bootClassPath == null) { 2501 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2502 } 2503 2504 if (systemServerClassPath == null) { 2505 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2506 } 2507 2508 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2509 2510 final VersionInfo ver = mSettings.getInternalVersion(); 2511 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2512 if (mIsUpgrade) { 2513 logCriticalInfo(Log.INFO, 2514 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2515 } 2516 2517 // when upgrading from pre-M, promote system app permissions from install to runtime 2518 mPromoteSystemApps = 2519 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2520 2521 // When upgrading from pre-N, we need to handle package extraction like first boot, 2522 // as there is no profiling data available. 2523 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2524 2525 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2526 2527 // save off the names of pre-existing system packages prior to scanning; we don't 2528 // want to automatically grant runtime permissions for new system apps 2529 if (mPromoteSystemApps) { 2530 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2531 while (pkgSettingIter.hasNext()) { 2532 PackageSetting ps = pkgSettingIter.next(); 2533 if (isSystemApp(ps)) { 2534 mExistingSystemPackages.add(ps.name); 2535 } 2536 } 2537 } 2538 2539 mCacheDir = preparePackageParserCache(mIsUpgrade); 2540 2541 // Set flag to monitor and not change apk file paths when 2542 // scanning install directories. 2543 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2544 2545 if (mIsUpgrade || mFirstBoot) { 2546 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2547 } 2548 2549 // Collect vendor overlay packages. (Do this before scanning any apps.) 2550 // For security and version matching reason, only consider 2551 // overlay packages if they reside in the right directory. 2552 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2553 mDefParseFlags 2554 | PackageParser.PARSE_IS_SYSTEM_DIR, 2555 scanFlags 2556 | SCAN_AS_SYSTEM 2557 | SCAN_TRUSTED_OVERLAY, 2558 0); 2559 2560 mParallelPackageParserCallback.findStaticOverlayPackages(); 2561 2562 // Find base frameworks (resource packages without code). 2563 scanDirTracedLI(frameworkDir, 2564 mDefParseFlags 2565 | PackageParser.PARSE_IS_SYSTEM_DIR, 2566 scanFlags 2567 | SCAN_NO_DEX 2568 | SCAN_AS_SYSTEM 2569 | SCAN_AS_PRIVILEGED, 2570 0); 2571 2572 // Collected privileged system packages. 2573 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2574 scanDirTracedLI(privilegedAppDir, 2575 mDefParseFlags 2576 | PackageParser.PARSE_IS_SYSTEM_DIR, 2577 scanFlags 2578 | SCAN_AS_SYSTEM 2579 | SCAN_AS_PRIVILEGED, 2580 0); 2581 2582 // Collect ordinary system packages. 2583 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2584 scanDirTracedLI(systemAppDir, 2585 mDefParseFlags 2586 | PackageParser.PARSE_IS_SYSTEM_DIR, 2587 scanFlags 2588 | SCAN_AS_SYSTEM, 2589 0); 2590 2591 // Collected privileged vendor packages. 2592 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), 2593 "priv-app"); 2594 try { 2595 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2596 } catch (IOException e) { 2597 // failed to look up canonical path, continue with original one 2598 } 2599 scanDirTracedLI(privilegedVendorAppDir, 2600 mDefParseFlags 2601 | PackageParser.PARSE_IS_SYSTEM_DIR, 2602 scanFlags 2603 | SCAN_AS_SYSTEM 2604 | SCAN_AS_VENDOR 2605 | SCAN_AS_PRIVILEGED, 2606 0); 2607 2608 // Collect ordinary vendor packages. 2609 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2610 try { 2611 vendorAppDir = vendorAppDir.getCanonicalFile(); 2612 } catch (IOException e) { 2613 // failed to look up canonical path, continue with original one 2614 } 2615 scanDirTracedLI(vendorAppDir, 2616 mDefParseFlags 2617 | PackageParser.PARSE_IS_SYSTEM_DIR, 2618 scanFlags 2619 | SCAN_AS_SYSTEM 2620 | SCAN_AS_VENDOR, 2621 0); 2622 2623 // Collect all OEM packages. 2624 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2625 scanDirTracedLI(oemAppDir, 2626 mDefParseFlags 2627 | PackageParser.PARSE_IS_SYSTEM_DIR, 2628 scanFlags 2629 | SCAN_AS_SYSTEM 2630 | SCAN_AS_OEM, 2631 0); 2632 2633 // Prune any system packages that no longer exist. 2634 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2635 // Stub packages must either be replaced with full versions in the /data 2636 // partition or be disabled. 2637 final List<String> stubSystemApps = new ArrayList<>(); 2638 if (!mOnlyCore) { 2639 // do this first before mucking with mPackages for the "expecting better" case 2640 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2641 while (pkgIterator.hasNext()) { 2642 final PackageParser.Package pkg = pkgIterator.next(); 2643 if (pkg.isStub) { 2644 stubSystemApps.add(pkg.packageName); 2645 } 2646 } 2647 2648 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2649 while (psit.hasNext()) { 2650 PackageSetting ps = psit.next(); 2651 2652 /* 2653 * If this is not a system app, it can't be a 2654 * disable system app. 2655 */ 2656 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2657 continue; 2658 } 2659 2660 /* 2661 * If the package is scanned, it's not erased. 2662 */ 2663 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2664 if (scannedPkg != null) { 2665 /* 2666 * If the system app is both scanned and in the 2667 * disabled packages list, then it must have been 2668 * added via OTA. Remove it from the currently 2669 * scanned package so the previously user-installed 2670 * application can be scanned. 2671 */ 2672 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2673 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2674 + ps.name + "; removing system app. Last known codePath=" 2675 + ps.codePathString + ", installStatus=" + ps.installStatus 2676 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2677 + scannedPkg.getLongVersionCode()); 2678 removePackageLI(scannedPkg, true); 2679 mExpectingBetter.put(ps.name, ps.codePath); 2680 } 2681 2682 continue; 2683 } 2684 2685 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2686 psit.remove(); 2687 logCriticalInfo(Log.WARN, "System package " + ps.name 2688 + " no longer exists; it's data will be wiped"); 2689 // Actual deletion of code and data will be handled by later 2690 // reconciliation step 2691 } else { 2692 // we still have a disabled system package, but, it still might have 2693 // been removed. check the code path still exists and check there's 2694 // still a package. the latter can happen if an OTA keeps the same 2695 // code path, but, changes the package name. 2696 final PackageSetting disabledPs = 2697 mSettings.getDisabledSystemPkgLPr(ps.name); 2698 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2699 || disabledPs.pkg == null) { 2700if (REFACTOR_DEBUG) { 2701Slog.e("TODD", 2702 "Possibly deleted app: " + ps.dumpState_temp() 2703 + "; path: " + (disabledPs.codePath == null ? "<<NULL>>":disabledPs.codePath) 2704 + "; pkg: " + (disabledPs.pkg==null?"<<NULL>>":disabledPs.pkg.toString())); 2705} 2706 possiblyDeletedUpdatedSystemApps.add(ps.name); 2707 } 2708 } 2709 } 2710 } 2711 2712 //look for any incomplete package installations 2713 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2714 for (int i = 0; i < deletePkgsList.size(); i++) { 2715 // Actual deletion of code and data will be handled by later 2716 // reconciliation step 2717 final String packageName = deletePkgsList.get(i).name; 2718 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2719 synchronized (mPackages) { 2720 mSettings.removePackageLPw(packageName); 2721 } 2722 } 2723 2724 //delete tmp files 2725 deleteTempPackageFiles(); 2726 2727 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2728 2729 // Remove any shared userIDs that have no associated packages 2730 mSettings.pruneSharedUsersLPw(); 2731 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2732 final int systemPackagesCount = mPackages.size(); 2733 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2734 + " ms, packageCount: " + systemPackagesCount 2735 + " , timePerPackage: " 2736 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2737 + " , cached: " + cachedSystemApps); 2738 if (mIsUpgrade && systemPackagesCount > 0) { 2739 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2740 ((int) systemScanTime) / systemPackagesCount); 2741 } 2742 if (!mOnlyCore) { 2743 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2744 SystemClock.uptimeMillis()); 2745 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2746 2747 scanDirTracedLI(sDrmAppPrivateInstallDir, mDefParseFlags 2748 | PackageParser.PARSE_FORWARD_LOCK, 2749 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2750 2751 // Remove disable package settings for updated system apps that were 2752 // removed via an OTA. If the update is no longer present, remove the 2753 // app completely. Otherwise, revoke their system privileges. 2754 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2755 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2756 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2757if (REFACTOR_DEBUG) { 2758Slog.e("TODD", 2759 "remove update; name: " + deletedAppName + ", exists? " + (deletedPkg != null)); 2760} 2761 final String msg; 2762 if (deletedPkg == null) { 2763 // should have found an update, but, we didn't; remove everything 2764 msg = "Updated system package " + deletedAppName 2765 + " no longer exists; removing its data"; 2766 // Actual deletion of code and data will be handled by later 2767 // reconciliation step 2768 } else { 2769 // found an update; revoke system privileges 2770 msg = "Updated system package + " + deletedAppName 2771 + " no longer exists; revoking system privileges"; 2772 2773 // Don't do anything if a stub is removed from the system image. If 2774 // we were to remove the uncompressed version from the /data partition, 2775 // this is where it'd be done. 2776 2777 final PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2778 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2779 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2780 } 2781 logCriticalInfo(Log.WARN, msg); 2782 } 2783 2784 /* 2785 * Make sure all system apps that we expected to appear on 2786 * the userdata partition actually showed up. If they never 2787 * appeared, crawl back and revive the system version. 2788 */ 2789 for (int i = 0; i < mExpectingBetter.size(); i++) { 2790 final String packageName = mExpectingBetter.keyAt(i); 2791 if (!mPackages.containsKey(packageName)) { 2792 final File scanFile = mExpectingBetter.valueAt(i); 2793 2794 logCriticalInfo(Log.WARN, "Expected better " + packageName 2795 + " but never showed up; reverting to system"); 2796 2797 final @ParseFlags int reparseFlags; 2798 final @ScanFlags int rescanFlags; 2799 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2800 reparseFlags = 2801 mDefParseFlags | 2802 PackageParser.PARSE_IS_SYSTEM_DIR; 2803 rescanFlags = 2804 scanFlags 2805 | SCAN_AS_SYSTEM 2806 | SCAN_AS_PRIVILEGED; 2807 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2808 reparseFlags = 2809 mDefParseFlags | 2810 PackageParser.PARSE_IS_SYSTEM_DIR; 2811 rescanFlags = 2812 scanFlags 2813 | SCAN_AS_SYSTEM; 2814 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile)) { 2815 reparseFlags = 2816 mDefParseFlags | 2817 PackageParser.PARSE_IS_SYSTEM_DIR; 2818 rescanFlags = 2819 scanFlags 2820 | SCAN_AS_SYSTEM 2821 | SCAN_AS_VENDOR 2822 | SCAN_AS_PRIVILEGED; 2823 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2824 reparseFlags = 2825 mDefParseFlags | 2826 PackageParser.PARSE_IS_SYSTEM_DIR; 2827 rescanFlags = 2828 scanFlags 2829 | SCAN_AS_SYSTEM 2830 | SCAN_AS_VENDOR; 2831 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2832 reparseFlags = 2833 mDefParseFlags | 2834 PackageParser.PARSE_IS_SYSTEM_DIR; 2835 rescanFlags = 2836 scanFlags 2837 | SCAN_AS_SYSTEM 2838 | SCAN_AS_OEM; 2839 } else { 2840 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2841 continue; 2842 } 2843 2844 mSettings.enableSystemPackageLPw(packageName); 2845 2846 try { 2847 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2848 } catch (PackageManagerException e) { 2849 Slog.e(TAG, "Failed to parse original system package: " 2850 + e.getMessage()); 2851 } 2852 } 2853 } 2854 2855 // Uncompress and install any stubbed system applications. 2856 // This must be done last to ensure all stubs are replaced or disabled. 2857 decompressSystemApplications(stubSystemApps, scanFlags); 2858 2859 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 2860 - cachedSystemApps; 2861 2862 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 2863 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 2864 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 2865 + " ms, packageCount: " + dataPackagesCount 2866 + " , timePerPackage: " 2867 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 2868 + " , cached: " + cachedNonSystemApps); 2869 if (mIsUpgrade && dataPackagesCount > 0) { 2870 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 2871 ((int) dataScanTime) / dataPackagesCount); 2872 } 2873 } 2874 mExpectingBetter.clear(); 2875 2876 // Resolve the storage manager. 2877 mStorageManagerPackage = getStorageManagerPackageName(); 2878 2879 // Resolve protected action filters. Only the setup wizard is allowed to 2880 // have a high priority filter for these actions. 2881 mSetupWizardPackage = getSetupWizardPackageName(); 2882 if (mProtectedFilters.size() > 0) { 2883 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2884 Slog.i(TAG, "No setup wizard;" 2885 + " All protected intents capped to priority 0"); 2886 } 2887 for (ActivityIntentInfo filter : mProtectedFilters) { 2888 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2889 if (DEBUG_FILTERS) { 2890 Slog.i(TAG, "Found setup wizard;" 2891 + " allow priority " + filter.getPriority() + ";" 2892 + " package: " + filter.activity.info.packageName 2893 + " activity: " + filter.activity.className 2894 + " priority: " + filter.getPriority()); 2895 } 2896 // skip setup wizard; allow it to keep the high priority filter 2897 continue; 2898 } 2899 if (DEBUG_FILTERS) { 2900 Slog.i(TAG, "Protected action; cap priority to 0;" 2901 + " package: " + filter.activity.info.packageName 2902 + " activity: " + filter.activity.className 2903 + " origPrio: " + filter.getPriority()); 2904 } 2905 filter.setPriority(0); 2906 } 2907 } 2908 mDeferProtectedFilters = false; 2909 mProtectedFilters.clear(); 2910 2911 // Now that we know all of the shared libraries, update all clients to have 2912 // the correct library paths. 2913 updateAllSharedLibrariesLPw(null); 2914 2915 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2916 // NOTE: We ignore potential failures here during a system scan (like 2917 // the rest of the commands above) because there's precious little we 2918 // can do about it. A settings error is reported, though. 2919 final List<String> changedAbiCodePath = 2920 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 2921 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2922 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2923 final String codePathString = changedAbiCodePath.get(i); 2924 try { 2925 mInstaller.rmdex(codePathString, 2926 getDexCodeInstructionSet(getPreferredInstructionSet())); 2927 } catch (InstallerException ignored) { 2928 } 2929 } 2930 } 2931 } 2932 2933 // Now that we know all the packages we are keeping, 2934 // read and update their last usage times. 2935 mPackageUsage.read(mPackages); 2936 mCompilerStats.read(); 2937 2938 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2939 SystemClock.uptimeMillis()); 2940 Slog.i(TAG, "Time to scan packages: " 2941 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2942 + " seconds"); 2943 2944 // If the platform SDK has changed since the last time we booted, 2945 // we need to re-grant app permission to catch any new ones that 2946 // appear. This is really a hack, and means that apps can in some 2947 // cases get permissions that the user didn't initially explicitly 2948 // allow... it would be nice to have some better way to handle 2949 // this situation. 2950 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 2951 if (sdkUpdated) { 2952 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2953 + mSdkVersion + "; regranting permissions for internal storage"); 2954 } 2955 mPermissionManager.updateAllPermissions( 2956 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 2957 mPermissionCallback); 2958 ver.sdkVersion = mSdkVersion; 2959 2960 // If this is the first boot or an update from pre-M, and it is a normal 2961 // boot, then we need to initialize the default preferred apps across 2962 // all defined users. 2963 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2964 for (UserInfo user : sUserManager.getUsers(true)) { 2965 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2966 applyFactoryDefaultBrowserLPw(user.id); 2967 primeDomainVerificationsLPw(user.id); 2968 } 2969 } 2970 2971 // Prepare storage for system user really early during boot, 2972 // since core system apps like SettingsProvider and SystemUI 2973 // can't wait for user to start 2974 final int storageFlags; 2975 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2976 storageFlags = StorageManager.FLAG_STORAGE_DE; 2977 } else { 2978 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2979 } 2980 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 2981 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 2982 true /* onlyCoreApps */); 2983 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 2984 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 2985 Trace.TRACE_TAG_PACKAGE_MANAGER); 2986 traceLog.traceBegin("AppDataFixup"); 2987 try { 2988 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 2989 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 2990 } catch (InstallerException e) { 2991 Slog.w(TAG, "Trouble fixing GIDs", e); 2992 } 2993 traceLog.traceEnd(); 2994 2995 traceLog.traceBegin("AppDataPrepare"); 2996 if (deferPackages == null || deferPackages.isEmpty()) { 2997 return; 2998 } 2999 int count = 0; 3000 for (String pkgName : deferPackages) { 3001 PackageParser.Package pkg = null; 3002 synchronized (mPackages) { 3003 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3004 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3005 pkg = ps.pkg; 3006 } 3007 } 3008 if (pkg != null) { 3009 synchronized (mInstallLock) { 3010 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3011 true /* maybeMigrateAppData */); 3012 } 3013 count++; 3014 } 3015 } 3016 traceLog.traceEnd(); 3017 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3018 }, "prepareAppData"); 3019 3020 // If this is first boot after an OTA, and a normal boot, then 3021 // we need to clear code cache directories. 3022 // Note that we do *not* clear the application profiles. These remain valid 3023 // across OTAs and are used to drive profile verification (post OTA) and 3024 // profile compilation (without waiting to collect a fresh set of profiles). 3025 if (mIsUpgrade && !onlyCore) { 3026 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3027 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3028 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3029 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3030 // No apps are running this early, so no need to freeze 3031 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3032 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 3033 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3034 } 3035 } 3036 ver.fingerprint = Build.FINGERPRINT; 3037 } 3038 3039 checkDefaultBrowser(); 3040 3041 // clear only after permissions and other defaults have been updated 3042 mExistingSystemPackages.clear(); 3043 mPromoteSystemApps = false; 3044 3045 // All the changes are done during package scanning. 3046 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3047 3048 // can downgrade to reader 3049 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3050 mSettings.writeLPr(); 3051 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3052 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3053 SystemClock.uptimeMillis()); 3054 3055 if (!mOnlyCore) { 3056 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3057 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3058 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3059 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3060 if (mIntentFilterVerifierComponent != null) { 3061 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3062 mIntentFilterVerifierComponent); 3063 } else { 3064 mIntentFilterVerifier = null; 3065 } 3066 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3067 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3068 SharedLibraryInfo.VERSION_UNDEFINED); 3069 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3070 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3071 SharedLibraryInfo.VERSION_UNDEFINED); 3072 } else { 3073 mRequiredVerifierPackage = null; 3074 mRequiredInstallerPackage = null; 3075 mRequiredUninstallerPackage = null; 3076 mIntentFilterVerifierComponent = null; 3077 mIntentFilterVerifier = null; 3078 mServicesSystemSharedLibraryPackageName = null; 3079 mSharedSystemSharedLibraryPackageName = null; 3080 } 3081 3082 mInstallerService = new PackageInstallerService(context, this); 3083 mArtManagerService = new ArtManagerService(this, mInstaller, mInstallLock); 3084 final Pair<ComponentName, String> instantAppResolverComponent = 3085 getInstantAppResolverLPr(); 3086 if (instantAppResolverComponent != null) { 3087 if (DEBUG_EPHEMERAL) { 3088 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3089 } 3090 mInstantAppResolverConnection = new EphemeralResolverConnection( 3091 mContext, instantAppResolverComponent.first, 3092 instantAppResolverComponent.second); 3093 mInstantAppResolverSettingsComponent = 3094 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3095 } else { 3096 mInstantAppResolverConnection = null; 3097 mInstantAppResolverSettingsComponent = null; 3098 } 3099 updateInstantAppInstallerLocked(null); 3100 3101 // Read and update the usage of dex files. 3102 // Do this at the end of PM init so that all the packages have their 3103 // data directory reconciled. 3104 // At this point we know the code paths of the packages, so we can validate 3105 // the disk file and build the internal cache. 3106 // The usage file is expected to be small so loading and verifying it 3107 // should take a fairly small time compare to the other activities (e.g. package 3108 // scanning). 3109 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3110 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 3111 for (int userId : currentUserIds) { 3112 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3113 } 3114 mDexManager.load(userPackages); 3115 if (mIsUpgrade) { 3116 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3117 (int) (SystemClock.uptimeMillis() - startTime)); 3118 } 3119 } // synchronized (mPackages) 3120 } // synchronized (mInstallLock) 3121 3122 // Now after opening every single application zip, make sure they 3123 // are all flushed. Not really needed, but keeps things nice and 3124 // tidy. 3125 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3126 Runtime.getRuntime().gc(); 3127 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3128 3129 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 3130 FallbackCategoryProvider.loadFallbacks(); 3131 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3132 3133 // The initial scanning above does many calls into installd while 3134 // holding the mPackages lock, but we're mostly interested in yelling 3135 // once we have a booted system. 3136 mInstaller.setWarnIfHeld(mPackages); 3137 3138 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3139 } 3140 3141 /** 3142 * Uncompress and install stub applications. 3143 * <p>In order to save space on the system partition, some applications are shipped in a 3144 * compressed form. In addition the compressed bits for the full application, the 3145 * system image contains a tiny stub comprised of only the Android manifest. 3146 * <p>During the first boot, attempt to uncompress and install the full application. If 3147 * the application can't be installed for any reason, disable the stub and prevent 3148 * uncompressing the full application during future boots. 3149 * <p>In order to forcefully attempt an installation of a full application, go to app 3150 * settings and enable the application. 3151 */ 3152 private void decompressSystemApplications(@NonNull List<String> stubSystemApps, int scanFlags) { 3153 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3154 final String pkgName = stubSystemApps.get(i); 3155 // skip if the system package is already disabled 3156 if (mSettings.isDisabledSystemPackageLPr(pkgName)) { 3157 stubSystemApps.remove(i); 3158 continue; 3159 } 3160 // skip if the package isn't installed (?!); this should never happen 3161 final PackageParser.Package pkg = mPackages.get(pkgName); 3162 if (pkg == null) { 3163 stubSystemApps.remove(i); 3164 continue; 3165 } 3166 // skip if the package has been disabled by the user 3167 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3168 if (ps != null) { 3169 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3170 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3171 stubSystemApps.remove(i); 3172 continue; 3173 } 3174 } 3175 3176 if (DEBUG_COMPRESSION) { 3177 Slog.i(TAG, "Uncompressing system stub; pkg: " + pkgName); 3178 } 3179 3180 // uncompress the binary to its eventual destination on /data 3181 final File scanFile = decompressPackage(pkg); 3182 if (scanFile == null) { 3183 continue; 3184 } 3185 3186 // install the package to replace the stub on /system 3187 try { 3188 mSettings.disableSystemPackageLPw(pkgName, true /*replaced*/); 3189 removePackageLI(pkg, true /*chatty*/); 3190 scanPackageTracedLI(scanFile, 0 /*reparseFlags*/, scanFlags, 0, null); 3191 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3192 UserHandle.USER_SYSTEM, "android"); 3193 stubSystemApps.remove(i); 3194 continue; 3195 } catch (PackageManagerException e) { 3196 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3197 } 3198 3199 // any failed attempt to install the package will be cleaned up later 3200 } 3201 3202 // disable any stub still left; these failed to install the full application 3203 for (int i = stubSystemApps.size() - 1; i >= 0; --i) { 3204 final String pkgName = stubSystemApps.get(i); 3205 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3206 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3207 UserHandle.USER_SYSTEM, "android"); 3208 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3209 } 3210 } 3211 3212 /** 3213 * Decompresses the given package on the system image onto 3214 * the /data partition. 3215 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3216 */ 3217 private File decompressPackage(PackageParser.Package pkg) { 3218 final File[] compressedFiles = getCompressedFiles(pkg.codePath); 3219 if (compressedFiles == null || compressedFiles.length == 0) { 3220 if (DEBUG_COMPRESSION) { 3221 Slog.i(TAG, "No files to decompress: " + pkg.baseCodePath); 3222 } 3223 return null; 3224 } 3225 final File dstCodePath = 3226 getNextCodePath(Environment.getDataAppDirectory(null), pkg.packageName); 3227 int ret = PackageManager.INSTALL_SUCCEEDED; 3228 try { 3229 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3230 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3231 for (File srcFile : compressedFiles) { 3232 final String srcFileName = srcFile.getName(); 3233 final String dstFileName = srcFileName.substring( 3234 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3235 final File dstFile = new File(dstCodePath, dstFileName); 3236 ret = decompressFile(srcFile, dstFile); 3237 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3238 logCriticalInfo(Log.ERROR, "Failed to decompress" 3239 + "; pkg: " + pkg.packageName 3240 + ", file: " + dstFileName); 3241 break; 3242 } 3243 } 3244 } catch (ErrnoException e) { 3245 logCriticalInfo(Log.ERROR, "Failed to decompress" 3246 + "; pkg: " + pkg.packageName 3247 + ", err: " + e.errno); 3248 } 3249 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3250 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3251 NativeLibraryHelper.Handle handle = null; 3252 try { 3253 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3254 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3255 null /*abiOverride*/); 3256 } catch (IOException e) { 3257 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3258 + "; pkg: " + pkg.packageName); 3259 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3260 } finally { 3261 IoUtils.closeQuietly(handle); 3262 } 3263 } 3264 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3265 if (dstCodePath == null || !dstCodePath.exists()) { 3266 return null; 3267 } 3268 removeCodePathLI(dstCodePath); 3269 return null; 3270 } 3271 3272 return dstCodePath; 3273 } 3274 3275 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3276 // we're only interested in updating the installer appliction when 1) it's not 3277 // already set or 2) the modified package is the installer 3278 if (mInstantAppInstallerActivity != null 3279 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3280 .equals(modifiedPackage)) { 3281 return; 3282 } 3283 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3284 } 3285 3286 private static File preparePackageParserCache(boolean isUpgrade) { 3287 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3288 return null; 3289 } 3290 3291 // Disable package parsing on eng builds to allow for faster incremental development. 3292 if (Build.IS_ENG) { 3293 return null; 3294 } 3295 3296 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3297 Slog.i(TAG, "Disabling package parser cache due to system property."); 3298 return null; 3299 } 3300 3301 // The base directory for the package parser cache lives under /data/system/. 3302 final File cacheBaseDir = FileUtils.createDir(Environment.getDataSystemDirectory(), 3303 "package_cache"); 3304 if (cacheBaseDir == null) { 3305 return null; 3306 } 3307 3308 // If this is a system upgrade scenario, delete the contents of the package cache dir. 3309 // This also serves to "GC" unused entries when the package cache version changes (which 3310 // can only happen during upgrades). 3311 if (isUpgrade) { 3312 FileUtils.deleteContents(cacheBaseDir); 3313 } 3314 3315 3316 // Return the versioned package cache directory. This is something like 3317 // "/data/system/package_cache/1" 3318 File cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3319 3320 // The following is a workaround to aid development on non-numbered userdebug 3321 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3322 // the system partition is newer. 3323 // 3324 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3325 // that starts with "eng." to signify that this is an engineering build and not 3326 // destined for release. 3327 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3328 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3329 3330 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3331 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3332 // in general and should not be used for production changes. In this specific case, 3333 // we know that they will work. 3334 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3335 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3336 FileUtils.deleteContents(cacheBaseDir); 3337 cacheDir = FileUtils.createDir(cacheBaseDir, PACKAGE_PARSER_CACHE_VERSION); 3338 } 3339 } 3340 3341 return cacheDir; 3342 } 3343 3344 @Override 3345 public boolean isFirstBoot() { 3346 // allow instant applications 3347 return mFirstBoot; 3348 } 3349 3350 @Override 3351 public boolean isOnlyCoreApps() { 3352 // allow instant applications 3353 return mOnlyCore; 3354 } 3355 3356 @Override 3357 public boolean isUpgrade() { 3358 // allow instant applications 3359 // The system property allows testing ota flow when upgraded to the same image. 3360 return mIsUpgrade || SystemProperties.getBoolean( 3361 "persist.pm.mock-upgrade", false /* default */); 3362 } 3363 3364 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3365 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3366 3367 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3368 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3369 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3370 if (matches.size() == 1) { 3371 return matches.get(0).getComponentInfo().packageName; 3372 } else if (matches.size() == 0) { 3373 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3374 return null; 3375 } 3376 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3377 } 3378 3379 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3380 synchronized (mPackages) { 3381 SharedLibraryEntry libraryEntry = getSharedLibraryEntryLPr(name, version); 3382 if (libraryEntry == null) { 3383 throw new IllegalStateException("Missing required shared library:" + name); 3384 } 3385 return libraryEntry.apk; 3386 } 3387 } 3388 3389 private @NonNull String getRequiredInstallerLPr() { 3390 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3391 intent.addCategory(Intent.CATEGORY_DEFAULT); 3392 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3393 3394 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3395 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3396 UserHandle.USER_SYSTEM); 3397 if (matches.size() == 1) { 3398 ResolveInfo resolveInfo = matches.get(0); 3399 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3400 throw new RuntimeException("The installer must be a privileged app"); 3401 } 3402 return matches.get(0).getComponentInfo().packageName; 3403 } else { 3404 throw new RuntimeException("There must be exactly one installer; found " + matches); 3405 } 3406 } 3407 3408 private @NonNull String getRequiredUninstallerLPr() { 3409 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3410 intent.addCategory(Intent.CATEGORY_DEFAULT); 3411 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3412 3413 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3414 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3415 UserHandle.USER_SYSTEM); 3416 if (resolveInfo == null || 3417 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3418 throw new RuntimeException("There must be exactly one uninstaller; found " 3419 + resolveInfo); 3420 } 3421 return resolveInfo.getComponentInfo().packageName; 3422 } 3423 3424 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3425 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_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 ResolveInfo best = null; 3431 final int N = matches.size(); 3432 for (int i = 0; i < N; i++) { 3433 final ResolveInfo cur = matches.get(i); 3434 final String packageName = cur.getComponentInfo().packageName; 3435 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3436 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3437 continue; 3438 } 3439 3440 if (best == null || cur.priority > best.priority) { 3441 best = cur; 3442 } 3443 } 3444 3445 if (best != null) { 3446 return best.getComponentInfo().getComponentName(); 3447 } 3448 Slog.w(TAG, "Intent filter verifier not found"); 3449 return null; 3450 } 3451 3452 @Override 3453 public @Nullable ComponentName getInstantAppResolverComponent() { 3454 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3455 return null; 3456 } 3457 synchronized (mPackages) { 3458 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3459 if (instantAppResolver == null) { 3460 return null; 3461 } 3462 return instantAppResolver.first; 3463 } 3464 } 3465 3466 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3467 final String[] packageArray = 3468 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3469 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3470 if (DEBUG_EPHEMERAL) { 3471 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3472 } 3473 return null; 3474 } 3475 3476 final int callingUid = Binder.getCallingUid(); 3477 final int resolveFlags = 3478 MATCH_DIRECT_BOOT_AWARE 3479 | MATCH_DIRECT_BOOT_UNAWARE 3480 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3481 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3482 final Intent resolverIntent = new Intent(actionName); 3483 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3484 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3485 // temporarily look for the old action 3486 if (resolvers.size() == 0) { 3487 if (DEBUG_EPHEMERAL) { 3488 Slog.d(TAG, "Ephemeral resolver not found with new action; try old one"); 3489 } 3490 actionName = Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE; 3491 resolverIntent.setAction(actionName); 3492 resolvers = queryIntentServicesInternal(resolverIntent, null, 3493 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3494 } 3495 final int N = resolvers.size(); 3496 if (N == 0) { 3497 if (DEBUG_EPHEMERAL) { 3498 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3499 } 3500 return null; 3501 } 3502 3503 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3504 for (int i = 0; i < N; i++) { 3505 final ResolveInfo info = resolvers.get(i); 3506 3507 if (info.serviceInfo == null) { 3508 continue; 3509 } 3510 3511 final String packageName = info.serviceInfo.packageName; 3512 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3513 if (DEBUG_EPHEMERAL) { 3514 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3515 + " pkg: " + packageName + ", info:" + info); 3516 } 3517 continue; 3518 } 3519 3520 if (DEBUG_EPHEMERAL) { 3521 Slog.v(TAG, "Ephemeral resolver found;" 3522 + " pkg: " + packageName + ", info:" + info); 3523 } 3524 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3525 } 3526 if (DEBUG_EPHEMERAL) { 3527 Slog.v(TAG, "Ephemeral resolver NOT found"); 3528 } 3529 return null; 3530 } 3531 3532 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3533 final Intent intent = new Intent(Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE); 3534 intent.addCategory(Intent.CATEGORY_DEFAULT); 3535 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3536 3537 final int resolveFlags = 3538 MATCH_DIRECT_BOOT_AWARE 3539 | MATCH_DIRECT_BOOT_UNAWARE 3540 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3541 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3542 resolveFlags, UserHandle.USER_SYSTEM); 3543 // temporarily look for the old action 3544 if (matches.isEmpty()) { 3545 if (DEBUG_EPHEMERAL) { 3546 Slog.d(TAG, "Ephemeral installer not found with new action; try old one"); 3547 } 3548 intent.setAction(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3549 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3550 resolveFlags, UserHandle.USER_SYSTEM); 3551 } 3552 Iterator<ResolveInfo> iter = matches.iterator(); 3553 while (iter.hasNext()) { 3554 final ResolveInfo rInfo = iter.next(); 3555 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3556 if (ps != null) { 3557 final PermissionsState permissionsState = ps.getPermissionsState(); 3558 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0)) { 3559 continue; 3560 } 3561 } 3562 iter.remove(); 3563 } 3564 if (matches.size() == 0) { 3565 return null; 3566 } else if (matches.size() == 1) { 3567 return (ActivityInfo) matches.get(0).getComponentInfo(); 3568 } else { 3569 throw new RuntimeException( 3570 "There must be at most one ephemeral installer; found " + matches); 3571 } 3572 } 3573 3574 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3575 @NonNull ComponentName resolver) { 3576 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3577 .addCategory(Intent.CATEGORY_DEFAULT) 3578 .setPackage(resolver.getPackageName()); 3579 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3580 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3581 UserHandle.USER_SYSTEM); 3582 // temporarily look for the old action 3583 if (matches.isEmpty()) { 3584 if (DEBUG_EPHEMERAL) { 3585 Slog.d(TAG, "Ephemeral resolver settings not found with new action; try old one"); 3586 } 3587 intent.setAction(Intent.ACTION_EPHEMERAL_RESOLVER_SETTINGS); 3588 matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3589 UserHandle.USER_SYSTEM); 3590 } 3591 if (matches.isEmpty()) { 3592 return null; 3593 } 3594 return matches.get(0).getComponentInfo().getComponentName(); 3595 } 3596 3597 private void primeDomainVerificationsLPw(int userId) { 3598 if (DEBUG_DOMAIN_VERIFICATION) { 3599 Slog.d(TAG, "Priming domain verifications in user " + userId); 3600 } 3601 3602 SystemConfig systemConfig = SystemConfig.getInstance(); 3603 ArraySet<String> packages = systemConfig.getLinkedApps(); 3604 3605 for (String packageName : packages) { 3606 PackageParser.Package pkg = mPackages.get(packageName); 3607 if (pkg != null) { 3608 if (!pkg.isSystem()) { 3609 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3610 continue; 3611 } 3612 3613 ArraySet<String> domains = null; 3614 for (PackageParser.Activity a : pkg.activities) { 3615 for (ActivityIntentInfo filter : a.intents) { 3616 if (hasValidDomains(filter)) { 3617 if (domains == null) { 3618 domains = new ArraySet<String>(); 3619 } 3620 domains.addAll(filter.getHostsList()); 3621 } 3622 } 3623 } 3624 3625 if (domains != null && domains.size() > 0) { 3626 if (DEBUG_DOMAIN_VERIFICATION) { 3627 Slog.v(TAG, " + " + packageName); 3628 } 3629 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3630 // state w.r.t. the formal app-linkage "no verification attempted" state; 3631 // and then 'always' in the per-user state actually used for intent resolution. 3632 final IntentFilterVerificationInfo ivi; 3633 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3634 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3635 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3636 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3637 } else { 3638 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3639 + "' does not handle web links"); 3640 } 3641 } else { 3642 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3643 } 3644 } 3645 3646 scheduleWritePackageRestrictionsLocked(userId); 3647 scheduleWriteSettingsLocked(); 3648 } 3649 3650 private void applyFactoryDefaultBrowserLPw(int userId) { 3651 // The default browser app's package name is stored in a string resource, 3652 // with a product-specific overlay used for vendor customization. 3653 String browserPkg = mContext.getResources().getString( 3654 com.android.internal.R.string.default_browser); 3655 if (!TextUtils.isEmpty(browserPkg)) { 3656 // non-empty string => required to be a known package 3657 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3658 if (ps == null) { 3659 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3660 browserPkg = null; 3661 } else { 3662 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3663 } 3664 } 3665 3666 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3667 // default. If there's more than one, just leave everything alone. 3668 if (browserPkg == null) { 3669 calculateDefaultBrowserLPw(userId); 3670 } 3671 } 3672 3673 private void calculateDefaultBrowserLPw(int userId) { 3674 List<String> allBrowsers = resolveAllBrowserApps(userId); 3675 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3676 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3677 } 3678 3679 private List<String> resolveAllBrowserApps(int userId) { 3680 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3681 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3682 PackageManager.MATCH_ALL, userId); 3683 3684 final int count = list.size(); 3685 List<String> result = new ArrayList<String>(count); 3686 for (int i=0; i<count; i++) { 3687 ResolveInfo info = list.get(i); 3688 if (info.activityInfo == null 3689 || !info.handleAllWebDataURI 3690 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3691 || result.contains(info.activityInfo.packageName)) { 3692 continue; 3693 } 3694 result.add(info.activityInfo.packageName); 3695 } 3696 3697 return result; 3698 } 3699 3700 private boolean packageIsBrowser(String packageName, int userId) { 3701 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3702 PackageManager.MATCH_ALL, userId); 3703 final int N = list.size(); 3704 for (int i = 0; i < N; i++) { 3705 ResolveInfo info = list.get(i); 3706 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3707 return true; 3708 } 3709 } 3710 return false; 3711 } 3712 3713 private void checkDefaultBrowser() { 3714 final int myUserId = UserHandle.myUserId(); 3715 final String packageName = getDefaultBrowserPackageName(myUserId); 3716 if (packageName != null) { 3717 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3718 if (info == null) { 3719 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3720 synchronized (mPackages) { 3721 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3722 } 3723 } 3724 } 3725 } 3726 3727 @Override 3728 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3729 throws RemoteException { 3730 try { 3731 return super.onTransact(code, data, reply, flags); 3732 } catch (RuntimeException e) { 3733 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3734 Slog.wtf(TAG, "Package Manager Crash", e); 3735 } 3736 throw e; 3737 } 3738 } 3739 3740 static int[] appendInts(int[] cur, int[] add) { 3741 if (add == null) return cur; 3742 if (cur == null) return add; 3743 final int N = add.length; 3744 for (int i=0; i<N; i++) { 3745 cur = appendInt(cur, add[i]); 3746 } 3747 return cur; 3748 } 3749 3750 /** 3751 * Returns whether or not a full application can see an instant application. 3752 * <p> 3753 * Currently, there are three cases in which this can occur: 3754 * <ol> 3755 * <li>The calling application is a "special" process. Special processes 3756 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3757 * <li>The calling application has the permission 3758 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3759 * <li>The calling application is the default launcher on the 3760 * system partition.</li> 3761 * </ol> 3762 */ 3763 private boolean canViewInstantApps(int callingUid, int userId) { 3764 if (callingUid < Process.FIRST_APPLICATION_UID) { 3765 return true; 3766 } 3767 if (mContext.checkCallingOrSelfPermission( 3768 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3769 return true; 3770 } 3771 if (mContext.checkCallingOrSelfPermission( 3772 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3773 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3774 if (homeComponent != null 3775 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3776 return true; 3777 } 3778 } 3779 return false; 3780 } 3781 3782 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3783 if (!sUserManager.exists(userId)) return null; 3784 if (ps == null) { 3785 return null; 3786 } 3787 PackageParser.Package p = ps.pkg; 3788 if (p == null) { 3789 return null; 3790 } 3791 final int callingUid = Binder.getCallingUid(); 3792 // Filter out ephemeral app metadata: 3793 // * The system/shell/root can see metadata for any app 3794 // * An installed app can see metadata for 1) other installed apps 3795 // and 2) ephemeral apps that have explicitly interacted with it 3796 // * Ephemeral apps can only see their own data and exposed installed apps 3797 // * Holding a signature permission allows seeing instant apps 3798 if (filterAppAccessLPr(ps, callingUid, userId)) { 3799 return null; 3800 } 3801 3802 final PermissionsState permissionsState = ps.getPermissionsState(); 3803 3804 // Compute GIDs only if requested 3805 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 3806 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 3807 // Compute granted permissions only if package has requested permissions 3808 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 3809 ? Collections.<String>emptySet() : permissionsState.getPermissions(userId); 3810 final PackageUserState state = ps.readUserState(userId); 3811 3812 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 3813 && ps.isSystem()) { 3814 flags |= MATCH_ANY_USER; 3815 } 3816 3817 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 3818 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3819 3820 if (packageInfo == null) { 3821 return null; 3822 } 3823 3824 packageInfo.packageName = packageInfo.applicationInfo.packageName = 3825 resolveExternalPackageNameLPr(p); 3826 3827 return packageInfo; 3828 } 3829 3830 @Override 3831 public void checkPackageStartable(String packageName, int userId) { 3832 final int callingUid = Binder.getCallingUid(); 3833 if (getInstantAppPackageName(callingUid) != null) { 3834 throw new SecurityException("Instant applications don't have access to this method"); 3835 } 3836 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3837 synchronized (mPackages) { 3838 final PackageSetting ps = mSettings.mPackages.get(packageName); 3839 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 3840 throw new SecurityException("Package " + packageName + " was not found!"); 3841 } 3842 3843 if (!ps.getInstalled(userId)) { 3844 throw new SecurityException( 3845 "Package " + packageName + " was not installed for user " + userId + "!"); 3846 } 3847 3848 if (mSafeMode && !ps.isSystem()) { 3849 throw new SecurityException("Package " + packageName + " not a system app!"); 3850 } 3851 3852 if (mFrozenPackages.contains(packageName)) { 3853 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3854 } 3855 3856 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 3857 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3858 } 3859 } 3860 } 3861 3862 @Override 3863 public boolean isPackageAvailable(String packageName, int userId) { 3864 if (!sUserManager.exists(userId)) return false; 3865 final int callingUid = Binder.getCallingUid(); 3866 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 3867 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 3868 synchronized (mPackages) { 3869 PackageParser.Package p = mPackages.get(packageName); 3870 if (p != null) { 3871 final PackageSetting ps = (PackageSetting) p.mExtras; 3872 if (filterAppAccessLPr(ps, callingUid, userId)) { 3873 return false; 3874 } 3875 if (ps != null) { 3876 final PackageUserState state = ps.readUserState(userId); 3877 if (state != null) { 3878 return PackageParser.isAvailable(state); 3879 } 3880 } 3881 } 3882 } 3883 return false; 3884 } 3885 3886 @Override 3887 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3888 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 3889 flags, Binder.getCallingUid(), userId); 3890 } 3891 3892 @Override 3893 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 3894 int flags, int userId) { 3895 return getPackageInfoInternal(versionedPackage.getPackageName(), 3896 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 3897 } 3898 3899 /** 3900 * Important: The provided filterCallingUid is used exclusively to filter out packages 3901 * that can be seen based on user state. It's typically the original caller uid prior 3902 * to clearing. Because it can only be provided by trusted code, it's value can be 3903 * trusted and will be used as-is; unlike userId which will be validated by this method. 3904 */ 3905 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 3906 int flags, int filterCallingUid, int userId) { 3907 if (!sUserManager.exists(userId)) return null; 3908 flags = updateFlagsForPackage(flags, userId, packageName); 3909 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 3910 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3911 3912 // reader 3913 synchronized (mPackages) { 3914 // Normalize package name to handle renamed packages and static libs 3915 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 3916 3917 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3918 if (matchFactoryOnly) { 3919 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3920 if (ps != null) { 3921 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3922 return null; 3923 } 3924 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3925 return null; 3926 } 3927 return generatePackageInfo(ps, flags, userId); 3928 } 3929 } 3930 3931 PackageParser.Package p = mPackages.get(packageName); 3932 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3933 return null; 3934 } 3935 if (DEBUG_PACKAGE_INFO) 3936 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3937 if (p != null) { 3938 final PackageSetting ps = (PackageSetting) p.mExtras; 3939 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3940 return null; 3941 } 3942 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 3943 return null; 3944 } 3945 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3946 } 3947 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 3948 final PackageSetting ps = mSettings.mPackages.get(packageName); 3949 if (ps == null) return null; 3950 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 3951 return null; 3952 } 3953 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 3954 return null; 3955 } 3956 return generatePackageInfo(ps, flags, userId); 3957 } 3958 } 3959 return null; 3960 } 3961 3962 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 3963 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 3964 return true; 3965 } 3966 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 3967 return true; 3968 } 3969 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 3970 return true; 3971 } 3972 return false; 3973 } 3974 3975 private boolean isComponentVisibleToInstantApp( 3976 @Nullable ComponentName component, @ComponentType int type) { 3977 if (type == TYPE_ACTIVITY) { 3978 final PackageParser.Activity activity = mActivities.mActivities.get(component); 3979 return activity != null 3980 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3981 : false; 3982 } else if (type == TYPE_RECEIVER) { 3983 final PackageParser.Activity activity = mReceivers.mActivities.get(component); 3984 return activity != null 3985 ? (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3986 : false; 3987 } else if (type == TYPE_SERVICE) { 3988 final PackageParser.Service service = mServices.mServices.get(component); 3989 return service != null 3990 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3991 : false; 3992 } else if (type == TYPE_PROVIDER) { 3993 final PackageParser.Provider provider = mProviders.mProviders.get(component); 3994 return provider != null 3995 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 3996 : false; 3997 } else if (type == TYPE_UNKNOWN) { 3998 return isComponentVisibleToInstantApp(component); 3999 } 4000 return false; 4001 } 4002 4003 /** 4004 * Returns whether or not access to the application should be filtered. 4005 * <p> 4006 * Access may be limited based upon whether the calling or target applications 4007 * are instant applications. 4008 * 4009 * @see #canAccessInstantApps(int) 4010 */ 4011 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4012 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4013 // if we're in an isolated process, get the real calling UID 4014 if (Process.isIsolated(callingUid)) { 4015 callingUid = mIsolatedOwners.get(callingUid); 4016 } 4017 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4018 final boolean callerIsInstantApp = instantAppPkgName != null; 4019 if (ps == null) { 4020 if (callerIsInstantApp) { 4021 // pretend the application exists, but, needs to be filtered 4022 return true; 4023 } 4024 return false; 4025 } 4026 // if the target and caller are the same application, don't filter 4027 if (isCallerSameApp(ps.name, callingUid)) { 4028 return false; 4029 } 4030 if (callerIsInstantApp) { 4031 // request for a specific component; if it hasn't been explicitly exposed, filter 4032 if (component != null) { 4033 return !isComponentVisibleToInstantApp(component, componentType); 4034 } 4035 // request for application; if no components have been explicitly exposed, filter 4036 return ps.getInstantApp(userId) || !ps.pkg.visibleToInstantApps; 4037 } 4038 if (ps.getInstantApp(userId)) { 4039 // caller can see all components of all instant applications, don't filter 4040 if (canViewInstantApps(callingUid, userId)) { 4041 return false; 4042 } 4043 // request for a specific instant application component, filter 4044 if (component != null) { 4045 return true; 4046 } 4047 // request for an instant application; if the caller hasn't been granted access, filter 4048 return !mInstantAppRegistry.isInstantAccessGranted( 4049 userId, UserHandle.getAppId(callingUid), ps.appId); 4050 } 4051 return false; 4052 } 4053 4054 /** 4055 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, boolean, int) 4056 */ 4057 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4058 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4059 } 4060 4061 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4062 int flags) { 4063 // Callers can access only the libs they depend on, otherwise they need to explicitly 4064 // ask for the shared libraries given the caller is allowed to access all static libs. 4065 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4066 // System/shell/root get to see all static libs 4067 final int appId = UserHandle.getAppId(uid); 4068 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4069 || appId == Process.ROOT_UID) { 4070 return false; 4071 } 4072 } 4073 4074 // No package means no static lib as it is always on internal storage 4075 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4076 return false; 4077 } 4078 4079 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(ps.pkg.staticSharedLibName, 4080 ps.pkg.staticSharedLibVersion); 4081 if (libEntry == null) { 4082 return false; 4083 } 4084 4085 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4086 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4087 if (uidPackageNames == null) { 4088 return true; 4089 } 4090 4091 for (String uidPackageName : uidPackageNames) { 4092 if (ps.name.equals(uidPackageName)) { 4093 return false; 4094 } 4095 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4096 if (uidPs != null) { 4097 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4098 libEntry.info.getName()); 4099 if (index < 0) { 4100 continue; 4101 } 4102 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libEntry.info.getLongVersion()) { 4103 return false; 4104 } 4105 } 4106 } 4107 return true; 4108 } 4109 4110 @Override 4111 public String[] currentToCanonicalPackageNames(String[] names) { 4112 final int callingUid = Binder.getCallingUid(); 4113 if (getInstantAppPackageName(callingUid) != null) { 4114 return names; 4115 } 4116 final String[] out = new String[names.length]; 4117 // reader 4118 synchronized (mPackages) { 4119 final int callingUserId = UserHandle.getUserId(callingUid); 4120 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4121 for (int i=names.length-1; i>=0; i--) { 4122 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4123 boolean translateName = false; 4124 if (ps != null && ps.realName != null) { 4125 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4126 translateName = !targetIsInstantApp 4127 || canViewInstantApps 4128 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4129 UserHandle.getAppId(callingUid), ps.appId); 4130 } 4131 out[i] = translateName ? ps.realName : names[i]; 4132 } 4133 } 4134 return out; 4135 } 4136 4137 @Override 4138 public String[] canonicalToCurrentPackageNames(String[] names) { 4139 final int callingUid = Binder.getCallingUid(); 4140 if (getInstantAppPackageName(callingUid) != null) { 4141 return names; 4142 } 4143 final String[] out = new String[names.length]; 4144 // reader 4145 synchronized (mPackages) { 4146 final int callingUserId = UserHandle.getUserId(callingUid); 4147 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4148 for (int i=names.length-1; i>=0; i--) { 4149 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4150 boolean translateName = false; 4151 if (cur != null) { 4152 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4153 final boolean targetIsInstantApp = 4154 ps != null && ps.getInstantApp(callingUserId); 4155 translateName = !targetIsInstantApp 4156 || canViewInstantApps 4157 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4158 UserHandle.getAppId(callingUid), ps.appId); 4159 } 4160 out[i] = translateName ? cur : names[i]; 4161 } 4162 } 4163 return out; 4164 } 4165 4166 @Override 4167 public int getPackageUid(String packageName, int flags, int userId) { 4168 if (!sUserManager.exists(userId)) return -1; 4169 final int callingUid = Binder.getCallingUid(); 4170 flags = updateFlagsForPackage(flags, userId, packageName); 4171 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4172 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4173 4174 // reader 4175 synchronized (mPackages) { 4176 final PackageParser.Package p = mPackages.get(packageName); 4177 if (p != null && p.isMatch(flags)) { 4178 PackageSetting ps = (PackageSetting) p.mExtras; 4179 if (filterAppAccessLPr(ps, callingUid, userId)) { 4180 return -1; 4181 } 4182 return UserHandle.getUid(userId, p.applicationInfo.uid); 4183 } 4184 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4185 final PackageSetting ps = mSettings.mPackages.get(packageName); 4186 if (ps != null && ps.isMatch(flags) 4187 && !filterAppAccessLPr(ps, callingUid, userId)) { 4188 return UserHandle.getUid(userId, ps.appId); 4189 } 4190 } 4191 } 4192 4193 return -1; 4194 } 4195 4196 @Override 4197 public int[] getPackageGids(String packageName, int flags, int userId) { 4198 if (!sUserManager.exists(userId)) return null; 4199 final int callingUid = Binder.getCallingUid(); 4200 flags = updateFlagsForPackage(flags, userId, packageName); 4201 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4202 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4203 4204 // reader 4205 synchronized (mPackages) { 4206 final PackageParser.Package p = mPackages.get(packageName); 4207 if (p != null && p.isMatch(flags)) { 4208 PackageSetting ps = (PackageSetting) p.mExtras; 4209 if (filterAppAccessLPr(ps, callingUid, userId)) { 4210 return null; 4211 } 4212 // TODO: Shouldn't this be checking for package installed state for userId and 4213 // return null? 4214 return ps.getPermissionsState().computeGids(userId); 4215 } 4216 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4217 final PackageSetting ps = mSettings.mPackages.get(packageName); 4218 if (ps != null && ps.isMatch(flags) 4219 && !filterAppAccessLPr(ps, callingUid, userId)) { 4220 return ps.getPermissionsState().computeGids(userId); 4221 } 4222 } 4223 } 4224 4225 return null; 4226 } 4227 4228 @Override 4229 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4230 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4231 } 4232 4233 @Override 4234 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4235 int flags) { 4236 final List<PermissionInfo> permissionList = 4237 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4238 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4239 } 4240 4241 @Override 4242 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4243 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4244 } 4245 4246 @Override 4247 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4248 final List<PermissionGroupInfo> permissionList = 4249 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4250 return (permissionList == null) 4251 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4252 } 4253 4254 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4255 int filterCallingUid, int userId) { 4256 if (!sUserManager.exists(userId)) return null; 4257 PackageSetting ps = mSettings.mPackages.get(packageName); 4258 if (ps != null) { 4259 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4260 return null; 4261 } 4262 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4263 return null; 4264 } 4265 if (ps.pkg == null) { 4266 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4267 if (pInfo != null) { 4268 return pInfo.applicationInfo; 4269 } 4270 return null; 4271 } 4272 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4273 ps.readUserState(userId), userId); 4274 if (ai != null) { 4275 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4276 } 4277 return ai; 4278 } 4279 return null; 4280 } 4281 4282 @Override 4283 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4284 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4285 } 4286 4287 /** 4288 * Important: The provided filterCallingUid is used exclusively to filter out applications 4289 * that can be seen based on user state. It's typically the original caller uid prior 4290 * to clearing. Because it can only be provided by trusted code, it's value can be 4291 * trusted and will be used as-is; unlike userId which will be validated by this method. 4292 */ 4293 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4294 int filterCallingUid, int userId) { 4295 if (!sUserManager.exists(userId)) return null; 4296 flags = updateFlagsForApplication(flags, userId, packageName); 4297 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4298 false /* requireFullPermission */, false /* checkShell */, "get application info"); 4299 4300 // writer 4301 synchronized (mPackages) { 4302 // Normalize package name to handle renamed packages and static libs 4303 packageName = resolveInternalPackageNameLPr(packageName, 4304 PackageManager.VERSION_CODE_HIGHEST); 4305 4306 PackageParser.Package p = mPackages.get(packageName); 4307 if (DEBUG_PACKAGE_INFO) Log.v( 4308 TAG, "getApplicationInfo " + packageName 4309 + ": " + p); 4310 if (p != null) { 4311 PackageSetting ps = mSettings.mPackages.get(packageName); 4312 if (ps == null) return null; 4313 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4314 return null; 4315 } 4316 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4317 return null; 4318 } 4319 // Note: isEnabledLP() does not apply here - always return info 4320 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4321 p, flags, ps.readUserState(userId), userId); 4322 if (ai != null) { 4323 ai.packageName = resolveExternalPackageNameLPr(p); 4324 } 4325 return ai; 4326 } 4327 if ("android".equals(packageName)||"system".equals(packageName)) { 4328 return mAndroidApplication; 4329 } 4330 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4331 // Already generates the external package name 4332 return generateApplicationInfoFromSettingsLPw(packageName, 4333 flags, filterCallingUid, userId); 4334 } 4335 } 4336 return null; 4337 } 4338 4339 private String normalizePackageNameLPr(String packageName) { 4340 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4341 return normalizedPackageName != null ? normalizedPackageName : packageName; 4342 } 4343 4344 @Override 4345 public void deletePreloadsFileCache() { 4346 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 4347 throw new SecurityException("Only system or settings may call deletePreloadsFileCache"); 4348 } 4349 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4350 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4351 FileUtils.deleteContents(dir); 4352 } 4353 4354 @Override 4355 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4356 final int storageFlags, final IPackageDataObserver observer) { 4357 mContext.enforceCallingOrSelfPermission( 4358 android.Manifest.permission.CLEAR_APP_CACHE, null); 4359 mHandler.post(() -> { 4360 boolean success = false; 4361 try { 4362 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4363 success = true; 4364 } catch (IOException e) { 4365 Slog.w(TAG, e); 4366 } 4367 if (observer != null) { 4368 try { 4369 observer.onRemoveCompleted(null, success); 4370 } catch (RemoteException e) { 4371 Slog.w(TAG, e); 4372 } 4373 } 4374 }); 4375 } 4376 4377 @Override 4378 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4379 final int storageFlags, final IntentSender pi) { 4380 mContext.enforceCallingOrSelfPermission( 4381 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4382 mHandler.post(() -> { 4383 boolean success = false; 4384 try { 4385 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4386 success = true; 4387 } catch (IOException e) { 4388 Slog.w(TAG, e); 4389 } 4390 if (pi != null) { 4391 try { 4392 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4393 } catch (SendIntentException e) { 4394 Slog.w(TAG, e); 4395 } 4396 } 4397 }); 4398 } 4399 4400 /** 4401 * Blocking call to clear various types of cached data across the system 4402 * until the requested bytes are available. 4403 */ 4404 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4405 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4406 final File file = storage.findPathForUuid(volumeUuid); 4407 if (file.getUsableSpace() >= bytes) return; 4408 4409 if (ENABLE_FREE_CACHE_V2) { 4410 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4411 volumeUuid); 4412 final boolean aggressive = (storageFlags 4413 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4414 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4415 4416 // 1. Pre-flight to determine if we have any chance to succeed 4417 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4418 if (internalVolume && (aggressive || SystemProperties 4419 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4420 deletePreloadsFileCache(); 4421 if (file.getUsableSpace() >= bytes) return; 4422 } 4423 4424 // 3. Consider parsed APK data (aggressive only) 4425 if (internalVolume && aggressive) { 4426 FileUtils.deleteContents(mCacheDir); 4427 if (file.getUsableSpace() >= bytes) return; 4428 } 4429 4430 // 4. Consider cached app data (above quotas) 4431 try { 4432 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4433 Installer.FLAG_FREE_CACHE_V2); 4434 } catch (InstallerException ignored) { 4435 } 4436 if (file.getUsableSpace() >= bytes) return; 4437 4438 // 5. Consider shared libraries with refcount=0 and age>min cache period 4439 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4440 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4441 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4442 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4443 return; 4444 } 4445 4446 // 6. Consider dexopt output (aggressive only) 4447 // TODO: Implement 4448 4449 // 7. Consider installed instant apps unused longer than min cache period 4450 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4451 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4452 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4453 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4454 return; 4455 } 4456 4457 // 8. Consider cached app data (below quotas) 4458 try { 4459 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4460 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4461 } catch (InstallerException ignored) { 4462 } 4463 if (file.getUsableSpace() >= bytes) return; 4464 4465 // 9. Consider DropBox entries 4466 // TODO: Implement 4467 4468 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4469 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4470 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4471 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4472 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4473 return; 4474 } 4475 } else { 4476 try { 4477 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4478 } catch (InstallerException ignored) { 4479 } 4480 if (file.getUsableSpace() >= bytes) return; 4481 } 4482 4483 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4484 } 4485 4486 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4487 throws IOException { 4488 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4489 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4490 4491 List<VersionedPackage> packagesToDelete = null; 4492 final long now = System.currentTimeMillis(); 4493 4494 synchronized (mPackages) { 4495 final int[] allUsers = sUserManager.getUserIds(); 4496 final int libCount = mSharedLibraries.size(); 4497 for (int i = 0; i < libCount; i++) { 4498 final LongSparseArray<SharedLibraryEntry> versionedLib 4499 = mSharedLibraries.valueAt(i); 4500 if (versionedLib == null) { 4501 continue; 4502 } 4503 final int versionCount = versionedLib.size(); 4504 for (int j = 0; j < versionCount; j++) { 4505 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4506 // Skip packages that are not static shared libs. 4507 if (!libInfo.isStatic()) { 4508 break; 4509 } 4510 // Important: We skip static shared libs used for some user since 4511 // in such a case we need to keep the APK on the device. The check for 4512 // a lib being used for any user is performed by the uninstall call. 4513 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4514 // Resolve the package name - we use synthetic package names internally 4515 final String internalPackageName = resolveInternalPackageNameLPr( 4516 declaringPackage.getPackageName(), 4517 declaringPackage.getLongVersionCode()); 4518 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4519 // Skip unused static shared libs cached less than the min period 4520 // to prevent pruning a lib needed by a subsequently installed package. 4521 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4522 continue; 4523 } 4524 if (packagesToDelete == null) { 4525 packagesToDelete = new ArrayList<>(); 4526 } 4527 packagesToDelete.add(new VersionedPackage(internalPackageName, 4528 declaringPackage.getLongVersionCode())); 4529 } 4530 } 4531 } 4532 4533 if (packagesToDelete != null) { 4534 final int packageCount = packagesToDelete.size(); 4535 for (int i = 0; i < packageCount; i++) { 4536 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4537 // Delete the package synchronously (will fail of the lib used for any user). 4538 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4539 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4540 == PackageManager.DELETE_SUCCEEDED) { 4541 if (volume.getUsableSpace() >= neededSpace) { 4542 return true; 4543 } 4544 } 4545 } 4546 } 4547 4548 return false; 4549 } 4550 4551 /** 4552 * Update given flags based on encryption status of current user. 4553 */ 4554 private int updateFlags(int flags, int userId) { 4555 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4556 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4557 // Caller expressed an explicit opinion about what encryption 4558 // aware/unaware components they want to see, so fall through and 4559 // give them what they want 4560 } else { 4561 // Caller expressed no opinion, so match based on user state 4562 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4563 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4564 } else { 4565 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4566 } 4567 } 4568 return flags; 4569 } 4570 4571 private UserManagerInternal getUserManagerInternal() { 4572 if (mUserManagerInternal == null) { 4573 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4574 } 4575 return mUserManagerInternal; 4576 } 4577 4578 private DeviceIdleController.LocalService getDeviceIdleController() { 4579 if (mDeviceIdleController == null) { 4580 mDeviceIdleController = 4581 LocalServices.getService(DeviceIdleController.LocalService.class); 4582 } 4583 return mDeviceIdleController; 4584 } 4585 4586 /** 4587 * Update given flags when being used to request {@link PackageInfo}. 4588 */ 4589 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4590 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4591 boolean triaged = true; 4592 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 4593 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 4594 // Caller is asking for component details, so they'd better be 4595 // asking for specific encryption matching behavior, or be triaged 4596 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4597 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4598 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4599 triaged = false; 4600 } 4601 } 4602 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 4603 | PackageManager.MATCH_SYSTEM_ONLY 4604 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4605 triaged = false; 4606 } 4607 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4608 mPermissionManager.enforceCrossUserPermission( 4609 Binder.getCallingUid(), userId, false, false, 4610 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4611 + Debug.getCallers(5)); 4612 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4613 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4614 // If the caller wants all packages and has a restricted profile associated with it, 4615 // then match all users. This is to make sure that launchers that need to access work 4616 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4617 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4618 flags |= PackageManager.MATCH_ANY_USER; 4619 } 4620 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4621 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4622 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4623 } 4624 return updateFlags(flags, userId); 4625 } 4626 4627 /** 4628 * Update given flags when being used to request {@link ApplicationInfo}. 4629 */ 4630 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4631 return updateFlagsForPackage(flags, userId, cookie); 4632 } 4633 4634 /** 4635 * Update given flags when being used to request {@link ComponentInfo}. 4636 */ 4637 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4638 if (cookie instanceof Intent) { 4639 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 4640 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 4641 } 4642 } 4643 4644 boolean triaged = true; 4645 // Caller is asking for component details, so they'd better be 4646 // asking for specific encryption matching behavior, or be triaged 4647 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4648 | PackageManager.MATCH_DIRECT_BOOT_AWARE 4649 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 4650 triaged = false; 4651 } 4652 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 4653 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 4654 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 4655 } 4656 4657 return updateFlags(flags, userId); 4658 } 4659 4660 /** 4661 * Update given intent when being used to request {@link ResolveInfo}. 4662 */ 4663 private Intent updateIntentForResolve(Intent intent) { 4664 if (intent.getSelector() != null) { 4665 intent = intent.getSelector(); 4666 } 4667 if (DEBUG_PREFERRED) { 4668 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4669 } 4670 return intent; 4671 } 4672 4673 /** 4674 * Update given flags when being used to request {@link ResolveInfo}. 4675 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4676 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4677 * flag set. However, this flag is only honoured in three circumstances: 4678 * <ul> 4679 * <li>when called from a system process</li> 4680 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4681 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4682 * action and a {@code android.intent.category.BROWSABLE} category</li> 4683 * </ul> 4684 */ 4685 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4686 return updateFlagsForResolve(flags, userId, intent, callingUid, 4687 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4688 } 4689 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4690 boolean wantInstantApps) { 4691 return updateFlagsForResolve(flags, userId, intent, callingUid, 4692 wantInstantApps, false /*onlyExposedExplicitly*/); 4693 } 4694 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4695 boolean wantInstantApps, boolean onlyExposedExplicitly) { 4696 // Safe mode means we shouldn't match any third-party components 4697 if (mSafeMode) { 4698 flags |= PackageManager.MATCH_SYSTEM_ONLY; 4699 } 4700 if (getInstantAppPackageName(callingUid) != null) { 4701 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 4702 if (onlyExposedExplicitly) { 4703 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 4704 } 4705 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 4706 flags |= PackageManager.MATCH_INSTANT; 4707 } else { 4708 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 4709 final boolean allowMatchInstant = 4710 (wantInstantApps 4711 && Intent.ACTION_VIEW.equals(intent.getAction()) 4712 && hasWebURI(intent)) 4713 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 4714 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 4715 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 4716 if (!allowMatchInstant) { 4717 flags &= ~PackageManager.MATCH_INSTANT; 4718 } 4719 } 4720 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 4721 } 4722 4723 @Override 4724 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 4725 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 4726 } 4727 4728 /** 4729 * Important: The provided filterCallingUid is used exclusively to filter out activities 4730 * that can be seen based on user state. It's typically the original caller uid prior 4731 * to clearing. Because it can only be provided by trusted code, it's value can be 4732 * trusted and will be used as-is; unlike userId which will be validated by this method. 4733 */ 4734 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 4735 int filterCallingUid, int userId) { 4736 if (!sUserManager.exists(userId)) return null; 4737 flags = updateFlagsForComponent(flags, userId, component); 4738 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4739 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 4740 synchronized (mPackages) { 4741 PackageParser.Activity a = mActivities.mActivities.get(component); 4742 4743 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 4744 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4745 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4746 if (ps == null) return null; 4747 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 4748 return null; 4749 } 4750 return PackageParser.generateActivityInfo( 4751 a, flags, ps.readUserState(userId), userId); 4752 } 4753 if (mResolveComponentName.equals(component)) { 4754 return PackageParser.generateActivityInfo( 4755 mResolveActivity, flags, new PackageUserState(), userId); 4756 } 4757 } 4758 return null; 4759 } 4760 4761 @Override 4762 public boolean activitySupportsIntent(ComponentName component, Intent intent, 4763 String resolvedType) { 4764 synchronized (mPackages) { 4765 if (component.equals(mResolveComponentName)) { 4766 // The resolver supports EVERYTHING! 4767 return true; 4768 } 4769 final int callingUid = Binder.getCallingUid(); 4770 final int callingUserId = UserHandle.getUserId(callingUid); 4771 PackageParser.Activity a = mActivities.mActivities.get(component); 4772 if (a == null) { 4773 return false; 4774 } 4775 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4776 if (ps == null) { 4777 return false; 4778 } 4779 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 4780 return false; 4781 } 4782 for (int i=0; i<a.intents.size(); i++) { 4783 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 4784 intent.getData(), intent.getCategories(), TAG) >= 0) { 4785 return true; 4786 } 4787 } 4788 return false; 4789 } 4790 } 4791 4792 @Override 4793 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 4794 if (!sUserManager.exists(userId)) return null; 4795 final int callingUid = Binder.getCallingUid(); 4796 flags = updateFlagsForComponent(flags, userId, component); 4797 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4798 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 4799 synchronized (mPackages) { 4800 PackageParser.Activity a = mReceivers.mActivities.get(component); 4801 if (DEBUG_PACKAGE_INFO) Log.v( 4802 TAG, "getReceiverInfo " + component + ": " + a); 4803 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 4804 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4805 if (ps == null) return null; 4806 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 4807 return null; 4808 } 4809 return PackageParser.generateActivityInfo( 4810 a, flags, ps.readUserState(userId), userId); 4811 } 4812 } 4813 return null; 4814 } 4815 4816 @Override 4817 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 4818 int flags, int userId) { 4819 if (!sUserManager.exists(userId)) return null; 4820 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4821 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4822 return null; 4823 } 4824 4825 flags = updateFlagsForPackage(flags, userId, null); 4826 4827 final boolean canSeeStaticLibraries = 4828 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 4829 == PERMISSION_GRANTED 4830 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 4831 == PERMISSION_GRANTED 4832 || canRequestPackageInstallsInternal(packageName, 4833 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 4834 false /* throwIfPermNotDeclared*/) 4835 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 4836 == PERMISSION_GRANTED; 4837 4838 synchronized (mPackages) { 4839 List<SharedLibraryInfo> result = null; 4840 4841 final int libCount = mSharedLibraries.size(); 4842 for (int i = 0; i < libCount; i++) { 4843 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4844 if (versionedLib == null) { 4845 continue; 4846 } 4847 4848 final int versionCount = versionedLib.size(); 4849 for (int j = 0; j < versionCount; j++) { 4850 SharedLibraryInfo libInfo = versionedLib.valueAt(j).info; 4851 if (!canSeeStaticLibraries && libInfo.isStatic()) { 4852 break; 4853 } 4854 final long identity = Binder.clearCallingIdentity(); 4855 try { 4856 PackageInfo packageInfo = getPackageInfoVersioned( 4857 libInfo.getDeclaringPackage(), flags 4858 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 4859 if (packageInfo == null) { 4860 continue; 4861 } 4862 } finally { 4863 Binder.restoreCallingIdentity(identity); 4864 } 4865 4866 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getName(), 4867 libInfo.getLongVersion(), libInfo.getType(), 4868 libInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr(libInfo, 4869 flags, userId)); 4870 4871 if (result == null) { 4872 result = new ArrayList<>(); 4873 } 4874 result.add(resLibInfo); 4875 } 4876 } 4877 4878 return result != null ? new ParceledListSlice<>(result) : null; 4879 } 4880 } 4881 4882 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 4883 SharedLibraryInfo libInfo, int flags, int userId) { 4884 List<VersionedPackage> versionedPackages = null; 4885 final int packageCount = mSettings.mPackages.size(); 4886 for (int i = 0; i < packageCount; i++) { 4887 PackageSetting ps = mSettings.mPackages.valueAt(i); 4888 4889 if (ps == null) { 4890 continue; 4891 } 4892 4893 if (!ps.getUserState().get(userId).isAvailable(flags)) { 4894 continue; 4895 } 4896 4897 final String libName = libInfo.getName(); 4898 if (libInfo.isStatic()) { 4899 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 4900 if (libIdx < 0) { 4901 continue; 4902 } 4903 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 4904 continue; 4905 } 4906 if (versionedPackages == null) { 4907 versionedPackages = new ArrayList<>(); 4908 } 4909 // If the dependent is a static shared lib, use the public package name 4910 String dependentPackageName = ps.name; 4911 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4912 dependentPackageName = ps.pkg.manifestPackageName; 4913 } 4914 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 4915 } else if (ps.pkg != null) { 4916 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 4917 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 4918 if (versionedPackages == null) { 4919 versionedPackages = new ArrayList<>(); 4920 } 4921 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 4922 } 4923 } 4924 } 4925 4926 return versionedPackages; 4927 } 4928 4929 @Override 4930 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 4931 if (!sUserManager.exists(userId)) return null; 4932 final int callingUid = Binder.getCallingUid(); 4933 flags = updateFlagsForComponent(flags, userId, component); 4934 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4935 false /* requireFullPermission */, false /* checkShell */, "get service info"); 4936 synchronized (mPackages) { 4937 PackageParser.Service s = mServices.mServices.get(component); 4938 if (DEBUG_PACKAGE_INFO) Log.v( 4939 TAG, "getServiceInfo " + component + ": " + s); 4940 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 4941 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4942 if (ps == null) return null; 4943 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 4944 return null; 4945 } 4946 return PackageParser.generateServiceInfo( 4947 s, flags, ps.readUserState(userId), userId); 4948 } 4949 } 4950 return null; 4951 } 4952 4953 @Override 4954 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 4955 if (!sUserManager.exists(userId)) return null; 4956 final int callingUid = Binder.getCallingUid(); 4957 flags = updateFlagsForComponent(flags, userId, component); 4958 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4959 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 4960 synchronized (mPackages) { 4961 PackageParser.Provider p = mProviders.mProviders.get(component); 4962 if (DEBUG_PACKAGE_INFO) Log.v( 4963 TAG, "getProviderInfo " + component + ": " + p); 4964 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 4965 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 4966 if (ps == null) return null; 4967 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 4968 return null; 4969 } 4970 return PackageParser.generateProviderInfo( 4971 p, flags, ps.readUserState(userId), userId); 4972 } 4973 } 4974 return null; 4975 } 4976 4977 @Override 4978 public String[] getSystemSharedLibraryNames() { 4979 // allow instant applications 4980 synchronized (mPackages) { 4981 Set<String> libs = null; 4982 final int libCount = mSharedLibraries.size(); 4983 for (int i = 0; i < libCount; i++) { 4984 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.valueAt(i); 4985 if (versionedLib == null) { 4986 continue; 4987 } 4988 final int versionCount = versionedLib.size(); 4989 for (int j = 0; j < versionCount; j++) { 4990 SharedLibraryEntry libEntry = versionedLib.valueAt(j); 4991 if (!libEntry.info.isStatic()) { 4992 if (libs == null) { 4993 libs = new ArraySet<>(); 4994 } 4995 libs.add(libEntry.info.getName()); 4996 break; 4997 } 4998 PackageSetting ps = mSettings.getPackageLPr(libEntry.apk); 4999 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5000 UserHandle.getUserId(Binder.getCallingUid()), 5001 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5002 if (libs == null) { 5003 libs = new ArraySet<>(); 5004 } 5005 libs.add(libEntry.info.getName()); 5006 break; 5007 } 5008 } 5009 } 5010 5011 if (libs != null) { 5012 String[] libsArray = new String[libs.size()]; 5013 libs.toArray(libsArray); 5014 return libsArray; 5015 } 5016 5017 return null; 5018 } 5019 } 5020 5021 @Override 5022 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5023 // allow instant applications 5024 synchronized (mPackages) { 5025 return mServicesSystemSharedLibraryPackageName; 5026 } 5027 } 5028 5029 @Override 5030 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5031 // allow instant applications 5032 synchronized (mPackages) { 5033 return mSharedSystemSharedLibraryPackageName; 5034 } 5035 } 5036 5037 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5038 for (int i = userList.length - 1; i >= 0; --i) { 5039 final int userId = userList[i]; 5040 // don't add instant app to the list of updates 5041 if (pkgSetting.getInstantApp(userId)) { 5042 continue; 5043 } 5044 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5045 if (changedPackages == null) { 5046 changedPackages = new SparseArray<>(); 5047 mChangedPackages.put(userId, changedPackages); 5048 } 5049 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5050 if (sequenceNumbers == null) { 5051 sequenceNumbers = new HashMap<>(); 5052 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5053 } 5054 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5055 if (sequenceNumber != null) { 5056 changedPackages.remove(sequenceNumber); 5057 } 5058 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5059 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5060 } 5061 mChangedPackagesSequenceNumber++; 5062 } 5063 5064 @Override 5065 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5066 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5067 return null; 5068 } 5069 synchronized (mPackages) { 5070 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5071 return null; 5072 } 5073 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5074 if (changedPackages == null) { 5075 return null; 5076 } 5077 final List<String> packageNames = 5078 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5079 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5080 final String packageName = changedPackages.get(i); 5081 if (packageName != null) { 5082 packageNames.add(packageName); 5083 } 5084 } 5085 return packageNames.isEmpty() 5086 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5087 } 5088 } 5089 5090 @Override 5091 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5092 // allow instant applications 5093 ArrayList<FeatureInfo> res; 5094 synchronized (mAvailableFeatures) { 5095 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5096 res.addAll(mAvailableFeatures.values()); 5097 } 5098 final FeatureInfo fi = new FeatureInfo(); 5099 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5100 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5101 res.add(fi); 5102 5103 return new ParceledListSlice<>(res); 5104 } 5105 5106 @Override 5107 public boolean hasSystemFeature(String name, int version) { 5108 // allow instant applications 5109 synchronized (mAvailableFeatures) { 5110 final FeatureInfo feat = mAvailableFeatures.get(name); 5111 if (feat == null) { 5112 return false; 5113 } else { 5114 return feat.version >= version; 5115 } 5116 } 5117 } 5118 5119 @Override 5120 public int checkPermission(String permName, String pkgName, int userId) { 5121 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5122 } 5123 5124 @Override 5125 public int checkUidPermission(String permName, int uid) { 5126 return mPermissionManager.checkUidPermission(permName, uid, getCallingUid()); 5127 } 5128 5129 @Override 5130 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5131 if (UserHandle.getCallingUserId() != userId) { 5132 mContext.enforceCallingPermission( 5133 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5134 "isPermissionRevokedByPolicy for user " + userId); 5135 } 5136 5137 if (checkPermission(permission, packageName, userId) 5138 == PackageManager.PERMISSION_GRANTED) { 5139 return false; 5140 } 5141 5142 final int callingUid = Binder.getCallingUid(); 5143 if (getInstantAppPackageName(callingUid) != null) { 5144 if (!isCallerSameApp(packageName, callingUid)) { 5145 return false; 5146 } 5147 } else { 5148 if (isInstantApp(packageName, userId)) { 5149 return false; 5150 } 5151 } 5152 5153 final long identity = Binder.clearCallingIdentity(); 5154 try { 5155 final int flags = getPermissionFlags(permission, packageName, userId); 5156 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5157 } finally { 5158 Binder.restoreCallingIdentity(identity); 5159 } 5160 } 5161 5162 @Override 5163 public String getPermissionControllerPackageName() { 5164 synchronized (mPackages) { 5165 return mRequiredInstallerPackage; 5166 } 5167 } 5168 5169 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5170 return mPermissionManager.addDynamicPermission( 5171 info, async, getCallingUid(), new PermissionCallback() { 5172 @Override 5173 public void onPermissionChanged() { 5174 if (!async) { 5175 mSettings.writeLPr(); 5176 } else { 5177 scheduleWriteSettingsLocked(); 5178 } 5179 } 5180 }); 5181 } 5182 5183 @Override 5184 public boolean addPermission(PermissionInfo info) { 5185 synchronized (mPackages) { 5186 return addDynamicPermission(info, false); 5187 } 5188 } 5189 5190 @Override 5191 public boolean addPermissionAsync(PermissionInfo info) { 5192 synchronized (mPackages) { 5193 return addDynamicPermission(info, true); 5194 } 5195 } 5196 5197 @Override 5198 public void removePermission(String permName) { 5199 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5200 } 5201 5202 @Override 5203 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5204 mPermissionManager.grantRuntimePermission(permName, packageName, false /*overridePolicy*/, 5205 getCallingUid(), userId, mPermissionCallback); 5206 } 5207 5208 @Override 5209 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5210 mPermissionManager.revokeRuntimePermission(permName, packageName, false /*overridePolicy*/, 5211 getCallingUid(), userId, mPermissionCallback); 5212 } 5213 5214 @Override 5215 public void resetRuntimePermissions() { 5216 mContext.enforceCallingOrSelfPermission( 5217 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5218 "revokeRuntimePermission"); 5219 5220 int callingUid = Binder.getCallingUid(); 5221 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5222 mContext.enforceCallingOrSelfPermission( 5223 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5224 "resetRuntimePermissions"); 5225 } 5226 5227 synchronized (mPackages) { 5228 mPermissionManager.updateAllPermissions( 5229 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5230 mPermissionCallback); 5231 for (int userId : UserManagerService.getInstance().getUserIds()) { 5232 final int packageCount = mPackages.size(); 5233 for (int i = 0; i < packageCount; i++) { 5234 PackageParser.Package pkg = mPackages.valueAt(i); 5235 if (!(pkg.mExtras instanceof PackageSetting)) { 5236 continue; 5237 } 5238 PackageSetting ps = (PackageSetting) pkg.mExtras; 5239 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5240 } 5241 } 5242 } 5243 } 5244 5245 @Override 5246 public int getPermissionFlags(String permName, String packageName, int userId) { 5247 return mPermissionManager.getPermissionFlags( 5248 permName, packageName, getCallingUid(), userId); 5249 } 5250 5251 @Override 5252 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5253 int flagValues, int userId) { 5254 mPermissionManager.updatePermissionFlags( 5255 permName, packageName, flagMask, flagValues, getCallingUid(), userId, 5256 mPermissionCallback); 5257 } 5258 5259 /** 5260 * Update the permission flags for all packages and runtime permissions of a user in order 5261 * to allow device or profile owner to remove POLICY_FIXED. 5262 */ 5263 @Override 5264 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5265 synchronized (mPackages) { 5266 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5267 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5268 mPermissionCallback); 5269 if (changed) { 5270 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5271 } 5272 } 5273 } 5274 5275 @Override 5276 public boolean shouldShowRequestPermissionRationale(String permissionName, 5277 String packageName, int userId) { 5278 if (UserHandle.getCallingUserId() != userId) { 5279 mContext.enforceCallingPermission( 5280 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5281 "canShowRequestPermissionRationale for user " + userId); 5282 } 5283 5284 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5285 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5286 return false; 5287 } 5288 5289 if (checkPermission(permissionName, packageName, userId) 5290 == PackageManager.PERMISSION_GRANTED) { 5291 return false; 5292 } 5293 5294 final int flags; 5295 5296 final long identity = Binder.clearCallingIdentity(); 5297 try { 5298 flags = getPermissionFlags(permissionName, 5299 packageName, userId); 5300 } finally { 5301 Binder.restoreCallingIdentity(identity); 5302 } 5303 5304 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 5305 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 5306 | PackageManager.FLAG_PERMISSION_USER_FIXED; 5307 5308 if ((flags & fixedFlags) != 0) { 5309 return false; 5310 } 5311 5312 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 5313 } 5314 5315 @Override 5316 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5317 mContext.enforceCallingOrSelfPermission( 5318 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 5319 "addOnPermissionsChangeListener"); 5320 5321 synchronized (mPackages) { 5322 mOnPermissionChangeListeners.addListenerLocked(listener); 5323 } 5324 } 5325 5326 @Override 5327 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 5328 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5329 throw new SecurityException("Instant applications don't have access to this method"); 5330 } 5331 synchronized (mPackages) { 5332 mOnPermissionChangeListeners.removeListenerLocked(listener); 5333 } 5334 } 5335 5336 @Override 5337 public boolean isProtectedBroadcast(String actionName) { 5338 // allow instant applications 5339 synchronized (mProtectedBroadcasts) { 5340 if (mProtectedBroadcasts.contains(actionName)) { 5341 return true; 5342 } else if (actionName != null) { 5343 // TODO: remove these terrible hacks 5344 if (actionName.startsWith("android.net.netmon.lingerExpired") 5345 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5346 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5347 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5348 return true; 5349 } 5350 } 5351 } 5352 return false; 5353 } 5354 5355 @Override 5356 public int checkSignatures(String pkg1, String pkg2) { 5357 synchronized (mPackages) { 5358 final PackageParser.Package p1 = mPackages.get(pkg1); 5359 final PackageParser.Package p2 = mPackages.get(pkg2); 5360 if (p1 == null || p1.mExtras == null 5361 || p2 == null || p2.mExtras == null) { 5362 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5363 } 5364 final int callingUid = Binder.getCallingUid(); 5365 final int callingUserId = UserHandle.getUserId(callingUid); 5366 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 5367 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 5368 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 5369 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 5370 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5371 } 5372 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 5373 } 5374 } 5375 5376 @Override 5377 public int checkUidSignatures(int uid1, int uid2) { 5378 final int callingUid = Binder.getCallingUid(); 5379 final int callingUserId = UserHandle.getUserId(callingUid); 5380 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5381 // Map to base uids. 5382 uid1 = UserHandle.getAppId(uid1); 5383 uid2 = UserHandle.getAppId(uid2); 5384 // reader 5385 synchronized (mPackages) { 5386 Signature[] s1; 5387 Signature[] s2; 5388 Object obj = mSettings.getUserIdLPr(uid1); 5389 if (obj != null) { 5390 if (obj instanceof SharedUserSetting) { 5391 if (isCallerInstantApp) { 5392 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5393 } 5394 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 5395 } else if (obj instanceof PackageSetting) { 5396 final PackageSetting ps = (PackageSetting) obj; 5397 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5398 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5399 } 5400 s1 = ps.signatures.mSignatures; 5401 } else { 5402 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5403 } 5404 } else { 5405 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5406 } 5407 obj = mSettings.getUserIdLPr(uid2); 5408 if (obj != null) { 5409 if (obj instanceof SharedUserSetting) { 5410 if (isCallerInstantApp) { 5411 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5412 } 5413 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 5414 } else if (obj instanceof PackageSetting) { 5415 final PackageSetting ps = (PackageSetting) obj; 5416 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 5417 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5418 } 5419 s2 = ps.signatures.mSignatures; 5420 } else { 5421 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5422 } 5423 } else { 5424 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 5425 } 5426 return compareSignatures(s1, s2); 5427 } 5428 } 5429 5430 /** 5431 * This method should typically only be used when granting or revoking 5432 * permissions, since the app may immediately restart after this call. 5433 * <p> 5434 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 5435 * guard your work against the app being relaunched. 5436 */ 5437 private void killUid(int appId, int userId, String reason) { 5438 final long identity = Binder.clearCallingIdentity(); 5439 try { 5440 IActivityManager am = ActivityManager.getService(); 5441 if (am != null) { 5442 try { 5443 am.killUid(appId, userId, reason); 5444 } catch (RemoteException e) { 5445 /* ignore - same process */ 5446 } 5447 } 5448 } finally { 5449 Binder.restoreCallingIdentity(identity); 5450 } 5451 } 5452 5453 /** 5454 * If the database version for this type of package (internal storage or 5455 * external storage) is less than the version where package signatures 5456 * were updated, return true. 5457 */ 5458 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5459 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5460 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 5461 } 5462 5463 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 5464 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 5465 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 5466 } 5467 5468 @Override 5469 public List<String> getAllPackages() { 5470 final int callingUid = Binder.getCallingUid(); 5471 final int callingUserId = UserHandle.getUserId(callingUid); 5472 synchronized (mPackages) { 5473 if (canViewInstantApps(callingUid, callingUserId)) { 5474 return new ArrayList<String>(mPackages.keySet()); 5475 } 5476 final String instantAppPkgName = getInstantAppPackageName(callingUid); 5477 final List<String> result = new ArrayList<>(); 5478 if (instantAppPkgName != null) { 5479 // caller is an instant application; filter unexposed applications 5480 for (PackageParser.Package pkg : mPackages.values()) { 5481 if (!pkg.visibleToInstantApps) { 5482 continue; 5483 } 5484 result.add(pkg.packageName); 5485 } 5486 } else { 5487 // caller is a normal application; filter instant applications 5488 for (PackageParser.Package pkg : mPackages.values()) { 5489 final PackageSetting ps = 5490 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 5491 if (ps != null 5492 && ps.getInstantApp(callingUserId) 5493 && !mInstantAppRegistry.isInstantAccessGranted( 5494 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 5495 continue; 5496 } 5497 result.add(pkg.packageName); 5498 } 5499 } 5500 return result; 5501 } 5502 } 5503 5504 @Override 5505 public String[] getPackagesForUid(int uid) { 5506 final int callingUid = Binder.getCallingUid(); 5507 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 5508 final int userId = UserHandle.getUserId(uid); 5509 uid = UserHandle.getAppId(uid); 5510 // reader 5511 synchronized (mPackages) { 5512 Object obj = mSettings.getUserIdLPr(uid); 5513 if (obj instanceof SharedUserSetting) { 5514 if (isCallerInstantApp) { 5515 return null; 5516 } 5517 final SharedUserSetting sus = (SharedUserSetting) obj; 5518 final int N = sus.packages.size(); 5519 String[] res = new String[N]; 5520 final Iterator<PackageSetting> it = sus.packages.iterator(); 5521 int i = 0; 5522 while (it.hasNext()) { 5523 PackageSetting ps = it.next(); 5524 if (ps.getInstalled(userId)) { 5525 res[i++] = ps.name; 5526 } else { 5527 res = ArrayUtils.removeElement(String.class, res, res[i]); 5528 } 5529 } 5530 return res; 5531 } else if (obj instanceof PackageSetting) { 5532 final PackageSetting ps = (PackageSetting) obj; 5533 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 5534 return new String[]{ps.name}; 5535 } 5536 } 5537 } 5538 return null; 5539 } 5540 5541 @Override 5542 public String getNameForUid(int uid) { 5543 final int callingUid = Binder.getCallingUid(); 5544 if (getInstantAppPackageName(callingUid) != null) { 5545 return null; 5546 } 5547 synchronized (mPackages) { 5548 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5549 if (obj instanceof SharedUserSetting) { 5550 final SharedUserSetting sus = (SharedUserSetting) obj; 5551 return sus.name + ":" + sus.userId; 5552 } else if (obj instanceof PackageSetting) { 5553 final PackageSetting ps = (PackageSetting) obj; 5554 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5555 return null; 5556 } 5557 return ps.name; 5558 } 5559 return null; 5560 } 5561 } 5562 5563 @Override 5564 public String[] getNamesForUids(int[] uids) { 5565 if (uids == null || uids.length == 0) { 5566 return null; 5567 } 5568 final int callingUid = Binder.getCallingUid(); 5569 if (getInstantAppPackageName(callingUid) != null) { 5570 return null; 5571 } 5572 final String[] names = new String[uids.length]; 5573 synchronized (mPackages) { 5574 for (int i = uids.length - 1; i >= 0; i--) { 5575 final int uid = uids[i]; 5576 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5577 if (obj instanceof SharedUserSetting) { 5578 final SharedUserSetting sus = (SharedUserSetting) obj; 5579 names[i] = "shared:" + sus.name; 5580 } else if (obj instanceof PackageSetting) { 5581 final PackageSetting ps = (PackageSetting) obj; 5582 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5583 names[i] = null; 5584 } else { 5585 names[i] = ps.name; 5586 } 5587 } else { 5588 names[i] = null; 5589 } 5590 } 5591 } 5592 return names; 5593 } 5594 5595 @Override 5596 public int getUidForSharedUser(String sharedUserName) { 5597 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5598 return -1; 5599 } 5600 if (sharedUserName == null) { 5601 return -1; 5602 } 5603 // reader 5604 synchronized (mPackages) { 5605 SharedUserSetting suid; 5606 try { 5607 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 5608 if (suid != null) { 5609 return suid.userId; 5610 } 5611 } catch (PackageManagerException ignore) { 5612 // can't happen, but, still need to catch it 5613 } 5614 return -1; 5615 } 5616 } 5617 5618 @Override 5619 public int getFlagsForUid(int uid) { 5620 final int callingUid = Binder.getCallingUid(); 5621 if (getInstantAppPackageName(callingUid) != null) { 5622 return 0; 5623 } 5624 synchronized (mPackages) { 5625 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5626 if (obj instanceof SharedUserSetting) { 5627 final SharedUserSetting sus = (SharedUserSetting) obj; 5628 return sus.pkgFlags; 5629 } else if (obj instanceof PackageSetting) { 5630 final PackageSetting ps = (PackageSetting) obj; 5631 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5632 return 0; 5633 } 5634 return ps.pkgFlags; 5635 } 5636 } 5637 return 0; 5638 } 5639 5640 @Override 5641 public int getPrivateFlagsForUid(int uid) { 5642 final int callingUid = Binder.getCallingUid(); 5643 if (getInstantAppPackageName(callingUid) != null) { 5644 return 0; 5645 } 5646 synchronized (mPackages) { 5647 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 5648 if (obj instanceof SharedUserSetting) { 5649 final SharedUserSetting sus = (SharedUserSetting) obj; 5650 return sus.pkgPrivateFlags; 5651 } else if (obj instanceof PackageSetting) { 5652 final PackageSetting ps = (PackageSetting) obj; 5653 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 5654 return 0; 5655 } 5656 return ps.pkgPrivateFlags; 5657 } 5658 } 5659 return 0; 5660 } 5661 5662 @Override 5663 public boolean isUidPrivileged(int uid) { 5664 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5665 return false; 5666 } 5667 uid = UserHandle.getAppId(uid); 5668 // reader 5669 synchronized (mPackages) { 5670 Object obj = mSettings.getUserIdLPr(uid); 5671 if (obj instanceof SharedUserSetting) { 5672 final SharedUserSetting sus = (SharedUserSetting) obj; 5673 final Iterator<PackageSetting> it = sus.packages.iterator(); 5674 while (it.hasNext()) { 5675 if (it.next().isPrivileged()) { 5676 return true; 5677 } 5678 } 5679 } else if (obj instanceof PackageSetting) { 5680 final PackageSetting ps = (PackageSetting) obj; 5681 return ps.isPrivileged(); 5682 } 5683 } 5684 return false; 5685 } 5686 5687 @Override 5688 public String[] getAppOpPermissionPackages(String permName) { 5689 return mPermissionManager.getAppOpPermissionPackages(permName); 5690 } 5691 5692 @Override 5693 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 5694 int flags, int userId) { 5695 return resolveIntentInternal( 5696 intent, resolvedType, flags, userId, false /*resolveForStart*/); 5697 } 5698 5699 /** 5700 * Normally instant apps can only be resolved when they're visible to the caller. 5701 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 5702 * since we need to allow the system to start any installed application. 5703 */ 5704 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 5705 int flags, int userId, boolean resolveForStart) { 5706 try { 5707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 5708 5709 if (!sUserManager.exists(userId)) return null; 5710 final int callingUid = Binder.getCallingUid(); 5711 flags = updateFlagsForResolve(flags, userId, intent, callingUid, resolveForStart); 5712 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5713 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 5714 5715 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5716 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 5717 flags, callingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 5718 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5719 5720 final ResolveInfo bestChoice = 5721 chooseBestActivity(intent, resolvedType, flags, query, userId); 5722 return bestChoice; 5723 } finally { 5724 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5725 } 5726 } 5727 5728 @Override 5729 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 5730 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 5731 throw new SecurityException( 5732 "findPersistentPreferredActivity can only be run by the system"); 5733 } 5734 if (!sUserManager.exists(userId)) { 5735 return null; 5736 } 5737 final int callingUid = Binder.getCallingUid(); 5738 intent = updateIntentForResolve(intent); 5739 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 5740 final int flags = updateFlagsForResolve( 5741 0, userId, intent, callingUid, false /*includeInstantApps*/); 5742 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5743 userId); 5744 synchronized (mPackages) { 5745 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 5746 userId); 5747 } 5748 } 5749 5750 @Override 5751 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 5752 IntentFilter filter, int match, ComponentName activity) { 5753 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5754 return; 5755 } 5756 final int userId = UserHandle.getCallingUserId(); 5757 if (DEBUG_PREFERRED) { 5758 Log.v(TAG, "setLastChosenActivity intent=" + intent 5759 + " resolvedType=" + resolvedType 5760 + " flags=" + flags 5761 + " filter=" + filter 5762 + " match=" + match 5763 + " activity=" + activity); 5764 filter.dump(new PrintStreamPrinter(System.out), " "); 5765 } 5766 intent.setComponent(null); 5767 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5768 userId); 5769 // Find any earlier preferred or last chosen entries and nuke them 5770 findPreferredActivity(intent, resolvedType, 5771 flags, query, 0, false, true, false, userId); 5772 // Add the new activity as the last chosen for this filter 5773 addPreferredActivityInternal(filter, match, null, activity, false, userId, 5774 "Setting last chosen"); 5775 } 5776 5777 @Override 5778 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5779 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5780 return null; 5781 } 5782 final int userId = UserHandle.getCallingUserId(); 5783 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 5784 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 5785 userId); 5786 return findPreferredActivity(intent, resolvedType, flags, query, 0, 5787 false, false, false, userId); 5788 } 5789 5790 /** 5791 * Returns whether or not instant apps have been disabled remotely. 5792 */ 5793 private boolean isEphemeralDisabled() { 5794 return mEphemeralAppsDisabled; 5795 } 5796 5797 private boolean isInstantAppAllowed( 5798 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 5799 boolean skipPackageCheck) { 5800 if (mInstantAppResolverConnection == null) { 5801 return false; 5802 } 5803 if (mInstantAppInstallerActivity == null) { 5804 return false; 5805 } 5806 if (intent.getComponent() != null) { 5807 return false; 5808 } 5809 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 5810 return false; 5811 } 5812 if (!skipPackageCheck && intent.getPackage() != null) { 5813 return false; 5814 } 5815 final boolean isWebUri = hasWebURI(intent); 5816 if (!isWebUri || intent.getData().getHost() == null) { 5817 return false; 5818 } 5819 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5820 // Or if there's already an ephemeral app installed that handles the action 5821 synchronized (mPackages) { 5822 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 5823 for (int n = 0; n < count; n++) { 5824 final ResolveInfo info = resolvedActivities.get(n); 5825 final String packageName = info.activityInfo.packageName; 5826 final PackageSetting ps = mSettings.mPackages.get(packageName); 5827 if (ps != null) { 5828 // only check domain verification status if the app is not a browser 5829 if (!info.handleAllWebDataURI) { 5830 // Try to get the status from User settings first 5831 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5832 final int status = (int) (packedStatus >> 32); 5833 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5834 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5835 if (DEBUG_EPHEMERAL) { 5836 Slog.v(TAG, "DENY instant app;" 5837 + " pkg: " + packageName + ", status: " + status); 5838 } 5839 return false; 5840 } 5841 } 5842 if (ps.getInstantApp(userId)) { 5843 if (DEBUG_EPHEMERAL) { 5844 Slog.v(TAG, "DENY instant app installed;" 5845 + " pkg: " + packageName); 5846 } 5847 return false; 5848 } 5849 } 5850 } 5851 } 5852 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5853 return true; 5854 } 5855 5856 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 5857 Intent origIntent, String resolvedType, String callingPackage, 5858 Bundle verificationBundle, int userId) { 5859 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 5860 new InstantAppRequest(responseObj, origIntent, resolvedType, 5861 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 5862 mHandler.sendMessage(msg); 5863 } 5864 5865 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5866 int flags, List<ResolveInfo> query, int userId) { 5867 if (query != null) { 5868 final int N = query.size(); 5869 if (N == 1) { 5870 return query.get(0); 5871 } else if (N > 1) { 5872 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5873 // If there is more than one activity with the same priority, 5874 // then let the user decide between them. 5875 ResolveInfo r0 = query.get(0); 5876 ResolveInfo r1 = query.get(1); 5877 if (DEBUG_INTENT_MATCHING || debug) { 5878 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5879 + r1.activityInfo.name + "=" + r1.priority); 5880 } 5881 // If the first activity has a higher priority, or a different 5882 // default, then it is always desirable to pick it. 5883 if (r0.priority != r1.priority 5884 || r0.preferredOrder != r1.preferredOrder 5885 || r0.isDefault != r1.isDefault) { 5886 return query.get(0); 5887 } 5888 // If we have saved a preference for a preferred activity for 5889 // this Intent, use that. 5890 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5891 flags, query, r0.priority, true, false, debug, userId); 5892 if (ri != null) { 5893 return ri; 5894 } 5895 // If we have an ephemeral app, use it 5896 for (int i = 0; i < N; i++) { 5897 ri = query.get(i); 5898 if (ri.activityInfo.applicationInfo.isInstantApp()) { 5899 final String packageName = ri.activityInfo.packageName; 5900 final PackageSetting ps = mSettings.mPackages.get(packageName); 5901 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5902 final int status = (int)(packedStatus >> 32); 5903 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5904 return ri; 5905 } 5906 } 5907 } 5908 ri = new ResolveInfo(mResolveInfo); 5909 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5910 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5911 // If all of the options come from the same package, show the application's 5912 // label and icon instead of the generic resolver's. 5913 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5914 // and then throw away the ResolveInfo itself, meaning that the caller loses 5915 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5916 // a fallback for this case; we only set the target package's resources on 5917 // the ResolveInfo, not the ActivityInfo. 5918 final String intentPackage = intent.getPackage(); 5919 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5920 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5921 ri.resolvePackageName = intentPackage; 5922 if (userNeedsBadging(userId)) { 5923 ri.noResourceId = true; 5924 } else { 5925 ri.icon = appi.icon; 5926 } 5927 ri.iconResourceId = appi.icon; 5928 ri.labelRes = appi.labelRes; 5929 } 5930 ri.activityInfo.applicationInfo = new ApplicationInfo( 5931 ri.activityInfo.applicationInfo); 5932 if (userId != 0) { 5933 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5934 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5935 } 5936 // Make sure that the resolver is displayable in car mode 5937 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5938 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5939 return ri; 5940 } 5941 } 5942 return null; 5943 } 5944 5945 /** 5946 * Return true if the given list is not empty and all of its contents have 5947 * an activityInfo with the given package name. 5948 */ 5949 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5950 if (ArrayUtils.isEmpty(list)) { 5951 return false; 5952 } 5953 for (int i = 0, N = list.size(); i < N; i++) { 5954 final ResolveInfo ri = list.get(i); 5955 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5956 if (ai == null || !packageName.equals(ai.packageName)) { 5957 return false; 5958 } 5959 } 5960 return true; 5961 } 5962 5963 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5964 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5965 final int N = query.size(); 5966 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5967 .get(userId); 5968 // Get the list of persistent preferred activities that handle the intent 5969 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5970 List<PersistentPreferredActivity> pprefs = ppir != null 5971 ? ppir.queryIntent(intent, resolvedType, 5972 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 5973 userId) 5974 : null; 5975 if (pprefs != null && pprefs.size() > 0) { 5976 final int M = pprefs.size(); 5977 for (int i=0; i<M; i++) { 5978 final PersistentPreferredActivity ppa = pprefs.get(i); 5979 if (DEBUG_PREFERRED || debug) { 5980 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5981 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5982 + "\n component=" + ppa.mComponent); 5983 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5984 } 5985 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5986 flags | MATCH_DISABLED_COMPONENTS, userId); 5987 if (DEBUG_PREFERRED || debug) { 5988 Slog.v(TAG, "Found persistent preferred activity:"); 5989 if (ai != null) { 5990 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5991 } else { 5992 Slog.v(TAG, " null"); 5993 } 5994 } 5995 if (ai == null) { 5996 // This previously registered persistent preferred activity 5997 // component is no longer known. Ignore it and do NOT remove it. 5998 continue; 5999 } 6000 for (int j=0; j<N; j++) { 6001 final ResolveInfo ri = query.get(j); 6002 if (!ri.activityInfo.applicationInfo.packageName 6003 .equals(ai.applicationInfo.packageName)) { 6004 continue; 6005 } 6006 if (!ri.activityInfo.name.equals(ai.name)) { 6007 continue; 6008 } 6009 // Found a persistent preference that can handle the intent. 6010 if (DEBUG_PREFERRED || debug) { 6011 Slog.v(TAG, "Returning persistent preferred activity: " + 6012 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6013 } 6014 return ri; 6015 } 6016 } 6017 } 6018 return null; 6019 } 6020 6021 // TODO: handle preferred activities missing while user has amnesia 6022 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 6023 List<ResolveInfo> query, int priority, boolean always, 6024 boolean removeMatches, boolean debug, int userId) { 6025 if (!sUserManager.exists(userId)) return null; 6026 final int callingUid = Binder.getCallingUid(); 6027 flags = updateFlagsForResolve( 6028 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6029 intent = updateIntentForResolve(intent); 6030 // writer 6031 synchronized (mPackages) { 6032 // Try to find a matching persistent preferred activity. 6033 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6034 debug, userId); 6035 6036 // If a persistent preferred activity matched, use it. 6037 if (pri != null) { 6038 return pri; 6039 } 6040 6041 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6042 // Get the list of preferred activities that handle the intent 6043 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6044 List<PreferredActivity> prefs = pir != null 6045 ? pir.queryIntent(intent, resolvedType, 6046 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6047 userId) 6048 : null; 6049 if (prefs != null && prefs.size() > 0) { 6050 boolean changed = false; 6051 try { 6052 // First figure out how good the original match set is. 6053 // We will only allow preferred activities that came 6054 // from the same match quality. 6055 int match = 0; 6056 6057 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6058 6059 final int N = query.size(); 6060 for (int j=0; j<N; j++) { 6061 final ResolveInfo ri = query.get(j); 6062 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6063 + ": 0x" + Integer.toHexString(match)); 6064 if (ri.match > match) { 6065 match = ri.match; 6066 } 6067 } 6068 6069 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6070 + Integer.toHexString(match)); 6071 6072 match &= IntentFilter.MATCH_CATEGORY_MASK; 6073 final int M = prefs.size(); 6074 for (int i=0; i<M; i++) { 6075 final PreferredActivity pa = prefs.get(i); 6076 if (DEBUG_PREFERRED || debug) { 6077 Slog.v(TAG, "Checking PreferredActivity ds=" 6078 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6079 + "\n component=" + pa.mPref.mComponent); 6080 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6081 } 6082 if (pa.mPref.mMatch != match) { 6083 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6084 + Integer.toHexString(pa.mPref.mMatch)); 6085 continue; 6086 } 6087 // If it's not an "always" type preferred activity and that's what we're 6088 // looking for, skip it. 6089 if (always && !pa.mPref.mAlways) { 6090 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6091 continue; 6092 } 6093 final ActivityInfo ai = getActivityInfo( 6094 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6095 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6096 userId); 6097 if (DEBUG_PREFERRED || debug) { 6098 Slog.v(TAG, "Found preferred activity:"); 6099 if (ai != null) { 6100 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6101 } else { 6102 Slog.v(TAG, " null"); 6103 } 6104 } 6105 if (ai == null) { 6106 // This previously registered preferred activity 6107 // component is no longer known. Most likely an update 6108 // to the app was installed and in the new version this 6109 // component no longer exists. Clean it up by removing 6110 // it from the preferred activities list, and skip it. 6111 Slog.w(TAG, "Removing dangling preferred activity: " 6112 + pa.mPref.mComponent); 6113 pir.removeFilter(pa); 6114 changed = true; 6115 continue; 6116 } 6117 for (int j=0; j<N; j++) { 6118 final ResolveInfo ri = query.get(j); 6119 if (!ri.activityInfo.applicationInfo.packageName 6120 .equals(ai.applicationInfo.packageName)) { 6121 continue; 6122 } 6123 if (!ri.activityInfo.name.equals(ai.name)) { 6124 continue; 6125 } 6126 6127 if (removeMatches) { 6128 pir.removeFilter(pa); 6129 changed = true; 6130 if (DEBUG_PREFERRED) { 6131 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6132 } 6133 break; 6134 } 6135 6136 // Okay we found a previously set preferred or last chosen app. 6137 // If the result set is different from when this 6138 // was created, and is not a subset of the preferred set, we need to 6139 // clear it and re-ask the user their preference, if we're looking for 6140 // an "always" type entry. 6141 if (always && !pa.mPref.sameSet(query)) { 6142 if (pa.mPref.isSuperset(query)) { 6143 // some components of the set are no longer present in 6144 // the query, but the preferred activity can still be reused 6145 if (DEBUG_PREFERRED) { 6146 Slog.i(TAG, "Result set changed, but PreferredActivity is" 6147 + " still valid as only non-preferred components" 6148 + " were removed for " + intent + " type " 6149 + resolvedType); 6150 } 6151 // remove obsolete components and re-add the up-to-date filter 6152 PreferredActivity freshPa = new PreferredActivity(pa, 6153 pa.mPref.mMatch, 6154 pa.mPref.discardObsoleteComponents(query), 6155 pa.mPref.mComponent, 6156 pa.mPref.mAlways); 6157 pir.removeFilter(pa); 6158 pir.addFilter(freshPa); 6159 changed = true; 6160 } else { 6161 Slog.i(TAG, 6162 "Result set changed, dropping preferred activity for " 6163 + intent + " type " + resolvedType); 6164 if (DEBUG_PREFERRED) { 6165 Slog.v(TAG, "Removing preferred activity since set changed " 6166 + pa.mPref.mComponent); 6167 } 6168 pir.removeFilter(pa); 6169 // Re-add the filter as a "last chosen" entry (!always) 6170 PreferredActivity lastChosen = new PreferredActivity( 6171 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 6172 pir.addFilter(lastChosen); 6173 changed = true; 6174 return null; 6175 } 6176 } 6177 6178 // Yay! Either the set matched or we're looking for the last chosen 6179 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 6180 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6181 return ri; 6182 } 6183 } 6184 } finally { 6185 if (changed) { 6186 if (DEBUG_PREFERRED) { 6187 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 6188 } 6189 scheduleWritePackageRestrictionsLocked(userId); 6190 } 6191 } 6192 } 6193 } 6194 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 6195 return null; 6196 } 6197 6198 /* 6199 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 6200 */ 6201 @Override 6202 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 6203 int targetUserId) { 6204 mContext.enforceCallingOrSelfPermission( 6205 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 6206 List<CrossProfileIntentFilter> matches = 6207 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 6208 if (matches != null) { 6209 int size = matches.size(); 6210 for (int i = 0; i < size; i++) { 6211 if (matches.get(i).getTargetUserId() == targetUserId) return true; 6212 } 6213 } 6214 if (hasWebURI(intent)) { 6215 // cross-profile app linking works only towards the parent. 6216 final int callingUid = Binder.getCallingUid(); 6217 final UserInfo parent = getProfileParent(sourceUserId); 6218 synchronized(mPackages) { 6219 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 6220 false /*includeInstantApps*/); 6221 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 6222 intent, resolvedType, flags, sourceUserId, parent.id); 6223 return xpDomainInfo != null; 6224 } 6225 } 6226 return false; 6227 } 6228 6229 private UserInfo getProfileParent(int userId) { 6230 final long identity = Binder.clearCallingIdentity(); 6231 try { 6232 return sUserManager.getProfileParent(userId); 6233 } finally { 6234 Binder.restoreCallingIdentity(identity); 6235 } 6236 } 6237 6238 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 6239 String resolvedType, int userId) { 6240 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 6241 if (resolver != null) { 6242 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 6243 } 6244 return null; 6245 } 6246 6247 @Override 6248 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 6249 String resolvedType, int flags, int userId) { 6250 try { 6251 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6252 6253 return new ParceledListSlice<>( 6254 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 6255 } finally { 6256 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6257 } 6258 } 6259 6260 /** 6261 * Returns the package name of the calling Uid if it's an instant app. If it isn't 6262 * instant, returns {@code null}. 6263 */ 6264 private String getInstantAppPackageName(int callingUid) { 6265 synchronized (mPackages) { 6266 // If the caller is an isolated app use the owner's uid for the lookup. 6267 if (Process.isIsolated(callingUid)) { 6268 callingUid = mIsolatedOwners.get(callingUid); 6269 } 6270 final int appId = UserHandle.getAppId(callingUid); 6271 final Object obj = mSettings.getUserIdLPr(appId); 6272 if (obj instanceof PackageSetting) { 6273 final PackageSetting ps = (PackageSetting) obj; 6274 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 6275 return isInstantApp ? ps.pkg.packageName : null; 6276 } 6277 } 6278 return null; 6279 } 6280 6281 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6282 String resolvedType, int flags, int userId) { 6283 return queryIntentActivitiesInternal( 6284 intent, resolvedType, flags, Binder.getCallingUid(), userId, 6285 false /*resolveForStart*/, true /*allowDynamicSplits*/); 6286 } 6287 6288 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 6289 String resolvedType, int flags, int filterCallingUid, int userId, 6290 boolean resolveForStart, boolean allowDynamicSplits) { 6291 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6292 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 6293 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6294 false /* requireFullPermission */, false /* checkShell */, 6295 "query intent activities"); 6296 final String pkgName = intent.getPackage(); 6297 ComponentName comp = intent.getComponent(); 6298 if (comp == null) { 6299 if (intent.getSelector() != null) { 6300 intent = intent.getSelector(); 6301 comp = intent.getComponent(); 6302 } 6303 } 6304 6305 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 6306 comp != null || pkgName != null /*onlyExposedExplicitly*/); 6307 if (comp != null) { 6308 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6309 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 6310 if (ai != null) { 6311 // When specifying an explicit component, we prevent the activity from being 6312 // used when either 1) the calling package is normal and the activity is within 6313 // an ephemeral application or 2) the calling package is ephemeral and the 6314 // activity is not visible to ephemeral applications. 6315 final boolean matchInstantApp = 6316 (flags & PackageManager.MATCH_INSTANT) != 0; 6317 final boolean matchVisibleToInstantAppOnly = 6318 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 6319 final boolean matchExplicitlyVisibleOnly = 6320 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 6321 final boolean isCallerInstantApp = 6322 instantAppPkgName != null; 6323 final boolean isTargetSameInstantApp = 6324 comp.getPackageName().equals(instantAppPkgName); 6325 final boolean isTargetInstantApp = 6326 (ai.applicationInfo.privateFlags 6327 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 6328 final boolean isTargetVisibleToInstantApp = 6329 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 6330 final boolean isTargetExplicitlyVisibleToInstantApp = 6331 isTargetVisibleToInstantApp 6332 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 6333 final boolean isTargetHiddenFromInstantApp = 6334 !isTargetVisibleToInstantApp 6335 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 6336 final boolean blockResolution = 6337 !isTargetSameInstantApp 6338 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 6339 || (matchVisibleToInstantAppOnly && isCallerInstantApp 6340 && isTargetHiddenFromInstantApp)); 6341 if (!blockResolution) { 6342 final ResolveInfo ri = new ResolveInfo(); 6343 ri.activityInfo = ai; 6344 list.add(ri); 6345 } 6346 } 6347 return applyPostResolutionFilter( 6348 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6349 } 6350 6351 // reader 6352 boolean sortResult = false; 6353 boolean addEphemeral = false; 6354 List<ResolveInfo> result; 6355 final boolean ephemeralDisabled = isEphemeralDisabled(); 6356 synchronized (mPackages) { 6357 if (pkgName == null) { 6358 List<CrossProfileIntentFilter> matchingFilters = 6359 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 6360 // Check for results that need to skip the current profile. 6361 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 6362 resolvedType, flags, userId); 6363 if (xpResolveInfo != null) { 6364 List<ResolveInfo> xpResult = new ArrayList<ResolveInfo>(1); 6365 xpResult.add(xpResolveInfo); 6366 return applyPostResolutionFilter( 6367 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 6368 allowDynamicSplits, filterCallingUid, userId); 6369 } 6370 6371 // Check for results in the current profile. 6372 result = filterIfNotSystemUser(mActivities.queryIntent( 6373 intent, resolvedType, flags, userId), userId); 6374 addEphemeral = !ephemeralDisabled 6375 && isInstantAppAllowed(intent, result, userId, false /*skipPackageCheck*/); 6376 // Check for cross profile results. 6377 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 6378 xpResolveInfo = queryCrossProfileIntents( 6379 matchingFilters, intent, resolvedType, flags, userId, 6380 hasNonNegativePriorityResult); 6381 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 6382 boolean isVisibleToUser = filterIfNotSystemUser( 6383 Collections.singletonList(xpResolveInfo), userId).size() > 0; 6384 if (isVisibleToUser) { 6385 result.add(xpResolveInfo); 6386 sortResult = true; 6387 } 6388 } 6389 if (hasWebURI(intent)) { 6390 CrossProfileDomainInfo xpDomainInfo = null; 6391 final UserInfo parent = getProfileParent(userId); 6392 if (parent != null) { 6393 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 6394 flags, userId, parent.id); 6395 } 6396 if (xpDomainInfo != null) { 6397 if (xpResolveInfo != null) { 6398 // If we didn't remove it, the cross-profile ResolveInfo would be twice 6399 // in the result. 6400 result.remove(xpResolveInfo); 6401 } 6402 if (result.size() == 0 && !addEphemeral) { 6403 // No result in current profile, but found candidate in parent user. 6404 // And we are not going to add emphemeral app, so we can return the 6405 // result straight away. 6406 result.add(xpDomainInfo.resolveInfo); 6407 return applyPostResolutionFilter(result, instantAppPkgName, 6408 allowDynamicSplits, filterCallingUid, userId); 6409 } 6410 } else if (result.size() <= 1 && !addEphemeral) { 6411 // No result in parent user and <= 1 result in current profile, and we 6412 // are not going to add emphemeral app, so we can return the result without 6413 // further processing. 6414 return applyPostResolutionFilter(result, instantAppPkgName, 6415 allowDynamicSplits, filterCallingUid, userId); 6416 } 6417 // We have more than one candidate (combining results from current and parent 6418 // profile), so we need filtering and sorting. 6419 result = filterCandidatesWithDomainPreferredActivitiesLPr( 6420 intent, flags, result, xpDomainInfo, userId); 6421 sortResult = true; 6422 } 6423 } else { 6424 final PackageParser.Package pkg = mPackages.get(pkgName); 6425 result = null; 6426 if (pkg != null) { 6427 result = filterIfNotSystemUser( 6428 mActivities.queryIntentForPackage( 6429 intent, resolvedType, flags, pkg.activities, userId), 6430 userId); 6431 } 6432 if (result == null || result.size() == 0) { 6433 // the caller wants to resolve for a particular package; however, there 6434 // were no installed results, so, try to find an ephemeral result 6435 addEphemeral = !ephemeralDisabled 6436 && isInstantAppAllowed( 6437 intent, null /*result*/, userId, true /*skipPackageCheck*/); 6438 if (result == null) { 6439 result = new ArrayList<>(); 6440 } 6441 } 6442 } 6443 } 6444 if (addEphemeral) { 6445 result = maybeAddInstantAppInstaller( 6446 result, intent, resolvedType, flags, userId, resolveForStart); 6447 } 6448 if (sortResult) { 6449 Collections.sort(result, mResolvePrioritySorter); 6450 } 6451 return applyPostResolutionFilter( 6452 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, userId); 6453 } 6454 6455 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 6456 String resolvedType, int flags, int userId, boolean resolveForStart) { 6457 // first, check to see if we've got an instant app already installed 6458 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 6459 ResolveInfo localInstantApp = null; 6460 boolean blockResolution = false; 6461 if (!alreadyResolvedLocally) { 6462 final List<ResolveInfo> instantApps = mActivities.queryIntent(intent, resolvedType, 6463 flags 6464 | PackageManager.GET_RESOLVED_FILTER 6465 | PackageManager.MATCH_INSTANT 6466 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 6467 userId); 6468 for (int i = instantApps.size() - 1; i >= 0; --i) { 6469 final ResolveInfo info = instantApps.get(i); 6470 final String packageName = info.activityInfo.packageName; 6471 final PackageSetting ps = mSettings.mPackages.get(packageName); 6472 if (ps.getInstantApp(userId)) { 6473 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6474 final int status = (int)(packedStatus >> 32); 6475 final int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6476 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6477 // there's a local instant application installed, but, the user has 6478 // chosen to never use it; skip resolution and don't acknowledge 6479 // an instant application is even available 6480 if (DEBUG_EPHEMERAL) { 6481 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 6482 } 6483 blockResolution = true; 6484 break; 6485 } else { 6486 // we have a locally installed instant application; skip resolution 6487 // but acknowledge there's an instant application available 6488 if (DEBUG_EPHEMERAL) { 6489 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 6490 } 6491 localInstantApp = info; 6492 break; 6493 } 6494 } 6495 } 6496 } 6497 // no app installed, let's see if one's available 6498 AuxiliaryResolveInfo auxiliaryResponse = null; 6499 if (!blockResolution) { 6500 if (localInstantApp == null) { 6501 // we don't have an instant app locally, resolve externally 6502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 6503 final InstantAppRequest requestObject = new InstantAppRequest( 6504 null /*responseObj*/, intent /*origIntent*/, resolvedType, 6505 null /*callingPackage*/, userId, null /*verificationBundle*/, 6506 resolveForStart); 6507 auxiliaryResponse = 6508 InstantAppResolver.doInstantAppResolutionPhaseOne( 6509 mContext, mInstantAppResolverConnection, requestObject); 6510 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6511 } else { 6512 // we have an instant application locally, but, we can't admit that since 6513 // callers shouldn't be able to determine prior browsing. create a dummy 6514 // auxiliary response so the downstream code behaves as if there's an 6515 // instant application available externally. when it comes time to start 6516 // the instant application, we'll do the right thing. 6517 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 6518 auxiliaryResponse = new AuxiliaryResolveInfo( 6519 ai.packageName, null /*splitName*/, null /*failureActivity*/, 6520 ai.versionCode, null /*failureIntent*/); 6521 } 6522 } 6523 if (auxiliaryResponse != null) { 6524 if (DEBUG_EPHEMERAL) { 6525 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 6526 } 6527 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 6528 final PackageSetting ps = 6529 mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 6530 if (ps != null) { 6531 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 6532 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 6533 ephemeralInstaller.activityInfo.launchToken = auxiliaryResponse.token; 6534 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 6535 // make sure this resolver is the default 6536 ephemeralInstaller.isDefault = true; 6537 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6538 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6539 // add a non-generic filter 6540 ephemeralInstaller.filter = new IntentFilter(intent.getAction()); 6541 ephemeralInstaller.filter.addDataPath( 6542 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 6543 ephemeralInstaller.isInstantAppAvailable = true; 6544 result.add(ephemeralInstaller); 6545 } 6546 } 6547 return result; 6548 } 6549 6550 private static class CrossProfileDomainInfo { 6551 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 6552 ResolveInfo resolveInfo; 6553 /* Best domain verification status of the activities found in the other profile */ 6554 int bestDomainVerificationStatus; 6555 } 6556 6557 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 6558 String resolvedType, int flags, int sourceUserId, int parentUserId) { 6559 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 6560 sourceUserId)) { 6561 return null; 6562 } 6563 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 6564 resolvedType, flags, parentUserId); 6565 6566 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 6567 return null; 6568 } 6569 CrossProfileDomainInfo result = null; 6570 int size = resultTargetUser.size(); 6571 for (int i = 0; i < size; i++) { 6572 ResolveInfo riTargetUser = resultTargetUser.get(i); 6573 // Intent filter verification is only for filters that specify a host. So don't return 6574 // those that handle all web uris. 6575 if (riTargetUser.handleAllWebDataURI) { 6576 continue; 6577 } 6578 String packageName = riTargetUser.activityInfo.packageName; 6579 PackageSetting ps = mSettings.mPackages.get(packageName); 6580 if (ps == null) { 6581 continue; 6582 } 6583 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 6584 int status = (int)(verificationState >> 32); 6585 if (result == null) { 6586 result = new CrossProfileDomainInfo(); 6587 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 6588 sourceUserId, parentUserId); 6589 result.bestDomainVerificationStatus = status; 6590 } else { 6591 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 6592 result.bestDomainVerificationStatus); 6593 } 6594 } 6595 // Don't consider matches with status NEVER across profiles. 6596 if (result != null && result.bestDomainVerificationStatus 6597 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6598 return null; 6599 } 6600 return result; 6601 } 6602 6603 /** 6604 * Verification statuses are ordered from the worse to the best, except for 6605 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 6606 */ 6607 private int bestDomainVerificationStatus(int status1, int status2) { 6608 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6609 return status2; 6610 } 6611 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6612 return status1; 6613 } 6614 return (int) MathUtils.max(status1, status2); 6615 } 6616 6617 private boolean isUserEnabled(int userId) { 6618 long callingId = Binder.clearCallingIdentity(); 6619 try { 6620 UserInfo userInfo = sUserManager.getUserInfo(userId); 6621 return userInfo != null && userInfo.isEnabled(); 6622 } finally { 6623 Binder.restoreCallingIdentity(callingId); 6624 } 6625 } 6626 6627 /** 6628 * Filter out activities with systemUserOnly flag set, when current user is not System. 6629 * 6630 * @return filtered list 6631 */ 6632 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 6633 if (userId == UserHandle.USER_SYSTEM) { 6634 return resolveInfos; 6635 } 6636 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6637 ResolveInfo info = resolveInfos.get(i); 6638 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 6639 resolveInfos.remove(i); 6640 } 6641 } 6642 return resolveInfos; 6643 } 6644 6645 /** 6646 * Filters out ephemeral activities. 6647 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 6648 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 6649 * 6650 * @param resolveInfos The pre-filtered list of resolved activities 6651 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 6652 * is performed. 6653 * @return A filtered list of resolved activities. 6654 */ 6655 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 6656 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, int userId) { 6657 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 6658 final ResolveInfo info = resolveInfos.get(i); 6659 // allow activities that are defined in the provided package 6660 if (allowDynamicSplits 6661 && info.activityInfo.splitName != null 6662 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 6663 info.activityInfo.splitName)) { 6664 if (mInstantAppInstallerInfo == null) { 6665 if (DEBUG_INSTALL) { 6666 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 6667 } 6668 resolveInfos.remove(i); 6669 continue; 6670 } 6671 // requested activity is defined in a split that hasn't been installed yet. 6672 // add the installer to the resolve list 6673 if (DEBUG_INSTALL) { 6674 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 6675 } 6676 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 6677 final ComponentName installFailureActivity = findInstallFailureActivity( 6678 info.activityInfo.packageName, filterCallingUid, userId); 6679 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 6680 info.activityInfo.packageName, info.activityInfo.splitName, 6681 installFailureActivity, 6682 info.activityInfo.applicationInfo.versionCode, 6683 null /*failureIntent*/); 6684 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 6685 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 6686 // add a non-generic filter 6687 installerInfo.filter = new IntentFilter(); 6688 6689 // This resolve info may appear in the chooser UI, so let us make it 6690 // look as the one it replaces as far as the user is concerned which 6691 // requires loading the correct label and icon for the resolve info. 6692 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 6693 installerInfo.labelRes = info.resolveLabelResId(); 6694 installerInfo.icon = info.resolveIconResId(); 6695 6696 // propagate priority/preferred order/default 6697 installerInfo.priority = info.priority; 6698 installerInfo.preferredOrder = info.preferredOrder; 6699 installerInfo.isDefault = info.isDefault; 6700 resolveInfos.set(i, installerInfo); 6701 continue; 6702 } 6703 // caller is a full app, don't need to apply any other filtering 6704 if (ephemeralPkgName == null) { 6705 continue; 6706 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 6707 // caller is same app; don't need to apply any other filtering 6708 continue; 6709 } 6710 // allow activities that have been explicitly exposed to ephemeral apps 6711 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 6712 if (!isEphemeralApp 6713 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 6714 continue; 6715 } 6716 resolveInfos.remove(i); 6717 } 6718 return resolveInfos; 6719 } 6720 6721 /** 6722 * Returns the activity component that can handle install failures. 6723 * <p>By default, the instant application installer handles failures. However, an 6724 * application may want to handle failures on its own. Applications do this by 6725 * creating an activity with an intent filter that handles the action 6726 * {@link Intent#ACTION_INSTALL_FAILURE}. 6727 */ 6728 private @Nullable ComponentName findInstallFailureActivity( 6729 String packageName, int filterCallingUid, int userId) { 6730 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 6731 failureActivityIntent.setPackage(packageName); 6732 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 6733 final List<ResolveInfo> result = queryIntentActivitiesInternal( 6734 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 6735 false /*resolveForStart*/, false /*allowDynamicSplits*/); 6736 final int NR = result.size(); 6737 if (NR > 0) { 6738 for (int i = 0; i < NR; i++) { 6739 final ResolveInfo info = result.get(i); 6740 if (info.activityInfo.splitName != null) { 6741 continue; 6742 } 6743 return new ComponentName(packageName, info.activityInfo.name); 6744 } 6745 } 6746 return null; 6747 } 6748 6749 /** 6750 * @param resolveInfos list of resolve infos in descending priority order 6751 * @return if the list contains a resolve info with non-negative priority 6752 */ 6753 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 6754 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 6755 } 6756 6757 private static boolean hasWebURI(Intent intent) { 6758 if (intent.getData() == null) { 6759 return false; 6760 } 6761 final String scheme = intent.getScheme(); 6762 if (TextUtils.isEmpty(scheme)) { 6763 return false; 6764 } 6765 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 6766 } 6767 6768 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 6769 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 6770 int userId) { 6771 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 6772 6773 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6774 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 6775 candidates.size()); 6776 } 6777 6778 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 6779 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 6780 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 6781 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 6782 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 6783 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 6784 6785 synchronized (mPackages) { 6786 final int count = candidates.size(); 6787 // First, try to use linked apps. Partition the candidates into four lists: 6788 // one for the final results, one for the "do not use ever", one for "undefined status" 6789 // and finally one for "browser app type". 6790 for (int n=0; n<count; n++) { 6791 ResolveInfo info = candidates.get(n); 6792 String packageName = info.activityInfo.packageName; 6793 PackageSetting ps = mSettings.mPackages.get(packageName); 6794 if (ps != null) { 6795 // Add to the special match all list (Browser use case) 6796 if (info.handleAllWebDataURI) { 6797 matchAllList.add(info); 6798 continue; 6799 } 6800 // Try to get the status from User settings first 6801 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6802 int status = (int)(packedStatus >> 32); 6803 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 6804 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 6805 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6806 Slog.i(TAG, " + always: " + info.activityInfo.packageName 6807 + " : linkgen=" + linkGeneration); 6808 } 6809 // Use link-enabled generation as preferredOrder, i.e. 6810 // prefer newly-enabled over earlier-enabled. 6811 info.preferredOrder = linkGeneration; 6812 alwaysList.add(info); 6813 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 6814 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6815 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 6816 } 6817 neverList.add(info); 6818 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6819 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6820 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 6821 } 6822 alwaysAskList.add(info); 6823 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 6824 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 6825 if (DEBUG_DOMAIN_VERIFICATION || debug) { 6826 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 6827 } 6828 undefinedList.add(info); 6829 } 6830 } 6831 } 6832 6833 // We'll want to include browser possibilities in a few cases 6834 boolean includeBrowser = false; 6835 6836 // First try to add the "always" resolution(s) for the current user, if any 6837 if (alwaysList.size() > 0) { 6838 result.addAll(alwaysList); 6839 } else { 6840 // Add all undefined apps as we want them to appear in the disambiguation dialog. 6841 result.addAll(undefinedList); 6842 // Maybe add one for the other profile. 6843 if (xpDomainInfo != null && ( 6844 xpDomainInfo.bestDomainVerificationStatus 6845 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 6846 result.add(xpDomainInfo.resolveInfo); 6847 } 6848 includeBrowser = true; 6849 } 6850 6851 // The presence of any 'always ask' alternatives means we'll also offer browsers. 6852 // If there were 'always' entries their preferred order has been set, so we also 6853 // back that off to make the alternatives equivalent 6854 if (alwaysAskList.size() > 0) { 6855 for (ResolveInfo i : result) { 6856 i.preferredOrder = 0; 6857 } 6858 result.addAll(alwaysAskList); 6859 includeBrowser = true; 6860 } 6861 6862 if (includeBrowser) { 6863 // Also add browsers (all of them or only the default one) 6864 if (DEBUG_DOMAIN_VERIFICATION) { 6865 Slog.v(TAG, " ...including browsers in candidate set"); 6866 } 6867 if ((matchFlags & MATCH_ALL) != 0) { 6868 result.addAll(matchAllList); 6869 } else { 6870 // Browser/generic handling case. If there's a default browser, go straight 6871 // to that (but only if there is no other higher-priority match). 6872 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 6873 int maxMatchPrio = 0; 6874 ResolveInfo defaultBrowserMatch = null; 6875 final int numCandidates = matchAllList.size(); 6876 for (int n = 0; n < numCandidates; n++) { 6877 ResolveInfo info = matchAllList.get(n); 6878 // track the highest overall match priority... 6879 if (info.priority > maxMatchPrio) { 6880 maxMatchPrio = info.priority; 6881 } 6882 // ...and the highest-priority default browser match 6883 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 6884 if (defaultBrowserMatch == null 6885 || (defaultBrowserMatch.priority < info.priority)) { 6886 if (debug) { 6887 Slog.v(TAG, "Considering default browser match " + info); 6888 } 6889 defaultBrowserMatch = info; 6890 } 6891 } 6892 } 6893 if (defaultBrowserMatch != null 6894 && defaultBrowserMatch.priority >= maxMatchPrio 6895 && !TextUtils.isEmpty(defaultBrowserPackageName)) 6896 { 6897 if (debug) { 6898 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 6899 } 6900 result.add(defaultBrowserMatch); 6901 } else { 6902 result.addAll(matchAllList); 6903 } 6904 } 6905 6906 // If there is nothing selected, add all candidates and remove the ones that the user 6907 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 6908 if (result.size() == 0) { 6909 result.addAll(candidates); 6910 result.removeAll(neverList); 6911 } 6912 } 6913 } 6914 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 6915 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 6916 result.size()); 6917 for (ResolveInfo info : result) { 6918 Slog.v(TAG, " + " + info.activityInfo); 6919 } 6920 } 6921 return result; 6922 } 6923 6924 // Returns a packed value as a long: 6925 // 6926 // high 'int'-sized word: link status: undefined/ask/never/always. 6927 // low 'int'-sized word: relative priority among 'always' results. 6928 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 6929 long result = ps.getDomainVerificationStatusForUser(userId); 6930 // if none available, get the master status 6931 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 6932 if (ps.getIntentFilterVerificationInfo() != null) { 6933 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 6934 } 6935 } 6936 return result; 6937 } 6938 6939 private ResolveInfo querySkipCurrentProfileIntents( 6940 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6941 int flags, int sourceUserId) { 6942 if (matchingFilters != null) { 6943 int size = matchingFilters.size(); 6944 for (int i = 0; i < size; i ++) { 6945 CrossProfileIntentFilter filter = matchingFilters.get(i); 6946 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 6947 // Checking if there are activities in the target user that can handle the 6948 // intent. 6949 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6950 resolvedType, flags, sourceUserId); 6951 if (resolveInfo != null) { 6952 return resolveInfo; 6953 } 6954 } 6955 } 6956 } 6957 return null; 6958 } 6959 6960 // Return matching ResolveInfo in target user if any. 6961 private ResolveInfo queryCrossProfileIntents( 6962 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 6963 int flags, int sourceUserId, boolean matchInCurrentProfile) { 6964 if (matchingFilters != null) { 6965 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 6966 // match the same intent. For performance reasons, it is better not to 6967 // run queryIntent twice for the same userId 6968 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 6969 int size = matchingFilters.size(); 6970 for (int i = 0; i < size; i++) { 6971 CrossProfileIntentFilter filter = matchingFilters.get(i); 6972 int targetUserId = filter.getTargetUserId(); 6973 boolean skipCurrentProfile = 6974 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 6975 boolean skipCurrentProfileIfNoMatchFound = 6976 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 6977 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 6978 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 6979 // Checking if there are activities in the target user that can handle the 6980 // intent. 6981 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 6982 resolvedType, flags, sourceUserId); 6983 if (resolveInfo != null) return resolveInfo; 6984 alreadyTriedUserIds.put(targetUserId, true); 6985 } 6986 } 6987 } 6988 return null; 6989 } 6990 6991 /** 6992 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 6993 * will forward the intent to the filter's target user. 6994 * Otherwise, returns null. 6995 */ 6996 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 6997 String resolvedType, int flags, int sourceUserId) { 6998 int targetUserId = filter.getTargetUserId(); 6999 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 7000 resolvedType, flags, targetUserId); 7001 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7002 // If all the matches in the target profile are suspended, return null. 7003 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7004 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7005 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7006 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7007 targetUserId); 7008 } 7009 } 7010 } 7011 return null; 7012 } 7013 7014 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7015 int sourceUserId, int targetUserId) { 7016 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7017 long ident = Binder.clearCallingIdentity(); 7018 boolean targetIsProfile; 7019 try { 7020 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7021 } finally { 7022 Binder.restoreCallingIdentity(ident); 7023 } 7024 String className; 7025 if (targetIsProfile) { 7026 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7027 } else { 7028 className = FORWARD_INTENT_TO_PARENT; 7029 } 7030 ComponentName forwardingActivityComponentName = new ComponentName( 7031 mAndroidApplication.packageName, className); 7032 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7033 sourceUserId); 7034 if (!targetIsProfile) { 7035 forwardingActivityInfo.showUserIcon = targetUserId; 7036 forwardingResolveInfo.noResourceId = true; 7037 } 7038 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7039 forwardingResolveInfo.priority = 0; 7040 forwardingResolveInfo.preferredOrder = 0; 7041 forwardingResolveInfo.match = 0; 7042 forwardingResolveInfo.isDefault = true; 7043 forwardingResolveInfo.filter = filter; 7044 forwardingResolveInfo.targetUserId = targetUserId; 7045 return forwardingResolveInfo; 7046 } 7047 7048 @Override 7049 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7050 Intent[] specifics, String[] specificTypes, Intent intent, 7051 String resolvedType, int flags, int userId) { 7052 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7053 specificTypes, intent, resolvedType, flags, userId)); 7054 } 7055 7056 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7057 Intent[] specifics, String[] specificTypes, Intent intent, 7058 String resolvedType, int flags, int userId) { 7059 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7060 final int callingUid = Binder.getCallingUid(); 7061 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7062 false /*includeInstantApps*/); 7063 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7064 false /*requireFullPermission*/, false /*checkShell*/, 7065 "query intent activity options"); 7066 final String resultsAction = intent.getAction(); 7067 7068 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7069 | PackageManager.GET_RESOLVED_FILTER, userId); 7070 7071 if (DEBUG_INTENT_MATCHING) { 7072 Log.v(TAG, "Query " + intent + ": " + results); 7073 } 7074 7075 int specificsPos = 0; 7076 int N; 7077 7078 // todo: note that the algorithm used here is O(N^2). This 7079 // isn't a problem in our current environment, but if we start running 7080 // into situations where we have more than 5 or 10 matches then this 7081 // should probably be changed to something smarter... 7082 7083 // First we go through and resolve each of the specific items 7084 // that were supplied, taking care of removing any corresponding 7085 // duplicate items in the generic resolve list. 7086 if (specifics != null) { 7087 for (int i=0; i<specifics.length; i++) { 7088 final Intent sintent = specifics[i]; 7089 if (sintent == null) { 7090 continue; 7091 } 7092 7093 if (DEBUG_INTENT_MATCHING) { 7094 Log.v(TAG, "Specific #" + i + ": " + sintent); 7095 } 7096 7097 String action = sintent.getAction(); 7098 if (resultsAction != null && resultsAction.equals(action)) { 7099 // If this action was explicitly requested, then don't 7100 // remove things that have it. 7101 action = null; 7102 } 7103 7104 ResolveInfo ri = null; 7105 ActivityInfo ai = null; 7106 7107 ComponentName comp = sintent.getComponent(); 7108 if (comp == null) { 7109 ri = resolveIntent( 7110 sintent, 7111 specificTypes != null ? specificTypes[i] : null, 7112 flags, userId); 7113 if (ri == null) { 7114 continue; 7115 } 7116 if (ri == mResolveInfo) { 7117 // ACK! Must do something better with this. 7118 } 7119 ai = ri.activityInfo; 7120 comp = new ComponentName(ai.applicationInfo.packageName, 7121 ai.name); 7122 } else { 7123 ai = getActivityInfo(comp, flags, userId); 7124 if (ai == null) { 7125 continue; 7126 } 7127 } 7128 7129 // Look for any generic query activities that are duplicates 7130 // of this specific one, and remove them from the results. 7131 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7132 N = results.size(); 7133 int j; 7134 for (j=specificsPos; j<N; j++) { 7135 ResolveInfo sri = results.get(j); 7136 if ((sri.activityInfo.name.equals(comp.getClassName()) 7137 && sri.activityInfo.applicationInfo.packageName.equals( 7138 comp.getPackageName())) 7139 || (action != null && sri.filter.matchAction(action))) { 7140 results.remove(j); 7141 if (DEBUG_INTENT_MATCHING) Log.v( 7142 TAG, "Removing duplicate item from " + j 7143 + " due to specific " + specificsPos); 7144 if (ri == null) { 7145 ri = sri; 7146 } 7147 j--; 7148 N--; 7149 } 7150 } 7151 7152 // Add this specific item to its proper place. 7153 if (ri == null) { 7154 ri = new ResolveInfo(); 7155 ri.activityInfo = ai; 7156 } 7157 results.add(specificsPos, ri); 7158 ri.specificIndex = i; 7159 specificsPos++; 7160 } 7161 } 7162 7163 // Now we go through the remaining generic results and remove any 7164 // duplicate actions that are found here. 7165 N = results.size(); 7166 for (int i=specificsPos; i<N-1; i++) { 7167 final ResolveInfo rii = results.get(i); 7168 if (rii.filter == null) { 7169 continue; 7170 } 7171 7172 // Iterate over all of the actions of this result's intent 7173 // filter... typically this should be just one. 7174 final Iterator<String> it = rii.filter.actionsIterator(); 7175 if (it == null) { 7176 continue; 7177 } 7178 while (it.hasNext()) { 7179 final String action = it.next(); 7180 if (resultsAction != null && resultsAction.equals(action)) { 7181 // If this action was explicitly requested, then don't 7182 // remove things that have it. 7183 continue; 7184 } 7185 for (int j=i+1; j<N; j++) { 7186 final ResolveInfo rij = results.get(j); 7187 if (rij.filter != null && rij.filter.hasAction(action)) { 7188 results.remove(j); 7189 if (DEBUG_INTENT_MATCHING) Log.v( 7190 TAG, "Removing duplicate item from " + j 7191 + " due to action " + action + " at " + i); 7192 j--; 7193 N--; 7194 } 7195 } 7196 } 7197 7198 // If the caller didn't request filter information, drop it now 7199 // so we don't have to marshall/unmarshall it. 7200 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7201 rii.filter = null; 7202 } 7203 } 7204 7205 // Filter out the caller activity if so requested. 7206 if (caller != null) { 7207 N = results.size(); 7208 for (int i=0; i<N; i++) { 7209 ActivityInfo ainfo = results.get(i).activityInfo; 7210 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 7211 && caller.getClassName().equals(ainfo.name)) { 7212 results.remove(i); 7213 break; 7214 } 7215 } 7216 } 7217 7218 // If the caller didn't request filter information, 7219 // drop them now so we don't have to 7220 // marshall/unmarshall it. 7221 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 7222 N = results.size(); 7223 for (int i=0; i<N; i++) { 7224 results.get(i).filter = null; 7225 } 7226 } 7227 7228 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 7229 return results; 7230 } 7231 7232 @Override 7233 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 7234 String resolvedType, int flags, int userId) { 7235 return new ParceledListSlice<>( 7236 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 7237 false /*allowDynamicSplits*/)); 7238 } 7239 7240 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 7241 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 7242 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7243 final int callingUid = Binder.getCallingUid(); 7244 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7245 false /*requireFullPermission*/, false /*checkShell*/, 7246 "query intent receivers"); 7247 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7248 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7249 false /*includeInstantApps*/); 7250 ComponentName comp = intent.getComponent(); 7251 if (comp == null) { 7252 if (intent.getSelector() != null) { 7253 intent = intent.getSelector(); 7254 comp = intent.getComponent(); 7255 } 7256 } 7257 if (comp != null) { 7258 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7259 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 7260 if (ai != null) { 7261 // When specifying an explicit component, we prevent the activity from being 7262 // used when either 1) the calling package is normal and the activity is within 7263 // an instant application or 2) the calling package is ephemeral and the 7264 // activity is not visible to instant applications. 7265 final boolean matchInstantApp = 7266 (flags & PackageManager.MATCH_INSTANT) != 0; 7267 final boolean matchVisibleToInstantAppOnly = 7268 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7269 final boolean matchExplicitlyVisibleOnly = 7270 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7271 final boolean isCallerInstantApp = 7272 instantAppPkgName != null; 7273 final boolean isTargetSameInstantApp = 7274 comp.getPackageName().equals(instantAppPkgName); 7275 final boolean isTargetInstantApp = 7276 (ai.applicationInfo.privateFlags 7277 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7278 final boolean isTargetVisibleToInstantApp = 7279 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7280 final boolean isTargetExplicitlyVisibleToInstantApp = 7281 isTargetVisibleToInstantApp 7282 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7283 final boolean isTargetHiddenFromInstantApp = 7284 !isTargetVisibleToInstantApp 7285 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7286 final boolean blockResolution = 7287 !isTargetSameInstantApp 7288 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7289 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7290 && isTargetHiddenFromInstantApp)); 7291 if (!blockResolution) { 7292 ResolveInfo ri = new ResolveInfo(); 7293 ri.activityInfo = ai; 7294 list.add(ri); 7295 } 7296 } 7297 return applyPostResolutionFilter( 7298 list, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7299 } 7300 7301 // reader 7302 synchronized (mPackages) { 7303 String pkgName = intent.getPackage(); 7304 if (pkgName == null) { 7305 final List<ResolveInfo> result = 7306 mReceivers.queryIntent(intent, resolvedType, flags, userId); 7307 return applyPostResolutionFilter( 7308 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7309 } 7310 final PackageParser.Package pkg = mPackages.get(pkgName); 7311 if (pkg != null) { 7312 final List<ResolveInfo> result = mReceivers.queryIntentForPackage( 7313 intent, resolvedType, flags, pkg.receivers, userId); 7314 return applyPostResolutionFilter( 7315 result, instantAppPkgName, allowDynamicSplits, callingUid, userId); 7316 } 7317 return Collections.emptyList(); 7318 } 7319 } 7320 7321 @Override 7322 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 7323 final int callingUid = Binder.getCallingUid(); 7324 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 7325 } 7326 7327 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 7328 int userId, int callingUid) { 7329 if (!sUserManager.exists(userId)) return null; 7330 flags = updateFlagsForResolve( 7331 flags, userId, intent, callingUid, false /*includeInstantApps*/); 7332 List<ResolveInfo> query = queryIntentServicesInternal( 7333 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 7334 if (query != null) { 7335 if (query.size() >= 1) { 7336 // If there is more than one service with the same priority, 7337 // just arbitrarily pick the first one. 7338 return query.get(0); 7339 } 7340 } 7341 return null; 7342 } 7343 7344 @Override 7345 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 7346 String resolvedType, int flags, int userId) { 7347 final int callingUid = Binder.getCallingUid(); 7348 return new ParceledListSlice<>(queryIntentServicesInternal( 7349 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 7350 } 7351 7352 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 7353 String resolvedType, int flags, int userId, int callingUid, 7354 boolean includeInstantApps) { 7355 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7356 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7357 false /*requireFullPermission*/, false /*checkShell*/, 7358 "query intent receivers"); 7359 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7360 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 7361 ComponentName comp = intent.getComponent(); 7362 if (comp == null) { 7363 if (intent.getSelector() != null) { 7364 intent = intent.getSelector(); 7365 comp = intent.getComponent(); 7366 } 7367 } 7368 if (comp != null) { 7369 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7370 final ServiceInfo si = getServiceInfo(comp, flags, userId); 7371 if (si != null) { 7372 // When specifying an explicit component, we prevent the service from being 7373 // used when either 1) the service is in an instant application and the 7374 // caller is not the same instant application or 2) the calling package is 7375 // ephemeral and the activity is not visible to ephemeral applications. 7376 final boolean matchInstantApp = 7377 (flags & PackageManager.MATCH_INSTANT) != 0; 7378 final boolean matchVisibleToInstantAppOnly = 7379 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7380 final boolean isCallerInstantApp = 7381 instantAppPkgName != null; 7382 final boolean isTargetSameInstantApp = 7383 comp.getPackageName().equals(instantAppPkgName); 7384 final boolean isTargetInstantApp = 7385 (si.applicationInfo.privateFlags 7386 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7387 final boolean isTargetHiddenFromInstantApp = 7388 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7389 final boolean blockResolution = 7390 !isTargetSameInstantApp 7391 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7392 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7393 && isTargetHiddenFromInstantApp)); 7394 if (!blockResolution) { 7395 final ResolveInfo ri = new ResolveInfo(); 7396 ri.serviceInfo = si; 7397 list.add(ri); 7398 } 7399 } 7400 return list; 7401 } 7402 7403 // reader 7404 synchronized (mPackages) { 7405 String pkgName = intent.getPackage(); 7406 if (pkgName == null) { 7407 return applyPostServiceResolutionFilter( 7408 mServices.queryIntent(intent, resolvedType, flags, userId), 7409 instantAppPkgName); 7410 } 7411 final PackageParser.Package pkg = mPackages.get(pkgName); 7412 if (pkg != null) { 7413 return applyPostServiceResolutionFilter( 7414 mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 7415 userId), 7416 instantAppPkgName); 7417 } 7418 return Collections.emptyList(); 7419 } 7420 } 7421 7422 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 7423 String instantAppPkgName) { 7424 if (instantAppPkgName == null) { 7425 return resolveInfos; 7426 } 7427 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7428 final ResolveInfo info = resolveInfos.get(i); 7429 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 7430 // allow services that are defined in the provided package 7431 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 7432 if (info.serviceInfo.splitName != null 7433 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 7434 info.serviceInfo.splitName)) { 7435 // requested service is defined in a split that hasn't been installed yet. 7436 // add the installer to the resolve list 7437 if (DEBUG_EPHEMERAL) { 7438 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7439 } 7440 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7441 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7442 info.serviceInfo.packageName, info.serviceInfo.splitName, 7443 null /*failureActivity*/, info.serviceInfo.applicationInfo.versionCode, 7444 null /*failureIntent*/); 7445 // make sure this resolver is the default 7446 installerInfo.isDefault = true; 7447 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7448 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7449 // add a non-generic filter 7450 installerInfo.filter = new IntentFilter(); 7451 // load resources from the correct package 7452 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7453 resolveInfos.set(i, installerInfo); 7454 } 7455 continue; 7456 } 7457 // allow services that have been explicitly exposed to ephemeral apps 7458 if (!isEphemeralApp 7459 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7460 continue; 7461 } 7462 resolveInfos.remove(i); 7463 } 7464 return resolveInfos; 7465 } 7466 7467 @Override 7468 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 7469 String resolvedType, int flags, int userId) { 7470 return new ParceledListSlice<>( 7471 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 7472 } 7473 7474 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 7475 Intent intent, String resolvedType, int flags, int userId) { 7476 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7477 final int callingUid = Binder.getCallingUid(); 7478 final String instantAppPkgName = getInstantAppPackageName(callingUid); 7479 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7480 false /*includeInstantApps*/); 7481 ComponentName comp = intent.getComponent(); 7482 if (comp == null) { 7483 if (intent.getSelector() != null) { 7484 intent = intent.getSelector(); 7485 comp = intent.getComponent(); 7486 } 7487 } 7488 if (comp != null) { 7489 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 7490 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 7491 if (pi != null) { 7492 // When specifying an explicit component, we prevent the provider from being 7493 // used when either 1) the provider is in an instant application and the 7494 // caller is not the same instant application or 2) the calling package is an 7495 // instant application and the provider is not visible to instant applications. 7496 final boolean matchInstantApp = 7497 (flags & PackageManager.MATCH_INSTANT) != 0; 7498 final boolean matchVisibleToInstantAppOnly = 7499 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7500 final boolean isCallerInstantApp = 7501 instantAppPkgName != null; 7502 final boolean isTargetSameInstantApp = 7503 comp.getPackageName().equals(instantAppPkgName); 7504 final boolean isTargetInstantApp = 7505 (pi.applicationInfo.privateFlags 7506 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7507 final boolean isTargetHiddenFromInstantApp = 7508 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 7509 final boolean blockResolution = 7510 !isTargetSameInstantApp 7511 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7512 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7513 && isTargetHiddenFromInstantApp)); 7514 if (!blockResolution) { 7515 final ResolveInfo ri = new ResolveInfo(); 7516 ri.providerInfo = pi; 7517 list.add(ri); 7518 } 7519 } 7520 return list; 7521 } 7522 7523 // reader 7524 synchronized (mPackages) { 7525 String pkgName = intent.getPackage(); 7526 if (pkgName == null) { 7527 return applyPostContentProviderResolutionFilter( 7528 mProviders.queryIntent(intent, resolvedType, flags, userId), 7529 instantAppPkgName); 7530 } 7531 final PackageParser.Package pkg = mPackages.get(pkgName); 7532 if (pkg != null) { 7533 return applyPostContentProviderResolutionFilter( 7534 mProviders.queryIntentForPackage( 7535 intent, resolvedType, flags, pkg.providers, userId), 7536 instantAppPkgName); 7537 } 7538 return Collections.emptyList(); 7539 } 7540 } 7541 7542 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 7543 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 7544 if (instantAppPkgName == null) { 7545 return resolveInfos; 7546 } 7547 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7548 final ResolveInfo info = resolveInfos.get(i); 7549 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 7550 // allow providers that are defined in the provided package 7551 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 7552 if (info.providerInfo.splitName != null 7553 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 7554 info.providerInfo.splitName)) { 7555 // requested provider is defined in a split that hasn't been installed yet. 7556 // add the installer to the resolve list 7557 if (DEBUG_EPHEMERAL) { 7558 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7559 } 7560 final ResolveInfo installerInfo = new ResolveInfo(mInstantAppInstallerInfo); 7561 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7562 info.providerInfo.packageName, info.providerInfo.splitName, 7563 null /*failureActivity*/, info.providerInfo.applicationInfo.versionCode, 7564 null /*failureIntent*/); 7565 // make sure this resolver is the default 7566 installerInfo.isDefault = true; 7567 installerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7568 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7569 // add a non-generic filter 7570 installerInfo.filter = new IntentFilter(); 7571 // load resources from the correct package 7572 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7573 resolveInfos.set(i, installerInfo); 7574 } 7575 continue; 7576 } 7577 // allow providers that have been explicitly exposed to instant applications 7578 if (!isEphemeralApp 7579 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7580 continue; 7581 } 7582 resolveInfos.remove(i); 7583 } 7584 return resolveInfos; 7585 } 7586 7587 @Override 7588 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 7589 final int callingUid = Binder.getCallingUid(); 7590 if (getInstantAppPackageName(callingUid) != null) { 7591 return ParceledListSlice.emptyList(); 7592 } 7593 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7594 flags = updateFlagsForPackage(flags, userId, null); 7595 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7596 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7597 true /* requireFullPermission */, false /* checkShell */, 7598 "get installed packages"); 7599 7600 // writer 7601 synchronized (mPackages) { 7602 ArrayList<PackageInfo> list; 7603 if (listUninstalled) { 7604 list = new ArrayList<>(mSettings.mPackages.size()); 7605 for (PackageSetting ps : mSettings.mPackages.values()) { 7606 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7607 continue; 7608 } 7609 if (filterAppAccessLPr(ps, callingUid, userId)) { 7610 continue; 7611 } 7612 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7613 if (pi != null) { 7614 list.add(pi); 7615 } 7616 } 7617 } else { 7618 list = new ArrayList<>(mPackages.size()); 7619 for (PackageParser.Package p : mPackages.values()) { 7620 final PackageSetting ps = (PackageSetting) p.mExtras; 7621 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7622 continue; 7623 } 7624 if (filterAppAccessLPr(ps, callingUid, userId)) { 7625 continue; 7626 } 7627 final PackageInfo pi = generatePackageInfo((PackageSetting) 7628 p.mExtras, flags, userId); 7629 if (pi != null) { 7630 list.add(pi); 7631 } 7632 } 7633 } 7634 7635 return new ParceledListSlice<>(list); 7636 } 7637 } 7638 7639 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 7640 String[] permissions, boolean[] tmp, int flags, int userId) { 7641 int numMatch = 0; 7642 final PermissionsState permissionsState = ps.getPermissionsState(); 7643 for (int i=0; i<permissions.length; i++) { 7644 final String permission = permissions[i]; 7645 if (permissionsState.hasPermission(permission, userId)) { 7646 tmp[i] = true; 7647 numMatch++; 7648 } else { 7649 tmp[i] = false; 7650 } 7651 } 7652 if (numMatch == 0) { 7653 return; 7654 } 7655 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 7656 7657 // The above might return null in cases of uninstalled apps or install-state 7658 // skew across users/profiles. 7659 if (pi != null) { 7660 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 7661 if (numMatch == permissions.length) { 7662 pi.requestedPermissions = permissions; 7663 } else { 7664 pi.requestedPermissions = new String[numMatch]; 7665 numMatch = 0; 7666 for (int i=0; i<permissions.length; i++) { 7667 if (tmp[i]) { 7668 pi.requestedPermissions[numMatch] = permissions[i]; 7669 numMatch++; 7670 } 7671 } 7672 } 7673 } 7674 list.add(pi); 7675 } 7676 } 7677 7678 @Override 7679 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 7680 String[] permissions, int flags, int userId) { 7681 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7682 flags = updateFlagsForPackage(flags, userId, permissions); 7683 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7684 true /* requireFullPermission */, false /* checkShell */, 7685 "get packages holding permissions"); 7686 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7687 7688 // writer 7689 synchronized (mPackages) { 7690 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 7691 boolean[] tmpBools = new boolean[permissions.length]; 7692 if (listUninstalled) { 7693 for (PackageSetting ps : mSettings.mPackages.values()) { 7694 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7695 userId); 7696 } 7697 } else { 7698 for (PackageParser.Package pkg : mPackages.values()) { 7699 PackageSetting ps = (PackageSetting)pkg.mExtras; 7700 if (ps != null) { 7701 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 7702 userId); 7703 } 7704 } 7705 } 7706 7707 return new ParceledListSlice<PackageInfo>(list); 7708 } 7709 } 7710 7711 @Override 7712 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 7713 final int callingUid = Binder.getCallingUid(); 7714 if (getInstantAppPackageName(callingUid) != null) { 7715 return ParceledListSlice.emptyList(); 7716 } 7717 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 7718 flags = updateFlagsForApplication(flags, userId, null); 7719 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 7720 7721 // writer 7722 synchronized (mPackages) { 7723 ArrayList<ApplicationInfo> list; 7724 if (listUninstalled) { 7725 list = new ArrayList<>(mSettings.mPackages.size()); 7726 for (PackageSetting ps : mSettings.mPackages.values()) { 7727 ApplicationInfo ai; 7728 int effectiveFlags = flags; 7729 if (ps.isSystem()) { 7730 effectiveFlags |= PackageManager.MATCH_ANY_USER; 7731 } 7732 if (ps.pkg != null) { 7733 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 7734 continue; 7735 } 7736 if (filterAppAccessLPr(ps, callingUid, userId)) { 7737 continue; 7738 } 7739 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 7740 ps.readUserState(userId), userId); 7741 if (ai != null) { 7742 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 7743 } 7744 } else { 7745 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 7746 // and already converts to externally visible package name 7747 ai = generateApplicationInfoFromSettingsLPw(ps.name, 7748 callingUid, effectiveFlags, userId); 7749 } 7750 if (ai != null) { 7751 list.add(ai); 7752 } 7753 } 7754 } else { 7755 list = new ArrayList<>(mPackages.size()); 7756 for (PackageParser.Package p : mPackages.values()) { 7757 if (p.mExtras != null) { 7758 PackageSetting ps = (PackageSetting) p.mExtras; 7759 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 7760 continue; 7761 } 7762 if (filterAppAccessLPr(ps, callingUid, userId)) { 7763 continue; 7764 } 7765 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7766 ps.readUserState(userId), userId); 7767 if (ai != null) { 7768 ai.packageName = resolveExternalPackageNameLPr(p); 7769 list.add(ai); 7770 } 7771 } 7772 } 7773 } 7774 7775 return new ParceledListSlice<>(list); 7776 } 7777 } 7778 7779 @Override 7780 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 7781 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7782 return null; 7783 } 7784 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7785 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7786 "getEphemeralApplications"); 7787 } 7788 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7789 true /* requireFullPermission */, false /* checkShell */, 7790 "getEphemeralApplications"); 7791 synchronized (mPackages) { 7792 List<InstantAppInfo> instantApps = mInstantAppRegistry 7793 .getInstantAppsLPr(userId); 7794 if (instantApps != null) { 7795 return new ParceledListSlice<>(instantApps); 7796 } 7797 } 7798 return null; 7799 } 7800 7801 @Override 7802 public boolean isInstantApp(String packageName, int userId) { 7803 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7804 true /* requireFullPermission */, false /* checkShell */, 7805 "isInstantApp"); 7806 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7807 return false; 7808 } 7809 7810 synchronized (mPackages) { 7811 int callingUid = Binder.getCallingUid(); 7812 if (Process.isIsolated(callingUid)) { 7813 callingUid = mIsolatedOwners.get(callingUid); 7814 } 7815 final PackageSetting ps = mSettings.mPackages.get(packageName); 7816 PackageParser.Package pkg = mPackages.get(packageName); 7817 final boolean returnAllowed = 7818 ps != null 7819 && (isCallerSameApp(packageName, callingUid) 7820 || canViewInstantApps(callingUid, userId) 7821 || mInstantAppRegistry.isInstantAccessGranted( 7822 userId, UserHandle.getAppId(callingUid), ps.appId)); 7823 if (returnAllowed) { 7824 return ps.getInstantApp(userId); 7825 } 7826 } 7827 return false; 7828 } 7829 7830 @Override 7831 public byte[] getInstantAppCookie(String packageName, int userId) { 7832 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7833 return null; 7834 } 7835 7836 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7837 true /* requireFullPermission */, false /* checkShell */, 7838 "getInstantAppCookie"); 7839 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7840 return null; 7841 } 7842 synchronized (mPackages) { 7843 return mInstantAppRegistry.getInstantAppCookieLPw( 7844 packageName, userId); 7845 } 7846 } 7847 7848 @Override 7849 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 7850 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7851 return true; 7852 } 7853 7854 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7855 true /* requireFullPermission */, true /* checkShell */, 7856 "setInstantAppCookie"); 7857 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 7858 return false; 7859 } 7860 synchronized (mPackages) { 7861 return mInstantAppRegistry.setInstantAppCookieLPw( 7862 packageName, cookie, userId); 7863 } 7864 } 7865 7866 @Override 7867 public Bitmap getInstantAppIcon(String packageName, int userId) { 7868 if (HIDE_EPHEMERAL_APIS || isEphemeralDisabled()) { 7869 return null; 7870 } 7871 7872 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 7873 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 7874 "getInstantAppIcon"); 7875 } 7876 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7877 true /* requireFullPermission */, false /* checkShell */, 7878 "getInstantAppIcon"); 7879 7880 synchronized (mPackages) { 7881 return mInstantAppRegistry.getInstantAppIconLPw( 7882 packageName, userId); 7883 } 7884 } 7885 7886 private boolean isCallerSameApp(String packageName, int uid) { 7887 PackageParser.Package pkg = mPackages.get(packageName); 7888 return pkg != null 7889 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 7890 } 7891 7892 @Override 7893 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 7894 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7895 return ParceledListSlice.emptyList(); 7896 } 7897 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 7898 } 7899 7900 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 7901 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 7902 7903 // reader 7904 synchronized (mPackages) { 7905 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 7906 final int userId = UserHandle.getCallingUserId(); 7907 while (i.hasNext()) { 7908 final PackageParser.Package p = i.next(); 7909 if (p.applicationInfo == null) continue; 7910 7911 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 7912 && !p.applicationInfo.isDirectBootAware(); 7913 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 7914 && p.applicationInfo.isDirectBootAware(); 7915 7916 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 7917 && (!mSafeMode || isSystemApp(p)) 7918 && (matchesUnaware || matchesAware)) { 7919 PackageSetting ps = mSettings.mPackages.get(p.packageName); 7920 if (ps != null) { 7921 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 7922 ps.readUserState(userId), userId); 7923 if (ai != null) { 7924 finalList.add(ai); 7925 } 7926 } 7927 } 7928 } 7929 } 7930 7931 return finalList; 7932 } 7933 7934 @Override 7935 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 7936 return resolveContentProviderInternal(name, flags, userId); 7937 } 7938 7939 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 7940 if (!sUserManager.exists(userId)) return null; 7941 flags = updateFlagsForComponent(flags, userId, name); 7942 final String instantAppPkgName = getInstantAppPackageName(Binder.getCallingUid()); 7943 // reader 7944 synchronized (mPackages) { 7945 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 7946 PackageSetting ps = provider != null 7947 ? mSettings.mPackages.get(provider.owner.packageName) 7948 : null; 7949 if (ps != null) { 7950 final boolean isInstantApp = ps.getInstantApp(userId); 7951 // normal application; filter out instant application provider 7952 if (instantAppPkgName == null && isInstantApp) { 7953 return null; 7954 } 7955 // instant application; filter out other instant applications 7956 if (instantAppPkgName != null 7957 && isInstantApp 7958 && !provider.owner.packageName.equals(instantAppPkgName)) { 7959 return null; 7960 } 7961 // instant application; filter out non-exposed provider 7962 if (instantAppPkgName != null 7963 && !isInstantApp 7964 && (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0) { 7965 return null; 7966 } 7967 // provider not enabled 7968 if (!mSettings.isEnabledAndMatchLPr(provider.info, flags, userId)) { 7969 return null; 7970 } 7971 return PackageParser.generateProviderInfo( 7972 provider, flags, ps.readUserState(userId), userId); 7973 } 7974 return null; 7975 } 7976 } 7977 7978 /** 7979 * @deprecated 7980 */ 7981 @Deprecated 7982 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 7983 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 7984 return; 7985 } 7986 // reader 7987 synchronized (mPackages) { 7988 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 7989 .entrySet().iterator(); 7990 final int userId = UserHandle.getCallingUserId(); 7991 while (i.hasNext()) { 7992 Map.Entry<String, PackageParser.Provider> entry = i.next(); 7993 PackageParser.Provider p = entry.getValue(); 7994 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 7995 7996 if (ps != null && p.syncable 7997 && (!mSafeMode || (p.info.applicationInfo.flags 7998 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 7999 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 8000 ps.readUserState(userId), userId); 8001 if (info != null) { 8002 outNames.add(entry.getKey()); 8003 outInfo.add(info); 8004 } 8005 } 8006 } 8007 } 8008 } 8009 8010 @Override 8011 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8012 int uid, int flags, String metaDataKey) { 8013 final int callingUid = Binder.getCallingUid(); 8014 final int userId = processName != null ? UserHandle.getUserId(uid) 8015 : UserHandle.getCallingUserId(); 8016 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8017 flags = updateFlagsForComponent(flags, userId, processName); 8018 ArrayList<ProviderInfo> finalList = null; 8019 // reader 8020 synchronized (mPackages) { 8021 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 8022 while (i.hasNext()) { 8023 final PackageParser.Provider p = i.next(); 8024 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 8025 if (ps != null && p.info.authority != null 8026 && (processName == null 8027 || (p.info.processName.equals(processName) 8028 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 8029 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 8030 8031 // See PM.queryContentProviders()'s javadoc for why we have the metaData 8032 // parameter. 8033 if (metaDataKey != null 8034 && (p.metaData == null || !p.metaData.containsKey(metaDataKey))) { 8035 continue; 8036 } 8037 final ComponentName component = 8038 new ComponentName(p.info.packageName, p.info.name); 8039 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8040 continue; 8041 } 8042 if (finalList == null) { 8043 finalList = new ArrayList<ProviderInfo>(3); 8044 } 8045 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 8046 ps.readUserState(userId), userId); 8047 if (info != null) { 8048 finalList.add(info); 8049 } 8050 } 8051 } 8052 } 8053 8054 if (finalList != null) { 8055 Collections.sort(finalList, mProviderInitOrderSorter); 8056 return new ParceledListSlice<ProviderInfo>(finalList); 8057 } 8058 8059 return ParceledListSlice.emptyList(); 8060 } 8061 8062 @Override 8063 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8064 // reader 8065 synchronized (mPackages) { 8066 final int callingUid = Binder.getCallingUid(); 8067 final int callingUserId = UserHandle.getUserId(callingUid); 8068 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8069 if (ps == null) return null; 8070 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8071 return null; 8072 } 8073 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8074 return PackageParser.generateInstrumentationInfo(i, flags); 8075 } 8076 } 8077 8078 @Override 8079 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8080 String targetPackage, int flags) { 8081 final int callingUid = Binder.getCallingUid(); 8082 final int callingUserId = UserHandle.getUserId(callingUid); 8083 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8084 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8085 return ParceledListSlice.emptyList(); 8086 } 8087 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8088 } 8089 8090 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8091 int flags) { 8092 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 8093 8094 // reader 8095 synchronized (mPackages) { 8096 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8097 while (i.hasNext()) { 8098 final PackageParser.Instrumentation p = i.next(); 8099 if (targetPackage == null 8100 || targetPackage.equals(p.info.targetPackage)) { 8101 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8102 flags); 8103 if (ii != null) { 8104 finalList.add(ii); 8105 } 8106 } 8107 } 8108 } 8109 8110 return finalList; 8111 } 8112 8113 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8114 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8115 try { 8116 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8117 } finally { 8118 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8119 } 8120 } 8121 8122 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8123 final File[] files = scanDir.listFiles(); 8124 if (ArrayUtils.isEmpty(files)) { 8125 Log.d(TAG, "No files in app dir " + scanDir); 8126 return; 8127 } 8128 8129 if (DEBUG_PACKAGE_SCANNING) { 8130 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8131 + " flags=0x" + Integer.toHexString(parseFlags)); 8132 } 8133 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8134 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8135 mParallelPackageParserCallback)) { 8136 // Submit files for parsing in parallel 8137 int fileCount = 0; 8138 for (File file : files) { 8139 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8140 && !PackageInstallerService.isStageName(file.getName()); 8141 if (!isPackage) { 8142 // Ignore entries which are not packages 8143 continue; 8144 } 8145 parallelPackageParser.submit(file, parseFlags); 8146 fileCount++; 8147 } 8148 8149 // Process results one by one 8150 for (; fileCount > 0; fileCount--) { 8151 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8152 Throwable throwable = parseResult.throwable; 8153 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8154 8155 if (throwable == null) { 8156 // TODO(toddke): move lower in the scan chain 8157 // Static shared libraries have synthetic package names 8158 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8159 renameStaticSharedLibraryPackage(parseResult.pkg); 8160 } 8161 try { 8162 if (errorCode == PackageManager.INSTALL_SUCCEEDED) { 8163 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8164 currentTime, null); 8165 } 8166 } catch (PackageManagerException e) { 8167 errorCode = e.error; 8168 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8169 } 8170 } else if (throwable instanceof PackageParser.PackageParserException) { 8171 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8172 throwable; 8173 errorCode = e.error; 8174 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8175 } else { 8176 throw new IllegalStateException("Unexpected exception occurred while parsing " 8177 + parseResult.scanFile, throwable); 8178 } 8179 8180 // Delete invalid userdata apps 8181 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 8182 errorCode == PackageManager.INSTALL_FAILED_INVALID_APK) { 8183 logCriticalInfo(Log.WARN, 8184 "Deleting invalid package at " + parseResult.scanFile); 8185 removeCodePathLI(parseResult.scanFile); 8186 } 8187 } 8188 } 8189 } 8190 8191 public static void reportSettingsProblem(int priority, String msg) { 8192 logCriticalInfo(priority, msg); 8193 } 8194 8195 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 8196 final @ParseFlags int parseFlags, boolean forceCollect) throws PackageManagerException { 8197 // When upgrading from pre-N MR1, verify the package time stamp using the package 8198 // directory and not the APK file. 8199 final long lastModifiedTime = mIsPreNMR1Upgrade 8200 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 8201 if (ps != null && !forceCollect 8202 && ps.codePathString.equals(pkg.codePath) 8203 && ps.timeStamp == lastModifiedTime 8204 && !isCompatSignatureUpdateNeeded(pkg) 8205 && !isRecoverSignatureUpdateNeeded(pkg)) { 8206 if (ps.signatures.mSignatures != null 8207 && ps.signatures.mSignatures.length != 0 8208 && ps.signatures.mSignatureSchemeVersion != SignatureSchemeVersion.UNKNOWN) { 8209 // Optimization: reuse the existing cached signing data 8210 // if the package appears to be unchanged. 8211 try { 8212 pkg.mSigningDetails = new PackageParser.SigningDetails(ps.signatures.mSignatures, 8213 ps.signatures.mSignatureSchemeVersion); 8214 return; 8215 } catch (CertificateException e) { 8216 Slog.e(TAG, "Attempt to read public keys from persisted signatures failed for " 8217 + ps.name, e); 8218 } 8219 } 8220 8221 Slog.w(TAG, "PackageSetting for " + ps.name 8222 + " is missing signatures. Collecting certs again to recover them."); 8223 } else { 8224 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 8225 (forceCollect ? " (forced)" : "")); 8226 } 8227 8228 try { 8229 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 8230 PackageParser.collectCertificates(pkg, parseFlags); 8231 } catch (PackageParserException e) { 8232 throw PackageManagerException.from(e); 8233 } finally { 8234 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8235 } 8236 } 8237 8238 /** 8239 * Traces a package scan. 8240 * @see #scanPackageLI(File, int, int, long, UserHandle) 8241 */ 8242 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 8243 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 8244 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 8245 try { 8246 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 8247 } finally { 8248 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8249 } 8250 } 8251 8252 /** 8253 * Scans a package and returns the newly parsed package. 8254 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 8255 */ 8256 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 8257 long currentTime, UserHandle user) throws PackageManagerException { 8258 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 8259 PackageParser pp = new PackageParser(); 8260 pp.setSeparateProcesses(mSeparateProcesses); 8261 pp.setOnlyCoreApps(mOnlyCore); 8262 pp.setDisplayMetrics(mMetrics); 8263 pp.setCallback(mPackageParserCallback); 8264 8265 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 8266 final PackageParser.Package pkg; 8267 try { 8268 pkg = pp.parsePackage(scanFile, parseFlags); 8269 } catch (PackageParserException e) { 8270 throw PackageManagerException.from(e); 8271 } finally { 8272 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8273 } 8274 8275 // Static shared libraries have synthetic package names 8276 if (pkg.applicationInfo.isStaticSharedLibrary()) { 8277 renameStaticSharedLibraryPackage(pkg); 8278 } 8279 8280 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8281 } 8282 8283 /** 8284 * Scans a package and returns the newly parsed package. 8285 * @throws PackageManagerException on a parse error. 8286 */ 8287 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 8288 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8289 @Nullable UserHandle user) 8290 throws PackageManagerException { 8291 // If the package has children and this is the first dive in the function 8292 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 8293 // packages (parent and children) would be successfully scanned before the 8294 // actual scan since scanning mutates internal state and we want to atomically 8295 // install the package and its children. 8296 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8297 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 8298 scanFlags |= SCAN_CHECK_ONLY; 8299 } 8300 } else { 8301 scanFlags &= ~SCAN_CHECK_ONLY; 8302 } 8303 8304 // Scan the parent 8305 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 8306 scanFlags, currentTime, user); 8307 8308 // Scan the children 8309 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 8310 for (int i = 0; i < childCount; i++) { 8311 PackageParser.Package childPackage = pkg.childPackages.get(i); 8312 addForInitLI(childPackage, parseFlags, scanFlags, 8313 currentTime, user); 8314 } 8315 8316 8317 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8318 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 8319 } 8320 8321 return scannedPkg; 8322 } 8323 8324 // Temporary to catch potential issues with refactoring 8325 private static boolean REFACTOR_DEBUG = true; 8326 /** 8327 * Adds a new package to the internal data structures during platform initialization. 8328 * <p>After adding, the package is known to the system and available for querying. 8329 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 8330 * etc...], additional checks are performed. Basic verification [such as ensuring 8331 * matching signatures, checking version codes, etc...] occurs if the package is 8332 * identical to a previously known package. If the package fails a signature check, 8333 * the version installed on /data will be removed. If the version of the new package 8334 * is less than or equal than the version on /data, it will be ignored. 8335 * <p>Regardless of the package location, the results are applied to the internal 8336 * structures and the package is made available to the rest of the system. 8337 * <p>NOTE: The return value should be removed. It's the passed in package object. 8338 */ 8339 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 8340 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 8341 @Nullable UserHandle user) 8342 throws PackageManagerException { 8343 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 8344 final String renamedPkgName; 8345 final PackageSetting disabledPkgSetting; 8346 final boolean isSystemPkgUpdated; 8347 final boolean pkgAlreadyExists; 8348 PackageSetting pkgSetting; 8349 8350 // NOTE: installPackageLI() has the same code to setup the package's 8351 // application info. This probably should be done lower in the call 8352 // stack [such as scanPackageOnly()]. However, we verify the application 8353 // info prior to that [in scanPackageNew()] and thus have to setup 8354 // the application info early. 8355 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 8356 pkg.setApplicationInfoCodePath(pkg.codePath); 8357 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 8358 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 8359 pkg.setApplicationInfoResourcePath(pkg.codePath); 8360 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 8361 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 8362 8363 synchronized (mPackages) { 8364 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 8365 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 8366if (REFACTOR_DEBUG) { 8367Slog.e("TODD", 8368 "Add pkg: " + pkg.packageName + (realPkgName==null?"":", realName: " + realPkgName)); 8369} 8370 if (realPkgName != null) { 8371 ensurePackageRenamed(pkg, renamedPkgName); 8372 } 8373 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 8374 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 8375 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 8376 pkgAlreadyExists = pkgSetting != null; 8377 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 8378 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 8379 isSystemPkgUpdated = disabledPkgSetting != null; 8380 8381 if (DEBUG_INSTALL && isSystemPkgUpdated) { 8382 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 8383 } 8384if (REFACTOR_DEBUG) { 8385Slog.e("TODD", 8386 "SSP? " + scanSystemPartition 8387 + ", exists? " + pkgAlreadyExists + (pkgAlreadyExists?" "+pkgSetting.toString():"") 8388 + ", upgraded? " + isSystemPkgUpdated + (isSystemPkgUpdated?" "+disabledPkgSetting.toString():"")); 8389} 8390 8391 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 8392 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 8393 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 8394 : null; 8395 if (DEBUG_PACKAGE_SCANNING 8396 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 8397 && sharedUserSetting != null) { 8398 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 8399 + " (uid=" + sharedUserSetting.userId + "):" 8400 + " packages=" + sharedUserSetting.packages); 8401if (REFACTOR_DEBUG) { 8402Slog.e("TODD", 8403 "Shared UserID " + pkg.mSharedUserId 8404 + " (uid=" + sharedUserSetting.userId + "):" 8405 + " packages=" + sharedUserSetting.packages); 8406} 8407 } 8408 8409 if (scanSystemPartition) { 8410 // Potentially prune child packages. If the application on the /system 8411 // partition has been updated via OTA, but, is still disabled by a 8412 // version on /data, cycle through all of its children packages and 8413 // remove children that are no longer defined. 8414 if (isSystemPkgUpdated) { 8415if (REFACTOR_DEBUG) { 8416Slog.e("TODD", 8417 "Disable child packages"); 8418} 8419 final int scannedChildCount = (pkg.childPackages != null) 8420 ? pkg.childPackages.size() : 0; 8421 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 8422 ? disabledPkgSetting.childPackageNames.size() : 0; 8423 for (int i = 0; i < disabledChildCount; i++) { 8424 String disabledChildPackageName = 8425 disabledPkgSetting.childPackageNames.get(i); 8426 boolean disabledPackageAvailable = false; 8427 for (int j = 0; j < scannedChildCount; j++) { 8428 PackageParser.Package childPkg = pkg.childPackages.get(j); 8429 if (childPkg.packageName.equals(disabledChildPackageName)) { 8430if (REFACTOR_DEBUG) { 8431Slog.e("TODD", 8432 "Ignore " + disabledChildPackageName); 8433} 8434 disabledPackageAvailable = true; 8435 break; 8436 } 8437 } 8438 if (!disabledPackageAvailable) { 8439if (REFACTOR_DEBUG) { 8440Slog.e("TODD", 8441 "Disable " + disabledChildPackageName); 8442} 8443 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 8444 } 8445 } 8446 // we're updating the disabled package, so, scan it as the package setting 8447 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 8448 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 8449 null /* originalPkgSetting */, null, parseFlags, scanFlags, 8450 (pkg == mPlatformPackage), user); 8451if (REFACTOR_DEBUG) { 8452Slog.e("TODD", 8453 "Scan disabled system package"); 8454Slog.e("TODD", 8455 "Pre: " + request.pkgSetting.dumpState_temp()); 8456} 8457final ScanResult result = 8458 scanPackageOnlyLI(request, mFactoryTest, -1L); 8459if (REFACTOR_DEBUG) { 8460Slog.e("TODD", 8461 "Post: " + (result.success?result.pkgSetting.dumpState_temp():"FAILED scan")); 8462} 8463 } 8464 } 8465 } 8466 8467 final boolean newPkgChangedPaths = 8468 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 8469if (REFACTOR_DEBUG) { 8470Slog.e("TODD", 8471 "paths changed? " + newPkgChangedPaths 8472 + "; old: " + pkg.codePath 8473 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.codePathString)); 8474} 8475 final boolean newPkgVersionGreater = 8476 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 8477if (REFACTOR_DEBUG) { 8478Slog.e("TODD", 8479 "version greater? " + newPkgVersionGreater 8480 + "; old: " + pkg.getLongVersionCode() 8481 + ", new: " + (pkgSetting==null?"<<NULL>>":pkgSetting.versionCode)); 8482} 8483 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 8484 && newPkgChangedPaths && newPkgVersionGreater; 8485if (REFACTOR_DEBUG) { 8486 Slog.e("TODD", 8487 "system better? " + isSystemPkgBetter); 8488} 8489 if (isSystemPkgBetter) { 8490 // The version of the application on /system is greater than the version on 8491 // /data. Switch back to the application on /system. 8492 // It's safe to assume the application on /system will correctly scan. If not, 8493 // there won't be a working copy of the application. 8494 synchronized (mPackages) { 8495 // just remove the loaded entries from package lists 8496 mPackages.remove(pkgSetting.name); 8497 } 8498 8499 logCriticalInfo(Log.WARN, 8500 "System package updated;" 8501 + " name: " + pkgSetting.name 8502 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8503 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8504if (REFACTOR_DEBUG) { 8505Slog.e("TODD", 8506 "System package changed;" 8507 + " name: " + pkgSetting.name 8508 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8509 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8510} 8511 8512 final InstallArgs args = createInstallArgsForExisting( 8513 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8514 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8515 args.cleanUpResourcesLI(); 8516 synchronized (mPackages) { 8517 mSettings.enableSystemPackageLPw(pkgSetting.name); 8518 } 8519 } 8520 8521 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 8522if (REFACTOR_DEBUG) { 8523Slog.e("TODD", 8524 "THROW exception; system pkg version not good enough"); 8525} 8526 // The version of the application on the /system partition is less than or 8527 // equal to the version on the /data partition. Throw an exception and use 8528 // the application already installed on the /data partition. 8529 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 8530 + pkg.codePath + " ignored: updated version " + disabledPkgSetting.versionCode 8531 + " better than this " + pkg.getLongVersionCode()); 8532 } 8533 8534 // Verify certificates against what was last scanned. If it is an updated priv app, we will 8535 // force the verification. Full apk verification will happen unless apk verity is set up for 8536 // the file. In that case, only small part of the apk is verified upfront. 8537 collectCertificatesLI(pkgSetting, pkg, parseFlags, 8538 PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting)); 8539 8540 boolean shouldHideSystemApp = false; 8541 // A new application appeared on /system, but, we already have a copy of 8542 // the application installed on /data. 8543 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 8544 && !pkgSetting.isSystem()) { 8545 // if the signatures don't match, wipe the installed application and its data 8546 if (compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSigningDetails.signatures) 8547 != PackageManager.SIGNATURE_MATCH) { 8548 logCriticalInfo(Log.WARN, 8549 "System package signature mismatch;" 8550 + " name: " + pkgSetting.name); 8551if (REFACTOR_DEBUG) { 8552Slog.e("TODD", 8553 "System package signature mismatch;" 8554 + " name: " + pkgSetting.name); 8555} 8556 try (PackageFreezer freezer = freezePackage(pkg.packageName, 8557 "scanPackageInternalLI")) { 8558 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 8559 } 8560 pkgSetting = null; 8561 } else if (newPkgVersionGreater) { 8562 // The application on /system is newer than the application on /data. 8563 // Simply remove the application on /data [keeping application data] 8564 // and replace it with the version on /system. 8565 logCriticalInfo(Log.WARN, 8566 "System package enabled;" 8567 + " name: " + pkgSetting.name 8568 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8569 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8570if (REFACTOR_DEBUG) { 8571Slog.e("TODD", 8572 "System package enabled;" 8573 + " name: " + pkgSetting.name 8574 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 8575 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 8576} 8577 InstallArgs args = createInstallArgsForExisting( 8578 packageFlagsToInstallFlags(pkgSetting), pkgSetting.codePathString, 8579 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 8580 synchronized (mInstallLock) { 8581 args.cleanUpResourcesLI(); 8582 } 8583 } else { 8584 // The application on /system is older than the application on /data. Hide 8585 // the application on /system and the version on /data will be scanned later 8586 // and re-added like an update. 8587 shouldHideSystemApp = true; 8588 logCriticalInfo(Log.INFO, 8589 "System package disabled;" 8590 + " name: " + pkgSetting.name 8591 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8592 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8593if (REFACTOR_DEBUG) { 8594Slog.e("TODD", 8595 "System package disabled;" 8596 + " name: " + pkgSetting.name 8597 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 8598 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 8599} 8600 } 8601 } 8602 8603if (REFACTOR_DEBUG) { 8604Slog.e("TODD", 8605 "Scan package"); 8606Slog.e("TODD", 8607 "Pre: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8608} 8609 final PackageParser.Package scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags 8610 | SCAN_UPDATE_SIGNATURE, currentTime, user); 8611if (REFACTOR_DEBUG) { 8612pkgSetting = mSettings.getPackageLPr(pkg.packageName); 8613Slog.e("TODD", 8614 "Post: " + (pkgSetting==null?"<<NONE>>":pkgSetting.dumpState_temp())); 8615} 8616 8617 if (shouldHideSystemApp) { 8618if (REFACTOR_DEBUG) { 8619Slog.e("TODD", 8620 "Disable package: " + pkg.packageName); 8621} 8622 synchronized (mPackages) { 8623 mSettings.disableSystemPackageLPw(pkg.packageName, true); 8624 } 8625 } 8626 return scannedPkg; 8627 } 8628 8629 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 8630 // Derive the new package synthetic package name 8631 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 8632 + pkg.staticSharedLibVersion); 8633 } 8634 8635 private static String fixProcessName(String defProcessName, 8636 String processName) { 8637 if (processName == null) { 8638 return defProcessName; 8639 } 8640 return processName; 8641 } 8642 8643 /** 8644 * Enforces that only the system UID or root's UID can call a method exposed 8645 * via Binder. 8646 * 8647 * @param message used as message if SecurityException is thrown 8648 * @throws SecurityException if the caller is not system or root 8649 */ 8650 private static final void enforceSystemOrRoot(String message) { 8651 final int uid = Binder.getCallingUid(); 8652 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 8653 throw new SecurityException(message); 8654 } 8655 } 8656 8657 @Override 8658 public void performFstrimIfNeeded() { 8659 enforceSystemOrRoot("Only the system can request fstrim"); 8660 8661 // Before everything else, see whether we need to fstrim. 8662 try { 8663 IStorageManager sm = PackageHelper.getStorageManager(); 8664 if (sm != null) { 8665 boolean doTrim = false; 8666 final long interval = android.provider.Settings.Global.getLong( 8667 mContext.getContentResolver(), 8668 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 8669 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 8670 if (interval > 0) { 8671 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 8672 if (timeSinceLast > interval) { 8673 doTrim = true; 8674 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 8675 + "; running immediately"); 8676 } 8677 } 8678 if (doTrim) { 8679 final boolean dexOptDialogShown; 8680 synchronized (mPackages) { 8681 dexOptDialogShown = mDexOptDialogShown; 8682 } 8683 if (!isFirstBoot() && dexOptDialogShown) { 8684 try { 8685 ActivityManager.getService().showBootMessage( 8686 mContext.getResources().getString( 8687 R.string.android_upgrading_fstrim), true); 8688 } catch (RemoteException e) { 8689 } 8690 } 8691 sm.runMaintenance(); 8692 } 8693 } else { 8694 Slog.e(TAG, "storageManager service unavailable!"); 8695 } 8696 } catch (RemoteException e) { 8697 // Can't happen; StorageManagerService is local 8698 } 8699 } 8700 8701 @Override 8702 public void updatePackagesIfNeeded() { 8703 enforceSystemOrRoot("Only the system can request package update"); 8704 8705 // We need to re-extract after an OTA. 8706 boolean causeUpgrade = isUpgrade(); 8707 8708 // First boot or factory reset. 8709 // Note: we also handle devices that are upgrading to N right now as if it is their 8710 // first boot, as they do not have profile data. 8711 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 8712 8713 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 8714 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 8715 8716 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 8717 return; 8718 } 8719 8720 List<PackageParser.Package> pkgs; 8721 synchronized (mPackages) { 8722 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 8723 } 8724 8725 final long startTime = System.nanoTime(); 8726 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 8727 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 8728 false /* bootComplete */); 8729 8730 final int elapsedTimeSeconds = 8731 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 8732 8733 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 8734 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 8735 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 8736 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 8737 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 8738 } 8739 8740 /* 8741 * Return the prebuilt profile path given a package base code path. 8742 */ 8743 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 8744 return pkg.baseCodePath + ".prof"; 8745 } 8746 8747 /** 8748 * Performs dexopt on the set of packages in {@code packages} and returns an int array 8749 * containing statistics about the invocation. The array consists of three elements, 8750 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 8751 * and {@code numberOfPackagesFailed}. 8752 */ 8753 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 8754 final String compilerFilter, boolean bootComplete) { 8755 8756 int numberOfPackagesVisited = 0; 8757 int numberOfPackagesOptimized = 0; 8758 int numberOfPackagesSkipped = 0; 8759 int numberOfPackagesFailed = 0; 8760 final int numberOfPackagesToDexopt = pkgs.size(); 8761 8762 for (PackageParser.Package pkg : pkgs) { 8763 numberOfPackagesVisited++; 8764 8765 boolean useProfileForDexopt = false; 8766 8767 if ((isFirstBoot() || isUpgrade()) && isSystemApp(pkg)) { 8768 // Copy over initial preopt profiles since we won't get any JIT samples for methods 8769 // that are already compiled. 8770 File profileFile = new File(getPrebuildProfilePath(pkg)); 8771 // Copy profile if it exists. 8772 if (profileFile.exists()) { 8773 try { 8774 // We could also do this lazily before calling dexopt in 8775 // PackageDexOptimizer to prevent this happening on first boot. The issue 8776 // is that we don't have a good way to say "do this only once". 8777 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8778 pkg.applicationInfo.uid, pkg.packageName)) { 8779 Log.e(TAG, "Installer failed to copy system profile!"); 8780 } else { 8781 // Disabled as this causes speed-profile compilation during first boot 8782 // even if things are already compiled. 8783 // useProfileForDexopt = true; 8784 } 8785 } catch (Exception e) { 8786 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 8787 e); 8788 } 8789 } else { 8790 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 8791 // Handle compressed APKs in this path. Only do this for stubs with profiles to 8792 // minimize the number off apps being speed-profile compiled during first boot. 8793 // The other paths will not change the filter. 8794 if (disabledPs != null && disabledPs.pkg.isStub) { 8795 // The package is the stub one, remove the stub suffix to get the normal 8796 // package and APK names. 8797 String systemProfilePath = 8798 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 8799 profileFile = new File(systemProfilePath); 8800 // If we have a profile for a compressed APK, copy it to the reference 8801 // location. 8802 // Note that copying the profile here will cause it to override the 8803 // reference profile every OTA even though the existing reference profile 8804 // may have more data. We can't copy during decompression since the 8805 // directories are not set up at that point. 8806 if (profileFile.exists()) { 8807 try { 8808 // We could also do this lazily before calling dexopt in 8809 // PackageDexOptimizer to prevent this happening on first boot. The 8810 // issue is that we don't have a good way to say "do this only 8811 // once". 8812 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 8813 pkg.applicationInfo.uid, pkg.packageName)) { 8814 Log.e(TAG, "Failed to copy system profile for stub package!"); 8815 } else { 8816 useProfileForDexopt = true; 8817 } 8818 } catch (Exception e) { 8819 Log.e(TAG, "Failed to copy profile " + 8820 profileFile.getAbsolutePath() + " ", e); 8821 } 8822 } 8823 } 8824 } 8825 } 8826 8827 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 8828 if (DEBUG_DEXOPT) { 8829 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 8830 } 8831 numberOfPackagesSkipped++; 8832 continue; 8833 } 8834 8835 if (DEBUG_DEXOPT) { 8836 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 8837 numberOfPackagesToDexopt + ": " + pkg.packageName); 8838 } 8839 8840 if (showDialog) { 8841 try { 8842 ActivityManager.getService().showBootMessage( 8843 mContext.getResources().getString(R.string.android_upgrading_apk, 8844 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 8845 } catch (RemoteException e) { 8846 } 8847 synchronized (mPackages) { 8848 mDexOptDialogShown = true; 8849 } 8850 } 8851 8852 String pkgCompilerFilter = compilerFilter; 8853 if (useProfileForDexopt) { 8854 // Use background dexopt mode to try and use the profile. Note that this does not 8855 // guarantee usage of the profile. 8856 pkgCompilerFilter = 8857 PackageManagerServiceCompilerMapping.getCompilerFilterForReason( 8858 PackageManagerService.REASON_BACKGROUND_DEXOPT); 8859 } 8860 8861 // checkProfiles is false to avoid merging profiles during boot which 8862 // might interfere with background compilation (b/28612421). 8863 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 8864 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 8865 // trade-off worth doing to save boot time work. 8866 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 8867 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 8868 pkg.packageName, 8869 pkgCompilerFilter, 8870 dexoptFlags)); 8871 8872 switch (primaryDexOptStaus) { 8873 case PackageDexOptimizer.DEX_OPT_PERFORMED: 8874 numberOfPackagesOptimized++; 8875 break; 8876 case PackageDexOptimizer.DEX_OPT_SKIPPED: 8877 numberOfPackagesSkipped++; 8878 break; 8879 case PackageDexOptimizer.DEX_OPT_FAILED: 8880 numberOfPackagesFailed++; 8881 break; 8882 default: 8883 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 8884 break; 8885 } 8886 } 8887 8888 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 8889 numberOfPackagesFailed }; 8890 } 8891 8892 @Override 8893 public void notifyPackageUse(String packageName, int reason) { 8894 synchronized (mPackages) { 8895 final int callingUid = Binder.getCallingUid(); 8896 final int callingUserId = UserHandle.getUserId(callingUid); 8897 if (getInstantAppPackageName(callingUid) != null) { 8898 if (!isCallerSameApp(packageName, callingUid)) { 8899 return; 8900 } 8901 } else { 8902 if (isInstantApp(packageName, callingUserId)) { 8903 return; 8904 } 8905 } 8906 notifyPackageUseLocked(packageName, reason); 8907 } 8908 } 8909 8910 private void notifyPackageUseLocked(String packageName, int reason) { 8911 final PackageParser.Package p = mPackages.get(packageName); 8912 if (p == null) { 8913 return; 8914 } 8915 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 8916 } 8917 8918 @Override 8919 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 8920 List<String> classPaths, String loaderIsa) { 8921 int userId = UserHandle.getCallingUserId(); 8922 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 8923 if (ai == null) { 8924 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 8925 + loadingPackageName + ", user=" + userId); 8926 return; 8927 } 8928 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 8929 } 8930 8931 @Override 8932 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 8933 IDexModuleRegisterCallback callback) { 8934 int userId = UserHandle.getCallingUserId(); 8935 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 8936 DexManager.RegisterDexModuleResult result; 8937 if (ai == null) { 8938 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 8939 " calling user. package=" + packageName + ", user=" + userId); 8940 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 8941 } else { 8942 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 8943 } 8944 8945 if (callback != null) { 8946 mHandler.post(() -> { 8947 try { 8948 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 8949 } catch (RemoteException e) { 8950 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 8951 } 8952 }); 8953 } 8954 } 8955 8956 /** 8957 * Ask the package manager to perform a dex-opt with the given compiler filter. 8958 * 8959 * Note: exposed only for the shell command to allow moving packages explicitly to a 8960 * definite state. 8961 */ 8962 @Override 8963 public boolean performDexOptMode(String packageName, 8964 boolean checkProfiles, String targetCompilerFilter, boolean force, 8965 boolean bootComplete, String splitName) { 8966 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 8967 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 8968 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 8969 return performDexOpt(new DexoptOptions(packageName, targetCompilerFilter, 8970 splitName, flags)); 8971 } 8972 8973 /** 8974 * Ask the package manager to perform a dex-opt with the given compiler filter on the 8975 * secondary dex files belonging to the given package. 8976 * 8977 * Note: exposed only for the shell command to allow moving packages explicitly to a 8978 * definite state. 8979 */ 8980 @Override 8981 public boolean performDexOptSecondary(String packageName, String compilerFilter, 8982 boolean force) { 8983 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 8984 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 8985 DexoptOptions.DEXOPT_BOOT_COMPLETE | 8986 (force ? DexoptOptions.DEXOPT_FORCE : 0); 8987 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 8988 } 8989 8990 /*package*/ boolean performDexOpt(DexoptOptions options) { 8991 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8992 return false; 8993 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 8994 return false; 8995 } 8996 8997 if (options.isDexoptOnlySecondaryDex()) { 8998 return mDexManager.dexoptSecondaryDex(options); 8999 } else { 9000 int dexoptStatus = performDexOptWithStatus(options); 9001 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9002 } 9003 } 9004 9005 /** 9006 * Perform dexopt on the given package and return one of following result: 9007 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9008 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9009 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9010 */ 9011 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9012 return performDexOptTraced(options); 9013 } 9014 9015 private int performDexOptTraced(DexoptOptions options) { 9016 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9017 try { 9018 return performDexOptInternal(options); 9019 } finally { 9020 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9021 } 9022 } 9023 9024 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9025 // if the package can now be considered up to date for the given filter. 9026 private int performDexOptInternal(DexoptOptions options) { 9027 PackageParser.Package p; 9028 synchronized (mPackages) { 9029 p = mPackages.get(options.getPackageName()); 9030 if (p == null) { 9031 // Package could not be found. Report failure. 9032 return PackageDexOptimizer.DEX_OPT_FAILED; 9033 } 9034 mPackageUsage.maybeWriteAsync(mPackages); 9035 mCompilerStats.maybeWriteAsync(); 9036 } 9037 long callingId = Binder.clearCallingIdentity(); 9038 try { 9039 synchronized (mInstallLock) { 9040 return performDexOptInternalWithDependenciesLI(p, options); 9041 } 9042 } finally { 9043 Binder.restoreCallingIdentity(callingId); 9044 } 9045 } 9046 9047 public ArraySet<String> getOptimizablePackages() { 9048 ArraySet<String> pkgs = new ArraySet<String>(); 9049 synchronized (mPackages) { 9050 for (PackageParser.Package p : mPackages.values()) { 9051 if (PackageDexOptimizer.canOptimizePackage(p)) { 9052 pkgs.add(p.packageName); 9053 } 9054 } 9055 } 9056 return pkgs; 9057 } 9058 9059 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9060 DexoptOptions options) { 9061 // Select the dex optimizer based on the force parameter. 9062 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9063 // allocate an object here. 9064 PackageDexOptimizer pdo = options.isForce() 9065 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9066 : mPackageDexOptimizer; 9067 9068 // Dexopt all dependencies first. Note: we ignore the return value and march on 9069 // on errors. 9070 // Note that we are going to call performDexOpt on those libraries as many times as 9071 // they are referenced in packages. When we do a batch of performDexOpt (for example 9072 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9073 // and the first package that uses the library will dexopt it. The 9074 // others will see that the compiled code for the library is up to date. 9075 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 9076 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9077 if (!deps.isEmpty()) { 9078 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9079 options.getCompilerFilter(), options.getSplitName(), 9080 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9081 for (PackageParser.Package depPackage : deps) { 9082 // TODO: Analyze and investigate if we (should) profile libraries. 9083 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 9084 getOrCreateCompilerPackageStats(depPackage), 9085 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), libraryOptions); 9086 } 9087 } 9088 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, 9089 getOrCreateCompilerPackageStats(p), 9090 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9091 } 9092 9093 /** 9094 * Reconcile the information we have about the secondary dex files belonging to 9095 * {@code packagName} and the actual dex files. For all dex files that were 9096 * deleted, update the internal records and delete the generated oat files. 9097 */ 9098 @Override 9099 public void reconcileSecondaryDexFiles(String packageName) { 9100 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9101 return; 9102 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 9103 return; 9104 } 9105 mDexManager.reconcileSecondaryDexFiles(packageName); 9106 } 9107 9108 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 9109 // a reference there. 9110 /*package*/ DexManager getDexManager() { 9111 return mDexManager; 9112 } 9113 9114 /** 9115 * Execute the background dexopt job immediately. 9116 */ 9117 @Override 9118 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 9119 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9120 return false; 9121 } 9122 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 9123 } 9124 9125 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 9126 if (p.usesLibraries != null || p.usesOptionalLibraries != null 9127 || p.usesStaticLibraries != null) { 9128 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 9129 Set<String> collectedNames = new HashSet<>(); 9130 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 9131 9132 retValue.remove(p); 9133 9134 return retValue; 9135 } else { 9136 return Collections.emptyList(); 9137 } 9138 } 9139 9140 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 9141 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9142 if (!collectedNames.contains(p.packageName)) { 9143 collectedNames.add(p.packageName); 9144 collected.add(p); 9145 9146 if (p.usesLibraries != null) { 9147 findSharedNonSystemLibrariesRecursive(p.usesLibraries, 9148 null, collected, collectedNames); 9149 } 9150 if (p.usesOptionalLibraries != null) { 9151 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, 9152 null, collected, collectedNames); 9153 } 9154 if (p.usesStaticLibraries != null) { 9155 findSharedNonSystemLibrariesRecursive(p.usesStaticLibraries, 9156 p.usesStaticLibrariesVersions, collected, collectedNames); 9157 } 9158 } 9159 } 9160 9161 private void findSharedNonSystemLibrariesRecursive(ArrayList<String> libs, long[] versions, 9162 ArrayList<PackageParser.Package> collected, Set<String> collectedNames) { 9163 final int libNameCount = libs.size(); 9164 for (int i = 0; i < libNameCount; i++) { 9165 String libName = libs.get(i); 9166 long version = (versions != null && versions.length == libNameCount) 9167 ? versions[i] : PackageManager.VERSION_CODE_HIGHEST; 9168 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName, version); 9169 if (libPkg != null) { 9170 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 9171 } 9172 } 9173 } 9174 9175 private PackageParser.Package findSharedNonSystemLibrary(String name, long version) { 9176 synchronized (mPackages) { 9177 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(name, version); 9178 if (libEntry != null) { 9179 return mPackages.get(libEntry.apk); 9180 } 9181 return null; 9182 } 9183 } 9184 9185 private SharedLibraryEntry getSharedLibraryEntryLPr(String name, long version) { 9186 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 9187 if (versionedLib == null) { 9188 return null; 9189 } 9190 return versionedLib.get(version); 9191 } 9192 9193 private SharedLibraryEntry getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 9194 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 9195 pkg.staticSharedLibName); 9196 if (versionedLib == null) { 9197 return null; 9198 } 9199 long previousLibVersion = -1; 9200 final int versionCount = versionedLib.size(); 9201 for (int i = 0; i < versionCount; i++) { 9202 final long libVersion = versionedLib.keyAt(i); 9203 if (libVersion < pkg.staticSharedLibVersion) { 9204 previousLibVersion = Math.max(previousLibVersion, libVersion); 9205 } 9206 } 9207 if (previousLibVersion >= 0) { 9208 return versionedLib.get(previousLibVersion); 9209 } 9210 return null; 9211 } 9212 9213 public void shutdown() { 9214 mPackageUsage.writeNow(mPackages); 9215 mCompilerStats.writeNow(); 9216 mDexManager.writePackageDexUsageNow(); 9217 } 9218 9219 @Override 9220 public void dumpProfiles(String packageName) { 9221 PackageParser.Package pkg; 9222 synchronized (mPackages) { 9223 pkg = mPackages.get(packageName); 9224 if (pkg == null) { 9225 throw new IllegalArgumentException("Unknown package: " + packageName); 9226 } 9227 } 9228 /* Only the shell, root, or the app user should be able to dump profiles. */ 9229 int callingUid = Binder.getCallingUid(); 9230 if (callingUid != Process.SHELL_UID && 9231 callingUid != Process.ROOT_UID && 9232 callingUid != pkg.applicationInfo.uid) { 9233 throw new SecurityException("dumpProfiles"); 9234 } 9235 9236 synchronized (mInstallLock) { 9237 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 9238 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 9239 try { 9240 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 9241 String codePaths = TextUtils.join(";", allCodePaths); 9242 mInstaller.dumpProfiles(sharedGid, packageName, codePaths); 9243 } catch (InstallerException e) { 9244 Slog.w(TAG, "Failed to dump profiles", e); 9245 } 9246 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9247 } 9248 } 9249 9250 @Override 9251 public void forceDexOpt(String packageName) { 9252 enforceSystemOrRoot("forceDexOpt"); 9253 9254 PackageParser.Package pkg; 9255 synchronized (mPackages) { 9256 pkg = mPackages.get(packageName); 9257 if (pkg == null) { 9258 throw new IllegalArgumentException("Unknown package: " + packageName); 9259 } 9260 } 9261 9262 synchronized (mInstallLock) { 9263 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9264 9265 // Whoever is calling forceDexOpt wants a compiled package. 9266 // Don't use profiles since that may cause compilation to be skipped. 9267 final int res = performDexOptInternalWithDependenciesLI( 9268 pkg, 9269 new DexoptOptions(packageName, 9270 getDefaultCompilerFilter(), 9271 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 9272 9273 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9274 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 9275 throw new IllegalStateException("Failed to dexopt: " + res); 9276 } 9277 } 9278 } 9279 9280 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 9281 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 9282 Slog.w(TAG, "Unable to update from " + oldPkg.name 9283 + " to " + newPkg.packageName 9284 + ": old package not in system partition"); 9285 return false; 9286 } else if (mPackages.get(oldPkg.name) != null) { 9287 Slog.w(TAG, "Unable to update from " + oldPkg.name 9288 + " to " + newPkg.packageName 9289 + ": old package still exists"); 9290 return false; 9291 } 9292 return true; 9293 } 9294 9295 void removeCodePathLI(File codePath) { 9296 if (codePath.isDirectory()) { 9297 try { 9298 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 9299 } catch (InstallerException e) { 9300 Slog.w(TAG, "Failed to remove code path", e); 9301 } 9302 } else { 9303 codePath.delete(); 9304 } 9305 } 9306 9307 private int[] resolveUserIds(int userId) { 9308 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 9309 } 9310 9311 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9312 if (pkg == null) { 9313 Slog.wtf(TAG, "Package was null!", new Throwable()); 9314 return; 9315 } 9316 clearAppDataLeafLIF(pkg, userId, flags); 9317 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9318 for (int i = 0; i < childCount; i++) { 9319 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9320 } 9321 } 9322 9323 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9324 final PackageSetting ps; 9325 synchronized (mPackages) { 9326 ps = mSettings.mPackages.get(pkg.packageName); 9327 } 9328 for (int realUserId : resolveUserIds(userId)) { 9329 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9330 try { 9331 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9332 ceDataInode); 9333 } catch (InstallerException e) { 9334 Slog.w(TAG, String.valueOf(e)); 9335 } 9336 } 9337 } 9338 9339 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 9340 if (pkg == null) { 9341 Slog.wtf(TAG, "Package was null!", new Throwable()); 9342 return; 9343 } 9344 destroyAppDataLeafLIF(pkg, userId, flags); 9345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9346 for (int i = 0; i < childCount; i++) { 9347 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 9348 } 9349 } 9350 9351 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 9352 final PackageSetting ps; 9353 synchronized (mPackages) { 9354 ps = mSettings.mPackages.get(pkg.packageName); 9355 } 9356 for (int realUserId : resolveUserIds(userId)) { 9357 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 9358 try { 9359 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 9360 ceDataInode); 9361 } catch (InstallerException e) { 9362 Slog.w(TAG, String.valueOf(e)); 9363 } 9364 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 9365 } 9366 } 9367 9368 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 9369 if (pkg == null) { 9370 Slog.wtf(TAG, "Package was null!", new Throwable()); 9371 return; 9372 } 9373 destroyAppProfilesLeafLIF(pkg); 9374 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9375 for (int i = 0; i < childCount; i++) { 9376 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 9377 } 9378 } 9379 9380 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 9381 try { 9382 mInstaller.destroyAppProfiles(pkg.packageName); 9383 } catch (InstallerException e) { 9384 Slog.w(TAG, String.valueOf(e)); 9385 } 9386 } 9387 9388 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 9389 if (pkg == null) { 9390 Slog.wtf(TAG, "Package was null!", new Throwable()); 9391 return; 9392 } 9393 clearAppProfilesLeafLIF(pkg); 9394 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9395 for (int i = 0; i < childCount; i++) { 9396 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 9397 } 9398 } 9399 9400 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 9401 try { 9402 mInstaller.clearAppProfiles(pkg.packageName); 9403 } catch (InstallerException e) { 9404 Slog.w(TAG, String.valueOf(e)); 9405 } 9406 } 9407 9408 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 9409 long lastUpdateTime) { 9410 // Set parent install/update time 9411 PackageSetting ps = (PackageSetting) pkg.mExtras; 9412 if (ps != null) { 9413 ps.firstInstallTime = firstInstallTime; 9414 ps.lastUpdateTime = lastUpdateTime; 9415 } 9416 // Set children install/update time 9417 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9418 for (int i = 0; i < childCount; i++) { 9419 PackageParser.Package childPkg = pkg.childPackages.get(i); 9420 ps = (PackageSetting) childPkg.mExtras; 9421 if (ps != null) { 9422 ps.firstInstallTime = firstInstallTime; 9423 ps.lastUpdateTime = lastUpdateTime; 9424 } 9425 } 9426 } 9427 9428 private void addSharedLibraryLPr(Set<String> usesLibraryFiles, 9429 SharedLibraryEntry file, 9430 PackageParser.Package changingLib) { 9431 if (file.path != null) { 9432 usesLibraryFiles.add(file.path); 9433 return; 9434 } 9435 PackageParser.Package p = mPackages.get(file.apk); 9436 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 9437 // If we are doing this while in the middle of updating a library apk, 9438 // then we need to make sure to use that new apk for determining the 9439 // dependencies here. (We haven't yet finished committing the new apk 9440 // to the package manager state.) 9441 if (p == null || p.packageName.equals(changingLib.packageName)) { 9442 p = changingLib; 9443 } 9444 } 9445 if (p != null) { 9446 usesLibraryFiles.addAll(p.getAllCodePaths()); 9447 if (p.usesLibraryFiles != null) { 9448 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 9449 } 9450 } 9451 } 9452 9453 private void updateSharedLibrariesLPr(PackageParser.Package pkg, 9454 PackageParser.Package changingLib) throws PackageManagerException { 9455 if (pkg == null) { 9456 return; 9457 } 9458 // The collection used here must maintain the order of addition (so 9459 // that libraries are searched in the correct order) and must have no 9460 // duplicates. 9461 Set<String> usesLibraryFiles = null; 9462 if (pkg.usesLibraries != null) { 9463 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesLibraries, 9464 null, null, pkg.packageName, changingLib, true, 9465 pkg.applicationInfo.targetSdkVersion, null); 9466 } 9467 if (pkg.usesStaticLibraries != null) { 9468 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesStaticLibraries, 9469 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 9470 pkg.packageName, changingLib, true, 9471 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9472 } 9473 if (pkg.usesOptionalLibraries != null) { 9474 usesLibraryFiles = addSharedLibrariesLPw(pkg.usesOptionalLibraries, 9475 null, null, pkg.packageName, changingLib, false, 9476 pkg.applicationInfo.targetSdkVersion, usesLibraryFiles); 9477 } 9478 if (!ArrayUtils.isEmpty(usesLibraryFiles)) { 9479 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 9480 } else { 9481 pkg.usesLibraryFiles = null; 9482 } 9483 } 9484 9485 private Set<String> addSharedLibrariesLPw(@NonNull List<String> requestedLibraries, 9486 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 9487 @NonNull String packageName, @Nullable PackageParser.Package changingLib, 9488 boolean required, int targetSdk, @Nullable Set<String> outUsedLibraries) 9489 throws PackageManagerException { 9490 final int libCount = requestedLibraries.size(); 9491 for (int i = 0; i < libCount; i++) { 9492 final String libName = requestedLibraries.get(i); 9493 final long libVersion = requiredVersions != null ? requiredVersions[i] 9494 : SharedLibraryInfo.VERSION_UNDEFINED; 9495 final SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(libName, libVersion); 9496 if (libEntry == null) { 9497 if (required) { 9498 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9499 "Package " + packageName + " requires unavailable shared library " 9500 + libName + "; failing!"); 9501 } else if (DEBUG_SHARED_LIBRARIES) { 9502 Slog.i(TAG, "Package " + packageName 9503 + " desires unavailable shared library " 9504 + libName + "; ignoring!"); 9505 } 9506 } else { 9507 if (requiredVersions != null && requiredCertDigests != null) { 9508 if (libEntry.info.getLongVersion() != requiredVersions[i]) { 9509 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9510 "Package " + packageName + " requires unavailable static shared" 9511 + " library " + libName + " version " 9512 + libEntry.info.getLongVersion() + "; failing!"); 9513 } 9514 9515 PackageParser.Package libPkg = mPackages.get(libEntry.apk); 9516 if (libPkg == null) { 9517 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9518 "Package " + packageName + " requires unavailable static shared" 9519 + " library; failing!"); 9520 } 9521 9522 final String[] expectedCertDigests = requiredCertDigests[i]; 9523 // For apps targeting O MR1 we require explicit enumeration of all certs. 9524 final String[] libCertDigests = (targetSdk > Build.VERSION_CODES.O) 9525 ? PackageUtils.computeSignaturesSha256Digests( 9526 libPkg.mSigningDetails.signatures) 9527 : PackageUtils.computeSignaturesSha256Digests( 9528 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 9529 9530 // Take a shortcut if sizes don't match. Note that if an app doesn't 9531 // target O we don't parse the "additional-certificate" tags similarly 9532 // how we only consider all certs only for apps targeting O (see above). 9533 // Therefore, the size check is safe to make. 9534 if (expectedCertDigests.length != libCertDigests.length) { 9535 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9536 "Package " + packageName + " requires differently signed" + 9537 " static shared library; failing!"); 9538 } 9539 9540 // Use a predictable order as signature order may vary 9541 Arrays.sort(libCertDigests); 9542 Arrays.sort(expectedCertDigests); 9543 9544 final int certCount = libCertDigests.length; 9545 for (int j = 0; j < certCount; j++) { 9546 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 9547 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 9548 "Package " + packageName + " requires differently signed" + 9549 " static shared library; failing!"); 9550 } 9551 } 9552 } 9553 9554 if (outUsedLibraries == null) { 9555 // Use LinkedHashSet to preserve the order of files added to 9556 // usesLibraryFiles while eliminating duplicates. 9557 outUsedLibraries = new LinkedHashSet<>(); 9558 } 9559 addSharedLibraryLPr(outUsedLibraries, libEntry, changingLib); 9560 } 9561 } 9562 return outUsedLibraries; 9563 } 9564 9565 private static boolean hasString(List<String> list, List<String> which) { 9566 if (list == null) { 9567 return false; 9568 } 9569 for (int i=list.size()-1; i>=0; i--) { 9570 for (int j=which.size()-1; j>=0; j--) { 9571 if (which.get(j).equals(list.get(i))) { 9572 return true; 9573 } 9574 } 9575 } 9576 return false; 9577 } 9578 9579 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 9580 PackageParser.Package changingPkg) { 9581 ArrayList<PackageParser.Package> res = null; 9582 for (PackageParser.Package pkg : mPackages.values()) { 9583 if (changingPkg != null 9584 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 9585 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 9586 && !ArrayUtils.contains(pkg.usesStaticLibraries, 9587 changingPkg.staticSharedLibName)) { 9588 return null; 9589 } 9590 if (res == null) { 9591 res = new ArrayList<>(); 9592 } 9593 res.add(pkg); 9594 try { 9595 updateSharedLibrariesLPr(pkg, changingPkg); 9596 } catch (PackageManagerException e) { 9597 // If a system app update or an app and a required lib missing we 9598 // delete the package and for updated system apps keep the data as 9599 // it is better for the user to reinstall than to be in an limbo 9600 // state. Also libs disappearing under an app should never happen 9601 // - just in case. 9602 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 9603 final int flags = pkg.isUpdatedSystemApp() 9604 ? PackageManager.DELETE_KEEP_DATA : 0; 9605 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 9606 flags , null, true, null); 9607 } 9608 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 9609 } 9610 } 9611 return res; 9612 } 9613 9614 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 9615 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9616 @Nullable UserHandle user) throws PackageManagerException { 9617 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 9618 // If the package has children and this is the first dive in the function 9619 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 9620 // whether all packages (parent and children) would be successfully scanned 9621 // before the actual scan since scanning mutates internal state and we want 9622 // to atomically install the package and its children. 9623 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9624 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9625 scanFlags |= SCAN_CHECK_ONLY; 9626 } 9627 } else { 9628 scanFlags &= ~SCAN_CHECK_ONLY; 9629 } 9630 9631 final PackageParser.Package scannedPkg; 9632 try { 9633 // Scan the parent 9634 scannedPkg = scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user); 9635 // Scan the children 9636 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9637 for (int i = 0; i < childCount; i++) { 9638 PackageParser.Package childPkg = pkg.childPackages.get(i); 9639 scanPackageNewLI(childPkg, parseFlags, 9640 scanFlags, currentTime, user); 9641 } 9642 } finally { 9643 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9644 } 9645 9646 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9647 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 9648 } 9649 9650 return scannedPkg; 9651 } 9652 9653 /** The result of a package scan. */ 9654 private static class ScanResult { 9655 /** Whether or not the package scan was successful */ 9656 public final boolean success; 9657 /** 9658 * The final package settings. This may be the same object passed in 9659 * the {@link ScanRequest}, but, with modified values. 9660 */ 9661 @Nullable public final PackageSetting pkgSetting; 9662 /** ABI code paths that have changed in the package scan */ 9663 @Nullable public final List<String> changedAbiCodePath; 9664 public ScanResult( 9665 boolean success, 9666 @Nullable PackageSetting pkgSetting, 9667 @Nullable List<String> changedAbiCodePath) { 9668 this.success = success; 9669 this.pkgSetting = pkgSetting; 9670 this.changedAbiCodePath = changedAbiCodePath; 9671 } 9672 } 9673 9674 /** A package to be scanned */ 9675 private static class ScanRequest { 9676 /** The parsed package */ 9677 @NonNull public final PackageParser.Package pkg; 9678 /** Shared user settings, if the package has a shared user */ 9679 @Nullable public final SharedUserSetting sharedUserSetting; 9680 /** 9681 * Package settings of the currently installed version. 9682 * <p><em>IMPORTANT:</em> The contents of this object may be modified 9683 * during scan. 9684 */ 9685 @Nullable public final PackageSetting pkgSetting; 9686 /** A copy of the settings for the currently installed version */ 9687 @Nullable public final PackageSetting oldPkgSetting; 9688 /** Package settings for the disabled version on the /system partition */ 9689 @Nullable public final PackageSetting disabledPkgSetting; 9690 /** Package settings for the installed version under its original package name */ 9691 @Nullable public final PackageSetting originalPkgSetting; 9692 /** The real package name of a renamed application */ 9693 @Nullable public final String realPkgName; 9694 public final @ParseFlags int parseFlags; 9695 public final @ScanFlags int scanFlags; 9696 /** The user for which the package is being scanned */ 9697 @Nullable public final UserHandle user; 9698 /** Whether or not the platform package is being scanned */ 9699 public final boolean isPlatformPackage; 9700 public ScanRequest( 9701 @NonNull PackageParser.Package pkg, 9702 @Nullable SharedUserSetting sharedUserSetting, 9703 @Nullable PackageSetting pkgSetting, 9704 @Nullable PackageSetting disabledPkgSetting, 9705 @Nullable PackageSetting originalPkgSetting, 9706 @Nullable String realPkgName, 9707 @ParseFlags int parseFlags, 9708 @ScanFlags int scanFlags, 9709 boolean isPlatformPackage, 9710 @Nullable UserHandle user) { 9711 this.pkg = pkg; 9712 this.pkgSetting = pkgSetting; 9713 this.sharedUserSetting = sharedUserSetting; 9714 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 9715 this.disabledPkgSetting = disabledPkgSetting; 9716 this.originalPkgSetting = originalPkgSetting; 9717 this.realPkgName = realPkgName; 9718 this.parseFlags = parseFlags; 9719 this.scanFlags = scanFlags; 9720 this.isPlatformPackage = isPlatformPackage; 9721 this.user = user; 9722 } 9723 } 9724 9725 /** 9726 * Returns the actual scan flags depending upon the state of the other settings. 9727 * <p>Updated system applications will not have the following flags set 9728 * by default and need to be adjusted after the fact: 9729 * <ul> 9730 * <li>{@link #SCAN_AS_SYSTEM}</li> 9731 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 9732 * <li>{@link #SCAN_AS_OEM}</li> 9733 * <li>{@link #SCAN_AS_VENDOR}</li> 9734 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 9735 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 9736 * </ul> 9737 */ 9738 private static @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 9739 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user) { 9740 if (disabledPkgSetting != null) { 9741 // updated system application, must at least have SCAN_AS_SYSTEM 9742 scanFlags |= SCAN_AS_SYSTEM; 9743 if ((disabledPkgSetting.pkgPrivateFlags 9744 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 9745 scanFlags |= SCAN_AS_PRIVILEGED; 9746 } 9747 if ((disabledPkgSetting.pkgPrivateFlags 9748 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 9749 scanFlags |= SCAN_AS_OEM; 9750 } 9751 if ((disabledPkgSetting.pkgPrivateFlags 9752 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 9753 scanFlags |= SCAN_AS_VENDOR; 9754 } 9755 } 9756 if (pkgSetting != null) { 9757 final int userId = ((user == null) ? 0 : user.getIdentifier()); 9758 if (pkgSetting.getInstantApp(userId)) { 9759 scanFlags |= SCAN_AS_INSTANT_APP; 9760 } 9761 if (pkgSetting.getVirtulalPreload(userId)) { 9762 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 9763 } 9764 } 9765 return scanFlags; 9766 } 9767 9768 @GuardedBy("mInstallLock") 9769 private PackageParser.Package scanPackageNewLI(@NonNull PackageParser.Package pkg, 9770 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9771 @Nullable UserHandle user) throws PackageManagerException { 9772 9773 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9774 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9775 if (realPkgName != null) { 9776 ensurePackageRenamed(pkg, renamedPkgName); 9777 } 9778 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9779 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 9780 final PackageSetting disabledPkgSetting = 9781 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9782 9783 if (mTransferedPackages.contains(pkg.packageName)) { 9784 Slog.w(TAG, "Package " + pkg.packageName 9785 + " was transferred to another, but its .apk remains"); 9786 } 9787 9788 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user); 9789 synchronized (mPackages) { 9790 applyPolicy(pkg, parseFlags, scanFlags); 9791 assertPackageIsValid(pkg, parseFlags, scanFlags); 9792 9793 SharedUserSetting sharedUserSetting = null; 9794 if (pkg.mSharedUserId != null) { 9795 // SIDE EFFECTS; may potentially allocate a new shared user 9796 sharedUserSetting = mSettings.getSharedUserLPw( 9797 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 9798 if (DEBUG_PACKAGE_SCANNING) { 9799 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 9800 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9801 + " (uid=" + sharedUserSetting.userId + "):" 9802 + " packages=" + sharedUserSetting.packages); 9803 } 9804 } 9805 9806 boolean scanSucceeded = false; 9807 try { 9808 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, pkgSetting, 9809 disabledPkgSetting, originalPkgSetting, realPkgName, parseFlags, scanFlags, 9810 (pkg == mPlatformPackage), user); 9811 final ScanResult result = scanPackageOnlyLI(request, mFactoryTest, currentTime); 9812 if (result.success) { 9813 commitScanResultsLocked(request, result); 9814 } 9815 scanSucceeded = true; 9816 } finally { 9817 if (!scanSucceeded && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 9818 // DELETE_DATA_ON_FAILURES is only used by frozen paths 9819 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 9820 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 9821 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 9822 } 9823 } 9824 } 9825 return pkg; 9826 } 9827 9828 /** 9829 * Commits the package scan and modifies system state. 9830 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 9831 * of committing the package, leaving the system in an inconsistent state. 9832 * This needs to be fixed so, once we get to this point, no errors are 9833 * possible and the system is not left in an inconsistent state. 9834 */ 9835 @GuardedBy("mPackages") 9836 private void commitScanResultsLocked(@NonNull ScanRequest request, @NonNull ScanResult result) 9837 throws PackageManagerException { 9838 final PackageParser.Package pkg = request.pkg; 9839 final @ParseFlags int parseFlags = request.parseFlags; 9840 final @ScanFlags int scanFlags = request.scanFlags; 9841 final PackageSetting oldPkgSetting = request.oldPkgSetting; 9842 final PackageSetting originalPkgSetting = request.originalPkgSetting; 9843 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 9844 final UserHandle user = request.user; 9845 final String realPkgName = request.realPkgName; 9846 final PackageSetting pkgSetting = result.pkgSetting; 9847 final List<String> changedAbiCodePath = result.changedAbiCodePath; 9848 final boolean newPkgSettingCreated = (result.pkgSetting != request.pkgSetting); 9849 9850 if (newPkgSettingCreated) { 9851 if (originalPkgSetting != null) { 9852 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 9853 } 9854 // THROWS: when we can't allocate a user id. add call to check if there's 9855 // enough space to ensure we won't throw; otherwise, don't modify state 9856 mSettings.addUserToSettingLPw(pkgSetting); 9857 9858 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 9859 mTransferedPackages.add(originalPkgSetting.name); 9860 } 9861 } 9862 // TODO(toddke): Consider a method specifically for modifying the Package object 9863 // post scan; or, moving this stuff out of the Package object since it has nothing 9864 // to do with the package on disk. 9865 // We need to have this here because addUserToSettingLPw() is sometimes responsible 9866 // for creating the application ID. If we did this earlier, we would be saving the 9867 // correct ID. 9868 pkg.applicationInfo.uid = pkgSetting.appId; 9869 9870 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 9871 9872 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 9873 mTransferedPackages.add(pkg.packageName); 9874 } 9875 9876 // THROWS: when requested libraries that can't be found. it only changes 9877 // the state of the passed in pkg object, so, move to the top of the method 9878 // and allow it to abort 9879 if ((scanFlags & SCAN_BOOTING) == 0 9880 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9881 // Check all shared libraries and map to their actual file path. 9882 // We only do this here for apps not on a system dir, because those 9883 // are the only ones that can fail an install due to this. We 9884 // will take care of the system apps by updating all of their 9885 // library paths after the scan is done. Also during the initial 9886 // scan don't update any libs as we do this wholesale after all 9887 // apps are scanned to avoid dependency based scanning. 9888 updateSharedLibrariesLPr(pkg, null); 9889 } 9890 9891 // All versions of a static shared library are referenced with the same 9892 // package name. Internally, we use a synthetic package name to allow 9893 // multiple versions of the same shared library to be installed. So, 9894 // we need to generate the synthetic package name of the latest shared 9895 // library in order to compare signatures. 9896 PackageSetting signatureCheckPs = pkgSetting; 9897 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9898 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 9899 if (libraryEntry != null) { 9900 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 9901 } 9902 } 9903 9904 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 9905 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 9906 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 9907 // We just determined the app is signed correctly, so bring 9908 // over the latest parsed certs. 9909 pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures; 9910 } else { 9911 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9912 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9913 "Package " + pkg.packageName + " upgrade keys do not match the " 9914 + "previously installed version"); 9915 } else { 9916 pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures; 9917 String msg = "System package " + pkg.packageName 9918 + " signature changed; retaining data."; 9919 reportSettingsProblem(Log.WARN, msg); 9920 } 9921 } 9922 } else { 9923 try { 9924 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 9925 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 9926 final boolean compatMatch = verifySignatures(signatureCheckPs, disabledPkgSetting, 9927 pkg.mSigningDetails, compareCompat, compareRecover); 9928 // The new KeySets will be re-added later in the scanning process. 9929 if (compatMatch) { 9930 synchronized (mPackages) { 9931 ksms.removeAppKeySetDataLPw(pkg.packageName); 9932 } 9933 } 9934 // We just determined the app is signed correctly, so bring 9935 // over the latest parsed certs. 9936 pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures; 9937 } catch (PackageManagerException e) { 9938 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 9939 throw e; 9940 } 9941 // The signature has changed, but this package is in the system 9942 // image... let's recover! 9943 pkgSetting.signatures.mSignatures = pkg.mSigningDetails.signatures; 9944 // However... if this package is part of a shared user, but it 9945 // doesn't match the signature of the shared user, let's fail. 9946 // What this means is that you can't change the signatures 9947 // associated with an overall shared user, which doesn't seem all 9948 // that unreasonable. 9949 if (signatureCheckPs.sharedUser != null) { 9950 if (compareSignatures(signatureCheckPs.sharedUser.signatures.mSignatures, 9951 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH) { 9952 throw new PackageManagerException( 9953 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 9954 "Signature mismatch for shared user: " 9955 + pkgSetting.sharedUser); 9956 } 9957 } 9958 // File a report about this. 9959 String msg = "System package " + pkg.packageName 9960 + " signature changed; retaining data."; 9961 reportSettingsProblem(Log.WARN, msg); 9962 } 9963 } 9964 9965 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 9966 // This package wants to adopt ownership of permissions from 9967 // another package. 9968 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 9969 final String origName = pkg.mAdoptPermissions.get(i); 9970 final PackageSetting orig = mSettings.getPackageLPr(origName); 9971 if (orig != null) { 9972 if (verifyPackageUpdateLPr(orig, pkg)) { 9973 Slog.i(TAG, "Adopting permissions from " + origName + " to " 9974 + pkg.packageName); 9975 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 9976 } 9977 } 9978 } 9979 } 9980 9981 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 9982 for (int i = changedAbiCodePath.size() - 1; i <= 0; --i) { 9983 final String codePathString = changedAbiCodePath.get(i); 9984 try { 9985 mInstaller.rmdex(codePathString, 9986 getDexCodeInstructionSet(getPreferredInstructionSet())); 9987 } catch (InstallerException ignored) { 9988 } 9989 } 9990 } 9991 9992 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9993 if (oldPkgSetting != null) { 9994 synchronized (mPackages) { 9995 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 9996 } 9997 } 9998 } else { 9999 final int userId = user == null ? 0 : user.getIdentifier(); 10000 // Modify state for the given package setting 10001 commitPackageSettings(pkg, pkgSetting, user, scanFlags, 10002 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/); 10003 if (pkgSetting.getInstantApp(userId)) { 10004 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 10005 } 10006 } 10007 } 10008 10009 /** 10010 * Returns the "real" name of the package. 10011 * <p>This may differ from the package's actual name if the application has already 10012 * been installed under one of this package's original names. 10013 */ 10014 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 10015 @Nullable String renamedPkgName) { 10016 if (isPackageRenamed(pkg, renamedPkgName)) { 10017 return pkg.mRealPackage; 10018 } 10019 return null; 10020 } 10021 10022 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 10023 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 10024 @Nullable String renamedPkgName) { 10025 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 10026 } 10027 10028 /** 10029 * Returns the original package setting. 10030 * <p>A package can migrate its name during an update. In this scenario, a package 10031 * designates a set of names that it considers as one of its original names. 10032 * <p>An original package must be signed identically and it must have the same 10033 * shared user [if any]. 10034 */ 10035 @GuardedBy("mPackages") 10036 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 10037 @Nullable String renamedPkgName) { 10038 if (!isPackageRenamed(pkg, renamedPkgName)) { 10039 return null; 10040 } 10041 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 10042 final PackageSetting originalPs = 10043 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 10044 if (originalPs != null) { 10045 // the package is already installed under its original name... 10046 // but, should we use it? 10047 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 10048 // the new package is incompatible with the original 10049 continue; 10050 } else if (originalPs.sharedUser != null) { 10051 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 10052 // the shared user id is incompatible with the original 10053 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 10054 + " to " + pkg.packageName + ": old uid " 10055 + originalPs.sharedUser.name 10056 + " differs from " + pkg.mSharedUserId); 10057 continue; 10058 } 10059 // TODO: Add case when shared user id is added [b/28144775] 10060 } else { 10061 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 10062 + pkg.packageName + " to old name " + originalPs.name); 10063 } 10064 return originalPs; 10065 } 10066 } 10067 return null; 10068 } 10069 10070 /** 10071 * Renames the package if it was installed under a different name. 10072 * <p>When we've already installed the package under an original name, update 10073 * the new package so we can continue to have the old name. 10074 */ 10075 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 10076 @NonNull String renamedPackageName) { 10077 if (pkg.mOriginalPackages == null 10078 || !pkg.mOriginalPackages.contains(renamedPackageName) 10079 || pkg.packageName.equals(renamedPackageName)) { 10080 return; 10081 } 10082 pkg.setPackageName(renamedPackageName); 10083 } 10084 10085 /** 10086 * Just scans the package without any side effects. 10087 * <p>Not entirely true at the moment. There is still one side effect -- this 10088 * method potentially modifies a live {@link PackageSetting} object representing 10089 * the package being scanned. This will be resolved in the future. 10090 * 10091 * @param request Information about the package to be scanned 10092 * @param isUnderFactoryTest Whether or not the device is under factory test 10093 * @param currentTime The current time, in millis 10094 * @return The results of the scan 10095 */ 10096 @GuardedBy("mInstallLock") 10097 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 10098 boolean isUnderFactoryTest, long currentTime) 10099 throws PackageManagerException { 10100 final PackageParser.Package pkg = request.pkg; 10101 PackageSetting pkgSetting = request.pkgSetting; 10102 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 10103 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10104 final @ParseFlags int parseFlags = request.parseFlags; 10105 final @ScanFlags int scanFlags = request.scanFlags; 10106 final String realPkgName = request.realPkgName; 10107 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 10108 final UserHandle user = request.user; 10109 final boolean isPlatformPackage = request.isPlatformPackage; 10110 10111 List<String> changedAbiCodePath = null; 10112 10113 if (DEBUG_PACKAGE_SCANNING) { 10114 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10115 Log.d(TAG, "Scanning package " + pkg.packageName); 10116 } 10117 10118 if (Build.IS_DEBUGGABLE && 10119 pkg.isPrivileged() && 10120 !SystemProperties.getBoolean("pm.dexopt.priv-apps", true)) { 10121 PackageManagerServiceUtils.logPackageHasUncompressedCode(pkg); 10122 } 10123 10124 // Initialize package source and resource directories 10125 final File scanFile = new File(pkg.codePath); 10126 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 10127 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 10128 10129 // We keep references to the derived CPU Abis from settings in oder to reuse 10130 // them in the case where we're not upgrading or booting for the first time. 10131 String primaryCpuAbiFromSettings = null; 10132 String secondaryCpuAbiFromSettings = null; 10133 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 10134 10135 if (!needToDeriveAbi) { 10136 if (pkgSetting != null) { 10137 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 10138 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 10139 } else { 10140 // Re-scanning a system package after uninstalling updates; need to derive ABI 10141 needToDeriveAbi = true; 10142 } 10143 } 10144 10145 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 10146 PackageManagerService.reportSettingsProblem(Log.WARN, 10147 "Package " + pkg.packageName + " shared user changed from " 10148 + (pkgSetting.sharedUser != null 10149 ? pkgSetting.sharedUser.name : "<nothing>") 10150 + " to " 10151 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 10152 + "; replacing with new"); 10153 pkgSetting = null; 10154 } 10155 10156 String[] usesStaticLibraries = null; 10157 if (pkg.usesStaticLibraries != null) { 10158 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 10159 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 10160 } 10161 final boolean createNewPackage = (pkgSetting == null); 10162 if (createNewPackage) { 10163 final String parentPackageName = (pkg.parentPackage != null) 10164 ? pkg.parentPackage.packageName : null; 10165 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 10166 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 10167 // REMOVE SharedUserSetting from method; update in a separate call 10168 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 10169 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 10170 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 10171 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10172 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10173 user, true /*allowInstall*/, instantApp, virtualPreload, 10174 parentPackageName, pkg.getChildPackageNames(), 10175 UserManagerService.getInstance(), usesStaticLibraries, 10176 pkg.usesStaticLibrariesVersions); 10177 } else { 10178 // REMOVE SharedUserSetting from method; update in a separate call. 10179 // 10180 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 10181 // secondaryCpuAbi are not known at this point so we always update them 10182 // to null here, only to reset them at a later point. 10183 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 10184 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 10185 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 10186 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 10187 pkg.getChildPackageNames(), UserManagerService.getInstance(), 10188 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 10189 } 10190 if (createNewPackage && originalPkgSetting != null) { 10191 // This is the initial transition from the original package, so, 10192 // fix up the new package's name now. We must do this after looking 10193 // up the package under its new name, so getPackageLP takes care of 10194 // fiddling things correctly. 10195 pkg.setPackageName(originalPkgSetting.name); 10196 10197 // File a report about this. 10198 String msg = "New package " + pkgSetting.realName 10199 + " renamed to replace old package " + pkgSetting.name; 10200 reportSettingsProblem(Log.WARN, msg); 10201 } 10202 10203 if (disabledPkgSetting != null) { 10204 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 10205 } 10206 10207 SELinuxMMAC.assignSeInfoValue(pkg); 10208 10209 pkg.mExtras = pkgSetting; 10210 pkg.applicationInfo.processName = fixProcessName( 10211 pkg.applicationInfo.packageName, 10212 pkg.applicationInfo.processName); 10213 10214 if (!isPlatformPackage) { 10215 // Get all of our default paths setup 10216 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 10217 } 10218 10219 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 10220 10221 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 10222 if (needToDeriveAbi) { 10223 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 10224 final boolean extractNativeLibs = !pkg.isLibrary(); 10225 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 10226 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10227 10228 // Some system apps still use directory structure for native libraries 10229 // in which case we might end up not detecting abi solely based on apk 10230 // structure. Try to detect abi based on directory structure. 10231 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 10232 pkg.applicationInfo.primaryCpuAbi == null) { 10233 setBundledAppAbisAndRoots(pkg, pkgSetting); 10234 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10235 } 10236 } else { 10237 // This is not a first boot or an upgrade, don't bother deriving the 10238 // ABI during the scan. Instead, trust the value that was stored in the 10239 // package setting. 10240 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 10241 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 10242 10243 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10244 10245 if (DEBUG_ABI_SELECTION) { 10246 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 10247 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 10248 pkg.applicationInfo.secondaryCpuAbi); 10249 } 10250 } 10251 } else { 10252 if ((scanFlags & SCAN_MOVE) != 0) { 10253 // We haven't run dex-opt for this move (since we've moved the compiled output too) 10254 // but we already have this packages package info in the PackageSetting. We just 10255 // use that and derive the native library path based on the new codepath. 10256 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 10257 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 10258 } 10259 10260 // Set native library paths again. For moves, the path will be updated based on the 10261 // ABIs we've determined above. For non-moves, the path will be updated based on the 10262 // ABIs we determined during compilation, but the path will depend on the final 10263 // package path (after the rename away from the stage path). 10264 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 10265 } 10266 10267 // This is a special case for the "system" package, where the ABI is 10268 // dictated by the zygote configuration (and init.rc). We should keep track 10269 // of this ABI so that we can deal with "normal" applications that run under 10270 // the same UID correctly. 10271 if (isPlatformPackage) { 10272 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 10273 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 10274 } 10275 10276 // If there's a mismatch between the abi-override in the package setting 10277 // and the abiOverride specified for the install. Warn about this because we 10278 // would've already compiled the app without taking the package setting into 10279 // account. 10280 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 10281 if (cpuAbiOverride == null && pkg.packageName != null) { 10282 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 10283 " for package " + pkg.packageName); 10284 } 10285 } 10286 10287 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 10288 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 10289 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 10290 10291 // Copy the derived override back to the parsed package, so that we can 10292 // update the package settings accordingly. 10293 pkg.cpuAbiOverride = cpuAbiOverride; 10294 10295 if (DEBUG_ABI_SELECTION) { 10296 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 10297 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 10298 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 10299 } 10300 10301 // Push the derived path down into PackageSettings so we know what to 10302 // clean up at uninstall time. 10303 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 10304 10305 if (DEBUG_ABI_SELECTION) { 10306 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 10307 " primary=" + pkg.applicationInfo.primaryCpuAbi + 10308 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 10309 } 10310 10311 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 10312 // We don't do this here during boot because we can do it all 10313 // at once after scanning all existing packages. 10314 // 10315 // We also do this *before* we perform dexopt on this package, so that 10316 // we can avoid redundant dexopts, and also to make sure we've got the 10317 // code and package path correct. 10318 changedAbiCodePath = 10319 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 10320 } 10321 10322 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 10323 android.Manifest.permission.FACTORY_TEST)) { 10324 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 10325 } 10326 10327 if (isSystemApp(pkg)) { 10328 pkgSetting.isOrphaned = true; 10329 } 10330 10331 // Take care of first install / last update times. 10332 final long scanFileTime = getLastModifiedTime(pkg); 10333 if (currentTime != 0) { 10334 if (pkgSetting.firstInstallTime == 0) { 10335 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 10336 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 10337 pkgSetting.lastUpdateTime = currentTime; 10338 } 10339 } else if (pkgSetting.firstInstallTime == 0) { 10340 // We need *something*. Take time time stamp of the file. 10341 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 10342 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 10343 if (scanFileTime != pkgSetting.timeStamp) { 10344 // A package on the system image has changed; consider this 10345 // to be an update. 10346 pkgSetting.lastUpdateTime = scanFileTime; 10347 } 10348 } 10349 pkgSetting.setTimeStamp(scanFileTime); 10350 10351 pkgSetting.pkg = pkg; 10352 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 10353 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 10354 pkgSetting.versionCode = pkg.getLongVersionCode(); 10355 } 10356 // Update volume if needed 10357 final String volumeUuid = pkg.applicationInfo.volumeUuid; 10358 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 10359 Slog.i(PackageManagerService.TAG, 10360 "Update" + (pkgSetting.isSystem() ? " system" : "") 10361 + " package " + pkg.packageName 10362 + " volume from " + pkgSetting.volumeUuid 10363 + " to " + volumeUuid); 10364 pkgSetting.volumeUuid = volumeUuid; 10365 } 10366 10367 return new ScanResult(true, pkgSetting, changedAbiCodePath); 10368 } 10369 10370 /** 10371 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 10372 */ 10373 private static boolean apkHasCode(String fileName) { 10374 StrictJarFile jarFile = null; 10375 try { 10376 jarFile = new StrictJarFile(fileName, 10377 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 10378 return jarFile.findEntry("classes.dex") != null; 10379 } catch (IOException ignore) { 10380 } finally { 10381 try { 10382 if (jarFile != null) { 10383 jarFile.close(); 10384 } 10385 } catch (IOException ignore) {} 10386 } 10387 return false; 10388 } 10389 10390 /** 10391 * Enforces code policy for the package. This ensures that if an APK has 10392 * declared hasCode="true" in its manifest that the APK actually contains 10393 * code. 10394 * 10395 * @throws PackageManagerException If bytecode could not be found when it should exist 10396 */ 10397 private static void assertCodePolicy(PackageParser.Package pkg) 10398 throws PackageManagerException { 10399 final boolean shouldHaveCode = 10400 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 10401 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 10402 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10403 "Package " + pkg.baseCodePath + " code is missing"); 10404 } 10405 10406 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 10407 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 10408 final boolean splitShouldHaveCode = 10409 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 10410 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 10411 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10412 "Package " + pkg.splitCodePaths[i] + " code is missing"); 10413 } 10414 } 10415 } 10416 } 10417 10418 /** 10419 * Applies policy to the parsed package based upon the given policy flags. 10420 * Ensures the package is in a good state. 10421 * <p> 10422 * Implementation detail: This method must NOT have any side effect. It would 10423 * ideally be static, but, it requires locks to read system state. 10424 */ 10425 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10426 final @ScanFlags int scanFlags) { 10427 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 10428 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 10429 if (pkg.applicationInfo.isDirectBootAware()) { 10430 // we're direct boot aware; set for all components 10431 for (PackageParser.Service s : pkg.services) { 10432 s.info.encryptionAware = s.info.directBootAware = true; 10433 } 10434 for (PackageParser.Provider p : pkg.providers) { 10435 p.info.encryptionAware = p.info.directBootAware = true; 10436 } 10437 for (PackageParser.Activity a : pkg.activities) { 10438 a.info.encryptionAware = a.info.directBootAware = true; 10439 } 10440 for (PackageParser.Activity r : pkg.receivers) { 10441 r.info.encryptionAware = r.info.directBootAware = true; 10442 } 10443 } 10444 if (compressedFileExists(pkg.codePath)) { 10445 pkg.isStub = true; 10446 } 10447 } else { 10448 // non system apps can't be flagged as core 10449 pkg.coreApp = false; 10450 // clear flags not applicable to regular apps 10451 pkg.applicationInfo.flags &= 10452 ~ApplicationInfo.FLAG_PERSISTENT; 10453 pkg.applicationInfo.privateFlags &= 10454 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 10455 pkg.applicationInfo.privateFlags &= 10456 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 10457 // clear protected broadcasts 10458 pkg.protectedBroadcasts = null; 10459 // cap permission priorities 10460 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 10461 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 10462 pkg.permissionGroups.get(i).info.priority = 0; 10463 } 10464 } 10465 } 10466 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10467 // ignore export request for single user receivers 10468 if (pkg.receivers != null) { 10469 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 10470 final PackageParser.Activity receiver = pkg.receivers.get(i); 10471 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 10472 receiver.info.exported = false; 10473 } 10474 } 10475 } 10476 // ignore export request for single user services 10477 if (pkg.services != null) { 10478 for (int i = pkg.services.size() - 1; i >= 0; --i) { 10479 final PackageParser.Service service = pkg.services.get(i); 10480 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 10481 service.info.exported = false; 10482 } 10483 } 10484 } 10485 // ignore export request for single user providers 10486 if (pkg.providers != null) { 10487 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 10488 final PackageParser.Provider provider = pkg.providers.get(i); 10489 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 10490 provider.info.exported = false; 10491 } 10492 } 10493 } 10494 } 10495 pkg.mTrustedOverlay = (scanFlags & SCAN_TRUSTED_OVERLAY) != 0; 10496 10497 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 10498 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 10499 } 10500 10501 if ((scanFlags & SCAN_AS_OEM) != 0) { 10502 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 10503 } 10504 10505 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 10506 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 10507 } 10508 10509 if (!isSystemApp(pkg)) { 10510 // Only system apps can use these features. 10511 pkg.mOriginalPackages = null; 10512 pkg.mRealPackage = null; 10513 pkg.mAdoptPermissions = null; 10514 } 10515 } 10516 10517 /** 10518 * Asserts the parsed package is valid according to the given policy. If the 10519 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 10520 * <p> 10521 * Implementation detail: This method must NOT have any side effects. It would 10522 * ideally be static, but, it requires locks to read system state. 10523 * 10524 * @throws PackageManagerException If the package fails any of the validation checks 10525 */ 10526 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 10527 final @ScanFlags int scanFlags) 10528 throws PackageManagerException { 10529 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 10530 assertCodePolicy(pkg); 10531 } 10532 10533 if (pkg.applicationInfo.getCodePath() == null || 10534 pkg.applicationInfo.getResourcePath() == null) { 10535 // Bail out. The resource and code paths haven't been set. 10536 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 10537 "Code and resource paths haven't been set correctly"); 10538 } 10539 10540 // Make sure we're not adding any bogus keyset info 10541 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 10542 ksms.assertScannedPackageValid(pkg); 10543 10544 synchronized (mPackages) { 10545 // The special "android" package can only be defined once 10546 if (pkg.packageName.equals("android")) { 10547 if (mAndroidApplication != null) { 10548 Slog.w(TAG, "*************************************************"); 10549 Slog.w(TAG, "Core android package being redefined. Skipping."); 10550 Slog.w(TAG, " codePath=" + pkg.codePath); 10551 Slog.w(TAG, "*************************************************"); 10552 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10553 "Core android package being redefined. Skipping."); 10554 } 10555 } 10556 10557 // A package name must be unique; don't allow duplicates 10558 if (mPackages.containsKey(pkg.packageName)) { 10559 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 10560 "Application package " + pkg.packageName 10561 + " already installed. Skipping duplicate."); 10562 } 10563 10564 if (pkg.applicationInfo.isStaticSharedLibrary()) { 10565 // Static libs have a synthetic package name containing the version 10566 // but we still want the base name to be unique. 10567 if (mPackages.containsKey(pkg.manifestPackageName)) { 10568 throw new PackageManagerException( 10569 "Duplicate static shared lib provider package"); 10570 } 10571 10572 // Static shared libraries should have at least O target SDK 10573 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 10574 throw new PackageManagerException( 10575 "Packages declaring static-shared libs must target O SDK or higher"); 10576 } 10577 10578 // Package declaring static a shared lib cannot be instant apps 10579 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 10580 throw new PackageManagerException( 10581 "Packages declaring static-shared libs cannot be instant apps"); 10582 } 10583 10584 // Package declaring static a shared lib cannot be renamed since the package 10585 // name is synthetic and apps can't code around package manager internals. 10586 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 10587 throw new PackageManagerException( 10588 "Packages declaring static-shared libs cannot be renamed"); 10589 } 10590 10591 // Package declaring static a shared lib cannot declare child packages 10592 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 10593 throw new PackageManagerException( 10594 "Packages declaring static-shared libs cannot have child packages"); 10595 } 10596 10597 // Package declaring static a shared lib cannot declare dynamic libs 10598 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 10599 throw new PackageManagerException( 10600 "Packages declaring static-shared libs cannot declare dynamic libs"); 10601 } 10602 10603 // Package declaring static a shared lib cannot declare shared users 10604 if (pkg.mSharedUserId != null) { 10605 throw new PackageManagerException( 10606 "Packages declaring static-shared libs cannot declare shared users"); 10607 } 10608 10609 // Static shared libs cannot declare activities 10610 if (!pkg.activities.isEmpty()) { 10611 throw new PackageManagerException( 10612 "Static shared libs cannot declare activities"); 10613 } 10614 10615 // Static shared libs cannot declare services 10616 if (!pkg.services.isEmpty()) { 10617 throw new PackageManagerException( 10618 "Static shared libs cannot declare services"); 10619 } 10620 10621 // Static shared libs cannot declare providers 10622 if (!pkg.providers.isEmpty()) { 10623 throw new PackageManagerException( 10624 "Static shared libs cannot declare content providers"); 10625 } 10626 10627 // Static shared libs cannot declare receivers 10628 if (!pkg.receivers.isEmpty()) { 10629 throw new PackageManagerException( 10630 "Static shared libs cannot declare broadcast receivers"); 10631 } 10632 10633 // Static shared libs cannot declare permission groups 10634 if (!pkg.permissionGroups.isEmpty()) { 10635 throw new PackageManagerException( 10636 "Static shared libs cannot declare permission groups"); 10637 } 10638 10639 // Static shared libs cannot declare permissions 10640 if (!pkg.permissions.isEmpty()) { 10641 throw new PackageManagerException( 10642 "Static shared libs cannot declare permissions"); 10643 } 10644 10645 // Static shared libs cannot declare protected broadcasts 10646 if (pkg.protectedBroadcasts != null) { 10647 throw new PackageManagerException( 10648 "Static shared libs cannot declare protected broadcasts"); 10649 } 10650 10651 // Static shared libs cannot be overlay targets 10652 if (pkg.mOverlayTarget != null) { 10653 throw new PackageManagerException( 10654 "Static shared libs cannot be overlay targets"); 10655 } 10656 10657 // The version codes must be ordered as lib versions 10658 long minVersionCode = Long.MIN_VALUE; 10659 long maxVersionCode = Long.MAX_VALUE; 10660 10661 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get( 10662 pkg.staticSharedLibName); 10663 if (versionedLib != null) { 10664 final int versionCount = versionedLib.size(); 10665 for (int i = 0; i < versionCount; i++) { 10666 SharedLibraryInfo libInfo = versionedLib.valueAt(i).info; 10667 final long libVersionCode = libInfo.getDeclaringPackage() 10668 .getLongVersionCode(); 10669 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 10670 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 10671 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 10672 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 10673 } else { 10674 minVersionCode = maxVersionCode = libVersionCode; 10675 break; 10676 } 10677 } 10678 } 10679 if (pkg.getLongVersionCode() < minVersionCode 10680 || pkg.getLongVersionCode() > maxVersionCode) { 10681 throw new PackageManagerException("Static shared" 10682 + " lib version codes must be ordered as lib versions"); 10683 } 10684 } 10685 10686 // Only privileged apps and updated privileged apps can add child packages. 10687 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 10688 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 10689 throw new PackageManagerException("Only privileged apps can add child " 10690 + "packages. Ignoring package " + pkg.packageName); 10691 } 10692 final int childCount = pkg.childPackages.size(); 10693 for (int i = 0; i < childCount; i++) { 10694 PackageParser.Package childPkg = pkg.childPackages.get(i); 10695 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 10696 childPkg.packageName)) { 10697 throw new PackageManagerException("Can't override child of " 10698 + "another disabled app. Ignoring package " + pkg.packageName); 10699 } 10700 } 10701 } 10702 10703 // If we're only installing presumed-existing packages, require that the 10704 // scanned APK is both already known and at the path previously established 10705 // for it. Previously unknown packages we pick up normally, but if we have an 10706 // a priori expectation about this package's install presence, enforce it. 10707 // With a singular exception for new system packages. When an OTA contains 10708 // a new system package, we allow the codepath to change from a system location 10709 // to the user-installed location. If we don't allow this change, any newer, 10710 // user-installed version of the application will be ignored. 10711 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 10712 if (mExpectingBetter.containsKey(pkg.packageName)) { 10713 logCriticalInfo(Log.WARN, 10714 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 10715 } else { 10716 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 10717 if (known != null) { 10718 if (DEBUG_PACKAGE_SCANNING) { 10719 Log.d(TAG, "Examining " + pkg.codePath 10720 + " and requiring known paths " + known.codePathString 10721 + " & " + known.resourcePathString); 10722 } 10723 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 10724 || !pkg.applicationInfo.getResourcePath().equals( 10725 known.resourcePathString)) { 10726 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 10727 "Application package " + pkg.packageName 10728 + " found at " + pkg.applicationInfo.getCodePath() 10729 + " but expected at " + known.codePathString 10730 + "; ignoring."); 10731 } 10732 } else { 10733 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 10734 "Application package " + pkg.packageName 10735 + " not found; ignoring."); 10736 } 10737 } 10738 } 10739 10740 // Verify that this new package doesn't have any content providers 10741 // that conflict with existing packages. Only do this if the 10742 // package isn't already installed, since we don't want to break 10743 // things that are installed. 10744 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 10745 final int N = pkg.providers.size(); 10746 int i; 10747 for (i=0; i<N; i++) { 10748 PackageParser.Provider p = pkg.providers.get(i); 10749 if (p.info.authority != null) { 10750 String names[] = p.info.authority.split(";"); 10751 for (int j = 0; j < names.length; j++) { 10752 if (mProvidersByAuthority.containsKey(names[j])) { 10753 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 10754 final String otherPackageName = 10755 ((other != null && other.getComponentName() != null) ? 10756 other.getComponentName().getPackageName() : "?"); 10757 throw new PackageManagerException( 10758 INSTALL_FAILED_CONFLICTING_PROVIDER, 10759 "Can't install because provider name " + names[j] 10760 + " (in package " + pkg.applicationInfo.packageName 10761 + ") is already used by " + otherPackageName); 10762 } 10763 } 10764 } 10765 } 10766 } 10767 } 10768 } 10769 10770 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 10771 int type, String declaringPackageName, long declaringVersionCode) { 10772 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10773 if (versionedLib == null) { 10774 versionedLib = new LongSparseArray<>(); 10775 mSharedLibraries.put(name, versionedLib); 10776 if (type == SharedLibraryInfo.TYPE_STATIC) { 10777 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10778 } 10779 } else if (versionedLib.indexOfKey(version) >= 0) { 10780 return false; 10781 } 10782 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10783 version, type, declaringPackageName, declaringVersionCode); 10784 versionedLib.put(version, libEntry); 10785 return true; 10786 } 10787 10788 private boolean removeSharedLibraryLPw(String name, long version) { 10789 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10790 if (versionedLib == null) { 10791 return false; 10792 } 10793 final int libIdx = versionedLib.indexOfKey(version); 10794 if (libIdx < 0) { 10795 return false; 10796 } 10797 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10798 versionedLib.remove(version); 10799 if (versionedLib.size() <= 0) { 10800 mSharedLibraries.remove(name); 10801 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10802 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10803 .getPackageName()); 10804 } 10805 } 10806 return true; 10807 } 10808 10809 /** 10810 * Adds a scanned package to the system. When this method is finished, the package will 10811 * be available for query, resolution, etc... 10812 */ 10813 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10814 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 10815 final String pkgName = pkg.packageName; 10816 if (mCustomResolverComponentName != null && 10817 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10818 setUpCustomResolverActivity(pkg); 10819 } 10820 10821 if (pkg.packageName.equals("android")) { 10822 synchronized (mPackages) { 10823 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10824 // Set up information for our fall-back user intent resolution activity. 10825 mPlatformPackage = pkg; 10826 pkg.mVersionCode = mSdkVersion; 10827 pkg.mVersionCodeMajor = 0; 10828 mAndroidApplication = pkg.applicationInfo; 10829 if (!mResolverReplaced) { 10830 mResolveActivity.applicationInfo = mAndroidApplication; 10831 mResolveActivity.name = ResolverActivity.class.getName(); 10832 mResolveActivity.packageName = mAndroidApplication.packageName; 10833 mResolveActivity.processName = "system:ui"; 10834 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10835 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10836 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10837 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10838 mResolveActivity.exported = true; 10839 mResolveActivity.enabled = true; 10840 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10841 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10842 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10843 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10844 | ActivityInfo.CONFIG_ORIENTATION 10845 | ActivityInfo.CONFIG_KEYBOARD 10846 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10847 mResolveInfo.activityInfo = mResolveActivity; 10848 mResolveInfo.priority = 0; 10849 mResolveInfo.preferredOrder = 0; 10850 mResolveInfo.match = 0; 10851 mResolveComponentName = new ComponentName( 10852 mAndroidApplication.packageName, mResolveActivity.name); 10853 } 10854 } 10855 } 10856 } 10857 10858 ArrayList<PackageParser.Package> clientLibPkgs = null; 10859 // writer 10860 synchronized (mPackages) { 10861 boolean hasStaticSharedLibs = false; 10862 10863 // Any app can add new static shared libraries 10864 if (pkg.staticSharedLibName != null) { 10865 // Static shared libs don't allow renaming as they have synthetic package 10866 // names to allow install of multiple versions, so use name from manifest. 10867 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10868 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10869 pkg.manifestPackageName, pkg.getLongVersionCode())) { 10870 hasStaticSharedLibs = true; 10871 } else { 10872 Slog.w(TAG, "Package " + pkg.packageName + " library " 10873 + pkg.staticSharedLibName + " already exists; skipping"); 10874 } 10875 // Static shared libs cannot be updated once installed since they 10876 // use synthetic package name which includes the version code, so 10877 // not need to update other packages's shared lib dependencies. 10878 } 10879 10880 if (!hasStaticSharedLibs 10881 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10882 // Only system apps can add new dynamic shared libraries. 10883 if (pkg.libraryNames != null) { 10884 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10885 String name = pkg.libraryNames.get(i); 10886 boolean allowed = false; 10887 if (pkg.isUpdatedSystemApp()) { 10888 // New library entries can only be added through the 10889 // system image. This is important to get rid of a lot 10890 // of nasty edge cases: for example if we allowed a non- 10891 // system update of the app to add a library, then uninstalling 10892 // the update would make the library go away, and assumptions 10893 // we made such as through app install filtering would now 10894 // have allowed apps on the device which aren't compatible 10895 // with it. Better to just have the restriction here, be 10896 // conservative, and create many fewer cases that can negatively 10897 // impact the user experience. 10898 final PackageSetting sysPs = mSettings 10899 .getDisabledSystemPkgLPr(pkg.packageName); 10900 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10901 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10902 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10903 allowed = true; 10904 break; 10905 } 10906 } 10907 } 10908 } else { 10909 allowed = true; 10910 } 10911 if (allowed) { 10912 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10913 SharedLibraryInfo.VERSION_UNDEFINED, 10914 SharedLibraryInfo.TYPE_DYNAMIC, 10915 pkg.packageName, pkg.getLongVersionCode())) { 10916 Slog.w(TAG, "Package " + pkg.packageName + " library " 10917 + name + " already exists; skipping"); 10918 } 10919 } else { 10920 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10921 + name + " that is not declared on system image; skipping"); 10922 } 10923 } 10924 10925 if ((scanFlags & SCAN_BOOTING) == 0) { 10926 // If we are not booting, we need to update any applications 10927 // that are clients of our shared library. If we are booting, 10928 // this will all be done once the scan is complete. 10929 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10930 } 10931 } 10932 } 10933 } 10934 10935 if ((scanFlags & SCAN_BOOTING) != 0) { 10936 // No apps can run during boot scan, so they don't need to be frozen 10937 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10938 // Caller asked to not kill app, so it's probably not frozen 10939 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10940 // Caller asked us to ignore frozen check for some reason; they 10941 // probably didn't know the package name 10942 } else { 10943 // We're doing major surgery on this package, so it better be frozen 10944 // right now to keep it from launching 10945 checkPackageFrozen(pkgName); 10946 } 10947 10948 // Also need to kill any apps that are dependent on the library. 10949 if (clientLibPkgs != null) { 10950 for (int i=0; i<clientLibPkgs.size(); i++) { 10951 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10952 killApplication(clientPkg.applicationInfo.packageName, 10953 clientPkg.applicationInfo.uid, "update lib"); 10954 } 10955 } 10956 10957 // writer 10958 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10959 10960 synchronized (mPackages) { 10961 // We don't expect installation to fail beyond this point 10962 10963 // Add the new setting to mSettings 10964 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10965 // Add the new setting to mPackages 10966 mPackages.put(pkg.applicationInfo.packageName, pkg); 10967 // Make sure we don't accidentally delete its data. 10968 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10969 while (iter.hasNext()) { 10970 PackageCleanItem item = iter.next(); 10971 if (pkgName.equals(item.packageName)) { 10972 iter.remove(); 10973 } 10974 } 10975 10976 // Add the package's KeySets to the global KeySetManagerService 10977 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10978 ksms.addScannedPackageLPw(pkg); 10979 10980 int N = pkg.providers.size(); 10981 StringBuilder r = null; 10982 int i; 10983 for (i=0; i<N; i++) { 10984 PackageParser.Provider p = pkg.providers.get(i); 10985 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 10986 p.info.processName); 10987 mProviders.addProvider(p); 10988 p.syncable = p.info.isSyncable; 10989 if (p.info.authority != null) { 10990 String names[] = p.info.authority.split(";"); 10991 p.info.authority = null; 10992 for (int j = 0; j < names.length; j++) { 10993 if (j == 1 && p.syncable) { 10994 // We only want the first authority for a provider to possibly be 10995 // syncable, so if we already added this provider using a different 10996 // authority clear the syncable flag. We copy the provider before 10997 // changing it because the mProviders object contains a reference 10998 // to a provider that we don't want to change. 10999 // Only do this for the second authority since the resulting provider 11000 // object can be the same for all future authorities for this provider. 11001 p = new PackageParser.Provider(p); 11002 p.syncable = false; 11003 } 11004 if (!mProvidersByAuthority.containsKey(names[j])) { 11005 mProvidersByAuthority.put(names[j], p); 11006 if (p.info.authority == null) { 11007 p.info.authority = names[j]; 11008 } else { 11009 p.info.authority = p.info.authority + ";" + names[j]; 11010 } 11011 if (DEBUG_PACKAGE_SCANNING) { 11012 if (chatty) 11013 Log.d(TAG, "Registered content provider: " + names[j] 11014 + ", className = " + p.info.name + ", isSyncable = " 11015 + p.info.isSyncable); 11016 } 11017 } else { 11018 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11019 Slog.w(TAG, "Skipping provider name " + names[j] + 11020 " (in package " + pkg.applicationInfo.packageName + 11021 "): name already used by " 11022 + ((other != null && other.getComponentName() != null) 11023 ? other.getComponentName().getPackageName() : "?")); 11024 } 11025 } 11026 } 11027 if (chatty) { 11028 if (r == null) { 11029 r = new StringBuilder(256); 11030 } else { 11031 r.append(' '); 11032 } 11033 r.append(p.info.name); 11034 } 11035 } 11036 if (r != null) { 11037 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11038 } 11039 11040 N = pkg.services.size(); 11041 r = null; 11042 for (i=0; i<N; i++) { 11043 PackageParser.Service s = pkg.services.get(i); 11044 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11045 s.info.processName); 11046 mServices.addService(s); 11047 if (chatty) { 11048 if (r == null) { 11049 r = new StringBuilder(256); 11050 } else { 11051 r.append(' '); 11052 } 11053 r.append(s.info.name); 11054 } 11055 } 11056 if (r != null) { 11057 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11058 } 11059 11060 N = pkg.receivers.size(); 11061 r = null; 11062 for (i=0; i<N; i++) { 11063 PackageParser.Activity a = pkg.receivers.get(i); 11064 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11065 a.info.processName); 11066 mReceivers.addActivity(a, "receiver"); 11067 if (chatty) { 11068 if (r == null) { 11069 r = new StringBuilder(256); 11070 } else { 11071 r.append(' '); 11072 } 11073 r.append(a.info.name); 11074 } 11075 } 11076 if (r != null) { 11077 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 11078 } 11079 11080 N = pkg.activities.size(); 11081 r = null; 11082 for (i=0; i<N; i++) { 11083 PackageParser.Activity a = pkg.activities.get(i); 11084 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11085 a.info.processName); 11086 mActivities.addActivity(a, "activity"); 11087 if (chatty) { 11088 if (r == null) { 11089 r = new StringBuilder(256); 11090 } else { 11091 r.append(' '); 11092 } 11093 r.append(a.info.name); 11094 } 11095 } 11096 if (r != null) { 11097 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11098 } 11099 11100 // Don't allow ephemeral applications to define new permissions groups. 11101 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11102 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11103 + " ignored: instant apps cannot define new permission groups."); 11104 } else { 11105 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11106 } 11107 11108 // Don't allow ephemeral applications to define new permissions. 11109 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11110 Slog.w(TAG, "Permissions from package " + pkg.packageName 11111 + " ignored: instant apps cannot define new permissions."); 11112 } else { 11113 mPermissionManager.addAllPermissions(pkg, chatty); 11114 } 11115 11116 N = pkg.instrumentation.size(); 11117 r = null; 11118 for (i=0; i<N; i++) { 11119 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11120 a.info.packageName = pkg.applicationInfo.packageName; 11121 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11122 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11123 a.info.splitNames = pkg.splitNames; 11124 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11125 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11126 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11127 a.info.dataDir = pkg.applicationInfo.dataDir; 11128 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11129 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11130 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11131 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11132 mInstrumentation.put(a.getComponentName(), a); 11133 if (chatty) { 11134 if (r == null) { 11135 r = new StringBuilder(256); 11136 } else { 11137 r.append(' '); 11138 } 11139 r.append(a.info.name); 11140 } 11141 } 11142 if (r != null) { 11143 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11144 } 11145 11146 if (pkg.protectedBroadcasts != null) { 11147 N = pkg.protectedBroadcasts.size(); 11148 synchronized (mProtectedBroadcasts) { 11149 for (i = 0; i < N; i++) { 11150 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11151 } 11152 } 11153 } 11154 } 11155 11156 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11157 } 11158 11159 /** 11160 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11161 * is derived purely on the basis of the contents of {@code scanFile} and 11162 * {@code cpuAbiOverride}. 11163 * 11164 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11165 */ 11166 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11167 boolean extractLibs) 11168 throws PackageManagerException { 11169 // Give ourselves some initial paths; we'll come back for another 11170 // pass once we've determined ABI below. 11171 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11172 11173 // We would never need to extract libs for forward-locked and external packages, 11174 // since the container service will do it for us. We shouldn't attempt to 11175 // extract libs from system app when it was not updated. 11176 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11177 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11178 extractLibs = false; 11179 } 11180 11181 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11182 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11183 11184 NativeLibraryHelper.Handle handle = null; 11185 try { 11186 handle = NativeLibraryHelper.Handle.create(pkg); 11187 // TODO(multiArch): This can be null for apps that didn't go through the 11188 // usual installation process. We can calculate it again, like we 11189 // do during install time. 11190 // 11191 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11192 // unnecessary. 11193 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11194 11195 // Null out the abis so that they can be recalculated. 11196 pkg.applicationInfo.primaryCpuAbi = null; 11197 pkg.applicationInfo.secondaryCpuAbi = null; 11198 if (isMultiArch(pkg.applicationInfo)) { 11199 // Warn if we've set an abiOverride for multi-lib packages.. 11200 // By definition, we need to copy both 32 and 64 bit libraries for 11201 // such packages. 11202 if (pkg.cpuAbiOverride != null 11203 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11204 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11205 } 11206 11207 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11208 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11209 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11210 if (extractLibs) { 11211 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11212 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11213 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11214 useIsaSpecificSubdirs); 11215 } else { 11216 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11217 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11218 } 11219 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11220 } 11221 11222 // Shared library native code should be in the APK zip aligned 11223 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11224 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11225 "Shared library native lib extraction not supported"); 11226 } 11227 11228 maybeThrowExceptionForMultiArchCopy( 11229 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11230 11231 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11232 if (extractLibs) { 11233 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11234 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11235 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11236 useIsaSpecificSubdirs); 11237 } else { 11238 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11239 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11240 } 11241 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11242 } 11243 11244 maybeThrowExceptionForMultiArchCopy( 11245 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11246 11247 if (abi64 >= 0) { 11248 // Shared library native libs should be in the APK zip aligned 11249 if (extractLibs && pkg.isLibrary()) { 11250 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11251 "Shared library native lib extraction not supported"); 11252 } 11253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11254 } 11255 11256 if (abi32 >= 0) { 11257 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11258 if (abi64 >= 0) { 11259 if (pkg.use32bitAbi) { 11260 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11261 pkg.applicationInfo.primaryCpuAbi = abi; 11262 } else { 11263 pkg.applicationInfo.secondaryCpuAbi = abi; 11264 } 11265 } else { 11266 pkg.applicationInfo.primaryCpuAbi = abi; 11267 } 11268 } 11269 } else { 11270 String[] abiList = (cpuAbiOverride != null) ? 11271 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11272 11273 // Enable gross and lame hacks for apps that are built with old 11274 // SDK tools. We must scan their APKs for renderscript bitcode and 11275 // not launch them if it's present. Don't bother checking on devices 11276 // that don't have 64 bit support. 11277 boolean needsRenderScriptOverride = false; 11278 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11279 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11280 abiList = Build.SUPPORTED_32_BIT_ABIS; 11281 needsRenderScriptOverride = true; 11282 } 11283 11284 final int copyRet; 11285 if (extractLibs) { 11286 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11287 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11288 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11289 } else { 11290 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11291 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11292 } 11293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11294 11295 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11296 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11297 "Error unpackaging native libs for app, errorCode=" + copyRet); 11298 } 11299 11300 if (copyRet >= 0) { 11301 // Shared libraries that have native libs must be multi-architecture 11302 if (pkg.isLibrary()) { 11303 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11304 "Shared library with native libs must be multiarch"); 11305 } 11306 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11307 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11308 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11309 } else if (needsRenderScriptOverride) { 11310 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11311 } 11312 } 11313 } catch (IOException ioe) { 11314 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11315 } finally { 11316 IoUtils.closeQuietly(handle); 11317 } 11318 11319 // Now that we've calculated the ABIs and determined if it's an internal app, 11320 // we will go ahead and populate the nativeLibraryPath. 11321 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11322 } 11323 11324 /** 11325 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11326 * i.e, so that all packages can be run inside a single process if required. 11327 * 11328 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11329 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11330 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11331 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11332 * updating a package that belongs to a shared user. 11333 * 11334 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11335 * adds unnecessary complexity. 11336 */ 11337 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11338 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11339 List<String> changedAbiCodePath = null; 11340 String requiredInstructionSet = null; 11341 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11342 requiredInstructionSet = VMRuntime.getInstructionSet( 11343 scannedPackage.applicationInfo.primaryCpuAbi); 11344 } 11345 11346 PackageSetting requirer = null; 11347 for (PackageSetting ps : packagesForUser) { 11348 // If packagesForUser contains scannedPackage, we skip it. This will happen 11349 // when scannedPackage is an update of an existing package. Without this check, 11350 // we will never be able to change the ABI of any package belonging to a shared 11351 // user, even if it's compatible with other packages. 11352 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11353 if (ps.primaryCpuAbiString == null) { 11354 continue; 11355 } 11356 11357 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11358 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11359 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11360 // this but there's not much we can do. 11361 String errorMessage = "Instruction set mismatch, " 11362 + ((requirer == null) ? "[caller]" : requirer) 11363 + " requires " + requiredInstructionSet + " whereas " + ps 11364 + " requires " + instructionSet; 11365 Slog.w(TAG, errorMessage); 11366 } 11367 11368 if (requiredInstructionSet == null) { 11369 requiredInstructionSet = instructionSet; 11370 requirer = ps; 11371 } 11372 } 11373 } 11374 11375 if (requiredInstructionSet != null) { 11376 String adjustedAbi; 11377 if (requirer != null) { 11378 // requirer != null implies that either scannedPackage was null or that scannedPackage 11379 // did not require an ABI, in which case we have to adjust scannedPackage to match 11380 // the ABI of the set (which is the same as requirer's ABI) 11381 adjustedAbi = requirer.primaryCpuAbiString; 11382 if (scannedPackage != null) { 11383 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11384 } 11385 } else { 11386 // requirer == null implies that we're updating all ABIs in the set to 11387 // match scannedPackage. 11388 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11389 } 11390 11391 for (PackageSetting ps : packagesForUser) { 11392 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11393 if (ps.primaryCpuAbiString != null) { 11394 continue; 11395 } 11396 11397 ps.primaryCpuAbiString = adjustedAbi; 11398 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11399 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11400 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11401 if (DEBUG_ABI_SELECTION) { 11402 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11403 + " (requirer=" 11404 + (requirer != null ? requirer.pkg : "null") 11405 + ", scannedPackage=" 11406 + (scannedPackage != null ? scannedPackage : "null") 11407 + ")"); 11408 } 11409 if (changedAbiCodePath == null) { 11410 changedAbiCodePath = new ArrayList<>(); 11411 } 11412 changedAbiCodePath.add(ps.codePathString); 11413 } 11414 } 11415 } 11416 } 11417 return changedAbiCodePath; 11418 } 11419 11420 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11421 synchronized (mPackages) { 11422 mResolverReplaced = true; 11423 // Set up information for custom user intent resolution activity. 11424 mResolveActivity.applicationInfo = pkg.applicationInfo; 11425 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11426 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11427 mResolveActivity.processName = pkg.applicationInfo.packageName; 11428 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11429 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11430 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11431 mResolveActivity.theme = 0; 11432 mResolveActivity.exported = true; 11433 mResolveActivity.enabled = true; 11434 mResolveInfo.activityInfo = mResolveActivity; 11435 mResolveInfo.priority = 0; 11436 mResolveInfo.preferredOrder = 0; 11437 mResolveInfo.match = 0; 11438 mResolveComponentName = mCustomResolverComponentName; 11439 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11440 mResolveComponentName); 11441 } 11442 } 11443 11444 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11445 if (installerActivity == null) { 11446 if (DEBUG_EPHEMERAL) { 11447 Slog.d(TAG, "Clear ephemeral installer activity"); 11448 } 11449 mInstantAppInstallerActivity = null; 11450 return; 11451 } 11452 11453 if (DEBUG_EPHEMERAL) { 11454 Slog.d(TAG, "Set ephemeral installer activity: " 11455 + installerActivity.getComponentName()); 11456 } 11457 // Set up information for ephemeral installer activity 11458 mInstantAppInstallerActivity = installerActivity; 11459 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11460 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11461 mInstantAppInstallerActivity.exported = true; 11462 mInstantAppInstallerActivity.enabled = true; 11463 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11464 mInstantAppInstallerInfo.priority = 0; 11465 mInstantAppInstallerInfo.preferredOrder = 1; 11466 mInstantAppInstallerInfo.isDefault = true; 11467 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11468 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11469 } 11470 11471 private static String calculateBundledApkRoot(final String codePathString) { 11472 final File codePath = new File(codePathString); 11473 final File codeRoot; 11474 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11475 codeRoot = Environment.getRootDirectory(); 11476 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11477 codeRoot = Environment.getOemDirectory(); 11478 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11479 codeRoot = Environment.getVendorDirectory(); 11480 } else { 11481 // Unrecognized code path; take its top real segment as the apk root: 11482 // e.g. /something/app/blah.apk => /something 11483 try { 11484 File f = codePath.getCanonicalFile(); 11485 File parent = f.getParentFile(); // non-null because codePath is a file 11486 File tmp; 11487 while ((tmp = parent.getParentFile()) != null) { 11488 f = parent; 11489 parent = tmp; 11490 } 11491 codeRoot = f; 11492 Slog.w(TAG, "Unrecognized code path " 11493 + codePath + " - using " + codeRoot); 11494 } catch (IOException e) { 11495 // Can't canonicalize the code path -- shenanigans? 11496 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11497 return Environment.getRootDirectory().getPath(); 11498 } 11499 } 11500 return codeRoot.getPath(); 11501 } 11502 11503 /** 11504 * Derive and set the location of native libraries for the given package, 11505 * which varies depending on where and how the package was installed. 11506 */ 11507 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11508 final ApplicationInfo info = pkg.applicationInfo; 11509 final String codePath = pkg.codePath; 11510 final File codeFile = new File(codePath); 11511 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11512 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11513 11514 info.nativeLibraryRootDir = null; 11515 info.nativeLibraryRootRequiresIsa = false; 11516 info.nativeLibraryDir = null; 11517 info.secondaryNativeLibraryDir = null; 11518 11519 if (isApkFile(codeFile)) { 11520 // Monolithic install 11521 if (bundledApp) { 11522 // If "/system/lib64/apkname" exists, assume that is the per-package 11523 // native library directory to use; otherwise use "/system/lib/apkname". 11524 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11525 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11526 getPrimaryInstructionSet(info)); 11527 11528 // This is a bundled system app so choose the path based on the ABI. 11529 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11530 // is just the default path. 11531 final String apkName = deriveCodePathName(codePath); 11532 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11533 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11534 apkName).getAbsolutePath(); 11535 11536 if (info.secondaryCpuAbi != null) { 11537 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11538 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11539 secondaryLibDir, apkName).getAbsolutePath(); 11540 } 11541 } else if (asecApp) { 11542 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11543 .getAbsolutePath(); 11544 } else { 11545 final String apkName = deriveCodePathName(codePath); 11546 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11547 .getAbsolutePath(); 11548 } 11549 11550 info.nativeLibraryRootRequiresIsa = false; 11551 info.nativeLibraryDir = info.nativeLibraryRootDir; 11552 } else { 11553 // Cluster install 11554 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11555 info.nativeLibraryRootRequiresIsa = true; 11556 11557 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11558 getPrimaryInstructionSet(info)).getAbsolutePath(); 11559 11560 if (info.secondaryCpuAbi != null) { 11561 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11562 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11563 } 11564 } 11565 } 11566 11567 /** 11568 * Calculate the abis and roots for a bundled app. These can uniquely 11569 * be determined from the contents of the system partition, i.e whether 11570 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11571 * of this information, and instead assume that the system was built 11572 * sensibly. 11573 */ 11574 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11575 PackageSetting pkgSetting) { 11576 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11577 11578 // If "/system/lib64/apkname" exists, assume that is the per-package 11579 // native library directory to use; otherwise use "/system/lib/apkname". 11580 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11581 setBundledAppAbi(pkg, apkRoot, apkName); 11582 // pkgSetting might be null during rescan following uninstall of updates 11583 // to a bundled app, so accommodate that possibility. The settings in 11584 // that case will be established later from the parsed package. 11585 // 11586 // If the settings aren't null, sync them up with what we've just derived. 11587 // note that apkRoot isn't stored in the package settings. 11588 if (pkgSetting != null) { 11589 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11590 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11591 } 11592 } 11593 11594 /** 11595 * Deduces the ABI of a bundled app and sets the relevant fields on the 11596 * parsed pkg object. 11597 * 11598 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11599 * under which system libraries are installed. 11600 * @param apkName the name of the installed package. 11601 */ 11602 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11603 final File codeFile = new File(pkg.codePath); 11604 11605 final boolean has64BitLibs; 11606 final boolean has32BitLibs; 11607 if (isApkFile(codeFile)) { 11608 // Monolithic install 11609 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11610 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11611 } else { 11612 // Cluster install 11613 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11614 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11615 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11616 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11617 has64BitLibs = (new File(rootDir, isa)).exists(); 11618 } else { 11619 has64BitLibs = false; 11620 } 11621 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11622 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11623 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11624 has32BitLibs = (new File(rootDir, isa)).exists(); 11625 } else { 11626 has32BitLibs = false; 11627 } 11628 } 11629 11630 if (has64BitLibs && !has32BitLibs) { 11631 // The package has 64 bit libs, but not 32 bit libs. Its primary 11632 // ABI should be 64 bit. We can safely assume here that the bundled 11633 // native libraries correspond to the most preferred ABI in the list. 11634 11635 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11636 pkg.applicationInfo.secondaryCpuAbi = null; 11637 } else if (has32BitLibs && !has64BitLibs) { 11638 // The package has 32 bit libs but not 64 bit libs. Its primary 11639 // ABI should be 32 bit. 11640 11641 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11642 pkg.applicationInfo.secondaryCpuAbi = null; 11643 } else if (has32BitLibs && has64BitLibs) { 11644 // The application has both 64 and 32 bit bundled libraries. We check 11645 // here that the app declares multiArch support, and warn if it doesn't. 11646 // 11647 // We will be lenient here and record both ABIs. The primary will be the 11648 // ABI that's higher on the list, i.e, a device that's configured to prefer 11649 // 64 bit apps will see a 64 bit primary ABI, 11650 11651 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11652 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11653 } 11654 11655 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11656 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11657 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11658 } else { 11659 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11660 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11661 } 11662 } else { 11663 pkg.applicationInfo.primaryCpuAbi = null; 11664 pkg.applicationInfo.secondaryCpuAbi = null; 11665 } 11666 } 11667 11668 private void killApplication(String pkgName, int appId, String reason) { 11669 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11670 } 11671 11672 private void killApplication(String pkgName, int appId, int userId, String reason) { 11673 // Request the ActivityManager to kill the process(only for existing packages) 11674 // so that we do not end up in a confused state while the user is still using the older 11675 // version of the application while the new one gets installed. 11676 final long token = Binder.clearCallingIdentity(); 11677 try { 11678 IActivityManager am = ActivityManager.getService(); 11679 if (am != null) { 11680 try { 11681 am.killApplication(pkgName, appId, userId, reason); 11682 } catch (RemoteException e) { 11683 } 11684 } 11685 } finally { 11686 Binder.restoreCallingIdentity(token); 11687 } 11688 } 11689 11690 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11691 // Remove the parent package setting 11692 PackageSetting ps = (PackageSetting) pkg.mExtras; 11693 if (ps != null) { 11694 removePackageLI(ps, chatty); 11695 } 11696 // Remove the child package setting 11697 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11698 for (int i = 0; i < childCount; i++) { 11699 PackageParser.Package childPkg = pkg.childPackages.get(i); 11700 ps = (PackageSetting) childPkg.mExtras; 11701 if (ps != null) { 11702 removePackageLI(ps, chatty); 11703 } 11704 } 11705 } 11706 11707 void removePackageLI(PackageSetting ps, boolean chatty) { 11708 if (DEBUG_INSTALL) { 11709 if (chatty) 11710 Log.d(TAG, "Removing package " + ps.name); 11711 } 11712 11713 // writer 11714 synchronized (mPackages) { 11715 mPackages.remove(ps.name); 11716 final PackageParser.Package pkg = ps.pkg; 11717 if (pkg != null) { 11718 cleanPackageDataStructuresLILPw(pkg, chatty); 11719 } 11720 } 11721 } 11722 11723 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11724 if (DEBUG_INSTALL) { 11725 if (chatty) 11726 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11727 } 11728 11729 // writer 11730 synchronized (mPackages) { 11731 // Remove the parent package 11732 mPackages.remove(pkg.applicationInfo.packageName); 11733 cleanPackageDataStructuresLILPw(pkg, chatty); 11734 11735 // Remove the child packages 11736 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11737 for (int i = 0; i < childCount; i++) { 11738 PackageParser.Package childPkg = pkg.childPackages.get(i); 11739 mPackages.remove(childPkg.applicationInfo.packageName); 11740 cleanPackageDataStructuresLILPw(childPkg, chatty); 11741 } 11742 } 11743 } 11744 11745 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11746 int N = pkg.providers.size(); 11747 StringBuilder r = null; 11748 int i; 11749 for (i=0; i<N; i++) { 11750 PackageParser.Provider p = pkg.providers.get(i); 11751 mProviders.removeProvider(p); 11752 if (p.info.authority == null) { 11753 11754 /* There was another ContentProvider with this authority when 11755 * this app was installed so this authority is null, 11756 * Ignore it as we don't have to unregister the provider. 11757 */ 11758 continue; 11759 } 11760 String names[] = p.info.authority.split(";"); 11761 for (int j = 0; j < names.length; j++) { 11762 if (mProvidersByAuthority.get(names[j]) == p) { 11763 mProvidersByAuthority.remove(names[j]); 11764 if (DEBUG_REMOVE) { 11765 if (chatty) 11766 Log.d(TAG, "Unregistered content provider: " + names[j] 11767 + ", className = " + p.info.name + ", isSyncable = " 11768 + p.info.isSyncable); 11769 } 11770 } 11771 } 11772 if (DEBUG_REMOVE && chatty) { 11773 if (r == null) { 11774 r = new StringBuilder(256); 11775 } else { 11776 r.append(' '); 11777 } 11778 r.append(p.info.name); 11779 } 11780 } 11781 if (r != null) { 11782 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11783 } 11784 11785 N = pkg.services.size(); 11786 r = null; 11787 for (i=0; i<N; i++) { 11788 PackageParser.Service s = pkg.services.get(i); 11789 mServices.removeService(s); 11790 if (chatty) { 11791 if (r == null) { 11792 r = new StringBuilder(256); 11793 } else { 11794 r.append(' '); 11795 } 11796 r.append(s.info.name); 11797 } 11798 } 11799 if (r != null) { 11800 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11801 } 11802 11803 N = pkg.receivers.size(); 11804 r = null; 11805 for (i=0; i<N; i++) { 11806 PackageParser.Activity a = pkg.receivers.get(i); 11807 mReceivers.removeActivity(a, "receiver"); 11808 if (DEBUG_REMOVE && chatty) { 11809 if (r == null) { 11810 r = new StringBuilder(256); 11811 } else { 11812 r.append(' '); 11813 } 11814 r.append(a.info.name); 11815 } 11816 } 11817 if (r != null) { 11818 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11819 } 11820 11821 N = pkg.activities.size(); 11822 r = null; 11823 for (i=0; i<N; i++) { 11824 PackageParser.Activity a = pkg.activities.get(i); 11825 mActivities.removeActivity(a, "activity"); 11826 if (DEBUG_REMOVE && chatty) { 11827 if (r == null) { 11828 r = new StringBuilder(256); 11829 } else { 11830 r.append(' '); 11831 } 11832 r.append(a.info.name); 11833 } 11834 } 11835 if (r != null) { 11836 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 11837 } 11838 11839 mPermissionManager.removeAllPermissions(pkg, chatty); 11840 11841 N = pkg.instrumentation.size(); 11842 r = null; 11843 for (i=0; i<N; i++) { 11844 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11845 mInstrumentation.remove(a.getComponentName()); 11846 if (DEBUG_REMOVE && chatty) { 11847 if (r == null) { 11848 r = new StringBuilder(256); 11849 } else { 11850 r.append(' '); 11851 } 11852 r.append(a.info.name); 11853 } 11854 } 11855 if (r != null) { 11856 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11857 } 11858 11859 r = null; 11860 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11861 // Only system apps can hold shared libraries. 11862 if (pkg.libraryNames != null) { 11863 for (i = 0; i < pkg.libraryNames.size(); i++) { 11864 String name = pkg.libraryNames.get(i); 11865 if (removeSharedLibraryLPw(name, 0)) { 11866 if (DEBUG_REMOVE && chatty) { 11867 if (r == null) { 11868 r = new StringBuilder(256); 11869 } else { 11870 r.append(' '); 11871 } 11872 r.append(name); 11873 } 11874 } 11875 } 11876 } 11877 } 11878 11879 r = null; 11880 11881 // Any package can hold static shared libraries. 11882 if (pkg.staticSharedLibName != null) { 11883 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11884 if (DEBUG_REMOVE && chatty) { 11885 if (r == null) { 11886 r = new StringBuilder(256); 11887 } else { 11888 r.append(' '); 11889 } 11890 r.append(pkg.staticSharedLibName); 11891 } 11892 } 11893 } 11894 11895 if (r != null) { 11896 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11897 } 11898 } 11899 11900 11901 final class ActivityIntentResolver 11902 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11903 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11904 boolean defaultOnly, int userId) { 11905 if (!sUserManager.exists(userId)) return null; 11906 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11907 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11908 } 11909 11910 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11911 int userId) { 11912 if (!sUserManager.exists(userId)) return null; 11913 mFlags = flags; 11914 return super.queryIntent(intent, resolvedType, 11915 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11916 userId); 11917 } 11918 11919 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11920 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11921 if (!sUserManager.exists(userId)) return null; 11922 if (packageActivities == null) { 11923 return null; 11924 } 11925 mFlags = flags; 11926 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11927 final int N = packageActivities.size(); 11928 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11929 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11930 11931 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11932 for (int i = 0; i < N; ++i) { 11933 intentFilters = packageActivities.get(i).intents; 11934 if (intentFilters != null && intentFilters.size() > 0) { 11935 PackageParser.ActivityIntentInfo[] array = 11936 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11937 intentFilters.toArray(array); 11938 listCut.add(array); 11939 } 11940 } 11941 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11942 } 11943 11944 /** 11945 * Finds a privileged activity that matches the specified activity names. 11946 */ 11947 private PackageParser.Activity findMatchingActivity( 11948 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11949 for (PackageParser.Activity sysActivity : activityList) { 11950 if (sysActivity.info.name.equals(activityInfo.name)) { 11951 return sysActivity; 11952 } 11953 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11954 return sysActivity; 11955 } 11956 if (sysActivity.info.targetActivity != null) { 11957 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11958 return sysActivity; 11959 } 11960 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11961 return sysActivity; 11962 } 11963 } 11964 } 11965 return null; 11966 } 11967 11968 public class IterGenerator<E> { 11969 public Iterator<E> generate(ActivityIntentInfo info) { 11970 return null; 11971 } 11972 } 11973 11974 public class ActionIterGenerator extends IterGenerator<String> { 11975 @Override 11976 public Iterator<String> generate(ActivityIntentInfo info) { 11977 return info.actionsIterator(); 11978 } 11979 } 11980 11981 public class CategoriesIterGenerator extends IterGenerator<String> { 11982 @Override 11983 public Iterator<String> generate(ActivityIntentInfo info) { 11984 return info.categoriesIterator(); 11985 } 11986 } 11987 11988 public class SchemesIterGenerator extends IterGenerator<String> { 11989 @Override 11990 public Iterator<String> generate(ActivityIntentInfo info) { 11991 return info.schemesIterator(); 11992 } 11993 } 11994 11995 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 11996 @Override 11997 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 11998 return info.authoritiesIterator(); 11999 } 12000 } 12001 12002 /** 12003 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12004 * MODIFIED. Do not pass in a list that should not be changed. 12005 */ 12006 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12007 IterGenerator<T> generator, Iterator<T> searchIterator) { 12008 // loop through the set of actions; every one must be found in the intent filter 12009 while (searchIterator.hasNext()) { 12010 // we must have at least one filter in the list to consider a match 12011 if (intentList.size() == 0) { 12012 break; 12013 } 12014 12015 final T searchAction = searchIterator.next(); 12016 12017 // loop through the set of intent filters 12018 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12019 while (intentIter.hasNext()) { 12020 final ActivityIntentInfo intentInfo = intentIter.next(); 12021 boolean selectionFound = false; 12022 12023 // loop through the intent filter's selection criteria; at least one 12024 // of them must match the searched criteria 12025 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12026 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12027 final T intentSelection = intentSelectionIter.next(); 12028 if (intentSelection != null && intentSelection.equals(searchAction)) { 12029 selectionFound = true; 12030 break; 12031 } 12032 } 12033 12034 // the selection criteria wasn't found in this filter's set; this filter 12035 // is not a potential match 12036 if (!selectionFound) { 12037 intentIter.remove(); 12038 } 12039 } 12040 } 12041 } 12042 12043 private boolean isProtectedAction(ActivityIntentInfo filter) { 12044 final Iterator<String> actionsIter = filter.actionsIterator(); 12045 while (actionsIter != null && actionsIter.hasNext()) { 12046 final String filterAction = actionsIter.next(); 12047 if (PROTECTED_ACTIONS.contains(filterAction)) { 12048 return true; 12049 } 12050 } 12051 return false; 12052 } 12053 12054 /** 12055 * Adjusts the priority of the given intent filter according to policy. 12056 * <p> 12057 * <ul> 12058 * <li>The priority for non privileged applications is capped to '0'</li> 12059 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12060 * <li>The priority for unbundled updates to privileged applications is capped to the 12061 * priority defined on the system partition</li> 12062 * </ul> 12063 * <p> 12064 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12065 * allowed to obtain any priority on any action. 12066 */ 12067 private void adjustPriority( 12068 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12069 // nothing to do; priority is fine as-is 12070 if (intent.getPriority() <= 0) { 12071 return; 12072 } 12073 12074 final ActivityInfo activityInfo = intent.activity.info; 12075 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12076 12077 final boolean privilegedApp = 12078 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12079 if (!privilegedApp) { 12080 // non-privileged applications can never define a priority >0 12081 if (DEBUG_FILTERS) { 12082 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12083 + " package: " + applicationInfo.packageName 12084 + " activity: " + intent.activity.className 12085 + " origPrio: " + intent.getPriority()); 12086 } 12087 intent.setPriority(0); 12088 return; 12089 } 12090 12091 if (systemActivities == null) { 12092 // the system package is not disabled; we're parsing the system partition 12093 if (isProtectedAction(intent)) { 12094 if (mDeferProtectedFilters) { 12095 // We can't deal with these just yet. No component should ever obtain a 12096 // >0 priority for a protected actions, with ONE exception -- the setup 12097 // wizard. The setup wizard, however, cannot be known until we're able to 12098 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12099 // until all intent filters have been processed. Chicken, meet egg. 12100 // Let the filter temporarily have a high priority and rectify the 12101 // priorities after all system packages have been scanned. 12102 mProtectedFilters.add(intent); 12103 if (DEBUG_FILTERS) { 12104 Slog.i(TAG, "Protected action; save for later;" 12105 + " package: " + applicationInfo.packageName 12106 + " activity: " + intent.activity.className 12107 + " origPrio: " + intent.getPriority()); 12108 } 12109 return; 12110 } else { 12111 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12112 Slog.i(TAG, "No setup wizard;" 12113 + " All protected intents capped to priority 0"); 12114 } 12115 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12116 if (DEBUG_FILTERS) { 12117 Slog.i(TAG, "Found setup wizard;" 12118 + " allow priority " + intent.getPriority() + ";" 12119 + " package: " + intent.activity.info.packageName 12120 + " activity: " + intent.activity.className 12121 + " priority: " + intent.getPriority()); 12122 } 12123 // setup wizard gets whatever it wants 12124 return; 12125 } 12126 if (DEBUG_FILTERS) { 12127 Slog.i(TAG, "Protected action; cap priority to 0;" 12128 + " package: " + intent.activity.info.packageName 12129 + " activity: " + intent.activity.className 12130 + " origPrio: " + intent.getPriority()); 12131 } 12132 intent.setPriority(0); 12133 return; 12134 } 12135 } 12136 // privileged apps on the system image get whatever priority they request 12137 return; 12138 } 12139 12140 // privileged app unbundled update ... try to find the same activity 12141 final PackageParser.Activity foundActivity = 12142 findMatchingActivity(systemActivities, activityInfo); 12143 if (foundActivity == null) { 12144 // this is a new activity; it cannot obtain >0 priority 12145 if (DEBUG_FILTERS) { 12146 Slog.i(TAG, "New activity; cap priority to 0;" 12147 + " package: " + applicationInfo.packageName 12148 + " activity: " + intent.activity.className 12149 + " origPrio: " + intent.getPriority()); 12150 } 12151 intent.setPriority(0); 12152 return; 12153 } 12154 12155 // found activity, now check for filter equivalence 12156 12157 // a shallow copy is enough; we modify the list, not its contents 12158 final List<ActivityIntentInfo> intentListCopy = 12159 new ArrayList<>(foundActivity.intents); 12160 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12161 12162 // find matching action subsets 12163 final Iterator<String> actionsIterator = intent.actionsIterator(); 12164 if (actionsIterator != null) { 12165 getIntentListSubset( 12166 intentListCopy, new ActionIterGenerator(), actionsIterator); 12167 if (intentListCopy.size() == 0) { 12168 // no more intents to match; we're not equivalent 12169 if (DEBUG_FILTERS) { 12170 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12171 + " package: " + applicationInfo.packageName 12172 + " activity: " + intent.activity.className 12173 + " origPrio: " + intent.getPriority()); 12174 } 12175 intent.setPriority(0); 12176 return; 12177 } 12178 } 12179 12180 // find matching category subsets 12181 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12182 if (categoriesIterator != null) { 12183 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12184 categoriesIterator); 12185 if (intentListCopy.size() == 0) { 12186 // no more intents to match; we're not equivalent 12187 if (DEBUG_FILTERS) { 12188 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12189 + " package: " + applicationInfo.packageName 12190 + " activity: " + intent.activity.className 12191 + " origPrio: " + intent.getPriority()); 12192 } 12193 intent.setPriority(0); 12194 return; 12195 } 12196 } 12197 12198 // find matching schemes subsets 12199 final Iterator<String> schemesIterator = intent.schemesIterator(); 12200 if (schemesIterator != null) { 12201 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12202 schemesIterator); 12203 if (intentListCopy.size() == 0) { 12204 // no more intents to match; we're not equivalent 12205 if (DEBUG_FILTERS) { 12206 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 12207 + " package: " + applicationInfo.packageName 12208 + " activity: " + intent.activity.className 12209 + " origPrio: " + intent.getPriority()); 12210 } 12211 intent.setPriority(0); 12212 return; 12213 } 12214 } 12215 12216 // find matching authorities subsets 12217 final Iterator<IntentFilter.AuthorityEntry> 12218 authoritiesIterator = intent.authoritiesIterator(); 12219 if (authoritiesIterator != null) { 12220 getIntentListSubset(intentListCopy, 12221 new AuthoritiesIterGenerator(), 12222 authoritiesIterator); 12223 if (intentListCopy.size() == 0) { 12224 // no more intents to match; we're not equivalent 12225 if (DEBUG_FILTERS) { 12226 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12227 + " package: " + applicationInfo.packageName 12228 + " activity: " + intent.activity.className 12229 + " origPrio: " + intent.getPriority()); 12230 } 12231 intent.setPriority(0); 12232 return; 12233 } 12234 } 12235 12236 // we found matching filter(s); app gets the max priority of all intents 12237 int cappedPriority = 0; 12238 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12239 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12240 } 12241 if (intent.getPriority() > cappedPriority) { 12242 if (DEBUG_FILTERS) { 12243 Slog.i(TAG, "Found matching filter(s);" 12244 + " cap priority to " + cappedPriority + ";" 12245 + " package: " + applicationInfo.packageName 12246 + " activity: " + intent.activity.className 12247 + " origPrio: " + intent.getPriority()); 12248 } 12249 intent.setPriority(cappedPriority); 12250 return; 12251 } 12252 // all this for nothing; the requested priority was <= what was on the system 12253 } 12254 12255 public final void addActivity(PackageParser.Activity a, String type) { 12256 mActivities.put(a.getComponentName(), a); 12257 if (DEBUG_SHOW_INFO) 12258 Log.v( 12259 TAG, " " + type + " " + 12260 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12261 if (DEBUG_SHOW_INFO) 12262 Log.v(TAG, " Class=" + a.info.name); 12263 final int NI = a.intents.size(); 12264 for (int j=0; j<NI; j++) { 12265 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12266 if ("activity".equals(type)) { 12267 final PackageSetting ps = 12268 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12269 final List<PackageParser.Activity> systemActivities = 12270 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12271 adjustPriority(systemActivities, intent); 12272 } 12273 if (DEBUG_SHOW_INFO) { 12274 Log.v(TAG, " IntentFilter:"); 12275 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12276 } 12277 if (!intent.debugCheck()) { 12278 Log.w(TAG, "==> For Activity " + a.info.name); 12279 } 12280 addFilter(intent); 12281 } 12282 } 12283 12284 public final void removeActivity(PackageParser.Activity a, String type) { 12285 mActivities.remove(a.getComponentName()); 12286 if (DEBUG_SHOW_INFO) { 12287 Log.v(TAG, " " + type + " " 12288 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12289 : a.info.name) + ":"); 12290 Log.v(TAG, " Class=" + a.info.name); 12291 } 12292 final int NI = a.intents.size(); 12293 for (int j=0; j<NI; j++) { 12294 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12295 if (DEBUG_SHOW_INFO) { 12296 Log.v(TAG, " IntentFilter:"); 12297 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12298 } 12299 removeFilter(intent); 12300 } 12301 } 12302 12303 @Override 12304 protected boolean allowFilterResult( 12305 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12306 ActivityInfo filterAi = filter.activity.info; 12307 for (int i=dest.size()-1; i>=0; i--) { 12308 ActivityInfo destAi = dest.get(i).activityInfo; 12309 if (destAi.name == filterAi.name 12310 && destAi.packageName == filterAi.packageName) { 12311 return false; 12312 } 12313 } 12314 return true; 12315 } 12316 12317 @Override 12318 protected ActivityIntentInfo[] newArray(int size) { 12319 return new ActivityIntentInfo[size]; 12320 } 12321 12322 @Override 12323 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12324 if (!sUserManager.exists(userId)) return true; 12325 PackageParser.Package p = filter.activity.owner; 12326 if (p != null) { 12327 PackageSetting ps = (PackageSetting)p.mExtras; 12328 if (ps != null) { 12329 // System apps are never considered stopped for purposes of 12330 // filtering, because there may be no way for the user to 12331 // actually re-launch them. 12332 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12333 && ps.getStopped(userId); 12334 } 12335 } 12336 return false; 12337 } 12338 12339 @Override 12340 protected boolean isPackageForFilter(String packageName, 12341 PackageParser.ActivityIntentInfo info) { 12342 return packageName.equals(info.activity.owner.packageName); 12343 } 12344 12345 @Override 12346 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12347 int match, int userId) { 12348 if (!sUserManager.exists(userId)) return null; 12349 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12350 return null; 12351 } 12352 final PackageParser.Activity activity = info.activity; 12353 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12354 if (ps == null) { 12355 return null; 12356 } 12357 final PackageUserState userState = ps.readUserState(userId); 12358 ActivityInfo ai = 12359 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12360 if (ai == null) { 12361 return null; 12362 } 12363 final boolean matchExplicitlyVisibleOnly = 12364 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12365 final boolean matchVisibleToInstantApp = 12366 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12367 final boolean componentVisible = 12368 matchVisibleToInstantApp 12369 && info.isVisibleToInstantApp() 12370 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12371 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12372 // throw out filters that aren't visible to ephemeral apps 12373 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12374 return null; 12375 } 12376 // throw out instant app filters if we're not explicitly requesting them 12377 if (!matchInstantApp && userState.instantApp) { 12378 return null; 12379 } 12380 // throw out instant app filters if updates are available; will trigger 12381 // instant app resolution 12382 if (userState.instantApp && ps.isUpdateAvailable()) { 12383 return null; 12384 } 12385 final ResolveInfo res = new ResolveInfo(); 12386 res.activityInfo = ai; 12387 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12388 res.filter = info; 12389 } 12390 if (info != null) { 12391 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12392 } 12393 res.priority = info.getPriority(); 12394 res.preferredOrder = activity.owner.mPreferredOrder; 12395 //System.out.println("Result: " + res.activityInfo.className + 12396 // " = " + res.priority); 12397 res.match = match; 12398 res.isDefault = info.hasDefault; 12399 res.labelRes = info.labelRes; 12400 res.nonLocalizedLabel = info.nonLocalizedLabel; 12401 if (userNeedsBadging(userId)) { 12402 res.noResourceId = true; 12403 } else { 12404 res.icon = info.icon; 12405 } 12406 res.iconResourceId = info.icon; 12407 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12408 res.isInstantAppAvailable = userState.instantApp; 12409 return res; 12410 } 12411 12412 @Override 12413 protected void sortResults(List<ResolveInfo> results) { 12414 Collections.sort(results, mResolvePrioritySorter); 12415 } 12416 12417 @Override 12418 protected void dumpFilter(PrintWriter out, String prefix, 12419 PackageParser.ActivityIntentInfo filter) { 12420 out.print(prefix); out.print( 12421 Integer.toHexString(System.identityHashCode(filter.activity))); 12422 out.print(' '); 12423 filter.activity.printComponentShortName(out); 12424 out.print(" filter "); 12425 out.println(Integer.toHexString(System.identityHashCode(filter))); 12426 } 12427 12428 @Override 12429 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12430 return filter.activity; 12431 } 12432 12433 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12434 PackageParser.Activity activity = (PackageParser.Activity)label; 12435 out.print(prefix); out.print( 12436 Integer.toHexString(System.identityHashCode(activity))); 12437 out.print(' '); 12438 activity.printComponentShortName(out); 12439 if (count > 1) { 12440 out.print(" ("); out.print(count); out.print(" filters)"); 12441 } 12442 out.println(); 12443 } 12444 12445 // Keys are String (activity class name), values are Activity. 12446 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12447 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12448 private int mFlags; 12449 } 12450 12451 private final class ServiceIntentResolver 12452 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12453 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12454 boolean defaultOnly, int userId) { 12455 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12456 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12457 } 12458 12459 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12460 int userId) { 12461 if (!sUserManager.exists(userId)) return null; 12462 mFlags = flags; 12463 return super.queryIntent(intent, resolvedType, 12464 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12465 userId); 12466 } 12467 12468 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12469 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12470 if (!sUserManager.exists(userId)) return null; 12471 if (packageServices == null) { 12472 return null; 12473 } 12474 mFlags = flags; 12475 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12476 final int N = packageServices.size(); 12477 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12478 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12479 12480 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12481 for (int i = 0; i < N; ++i) { 12482 intentFilters = packageServices.get(i).intents; 12483 if (intentFilters != null && intentFilters.size() > 0) { 12484 PackageParser.ServiceIntentInfo[] array = 12485 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12486 intentFilters.toArray(array); 12487 listCut.add(array); 12488 } 12489 } 12490 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12491 } 12492 12493 public final void addService(PackageParser.Service s) { 12494 mServices.put(s.getComponentName(), s); 12495 if (DEBUG_SHOW_INFO) { 12496 Log.v(TAG, " " 12497 + (s.info.nonLocalizedLabel != null 12498 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12499 Log.v(TAG, " Class=" + s.info.name); 12500 } 12501 final int NI = s.intents.size(); 12502 int j; 12503 for (j=0; j<NI; j++) { 12504 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12505 if (DEBUG_SHOW_INFO) { 12506 Log.v(TAG, " IntentFilter:"); 12507 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12508 } 12509 if (!intent.debugCheck()) { 12510 Log.w(TAG, "==> For Service " + s.info.name); 12511 } 12512 addFilter(intent); 12513 } 12514 } 12515 12516 public final void removeService(PackageParser.Service s) { 12517 mServices.remove(s.getComponentName()); 12518 if (DEBUG_SHOW_INFO) { 12519 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12520 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12521 Log.v(TAG, " Class=" + s.info.name); 12522 } 12523 final int NI = s.intents.size(); 12524 int j; 12525 for (j=0; j<NI; j++) { 12526 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12527 if (DEBUG_SHOW_INFO) { 12528 Log.v(TAG, " IntentFilter:"); 12529 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12530 } 12531 removeFilter(intent); 12532 } 12533 } 12534 12535 @Override 12536 protected boolean allowFilterResult( 12537 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12538 ServiceInfo filterSi = filter.service.info; 12539 for (int i=dest.size()-1; i>=0; i--) { 12540 ServiceInfo destAi = dest.get(i).serviceInfo; 12541 if (destAi.name == filterSi.name 12542 && destAi.packageName == filterSi.packageName) { 12543 return false; 12544 } 12545 } 12546 return true; 12547 } 12548 12549 @Override 12550 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12551 return new PackageParser.ServiceIntentInfo[size]; 12552 } 12553 12554 @Override 12555 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12556 if (!sUserManager.exists(userId)) return true; 12557 PackageParser.Package p = filter.service.owner; 12558 if (p != null) { 12559 PackageSetting ps = (PackageSetting)p.mExtras; 12560 if (ps != null) { 12561 // System apps are never considered stopped for purposes of 12562 // filtering, because there may be no way for the user to 12563 // actually re-launch them. 12564 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12565 && ps.getStopped(userId); 12566 } 12567 } 12568 return false; 12569 } 12570 12571 @Override 12572 protected boolean isPackageForFilter(String packageName, 12573 PackageParser.ServiceIntentInfo info) { 12574 return packageName.equals(info.service.owner.packageName); 12575 } 12576 12577 @Override 12578 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12579 int match, int userId) { 12580 if (!sUserManager.exists(userId)) return null; 12581 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12582 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12583 return null; 12584 } 12585 final PackageParser.Service service = info.service; 12586 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12587 if (ps == null) { 12588 return null; 12589 } 12590 final PackageUserState userState = ps.readUserState(userId); 12591 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12592 userState, userId); 12593 if (si == null) { 12594 return null; 12595 } 12596 final boolean matchVisibleToInstantApp = 12597 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12598 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12599 // throw out filters that aren't visible to ephemeral apps 12600 if (matchVisibleToInstantApp 12601 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12602 return null; 12603 } 12604 // throw out ephemeral filters if we're not explicitly requesting them 12605 if (!isInstantApp && userState.instantApp) { 12606 return null; 12607 } 12608 // throw out instant app filters if updates are available; will trigger 12609 // instant app resolution 12610 if (userState.instantApp && ps.isUpdateAvailable()) { 12611 return null; 12612 } 12613 final ResolveInfo res = new ResolveInfo(); 12614 res.serviceInfo = si; 12615 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12616 res.filter = filter; 12617 } 12618 res.priority = info.getPriority(); 12619 res.preferredOrder = service.owner.mPreferredOrder; 12620 res.match = match; 12621 res.isDefault = info.hasDefault; 12622 res.labelRes = info.labelRes; 12623 res.nonLocalizedLabel = info.nonLocalizedLabel; 12624 res.icon = info.icon; 12625 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12626 return res; 12627 } 12628 12629 @Override 12630 protected void sortResults(List<ResolveInfo> results) { 12631 Collections.sort(results, mResolvePrioritySorter); 12632 } 12633 12634 @Override 12635 protected void dumpFilter(PrintWriter out, String prefix, 12636 PackageParser.ServiceIntentInfo filter) { 12637 out.print(prefix); out.print( 12638 Integer.toHexString(System.identityHashCode(filter.service))); 12639 out.print(' '); 12640 filter.service.printComponentShortName(out); 12641 out.print(" filter "); 12642 out.print(Integer.toHexString(System.identityHashCode(filter))); 12643 if (filter.service.info.permission != null) { 12644 out.print(" permission "); out.println(filter.service.info.permission); 12645 } else { 12646 out.println(); 12647 } 12648 } 12649 12650 @Override 12651 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12652 return filter.service; 12653 } 12654 12655 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12656 PackageParser.Service service = (PackageParser.Service)label; 12657 out.print(prefix); out.print( 12658 Integer.toHexString(System.identityHashCode(service))); 12659 out.print(' '); 12660 service.printComponentShortName(out); 12661 if (count > 1) { 12662 out.print(" ("); out.print(count); out.print(" filters)"); 12663 } 12664 out.println(); 12665 } 12666 12667// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12668// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12669// final List<ResolveInfo> retList = Lists.newArrayList(); 12670// while (i.hasNext()) { 12671// final ResolveInfo resolveInfo = (ResolveInfo) i; 12672// if (isEnabledLP(resolveInfo.serviceInfo)) { 12673// retList.add(resolveInfo); 12674// } 12675// } 12676// return retList; 12677// } 12678 12679 // Keys are String (activity class name), values are Activity. 12680 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12681 = new ArrayMap<ComponentName, PackageParser.Service>(); 12682 private int mFlags; 12683 } 12684 12685 private final class ProviderIntentResolver 12686 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12687 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12688 boolean defaultOnly, int userId) { 12689 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12690 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12691 } 12692 12693 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12694 int userId) { 12695 if (!sUserManager.exists(userId)) 12696 return null; 12697 mFlags = flags; 12698 return super.queryIntent(intent, resolvedType, 12699 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12700 userId); 12701 } 12702 12703 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12704 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12705 if (!sUserManager.exists(userId)) 12706 return null; 12707 if (packageProviders == null) { 12708 return null; 12709 } 12710 mFlags = flags; 12711 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12712 final int N = packageProviders.size(); 12713 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12714 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12715 12716 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12717 for (int i = 0; i < N; ++i) { 12718 intentFilters = packageProviders.get(i).intents; 12719 if (intentFilters != null && intentFilters.size() > 0) { 12720 PackageParser.ProviderIntentInfo[] array = 12721 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12722 intentFilters.toArray(array); 12723 listCut.add(array); 12724 } 12725 } 12726 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12727 } 12728 12729 public final void addProvider(PackageParser.Provider p) { 12730 if (mProviders.containsKey(p.getComponentName())) { 12731 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12732 return; 12733 } 12734 12735 mProviders.put(p.getComponentName(), p); 12736 if (DEBUG_SHOW_INFO) { 12737 Log.v(TAG, " " 12738 + (p.info.nonLocalizedLabel != null 12739 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12740 Log.v(TAG, " Class=" + p.info.name); 12741 } 12742 final int NI = p.intents.size(); 12743 int j; 12744 for (j = 0; j < NI; j++) { 12745 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12746 if (DEBUG_SHOW_INFO) { 12747 Log.v(TAG, " IntentFilter:"); 12748 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12749 } 12750 if (!intent.debugCheck()) { 12751 Log.w(TAG, "==> For Provider " + p.info.name); 12752 } 12753 addFilter(intent); 12754 } 12755 } 12756 12757 public final void removeProvider(PackageParser.Provider p) { 12758 mProviders.remove(p.getComponentName()); 12759 if (DEBUG_SHOW_INFO) { 12760 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12761 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12762 Log.v(TAG, " Class=" + p.info.name); 12763 } 12764 final int NI = p.intents.size(); 12765 int j; 12766 for (j = 0; j < NI; j++) { 12767 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12768 if (DEBUG_SHOW_INFO) { 12769 Log.v(TAG, " IntentFilter:"); 12770 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12771 } 12772 removeFilter(intent); 12773 } 12774 } 12775 12776 @Override 12777 protected boolean allowFilterResult( 12778 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12779 ProviderInfo filterPi = filter.provider.info; 12780 for (int i = dest.size() - 1; i >= 0; i--) { 12781 ProviderInfo destPi = dest.get(i).providerInfo; 12782 if (destPi.name == filterPi.name 12783 && destPi.packageName == filterPi.packageName) { 12784 return false; 12785 } 12786 } 12787 return true; 12788 } 12789 12790 @Override 12791 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12792 return new PackageParser.ProviderIntentInfo[size]; 12793 } 12794 12795 @Override 12796 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12797 if (!sUserManager.exists(userId)) 12798 return true; 12799 PackageParser.Package p = filter.provider.owner; 12800 if (p != null) { 12801 PackageSetting ps = (PackageSetting) p.mExtras; 12802 if (ps != null) { 12803 // System apps are never considered stopped for purposes of 12804 // filtering, because there may be no way for the user to 12805 // actually re-launch them. 12806 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12807 && ps.getStopped(userId); 12808 } 12809 } 12810 return false; 12811 } 12812 12813 @Override 12814 protected boolean isPackageForFilter(String packageName, 12815 PackageParser.ProviderIntentInfo info) { 12816 return packageName.equals(info.provider.owner.packageName); 12817 } 12818 12819 @Override 12820 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12821 int match, int userId) { 12822 if (!sUserManager.exists(userId)) 12823 return null; 12824 final PackageParser.ProviderIntentInfo info = filter; 12825 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12826 return null; 12827 } 12828 final PackageParser.Provider provider = info.provider; 12829 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12830 if (ps == null) { 12831 return null; 12832 } 12833 final PackageUserState userState = ps.readUserState(userId); 12834 final boolean matchVisibleToInstantApp = 12835 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12836 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12837 // throw out filters that aren't visible to instant applications 12838 if (matchVisibleToInstantApp 12839 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12840 return null; 12841 } 12842 // throw out instant application filters if we're not explicitly requesting them 12843 if (!isInstantApp && userState.instantApp) { 12844 return null; 12845 } 12846 // throw out instant application filters if updates are available; will trigger 12847 // instant application resolution 12848 if (userState.instantApp && ps.isUpdateAvailable()) { 12849 return null; 12850 } 12851 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12852 userState, userId); 12853 if (pi == null) { 12854 return null; 12855 } 12856 final ResolveInfo res = new ResolveInfo(); 12857 res.providerInfo = pi; 12858 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12859 res.filter = filter; 12860 } 12861 res.priority = info.getPriority(); 12862 res.preferredOrder = provider.owner.mPreferredOrder; 12863 res.match = match; 12864 res.isDefault = info.hasDefault; 12865 res.labelRes = info.labelRes; 12866 res.nonLocalizedLabel = info.nonLocalizedLabel; 12867 res.icon = info.icon; 12868 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12869 return res; 12870 } 12871 12872 @Override 12873 protected void sortResults(List<ResolveInfo> results) { 12874 Collections.sort(results, mResolvePrioritySorter); 12875 } 12876 12877 @Override 12878 protected void dumpFilter(PrintWriter out, String prefix, 12879 PackageParser.ProviderIntentInfo filter) { 12880 out.print(prefix); 12881 out.print( 12882 Integer.toHexString(System.identityHashCode(filter.provider))); 12883 out.print(' '); 12884 filter.provider.printComponentShortName(out); 12885 out.print(" filter "); 12886 out.println(Integer.toHexString(System.identityHashCode(filter))); 12887 } 12888 12889 @Override 12890 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12891 return filter.provider; 12892 } 12893 12894 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12895 PackageParser.Provider provider = (PackageParser.Provider)label; 12896 out.print(prefix); out.print( 12897 Integer.toHexString(System.identityHashCode(provider))); 12898 out.print(' '); 12899 provider.printComponentShortName(out); 12900 if (count > 1) { 12901 out.print(" ("); out.print(count); out.print(" filters)"); 12902 } 12903 out.println(); 12904 } 12905 12906 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12907 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12908 private int mFlags; 12909 } 12910 12911 static final class EphemeralIntentResolver 12912 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12913 /** 12914 * The result that has the highest defined order. Ordering applies on a 12915 * per-package basis. Mapping is from package name to Pair of order and 12916 * EphemeralResolveInfo. 12917 * <p> 12918 * NOTE: This is implemented as a field variable for convenience and efficiency. 12919 * By having a field variable, we're able to track filter ordering as soon as 12920 * a non-zero order is defined. Otherwise, multiple loops across the result set 12921 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12922 * this needs to be contained entirely within {@link #filterResults}. 12923 */ 12924 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12925 12926 @Override 12927 protected AuxiliaryResolveInfo[] newArray(int size) { 12928 return new AuxiliaryResolveInfo[size]; 12929 } 12930 12931 @Override 12932 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12933 return true; 12934 } 12935 12936 @Override 12937 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12938 int userId) { 12939 if (!sUserManager.exists(userId)) { 12940 return null; 12941 } 12942 final String packageName = responseObj.resolveInfo.getPackageName(); 12943 final Integer order = responseObj.getOrder(); 12944 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12945 mOrderResult.get(packageName); 12946 // ordering is enabled and this item's order isn't high enough 12947 if (lastOrderResult != null && lastOrderResult.first >= order) { 12948 return null; 12949 } 12950 final InstantAppResolveInfo res = responseObj.resolveInfo; 12951 if (order > 0) { 12952 // non-zero order, enable ordering 12953 mOrderResult.put(packageName, new Pair<>(order, res)); 12954 } 12955 return responseObj; 12956 } 12957 12958 @Override 12959 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12960 // only do work if ordering is enabled [most of the time it won't be] 12961 if (mOrderResult.size() == 0) { 12962 return; 12963 } 12964 int resultSize = results.size(); 12965 for (int i = 0; i < resultSize; i++) { 12966 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12967 final String packageName = info.getPackageName(); 12968 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12969 if (savedInfo == null) { 12970 // package doesn't having ordering 12971 continue; 12972 } 12973 if (savedInfo.second == info) { 12974 // circled back to the highest ordered item; remove from order list 12975 mOrderResult.remove(packageName); 12976 if (mOrderResult.size() == 0) { 12977 // no more ordered items 12978 break; 12979 } 12980 continue; 12981 } 12982 // item has a worse order, remove it from the result list 12983 results.remove(i); 12984 resultSize--; 12985 i--; 12986 } 12987 } 12988 } 12989 12990 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 12991 new Comparator<ResolveInfo>() { 12992 public int compare(ResolveInfo r1, ResolveInfo r2) { 12993 int v1 = r1.priority; 12994 int v2 = r2.priority; 12995 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 12996 if (v1 != v2) { 12997 return (v1 > v2) ? -1 : 1; 12998 } 12999 v1 = r1.preferredOrder; 13000 v2 = r2.preferredOrder; 13001 if (v1 != v2) { 13002 return (v1 > v2) ? -1 : 1; 13003 } 13004 if (r1.isDefault != r2.isDefault) { 13005 return r1.isDefault ? -1 : 1; 13006 } 13007 v1 = r1.match; 13008 v2 = r2.match; 13009 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13010 if (v1 != v2) { 13011 return (v1 > v2) ? -1 : 1; 13012 } 13013 if (r1.system != r2.system) { 13014 return r1.system ? -1 : 1; 13015 } 13016 if (r1.activityInfo != null) { 13017 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13018 } 13019 if (r1.serviceInfo != null) { 13020 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13021 } 13022 if (r1.providerInfo != null) { 13023 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13024 } 13025 return 0; 13026 } 13027 }; 13028 13029 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13030 new Comparator<ProviderInfo>() { 13031 public int compare(ProviderInfo p1, ProviderInfo p2) { 13032 final int v1 = p1.initOrder; 13033 final int v2 = p2.initOrder; 13034 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13035 } 13036 }; 13037 13038 @Override 13039 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13040 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13041 final int[] userIds, int[] instantUserIds) { 13042 mHandler.post(new Runnable() { 13043 @Override 13044 public void run() { 13045 try { 13046 final IActivityManager am = ActivityManager.getService(); 13047 if (am == null) return; 13048 final int[] resolvedUserIds; 13049 if (userIds == null) { 13050 resolvedUserIds = am.getRunningUserIds(); 13051 } else { 13052 resolvedUserIds = userIds; 13053 } 13054 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13055 resolvedUserIds, false); 13056 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13057 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13058 instantUserIds, true); 13059 } 13060 } catch (RemoteException ex) { 13061 } 13062 } 13063 }); 13064 } 13065 13066 @Override 13067 public void notifyPackageAdded(String packageName) { 13068 final PackageListObserver[] observers; 13069 synchronized (mPackages) { 13070 if (mPackageListObservers.size() == 0) { 13071 return; 13072 } 13073 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13074 } 13075 for (int i = observers.length - 1; i >= 0; --i) { 13076 observers[i].onPackageAdded(packageName); 13077 } 13078 } 13079 13080 @Override 13081 public void notifyPackageRemoved(String packageName) { 13082 final PackageListObserver[] observers; 13083 synchronized (mPackages) { 13084 if (mPackageListObservers.size() == 0) { 13085 return; 13086 } 13087 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13088 } 13089 for (int i = observers.length - 1; i >= 0; --i) { 13090 observers[i].onPackageRemoved(packageName); 13091 } 13092 } 13093 13094 /** 13095 * Sends a broadcast for the given action. 13096 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13097 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13098 * the system and applications allowed to see instant applications to receive package 13099 * lifecycle events for instant applications. 13100 */ 13101 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13102 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13103 int[] userIds, boolean isInstantApp) 13104 throws RemoteException { 13105 for (int id : userIds) { 13106 final Intent intent = new Intent(action, 13107 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13108 final String[] requiredPermissions = 13109 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13110 if (extras != null) { 13111 intent.putExtras(extras); 13112 } 13113 if (targetPkg != null) { 13114 intent.setPackage(targetPkg); 13115 } 13116 // Modify the UID when posting to other users 13117 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13118 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13119 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13120 intent.putExtra(Intent.EXTRA_UID, uid); 13121 } 13122 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13123 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13124 if (DEBUG_BROADCASTS) { 13125 RuntimeException here = new RuntimeException("here"); 13126 here.fillInStackTrace(); 13127 Slog.d(TAG, "Sending to user " + id + ": " 13128 + intent.toShortString(false, true, false, false) 13129 + " " + intent.getExtras(), here); 13130 } 13131 am.broadcastIntent(null, intent, null, finishedReceiver, 13132 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13133 null, finishedReceiver != null, false, id); 13134 } 13135 } 13136 13137 /** 13138 * Check if the external storage media is available. This is true if there 13139 * is a mounted external storage medium or if the external storage is 13140 * emulated. 13141 */ 13142 private boolean isExternalMediaAvailable() { 13143 return mMediaMounted || Environment.isExternalStorageEmulated(); 13144 } 13145 13146 @Override 13147 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13148 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13149 return null; 13150 } 13151 if (!isExternalMediaAvailable()) { 13152 // If the external storage is no longer mounted at this point, 13153 // the caller may not have been able to delete all of this 13154 // packages files and can not delete any more. Bail. 13155 return null; 13156 } 13157 synchronized (mPackages) { 13158 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13159 if (lastPackage != null) { 13160 pkgs.remove(lastPackage); 13161 } 13162 if (pkgs.size() > 0) { 13163 return pkgs.get(0); 13164 } 13165 } 13166 return null; 13167 } 13168 13169 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13170 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13171 userId, andCode ? 1 : 0, packageName); 13172 if (mSystemReady) { 13173 msg.sendToTarget(); 13174 } else { 13175 if (mPostSystemReadyMessages == null) { 13176 mPostSystemReadyMessages = new ArrayList<>(); 13177 } 13178 mPostSystemReadyMessages.add(msg); 13179 } 13180 } 13181 13182 void startCleaningPackages() { 13183 // reader 13184 if (!isExternalMediaAvailable()) { 13185 return; 13186 } 13187 synchronized (mPackages) { 13188 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13189 return; 13190 } 13191 } 13192 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13193 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13194 IActivityManager am = ActivityManager.getService(); 13195 if (am != null) { 13196 int dcsUid = -1; 13197 synchronized (mPackages) { 13198 if (!mDefaultContainerWhitelisted) { 13199 mDefaultContainerWhitelisted = true; 13200 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13201 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13202 } 13203 } 13204 try { 13205 if (dcsUid > 0) { 13206 am.backgroundWhitelistUid(dcsUid); 13207 } 13208 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13209 UserHandle.USER_SYSTEM); 13210 } catch (RemoteException e) { 13211 } 13212 } 13213 } 13214 13215 /** 13216 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13217 * it is acting on behalf on an enterprise or the user). 13218 * 13219 * Note that the ordering of the conditionals in this method is important. The checks we perform 13220 * are as follows, in this order: 13221 * 13222 * 1) If the install is being performed by a system app, we can trust the app to have set the 13223 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13224 * what it is. 13225 * 2) If the install is being performed by a device or profile owner app, the install reason 13226 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13227 * set the install reason correctly. If the app targets an older SDK version where install 13228 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13229 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13230 * 3) In all other cases, the install is being performed by a regular app that is neither part 13231 * of the system nor a device or profile owner. We have no reason to believe that this app is 13232 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13233 * set to enterprise policy and if so, change it to unknown instead. 13234 */ 13235 private int fixUpInstallReason(String installerPackageName, int installerUid, 13236 int installReason) { 13237 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13238 == PERMISSION_GRANTED) { 13239 // If the install is being performed by a system app, we trust that app to have set the 13240 // install reason correctly. 13241 return installReason; 13242 } 13243 13244 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13245 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13246 if (dpm != null) { 13247 ComponentName owner = null; 13248 try { 13249 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13250 if (owner == null) { 13251 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13252 } 13253 } catch (RemoteException e) { 13254 } 13255 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13256 // If the install is being performed by a device or profile owner, the install 13257 // reason should be enterprise policy. 13258 return PackageManager.INSTALL_REASON_POLICY; 13259 } 13260 } 13261 13262 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13263 // If the install is being performed by a regular app (i.e. neither system app nor 13264 // device or profile owner), we have no reason to believe that the app is acting on 13265 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13266 // change it to unknown instead. 13267 return PackageManager.INSTALL_REASON_UNKNOWN; 13268 } 13269 13270 // If the install is being performed by a regular app and the install reason was set to any 13271 // value but enterprise policy, leave the install reason unchanged. 13272 return installReason; 13273 } 13274 13275 void installStage(String packageName, File stagedDir, 13276 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13277 String installerPackageName, int installerUid, UserHandle user, 13278 PackageParser.SigningDetails signingDetails) { 13279 if (DEBUG_EPHEMERAL) { 13280 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13281 Slog.d(TAG, "Ephemeral install of " + packageName); 13282 } 13283 } 13284 final VerificationInfo verificationInfo = new VerificationInfo( 13285 sessionParams.originatingUri, sessionParams.referrerUri, 13286 sessionParams.originatingUid, installerUid); 13287 13288 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13289 13290 final Message msg = mHandler.obtainMessage(INIT_COPY); 13291 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13292 sessionParams.installReason); 13293 final InstallParams params = new InstallParams(origin, null, observer, 13294 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13295 verificationInfo, user, sessionParams.abiOverride, 13296 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13297 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13298 msg.obj = params; 13299 13300 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13301 System.identityHashCode(msg.obj)); 13302 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13303 System.identityHashCode(msg.obj)); 13304 13305 mHandler.sendMessage(msg); 13306 } 13307 13308 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13309 int userId) { 13310 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13311 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13312 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13313 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13314 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13315 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13316 13317 // Send a session commit broadcast 13318 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13319 info.installReason = pkgSetting.getInstallReason(userId); 13320 info.appPackageName = packageName; 13321 sendSessionCommitBroadcast(info, userId); 13322 } 13323 13324 @Override 13325 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13326 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13327 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13328 return; 13329 } 13330 Bundle extras = new Bundle(1); 13331 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13332 final int uid = UserHandle.getUid( 13333 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13334 extras.putInt(Intent.EXTRA_UID, uid); 13335 13336 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13337 packageName, extras, 0, null, null, userIds, instantUserIds); 13338 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13339 mHandler.post(() -> { 13340 for (int userId : userIds) { 13341 sendBootCompletedBroadcastToSystemApp( 13342 packageName, includeStopped, userId); 13343 } 13344 } 13345 ); 13346 } 13347 } 13348 13349 /** 13350 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13351 * automatically without needing an explicit launch. 13352 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13353 */ 13354 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13355 int userId) { 13356 // If user is not running, the app didn't miss any broadcast 13357 if (!mUserManagerInternal.isUserRunning(userId)) { 13358 return; 13359 } 13360 final IActivityManager am = ActivityManager.getService(); 13361 try { 13362 // Deliver LOCKED_BOOT_COMPLETED first 13363 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13364 .setPackage(packageName); 13365 if (includeStopped) { 13366 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13367 } 13368 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13369 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13370 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13371 13372 // Deliver BOOT_COMPLETED only if user is unlocked 13373 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13374 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13375 if (includeStopped) { 13376 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13377 } 13378 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13379 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13380 } 13381 } catch (RemoteException e) { 13382 throw e.rethrowFromSystemServer(); 13383 } 13384 } 13385 13386 @Override 13387 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13388 int userId) { 13389 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13390 PackageSetting pkgSetting; 13391 final int callingUid = Binder.getCallingUid(); 13392 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13393 true /* requireFullPermission */, true /* checkShell */, 13394 "setApplicationHiddenSetting for user " + userId); 13395 13396 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13397 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13398 return false; 13399 } 13400 13401 long callingId = Binder.clearCallingIdentity(); 13402 try { 13403 boolean sendAdded = false; 13404 boolean sendRemoved = false; 13405 // writer 13406 synchronized (mPackages) { 13407 pkgSetting = mSettings.mPackages.get(packageName); 13408 if (pkgSetting == null) { 13409 return false; 13410 } 13411 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13412 return false; 13413 } 13414 // Do not allow "android" is being disabled 13415 if ("android".equals(packageName)) { 13416 Slog.w(TAG, "Cannot hide package: android"); 13417 return false; 13418 } 13419 // Cannot hide static shared libs as they are considered 13420 // a part of the using app (emulating static linking). Also 13421 // static libs are installed always on internal storage. 13422 PackageParser.Package pkg = mPackages.get(packageName); 13423 if (pkg != null && pkg.staticSharedLibName != null) { 13424 Slog.w(TAG, "Cannot hide package: " + packageName 13425 + " providing static shared library: " 13426 + pkg.staticSharedLibName); 13427 return false; 13428 } 13429 // Only allow protected packages to hide themselves. 13430 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13431 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13432 Slog.w(TAG, "Not hiding protected package: " + packageName); 13433 return false; 13434 } 13435 13436 if (pkgSetting.getHidden(userId) != hidden) { 13437 pkgSetting.setHidden(hidden, userId); 13438 mSettings.writePackageRestrictionsLPr(userId); 13439 if (hidden) { 13440 sendRemoved = true; 13441 } else { 13442 sendAdded = true; 13443 } 13444 } 13445 } 13446 if (sendAdded) { 13447 sendPackageAddedForUser(packageName, pkgSetting, userId); 13448 return true; 13449 } 13450 if (sendRemoved) { 13451 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13452 "hiding pkg"); 13453 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13454 return true; 13455 } 13456 } finally { 13457 Binder.restoreCallingIdentity(callingId); 13458 } 13459 return false; 13460 } 13461 13462 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13463 int userId) { 13464 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13465 info.removedPackage = packageName; 13466 info.installerPackageName = pkgSetting.installerPackageName; 13467 info.removedUsers = new int[] {userId}; 13468 info.broadcastUsers = new int[] {userId}; 13469 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13470 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13471 } 13472 13473 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13474 if (pkgList.length > 0) { 13475 Bundle extras = new Bundle(1); 13476 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13477 13478 sendPackageBroadcast( 13479 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13480 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13481 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13482 new int[] {userId}, null); 13483 } 13484 } 13485 13486 /** 13487 * Returns true if application is not found or there was an error. Otherwise it returns 13488 * the hidden state of the package for the given user. 13489 */ 13490 @Override 13491 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13492 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13493 final int callingUid = Binder.getCallingUid(); 13494 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13495 true /* requireFullPermission */, false /* checkShell */, 13496 "getApplicationHidden for user " + userId); 13497 PackageSetting ps; 13498 long callingId = Binder.clearCallingIdentity(); 13499 try { 13500 // writer 13501 synchronized (mPackages) { 13502 ps = mSettings.mPackages.get(packageName); 13503 if (ps == null) { 13504 return true; 13505 } 13506 if (filterAppAccessLPr(ps, callingUid, userId)) { 13507 return true; 13508 } 13509 return ps.getHidden(userId); 13510 } 13511 } finally { 13512 Binder.restoreCallingIdentity(callingId); 13513 } 13514 } 13515 13516 /** 13517 * @hide 13518 */ 13519 @Override 13520 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13521 int installReason) { 13522 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13523 null); 13524 PackageSetting pkgSetting; 13525 final int callingUid = Binder.getCallingUid(); 13526 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13527 true /* requireFullPermission */, true /* checkShell */, 13528 "installExistingPackage for user " + userId); 13529 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13530 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13531 } 13532 13533 long callingId = Binder.clearCallingIdentity(); 13534 try { 13535 boolean installed = false; 13536 final boolean instantApp = 13537 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13538 final boolean fullApp = 13539 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13540 13541 // writer 13542 synchronized (mPackages) { 13543 pkgSetting = mSettings.mPackages.get(packageName); 13544 if (pkgSetting == null) { 13545 return PackageManager.INSTALL_FAILED_INVALID_URI; 13546 } 13547 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13548 // only allow the existing package to be used if it's installed as a full 13549 // application for at least one user 13550 boolean installAllowed = false; 13551 for (int checkUserId : sUserManager.getUserIds()) { 13552 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13553 if (installAllowed) { 13554 break; 13555 } 13556 } 13557 if (!installAllowed) { 13558 return PackageManager.INSTALL_FAILED_INVALID_URI; 13559 } 13560 } 13561 if (!pkgSetting.getInstalled(userId)) { 13562 pkgSetting.setInstalled(true, userId); 13563 pkgSetting.setHidden(false, userId); 13564 pkgSetting.setInstallReason(installReason, userId); 13565 mSettings.writePackageRestrictionsLPr(userId); 13566 mSettings.writeKernelMappingLPr(pkgSetting); 13567 installed = true; 13568 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13569 // upgrade app from instant to full; we don't allow app downgrade 13570 installed = true; 13571 } 13572 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13573 } 13574 13575 if (installed) { 13576 if (pkgSetting.pkg != null) { 13577 synchronized (mInstallLock) { 13578 // We don't need to freeze for a brand new install 13579 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13580 } 13581 } 13582 sendPackageAddedForUser(packageName, pkgSetting, userId); 13583 synchronized (mPackages) { 13584 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13585 } 13586 } 13587 } finally { 13588 Binder.restoreCallingIdentity(callingId); 13589 } 13590 13591 return PackageManager.INSTALL_SUCCEEDED; 13592 } 13593 13594 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13595 boolean instantApp, boolean fullApp) { 13596 // no state specified; do nothing 13597 if (!instantApp && !fullApp) { 13598 return; 13599 } 13600 if (userId != UserHandle.USER_ALL) { 13601 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13602 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13603 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13604 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13605 } 13606 } else { 13607 for (int currentUserId : sUserManager.getUserIds()) { 13608 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13609 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13610 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13611 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13612 } 13613 } 13614 } 13615 } 13616 13617 boolean isUserRestricted(int userId, String restrictionKey) { 13618 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13619 if (restrictions.getBoolean(restrictionKey, false)) { 13620 Log.w(TAG, "User is restricted: " + restrictionKey); 13621 return true; 13622 } 13623 return false; 13624 } 13625 13626 @Override 13627 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13628 int userId) { 13629 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13630 final int callingUid = Binder.getCallingUid(); 13631 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13632 true /* requireFullPermission */, true /* checkShell */, 13633 "setPackagesSuspended for user " + userId); 13634 13635 if (ArrayUtils.isEmpty(packageNames)) { 13636 return packageNames; 13637 } 13638 13639 // List of package names for whom the suspended state has changed. 13640 List<String> changedPackages = new ArrayList<>(packageNames.length); 13641 // List of package names for whom the suspended state is not set as requested in this 13642 // method. 13643 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13644 long callingId = Binder.clearCallingIdentity(); 13645 try { 13646 for (int i = 0; i < packageNames.length; i++) { 13647 String packageName = packageNames[i]; 13648 boolean changed = false; 13649 final int appId; 13650 synchronized (mPackages) { 13651 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13652 if (pkgSetting == null 13653 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13654 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13655 + "\". Skipping suspending/un-suspending."); 13656 unactionedPackages.add(packageName); 13657 continue; 13658 } 13659 appId = pkgSetting.appId; 13660 if (pkgSetting.getSuspended(userId) != suspended) { 13661 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13662 unactionedPackages.add(packageName); 13663 continue; 13664 } 13665 pkgSetting.setSuspended(suspended, userId); 13666 mSettings.writePackageRestrictionsLPr(userId); 13667 changed = true; 13668 changedPackages.add(packageName); 13669 } 13670 } 13671 13672 if (changed && suspended) { 13673 killApplication(packageName, UserHandle.getUid(userId, appId), 13674 "suspending package"); 13675 } 13676 } 13677 } finally { 13678 Binder.restoreCallingIdentity(callingId); 13679 } 13680 13681 if (!changedPackages.isEmpty()) { 13682 sendPackagesSuspendedForUser(changedPackages.toArray( 13683 new String[changedPackages.size()]), userId, suspended); 13684 } 13685 13686 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13687 } 13688 13689 @Override 13690 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13691 final int callingUid = Binder.getCallingUid(); 13692 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13693 true /* requireFullPermission */, false /* checkShell */, 13694 "isPackageSuspendedForUser for user " + userId); 13695 synchronized (mPackages) { 13696 final PackageSetting ps = mSettings.mPackages.get(packageName); 13697 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13698 throw new IllegalArgumentException("Unknown target package: " + packageName); 13699 } 13700 return ps.getSuspended(userId); 13701 } 13702 } 13703 13704 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13705 if (isPackageDeviceAdmin(packageName, userId)) { 13706 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13707 + "\": has an active device admin"); 13708 return false; 13709 } 13710 13711 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13712 if (packageName.equals(activeLauncherPackageName)) { 13713 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13714 + "\": contains the active launcher"); 13715 return false; 13716 } 13717 13718 if (packageName.equals(mRequiredInstallerPackage)) { 13719 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13720 + "\": required for package installation"); 13721 return false; 13722 } 13723 13724 if (packageName.equals(mRequiredUninstallerPackage)) { 13725 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13726 + "\": required for package uninstallation"); 13727 return false; 13728 } 13729 13730 if (packageName.equals(mRequiredVerifierPackage)) { 13731 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13732 + "\": required for package verification"); 13733 return false; 13734 } 13735 13736 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13737 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13738 + "\": is the default dialer"); 13739 return false; 13740 } 13741 13742 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13743 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13744 + "\": protected package"); 13745 return false; 13746 } 13747 13748 // Cannot suspend static shared libs as they are considered 13749 // a part of the using app (emulating static linking). Also 13750 // static libs are installed always on internal storage. 13751 PackageParser.Package pkg = mPackages.get(packageName); 13752 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13753 Slog.w(TAG, "Cannot suspend package: " + packageName 13754 + " providing static shared library: " 13755 + pkg.staticSharedLibName); 13756 return false; 13757 } 13758 13759 return true; 13760 } 13761 13762 private String getActiveLauncherPackageName(int userId) { 13763 Intent intent = new Intent(Intent.ACTION_MAIN); 13764 intent.addCategory(Intent.CATEGORY_HOME); 13765 ResolveInfo resolveInfo = resolveIntent( 13766 intent, 13767 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13768 PackageManager.MATCH_DEFAULT_ONLY, 13769 userId); 13770 13771 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13772 } 13773 13774 private String getDefaultDialerPackageName(int userId) { 13775 synchronized (mPackages) { 13776 return mSettings.getDefaultDialerPackageNameLPw(userId); 13777 } 13778 } 13779 13780 @Override 13781 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13782 mContext.enforceCallingOrSelfPermission( 13783 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13784 "Only package verification agents can verify applications"); 13785 13786 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13787 final PackageVerificationResponse response = new PackageVerificationResponse( 13788 verificationCode, Binder.getCallingUid()); 13789 msg.arg1 = id; 13790 msg.obj = response; 13791 mHandler.sendMessage(msg); 13792 } 13793 13794 @Override 13795 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13796 long millisecondsToDelay) { 13797 mContext.enforceCallingOrSelfPermission( 13798 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13799 "Only package verification agents can extend verification timeouts"); 13800 13801 final PackageVerificationState state = mPendingVerification.get(id); 13802 final PackageVerificationResponse response = new PackageVerificationResponse( 13803 verificationCodeAtTimeout, Binder.getCallingUid()); 13804 13805 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13806 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13807 } 13808 if (millisecondsToDelay < 0) { 13809 millisecondsToDelay = 0; 13810 } 13811 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13812 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13813 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13814 } 13815 13816 if ((state != null) && !state.timeoutExtended()) { 13817 state.extendTimeout(); 13818 13819 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13820 msg.arg1 = id; 13821 msg.obj = response; 13822 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13823 } 13824 } 13825 13826 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13827 int verificationCode, UserHandle user) { 13828 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13829 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13830 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13831 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13832 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13833 13834 mContext.sendBroadcastAsUser(intent, user, 13835 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13836 } 13837 13838 private ComponentName matchComponentForVerifier(String packageName, 13839 List<ResolveInfo> receivers) { 13840 ActivityInfo targetReceiver = null; 13841 13842 final int NR = receivers.size(); 13843 for (int i = 0; i < NR; i++) { 13844 final ResolveInfo info = receivers.get(i); 13845 if (info.activityInfo == null) { 13846 continue; 13847 } 13848 13849 if (packageName.equals(info.activityInfo.packageName)) { 13850 targetReceiver = info.activityInfo; 13851 break; 13852 } 13853 } 13854 13855 if (targetReceiver == null) { 13856 return null; 13857 } 13858 13859 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13860 } 13861 13862 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13863 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13864 if (pkgInfo.verifiers.length == 0) { 13865 return null; 13866 } 13867 13868 final int N = pkgInfo.verifiers.length; 13869 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13870 for (int i = 0; i < N; i++) { 13871 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13872 13873 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13874 receivers); 13875 if (comp == null) { 13876 continue; 13877 } 13878 13879 final int verifierUid = getUidForVerifier(verifierInfo); 13880 if (verifierUid == -1) { 13881 continue; 13882 } 13883 13884 if (DEBUG_VERIFY) { 13885 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13886 + " with the correct signature"); 13887 } 13888 sufficientVerifiers.add(comp); 13889 verificationState.addSufficientVerifier(verifierUid); 13890 } 13891 13892 return sufficientVerifiers; 13893 } 13894 13895 private int getUidForVerifier(VerifierInfo verifierInfo) { 13896 synchronized (mPackages) { 13897 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13898 if (pkg == null) { 13899 return -1; 13900 } else if (pkg.mSigningDetails.signatures.length != 1) { 13901 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13902 + " has more than one signature; ignoring"); 13903 return -1; 13904 } 13905 13906 /* 13907 * If the public key of the package's signature does not match 13908 * our expected public key, then this is a different package and 13909 * we should skip. 13910 */ 13911 13912 final byte[] expectedPublicKey; 13913 try { 13914 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 13915 final PublicKey publicKey = verifierSig.getPublicKey(); 13916 expectedPublicKey = publicKey.getEncoded(); 13917 } catch (CertificateException e) { 13918 return -1; 13919 } 13920 13921 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13922 13923 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13924 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13925 + " does not have the expected public key; ignoring"); 13926 return -1; 13927 } 13928 13929 return pkg.applicationInfo.uid; 13930 } 13931 } 13932 13933 @Override 13934 public void finishPackageInstall(int token, boolean didLaunch) { 13935 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13936 13937 if (DEBUG_INSTALL) { 13938 Slog.v(TAG, "BM finishing package install for " + token); 13939 } 13940 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13941 13942 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13943 mHandler.sendMessage(msg); 13944 } 13945 13946 /** 13947 * Get the verification agent timeout. Used for both the APK verifier and the 13948 * intent filter verifier. 13949 * 13950 * @return verification timeout in milliseconds 13951 */ 13952 private long getVerificationTimeout() { 13953 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13954 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13955 DEFAULT_VERIFICATION_TIMEOUT); 13956 } 13957 13958 /** 13959 * Get the default verification agent response code. 13960 * 13961 * @return default verification response code 13962 */ 13963 private int getDefaultVerificationResponse(UserHandle user) { 13964 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13965 return PackageManager.VERIFICATION_REJECT; 13966 } 13967 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13968 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13969 DEFAULT_VERIFICATION_RESPONSE); 13970 } 13971 13972 /** 13973 * Check whether or not package verification has been enabled. 13974 * 13975 * @return true if verification should be performed 13976 */ 13977 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13978 if (!DEFAULT_VERIFY_ENABLE) { 13979 return false; 13980 } 13981 13982 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13983 13984 // Check if installing from ADB 13985 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13986 // Do not run verification in a test harness environment 13987 if (ActivityManager.isRunningInTestHarness()) { 13988 return false; 13989 } 13990 if (ensureVerifyAppsEnabled) { 13991 return true; 13992 } 13993 // Check if the developer does not want package verification for ADB installs 13994 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13995 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13996 return false; 13997 } 13998 } else { 13999 // only when not installed from ADB, skip verification for instant apps when 14000 // the installer and verifier are the same. 14001 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14002 if (mInstantAppInstallerActivity != null 14003 && mInstantAppInstallerActivity.packageName.equals( 14004 mRequiredVerifierPackage)) { 14005 try { 14006 mContext.getSystemService(AppOpsManager.class) 14007 .checkPackage(installerUid, mRequiredVerifierPackage); 14008 if (DEBUG_VERIFY) { 14009 Slog.i(TAG, "disable verification for instant app"); 14010 } 14011 return false; 14012 } catch (SecurityException ignore) { } 14013 } 14014 } 14015 } 14016 14017 if (ensureVerifyAppsEnabled) { 14018 return true; 14019 } 14020 14021 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14022 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14023 } 14024 14025 @Override 14026 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14027 throws RemoteException { 14028 mContext.enforceCallingOrSelfPermission( 14029 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14030 "Only intentfilter verification agents can verify applications"); 14031 14032 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14033 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14034 Binder.getCallingUid(), verificationCode, failedDomains); 14035 msg.arg1 = id; 14036 msg.obj = response; 14037 mHandler.sendMessage(msg); 14038 } 14039 14040 @Override 14041 public int getIntentVerificationStatus(String packageName, int userId) { 14042 final int callingUid = Binder.getCallingUid(); 14043 if (UserHandle.getUserId(callingUid) != userId) { 14044 mContext.enforceCallingOrSelfPermission( 14045 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14046 "getIntentVerificationStatus" + userId); 14047 } 14048 if (getInstantAppPackageName(callingUid) != null) { 14049 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14050 } 14051 synchronized (mPackages) { 14052 final PackageSetting ps = mSettings.mPackages.get(packageName); 14053 if (ps == null 14054 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14055 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14056 } 14057 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14058 } 14059 } 14060 14061 @Override 14062 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14063 mContext.enforceCallingOrSelfPermission( 14064 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14065 14066 boolean result = false; 14067 synchronized (mPackages) { 14068 final PackageSetting ps = mSettings.mPackages.get(packageName); 14069 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14070 return false; 14071 } 14072 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14073 } 14074 if (result) { 14075 scheduleWritePackageRestrictionsLocked(userId); 14076 } 14077 return result; 14078 } 14079 14080 @Override 14081 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14082 String packageName) { 14083 final int callingUid = Binder.getCallingUid(); 14084 if (getInstantAppPackageName(callingUid) != null) { 14085 return ParceledListSlice.emptyList(); 14086 } 14087 synchronized (mPackages) { 14088 final PackageSetting ps = mSettings.mPackages.get(packageName); 14089 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14090 return ParceledListSlice.emptyList(); 14091 } 14092 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14093 } 14094 } 14095 14096 @Override 14097 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14098 if (TextUtils.isEmpty(packageName)) { 14099 return ParceledListSlice.emptyList(); 14100 } 14101 final int callingUid = Binder.getCallingUid(); 14102 final int callingUserId = UserHandle.getUserId(callingUid); 14103 synchronized (mPackages) { 14104 PackageParser.Package pkg = mPackages.get(packageName); 14105 if (pkg == null || pkg.activities == null) { 14106 return ParceledListSlice.emptyList(); 14107 } 14108 if (pkg.mExtras == null) { 14109 return ParceledListSlice.emptyList(); 14110 } 14111 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14112 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14113 return ParceledListSlice.emptyList(); 14114 } 14115 final int count = pkg.activities.size(); 14116 ArrayList<IntentFilter> result = new ArrayList<>(); 14117 for (int n=0; n<count; n++) { 14118 PackageParser.Activity activity = pkg.activities.get(n); 14119 if (activity.intents != null && activity.intents.size() > 0) { 14120 result.addAll(activity.intents); 14121 } 14122 } 14123 return new ParceledListSlice<>(result); 14124 } 14125 } 14126 14127 @Override 14128 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14129 mContext.enforceCallingOrSelfPermission( 14130 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14131 if (UserHandle.getCallingUserId() != userId) { 14132 mContext.enforceCallingOrSelfPermission( 14133 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14134 } 14135 14136 synchronized (mPackages) { 14137 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14138 if (packageName != null) { 14139 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14140 packageName, userId); 14141 } 14142 return result; 14143 } 14144 } 14145 14146 @Override 14147 public String getDefaultBrowserPackageName(int userId) { 14148 if (UserHandle.getCallingUserId() != userId) { 14149 mContext.enforceCallingOrSelfPermission( 14150 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14151 } 14152 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14153 return null; 14154 } 14155 synchronized (mPackages) { 14156 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14157 } 14158 } 14159 14160 /** 14161 * Get the "allow unknown sources" setting. 14162 * 14163 * @return the current "allow unknown sources" setting 14164 */ 14165 private int getUnknownSourcesSettings() { 14166 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14167 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14168 -1); 14169 } 14170 14171 @Override 14172 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14173 final int callingUid = Binder.getCallingUid(); 14174 if (getInstantAppPackageName(callingUid) != null) { 14175 return; 14176 } 14177 // writer 14178 synchronized (mPackages) { 14179 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14180 if (targetPackageSetting == null 14181 || filterAppAccessLPr( 14182 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14183 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14184 } 14185 14186 PackageSetting installerPackageSetting; 14187 if (installerPackageName != null) { 14188 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14189 if (installerPackageSetting == null) { 14190 throw new IllegalArgumentException("Unknown installer package: " 14191 + installerPackageName); 14192 } 14193 } else { 14194 installerPackageSetting = null; 14195 } 14196 14197 Signature[] callerSignature; 14198 Object obj = mSettings.getUserIdLPr(callingUid); 14199 if (obj != null) { 14200 if (obj instanceof SharedUserSetting) { 14201 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14202 } else if (obj instanceof PackageSetting) { 14203 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14204 } else { 14205 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14206 } 14207 } else { 14208 throw new SecurityException("Unknown calling UID: " + callingUid); 14209 } 14210 14211 // Verify: can't set installerPackageName to a package that is 14212 // not signed with the same cert as the caller. 14213 if (installerPackageSetting != null) { 14214 if (compareSignatures(callerSignature, 14215 installerPackageSetting.signatures.mSignatures) 14216 != PackageManager.SIGNATURE_MATCH) { 14217 throw new SecurityException( 14218 "Caller does not have same cert as new installer package " 14219 + installerPackageName); 14220 } 14221 } 14222 14223 // Verify: if target already has an installer package, it must 14224 // be signed with the same cert as the caller. 14225 if (targetPackageSetting.installerPackageName != null) { 14226 PackageSetting setting = mSettings.mPackages.get( 14227 targetPackageSetting.installerPackageName); 14228 // If the currently set package isn't valid, then it's always 14229 // okay to change it. 14230 if (setting != null) { 14231 if (compareSignatures(callerSignature, 14232 setting.signatures.mSignatures) 14233 != PackageManager.SIGNATURE_MATCH) { 14234 throw new SecurityException( 14235 "Caller does not have same cert as old installer package " 14236 + targetPackageSetting.installerPackageName); 14237 } 14238 } 14239 } 14240 14241 // Okay! 14242 targetPackageSetting.installerPackageName = installerPackageName; 14243 if (installerPackageName != null) { 14244 mSettings.mInstallerPackages.add(installerPackageName); 14245 } 14246 scheduleWriteSettingsLocked(); 14247 } 14248 } 14249 14250 @Override 14251 public void setApplicationCategoryHint(String packageName, int categoryHint, 14252 String callerPackageName) { 14253 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14254 throw new SecurityException("Instant applications don't have access to this method"); 14255 } 14256 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14257 callerPackageName); 14258 synchronized (mPackages) { 14259 PackageSetting ps = mSettings.mPackages.get(packageName); 14260 if (ps == null) { 14261 throw new IllegalArgumentException("Unknown target package " + packageName); 14262 } 14263 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14264 throw new IllegalArgumentException("Unknown target package " + packageName); 14265 } 14266 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14267 throw new IllegalArgumentException("Calling package " + callerPackageName 14268 + " is not installer for " + packageName); 14269 } 14270 14271 if (ps.categoryHint != categoryHint) { 14272 ps.categoryHint = categoryHint; 14273 scheduleWriteSettingsLocked(); 14274 } 14275 } 14276 } 14277 14278 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14279 // Queue up an async operation since the package installation may take a little while. 14280 mHandler.post(new Runnable() { 14281 public void run() { 14282 mHandler.removeCallbacks(this); 14283 // Result object to be returned 14284 PackageInstalledInfo res = new PackageInstalledInfo(); 14285 res.setReturnCode(currentStatus); 14286 res.uid = -1; 14287 res.pkg = null; 14288 res.removedInfo = null; 14289 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14290 args.doPreInstall(res.returnCode); 14291 synchronized (mInstallLock) { 14292 installPackageTracedLI(args, res); 14293 } 14294 args.doPostInstall(res.returnCode, res.uid); 14295 } 14296 14297 // A restore should be performed at this point if (a) the install 14298 // succeeded, (b) the operation is not an update, and (c) the new 14299 // package has not opted out of backup participation. 14300 final boolean update = res.removedInfo != null 14301 && res.removedInfo.removedPackage != null; 14302 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14303 boolean doRestore = !update 14304 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14305 14306 // Set up the post-install work request bookkeeping. This will be used 14307 // and cleaned up by the post-install event handling regardless of whether 14308 // there's a restore pass performed. Token values are >= 1. 14309 int token; 14310 if (mNextInstallToken < 0) mNextInstallToken = 1; 14311 token = mNextInstallToken++; 14312 14313 PostInstallData data = new PostInstallData(args, res); 14314 mRunningInstalls.put(token, data); 14315 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14316 14317 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14318 // Pass responsibility to the Backup Manager. It will perform a 14319 // restore if appropriate, then pass responsibility back to the 14320 // Package Manager to run the post-install observer callbacks 14321 // and broadcasts. 14322 IBackupManager bm = IBackupManager.Stub.asInterface( 14323 ServiceManager.getService(Context.BACKUP_SERVICE)); 14324 if (bm != null) { 14325 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14326 + " to BM for possible restore"); 14327 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14328 try { 14329 // TODO: http://b/22388012 14330 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14331 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14332 } else { 14333 doRestore = false; 14334 } 14335 } catch (RemoteException e) { 14336 // can't happen; the backup manager is local 14337 } catch (Exception e) { 14338 Slog.e(TAG, "Exception trying to enqueue restore", e); 14339 doRestore = false; 14340 } 14341 } else { 14342 Slog.e(TAG, "Backup Manager not found!"); 14343 doRestore = false; 14344 } 14345 } 14346 14347 if (!doRestore) { 14348 // No restore possible, or the Backup Manager was mysteriously not 14349 // available -- just fire the post-install work request directly. 14350 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14351 14352 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14353 14354 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14355 mHandler.sendMessage(msg); 14356 } 14357 } 14358 }); 14359 } 14360 14361 /** 14362 * Callback from PackageSettings whenever an app is first transitioned out of the 14363 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14364 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14365 * here whether the app is the target of an ongoing install, and only send the 14366 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14367 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14368 * handling. 14369 */ 14370 void notifyFirstLaunch(final String packageName, final String installerPackage, 14371 final int userId) { 14372 // Serialize this with the rest of the install-process message chain. In the 14373 // restore-at-install case, this Runnable will necessarily run before the 14374 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14375 // are coherent. In the non-restore case, the app has already completed install 14376 // and been launched through some other means, so it is not in a problematic 14377 // state for observers to see the FIRST_LAUNCH signal. 14378 mHandler.post(new Runnable() { 14379 @Override 14380 public void run() { 14381 for (int i = 0; i < mRunningInstalls.size(); i++) { 14382 final PostInstallData data = mRunningInstalls.valueAt(i); 14383 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14384 continue; 14385 } 14386 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14387 // right package; but is it for the right user? 14388 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14389 if (userId == data.res.newUsers[uIndex]) { 14390 if (DEBUG_BACKUP) { 14391 Slog.i(TAG, "Package " + packageName 14392 + " being restored so deferring FIRST_LAUNCH"); 14393 } 14394 return; 14395 } 14396 } 14397 } 14398 } 14399 // didn't find it, so not being restored 14400 if (DEBUG_BACKUP) { 14401 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14402 } 14403 final boolean isInstantApp = isInstantApp(packageName, userId); 14404 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14405 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14406 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14407 } 14408 }); 14409 } 14410 14411 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14412 int[] userIds, int[] instantUserIds) { 14413 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14414 installerPkg, null, userIds, instantUserIds); 14415 } 14416 14417 private abstract class HandlerParams { 14418 private static final int MAX_RETRIES = 4; 14419 14420 /** 14421 * Number of times startCopy() has been attempted and had a non-fatal 14422 * error. 14423 */ 14424 private int mRetries = 0; 14425 14426 /** User handle for the user requesting the information or installation. */ 14427 private final UserHandle mUser; 14428 String traceMethod; 14429 int traceCookie; 14430 14431 HandlerParams(UserHandle user) { 14432 mUser = user; 14433 } 14434 14435 UserHandle getUser() { 14436 return mUser; 14437 } 14438 14439 HandlerParams setTraceMethod(String traceMethod) { 14440 this.traceMethod = traceMethod; 14441 return this; 14442 } 14443 14444 HandlerParams setTraceCookie(int traceCookie) { 14445 this.traceCookie = traceCookie; 14446 return this; 14447 } 14448 14449 final boolean startCopy() { 14450 boolean res; 14451 try { 14452 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14453 14454 if (++mRetries > MAX_RETRIES) { 14455 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14456 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14457 handleServiceError(); 14458 return false; 14459 } else { 14460 handleStartCopy(); 14461 res = true; 14462 } 14463 } catch (RemoteException e) { 14464 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14465 mHandler.sendEmptyMessage(MCS_RECONNECT); 14466 res = false; 14467 } 14468 handleReturnCode(); 14469 return res; 14470 } 14471 14472 final void serviceError() { 14473 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14474 handleServiceError(); 14475 handleReturnCode(); 14476 } 14477 14478 abstract void handleStartCopy() throws RemoteException; 14479 abstract void handleServiceError(); 14480 abstract void handleReturnCode(); 14481 } 14482 14483 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14484 for (File path : paths) { 14485 try { 14486 mcs.clearDirectory(path.getAbsolutePath()); 14487 } catch (RemoteException e) { 14488 } 14489 } 14490 } 14491 14492 static class OriginInfo { 14493 /** 14494 * Location where install is coming from, before it has been 14495 * copied/renamed into place. This could be a single monolithic APK 14496 * file, or a cluster directory. This location may be untrusted. 14497 */ 14498 final File file; 14499 14500 /** 14501 * Flag indicating that {@link #file} or {@link #cid} has already been 14502 * staged, meaning downstream users don't need to defensively copy the 14503 * contents. 14504 */ 14505 final boolean staged; 14506 14507 /** 14508 * Flag indicating that {@link #file} or {@link #cid} is an already 14509 * installed app that is being moved. 14510 */ 14511 final boolean existing; 14512 14513 final String resolvedPath; 14514 final File resolvedFile; 14515 14516 static OriginInfo fromNothing() { 14517 return new OriginInfo(null, false, false); 14518 } 14519 14520 static OriginInfo fromUntrustedFile(File file) { 14521 return new OriginInfo(file, false, false); 14522 } 14523 14524 static OriginInfo fromExistingFile(File file) { 14525 return new OriginInfo(file, false, true); 14526 } 14527 14528 static OriginInfo fromStagedFile(File file) { 14529 return new OriginInfo(file, true, false); 14530 } 14531 14532 private OriginInfo(File file, boolean staged, boolean existing) { 14533 this.file = file; 14534 this.staged = staged; 14535 this.existing = existing; 14536 14537 if (file != null) { 14538 resolvedPath = file.getAbsolutePath(); 14539 resolvedFile = file; 14540 } else { 14541 resolvedPath = null; 14542 resolvedFile = null; 14543 } 14544 } 14545 } 14546 14547 static class MoveInfo { 14548 final int moveId; 14549 final String fromUuid; 14550 final String toUuid; 14551 final String packageName; 14552 final String dataAppName; 14553 final int appId; 14554 final String seinfo; 14555 final int targetSdkVersion; 14556 14557 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14558 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14559 this.moveId = moveId; 14560 this.fromUuid = fromUuid; 14561 this.toUuid = toUuid; 14562 this.packageName = packageName; 14563 this.dataAppName = dataAppName; 14564 this.appId = appId; 14565 this.seinfo = seinfo; 14566 this.targetSdkVersion = targetSdkVersion; 14567 } 14568 } 14569 14570 static class VerificationInfo { 14571 /** A constant used to indicate that a uid value is not present. */ 14572 public static final int NO_UID = -1; 14573 14574 /** URI referencing where the package was downloaded from. */ 14575 final Uri originatingUri; 14576 14577 /** HTTP referrer URI associated with the originatingURI. */ 14578 final Uri referrer; 14579 14580 /** UID of the application that the install request originated from. */ 14581 final int originatingUid; 14582 14583 /** UID of application requesting the install */ 14584 final int installerUid; 14585 14586 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14587 this.originatingUri = originatingUri; 14588 this.referrer = referrer; 14589 this.originatingUid = originatingUid; 14590 this.installerUid = installerUid; 14591 } 14592 } 14593 14594 class InstallParams extends HandlerParams { 14595 final OriginInfo origin; 14596 final MoveInfo move; 14597 final IPackageInstallObserver2 observer; 14598 int installFlags; 14599 final String installerPackageName; 14600 final String volumeUuid; 14601 private InstallArgs mArgs; 14602 private int mRet; 14603 final String packageAbiOverride; 14604 final String[] grantedRuntimePermissions; 14605 final VerificationInfo verificationInfo; 14606 final PackageParser.SigningDetails signingDetails; 14607 final int installReason; 14608 14609 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14610 int installFlags, String installerPackageName, String volumeUuid, 14611 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14612 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14613 super(user); 14614 this.origin = origin; 14615 this.move = move; 14616 this.observer = observer; 14617 this.installFlags = installFlags; 14618 this.installerPackageName = installerPackageName; 14619 this.volumeUuid = volumeUuid; 14620 this.verificationInfo = verificationInfo; 14621 this.packageAbiOverride = packageAbiOverride; 14622 this.grantedRuntimePermissions = grantedPermissions; 14623 this.signingDetails = signingDetails; 14624 this.installReason = installReason; 14625 } 14626 14627 @Override 14628 public String toString() { 14629 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14630 + " file=" + origin.file + "}"; 14631 } 14632 14633 private int installLocationPolicy(PackageInfoLite pkgLite) { 14634 String packageName = pkgLite.packageName; 14635 int installLocation = pkgLite.installLocation; 14636 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14637 // reader 14638 synchronized (mPackages) { 14639 // Currently installed package which the new package is attempting to replace or 14640 // null if no such package is installed. 14641 PackageParser.Package installedPkg = mPackages.get(packageName); 14642 // Package which currently owns the data which the new package will own if installed. 14643 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14644 // will be null whereas dataOwnerPkg will contain information about the package 14645 // which was uninstalled while keeping its data. 14646 PackageParser.Package dataOwnerPkg = installedPkg; 14647 if (dataOwnerPkg == null) { 14648 PackageSetting ps = mSettings.mPackages.get(packageName); 14649 if (ps != null) { 14650 dataOwnerPkg = ps.pkg; 14651 } 14652 } 14653 14654 if (dataOwnerPkg != null) { 14655 // If installed, the package will get access to data left on the device by its 14656 // predecessor. As a security measure, this is permited only if this is not a 14657 // version downgrade or if the predecessor package is marked as debuggable and 14658 // a downgrade is explicitly requested. 14659 // 14660 // On debuggable platform builds, downgrades are permitted even for 14661 // non-debuggable packages to make testing easier. Debuggable platform builds do 14662 // not offer security guarantees and thus it's OK to disable some security 14663 // mechanisms to make debugging/testing easier on those builds. However, even on 14664 // debuggable builds downgrades of packages are permitted only if requested via 14665 // installFlags. This is because we aim to keep the behavior of debuggable 14666 // platform builds as close as possible to the behavior of non-debuggable 14667 // platform builds. 14668 final boolean downgradeRequested = 14669 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14670 final boolean packageDebuggable = 14671 (dataOwnerPkg.applicationInfo.flags 14672 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14673 final boolean downgradePermitted = 14674 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14675 if (!downgradePermitted) { 14676 try { 14677 checkDowngrade(dataOwnerPkg, pkgLite); 14678 } catch (PackageManagerException e) { 14679 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14680 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14681 } 14682 } 14683 } 14684 14685 if (installedPkg != null) { 14686 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14687 // Check for updated system application. 14688 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14689 if (onSd) { 14690 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14691 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14692 } 14693 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14694 } else { 14695 if (onSd) { 14696 // Install flag overrides everything. 14697 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14698 } 14699 // If current upgrade specifies particular preference 14700 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14701 // Application explicitly specified internal. 14702 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14703 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14704 // App explictly prefers external. Let policy decide 14705 } else { 14706 // Prefer previous location 14707 if (isExternal(installedPkg)) { 14708 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14709 } 14710 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14711 } 14712 } 14713 } else { 14714 // Invalid install. Return error code 14715 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14716 } 14717 } 14718 } 14719 // All the special cases have been taken care of. 14720 // Return result based on recommended install location. 14721 if (onSd) { 14722 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14723 } 14724 return pkgLite.recommendedInstallLocation; 14725 } 14726 14727 /* 14728 * Invoke remote method to get package information and install 14729 * location values. Override install location based on default 14730 * policy if needed and then create install arguments based 14731 * on the install location. 14732 */ 14733 public void handleStartCopy() throws RemoteException { 14734 int ret = PackageManager.INSTALL_SUCCEEDED; 14735 14736 // If we're already staged, we've firmly committed to an install location 14737 if (origin.staged) { 14738 if (origin.file != null) { 14739 installFlags |= PackageManager.INSTALL_INTERNAL; 14740 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14741 } else { 14742 throw new IllegalStateException("Invalid stage location"); 14743 } 14744 } 14745 14746 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14747 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14748 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14749 PackageInfoLite pkgLite = null; 14750 14751 if (onInt && onSd) { 14752 // Check if both bits are set. 14753 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14754 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14755 } else if (onSd && ephemeral) { 14756 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14757 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14758 } else { 14759 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14760 packageAbiOverride); 14761 14762 if (DEBUG_EPHEMERAL && ephemeral) { 14763 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14764 } 14765 14766 /* 14767 * If we have too little free space, try to free cache 14768 * before giving up. 14769 */ 14770 if (!origin.staged && pkgLite.recommendedInstallLocation 14771 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14772 // TODO: focus freeing disk space on the target device 14773 final StorageManager storage = StorageManager.from(mContext); 14774 final long lowThreshold = storage.getStorageLowBytes( 14775 Environment.getDataDirectory()); 14776 14777 final long sizeBytes = mContainerService.calculateInstalledSize( 14778 origin.resolvedPath, packageAbiOverride); 14779 14780 try { 14781 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14782 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14783 installFlags, packageAbiOverride); 14784 } catch (InstallerException e) { 14785 Slog.w(TAG, "Failed to free cache", e); 14786 } 14787 14788 /* 14789 * The cache free must have deleted the file we 14790 * downloaded to install. 14791 * 14792 * TODO: fix the "freeCache" call to not delete 14793 * the file we care about. 14794 */ 14795 if (pkgLite.recommendedInstallLocation 14796 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14797 pkgLite.recommendedInstallLocation 14798 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14799 } 14800 } 14801 } 14802 14803 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14804 int loc = pkgLite.recommendedInstallLocation; 14805 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14806 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14807 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14808 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14809 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14810 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14811 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14812 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14813 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14814 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14815 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14816 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14817 } else { 14818 // Override with defaults if needed. 14819 loc = installLocationPolicy(pkgLite); 14820 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14821 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14822 } else if (!onSd && !onInt) { 14823 // Override install location with flags 14824 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14825 // Set the flag to install on external media. 14826 installFlags |= PackageManager.INSTALL_EXTERNAL; 14827 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14828 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14829 if (DEBUG_EPHEMERAL) { 14830 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14831 } 14832 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14833 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14834 |PackageManager.INSTALL_INTERNAL); 14835 } else { 14836 // Make sure the flag for installing on external 14837 // media is unset 14838 installFlags |= PackageManager.INSTALL_INTERNAL; 14839 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14840 } 14841 } 14842 } 14843 } 14844 14845 final InstallArgs args = createInstallArgs(this); 14846 mArgs = args; 14847 14848 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14849 // TODO: http://b/22976637 14850 // Apps installed for "all" users use the device owner to verify the app 14851 UserHandle verifierUser = getUser(); 14852 if (verifierUser == UserHandle.ALL) { 14853 verifierUser = UserHandle.SYSTEM; 14854 } 14855 14856 /* 14857 * Determine if we have any installed package verifiers. If we 14858 * do, then we'll defer to them to verify the packages. 14859 */ 14860 final int requiredUid = mRequiredVerifierPackage == null ? -1 14861 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14862 verifierUser.getIdentifier()); 14863 final int installerUid = 14864 verificationInfo == null ? -1 : verificationInfo.installerUid; 14865 if (!origin.existing && requiredUid != -1 14866 && isVerificationEnabled( 14867 verifierUser.getIdentifier(), installFlags, installerUid)) { 14868 final Intent verification = new Intent( 14869 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14870 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14871 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14872 PACKAGE_MIME_TYPE); 14873 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14874 14875 // Query all live verifiers based on current user state 14876 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14877 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14878 false /*allowDynamicSplits*/); 14879 14880 if (DEBUG_VERIFY) { 14881 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14882 + verification.toString() + " with " + pkgLite.verifiers.length 14883 + " optional verifiers"); 14884 } 14885 14886 final int verificationId = mPendingVerificationToken++; 14887 14888 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14889 14890 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14891 installerPackageName); 14892 14893 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14894 installFlags); 14895 14896 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14897 pkgLite.packageName); 14898 14899 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14900 pkgLite.versionCode); 14901 14902 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 14903 pkgLite.getLongVersionCode()); 14904 14905 if (verificationInfo != null) { 14906 if (verificationInfo.originatingUri != null) { 14907 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14908 verificationInfo.originatingUri); 14909 } 14910 if (verificationInfo.referrer != null) { 14911 verification.putExtra(Intent.EXTRA_REFERRER, 14912 verificationInfo.referrer); 14913 } 14914 if (verificationInfo.originatingUid >= 0) { 14915 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14916 verificationInfo.originatingUid); 14917 } 14918 if (verificationInfo.installerUid >= 0) { 14919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14920 verificationInfo.installerUid); 14921 } 14922 } 14923 14924 final PackageVerificationState verificationState = new PackageVerificationState( 14925 requiredUid, args); 14926 14927 mPendingVerification.append(verificationId, verificationState); 14928 14929 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14930 receivers, verificationState); 14931 14932 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14933 final long idleDuration = getVerificationTimeout(); 14934 14935 /* 14936 * If any sufficient verifiers were listed in the package 14937 * manifest, attempt to ask them. 14938 */ 14939 if (sufficientVerifiers != null) { 14940 final int N = sufficientVerifiers.size(); 14941 if (N == 0) { 14942 Slog.i(TAG, "Additional verifiers required, but none installed."); 14943 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14944 } else { 14945 for (int i = 0; i < N; i++) { 14946 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14947 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14948 verifierComponent.getPackageName(), idleDuration, 14949 verifierUser.getIdentifier(), false, "package verifier"); 14950 14951 final Intent sufficientIntent = new Intent(verification); 14952 sufficientIntent.setComponent(verifierComponent); 14953 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14954 } 14955 } 14956 } 14957 14958 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14959 mRequiredVerifierPackage, receivers); 14960 if (ret == PackageManager.INSTALL_SUCCEEDED 14961 && mRequiredVerifierPackage != null) { 14962 Trace.asyncTraceBegin( 14963 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14964 /* 14965 * Send the intent to the required verification agent, 14966 * but only start the verification timeout after the 14967 * target BroadcastReceivers have run. 14968 */ 14969 verification.setComponent(requiredVerifierComponent); 14970 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14971 mRequiredVerifierPackage, idleDuration, 14972 verifierUser.getIdentifier(), false, "package verifier"); 14973 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14974 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14975 new BroadcastReceiver() { 14976 @Override 14977 public void onReceive(Context context, Intent intent) { 14978 final Message msg = mHandler 14979 .obtainMessage(CHECK_PENDING_VERIFICATION); 14980 msg.arg1 = verificationId; 14981 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14982 } 14983 }, null, 0, null, null); 14984 14985 /* 14986 * We don't want the copy to proceed until verification 14987 * succeeds, so null out this field. 14988 */ 14989 mArgs = null; 14990 } 14991 } else { 14992 /* 14993 * No package verification is enabled, so immediately start 14994 * the remote call to initiate copy using temporary file. 14995 */ 14996 ret = args.copyApk(mContainerService, true); 14997 } 14998 } 14999 15000 mRet = ret; 15001 } 15002 15003 @Override 15004 void handleReturnCode() { 15005 // If mArgs is null, then MCS couldn't be reached. When it 15006 // reconnects, it will try again to install. At that point, this 15007 // will succeed. 15008 if (mArgs != null) { 15009 processPendingInstall(mArgs, mRet); 15010 } 15011 } 15012 15013 @Override 15014 void handleServiceError() { 15015 mArgs = createInstallArgs(this); 15016 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15017 } 15018 } 15019 15020 private InstallArgs createInstallArgs(InstallParams params) { 15021 if (params.move != null) { 15022 return new MoveInstallArgs(params); 15023 } else { 15024 return new FileInstallArgs(params); 15025 } 15026 } 15027 15028 /** 15029 * Create args that describe an existing installed package. Typically used 15030 * when cleaning up old installs, or used as a move source. 15031 */ 15032 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15033 String resourcePath, String[] instructionSets) { 15034 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15035 } 15036 15037 static abstract class InstallArgs { 15038 /** @see InstallParams#origin */ 15039 final OriginInfo origin; 15040 /** @see InstallParams#move */ 15041 final MoveInfo move; 15042 15043 final IPackageInstallObserver2 observer; 15044 // Always refers to PackageManager flags only 15045 final int installFlags; 15046 final String installerPackageName; 15047 final String volumeUuid; 15048 final UserHandle user; 15049 final String abiOverride; 15050 final String[] installGrantPermissions; 15051 /** If non-null, drop an async trace when the install completes */ 15052 final String traceMethod; 15053 final int traceCookie; 15054 final PackageParser.SigningDetails signingDetails; 15055 final int installReason; 15056 15057 // The list of instruction sets supported by this app. This is currently 15058 // only used during the rmdex() phase to clean up resources. We can get rid of this 15059 // if we move dex files under the common app path. 15060 /* nullable */ String[] instructionSets; 15061 15062 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15063 int installFlags, String installerPackageName, String volumeUuid, 15064 UserHandle user, String[] instructionSets, 15065 String abiOverride, String[] installGrantPermissions, 15066 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15067 int installReason) { 15068 this.origin = origin; 15069 this.move = move; 15070 this.installFlags = installFlags; 15071 this.observer = observer; 15072 this.installerPackageName = installerPackageName; 15073 this.volumeUuid = volumeUuid; 15074 this.user = user; 15075 this.instructionSets = instructionSets; 15076 this.abiOverride = abiOverride; 15077 this.installGrantPermissions = installGrantPermissions; 15078 this.traceMethod = traceMethod; 15079 this.traceCookie = traceCookie; 15080 this.signingDetails = signingDetails; 15081 this.installReason = installReason; 15082 } 15083 15084 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15085 abstract int doPreInstall(int status); 15086 15087 /** 15088 * Rename package into final resting place. All paths on the given 15089 * scanned package should be updated to reflect the rename. 15090 */ 15091 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15092 abstract int doPostInstall(int status, int uid); 15093 15094 /** @see PackageSettingBase#codePathString */ 15095 abstract String getCodePath(); 15096 /** @see PackageSettingBase#resourcePathString */ 15097 abstract String getResourcePath(); 15098 15099 // Need installer lock especially for dex file removal. 15100 abstract void cleanUpResourcesLI(); 15101 abstract boolean doPostDeleteLI(boolean delete); 15102 15103 /** 15104 * Called before the source arguments are copied. This is used mostly 15105 * for MoveParams when it needs to read the source file to put it in the 15106 * destination. 15107 */ 15108 int doPreCopy() { 15109 return PackageManager.INSTALL_SUCCEEDED; 15110 } 15111 15112 /** 15113 * Called after the source arguments are copied. This is used mostly for 15114 * MoveParams when it needs to read the source file to put it in the 15115 * destination. 15116 */ 15117 int doPostCopy(int uid) { 15118 return PackageManager.INSTALL_SUCCEEDED; 15119 } 15120 15121 protected boolean isFwdLocked() { 15122 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15123 } 15124 15125 protected boolean isExternalAsec() { 15126 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15127 } 15128 15129 protected boolean isEphemeral() { 15130 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15131 } 15132 15133 UserHandle getUser() { 15134 return user; 15135 } 15136 } 15137 15138 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15139 if (!allCodePaths.isEmpty()) { 15140 if (instructionSets == null) { 15141 throw new IllegalStateException("instructionSet == null"); 15142 } 15143 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15144 for (String codePath : allCodePaths) { 15145 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15146 try { 15147 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15148 } catch (InstallerException ignored) { 15149 } 15150 } 15151 } 15152 } 15153 } 15154 15155 /** 15156 * Logic to handle installation of non-ASEC applications, including copying 15157 * and renaming logic. 15158 */ 15159 class FileInstallArgs extends InstallArgs { 15160 private File codeFile; 15161 private File resourceFile; 15162 15163 // Example topology: 15164 // /data/app/com.example/base.apk 15165 // /data/app/com.example/split_foo.apk 15166 // /data/app/com.example/lib/arm/libfoo.so 15167 // /data/app/com.example/lib/arm64/libfoo.so 15168 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15169 15170 /** New install */ 15171 FileInstallArgs(InstallParams params) { 15172 super(params.origin, params.move, params.observer, params.installFlags, 15173 params.installerPackageName, params.volumeUuid, 15174 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15175 params.grantedRuntimePermissions, 15176 params.traceMethod, params.traceCookie, params.signingDetails, 15177 params.installReason); 15178 if (isFwdLocked()) { 15179 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15180 } 15181 } 15182 15183 /** Existing install */ 15184 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15185 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15186 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15187 PackageManager.INSTALL_REASON_UNKNOWN); 15188 this.codeFile = (codePath != null) ? new File(codePath) : null; 15189 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15190 } 15191 15192 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15193 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15194 try { 15195 return doCopyApk(imcs, temp); 15196 } finally { 15197 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15198 } 15199 } 15200 15201 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15202 if (origin.staged) { 15203 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15204 codeFile = origin.file; 15205 resourceFile = origin.file; 15206 return PackageManager.INSTALL_SUCCEEDED; 15207 } 15208 15209 try { 15210 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15211 final File tempDir = 15212 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15213 codeFile = tempDir; 15214 resourceFile = tempDir; 15215 } catch (IOException e) { 15216 Slog.w(TAG, "Failed to create copy file: " + e); 15217 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15218 } 15219 15220 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15221 @Override 15222 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15223 if (!FileUtils.isValidExtFilename(name)) { 15224 throw new IllegalArgumentException("Invalid filename: " + name); 15225 } 15226 try { 15227 final File file = new File(codeFile, name); 15228 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15229 O_RDWR | O_CREAT, 0644); 15230 Os.chmod(file.getAbsolutePath(), 0644); 15231 return new ParcelFileDescriptor(fd); 15232 } catch (ErrnoException e) { 15233 throw new RemoteException("Failed to open: " + e.getMessage()); 15234 } 15235 } 15236 }; 15237 15238 int ret = PackageManager.INSTALL_SUCCEEDED; 15239 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15240 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15241 Slog.e(TAG, "Failed to copy package"); 15242 return ret; 15243 } 15244 15245 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15246 NativeLibraryHelper.Handle handle = null; 15247 try { 15248 handle = NativeLibraryHelper.Handle.create(codeFile); 15249 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15250 abiOverride); 15251 } catch (IOException e) { 15252 Slog.e(TAG, "Copying native libraries failed", e); 15253 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15254 } finally { 15255 IoUtils.closeQuietly(handle); 15256 } 15257 15258 return ret; 15259 } 15260 15261 int doPreInstall(int status) { 15262 if (status != PackageManager.INSTALL_SUCCEEDED) { 15263 cleanUp(); 15264 } 15265 return status; 15266 } 15267 15268 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15269 if (status != PackageManager.INSTALL_SUCCEEDED) { 15270 cleanUp(); 15271 return false; 15272 } 15273 15274 final File targetDir = codeFile.getParentFile(); 15275 final File beforeCodeFile = codeFile; 15276 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15277 15278 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15279 try { 15280 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15281 } catch (ErrnoException e) { 15282 Slog.w(TAG, "Failed to rename", e); 15283 return false; 15284 } 15285 15286 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15287 Slog.w(TAG, "Failed to restorecon"); 15288 return false; 15289 } 15290 15291 // Reflect the rename internally 15292 codeFile = afterCodeFile; 15293 resourceFile = afterCodeFile; 15294 15295 // Reflect the rename in scanned details 15296 try { 15297 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15298 } catch (IOException e) { 15299 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15300 return false; 15301 } 15302 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15303 afterCodeFile, pkg.baseCodePath)); 15304 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15305 afterCodeFile, pkg.splitCodePaths)); 15306 15307 // Reflect the rename in app info 15308 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15309 pkg.setApplicationInfoCodePath(pkg.codePath); 15310 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15311 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15312 pkg.setApplicationInfoResourcePath(pkg.codePath); 15313 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15314 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15315 15316 return true; 15317 } 15318 15319 int doPostInstall(int status, int uid) { 15320 if (status != PackageManager.INSTALL_SUCCEEDED) { 15321 cleanUp(); 15322 } 15323 return status; 15324 } 15325 15326 @Override 15327 String getCodePath() { 15328 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15329 } 15330 15331 @Override 15332 String getResourcePath() { 15333 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15334 } 15335 15336 private boolean cleanUp() { 15337 if (codeFile == null || !codeFile.exists()) { 15338 return false; 15339 } 15340 15341 removeCodePathLI(codeFile); 15342 15343 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15344 resourceFile.delete(); 15345 } 15346 15347 return true; 15348 } 15349 15350 void cleanUpResourcesLI() { 15351 // Try enumerating all code paths before deleting 15352 List<String> allCodePaths = Collections.EMPTY_LIST; 15353 if (codeFile != null && codeFile.exists()) { 15354 try { 15355 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15356 allCodePaths = pkg.getAllCodePaths(); 15357 } catch (PackageParserException e) { 15358 // Ignored; we tried our best 15359 } 15360 } 15361 15362 cleanUp(); 15363 removeDexFiles(allCodePaths, instructionSets); 15364 } 15365 15366 boolean doPostDeleteLI(boolean delete) { 15367 // XXX err, shouldn't we respect the delete flag? 15368 cleanUpResourcesLI(); 15369 return true; 15370 } 15371 } 15372 15373 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15374 PackageManagerException { 15375 if (copyRet < 0) { 15376 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15377 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15378 throw new PackageManagerException(copyRet, message); 15379 } 15380 } 15381 } 15382 15383 /** 15384 * Extract the StorageManagerService "container ID" from the full code path of an 15385 * .apk. 15386 */ 15387 static String cidFromCodePath(String fullCodePath) { 15388 int eidx = fullCodePath.lastIndexOf("/"); 15389 String subStr1 = fullCodePath.substring(0, eidx); 15390 int sidx = subStr1.lastIndexOf("/"); 15391 return subStr1.substring(sidx+1, eidx); 15392 } 15393 15394 /** 15395 * Logic to handle movement of existing installed applications. 15396 */ 15397 class MoveInstallArgs extends InstallArgs { 15398 private File codeFile; 15399 private File resourceFile; 15400 15401 /** New install */ 15402 MoveInstallArgs(InstallParams params) { 15403 super(params.origin, params.move, params.observer, params.installFlags, 15404 params.installerPackageName, params.volumeUuid, 15405 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15406 params.grantedRuntimePermissions, 15407 params.traceMethod, params.traceCookie, params.signingDetails, 15408 params.installReason); 15409 } 15410 15411 int copyApk(IMediaContainerService imcs, boolean temp) { 15412 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15413 + move.fromUuid + " to " + move.toUuid); 15414 synchronized (mInstaller) { 15415 try { 15416 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15417 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15418 } catch (InstallerException e) { 15419 Slog.w(TAG, "Failed to move app", e); 15420 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15421 } 15422 } 15423 15424 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15425 resourceFile = codeFile; 15426 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15427 15428 return PackageManager.INSTALL_SUCCEEDED; 15429 } 15430 15431 int doPreInstall(int status) { 15432 if (status != PackageManager.INSTALL_SUCCEEDED) { 15433 cleanUp(move.toUuid); 15434 } 15435 return status; 15436 } 15437 15438 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15439 if (status != PackageManager.INSTALL_SUCCEEDED) { 15440 cleanUp(move.toUuid); 15441 return false; 15442 } 15443 15444 // Reflect the move in app info 15445 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15446 pkg.setApplicationInfoCodePath(pkg.codePath); 15447 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15448 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15449 pkg.setApplicationInfoResourcePath(pkg.codePath); 15450 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15451 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15452 15453 return true; 15454 } 15455 15456 int doPostInstall(int status, int uid) { 15457 if (status == PackageManager.INSTALL_SUCCEEDED) { 15458 cleanUp(move.fromUuid); 15459 } else { 15460 cleanUp(move.toUuid); 15461 } 15462 return status; 15463 } 15464 15465 @Override 15466 String getCodePath() { 15467 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15468 } 15469 15470 @Override 15471 String getResourcePath() { 15472 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15473 } 15474 15475 private boolean cleanUp(String volumeUuid) { 15476 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15477 move.dataAppName); 15478 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15479 final int[] userIds = sUserManager.getUserIds(); 15480 synchronized (mInstallLock) { 15481 // Clean up both app data and code 15482 // All package moves are frozen until finished 15483 for (int userId : userIds) { 15484 try { 15485 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15486 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15487 } catch (InstallerException e) { 15488 Slog.w(TAG, String.valueOf(e)); 15489 } 15490 } 15491 removeCodePathLI(codeFile); 15492 } 15493 return true; 15494 } 15495 15496 void cleanUpResourcesLI() { 15497 throw new UnsupportedOperationException(); 15498 } 15499 15500 boolean doPostDeleteLI(boolean delete) { 15501 throw new UnsupportedOperationException(); 15502 } 15503 } 15504 15505 static String getAsecPackageName(String packageCid) { 15506 int idx = packageCid.lastIndexOf("-"); 15507 if (idx == -1) { 15508 return packageCid; 15509 } 15510 return packageCid.substring(0, idx); 15511 } 15512 15513 // Utility method used to create code paths based on package name and available index. 15514 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15515 String idxStr = ""; 15516 int idx = 1; 15517 // Fall back to default value of idx=1 if prefix is not 15518 // part of oldCodePath 15519 if (oldCodePath != null) { 15520 String subStr = oldCodePath; 15521 // Drop the suffix right away 15522 if (suffix != null && subStr.endsWith(suffix)) { 15523 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15524 } 15525 // If oldCodePath already contains prefix find out the 15526 // ending index to either increment or decrement. 15527 int sidx = subStr.lastIndexOf(prefix); 15528 if (sidx != -1) { 15529 subStr = subStr.substring(sidx + prefix.length()); 15530 if (subStr != null) { 15531 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15532 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15533 } 15534 try { 15535 idx = Integer.parseInt(subStr); 15536 if (idx <= 1) { 15537 idx++; 15538 } else { 15539 idx--; 15540 } 15541 } catch(NumberFormatException e) { 15542 } 15543 } 15544 } 15545 } 15546 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15547 return prefix + idxStr; 15548 } 15549 15550 private File getNextCodePath(File targetDir, String packageName) { 15551 File result; 15552 SecureRandom random = new SecureRandom(); 15553 byte[] bytes = new byte[16]; 15554 do { 15555 random.nextBytes(bytes); 15556 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15557 result = new File(targetDir, packageName + "-" + suffix); 15558 } while (result.exists()); 15559 return result; 15560 } 15561 15562 // Utility method that returns the relative package path with respect 15563 // to the installation directory. Like say for /data/data/com.test-1.apk 15564 // string com.test-1 is returned. 15565 static String deriveCodePathName(String codePath) { 15566 if (codePath == null) { 15567 return null; 15568 } 15569 final File codeFile = new File(codePath); 15570 final String name = codeFile.getName(); 15571 if (codeFile.isDirectory()) { 15572 return name; 15573 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15574 final int lastDot = name.lastIndexOf('.'); 15575 return name.substring(0, lastDot); 15576 } else { 15577 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15578 return null; 15579 } 15580 } 15581 15582 static class PackageInstalledInfo { 15583 String name; 15584 int uid; 15585 // The set of users that originally had this package installed. 15586 int[] origUsers; 15587 // The set of users that now have this package installed. 15588 int[] newUsers; 15589 PackageParser.Package pkg; 15590 int returnCode; 15591 String returnMsg; 15592 String installerPackageName; 15593 PackageRemovedInfo removedInfo; 15594 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15595 15596 public void setError(int code, String msg) { 15597 setReturnCode(code); 15598 setReturnMessage(msg); 15599 Slog.w(TAG, msg); 15600 } 15601 15602 public void setError(String msg, PackageParserException e) { 15603 setReturnCode(e.error); 15604 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15605 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15606 for (int i = 0; i < childCount; i++) { 15607 addedChildPackages.valueAt(i).setError(msg, e); 15608 } 15609 Slog.w(TAG, msg, e); 15610 } 15611 15612 public void setError(String msg, PackageManagerException e) { 15613 returnCode = e.error; 15614 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15615 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15616 for (int i = 0; i < childCount; i++) { 15617 addedChildPackages.valueAt(i).setError(msg, e); 15618 } 15619 Slog.w(TAG, msg, e); 15620 } 15621 15622 public void setReturnCode(int returnCode) { 15623 this.returnCode = returnCode; 15624 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15625 for (int i = 0; i < childCount; i++) { 15626 addedChildPackages.valueAt(i).returnCode = returnCode; 15627 } 15628 } 15629 15630 private void setReturnMessage(String returnMsg) { 15631 this.returnMsg = returnMsg; 15632 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15633 for (int i = 0; i < childCount; i++) { 15634 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15635 } 15636 } 15637 15638 // In some error cases we want to convey more info back to the observer 15639 String origPackage; 15640 String origPermission; 15641 } 15642 15643 /* 15644 * Install a non-existing package. 15645 */ 15646 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15647 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15648 String volumeUuid, PackageInstalledInfo res, int installReason) { 15649 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15650 15651 // Remember this for later, in case we need to rollback this install 15652 String pkgName = pkg.packageName; 15653 15654 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15655 15656 synchronized(mPackages) { 15657 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15658 if (renamedPackage != null) { 15659 // A package with the same name is already installed, though 15660 // it has been renamed to an older name. The package we 15661 // are trying to install should be installed as an update to 15662 // the existing one, but that has not been requested, so bail. 15663 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15664 + " without first uninstalling package running as " 15665 + renamedPackage); 15666 return; 15667 } 15668 if (mPackages.containsKey(pkgName)) { 15669 // Don't allow installation over an existing package with the same name. 15670 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15671 + " without first uninstalling."); 15672 return; 15673 } 15674 } 15675 15676 try { 15677 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15678 System.currentTimeMillis(), user); 15679 15680 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15681 15682 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15683 prepareAppDataAfterInstallLIF(newPackage); 15684 15685 } else { 15686 // Remove package from internal structures, but keep around any 15687 // data that might have already existed 15688 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15689 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15690 } 15691 } catch (PackageManagerException e) { 15692 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15693 } 15694 15695 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15696 } 15697 15698 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15699 try (DigestInputStream digestStream = 15700 new DigestInputStream(new FileInputStream(file), digest)) { 15701 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15702 } 15703 } 15704 15705 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15706 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15707 PackageInstalledInfo res, int installReason) { 15708 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15709 15710 final PackageParser.Package oldPackage; 15711 final PackageSetting ps; 15712 final String pkgName = pkg.packageName; 15713 final int[] allUsers; 15714 final int[] installedUsers; 15715 15716 synchronized(mPackages) { 15717 oldPackage = mPackages.get(pkgName); 15718 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15719 15720 // don't allow upgrade to target a release SDK from a pre-release SDK 15721 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15722 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15723 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15724 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15725 if (oldTargetsPreRelease 15726 && !newTargetsPreRelease 15727 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15728 Slog.w(TAG, "Can't install package targeting released sdk"); 15729 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15730 return; 15731 } 15732 15733 ps = mSettings.mPackages.get(pkgName); 15734 15735 // verify signatures are valid 15736 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15737 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15738 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15739 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15740 "New package not signed by keys specified by upgrade-keysets: " 15741 + pkgName); 15742 return; 15743 } 15744 } else { 15745 // default to original signature matching 15746 if (compareSignatures(oldPackage.mSigningDetails.signatures, 15747 pkg.mSigningDetails.signatures) 15748 != PackageManager.SIGNATURE_MATCH) { 15749 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15750 "New package has a different signature: " + pkgName); 15751 return; 15752 } 15753 } 15754 15755 // don't allow a system upgrade unless the upgrade hash matches 15756 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15757 byte[] digestBytes = null; 15758 try { 15759 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15760 updateDigest(digest, new File(pkg.baseCodePath)); 15761 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15762 for (String path : pkg.splitCodePaths) { 15763 updateDigest(digest, new File(path)); 15764 } 15765 } 15766 digestBytes = digest.digest(); 15767 } catch (NoSuchAlgorithmException | IOException e) { 15768 res.setError(INSTALL_FAILED_INVALID_APK, 15769 "Could not compute hash: " + pkgName); 15770 return; 15771 } 15772 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15773 res.setError(INSTALL_FAILED_INVALID_APK, 15774 "New package fails restrict-update check: " + pkgName); 15775 return; 15776 } 15777 // retain upgrade restriction 15778 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15779 } 15780 15781 // Check for shared user id changes 15782 String invalidPackageName = 15783 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15784 if (invalidPackageName != null) { 15785 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15786 "Package " + invalidPackageName + " tried to change user " 15787 + oldPackage.mSharedUserId); 15788 return; 15789 } 15790 15791 // check if the new package supports all of the abis which the old package supports 15792 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 15793 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 15794 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 15795 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15796 "Update to package " + pkgName + " doesn't support multi arch"); 15797 return; 15798 } 15799 15800 // In case of rollback, remember per-user/profile install state 15801 allUsers = sUserManager.getUserIds(); 15802 installedUsers = ps.queryInstalledUsers(allUsers, true); 15803 15804 // don't allow an upgrade from full to ephemeral 15805 if (isInstantApp) { 15806 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15807 for (int currentUser : allUsers) { 15808 if (!ps.getInstantApp(currentUser)) { 15809 // can't downgrade from full to instant 15810 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15811 + " for user: " + currentUser); 15812 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15813 return; 15814 } 15815 } 15816 } else if (!ps.getInstantApp(user.getIdentifier())) { 15817 // can't downgrade from full to instant 15818 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15819 + " for user: " + user.getIdentifier()); 15820 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15821 return; 15822 } 15823 } 15824 } 15825 15826 // Update what is removed 15827 res.removedInfo = new PackageRemovedInfo(this); 15828 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15829 res.removedInfo.removedPackage = oldPackage.packageName; 15830 res.removedInfo.installerPackageName = ps.installerPackageName; 15831 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15832 res.removedInfo.isUpdate = true; 15833 res.removedInfo.origUsers = installedUsers; 15834 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15835 for (int i = 0; i < installedUsers.length; i++) { 15836 final int userId = installedUsers[i]; 15837 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15838 } 15839 15840 final int childCount = (oldPackage.childPackages != null) 15841 ? oldPackage.childPackages.size() : 0; 15842 for (int i = 0; i < childCount; i++) { 15843 boolean childPackageUpdated = false; 15844 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15845 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15846 if (res.addedChildPackages != null) { 15847 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15848 if (childRes != null) { 15849 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15850 childRes.removedInfo.removedPackage = childPkg.packageName; 15851 if (childPs != null) { 15852 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15853 } 15854 childRes.removedInfo.isUpdate = true; 15855 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15856 childPackageUpdated = true; 15857 } 15858 } 15859 if (!childPackageUpdated) { 15860 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15861 childRemovedRes.removedPackage = childPkg.packageName; 15862 if (childPs != null) { 15863 childRemovedRes.installerPackageName = childPs.installerPackageName; 15864 } 15865 childRemovedRes.isUpdate = false; 15866 childRemovedRes.dataRemoved = true; 15867 synchronized (mPackages) { 15868 if (childPs != null) { 15869 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15870 } 15871 } 15872 if (res.removedInfo.removedChildPackages == null) { 15873 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15874 } 15875 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15876 } 15877 } 15878 15879 boolean sysPkg = (isSystemApp(oldPackage)); 15880 if (sysPkg) { 15881 // Set the system/privileged/oem/vendor flags as needed 15882 final boolean privileged = 15883 (oldPackage.applicationInfo.privateFlags 15884 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15885 final boolean oem = 15886 (oldPackage.applicationInfo.privateFlags 15887 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15888 final boolean vendor = 15889 (oldPackage.applicationInfo.privateFlags 15890 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 15891 final @ParseFlags int systemParseFlags = parseFlags; 15892 final @ScanFlags int systemScanFlags = scanFlags 15893 | SCAN_AS_SYSTEM 15894 | (privileged ? SCAN_AS_PRIVILEGED : 0) 15895 | (oem ? SCAN_AS_OEM : 0) 15896 | (vendor ? SCAN_AS_VENDOR : 0); 15897 15898 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 15899 user, allUsers, installerPackageName, res, installReason); 15900 } else { 15901 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 15902 user, allUsers, installerPackageName, res, installReason); 15903 } 15904 } 15905 15906 @Override 15907 public List<String> getPreviousCodePaths(String packageName) { 15908 final int callingUid = Binder.getCallingUid(); 15909 final List<String> result = new ArrayList<>(); 15910 if (getInstantAppPackageName(callingUid) != null) { 15911 return result; 15912 } 15913 final PackageSetting ps = mSettings.mPackages.get(packageName); 15914 if (ps != null 15915 && ps.oldCodePaths != null 15916 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15917 result.addAll(ps.oldCodePaths); 15918 } 15919 return result; 15920 } 15921 15922 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15923 PackageParser.Package pkg, final @ParseFlags int parseFlags, 15924 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 15925 String installerPackageName, PackageInstalledInfo res, int installReason) { 15926 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15927 + deletedPackage); 15928 15929 String pkgName = deletedPackage.packageName; 15930 boolean deletedPkg = true; 15931 boolean addedPkg = false; 15932 boolean updatedSettings = false; 15933 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15934 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15935 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15936 15937 final long origUpdateTime = (pkg.mExtras != null) 15938 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15939 15940 // First delete the existing package while retaining the data directory 15941 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15942 res.removedInfo, true, pkg)) { 15943 // If the existing package wasn't successfully deleted 15944 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15945 deletedPkg = false; 15946 } else { 15947 // Successfully deleted the old package; proceed with replace. 15948 15949 // If deleted package lived in a container, give users a chance to 15950 // relinquish resources before killing. 15951 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15952 if (DEBUG_INSTALL) { 15953 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15954 } 15955 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15956 final ArrayList<String> pkgList = new ArrayList<String>(1); 15957 pkgList.add(deletedPackage.applicationInfo.packageName); 15958 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15959 } 15960 15961 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15962 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15963 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15964 15965 try { 15966 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 15967 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15968 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15969 installReason); 15970 15971 // Update the in-memory copy of the previous code paths. 15972 PackageSetting ps = mSettings.mPackages.get(pkgName); 15973 if (!killApp) { 15974 if (ps.oldCodePaths == null) { 15975 ps.oldCodePaths = new ArraySet<>(); 15976 } 15977 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15978 if (deletedPackage.splitCodePaths != null) { 15979 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 15980 } 15981 } else { 15982 ps.oldCodePaths = null; 15983 } 15984 if (ps.childPackageNames != null) { 15985 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 15986 final String childPkgName = ps.childPackageNames.get(i); 15987 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 15988 childPs.oldCodePaths = ps.oldCodePaths; 15989 } 15990 } 15991 // set instant app status, but, only if it's explicitly specified 15992 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15993 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 15994 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 15995 prepareAppDataAfterInstallLIF(newPackage); 15996 addedPkg = true; 15997 mDexManager.notifyPackageUpdated(newPackage.packageName, 15998 newPackage.baseCodePath, newPackage.splitCodePaths); 15999 } catch (PackageManagerException e) { 16000 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16001 } 16002 } 16003 16004 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16005 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16006 16007 // Revert all internal state mutations and added folders for the failed install 16008 if (addedPkg) { 16009 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16010 res.removedInfo, true, null); 16011 } 16012 16013 // Restore the old package 16014 if (deletedPkg) { 16015 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16016 File restoreFile = new File(deletedPackage.codePath); 16017 // Parse old package 16018 boolean oldExternal = isExternal(deletedPackage); 16019 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16020 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16021 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16022 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16023 try { 16024 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16025 null); 16026 } catch (PackageManagerException e) { 16027 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16028 + e.getMessage()); 16029 return; 16030 } 16031 16032 synchronized (mPackages) { 16033 // Ensure the installer package name up to date 16034 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16035 16036 // Update permissions for restored package 16037 mPermissionManager.updatePermissions( 16038 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16039 mPermissionCallback); 16040 16041 mSettings.writeLPr(); 16042 } 16043 16044 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16045 } 16046 } else { 16047 synchronized (mPackages) { 16048 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16049 if (ps != null) { 16050 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16051 if (res.removedInfo.removedChildPackages != null) { 16052 final int childCount = res.removedInfo.removedChildPackages.size(); 16053 // Iterate in reverse as we may modify the collection 16054 for (int i = childCount - 1; i >= 0; i--) { 16055 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16056 if (res.addedChildPackages.containsKey(childPackageName)) { 16057 res.removedInfo.removedChildPackages.removeAt(i); 16058 } else { 16059 PackageRemovedInfo childInfo = res.removedInfo 16060 .removedChildPackages.valueAt(i); 16061 childInfo.removedForAllUsers = mPackages.get( 16062 childInfo.removedPackage) == null; 16063 } 16064 } 16065 } 16066 } 16067 } 16068 } 16069 } 16070 16071 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16072 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16073 final @ScanFlags int scanFlags, UserHandle user, 16074 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16075 int installReason) { 16076 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16077 + ", old=" + deletedPackage); 16078 16079 final boolean disabledSystem; 16080 16081 // Remove existing system package 16082 removePackageLI(deletedPackage, true); 16083 16084 synchronized (mPackages) { 16085 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16086 } 16087 if (!disabledSystem) { 16088 // We didn't need to disable the .apk as a current system package, 16089 // which means we are replacing another update that is already 16090 // installed. We need to make sure to delete the older one's .apk. 16091 res.removedInfo.args = createInstallArgsForExisting(0, 16092 deletedPackage.applicationInfo.getCodePath(), 16093 deletedPackage.applicationInfo.getResourcePath(), 16094 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16095 } else { 16096 res.removedInfo.args = null; 16097 } 16098 16099 // Successfully disabled the old package. Now proceed with re-installation 16100 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16101 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16102 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16103 16104 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16105 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16106 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16107 16108 PackageParser.Package newPackage = null; 16109 try { 16110 // Add the package to the internal data structures 16111 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16112 16113 // Set the update and install times 16114 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16115 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16116 System.currentTimeMillis()); 16117 16118 // Update the package dynamic state if succeeded 16119 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16120 // Now that the install succeeded make sure we remove data 16121 // directories for any child package the update removed. 16122 final int deletedChildCount = (deletedPackage.childPackages != null) 16123 ? deletedPackage.childPackages.size() : 0; 16124 final int newChildCount = (newPackage.childPackages != null) 16125 ? newPackage.childPackages.size() : 0; 16126 for (int i = 0; i < deletedChildCount; i++) { 16127 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16128 boolean childPackageDeleted = true; 16129 for (int j = 0; j < newChildCount; j++) { 16130 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16131 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16132 childPackageDeleted = false; 16133 break; 16134 } 16135 } 16136 if (childPackageDeleted) { 16137 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16138 deletedChildPkg.packageName); 16139 if (ps != null && res.removedInfo.removedChildPackages != null) { 16140 PackageRemovedInfo removedChildRes = res.removedInfo 16141 .removedChildPackages.get(deletedChildPkg.packageName); 16142 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16143 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16144 } 16145 } 16146 } 16147 16148 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16149 installReason); 16150 prepareAppDataAfterInstallLIF(newPackage); 16151 16152 mDexManager.notifyPackageUpdated(newPackage.packageName, 16153 newPackage.baseCodePath, newPackage.splitCodePaths); 16154 } 16155 } catch (PackageManagerException e) { 16156 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16157 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16158 } 16159 16160 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16161 // Re installation failed. Restore old information 16162 // Remove new pkg information 16163 if (newPackage != null) { 16164 removeInstalledPackageLI(newPackage, true); 16165 } 16166 // Add back the old system package 16167 try { 16168 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16169 } catch (PackageManagerException e) { 16170 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16171 } 16172 16173 synchronized (mPackages) { 16174 if (disabledSystem) { 16175 enableSystemPackageLPw(deletedPackage); 16176 } 16177 16178 // Ensure the installer package name up to date 16179 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16180 16181 // Update permissions for restored package 16182 mPermissionManager.updatePermissions( 16183 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16184 mPermissionCallback); 16185 16186 mSettings.writeLPr(); 16187 } 16188 16189 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16190 + " after failed upgrade"); 16191 } 16192 } 16193 16194 /** 16195 * Checks whether the parent or any of the child packages have a change shared 16196 * user. For a package to be a valid update the shred users of the parent and 16197 * the children should match. We may later support changing child shared users. 16198 * @param oldPkg The updated package. 16199 * @param newPkg The update package. 16200 * @return The shared user that change between the versions. 16201 */ 16202 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16203 PackageParser.Package newPkg) { 16204 // Check parent shared user 16205 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16206 return newPkg.packageName; 16207 } 16208 // Check child shared users 16209 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16210 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16211 for (int i = 0; i < newChildCount; i++) { 16212 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16213 // If this child was present, did it have the same shared user? 16214 for (int j = 0; j < oldChildCount; j++) { 16215 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16216 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16217 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16218 return newChildPkg.packageName; 16219 } 16220 } 16221 } 16222 return null; 16223 } 16224 16225 private void removeNativeBinariesLI(PackageSetting ps) { 16226 // Remove the lib path for the parent package 16227 if (ps != null) { 16228 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16229 // Remove the lib path for the child packages 16230 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16231 for (int i = 0; i < childCount; i++) { 16232 PackageSetting childPs = null; 16233 synchronized (mPackages) { 16234 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16235 } 16236 if (childPs != null) { 16237 NativeLibraryHelper.removeNativeBinariesLI(childPs 16238 .legacyNativeLibraryPathString); 16239 } 16240 } 16241 } 16242 } 16243 16244 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16245 // Enable the parent package 16246 mSettings.enableSystemPackageLPw(pkg.packageName); 16247 // Enable the child packages 16248 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16249 for (int i = 0; i < childCount; i++) { 16250 PackageParser.Package childPkg = pkg.childPackages.get(i); 16251 mSettings.enableSystemPackageLPw(childPkg.packageName); 16252 } 16253 } 16254 16255 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16256 PackageParser.Package newPkg) { 16257 // Disable the parent package (parent always replaced) 16258 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16259 // Disable the child packages 16260 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16261 for (int i = 0; i < childCount; i++) { 16262 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16263 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16264 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16265 } 16266 return disabled; 16267 } 16268 16269 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16270 String installerPackageName) { 16271 // Enable the parent package 16272 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16273 // Enable the child packages 16274 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16275 for (int i = 0; i < childCount; i++) { 16276 PackageParser.Package childPkg = pkg.childPackages.get(i); 16277 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16278 } 16279 } 16280 16281 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16282 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16283 // Update the parent package setting 16284 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16285 res, user, installReason); 16286 // Update the child packages setting 16287 final int childCount = (newPackage.childPackages != null) 16288 ? newPackage.childPackages.size() : 0; 16289 for (int i = 0; i < childCount; i++) { 16290 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16291 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16292 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16293 childRes.origUsers, childRes, user, installReason); 16294 } 16295 } 16296 16297 private void updateSettingsInternalLI(PackageParser.Package pkg, 16298 String installerPackageName, int[] allUsers, int[] installedForUsers, 16299 PackageInstalledInfo res, UserHandle user, int installReason) { 16300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16301 16302 String pkgName = pkg.packageName; 16303 synchronized (mPackages) { 16304 //write settings. the installStatus will be incomplete at this stage. 16305 //note that the new package setting would have already been 16306 //added to mPackages. It hasn't been persisted yet. 16307 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16308 // TODO: Remove this write? It's also written at the end of this method 16309 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16310 mSettings.writeLPr(); 16311 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16312 } 16313 16314 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16315 synchronized (mPackages) { 16316// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16317 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16318 mPermissionCallback); 16319 // For system-bundled packages, we assume that installing an upgraded version 16320 // of the package implies that the user actually wants to run that new code, 16321 // so we enable the package. 16322 PackageSetting ps = mSettings.mPackages.get(pkgName); 16323 final int userId = user.getIdentifier(); 16324 if (ps != null) { 16325 if (isSystemApp(pkg)) { 16326 if (DEBUG_INSTALL) { 16327 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16328 } 16329 // Enable system package for requested users 16330 if (res.origUsers != null) { 16331 for (int origUserId : res.origUsers) { 16332 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16333 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16334 origUserId, installerPackageName); 16335 } 16336 } 16337 } 16338 // Also convey the prior install/uninstall state 16339 if (allUsers != null && installedForUsers != null) { 16340 for (int currentUserId : allUsers) { 16341 final boolean installed = ArrayUtils.contains( 16342 installedForUsers, currentUserId); 16343 if (DEBUG_INSTALL) { 16344 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16345 } 16346 ps.setInstalled(installed, currentUserId); 16347 } 16348 // these install state changes will be persisted in the 16349 // upcoming call to mSettings.writeLPr(). 16350 } 16351 } 16352 // It's implied that when a user requests installation, they want the app to be 16353 // installed and enabled. 16354 if (userId != UserHandle.USER_ALL) { 16355 ps.setInstalled(true, userId); 16356 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16357 } 16358 16359 // When replacing an existing package, preserve the original install reason for all 16360 // users that had the package installed before. 16361 final Set<Integer> previousUserIds = new ArraySet<>(); 16362 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16363 final int installReasonCount = res.removedInfo.installReasons.size(); 16364 for (int i = 0; i < installReasonCount; i++) { 16365 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16366 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16367 ps.setInstallReason(previousInstallReason, previousUserId); 16368 previousUserIds.add(previousUserId); 16369 } 16370 } 16371 16372 // Set install reason for users that are having the package newly installed. 16373 if (userId == UserHandle.USER_ALL) { 16374 for (int currentUserId : sUserManager.getUserIds()) { 16375 if (!previousUserIds.contains(currentUserId)) { 16376 ps.setInstallReason(installReason, currentUserId); 16377 } 16378 } 16379 } else if (!previousUserIds.contains(userId)) { 16380 ps.setInstallReason(installReason, userId); 16381 } 16382 mSettings.writeKernelMappingLPr(ps); 16383 } 16384 res.name = pkgName; 16385 res.uid = pkg.applicationInfo.uid; 16386 res.pkg = pkg; 16387 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16388 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16389 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16390 //to update install status 16391 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16392 mSettings.writeLPr(); 16393 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16394 } 16395 16396 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16397 } 16398 16399 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16400 try { 16401 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16402 installPackageLI(args, res); 16403 } finally { 16404 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16405 } 16406 } 16407 16408 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16409 final int installFlags = args.installFlags; 16410 final String installerPackageName = args.installerPackageName; 16411 final String volumeUuid = args.volumeUuid; 16412 final File tmpPackageFile = new File(args.getCodePath()); 16413 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16414 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16415 || (args.volumeUuid != null)); 16416 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16417 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16418 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16419 final boolean virtualPreload = 16420 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16421 boolean replace = false; 16422 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16423 if (args.move != null) { 16424 // moving a complete application; perform an initial scan on the new install location 16425 scanFlags |= SCAN_INITIAL; 16426 } 16427 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16428 scanFlags |= SCAN_DONT_KILL_APP; 16429 } 16430 if (instantApp) { 16431 scanFlags |= SCAN_AS_INSTANT_APP; 16432 } 16433 if (fullApp) { 16434 scanFlags |= SCAN_AS_FULL_APP; 16435 } 16436 if (virtualPreload) { 16437 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16438 } 16439 16440 // Result object to be returned 16441 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16442 res.installerPackageName = installerPackageName; 16443 16444 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16445 16446 // Sanity check 16447 if (instantApp && (forwardLocked || onExternal)) { 16448 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16449 + " external=" + onExternal); 16450 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16451 return; 16452 } 16453 16454 // Retrieve PackageSettings and parse package 16455 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16456 | PackageParser.PARSE_ENFORCE_CODE 16457 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16458 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16459 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16460 PackageParser pp = new PackageParser(); 16461 pp.setSeparateProcesses(mSeparateProcesses); 16462 pp.setDisplayMetrics(mMetrics); 16463 pp.setCallback(mPackageParserCallback); 16464 16465 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16466 final PackageParser.Package pkg; 16467 try { 16468 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16469 } catch (PackageParserException e) { 16470 res.setError("Failed parse during installPackageLI", e); 16471 return; 16472 } finally { 16473 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16474 } 16475 16476 // App targetSdkVersion is below min supported version 16477 if (!forceSdk && pkg.applicationInfo.isTargetingDeprecatedSdkVersion()) { 16478 Slog.w(TAG, "App " + pkg.packageName + " targets deprecated sdk"); 16479 16480 res.setError(INSTALL_FAILED_NEWER_SDK, 16481 "App is targeting deprecated sdk (targetSdkVersion should be at least " 16482 + Build.VERSION.MIN_SUPPORTED_TARGET_SDK_INT + ")."); 16483 return; 16484 } 16485 16486 // Instant apps have several additional install-time checks. 16487 if (instantApp) { 16488 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16489 Slog.w(TAG, 16490 "Instant app package " + pkg.packageName + " does not target at least O"); 16491 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16492 "Instant app package must target at least O"); 16493 return; 16494 } 16495 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16496 Slog.w(TAG, "Instant app package " + pkg.packageName 16497 + " does not target targetSandboxVersion 2"); 16498 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16499 "Instant app package must use targetSandboxVersion 2"); 16500 return; 16501 } 16502 if (pkg.mSharedUserId != null) { 16503 Slog.w(TAG, "Instant app package " + pkg.packageName 16504 + " may not declare sharedUserId."); 16505 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16506 "Instant app package may not declare a sharedUserId"); 16507 return; 16508 } 16509 } 16510 16511 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16512 // Static shared libraries have synthetic package names 16513 renameStaticSharedLibraryPackage(pkg); 16514 16515 // No static shared libs on external storage 16516 if (onExternal) { 16517 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16518 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16519 "Packages declaring static-shared libs cannot be updated"); 16520 return; 16521 } 16522 } 16523 16524 // If we are installing a clustered package add results for the children 16525 if (pkg.childPackages != null) { 16526 synchronized (mPackages) { 16527 final int childCount = pkg.childPackages.size(); 16528 for (int i = 0; i < childCount; i++) { 16529 PackageParser.Package childPkg = pkg.childPackages.get(i); 16530 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16531 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16532 childRes.pkg = childPkg; 16533 childRes.name = childPkg.packageName; 16534 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16535 if (childPs != null) { 16536 childRes.origUsers = childPs.queryInstalledUsers( 16537 sUserManager.getUserIds(), true); 16538 } 16539 if ((mPackages.containsKey(childPkg.packageName))) { 16540 childRes.removedInfo = new PackageRemovedInfo(this); 16541 childRes.removedInfo.removedPackage = childPkg.packageName; 16542 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16543 } 16544 if (res.addedChildPackages == null) { 16545 res.addedChildPackages = new ArrayMap<>(); 16546 } 16547 res.addedChildPackages.put(childPkg.packageName, childRes); 16548 } 16549 } 16550 } 16551 16552 // If package doesn't declare API override, mark that we have an install 16553 // time CPU ABI override. 16554 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16555 pkg.cpuAbiOverride = args.abiOverride; 16556 } 16557 16558 String pkgName = res.name = pkg.packageName; 16559 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16560 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16561 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16562 return; 16563 } 16564 } 16565 16566 try { 16567 // either use what we've been given or parse directly from the APK 16568 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16569 pkg.setSigningDetails(args.signingDetails); 16570 } else { 16571 PackageParser.collectCertificates(pkg, parseFlags); 16572 } 16573 } catch (PackageParserException e) { 16574 res.setError("Failed collect during installPackageLI", e); 16575 return; 16576 } 16577 16578 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16579 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16580 Slog.w(TAG, "Instant app package " + pkg.packageName 16581 + " is not signed with at least APK Signature Scheme v2"); 16582 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16583 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16584 return; 16585 } 16586 16587 // Get rid of all references to package scan path via parser. 16588 pp = null; 16589 String oldCodePath = null; 16590 boolean systemApp = false; 16591 synchronized (mPackages) { 16592 // Check if installing already existing package 16593 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16594 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16595 if (pkg.mOriginalPackages != null 16596 && pkg.mOriginalPackages.contains(oldName) 16597 && mPackages.containsKey(oldName)) { 16598 // This package is derived from an original package, 16599 // and this device has been updating from that original 16600 // name. We must continue using the original name, so 16601 // rename the new package here. 16602 pkg.setPackageName(oldName); 16603 pkgName = pkg.packageName; 16604 replace = true; 16605 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16606 + oldName + " pkgName=" + pkgName); 16607 } else if (mPackages.containsKey(pkgName)) { 16608 // This package, under its official name, already exists 16609 // on the device; we should replace it. 16610 replace = true; 16611 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16612 } 16613 16614 // Child packages are installed through the parent package 16615 if (pkg.parentPackage != null) { 16616 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16617 "Package " + pkg.packageName + " is child of package " 16618 + pkg.parentPackage.parentPackage + ". Child packages " 16619 + "can be updated only through the parent package."); 16620 return; 16621 } 16622 16623 if (replace) { 16624 // Prevent apps opting out from runtime permissions 16625 PackageParser.Package oldPackage = mPackages.get(pkgName); 16626 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16627 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16628 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16629 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16630 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16631 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16632 + " doesn't support runtime permissions but the old" 16633 + " target SDK " + oldTargetSdk + " does."); 16634 return; 16635 } 16636 // Prevent persistent apps from being updated 16637 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16638 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16639 "Package " + oldPackage.packageName + " is a persistent app. " 16640 + "Persistent apps are not updateable."); 16641 return; 16642 } 16643 // Prevent apps from downgrading their targetSandbox. 16644 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16645 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16646 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16647 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16648 "Package " + pkg.packageName + " new target sandbox " 16649 + newTargetSandbox + " is incompatible with the previous value of" 16650 + oldTargetSandbox + "."); 16651 return; 16652 } 16653 16654 // Prevent installing of child packages 16655 if (oldPackage.parentPackage != null) { 16656 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16657 "Package " + pkg.packageName + " is child of package " 16658 + oldPackage.parentPackage + ". Child packages " 16659 + "can be updated only through the parent package."); 16660 return; 16661 } 16662 } 16663 } 16664 16665 PackageSetting ps = mSettings.mPackages.get(pkgName); 16666 if (ps != null) { 16667 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16668 16669 // Static shared libs have same package with different versions where 16670 // we internally use a synthetic package name to allow multiple versions 16671 // of the same package, therefore we need to compare signatures against 16672 // the package setting for the latest library version. 16673 PackageSetting signatureCheckPs = ps; 16674 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16675 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16676 if (libraryEntry != null) { 16677 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16678 } 16679 } 16680 16681 // Quick sanity check that we're signed correctly if updating; 16682 // we'll check this again later when scanning, but we want to 16683 // bail early here before tripping over redefined permissions. 16684 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16685 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16686 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16687 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16688 + pkg.packageName + " upgrade keys do not match the " 16689 + "previously installed version"); 16690 return; 16691 } 16692 } else { 16693 try { 16694 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16695 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16696 // We don't care about disabledPkgSetting on install for now. 16697 final boolean compatMatch = verifySignatures( 16698 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16699 compareRecover); 16700 // The new KeySets will be re-added later in the scanning process. 16701 if (compatMatch) { 16702 synchronized (mPackages) { 16703 ksms.removeAppKeySetDataLPw(pkg.packageName); 16704 } 16705 } 16706 } catch (PackageManagerException e) { 16707 res.setError(e.error, e.getMessage()); 16708 return; 16709 } 16710 } 16711 16712 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16713 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16714 systemApp = (ps.pkg.applicationInfo.flags & 16715 ApplicationInfo.FLAG_SYSTEM) != 0; 16716 } 16717 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16718 } 16719 16720 int N = pkg.permissions.size(); 16721 for (int i = N-1; i >= 0; i--) { 16722 final PackageParser.Permission perm = pkg.permissions.get(i); 16723 final BasePermission bp = 16724 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16725 16726 // Don't allow anyone but the system to define ephemeral permissions. 16727 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16728 && !systemApp) { 16729 Slog.w(TAG, "Non-System package " + pkg.packageName 16730 + " attempting to delcare ephemeral permission " 16731 + perm.info.name + "; Removing ephemeral."); 16732 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16733 } 16734 16735 // Check whether the newly-scanned package wants to define an already-defined perm 16736 if (bp != null) { 16737 // If the defining package is signed with our cert, it's okay. This 16738 // also includes the "updating the same package" case, of course. 16739 // "updating same package" could also involve key-rotation. 16740 final boolean sigsOk; 16741 final String sourcePackageName = bp.getSourcePackageName(); 16742 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16743 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16744 if (sourcePackageName.equals(pkg.packageName) 16745 && (ksms.shouldCheckUpgradeKeySetLocked( 16746 sourcePackageSetting, scanFlags))) { 16747 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16748 } else { 16749 sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures, 16750 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 16751 } 16752 if (!sigsOk) { 16753 // If the owning package is the system itself, we log but allow 16754 // install to proceed; we fail the install on all other permission 16755 // redefinitions. 16756 if (!sourcePackageName.equals("android")) { 16757 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16758 + pkg.packageName + " attempting to redeclare permission " 16759 + perm.info.name + " already owned by " + sourcePackageName); 16760 res.origPermission = perm.info.name; 16761 res.origPackage = sourcePackageName; 16762 return; 16763 } else { 16764 Slog.w(TAG, "Package " + pkg.packageName 16765 + " attempting to redeclare system permission " 16766 + perm.info.name + "; ignoring new declaration"); 16767 pkg.permissions.remove(i); 16768 } 16769 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16770 // Prevent apps to change protection level to dangerous from any other 16771 // type as this would allow a privilege escalation where an app adds a 16772 // normal/signature permission in other app's group and later redefines 16773 // it as dangerous leading to the group auto-grant. 16774 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16775 == PermissionInfo.PROTECTION_DANGEROUS) { 16776 if (bp != null && !bp.isRuntime()) { 16777 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16778 + "non-runtime permission " + perm.info.name 16779 + " to runtime; keeping old protection level"); 16780 perm.info.protectionLevel = bp.getProtectionLevel(); 16781 } 16782 } 16783 } 16784 } 16785 } 16786 } 16787 16788 if (systemApp) { 16789 if (onExternal) { 16790 // Abort update; system app can't be replaced with app on sdcard 16791 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16792 "Cannot install updates to system apps on sdcard"); 16793 return; 16794 } else if (instantApp) { 16795 // Abort update; system app can't be replaced with an instant app 16796 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16797 "Cannot update a system app with an instant app"); 16798 return; 16799 } 16800 } 16801 16802 if (args.move != null) { 16803 // We did an in-place move, so dex is ready to roll 16804 scanFlags |= SCAN_NO_DEX; 16805 scanFlags |= SCAN_MOVE; 16806 16807 synchronized (mPackages) { 16808 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16809 if (ps == null) { 16810 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16811 "Missing settings for moved package " + pkgName); 16812 } 16813 16814 // We moved the entire application as-is, so bring over the 16815 // previously derived ABI information. 16816 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16817 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16818 } 16819 16820 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16821 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16822 scanFlags |= SCAN_NO_DEX; 16823 16824 try { 16825 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16826 args.abiOverride : pkg.cpuAbiOverride); 16827 final boolean extractNativeLibs = !pkg.isLibrary(); 16828 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 16829 } catch (PackageManagerException pme) { 16830 Slog.e(TAG, "Error deriving application ABI", pme); 16831 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16832 return; 16833 } 16834 16835 // Shared libraries for the package need to be updated. 16836 synchronized (mPackages) { 16837 try { 16838 updateSharedLibrariesLPr(pkg, null); 16839 } catch (PackageManagerException e) { 16840 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16841 } 16842 } 16843 } 16844 16845 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16846 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16847 return; 16848 } 16849 16850 if (!instantApp) { 16851 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16852 } else { 16853 if (DEBUG_DOMAIN_VERIFICATION) { 16854 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16855 } 16856 } 16857 16858 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16859 "installPackageLI")) { 16860 if (replace) { 16861 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16862 // Static libs have a synthetic package name containing the version 16863 // and cannot be updated as an update would get a new package name, 16864 // unless this is the exact same version code which is useful for 16865 // development. 16866 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16867 if (existingPkg != null && 16868 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 16869 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16870 + "static-shared libs cannot be updated"); 16871 return; 16872 } 16873 } 16874 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 16875 installerPackageName, res, args.installReason); 16876 } else { 16877 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16878 args.user, installerPackageName, volumeUuid, res, args.installReason); 16879 } 16880 } 16881 16882 // Check whether we need to dexopt the app. 16883 // 16884 // NOTE: it is IMPORTANT to call dexopt: 16885 // - after doRename which will sync the package data from PackageParser.Package and its 16886 // corresponding ApplicationInfo. 16887 // - after installNewPackageLIF or replacePackageLIF which will update result with the 16888 // uid of the application (pkg.applicationInfo.uid). 16889 // This update happens in place! 16890 // 16891 // We only need to dexopt if the package meets ALL of the following conditions: 16892 // 1) it is not forward locked. 16893 // 2) it is not on on an external ASEC container. 16894 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16895 // 16896 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16897 // complete, so we skip this step during installation. Instead, we'll take extra time 16898 // the first time the instant app starts. It's preferred to do it this way to provide 16899 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16900 // middle of running an instant app. The default behaviour can be overridden 16901 // via gservices. 16902 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 16903 && !forwardLocked 16904 && !pkg.applicationInfo.isExternalAsec() 16905 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16906 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16907 16908 if (performDexopt) { 16909 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16910 // Do not run PackageDexOptimizer through the local performDexOpt 16911 // method because `pkg` may not be in `mPackages` yet. 16912 // 16913 // Also, don't fail application installs if the dexopt step fails. 16914 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 16915 REASON_INSTALL, 16916 DexoptOptions.DEXOPT_BOOT_COMPLETE); 16917 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16918 null /* instructionSets */, 16919 getOrCreateCompilerPackageStats(pkg), 16920 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 16921 dexoptOptions); 16922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16923 } 16924 16925 // Notify BackgroundDexOptService that the package has been changed. 16926 // If this is an update of a package which used to fail to compile, 16927 // BackgroundDexOptService will remove it from its blacklist. 16928 // TODO: Layering violation 16929 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16930 16931 synchronized (mPackages) { 16932 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16933 if (ps != null) { 16934 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16935 ps.setUpdateAvailable(false /*updateAvailable*/); 16936 } 16937 16938 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16939 for (int i = 0; i < childCount; i++) { 16940 PackageParser.Package childPkg = pkg.childPackages.get(i); 16941 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16942 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16943 if (childPs != null) { 16944 childRes.newUsers = childPs.queryInstalledUsers( 16945 sUserManager.getUserIds(), true); 16946 } 16947 } 16948 16949 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16950 updateSequenceNumberLP(ps, res.newUsers); 16951 updateInstantAppInstallerLocked(pkgName); 16952 } 16953 } 16954 } 16955 16956 private void startIntentFilterVerifications(int userId, boolean replacing, 16957 PackageParser.Package pkg) { 16958 if (mIntentFilterVerifierComponent == null) { 16959 Slog.w(TAG, "No IntentFilter verification will not be done as " 16960 + "there is no IntentFilterVerifier available!"); 16961 return; 16962 } 16963 16964 final int verifierUid = getPackageUid( 16965 mIntentFilterVerifierComponent.getPackageName(), 16966 MATCH_DEBUG_TRIAGED_MISSING, 16967 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16968 16969 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16970 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16971 mHandler.sendMessage(msg); 16972 16973 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16974 for (int i = 0; i < childCount; i++) { 16975 PackageParser.Package childPkg = pkg.childPackages.get(i); 16976 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16977 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16978 mHandler.sendMessage(msg); 16979 } 16980 } 16981 16982 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16983 PackageParser.Package pkg) { 16984 int size = pkg.activities.size(); 16985 if (size == 0) { 16986 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16987 "No activity, so no need to verify any IntentFilter!"); 16988 return; 16989 } 16990 16991 final boolean hasDomainURLs = hasDomainURLs(pkg); 16992 if (!hasDomainURLs) { 16993 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16994 "No domain URLs, so no need to verify any IntentFilter!"); 16995 return; 16996 } 16997 16998 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 16999 + " if any IntentFilter from the " + size 17000 + " Activities needs verification ..."); 17001 17002 int count = 0; 17003 final String packageName = pkg.packageName; 17004 17005 synchronized (mPackages) { 17006 // If this is a new install and we see that we've already run verification for this 17007 // package, we have nothing to do: it means the state was restored from backup. 17008 if (!replacing) { 17009 IntentFilterVerificationInfo ivi = 17010 mSettings.getIntentFilterVerificationLPr(packageName); 17011 if (ivi != null) { 17012 if (DEBUG_DOMAIN_VERIFICATION) { 17013 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17014 + ivi.getStatusString()); 17015 } 17016 return; 17017 } 17018 } 17019 17020 // If any filters need to be verified, then all need to be. 17021 boolean needToVerify = false; 17022 for (PackageParser.Activity a : pkg.activities) { 17023 for (ActivityIntentInfo filter : a.intents) { 17024 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17025 if (DEBUG_DOMAIN_VERIFICATION) { 17026 Slog.d(TAG, 17027 "Intent filter needs verification, so processing all filters"); 17028 } 17029 needToVerify = true; 17030 break; 17031 } 17032 } 17033 } 17034 17035 if (needToVerify) { 17036 final int verificationId = mIntentFilterVerificationToken++; 17037 for (PackageParser.Activity a : pkg.activities) { 17038 for (ActivityIntentInfo filter : a.intents) { 17039 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17040 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17041 "Verification needed for IntentFilter:" + filter.toString()); 17042 mIntentFilterVerifier.addOneIntentFilterVerification( 17043 verifierUid, userId, verificationId, filter, packageName); 17044 count++; 17045 } 17046 } 17047 } 17048 } 17049 } 17050 17051 if (count > 0) { 17052 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17053 + " IntentFilter verification" + (count > 1 ? "s" : "") 17054 + " for userId:" + userId); 17055 mIntentFilterVerifier.startVerifications(userId); 17056 } else { 17057 if (DEBUG_DOMAIN_VERIFICATION) { 17058 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17059 } 17060 } 17061 } 17062 17063 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17064 final ComponentName cn = filter.activity.getComponentName(); 17065 final String packageName = cn.getPackageName(); 17066 17067 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17068 packageName); 17069 if (ivi == null) { 17070 return true; 17071 } 17072 int status = ivi.getStatus(); 17073 switch (status) { 17074 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17075 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17076 return true; 17077 17078 default: 17079 // Nothing to do 17080 return false; 17081 } 17082 } 17083 17084 private static boolean isMultiArch(ApplicationInfo info) { 17085 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17086 } 17087 17088 private static boolean isExternal(PackageParser.Package pkg) { 17089 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17090 } 17091 17092 private static boolean isExternal(PackageSetting ps) { 17093 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17094 } 17095 17096 private static boolean isSystemApp(PackageParser.Package pkg) { 17097 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17098 } 17099 17100 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17101 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17102 } 17103 17104 private static boolean isOemApp(PackageParser.Package pkg) { 17105 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17106 } 17107 17108 private static boolean isVendorApp(PackageParser.Package pkg) { 17109 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17110 } 17111 17112 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17113 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17114 } 17115 17116 private static boolean isSystemApp(PackageSetting ps) { 17117 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17118 } 17119 17120 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17121 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17122 } 17123 17124 private int packageFlagsToInstallFlags(PackageSetting ps) { 17125 int installFlags = 0; 17126 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17127 // This existing package was an external ASEC install when we have 17128 // the external flag without a UUID 17129 installFlags |= PackageManager.INSTALL_EXTERNAL; 17130 } 17131 if (ps.isForwardLocked()) { 17132 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17133 } 17134 return installFlags; 17135 } 17136 17137 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17138 if (isExternal(pkg)) { 17139 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17140 return mSettings.getExternalVersion(); 17141 } else { 17142 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17143 } 17144 } else { 17145 return mSettings.getInternalVersion(); 17146 } 17147 } 17148 17149 private void deleteTempPackageFiles() { 17150 final FilenameFilter filter = new FilenameFilter() { 17151 public boolean accept(File dir, String name) { 17152 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17153 } 17154 }; 17155 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17156 file.delete(); 17157 } 17158 } 17159 17160 @Override 17161 public void deletePackageAsUser(String packageName, int versionCode, 17162 IPackageDeleteObserver observer, int userId, int flags) { 17163 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17164 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17165 } 17166 17167 @Override 17168 public void deletePackageVersioned(VersionedPackage versionedPackage, 17169 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17170 final int callingUid = Binder.getCallingUid(); 17171 mContext.enforceCallingOrSelfPermission( 17172 android.Manifest.permission.DELETE_PACKAGES, null); 17173 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17174 Preconditions.checkNotNull(versionedPackage); 17175 Preconditions.checkNotNull(observer); 17176 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17177 PackageManager.VERSION_CODE_HIGHEST, 17178 Long.MAX_VALUE, "versionCode must be >= -1"); 17179 17180 final String packageName = versionedPackage.getPackageName(); 17181 final long versionCode = versionedPackage.getLongVersionCode(); 17182 final String internalPackageName; 17183 synchronized (mPackages) { 17184 // Normalize package name to handle renamed packages and static libs 17185 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17186 } 17187 17188 final int uid = Binder.getCallingUid(); 17189 if (!isOrphaned(internalPackageName) 17190 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17191 try { 17192 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17193 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17194 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17195 observer.onUserActionRequired(intent); 17196 } catch (RemoteException re) { 17197 } 17198 return; 17199 } 17200 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17201 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17202 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17203 mContext.enforceCallingOrSelfPermission( 17204 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17205 "deletePackage for user " + userId); 17206 } 17207 17208 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17209 try { 17210 observer.onPackageDeleted(packageName, 17211 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17212 } catch (RemoteException re) { 17213 } 17214 return; 17215 } 17216 17217 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17218 try { 17219 observer.onPackageDeleted(packageName, 17220 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17221 } catch (RemoteException re) { 17222 } 17223 return; 17224 } 17225 17226 if (DEBUG_REMOVE) { 17227 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17228 + " deleteAllUsers: " + deleteAllUsers + " version=" 17229 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17230 ? "VERSION_CODE_HIGHEST" : versionCode)); 17231 } 17232 // Queue up an async operation since the package deletion may take a little while. 17233 mHandler.post(new Runnable() { 17234 public void run() { 17235 mHandler.removeCallbacks(this); 17236 int returnCode; 17237 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17238 boolean doDeletePackage = true; 17239 if (ps != null) { 17240 final boolean targetIsInstantApp = 17241 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17242 doDeletePackage = !targetIsInstantApp 17243 || canViewInstantApps; 17244 } 17245 if (doDeletePackage) { 17246 if (!deleteAllUsers) { 17247 returnCode = deletePackageX(internalPackageName, versionCode, 17248 userId, deleteFlags); 17249 } else { 17250 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17251 internalPackageName, users); 17252 // If nobody is blocking uninstall, proceed with delete for all users 17253 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17254 returnCode = deletePackageX(internalPackageName, versionCode, 17255 userId, deleteFlags); 17256 } else { 17257 // Otherwise uninstall individually for users with blockUninstalls=false 17258 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17259 for (int userId : users) { 17260 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17261 returnCode = deletePackageX(internalPackageName, versionCode, 17262 userId, userFlags); 17263 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17264 Slog.w(TAG, "Package delete failed for user " + userId 17265 + ", returnCode " + returnCode); 17266 } 17267 } 17268 } 17269 // The app has only been marked uninstalled for certain users. 17270 // We still need to report that delete was blocked 17271 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17272 } 17273 } 17274 } else { 17275 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17276 } 17277 try { 17278 observer.onPackageDeleted(packageName, returnCode, null); 17279 } catch (RemoteException e) { 17280 Log.i(TAG, "Observer no longer exists."); 17281 } //end catch 17282 } //end run 17283 }); 17284 } 17285 17286 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17287 if (pkg.staticSharedLibName != null) { 17288 return pkg.manifestPackageName; 17289 } 17290 return pkg.packageName; 17291 } 17292 17293 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17294 // Handle renamed packages 17295 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17296 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17297 17298 // Is this a static library? 17299 LongSparseArray<SharedLibraryEntry> versionedLib = 17300 mStaticLibsByDeclaringPackage.get(packageName); 17301 if (versionedLib == null || versionedLib.size() <= 0) { 17302 return packageName; 17303 } 17304 17305 // Figure out which lib versions the caller can see 17306 LongSparseLongArray versionsCallerCanSee = null; 17307 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17308 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17309 && callingAppId != Process.ROOT_UID) { 17310 versionsCallerCanSee = new LongSparseLongArray(); 17311 String libName = versionedLib.valueAt(0).info.getName(); 17312 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17313 if (uidPackages != null) { 17314 for (String uidPackage : uidPackages) { 17315 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17316 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17317 if (libIdx >= 0) { 17318 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17319 versionsCallerCanSee.append(libVersion, libVersion); 17320 } 17321 } 17322 } 17323 } 17324 17325 // Caller can see nothing - done 17326 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17327 return packageName; 17328 } 17329 17330 // Find the version the caller can see and the app version code 17331 SharedLibraryEntry highestVersion = null; 17332 final int versionCount = versionedLib.size(); 17333 for (int i = 0; i < versionCount; i++) { 17334 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17335 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17336 libEntry.info.getLongVersion()) < 0) { 17337 continue; 17338 } 17339 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17340 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17341 if (libVersionCode == versionCode) { 17342 return libEntry.apk; 17343 } 17344 } else if (highestVersion == null) { 17345 highestVersion = libEntry; 17346 } else if (libVersionCode > highestVersion.info 17347 .getDeclaringPackage().getLongVersionCode()) { 17348 highestVersion = libEntry; 17349 } 17350 } 17351 17352 if (highestVersion != null) { 17353 return highestVersion.apk; 17354 } 17355 17356 return packageName; 17357 } 17358 17359 boolean isCallerVerifier(int callingUid) { 17360 final int callingUserId = UserHandle.getUserId(callingUid); 17361 return mRequiredVerifierPackage != null && 17362 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17363 } 17364 17365 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17366 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17367 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17368 return true; 17369 } 17370 final int callingUserId = UserHandle.getUserId(callingUid); 17371 // If the caller installed the pkgName, then allow it to silently uninstall. 17372 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17373 return true; 17374 } 17375 17376 // Allow package verifier to silently uninstall. 17377 if (mRequiredVerifierPackage != null && 17378 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17379 return true; 17380 } 17381 17382 // Allow package uninstaller to silently uninstall. 17383 if (mRequiredUninstallerPackage != null && 17384 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17385 return true; 17386 } 17387 17388 // Allow storage manager to silently uninstall. 17389 if (mStorageManagerPackage != null && 17390 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17391 return true; 17392 } 17393 17394 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17395 // uninstall for device owner provisioning. 17396 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17397 == PERMISSION_GRANTED) { 17398 return true; 17399 } 17400 17401 return false; 17402 } 17403 17404 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17405 int[] result = EMPTY_INT_ARRAY; 17406 for (int userId : userIds) { 17407 if (getBlockUninstallForUser(packageName, userId)) { 17408 result = ArrayUtils.appendInt(result, userId); 17409 } 17410 } 17411 return result; 17412 } 17413 17414 @Override 17415 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17416 final int callingUid = Binder.getCallingUid(); 17417 if (getInstantAppPackageName(callingUid) != null 17418 && !isCallerSameApp(packageName, callingUid)) { 17419 return false; 17420 } 17421 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17422 } 17423 17424 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17425 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17426 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17427 try { 17428 if (dpm != null) { 17429 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17430 /* callingUserOnly =*/ false); 17431 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17432 : deviceOwnerComponentName.getPackageName(); 17433 // Does the package contains the device owner? 17434 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17435 // this check is probably not needed, since DO should be registered as a device 17436 // admin on some user too. (Original bug for this: b/17657954) 17437 if (packageName.equals(deviceOwnerPackageName)) { 17438 return true; 17439 } 17440 // Does it contain a device admin for any user? 17441 int[] users; 17442 if (userId == UserHandle.USER_ALL) { 17443 users = sUserManager.getUserIds(); 17444 } else { 17445 users = new int[]{userId}; 17446 } 17447 for (int i = 0; i < users.length; ++i) { 17448 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17449 return true; 17450 } 17451 } 17452 } 17453 } catch (RemoteException e) { 17454 } 17455 return false; 17456 } 17457 17458 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17459 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17460 } 17461 17462 /** 17463 * This method is an internal method that could be get invoked either 17464 * to delete an installed package or to clean up a failed installation. 17465 * After deleting an installed package, a broadcast is sent to notify any 17466 * listeners that the package has been removed. For cleaning up a failed 17467 * installation, the broadcast is not necessary since the package's 17468 * installation wouldn't have sent the initial broadcast either 17469 * The key steps in deleting a package are 17470 * deleting the package information in internal structures like mPackages, 17471 * deleting the packages base directories through installd 17472 * updating mSettings to reflect current status 17473 * persisting settings for later use 17474 * sending a broadcast if necessary 17475 */ 17476 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17477 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17478 final boolean res; 17479 17480 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17481 ? UserHandle.USER_ALL : userId; 17482 17483 if (isPackageDeviceAdmin(packageName, removeUser)) { 17484 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17485 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17486 } 17487 17488 PackageSetting uninstalledPs = null; 17489 PackageParser.Package pkg = null; 17490 17491 // for the uninstall-updates case and restricted profiles, remember the per- 17492 // user handle installed state 17493 int[] allUsers; 17494 synchronized (mPackages) { 17495 uninstalledPs = mSettings.mPackages.get(packageName); 17496 if (uninstalledPs == null) { 17497 Slog.w(TAG, "Not removing non-existent package " + packageName); 17498 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17499 } 17500 17501 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17502 && uninstalledPs.versionCode != versionCode) { 17503 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17504 + uninstalledPs.versionCode + " != " + versionCode); 17505 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17506 } 17507 17508 // Static shared libs can be declared by any package, so let us not 17509 // allow removing a package if it provides a lib others depend on. 17510 pkg = mPackages.get(packageName); 17511 17512 allUsers = sUserManager.getUserIds(); 17513 17514 if (pkg != null && pkg.staticSharedLibName != null) { 17515 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17516 pkg.staticSharedLibVersion); 17517 if (libEntry != null) { 17518 for (int currUserId : allUsers) { 17519 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17520 continue; 17521 } 17522 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17523 libEntry.info, 0, currUserId); 17524 if (!ArrayUtils.isEmpty(libClientPackages)) { 17525 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17526 + " hosting lib " + libEntry.info.getName() + " version " 17527 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17528 + " for user " + currUserId); 17529 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17530 } 17531 } 17532 } 17533 } 17534 17535 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17536 } 17537 17538 final int freezeUser; 17539 if (isUpdatedSystemApp(uninstalledPs) 17540 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17541 // We're downgrading a system app, which will apply to all users, so 17542 // freeze them all during the downgrade 17543 freezeUser = UserHandle.USER_ALL; 17544 } else { 17545 freezeUser = removeUser; 17546 } 17547 17548 synchronized (mInstallLock) { 17549 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17550 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17551 deleteFlags, "deletePackageX")) { 17552 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17553 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17554 } 17555 synchronized (mPackages) { 17556 if (res) { 17557 if (pkg != null) { 17558 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17559 } 17560 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17561 updateInstantAppInstallerLocked(packageName); 17562 } 17563 } 17564 } 17565 17566 if (res) { 17567 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17568 info.sendPackageRemovedBroadcasts(killApp); 17569 info.sendSystemPackageUpdatedBroadcasts(); 17570 info.sendSystemPackageAppearedBroadcasts(); 17571 } 17572 // Force a gc here. 17573 Runtime.getRuntime().gc(); 17574 // Delete the resources here after sending the broadcast to let 17575 // other processes clean up before deleting resources. 17576 if (info.args != null) { 17577 synchronized (mInstallLock) { 17578 info.args.doPostDeleteLI(true); 17579 } 17580 } 17581 17582 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17583 } 17584 17585 static class PackageRemovedInfo { 17586 final PackageSender packageSender; 17587 String removedPackage; 17588 String installerPackageName; 17589 int uid = -1; 17590 int removedAppId = -1; 17591 int[] origUsers; 17592 int[] removedUsers = null; 17593 int[] broadcastUsers = null; 17594 int[] instantUserIds = null; 17595 SparseArray<Integer> installReasons; 17596 boolean isRemovedPackageSystemUpdate = false; 17597 boolean isUpdate; 17598 boolean dataRemoved; 17599 boolean removedForAllUsers; 17600 boolean isStaticSharedLib; 17601 // Clean up resources deleted packages. 17602 InstallArgs args = null; 17603 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17604 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17605 17606 PackageRemovedInfo(PackageSender packageSender) { 17607 this.packageSender = packageSender; 17608 } 17609 17610 void sendPackageRemovedBroadcasts(boolean killApp) { 17611 sendPackageRemovedBroadcastInternal(killApp); 17612 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17613 for (int i = 0; i < childCount; i++) { 17614 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17615 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17616 } 17617 } 17618 17619 void sendSystemPackageUpdatedBroadcasts() { 17620 if (isRemovedPackageSystemUpdate) { 17621 sendSystemPackageUpdatedBroadcastsInternal(); 17622 final int childCount = (removedChildPackages != null) 17623 ? removedChildPackages.size() : 0; 17624 for (int i = 0; i < childCount; i++) { 17625 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17626 if (childInfo.isRemovedPackageSystemUpdate) { 17627 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17628 } 17629 } 17630 } 17631 } 17632 17633 void sendSystemPackageAppearedBroadcasts() { 17634 final int packageCount = (appearedChildPackages != null) 17635 ? appearedChildPackages.size() : 0; 17636 for (int i = 0; i < packageCount; i++) { 17637 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17638 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17639 true /*sendBootCompleted*/, false /*startReceiver*/, 17640 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17641 } 17642 } 17643 17644 private void sendSystemPackageUpdatedBroadcastsInternal() { 17645 Bundle extras = new Bundle(2); 17646 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17647 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17648 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17649 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17650 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17651 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17652 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17653 null, null, 0, removedPackage, null, null, null); 17654 if (installerPackageName != null) { 17655 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17656 removedPackage, extras, 0 /*flags*/, 17657 installerPackageName, null, null, null); 17658 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17659 removedPackage, extras, 0 /*flags*/, 17660 installerPackageName, null, null, null); 17661 } 17662 } 17663 17664 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17665 // Don't send static shared library removal broadcasts as these 17666 // libs are visible only the the apps that depend on them an one 17667 // cannot remove the library if it has a dependency. 17668 if (isStaticSharedLib) { 17669 return; 17670 } 17671 Bundle extras = new Bundle(2); 17672 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17673 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17674 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17675 if (isUpdate || isRemovedPackageSystemUpdate) { 17676 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17677 } 17678 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17679 if (removedPackage != null) { 17680 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17681 removedPackage, extras, 0, null /*targetPackage*/, null, 17682 broadcastUsers, instantUserIds); 17683 if (installerPackageName != null) { 17684 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17685 removedPackage, extras, 0 /*flags*/, 17686 installerPackageName, null, broadcastUsers, instantUserIds); 17687 } 17688 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17689 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17690 removedPackage, extras, 17691 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17692 null, null, broadcastUsers, instantUserIds); 17693 packageSender.notifyPackageRemoved(removedPackage); 17694 } 17695 } 17696 if (removedAppId >= 0) { 17697 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17698 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17699 null, null, broadcastUsers, instantUserIds); 17700 } 17701 } 17702 17703 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17704 removedUsers = userIds; 17705 if (removedUsers == null) { 17706 broadcastUsers = null; 17707 return; 17708 } 17709 17710 broadcastUsers = EMPTY_INT_ARRAY; 17711 instantUserIds = EMPTY_INT_ARRAY; 17712 for (int i = userIds.length - 1; i >= 0; --i) { 17713 final int userId = userIds[i]; 17714 if (deletedPackageSetting.getInstantApp(userId)) { 17715 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 17716 } else { 17717 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17718 } 17719 } 17720 } 17721 } 17722 17723 /* 17724 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17725 * flag is not set, the data directory is removed as well. 17726 * make sure this flag is set for partially installed apps. If not its meaningless to 17727 * delete a partially installed application. 17728 */ 17729 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17730 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17731 String packageName = ps.name; 17732 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17733 // Retrieve object to delete permissions for shared user later on 17734 final PackageParser.Package deletedPkg; 17735 final PackageSetting deletedPs; 17736 // reader 17737 synchronized (mPackages) { 17738 deletedPkg = mPackages.get(packageName); 17739 deletedPs = mSettings.mPackages.get(packageName); 17740 if (outInfo != null) { 17741 outInfo.removedPackage = packageName; 17742 outInfo.installerPackageName = ps.installerPackageName; 17743 outInfo.isStaticSharedLib = deletedPkg != null 17744 && deletedPkg.staticSharedLibName != null; 17745 outInfo.populateUsers(deletedPs == null ? null 17746 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17747 } 17748 } 17749 17750 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17751 17752 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17753 final PackageParser.Package resolvedPkg; 17754 if (deletedPkg != null) { 17755 resolvedPkg = deletedPkg; 17756 } else { 17757 // We don't have a parsed package when it lives on an ejected 17758 // adopted storage device, so fake something together 17759 resolvedPkg = new PackageParser.Package(ps.name); 17760 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17761 } 17762 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17763 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17764 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17765 if (outInfo != null) { 17766 outInfo.dataRemoved = true; 17767 } 17768 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17769 } 17770 17771 int removedAppId = -1; 17772 17773 // writer 17774 synchronized (mPackages) { 17775 boolean installedStateChanged = false; 17776 if (deletedPs != null) { 17777 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17778 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17779 clearDefaultBrowserIfNeeded(packageName); 17780 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17781 removedAppId = mSettings.removePackageLPw(packageName); 17782 if (outInfo != null) { 17783 outInfo.removedAppId = removedAppId; 17784 } 17785 mPermissionManager.updatePermissions( 17786 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17787 if (deletedPs.sharedUser != null) { 17788 // Remove permissions associated with package. Since runtime 17789 // permissions are per user we have to kill the removed package 17790 // or packages running under the shared user of the removed 17791 // package if revoking the permissions requested only by the removed 17792 // package is successful and this causes a change in gids. 17793 for (int userId : UserManagerService.getInstance().getUserIds()) { 17794 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17795 userId); 17796 if (userIdToKill == UserHandle.USER_ALL 17797 || userIdToKill >= UserHandle.USER_SYSTEM) { 17798 // If gids changed for this user, kill all affected packages. 17799 mHandler.post(new Runnable() { 17800 @Override 17801 public void run() { 17802 // This has to happen with no lock held. 17803 killApplication(deletedPs.name, deletedPs.appId, 17804 KILL_APP_REASON_GIDS_CHANGED); 17805 } 17806 }); 17807 break; 17808 } 17809 } 17810 } 17811 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17812 } 17813 // make sure to preserve per-user disabled state if this removal was just 17814 // a downgrade of a system app to the factory package 17815 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17816 if (DEBUG_REMOVE) { 17817 Slog.d(TAG, "Propagating install state across downgrade"); 17818 } 17819 for (int userId : allUserHandles) { 17820 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17821 if (DEBUG_REMOVE) { 17822 Slog.d(TAG, " user " + userId + " => " + installed); 17823 } 17824 if (installed != ps.getInstalled(userId)) { 17825 installedStateChanged = true; 17826 } 17827 ps.setInstalled(installed, userId); 17828 } 17829 } 17830 } 17831 // can downgrade to reader 17832 if (writeSettings) { 17833 // Save settings now 17834 mSettings.writeLPr(); 17835 } 17836 if (installedStateChanged) { 17837 mSettings.writeKernelMappingLPr(ps); 17838 } 17839 } 17840 if (removedAppId != -1) { 17841 // A user ID was deleted here. Go through all users and remove it 17842 // from KeyStore. 17843 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17844 } 17845 } 17846 17847 static boolean locationIsPrivileged(String path) { 17848 try { 17849 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 17850 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 17851 return path.startsWith(privilegedAppDir.getCanonicalPath()) 17852 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 17853 } catch (IOException e) { 17854 Slog.e(TAG, "Unable to access code path " + path); 17855 } 17856 return false; 17857 } 17858 17859 static boolean locationIsOem(String path) { 17860 try { 17861 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 17862 } catch (IOException e) { 17863 Slog.e(TAG, "Unable to access code path " + path); 17864 } 17865 return false; 17866 } 17867 17868 static boolean locationIsVendor(String path) { 17869 try { 17870 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 17871 } catch (IOException e) { 17872 Slog.e(TAG, "Unable to access code path " + path); 17873 } 17874 return false; 17875 } 17876 17877 /* 17878 * Tries to delete system package. 17879 */ 17880 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17881 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17882 boolean writeSettings) { 17883 if (deletedPs.parentPackageName != null) { 17884 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17885 return false; 17886 } 17887 17888 final boolean applyUserRestrictions 17889 = (allUserHandles != null) && (outInfo.origUsers != null); 17890 final PackageSetting disabledPs; 17891 // Confirm if the system package has been updated 17892 // An updated system app can be deleted. This will also have to restore 17893 // the system pkg from system partition 17894 // reader 17895 synchronized (mPackages) { 17896 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17897 } 17898 17899 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17900 + " disabledPs=" + disabledPs); 17901 17902 if (disabledPs == null) { 17903 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17904 return false; 17905 } else if (DEBUG_REMOVE) { 17906 Slog.d(TAG, "Deleting system pkg from data partition"); 17907 } 17908 17909 if (DEBUG_REMOVE) { 17910 if (applyUserRestrictions) { 17911 Slog.d(TAG, "Remembering install states:"); 17912 for (int userId : allUserHandles) { 17913 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17914 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17915 } 17916 } 17917 } 17918 17919 // Delete the updated package 17920 outInfo.isRemovedPackageSystemUpdate = true; 17921 if (outInfo.removedChildPackages != null) { 17922 final int childCount = (deletedPs.childPackageNames != null) 17923 ? deletedPs.childPackageNames.size() : 0; 17924 for (int i = 0; i < childCount; i++) { 17925 String childPackageName = deletedPs.childPackageNames.get(i); 17926 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17927 .contains(childPackageName)) { 17928 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17929 childPackageName); 17930 if (childInfo != null) { 17931 childInfo.isRemovedPackageSystemUpdate = true; 17932 } 17933 } 17934 } 17935 } 17936 17937 if (disabledPs.versionCode < deletedPs.versionCode) { 17938 // Delete data for downgrades 17939 flags &= ~PackageManager.DELETE_KEEP_DATA; 17940 } else { 17941 // Preserve data by setting flag 17942 flags |= PackageManager.DELETE_KEEP_DATA; 17943 } 17944 17945 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17946 outInfo, writeSettings, disabledPs.pkg); 17947 if (!ret) { 17948 return false; 17949 } 17950 17951 // writer 17952 synchronized (mPackages) { 17953 // NOTE: The system package always needs to be enabled; even if it's for 17954 // a compressed stub. If we don't, installing the system package fails 17955 // during scan [scanning checks the disabled packages]. We will reverse 17956 // this later, after we've "installed" the stub. 17957 // Reinstate the old system package 17958 enableSystemPackageLPw(disabledPs.pkg); 17959 // Remove any native libraries from the upgraded package. 17960 removeNativeBinariesLI(deletedPs); 17961 } 17962 17963 // Install the system package 17964 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17965 try { 17966 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 17967 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 17968 } catch (PackageManagerException e) { 17969 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17970 + e.getMessage()); 17971 return false; 17972 } finally { 17973 if (disabledPs.pkg.isStub) { 17974 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 17975 } 17976 } 17977 return true; 17978 } 17979 17980 /** 17981 * Installs a package that's already on the system partition. 17982 */ 17983 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 17984 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 17985 @Nullable PermissionsState origPermissionState, boolean writeSettings) 17986 throws PackageManagerException { 17987 @ParseFlags int parseFlags = 17988 mDefParseFlags 17989 | PackageParser.PARSE_MUST_BE_APK 17990 | PackageParser.PARSE_IS_SYSTEM_DIR; 17991 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 17992 if (isPrivileged || locationIsPrivileged(codePathString)) { 17993 scanFlags |= SCAN_AS_PRIVILEGED; 17994 } 17995 if (locationIsOem(codePathString)) { 17996 scanFlags |= SCAN_AS_OEM; 17997 } 17998 if (locationIsVendor(codePathString)) { 17999 scanFlags |= SCAN_AS_VENDOR; 18000 } 18001 18002 final File codePath = new File(codePathString); 18003 final PackageParser.Package pkg = 18004 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18005 18006 try { 18007 // update shared libraries for the newly re-installed system package 18008 updateSharedLibrariesLPr(pkg, null); 18009 } catch (PackageManagerException e) { 18010 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18011 } 18012 18013 prepareAppDataAfterInstallLIF(pkg); 18014 18015 // writer 18016 synchronized (mPackages) { 18017 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18018 18019 // Propagate the permissions state as we do not want to drop on the floor 18020 // runtime permissions. The update permissions method below will take 18021 // care of removing obsolete permissions and grant install permissions. 18022 if (origPermissionState != null) { 18023 ps.getPermissionsState().copyFrom(origPermissionState); 18024 } 18025 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18026 mPermissionCallback); 18027 18028 final boolean applyUserRestrictions 18029 = (allUserHandles != null) && (origUserHandles != null); 18030 if (applyUserRestrictions) { 18031 boolean installedStateChanged = false; 18032 if (DEBUG_REMOVE) { 18033 Slog.d(TAG, "Propagating install state across reinstall"); 18034 } 18035 for (int userId : allUserHandles) { 18036 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18037 if (DEBUG_REMOVE) { 18038 Slog.d(TAG, " user " + userId + " => " + installed); 18039 } 18040 if (installed != ps.getInstalled(userId)) { 18041 installedStateChanged = true; 18042 } 18043 ps.setInstalled(installed, userId); 18044 18045 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18046 } 18047 // Regardless of writeSettings we need to ensure that this restriction 18048 // state propagation is persisted 18049 mSettings.writeAllUsersPackageRestrictionsLPr(); 18050 if (installedStateChanged) { 18051 mSettings.writeKernelMappingLPr(ps); 18052 } 18053 } 18054 // can downgrade to reader here 18055 if (writeSettings) { 18056 mSettings.writeLPr(); 18057 } 18058 } 18059 return pkg; 18060 } 18061 18062 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18063 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18064 PackageRemovedInfo outInfo, boolean writeSettings, 18065 PackageParser.Package replacingPackage) { 18066 synchronized (mPackages) { 18067 if (outInfo != null) { 18068 outInfo.uid = ps.appId; 18069 } 18070 18071 if (outInfo != null && outInfo.removedChildPackages != null) { 18072 final int childCount = (ps.childPackageNames != null) 18073 ? ps.childPackageNames.size() : 0; 18074 for (int i = 0; i < childCount; i++) { 18075 String childPackageName = ps.childPackageNames.get(i); 18076 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18077 if (childPs == null) { 18078 return false; 18079 } 18080 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18081 childPackageName); 18082 if (childInfo != null) { 18083 childInfo.uid = childPs.appId; 18084 } 18085 } 18086 } 18087 } 18088 18089 // Delete package data from internal structures and also remove data if flag is set 18090 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18091 18092 // Delete the child packages data 18093 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18094 for (int i = 0; i < childCount; i++) { 18095 PackageSetting childPs; 18096 synchronized (mPackages) { 18097 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18098 } 18099 if (childPs != null) { 18100 PackageRemovedInfo childOutInfo = (outInfo != null 18101 && outInfo.removedChildPackages != null) 18102 ? outInfo.removedChildPackages.get(childPs.name) : null; 18103 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18104 && (replacingPackage != null 18105 && !replacingPackage.hasChildPackage(childPs.name)) 18106 ? flags & ~DELETE_KEEP_DATA : flags; 18107 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18108 deleteFlags, writeSettings); 18109 } 18110 } 18111 18112 // Delete application code and resources only for parent packages 18113 if (ps.parentPackageName == null) { 18114 if (deleteCodeAndResources && (outInfo != null)) { 18115 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18116 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18117 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18118 } 18119 } 18120 18121 return true; 18122 } 18123 18124 @Override 18125 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18126 int userId) { 18127 mContext.enforceCallingOrSelfPermission( 18128 android.Manifest.permission.DELETE_PACKAGES, null); 18129 synchronized (mPackages) { 18130 // Cannot block uninstall of static shared libs as they are 18131 // considered a part of the using app (emulating static linking). 18132 // Also static libs are installed always on internal storage. 18133 PackageParser.Package pkg = mPackages.get(packageName); 18134 if (pkg != null && pkg.staticSharedLibName != null) { 18135 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18136 + " providing static shared library: " + pkg.staticSharedLibName); 18137 return false; 18138 } 18139 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18140 mSettings.writePackageRestrictionsLPr(userId); 18141 } 18142 return true; 18143 } 18144 18145 @Override 18146 public boolean getBlockUninstallForUser(String packageName, int userId) { 18147 synchronized (mPackages) { 18148 final PackageSetting ps = mSettings.mPackages.get(packageName); 18149 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18150 return false; 18151 } 18152 return mSettings.getBlockUninstallLPr(userId, packageName); 18153 } 18154 } 18155 18156 @Override 18157 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18158 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18159 synchronized (mPackages) { 18160 PackageSetting ps = mSettings.mPackages.get(packageName); 18161 if (ps == null) { 18162 Log.w(TAG, "Package doesn't exist: " + packageName); 18163 return false; 18164 } 18165 if (systemUserApp) { 18166 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18167 } else { 18168 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18169 } 18170 mSettings.writeLPr(); 18171 } 18172 return true; 18173 } 18174 18175 /* 18176 * This method handles package deletion in general 18177 */ 18178 private boolean deletePackageLIF(String packageName, UserHandle user, 18179 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18180 PackageRemovedInfo outInfo, boolean writeSettings, 18181 PackageParser.Package replacingPackage) { 18182 if (packageName == null) { 18183 Slog.w(TAG, "Attempt to delete null packageName."); 18184 return false; 18185 } 18186 18187 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18188 18189 PackageSetting ps; 18190 synchronized (mPackages) { 18191 ps = mSettings.mPackages.get(packageName); 18192 if (ps == null) { 18193 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18194 return false; 18195 } 18196 18197 if (ps.parentPackageName != null && (!isSystemApp(ps) 18198 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18199 if (DEBUG_REMOVE) { 18200 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18201 + ((user == null) ? UserHandle.USER_ALL : user)); 18202 } 18203 final int removedUserId = (user != null) ? user.getIdentifier() 18204 : UserHandle.USER_ALL; 18205 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18206 return false; 18207 } 18208 markPackageUninstalledForUserLPw(ps, user); 18209 scheduleWritePackageRestrictionsLocked(user); 18210 return true; 18211 } 18212 } 18213 18214 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18215 && user.getIdentifier() != UserHandle.USER_ALL)) { 18216 // The caller is asking that the package only be deleted for a single 18217 // user. To do this, we just mark its uninstalled state and delete 18218 // its data. If this is a system app, we only allow this to happen if 18219 // they have set the special DELETE_SYSTEM_APP which requests different 18220 // semantics than normal for uninstalling system apps. 18221 markPackageUninstalledForUserLPw(ps, user); 18222 18223 if (!isSystemApp(ps)) { 18224 // Do not uninstall the APK if an app should be cached 18225 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18226 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18227 // Other user still have this package installed, so all 18228 // we need to do is clear this user's data and save that 18229 // it is uninstalled. 18230 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18231 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18232 return false; 18233 } 18234 scheduleWritePackageRestrictionsLocked(user); 18235 return true; 18236 } else { 18237 // We need to set it back to 'installed' so the uninstall 18238 // broadcasts will be sent correctly. 18239 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18240 ps.setInstalled(true, user.getIdentifier()); 18241 mSettings.writeKernelMappingLPr(ps); 18242 } 18243 } else { 18244 // This is a system app, so we assume that the 18245 // other users still have this package installed, so all 18246 // we need to do is clear this user's data and save that 18247 // it is uninstalled. 18248 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18249 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18250 return false; 18251 } 18252 scheduleWritePackageRestrictionsLocked(user); 18253 return true; 18254 } 18255 } 18256 18257 // If we are deleting a composite package for all users, keep track 18258 // of result for each child. 18259 if (ps.childPackageNames != null && outInfo != null) { 18260 synchronized (mPackages) { 18261 final int childCount = ps.childPackageNames.size(); 18262 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18263 for (int i = 0; i < childCount; i++) { 18264 String childPackageName = ps.childPackageNames.get(i); 18265 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18266 childInfo.removedPackage = childPackageName; 18267 childInfo.installerPackageName = ps.installerPackageName; 18268 outInfo.removedChildPackages.put(childPackageName, childInfo); 18269 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18270 if (childPs != null) { 18271 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18272 } 18273 } 18274 } 18275 } 18276 18277 boolean ret = false; 18278 if (isSystemApp(ps)) { 18279 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18280 // When an updated system application is deleted we delete the existing resources 18281 // as well and fall back to existing code in system partition 18282 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18283 } else { 18284 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18285 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18286 outInfo, writeSettings, replacingPackage); 18287 } 18288 18289 // Take a note whether we deleted the package for all users 18290 if (outInfo != null) { 18291 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18292 if (outInfo.removedChildPackages != null) { 18293 synchronized (mPackages) { 18294 final int childCount = outInfo.removedChildPackages.size(); 18295 for (int i = 0; i < childCount; i++) { 18296 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18297 if (childInfo != null) { 18298 childInfo.removedForAllUsers = mPackages.get( 18299 childInfo.removedPackage) == null; 18300 } 18301 } 18302 } 18303 } 18304 // If we uninstalled an update to a system app there may be some 18305 // child packages that appeared as they are declared in the system 18306 // app but were not declared in the update. 18307 if (isSystemApp(ps)) { 18308 synchronized (mPackages) { 18309 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18310 final int childCount = (updatedPs.childPackageNames != null) 18311 ? updatedPs.childPackageNames.size() : 0; 18312 for (int i = 0; i < childCount; i++) { 18313 String childPackageName = updatedPs.childPackageNames.get(i); 18314 if (outInfo.removedChildPackages == null 18315 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18316 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18317 if (childPs == null) { 18318 continue; 18319 } 18320 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18321 installRes.name = childPackageName; 18322 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18323 installRes.pkg = mPackages.get(childPackageName); 18324 installRes.uid = childPs.pkg.applicationInfo.uid; 18325 if (outInfo.appearedChildPackages == null) { 18326 outInfo.appearedChildPackages = new ArrayMap<>(); 18327 } 18328 outInfo.appearedChildPackages.put(childPackageName, installRes); 18329 } 18330 } 18331 } 18332 } 18333 } 18334 18335 return ret; 18336 } 18337 18338 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18339 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18340 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18341 for (int nextUserId : userIds) { 18342 if (DEBUG_REMOVE) { 18343 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18344 } 18345 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18346 false /*installed*/, 18347 true /*stopped*/, 18348 true /*notLaunched*/, 18349 false /*hidden*/, 18350 false /*suspended*/, 18351 false /*instantApp*/, 18352 false /*virtualPreload*/, 18353 null /*lastDisableAppCaller*/, 18354 null /*enabledComponents*/, 18355 null /*disabledComponents*/, 18356 ps.readUserState(nextUserId).domainVerificationStatus, 18357 0, PackageManager.INSTALL_REASON_UNKNOWN, 18358 null /*harmfulAppWarning*/); 18359 } 18360 mSettings.writeKernelMappingLPr(ps); 18361 } 18362 18363 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18364 PackageRemovedInfo outInfo) { 18365 final PackageParser.Package pkg; 18366 synchronized (mPackages) { 18367 pkg = mPackages.get(ps.name); 18368 } 18369 18370 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18371 : new int[] {userId}; 18372 for (int nextUserId : userIds) { 18373 if (DEBUG_REMOVE) { 18374 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18375 + nextUserId); 18376 } 18377 18378 destroyAppDataLIF(pkg, userId, 18379 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18380 destroyAppProfilesLIF(pkg, userId); 18381 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18382 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18383 schedulePackageCleaning(ps.name, nextUserId, false); 18384 synchronized (mPackages) { 18385 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18386 scheduleWritePackageRestrictionsLocked(nextUserId); 18387 } 18388 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18389 } 18390 } 18391 18392 if (outInfo != null) { 18393 outInfo.removedPackage = ps.name; 18394 outInfo.installerPackageName = ps.installerPackageName; 18395 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18396 outInfo.removedAppId = ps.appId; 18397 outInfo.removedUsers = userIds; 18398 outInfo.broadcastUsers = userIds; 18399 } 18400 18401 return true; 18402 } 18403 18404 private final class ClearStorageConnection implements ServiceConnection { 18405 IMediaContainerService mContainerService; 18406 18407 @Override 18408 public void onServiceConnected(ComponentName name, IBinder service) { 18409 synchronized (this) { 18410 mContainerService = IMediaContainerService.Stub 18411 .asInterface(Binder.allowBlocking(service)); 18412 notifyAll(); 18413 } 18414 } 18415 18416 @Override 18417 public void onServiceDisconnected(ComponentName name) { 18418 } 18419 } 18420 18421 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18422 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18423 18424 final boolean mounted; 18425 if (Environment.isExternalStorageEmulated()) { 18426 mounted = true; 18427 } else { 18428 final String status = Environment.getExternalStorageState(); 18429 18430 mounted = status.equals(Environment.MEDIA_MOUNTED) 18431 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18432 } 18433 18434 if (!mounted) { 18435 return; 18436 } 18437 18438 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18439 int[] users; 18440 if (userId == UserHandle.USER_ALL) { 18441 users = sUserManager.getUserIds(); 18442 } else { 18443 users = new int[] { userId }; 18444 } 18445 final ClearStorageConnection conn = new ClearStorageConnection(); 18446 if (mContext.bindServiceAsUser( 18447 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18448 try { 18449 for (int curUser : users) { 18450 long timeout = SystemClock.uptimeMillis() + 5000; 18451 synchronized (conn) { 18452 long now; 18453 while (conn.mContainerService == null && 18454 (now = SystemClock.uptimeMillis()) < timeout) { 18455 try { 18456 conn.wait(timeout - now); 18457 } catch (InterruptedException e) { 18458 } 18459 } 18460 } 18461 if (conn.mContainerService == null) { 18462 return; 18463 } 18464 18465 final UserEnvironment userEnv = new UserEnvironment(curUser); 18466 clearDirectory(conn.mContainerService, 18467 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18468 if (allData) { 18469 clearDirectory(conn.mContainerService, 18470 userEnv.buildExternalStorageAppDataDirs(packageName)); 18471 clearDirectory(conn.mContainerService, 18472 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18473 } 18474 } 18475 } finally { 18476 mContext.unbindService(conn); 18477 } 18478 } 18479 } 18480 18481 @Override 18482 public void clearApplicationProfileData(String packageName) { 18483 enforceSystemOrRoot("Only the system can clear all profile data"); 18484 18485 final PackageParser.Package pkg; 18486 synchronized (mPackages) { 18487 pkg = mPackages.get(packageName); 18488 } 18489 18490 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18491 synchronized (mInstallLock) { 18492 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18493 } 18494 } 18495 } 18496 18497 @Override 18498 public void clearApplicationUserData(final String packageName, 18499 final IPackageDataObserver observer, final int userId) { 18500 mContext.enforceCallingOrSelfPermission( 18501 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18502 18503 final int callingUid = Binder.getCallingUid(); 18504 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18505 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18506 18507 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18508 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18509 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18510 throw new SecurityException("Cannot clear data for a protected package: " 18511 + packageName); 18512 } 18513 // Queue up an async operation since the package deletion may take a little while. 18514 mHandler.post(new Runnable() { 18515 public void run() { 18516 mHandler.removeCallbacks(this); 18517 final boolean succeeded; 18518 if (!filterApp) { 18519 try (PackageFreezer freezer = freezePackage(packageName, 18520 "clearApplicationUserData")) { 18521 synchronized (mInstallLock) { 18522 succeeded = clearApplicationUserDataLIF(packageName, userId); 18523 } 18524 clearExternalStorageDataSync(packageName, userId, true); 18525 synchronized (mPackages) { 18526 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18527 packageName, userId); 18528 } 18529 } 18530 if (succeeded) { 18531 // invoke DeviceStorageMonitor's update method to clear any notifications 18532 DeviceStorageMonitorInternal dsm = LocalServices 18533 .getService(DeviceStorageMonitorInternal.class); 18534 if (dsm != null) { 18535 dsm.checkMemory(); 18536 } 18537 } 18538 } else { 18539 succeeded = false; 18540 } 18541 if (observer != null) { 18542 try { 18543 observer.onRemoveCompleted(packageName, succeeded); 18544 } catch (RemoteException e) { 18545 Log.i(TAG, "Observer no longer exists."); 18546 } 18547 } //end if observer 18548 } //end run 18549 }); 18550 } 18551 18552 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18553 if (packageName == null) { 18554 Slog.w(TAG, "Attempt to delete null packageName."); 18555 return false; 18556 } 18557 18558 // Try finding details about the requested package 18559 PackageParser.Package pkg; 18560 synchronized (mPackages) { 18561 pkg = mPackages.get(packageName); 18562 if (pkg == null) { 18563 final PackageSetting ps = mSettings.mPackages.get(packageName); 18564 if (ps != null) { 18565 pkg = ps.pkg; 18566 } 18567 } 18568 18569 if (pkg == null) { 18570 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18571 return false; 18572 } 18573 18574 PackageSetting ps = (PackageSetting) pkg.mExtras; 18575 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18576 } 18577 18578 clearAppDataLIF(pkg, userId, 18579 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18580 18581 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18582 removeKeystoreDataIfNeeded(userId, appId); 18583 18584 UserManagerInternal umInternal = getUserManagerInternal(); 18585 final int flags; 18586 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18587 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18588 } else if (umInternal.isUserRunning(userId)) { 18589 flags = StorageManager.FLAG_STORAGE_DE; 18590 } else { 18591 flags = 0; 18592 } 18593 prepareAppDataContentsLIF(pkg, userId, flags); 18594 18595 return true; 18596 } 18597 18598 /** 18599 * Reverts user permission state changes (permissions and flags) in 18600 * all packages for a given user. 18601 * 18602 * @param userId The device user for which to do a reset. 18603 */ 18604 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18605 final int packageCount = mPackages.size(); 18606 for (int i = 0; i < packageCount; i++) { 18607 PackageParser.Package pkg = mPackages.valueAt(i); 18608 PackageSetting ps = (PackageSetting) pkg.mExtras; 18609 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18610 } 18611 } 18612 18613 private void resetNetworkPolicies(int userId) { 18614 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18615 } 18616 18617 /** 18618 * Reverts user permission state changes (permissions and flags). 18619 * 18620 * @param ps The package for which to reset. 18621 * @param userId The device user for which to do a reset. 18622 */ 18623 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18624 final PackageSetting ps, final int userId) { 18625 if (ps.pkg == null) { 18626 return; 18627 } 18628 18629 // These are flags that can change base on user actions. 18630 final int userSettableMask = FLAG_PERMISSION_USER_SET 18631 | FLAG_PERMISSION_USER_FIXED 18632 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18633 | FLAG_PERMISSION_REVIEW_REQUIRED; 18634 18635 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18636 | FLAG_PERMISSION_POLICY_FIXED; 18637 18638 boolean writeInstallPermissions = false; 18639 boolean writeRuntimePermissions = false; 18640 18641 final int permissionCount = ps.pkg.requestedPermissions.size(); 18642 for (int i = 0; i < permissionCount; i++) { 18643 final String permName = ps.pkg.requestedPermissions.get(i); 18644 final BasePermission bp = 18645 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18646 if (bp == null) { 18647 continue; 18648 } 18649 18650 // If shared user we just reset the state to which only this app contributed. 18651 if (ps.sharedUser != null) { 18652 boolean used = false; 18653 final int packageCount = ps.sharedUser.packages.size(); 18654 for (int j = 0; j < packageCount; j++) { 18655 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18656 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18657 && pkg.pkg.requestedPermissions.contains(permName)) { 18658 used = true; 18659 break; 18660 } 18661 } 18662 if (used) { 18663 continue; 18664 } 18665 } 18666 18667 final PermissionsState permissionsState = ps.getPermissionsState(); 18668 18669 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18670 18671 // Always clear the user settable flags. 18672 final boolean hasInstallState = 18673 permissionsState.getInstallPermissionState(permName) != null; 18674 // If permission review is enabled and this is a legacy app, mark the 18675 // permission as requiring a review as this is the initial state. 18676 int flags = 0; 18677 if (mSettings.mPermissions.mPermissionReviewRequired 18678 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18679 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18680 } 18681 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18682 if (hasInstallState) { 18683 writeInstallPermissions = true; 18684 } else { 18685 writeRuntimePermissions = true; 18686 } 18687 } 18688 18689 // Below is only runtime permission handling. 18690 if (!bp.isRuntime()) { 18691 continue; 18692 } 18693 18694 // Never clobber system or policy. 18695 if ((oldFlags & policyOrSystemFlags) != 0) { 18696 continue; 18697 } 18698 18699 // If this permission was granted by default, make sure it is. 18700 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18701 if (permissionsState.grantRuntimePermission(bp, userId) 18702 != PERMISSION_OPERATION_FAILURE) { 18703 writeRuntimePermissions = true; 18704 } 18705 // If permission review is enabled the permissions for a legacy apps 18706 // are represented as constantly granted runtime ones, so don't revoke. 18707 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18708 // Otherwise, reset the permission. 18709 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18710 switch (revokeResult) { 18711 case PERMISSION_OPERATION_SUCCESS: 18712 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18713 writeRuntimePermissions = true; 18714 final int appId = ps.appId; 18715 mHandler.post(new Runnable() { 18716 @Override 18717 public void run() { 18718 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18719 } 18720 }); 18721 } break; 18722 } 18723 } 18724 } 18725 18726 // Synchronously write as we are taking permissions away. 18727 if (writeRuntimePermissions) { 18728 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18729 } 18730 18731 // Synchronously write as we are taking permissions away. 18732 if (writeInstallPermissions) { 18733 mSettings.writeLPr(); 18734 } 18735 } 18736 18737 /** 18738 * Remove entries from the keystore daemon. Will only remove it if the 18739 * {@code appId} is valid. 18740 */ 18741 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18742 if (appId < 0) { 18743 return; 18744 } 18745 18746 final KeyStore keyStore = KeyStore.getInstance(); 18747 if (keyStore != null) { 18748 if (userId == UserHandle.USER_ALL) { 18749 for (final int individual : sUserManager.getUserIds()) { 18750 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18751 } 18752 } else { 18753 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18754 } 18755 } else { 18756 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18757 } 18758 } 18759 18760 @Override 18761 public void deleteApplicationCacheFiles(final String packageName, 18762 final IPackageDataObserver observer) { 18763 final int userId = UserHandle.getCallingUserId(); 18764 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18765 } 18766 18767 @Override 18768 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18769 final IPackageDataObserver observer) { 18770 final int callingUid = Binder.getCallingUid(); 18771 mContext.enforceCallingOrSelfPermission( 18772 android.Manifest.permission.DELETE_CACHE_FILES, null); 18773 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18774 /* requireFullPermission= */ true, /* checkShell= */ false, 18775 "delete application cache files"); 18776 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18777 android.Manifest.permission.ACCESS_INSTANT_APPS); 18778 18779 final PackageParser.Package pkg; 18780 synchronized (mPackages) { 18781 pkg = mPackages.get(packageName); 18782 } 18783 18784 // Queue up an async operation since the package deletion may take a little while. 18785 mHandler.post(new Runnable() { 18786 public void run() { 18787 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18788 boolean doClearData = true; 18789 if (ps != null) { 18790 final boolean targetIsInstantApp = 18791 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18792 doClearData = !targetIsInstantApp 18793 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18794 } 18795 if (doClearData) { 18796 synchronized (mInstallLock) { 18797 final int flags = StorageManager.FLAG_STORAGE_DE 18798 | StorageManager.FLAG_STORAGE_CE; 18799 // We're only clearing cache files, so we don't care if the 18800 // app is unfrozen and still able to run 18801 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18802 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18803 } 18804 clearExternalStorageDataSync(packageName, userId, false); 18805 } 18806 if (observer != null) { 18807 try { 18808 observer.onRemoveCompleted(packageName, true); 18809 } catch (RemoteException e) { 18810 Log.i(TAG, "Observer no longer exists."); 18811 } 18812 } 18813 } 18814 }); 18815 } 18816 18817 @Override 18818 public void getPackageSizeInfo(final String packageName, int userHandle, 18819 final IPackageStatsObserver observer) { 18820 throw new UnsupportedOperationException( 18821 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18822 } 18823 18824 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18825 final PackageSetting ps; 18826 synchronized (mPackages) { 18827 ps = mSettings.mPackages.get(packageName); 18828 if (ps == null) { 18829 Slog.w(TAG, "Failed to find settings for " + packageName); 18830 return false; 18831 } 18832 } 18833 18834 final String[] packageNames = { packageName }; 18835 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18836 final String[] codePaths = { ps.codePathString }; 18837 18838 try { 18839 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18840 ps.appId, ceDataInodes, codePaths, stats); 18841 18842 // For now, ignore code size of packages on system partition 18843 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18844 stats.codeSize = 0; 18845 } 18846 18847 // External clients expect these to be tracked separately 18848 stats.dataSize -= stats.cacheSize; 18849 18850 } catch (InstallerException e) { 18851 Slog.w(TAG, String.valueOf(e)); 18852 return false; 18853 } 18854 18855 return true; 18856 } 18857 18858 private int getUidTargetSdkVersionLockedLPr(int uid) { 18859 Object obj = mSettings.getUserIdLPr(uid); 18860 if (obj instanceof SharedUserSetting) { 18861 final SharedUserSetting sus = (SharedUserSetting) obj; 18862 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18863 final Iterator<PackageSetting> it = sus.packages.iterator(); 18864 while (it.hasNext()) { 18865 final PackageSetting ps = it.next(); 18866 if (ps.pkg != null) { 18867 int v = ps.pkg.applicationInfo.targetSdkVersion; 18868 if (v < vers) vers = v; 18869 } 18870 } 18871 return vers; 18872 } else if (obj instanceof PackageSetting) { 18873 final PackageSetting ps = (PackageSetting) obj; 18874 if (ps.pkg != null) { 18875 return ps.pkg.applicationInfo.targetSdkVersion; 18876 } 18877 } 18878 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18879 } 18880 18881 @Override 18882 public void addPreferredActivity(IntentFilter filter, int match, 18883 ComponentName[] set, ComponentName activity, int userId) { 18884 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18885 "Adding preferred"); 18886 } 18887 18888 private void addPreferredActivityInternal(IntentFilter filter, int match, 18889 ComponentName[] set, ComponentName activity, boolean always, int userId, 18890 String opname) { 18891 // writer 18892 int callingUid = Binder.getCallingUid(); 18893 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18894 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18895 if (filter.countActions() == 0) { 18896 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18897 return; 18898 } 18899 synchronized (mPackages) { 18900 if (mContext.checkCallingOrSelfPermission( 18901 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18902 != PackageManager.PERMISSION_GRANTED) { 18903 if (getUidTargetSdkVersionLockedLPr(callingUid) 18904 < Build.VERSION_CODES.FROYO) { 18905 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18906 + callingUid); 18907 return; 18908 } 18909 mContext.enforceCallingOrSelfPermission( 18910 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18911 } 18912 18913 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18914 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18915 + userId + ":"); 18916 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18917 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18918 scheduleWritePackageRestrictionsLocked(userId); 18919 postPreferredActivityChangedBroadcast(userId); 18920 } 18921 } 18922 18923 private void postPreferredActivityChangedBroadcast(int userId) { 18924 mHandler.post(() -> { 18925 final IActivityManager am = ActivityManager.getService(); 18926 if (am == null) { 18927 return; 18928 } 18929 18930 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18931 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18932 try { 18933 am.broadcastIntent(null, intent, null, null, 18934 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18935 null, false, false, userId); 18936 } catch (RemoteException e) { 18937 } 18938 }); 18939 } 18940 18941 @Override 18942 public void replacePreferredActivity(IntentFilter filter, int match, 18943 ComponentName[] set, ComponentName activity, int userId) { 18944 if (filter.countActions() != 1) { 18945 throw new IllegalArgumentException( 18946 "replacePreferredActivity expects filter to have only 1 action."); 18947 } 18948 if (filter.countDataAuthorities() != 0 18949 || filter.countDataPaths() != 0 18950 || filter.countDataSchemes() > 1 18951 || filter.countDataTypes() != 0) { 18952 throw new IllegalArgumentException( 18953 "replacePreferredActivity expects filter to have no data authorities, " + 18954 "paths, or types; and at most one scheme."); 18955 } 18956 18957 final int callingUid = Binder.getCallingUid(); 18958 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18959 true /* requireFullPermission */, false /* checkShell */, 18960 "replace preferred activity"); 18961 synchronized (mPackages) { 18962 if (mContext.checkCallingOrSelfPermission( 18963 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18964 != PackageManager.PERMISSION_GRANTED) { 18965 if (getUidTargetSdkVersionLockedLPr(callingUid) 18966 < Build.VERSION_CODES.FROYO) { 18967 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18968 + Binder.getCallingUid()); 18969 return; 18970 } 18971 mContext.enforceCallingOrSelfPermission( 18972 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18973 } 18974 18975 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18976 if (pir != null) { 18977 // Get all of the existing entries that exactly match this filter. 18978 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18979 if (existing != null && existing.size() == 1) { 18980 PreferredActivity cur = existing.get(0); 18981 if (DEBUG_PREFERRED) { 18982 Slog.i(TAG, "Checking replace of preferred:"); 18983 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18984 if (!cur.mPref.mAlways) { 18985 Slog.i(TAG, " -- CUR; not mAlways!"); 18986 } else { 18987 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 18988 Slog.i(TAG, " -- CUR: mSet=" 18989 + Arrays.toString(cur.mPref.mSetComponents)); 18990 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 18991 Slog.i(TAG, " -- NEW: mMatch=" 18992 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 18993 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 18994 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 18995 } 18996 } 18997 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 18998 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 18999 && cur.mPref.sameSet(set)) { 19000 // Setting the preferred activity to what it happens to be already 19001 if (DEBUG_PREFERRED) { 19002 Slog.i(TAG, "Replacing with same preferred activity " 19003 + cur.mPref.mShortComponent + " for user " 19004 + userId + ":"); 19005 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19006 } 19007 return; 19008 } 19009 } 19010 19011 if (existing != null) { 19012 if (DEBUG_PREFERRED) { 19013 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19014 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19015 } 19016 for (int i = 0; i < existing.size(); i++) { 19017 PreferredActivity pa = existing.get(i); 19018 if (DEBUG_PREFERRED) { 19019 Slog.i(TAG, "Removing existing preferred activity " 19020 + pa.mPref.mComponent + ":"); 19021 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19022 } 19023 pir.removeFilter(pa); 19024 } 19025 } 19026 } 19027 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19028 "Replacing preferred"); 19029 } 19030 } 19031 19032 @Override 19033 public void clearPackagePreferredActivities(String packageName) { 19034 final int callingUid = Binder.getCallingUid(); 19035 if (getInstantAppPackageName(callingUid) != null) { 19036 return; 19037 } 19038 // writer 19039 synchronized (mPackages) { 19040 PackageParser.Package pkg = mPackages.get(packageName); 19041 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19042 if (mContext.checkCallingOrSelfPermission( 19043 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19044 != PackageManager.PERMISSION_GRANTED) { 19045 if (getUidTargetSdkVersionLockedLPr(callingUid) 19046 < Build.VERSION_CODES.FROYO) { 19047 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19048 + callingUid); 19049 return; 19050 } 19051 mContext.enforceCallingOrSelfPermission( 19052 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19053 } 19054 } 19055 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19056 if (ps != null 19057 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19058 return; 19059 } 19060 int user = UserHandle.getCallingUserId(); 19061 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19062 scheduleWritePackageRestrictionsLocked(user); 19063 } 19064 } 19065 } 19066 19067 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19068 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19069 ArrayList<PreferredActivity> removed = null; 19070 boolean changed = false; 19071 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19072 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19073 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19074 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19075 continue; 19076 } 19077 Iterator<PreferredActivity> it = pir.filterIterator(); 19078 while (it.hasNext()) { 19079 PreferredActivity pa = it.next(); 19080 // Mark entry for removal only if it matches the package name 19081 // and the entry is of type "always". 19082 if (packageName == null || 19083 (pa.mPref.mComponent.getPackageName().equals(packageName) 19084 && pa.mPref.mAlways)) { 19085 if (removed == null) { 19086 removed = new ArrayList<PreferredActivity>(); 19087 } 19088 removed.add(pa); 19089 } 19090 } 19091 if (removed != null) { 19092 for (int j=0; j<removed.size(); j++) { 19093 PreferredActivity pa = removed.get(j); 19094 pir.removeFilter(pa); 19095 } 19096 changed = true; 19097 } 19098 } 19099 if (changed) { 19100 postPreferredActivityChangedBroadcast(userId); 19101 } 19102 return changed; 19103 } 19104 19105 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19106 private void clearIntentFilterVerificationsLPw(int userId) { 19107 final int packageCount = mPackages.size(); 19108 for (int i = 0; i < packageCount; i++) { 19109 PackageParser.Package pkg = mPackages.valueAt(i); 19110 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19111 } 19112 } 19113 19114 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19115 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19116 if (userId == UserHandle.USER_ALL) { 19117 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19118 sUserManager.getUserIds())) { 19119 for (int oneUserId : sUserManager.getUserIds()) { 19120 scheduleWritePackageRestrictionsLocked(oneUserId); 19121 } 19122 } 19123 } else { 19124 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19125 scheduleWritePackageRestrictionsLocked(userId); 19126 } 19127 } 19128 } 19129 19130 /** Clears state for all users, and touches intent filter verification policy */ 19131 void clearDefaultBrowserIfNeeded(String packageName) { 19132 for (int oneUserId : sUserManager.getUserIds()) { 19133 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19134 } 19135 } 19136 19137 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19138 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19139 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19140 if (packageName.equals(defaultBrowserPackageName)) { 19141 setDefaultBrowserPackageName(null, userId); 19142 } 19143 } 19144 } 19145 19146 @Override 19147 public void resetApplicationPreferences(int userId) { 19148 mContext.enforceCallingOrSelfPermission( 19149 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19150 final long identity = Binder.clearCallingIdentity(); 19151 // writer 19152 try { 19153 synchronized (mPackages) { 19154 clearPackagePreferredActivitiesLPw(null, userId); 19155 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19156 // TODO: We have to reset the default SMS and Phone. This requires 19157 // significant refactoring to keep all default apps in the package 19158 // manager (cleaner but more work) or have the services provide 19159 // callbacks to the package manager to request a default app reset. 19160 applyFactoryDefaultBrowserLPw(userId); 19161 clearIntentFilterVerificationsLPw(userId); 19162 primeDomainVerificationsLPw(userId); 19163 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19164 scheduleWritePackageRestrictionsLocked(userId); 19165 } 19166 resetNetworkPolicies(userId); 19167 } finally { 19168 Binder.restoreCallingIdentity(identity); 19169 } 19170 } 19171 19172 @Override 19173 public int getPreferredActivities(List<IntentFilter> outFilters, 19174 List<ComponentName> outActivities, String packageName) { 19175 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19176 return 0; 19177 } 19178 int num = 0; 19179 final int userId = UserHandle.getCallingUserId(); 19180 // reader 19181 synchronized (mPackages) { 19182 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19183 if (pir != null) { 19184 final Iterator<PreferredActivity> it = pir.filterIterator(); 19185 while (it.hasNext()) { 19186 final PreferredActivity pa = it.next(); 19187 if (packageName == null 19188 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19189 && pa.mPref.mAlways)) { 19190 if (outFilters != null) { 19191 outFilters.add(new IntentFilter(pa)); 19192 } 19193 if (outActivities != null) { 19194 outActivities.add(pa.mPref.mComponent); 19195 } 19196 } 19197 } 19198 } 19199 } 19200 19201 return num; 19202 } 19203 19204 @Override 19205 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19206 int userId) { 19207 int callingUid = Binder.getCallingUid(); 19208 if (callingUid != Process.SYSTEM_UID) { 19209 throw new SecurityException( 19210 "addPersistentPreferredActivity can only be run by the system"); 19211 } 19212 if (filter.countActions() == 0) { 19213 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19214 return; 19215 } 19216 synchronized (mPackages) { 19217 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19218 ":"); 19219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19220 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19221 new PersistentPreferredActivity(filter, activity)); 19222 scheduleWritePackageRestrictionsLocked(userId); 19223 postPreferredActivityChangedBroadcast(userId); 19224 } 19225 } 19226 19227 @Override 19228 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19229 int callingUid = Binder.getCallingUid(); 19230 if (callingUid != Process.SYSTEM_UID) { 19231 throw new SecurityException( 19232 "clearPackagePersistentPreferredActivities can only be run by the system"); 19233 } 19234 ArrayList<PersistentPreferredActivity> removed = null; 19235 boolean changed = false; 19236 synchronized (mPackages) { 19237 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19238 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19239 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19240 .valueAt(i); 19241 if (userId != thisUserId) { 19242 continue; 19243 } 19244 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19245 while (it.hasNext()) { 19246 PersistentPreferredActivity ppa = it.next(); 19247 // Mark entry for removal only if it matches the package name. 19248 if (ppa.mComponent.getPackageName().equals(packageName)) { 19249 if (removed == null) { 19250 removed = new ArrayList<PersistentPreferredActivity>(); 19251 } 19252 removed.add(ppa); 19253 } 19254 } 19255 if (removed != null) { 19256 for (int j=0; j<removed.size(); j++) { 19257 PersistentPreferredActivity ppa = removed.get(j); 19258 ppir.removeFilter(ppa); 19259 } 19260 changed = true; 19261 } 19262 } 19263 19264 if (changed) { 19265 scheduleWritePackageRestrictionsLocked(userId); 19266 postPreferredActivityChangedBroadcast(userId); 19267 } 19268 } 19269 } 19270 19271 /** 19272 * Common machinery for picking apart a restored XML blob and passing 19273 * it to a caller-supplied functor to be applied to the running system. 19274 */ 19275 private void restoreFromXml(XmlPullParser parser, int userId, 19276 String expectedStartTag, BlobXmlRestorer functor) 19277 throws IOException, XmlPullParserException { 19278 int type; 19279 while ((type = parser.next()) != XmlPullParser.START_TAG 19280 && type != XmlPullParser.END_DOCUMENT) { 19281 } 19282 if (type != XmlPullParser.START_TAG) { 19283 // oops didn't find a start tag?! 19284 if (DEBUG_BACKUP) { 19285 Slog.e(TAG, "Didn't find start tag during restore"); 19286 } 19287 return; 19288 } 19289Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19290 // this is supposed to be TAG_PREFERRED_BACKUP 19291 if (!expectedStartTag.equals(parser.getName())) { 19292 if (DEBUG_BACKUP) { 19293 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19294 } 19295 return; 19296 } 19297 19298 // skip interfering stuff, then we're aligned with the backing implementation 19299 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19300Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19301 functor.apply(parser, userId); 19302 } 19303 19304 private interface BlobXmlRestorer { 19305 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19306 } 19307 19308 /** 19309 * Non-Binder method, support for the backup/restore mechanism: write the 19310 * full set of preferred activities in its canonical XML format. Returns the 19311 * XML output as a byte array, or null if there is none. 19312 */ 19313 @Override 19314 public byte[] getPreferredActivityBackup(int userId) { 19315 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19316 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19317 } 19318 19319 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19320 try { 19321 final XmlSerializer serializer = new FastXmlSerializer(); 19322 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19323 serializer.startDocument(null, true); 19324 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19325 19326 synchronized (mPackages) { 19327 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19328 } 19329 19330 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19331 serializer.endDocument(); 19332 serializer.flush(); 19333 } catch (Exception e) { 19334 if (DEBUG_BACKUP) { 19335 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19336 } 19337 return null; 19338 } 19339 19340 return dataStream.toByteArray(); 19341 } 19342 19343 @Override 19344 public void restorePreferredActivities(byte[] backup, int userId) { 19345 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19346 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19347 } 19348 19349 try { 19350 final XmlPullParser parser = Xml.newPullParser(); 19351 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19352 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19353 new BlobXmlRestorer() { 19354 @Override 19355 public void apply(XmlPullParser parser, int userId) 19356 throws XmlPullParserException, IOException { 19357 synchronized (mPackages) { 19358 mSettings.readPreferredActivitiesLPw(parser, userId); 19359 } 19360 } 19361 } ); 19362 } catch (Exception e) { 19363 if (DEBUG_BACKUP) { 19364 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19365 } 19366 } 19367 } 19368 19369 /** 19370 * Non-Binder method, support for the backup/restore mechanism: write the 19371 * default browser (etc) settings in its canonical XML format. Returns the default 19372 * browser XML representation as a byte array, or null if there is none. 19373 */ 19374 @Override 19375 public byte[] getDefaultAppsBackup(int userId) { 19376 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19377 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19378 } 19379 19380 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19381 try { 19382 final XmlSerializer serializer = new FastXmlSerializer(); 19383 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19384 serializer.startDocument(null, true); 19385 serializer.startTag(null, TAG_DEFAULT_APPS); 19386 19387 synchronized (mPackages) { 19388 mSettings.writeDefaultAppsLPr(serializer, userId); 19389 } 19390 19391 serializer.endTag(null, TAG_DEFAULT_APPS); 19392 serializer.endDocument(); 19393 serializer.flush(); 19394 } catch (Exception e) { 19395 if (DEBUG_BACKUP) { 19396 Slog.e(TAG, "Unable to write default apps for backup", e); 19397 } 19398 return null; 19399 } 19400 19401 return dataStream.toByteArray(); 19402 } 19403 19404 @Override 19405 public void restoreDefaultApps(byte[] backup, int userId) { 19406 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19407 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19408 } 19409 19410 try { 19411 final XmlPullParser parser = Xml.newPullParser(); 19412 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19413 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19414 new BlobXmlRestorer() { 19415 @Override 19416 public void apply(XmlPullParser parser, int userId) 19417 throws XmlPullParserException, IOException { 19418 synchronized (mPackages) { 19419 mSettings.readDefaultAppsLPw(parser, userId); 19420 } 19421 } 19422 } ); 19423 } catch (Exception e) { 19424 if (DEBUG_BACKUP) { 19425 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19426 } 19427 } 19428 } 19429 19430 @Override 19431 public byte[] getIntentFilterVerificationBackup(int userId) { 19432 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19433 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19434 } 19435 19436 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19437 try { 19438 final XmlSerializer serializer = new FastXmlSerializer(); 19439 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19440 serializer.startDocument(null, true); 19441 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19442 19443 synchronized (mPackages) { 19444 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19445 } 19446 19447 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19448 serializer.endDocument(); 19449 serializer.flush(); 19450 } catch (Exception e) { 19451 if (DEBUG_BACKUP) { 19452 Slog.e(TAG, "Unable to write default apps for backup", e); 19453 } 19454 return null; 19455 } 19456 19457 return dataStream.toByteArray(); 19458 } 19459 19460 @Override 19461 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19462 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19463 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19464 } 19465 19466 try { 19467 final XmlPullParser parser = Xml.newPullParser(); 19468 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19469 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19470 new BlobXmlRestorer() { 19471 @Override 19472 public void apply(XmlPullParser parser, int userId) 19473 throws XmlPullParserException, IOException { 19474 synchronized (mPackages) { 19475 mSettings.readAllDomainVerificationsLPr(parser, userId); 19476 mSettings.writeLPr(); 19477 } 19478 } 19479 } ); 19480 } catch (Exception e) { 19481 if (DEBUG_BACKUP) { 19482 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19483 } 19484 } 19485 } 19486 19487 @Override 19488 public byte[] getPermissionGrantBackup(int userId) { 19489 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19490 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19491 } 19492 19493 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19494 try { 19495 final XmlSerializer serializer = new FastXmlSerializer(); 19496 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19497 serializer.startDocument(null, true); 19498 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19499 19500 synchronized (mPackages) { 19501 serializeRuntimePermissionGrantsLPr(serializer, userId); 19502 } 19503 19504 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19505 serializer.endDocument(); 19506 serializer.flush(); 19507 } catch (Exception e) { 19508 if (DEBUG_BACKUP) { 19509 Slog.e(TAG, "Unable to write default apps for backup", e); 19510 } 19511 return null; 19512 } 19513 19514 return dataStream.toByteArray(); 19515 } 19516 19517 @Override 19518 public void restorePermissionGrants(byte[] backup, int userId) { 19519 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19520 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19521 } 19522 19523 try { 19524 final XmlPullParser parser = Xml.newPullParser(); 19525 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19526 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19527 new BlobXmlRestorer() { 19528 @Override 19529 public void apply(XmlPullParser parser, int userId) 19530 throws XmlPullParserException, IOException { 19531 synchronized (mPackages) { 19532 processRestoredPermissionGrantsLPr(parser, userId); 19533 } 19534 } 19535 } ); 19536 } catch (Exception e) { 19537 if (DEBUG_BACKUP) { 19538 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19539 } 19540 } 19541 } 19542 19543 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19544 throws IOException { 19545 serializer.startTag(null, TAG_ALL_GRANTS); 19546 19547 final int N = mSettings.mPackages.size(); 19548 for (int i = 0; i < N; i++) { 19549 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19550 boolean pkgGrantsKnown = false; 19551 19552 PermissionsState packagePerms = ps.getPermissionsState(); 19553 19554 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19555 final int grantFlags = state.getFlags(); 19556 // only look at grants that are not system/policy fixed 19557 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19558 final boolean isGranted = state.isGranted(); 19559 // And only back up the user-twiddled state bits 19560 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19561 final String packageName = mSettings.mPackages.keyAt(i); 19562 if (!pkgGrantsKnown) { 19563 serializer.startTag(null, TAG_GRANT); 19564 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19565 pkgGrantsKnown = true; 19566 } 19567 19568 final boolean userSet = 19569 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19570 final boolean userFixed = 19571 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19572 final boolean revoke = 19573 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19574 19575 serializer.startTag(null, TAG_PERMISSION); 19576 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19577 if (isGranted) { 19578 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19579 } 19580 if (userSet) { 19581 serializer.attribute(null, ATTR_USER_SET, "true"); 19582 } 19583 if (userFixed) { 19584 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19585 } 19586 if (revoke) { 19587 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19588 } 19589 serializer.endTag(null, TAG_PERMISSION); 19590 } 19591 } 19592 } 19593 19594 if (pkgGrantsKnown) { 19595 serializer.endTag(null, TAG_GRANT); 19596 } 19597 } 19598 19599 serializer.endTag(null, TAG_ALL_GRANTS); 19600 } 19601 19602 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19603 throws XmlPullParserException, IOException { 19604 String pkgName = null; 19605 int outerDepth = parser.getDepth(); 19606 int type; 19607 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19608 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19609 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19610 continue; 19611 } 19612 19613 final String tagName = parser.getName(); 19614 if (tagName.equals(TAG_GRANT)) { 19615 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19616 if (DEBUG_BACKUP) { 19617 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19618 } 19619 } else if (tagName.equals(TAG_PERMISSION)) { 19620 19621 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19622 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19623 19624 int newFlagSet = 0; 19625 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19626 newFlagSet |= FLAG_PERMISSION_USER_SET; 19627 } 19628 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19629 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19630 } 19631 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19632 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19633 } 19634 if (DEBUG_BACKUP) { 19635 Slog.v(TAG, " + Restoring grant:" 19636 + " pkg=" + pkgName 19637 + " perm=" + permName 19638 + " granted=" + isGranted 19639 + " bits=0x" + Integer.toHexString(newFlagSet)); 19640 } 19641 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19642 if (ps != null) { 19643 // Already installed so we apply the grant immediately 19644 if (DEBUG_BACKUP) { 19645 Slog.v(TAG, " + already installed; applying"); 19646 } 19647 PermissionsState perms = ps.getPermissionsState(); 19648 BasePermission bp = 19649 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19650 if (bp != null) { 19651 if (isGranted) { 19652 perms.grantRuntimePermission(bp, userId); 19653 } 19654 if (newFlagSet != 0) { 19655 perms.updatePermissionFlags( 19656 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19657 } 19658 } 19659 } else { 19660 // Need to wait for post-restore install to apply the grant 19661 if (DEBUG_BACKUP) { 19662 Slog.v(TAG, " - not yet installed; saving for later"); 19663 } 19664 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19665 isGranted, newFlagSet, userId); 19666 } 19667 } else { 19668 PackageManagerService.reportSettingsProblem(Log.WARN, 19669 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19670 XmlUtils.skipCurrentTag(parser); 19671 } 19672 } 19673 19674 scheduleWriteSettingsLocked(); 19675 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19676 } 19677 19678 @Override 19679 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19680 int sourceUserId, int targetUserId, int flags) { 19681 mContext.enforceCallingOrSelfPermission( 19682 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19683 int callingUid = Binder.getCallingUid(); 19684 enforceOwnerRights(ownerPackage, callingUid); 19685 PackageManagerServiceUtils.enforceShellRestriction( 19686 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19687 if (intentFilter.countActions() == 0) { 19688 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19689 return; 19690 } 19691 synchronized (mPackages) { 19692 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19693 ownerPackage, targetUserId, flags); 19694 CrossProfileIntentResolver resolver = 19695 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19696 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19697 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19698 if (existing != null) { 19699 int size = existing.size(); 19700 for (int i = 0; i < size; i++) { 19701 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19702 return; 19703 } 19704 } 19705 } 19706 resolver.addFilter(newFilter); 19707 scheduleWritePackageRestrictionsLocked(sourceUserId); 19708 } 19709 } 19710 19711 @Override 19712 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19713 mContext.enforceCallingOrSelfPermission( 19714 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19715 final int callingUid = Binder.getCallingUid(); 19716 enforceOwnerRights(ownerPackage, callingUid); 19717 PackageManagerServiceUtils.enforceShellRestriction( 19718 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19719 synchronized (mPackages) { 19720 CrossProfileIntentResolver resolver = 19721 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19722 ArraySet<CrossProfileIntentFilter> set = 19723 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19724 for (CrossProfileIntentFilter filter : set) { 19725 if (filter.getOwnerPackage().equals(ownerPackage)) { 19726 resolver.removeFilter(filter); 19727 } 19728 } 19729 scheduleWritePackageRestrictionsLocked(sourceUserId); 19730 } 19731 } 19732 19733 // Enforcing that callingUid is owning pkg on userId 19734 private void enforceOwnerRights(String pkg, int callingUid) { 19735 // The system owns everything. 19736 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19737 return; 19738 } 19739 final int callingUserId = UserHandle.getUserId(callingUid); 19740 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19741 if (pi == null) { 19742 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19743 + callingUserId); 19744 } 19745 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19746 throw new SecurityException("Calling uid " + callingUid 19747 + " does not own package " + pkg); 19748 } 19749 } 19750 19751 @Override 19752 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19753 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19754 return null; 19755 } 19756 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19757 } 19758 19759 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19760 UserManagerService ums = UserManagerService.getInstance(); 19761 if (ums != null) { 19762 final UserInfo parent = ums.getProfileParent(userId); 19763 final int launcherUid = (parent != null) ? parent.id : userId; 19764 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19765 if (launcherComponent != null) { 19766 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19767 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19768 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19769 .setPackage(launcherComponent.getPackageName()); 19770 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19771 } 19772 } 19773 } 19774 19775 /** 19776 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19777 * then reports the most likely home activity or null if there are more than one. 19778 */ 19779 private ComponentName getDefaultHomeActivity(int userId) { 19780 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19781 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19782 if (cn != null) { 19783 return cn; 19784 } 19785 19786 // Find the launcher with the highest priority and return that component if there are no 19787 // other home activity with the same priority. 19788 int lastPriority = Integer.MIN_VALUE; 19789 ComponentName lastComponent = null; 19790 final int size = allHomeCandidates.size(); 19791 for (int i = 0; i < size; i++) { 19792 final ResolveInfo ri = allHomeCandidates.get(i); 19793 if (ri.priority > lastPriority) { 19794 lastComponent = ri.activityInfo.getComponentName(); 19795 lastPriority = ri.priority; 19796 } else if (ri.priority == lastPriority) { 19797 // Two components found with same priority. 19798 lastComponent = null; 19799 } 19800 } 19801 return lastComponent; 19802 } 19803 19804 private Intent getHomeIntent() { 19805 Intent intent = new Intent(Intent.ACTION_MAIN); 19806 intent.addCategory(Intent.CATEGORY_HOME); 19807 intent.addCategory(Intent.CATEGORY_DEFAULT); 19808 return intent; 19809 } 19810 19811 private IntentFilter getHomeFilter() { 19812 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19813 filter.addCategory(Intent.CATEGORY_HOME); 19814 filter.addCategory(Intent.CATEGORY_DEFAULT); 19815 return filter; 19816 } 19817 19818 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19819 int userId) { 19820 Intent intent = getHomeIntent(); 19821 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19822 PackageManager.GET_META_DATA, userId); 19823 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19824 true, false, false, userId); 19825 19826 allHomeCandidates.clear(); 19827 if (list != null) { 19828 for (ResolveInfo ri : list) { 19829 allHomeCandidates.add(ri); 19830 } 19831 } 19832 return (preferred == null || preferred.activityInfo == null) 19833 ? null 19834 : new ComponentName(preferred.activityInfo.packageName, 19835 preferred.activityInfo.name); 19836 } 19837 19838 @Override 19839 public void setHomeActivity(ComponentName comp, int userId) { 19840 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19841 return; 19842 } 19843 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19844 getHomeActivitiesAsUser(homeActivities, userId); 19845 19846 boolean found = false; 19847 19848 final int size = homeActivities.size(); 19849 final ComponentName[] set = new ComponentName[size]; 19850 for (int i = 0; i < size; i++) { 19851 final ResolveInfo candidate = homeActivities.get(i); 19852 final ActivityInfo info = candidate.activityInfo; 19853 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19854 set[i] = activityName; 19855 if (!found && activityName.equals(comp)) { 19856 found = true; 19857 } 19858 } 19859 if (!found) { 19860 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19861 + userId); 19862 } 19863 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19864 set, comp, userId); 19865 } 19866 19867 private @Nullable String getSetupWizardPackageName() { 19868 final Intent intent = new Intent(Intent.ACTION_MAIN); 19869 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19870 19871 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19872 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19873 | MATCH_DISABLED_COMPONENTS, 19874 UserHandle.myUserId()); 19875 if (matches.size() == 1) { 19876 return matches.get(0).getComponentInfo().packageName; 19877 } else { 19878 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19879 + ": matches=" + matches); 19880 return null; 19881 } 19882 } 19883 19884 private @Nullable String getStorageManagerPackageName() { 19885 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19886 19887 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19888 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19889 | MATCH_DISABLED_COMPONENTS, 19890 UserHandle.myUserId()); 19891 if (matches.size() == 1) { 19892 return matches.get(0).getComponentInfo().packageName; 19893 } else { 19894 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19895 + matches.size() + ": matches=" + matches); 19896 return null; 19897 } 19898 } 19899 19900 @Override 19901 public void setApplicationEnabledSetting(String appPackageName, 19902 int newState, int flags, int userId, String callingPackage) { 19903 if (!sUserManager.exists(userId)) return; 19904 if (callingPackage == null) { 19905 callingPackage = Integer.toString(Binder.getCallingUid()); 19906 } 19907 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19908 } 19909 19910 @Override 19911 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19912 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19913 synchronized (mPackages) { 19914 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19915 if (pkgSetting != null) { 19916 pkgSetting.setUpdateAvailable(updateAvailable); 19917 } 19918 } 19919 } 19920 19921 @Override 19922 public void setComponentEnabledSetting(ComponentName componentName, 19923 int newState, int flags, int userId) { 19924 if (!sUserManager.exists(userId)) return; 19925 setEnabledSetting(componentName.getPackageName(), 19926 componentName.getClassName(), newState, flags, userId, null); 19927 } 19928 19929 private void setEnabledSetting(final String packageName, String className, int newState, 19930 final int flags, int userId, String callingPackage) { 19931 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19932 || newState == COMPONENT_ENABLED_STATE_ENABLED 19933 || newState == COMPONENT_ENABLED_STATE_DISABLED 19934 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19935 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19936 throw new IllegalArgumentException("Invalid new component state: " 19937 + newState); 19938 } 19939 PackageSetting pkgSetting; 19940 final int callingUid = Binder.getCallingUid(); 19941 final int permission; 19942 if (callingUid == Process.SYSTEM_UID) { 19943 permission = PackageManager.PERMISSION_GRANTED; 19944 } else { 19945 permission = mContext.checkCallingOrSelfPermission( 19946 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19947 } 19948 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19949 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19950 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19951 boolean sendNow = false; 19952 boolean isApp = (className == null); 19953 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 19954 String componentName = isApp ? packageName : className; 19955 int packageUid = -1; 19956 ArrayList<String> components; 19957 19958 // reader 19959 synchronized (mPackages) { 19960 pkgSetting = mSettings.mPackages.get(packageName); 19961 if (pkgSetting == null) { 19962 if (!isCallerInstantApp) { 19963 if (className == null) { 19964 throw new IllegalArgumentException("Unknown package: " + packageName); 19965 } 19966 throw new IllegalArgumentException( 19967 "Unknown component: " + packageName + "/" + className); 19968 } else { 19969 // throw SecurityException to prevent leaking package information 19970 throw new SecurityException( 19971 "Attempt to change component state; " 19972 + "pid=" + Binder.getCallingPid() 19973 + ", uid=" + callingUid 19974 + (className == null 19975 ? ", package=" + packageName 19976 : ", component=" + packageName + "/" + className)); 19977 } 19978 } 19979 } 19980 19981 // Limit who can change which apps 19982 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 19983 // Don't allow apps that don't have permission to modify other apps 19984 if (!allowedByPermission 19985 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 19986 throw new SecurityException( 19987 "Attempt to change component state; " 19988 + "pid=" + Binder.getCallingPid() 19989 + ", uid=" + callingUid 19990 + (className == null 19991 ? ", package=" + packageName 19992 : ", component=" + packageName + "/" + className)); 19993 } 19994 // Don't allow changing protected packages. 19995 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 19996 throw new SecurityException("Cannot disable a protected package: " + packageName); 19997 } 19998 } 19999 20000 synchronized (mPackages) { 20001 if (callingUid == Process.SHELL_UID 20002 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20003 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20004 // unless it is a test package. 20005 int oldState = pkgSetting.getEnabled(userId); 20006 if (className == null 20007 && 20008 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20009 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20010 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20011 && 20012 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20013 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20014 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20015 // ok 20016 } else { 20017 throw new SecurityException( 20018 "Shell cannot change component state for " + packageName + "/" 20019 + className + " to " + newState); 20020 } 20021 } 20022 } 20023 if (className == null) { 20024 // We're dealing with an application/package level state change 20025 synchronized (mPackages) { 20026 if (pkgSetting.getEnabled(userId) == newState) { 20027 // Nothing to do 20028 return; 20029 } 20030 } 20031 // If we're enabling a system stub, there's a little more work to do. 20032 // Prior to enabling the package, we need to decompress the APK(s) to the 20033 // data partition and then replace the version on the system partition. 20034 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20035 final boolean isSystemStub = deletedPkg.isStub 20036 && deletedPkg.isSystem(); 20037 if (isSystemStub 20038 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20039 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20040 final File codePath = decompressPackage(deletedPkg); 20041 if (codePath == null) { 20042 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20043 return; 20044 } 20045 // TODO remove direct parsing of the package object during internal cleanup 20046 // of scan package 20047 // We need to call parse directly here for no other reason than we need 20048 // the new package in order to disable the old one [we use the information 20049 // for some internal optimization to optionally create a new package setting 20050 // object on replace]. However, we can't get the package from the scan 20051 // because the scan modifies live structures and we need to remove the 20052 // old [system] package from the system before a scan can be attempted. 20053 // Once scan is indempotent we can remove this parse and use the package 20054 // object we scanned, prior to adding it to package settings. 20055 final PackageParser pp = new PackageParser(); 20056 pp.setSeparateProcesses(mSeparateProcesses); 20057 pp.setDisplayMetrics(mMetrics); 20058 pp.setCallback(mPackageParserCallback); 20059 final PackageParser.Package tmpPkg; 20060 try { 20061 final @ParseFlags int parseFlags = mDefParseFlags 20062 | PackageParser.PARSE_MUST_BE_APK 20063 | PackageParser.PARSE_IS_SYSTEM_DIR; 20064 tmpPkg = pp.parsePackage(codePath, parseFlags); 20065 } catch (PackageParserException e) { 20066 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20067 return; 20068 } 20069 synchronized (mInstallLock) { 20070 // Disable the stub and remove any package entries 20071 removePackageLI(deletedPkg, true); 20072 synchronized (mPackages) { 20073 disableSystemPackageLPw(deletedPkg, tmpPkg); 20074 } 20075 final PackageParser.Package pkg; 20076 try (PackageFreezer freezer = 20077 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20078 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20079 | PackageParser.PARSE_ENFORCE_CODE; 20080 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20081 0 /*currentTime*/, null /*user*/); 20082 prepareAppDataAfterInstallLIF(pkg); 20083 synchronized (mPackages) { 20084 try { 20085 updateSharedLibrariesLPr(pkg, null); 20086 } catch (PackageManagerException e) { 20087 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20088 } 20089 mPermissionManager.updatePermissions( 20090 pkg.packageName, pkg, true, mPackages.values(), 20091 mPermissionCallback); 20092 mSettings.writeLPr(); 20093 } 20094 } catch (PackageManagerException e) { 20095 // Whoops! Something went wrong; try to roll back to the stub 20096 Slog.w(TAG, "Failed to install compressed system package:" 20097 + pkgSetting.name, e); 20098 // Remove the failed install 20099 removeCodePathLI(codePath); 20100 20101 // Install the system package 20102 try (PackageFreezer freezer = 20103 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20104 synchronized (mPackages) { 20105 // NOTE: The system package always needs to be enabled; even 20106 // if it's for a compressed stub. If we don't, installing the 20107 // system package fails during scan [scanning checks the disabled 20108 // packages]. We will reverse this later, after we've "installed" 20109 // the stub. 20110 // This leaves us in a fragile state; the stub should never be 20111 // enabled, so, cross your fingers and hope nothing goes wrong 20112 // until we can disable the package later. 20113 enableSystemPackageLPw(deletedPkg); 20114 } 20115 installPackageFromSystemLIF(deletedPkg.codePath, 20116 false /*isPrivileged*/, null /*allUserHandles*/, 20117 null /*origUserHandles*/, null /*origPermissionsState*/, 20118 true /*writeSettings*/); 20119 } catch (PackageManagerException pme) { 20120 Slog.w(TAG, "Failed to restore system package:" 20121 + deletedPkg.packageName, pme); 20122 } finally { 20123 synchronized (mPackages) { 20124 mSettings.disableSystemPackageLPw( 20125 deletedPkg.packageName, true /*replaced*/); 20126 mSettings.writeLPr(); 20127 } 20128 } 20129 return; 20130 } 20131 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20132 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20133 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20134 mDexManager.notifyPackageUpdated(pkg.packageName, 20135 pkg.baseCodePath, pkg.splitCodePaths); 20136 } 20137 } 20138 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20139 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20140 // Don't care about who enables an app. 20141 callingPackage = null; 20142 } 20143 synchronized (mPackages) { 20144 pkgSetting.setEnabled(newState, userId, callingPackage); 20145 } 20146 } else { 20147 synchronized (mPackages) { 20148 // We're dealing with a component level state change 20149 // First, verify that this is a valid class name. 20150 PackageParser.Package pkg = pkgSetting.pkg; 20151 if (pkg == null || !pkg.hasComponentClassName(className)) { 20152 if (pkg != null && 20153 pkg.applicationInfo.targetSdkVersion >= 20154 Build.VERSION_CODES.JELLY_BEAN) { 20155 throw new IllegalArgumentException("Component class " + className 20156 + " does not exist in " + packageName); 20157 } else { 20158 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20159 + className + " does not exist in " + packageName); 20160 } 20161 } 20162 switch (newState) { 20163 case COMPONENT_ENABLED_STATE_ENABLED: 20164 if (!pkgSetting.enableComponentLPw(className, userId)) { 20165 return; 20166 } 20167 break; 20168 case COMPONENT_ENABLED_STATE_DISABLED: 20169 if (!pkgSetting.disableComponentLPw(className, userId)) { 20170 return; 20171 } 20172 break; 20173 case COMPONENT_ENABLED_STATE_DEFAULT: 20174 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20175 return; 20176 } 20177 break; 20178 default: 20179 Slog.e(TAG, "Invalid new component state: " + newState); 20180 return; 20181 } 20182 } 20183 } 20184 synchronized (mPackages) { 20185 scheduleWritePackageRestrictionsLocked(userId); 20186 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20187 final long callingId = Binder.clearCallingIdentity(); 20188 try { 20189 updateInstantAppInstallerLocked(packageName); 20190 } finally { 20191 Binder.restoreCallingIdentity(callingId); 20192 } 20193 components = mPendingBroadcasts.get(userId, packageName); 20194 final boolean newPackage = components == null; 20195 if (newPackage) { 20196 components = new ArrayList<String>(); 20197 } 20198 if (!components.contains(componentName)) { 20199 components.add(componentName); 20200 } 20201 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20202 sendNow = true; 20203 // Purge entry from pending broadcast list if another one exists already 20204 // since we are sending one right away. 20205 mPendingBroadcasts.remove(userId, packageName); 20206 } else { 20207 if (newPackage) { 20208 mPendingBroadcasts.put(userId, packageName, components); 20209 } 20210 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20211 // Schedule a message 20212 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20213 } 20214 } 20215 } 20216 20217 long callingId = Binder.clearCallingIdentity(); 20218 try { 20219 if (sendNow) { 20220 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20221 sendPackageChangedBroadcast(packageName, 20222 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20223 } 20224 } finally { 20225 Binder.restoreCallingIdentity(callingId); 20226 } 20227 } 20228 20229 @Override 20230 public void flushPackageRestrictionsAsUser(int userId) { 20231 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20232 return; 20233 } 20234 if (!sUserManager.exists(userId)) { 20235 return; 20236 } 20237 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20238 false /* checkShell */, "flushPackageRestrictions"); 20239 synchronized (mPackages) { 20240 mSettings.writePackageRestrictionsLPr(userId); 20241 mDirtyUsers.remove(userId); 20242 if (mDirtyUsers.isEmpty()) { 20243 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20244 } 20245 } 20246 } 20247 20248 private void sendPackageChangedBroadcast(String packageName, 20249 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20250 if (DEBUG_INSTALL) 20251 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20252 + componentNames); 20253 Bundle extras = new Bundle(4); 20254 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20255 String nameList[] = new String[componentNames.size()]; 20256 componentNames.toArray(nameList); 20257 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20258 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20259 extras.putInt(Intent.EXTRA_UID, packageUid); 20260 // If this is not reporting a change of the overall package, then only send it 20261 // to registered receivers. We don't want to launch a swath of apps for every 20262 // little component state change. 20263 final int flags = !componentNames.contains(packageName) 20264 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20265 final int userId = UserHandle.getUserId(packageUid); 20266 final boolean isInstantApp = isInstantApp(packageName, userId); 20267 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20268 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20269 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20270 userIds, instantUserIds); 20271 } 20272 20273 @Override 20274 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20275 if (!sUserManager.exists(userId)) return; 20276 final int callingUid = Binder.getCallingUid(); 20277 if (getInstantAppPackageName(callingUid) != null) { 20278 return; 20279 } 20280 final int permission = mContext.checkCallingOrSelfPermission( 20281 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20282 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20283 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20284 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20285 // writer 20286 synchronized (mPackages) { 20287 final PackageSetting ps = mSettings.mPackages.get(packageName); 20288 if (!filterAppAccessLPr(ps, callingUid, userId) 20289 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20290 allowedByPermission, callingUid, userId)) { 20291 scheduleWritePackageRestrictionsLocked(userId); 20292 } 20293 } 20294 } 20295 20296 @Override 20297 public String getInstallerPackageName(String packageName) { 20298 final int callingUid = Binder.getCallingUid(); 20299 if (getInstantAppPackageName(callingUid) != null) { 20300 return null; 20301 } 20302 // reader 20303 synchronized (mPackages) { 20304 final PackageSetting ps = mSettings.mPackages.get(packageName); 20305 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20306 return null; 20307 } 20308 return mSettings.getInstallerPackageNameLPr(packageName); 20309 } 20310 } 20311 20312 public boolean isOrphaned(String packageName) { 20313 // reader 20314 synchronized (mPackages) { 20315 return mSettings.isOrphaned(packageName); 20316 } 20317 } 20318 20319 @Override 20320 public int getApplicationEnabledSetting(String packageName, int userId) { 20321 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20322 int callingUid = Binder.getCallingUid(); 20323 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20324 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20325 // reader 20326 synchronized (mPackages) { 20327 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20328 return COMPONENT_ENABLED_STATE_DISABLED; 20329 } 20330 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20331 } 20332 } 20333 20334 @Override 20335 public int getComponentEnabledSetting(ComponentName component, int userId) { 20336 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20337 int callingUid = Binder.getCallingUid(); 20338 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20339 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20340 synchronized (mPackages) { 20341 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20342 component, TYPE_UNKNOWN, userId)) { 20343 return COMPONENT_ENABLED_STATE_DISABLED; 20344 } 20345 return mSettings.getComponentEnabledSettingLPr(component, userId); 20346 } 20347 } 20348 20349 @Override 20350 public void enterSafeMode() { 20351 enforceSystemOrRoot("Only the system can request entering safe mode"); 20352 20353 if (!mSystemReady) { 20354 mSafeMode = true; 20355 } 20356 } 20357 20358 @Override 20359 public void systemReady() { 20360 enforceSystemOrRoot("Only the system can claim the system is ready"); 20361 20362 mSystemReady = true; 20363 final ContentResolver resolver = mContext.getContentResolver(); 20364 ContentObserver co = new ContentObserver(mHandler) { 20365 @Override 20366 public void onChange(boolean selfChange) { 20367 mEphemeralAppsDisabled = 20368 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20369 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20370 } 20371 }; 20372 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20373 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20374 false, co, UserHandle.USER_SYSTEM); 20375 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20376 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20377 co.onChange(true); 20378 20379 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20380 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20381 // it is done. 20382 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20383 @Override 20384 public void onChange(boolean selfChange) { 20385 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20386 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20387 oobEnabled == 1 ? "true" : "false"); 20388 } 20389 }; 20390 mContext.getContentResolver().registerContentObserver( 20391 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20392 UserHandle.USER_SYSTEM); 20393 // At boot, restore the value from the setting, which persists across reboot. 20394 privAppOobObserver.onChange(true); 20395 20396 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20397 // disabled after already being started. 20398 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20399 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20400 20401 // Read the compatibilty setting when the system is ready. 20402 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20403 mContext.getContentResolver(), 20404 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20405 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20406 if (DEBUG_SETTINGS) { 20407 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20408 } 20409 20410 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20411 20412 synchronized (mPackages) { 20413 // Verify that all of the preferred activity components actually 20414 // exist. It is possible for applications to be updated and at 20415 // that point remove a previously declared activity component that 20416 // had been set as a preferred activity. We try to clean this up 20417 // the next time we encounter that preferred activity, but it is 20418 // possible for the user flow to never be able to return to that 20419 // situation so here we do a sanity check to make sure we haven't 20420 // left any junk around. 20421 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20422 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20423 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20424 removed.clear(); 20425 for (PreferredActivity pa : pir.filterSet()) { 20426 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20427 removed.add(pa); 20428 } 20429 } 20430 if (removed.size() > 0) { 20431 for (int r=0; r<removed.size(); r++) { 20432 PreferredActivity pa = removed.get(r); 20433 Slog.w(TAG, "Removing dangling preferred activity: " 20434 + pa.mPref.mComponent); 20435 pir.removeFilter(pa); 20436 } 20437 mSettings.writePackageRestrictionsLPr( 20438 mSettings.mPreferredActivities.keyAt(i)); 20439 } 20440 } 20441 20442 for (int userId : UserManagerService.getInstance().getUserIds()) { 20443 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20444 grantPermissionsUserIds = ArrayUtils.appendInt( 20445 grantPermissionsUserIds, userId); 20446 } 20447 } 20448 } 20449 sUserManager.systemReady(); 20450 // If we upgraded grant all default permissions before kicking off. 20451 for (int userId : grantPermissionsUserIds) { 20452 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20453 } 20454 20455 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20456 // If we did not grant default permissions, we preload from this the 20457 // default permission exceptions lazily to ensure we don't hit the 20458 // disk on a new user creation. 20459 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20460 } 20461 20462 // Now that we've scanned all packages, and granted any default 20463 // permissions, ensure permissions are updated. Beware of dragons if you 20464 // try optimizing this. 20465 synchronized (mPackages) { 20466 mPermissionManager.updateAllPermissions( 20467 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20468 mPermissionCallback); 20469 } 20470 20471 // Kick off any messages waiting for system ready 20472 if (mPostSystemReadyMessages != null) { 20473 for (Message msg : mPostSystemReadyMessages) { 20474 msg.sendToTarget(); 20475 } 20476 mPostSystemReadyMessages = null; 20477 } 20478 20479 // Watch for external volumes that come and go over time 20480 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20481 storage.registerListener(mStorageListener); 20482 20483 mInstallerService.systemReady(); 20484 mPackageDexOptimizer.systemReady(); 20485 20486 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20487 StorageManagerInternal.class); 20488 StorageManagerInternal.addExternalStoragePolicy( 20489 new StorageManagerInternal.ExternalStorageMountPolicy() { 20490 @Override 20491 public int getMountMode(int uid, String packageName) { 20492 if (Process.isIsolated(uid)) { 20493 return Zygote.MOUNT_EXTERNAL_NONE; 20494 } 20495 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20496 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20497 } 20498 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20499 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20500 } 20501 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20502 return Zygote.MOUNT_EXTERNAL_READ; 20503 } 20504 return Zygote.MOUNT_EXTERNAL_WRITE; 20505 } 20506 20507 @Override 20508 public boolean hasExternalStorage(int uid, String packageName) { 20509 return true; 20510 } 20511 }); 20512 20513 // Now that we're mostly running, clean up stale users and apps 20514 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20515 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20516 20517 mPermissionManager.systemReady(); 20518 } 20519 20520 public void waitForAppDataPrepared() { 20521 if (mPrepareAppDataFuture == null) { 20522 return; 20523 } 20524 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20525 mPrepareAppDataFuture = null; 20526 } 20527 20528 @Override 20529 public boolean isSafeMode() { 20530 // allow instant applications 20531 return mSafeMode; 20532 } 20533 20534 @Override 20535 public boolean hasSystemUidErrors() { 20536 // allow instant applications 20537 return mHasSystemUidErrors; 20538 } 20539 20540 static String arrayToString(int[] array) { 20541 StringBuffer buf = new StringBuffer(128); 20542 buf.append('['); 20543 if (array != null) { 20544 for (int i=0; i<array.length; i++) { 20545 if (i > 0) buf.append(", "); 20546 buf.append(array[i]); 20547 } 20548 } 20549 buf.append(']'); 20550 return buf.toString(); 20551 } 20552 20553 @Override 20554 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20555 FileDescriptor err, String[] args, ShellCallback callback, 20556 ResultReceiver resultReceiver) { 20557 (new PackageManagerShellCommand(this)).exec( 20558 this, in, out, err, args, callback, resultReceiver); 20559 } 20560 20561 @Override 20562 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20563 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20564 20565 DumpState dumpState = new DumpState(); 20566 boolean fullPreferred = false; 20567 boolean checkin = false; 20568 20569 String packageName = null; 20570 ArraySet<String> permissionNames = null; 20571 20572 int opti = 0; 20573 while (opti < args.length) { 20574 String opt = args[opti]; 20575 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20576 break; 20577 } 20578 opti++; 20579 20580 if ("-a".equals(opt)) { 20581 // Right now we only know how to print all. 20582 } else if ("-h".equals(opt)) { 20583 pw.println("Package manager dump options:"); 20584 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20585 pw.println(" --checkin: dump for a checkin"); 20586 pw.println(" -f: print details of intent filters"); 20587 pw.println(" -h: print this help"); 20588 pw.println(" cmd may be one of:"); 20589 pw.println(" l[ibraries]: list known shared libraries"); 20590 pw.println(" f[eatures]: list device features"); 20591 pw.println(" k[eysets]: print known keysets"); 20592 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20593 pw.println(" perm[issions]: dump permissions"); 20594 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20595 pw.println(" pref[erred]: print preferred package settings"); 20596 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20597 pw.println(" prov[iders]: dump content providers"); 20598 pw.println(" p[ackages]: dump installed packages"); 20599 pw.println(" s[hared-users]: dump shared user IDs"); 20600 pw.println(" m[essages]: print collected runtime messages"); 20601 pw.println(" v[erifiers]: print package verifier info"); 20602 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20603 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20604 pw.println(" version: print database version info"); 20605 pw.println(" write: write current settings now"); 20606 pw.println(" installs: details about install sessions"); 20607 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20608 pw.println(" dexopt: dump dexopt state"); 20609 pw.println(" compiler-stats: dump compiler statistics"); 20610 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20611 pw.println(" service-permissions: dump permissions required by services"); 20612 pw.println(" <package.name>: info about given package"); 20613 return; 20614 } else if ("--checkin".equals(opt)) { 20615 checkin = true; 20616 } else if ("-f".equals(opt)) { 20617 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20618 } else if ("--proto".equals(opt)) { 20619 dumpProto(fd); 20620 return; 20621 } else { 20622 pw.println("Unknown argument: " + opt + "; use -h for help"); 20623 } 20624 } 20625 20626 // Is the caller requesting to dump a particular piece of data? 20627 if (opti < args.length) { 20628 String cmd = args[opti]; 20629 opti++; 20630 // Is this a package name? 20631 if ("android".equals(cmd) || cmd.contains(".")) { 20632 packageName = cmd; 20633 // When dumping a single package, we always dump all of its 20634 // filter information since the amount of data will be reasonable. 20635 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20636 } else if ("check-permission".equals(cmd)) { 20637 if (opti >= args.length) { 20638 pw.println("Error: check-permission missing permission argument"); 20639 return; 20640 } 20641 String perm = args[opti]; 20642 opti++; 20643 if (opti >= args.length) { 20644 pw.println("Error: check-permission missing package argument"); 20645 return; 20646 } 20647 20648 String pkg = args[opti]; 20649 opti++; 20650 int user = UserHandle.getUserId(Binder.getCallingUid()); 20651 if (opti < args.length) { 20652 try { 20653 user = Integer.parseInt(args[opti]); 20654 } catch (NumberFormatException e) { 20655 pw.println("Error: check-permission user argument is not a number: " 20656 + args[opti]); 20657 return; 20658 } 20659 } 20660 20661 // Normalize package name to handle renamed packages and static libs 20662 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20663 20664 pw.println(checkPermission(perm, pkg, user)); 20665 return; 20666 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20667 dumpState.setDump(DumpState.DUMP_LIBS); 20668 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20669 dumpState.setDump(DumpState.DUMP_FEATURES); 20670 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20671 if (opti >= args.length) { 20672 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20673 | DumpState.DUMP_SERVICE_RESOLVERS 20674 | DumpState.DUMP_RECEIVER_RESOLVERS 20675 | DumpState.DUMP_CONTENT_RESOLVERS); 20676 } else { 20677 while (opti < args.length) { 20678 String name = args[opti]; 20679 if ("a".equals(name) || "activity".equals(name)) { 20680 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20681 } else if ("s".equals(name) || "service".equals(name)) { 20682 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20683 } else if ("r".equals(name) || "receiver".equals(name)) { 20684 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20685 } else if ("c".equals(name) || "content".equals(name)) { 20686 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20687 } else { 20688 pw.println("Error: unknown resolver table type: " + name); 20689 return; 20690 } 20691 opti++; 20692 } 20693 } 20694 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20695 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20696 } else if ("permission".equals(cmd)) { 20697 if (opti >= args.length) { 20698 pw.println("Error: permission requires permission name"); 20699 return; 20700 } 20701 permissionNames = new ArraySet<>(); 20702 while (opti < args.length) { 20703 permissionNames.add(args[opti]); 20704 opti++; 20705 } 20706 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20707 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20708 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20709 dumpState.setDump(DumpState.DUMP_PREFERRED); 20710 } else if ("preferred-xml".equals(cmd)) { 20711 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20712 if (opti < args.length && "--full".equals(args[opti])) { 20713 fullPreferred = true; 20714 opti++; 20715 } 20716 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20717 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20718 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20719 dumpState.setDump(DumpState.DUMP_PACKAGES); 20720 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20721 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20722 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20723 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20724 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20725 dumpState.setDump(DumpState.DUMP_MESSAGES); 20726 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20727 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20728 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20729 || "intent-filter-verifiers".equals(cmd)) { 20730 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20731 } else if ("version".equals(cmd)) { 20732 dumpState.setDump(DumpState.DUMP_VERSION); 20733 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20734 dumpState.setDump(DumpState.DUMP_KEYSETS); 20735 } else if ("installs".equals(cmd)) { 20736 dumpState.setDump(DumpState.DUMP_INSTALLS); 20737 } else if ("frozen".equals(cmd)) { 20738 dumpState.setDump(DumpState.DUMP_FROZEN); 20739 } else if ("volumes".equals(cmd)) { 20740 dumpState.setDump(DumpState.DUMP_VOLUMES); 20741 } else if ("dexopt".equals(cmd)) { 20742 dumpState.setDump(DumpState.DUMP_DEXOPT); 20743 } else if ("compiler-stats".equals(cmd)) { 20744 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20745 } else if ("changes".equals(cmd)) { 20746 dumpState.setDump(DumpState.DUMP_CHANGES); 20747 } else if ("service-permissions".equals(cmd)) { 20748 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 20749 } else if ("write".equals(cmd)) { 20750 synchronized (mPackages) { 20751 mSettings.writeLPr(); 20752 pw.println("Settings written."); 20753 return; 20754 } 20755 } 20756 } 20757 20758 if (checkin) { 20759 pw.println("vers,1"); 20760 } 20761 20762 // reader 20763 synchronized (mPackages) { 20764 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20765 if (!checkin) { 20766 if (dumpState.onTitlePrinted()) 20767 pw.println(); 20768 pw.println("Database versions:"); 20769 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20770 } 20771 } 20772 20773 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20774 if (!checkin) { 20775 if (dumpState.onTitlePrinted()) 20776 pw.println(); 20777 pw.println("Verifiers:"); 20778 pw.print(" Required: "); 20779 pw.print(mRequiredVerifierPackage); 20780 pw.print(" (uid="); 20781 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20782 UserHandle.USER_SYSTEM)); 20783 pw.println(")"); 20784 } else if (mRequiredVerifierPackage != null) { 20785 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20786 pw.print(","); 20787 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20788 UserHandle.USER_SYSTEM)); 20789 } 20790 } 20791 20792 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20793 packageName == null) { 20794 if (mIntentFilterVerifierComponent != null) { 20795 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20796 if (!checkin) { 20797 if (dumpState.onTitlePrinted()) 20798 pw.println(); 20799 pw.println("Intent Filter Verifier:"); 20800 pw.print(" Using: "); 20801 pw.print(verifierPackageName); 20802 pw.print(" (uid="); 20803 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20804 UserHandle.USER_SYSTEM)); 20805 pw.println(")"); 20806 } else if (verifierPackageName != null) { 20807 pw.print("ifv,"); pw.print(verifierPackageName); 20808 pw.print(","); 20809 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20810 UserHandle.USER_SYSTEM)); 20811 } 20812 } else { 20813 pw.println(); 20814 pw.println("No Intent Filter Verifier available!"); 20815 } 20816 } 20817 20818 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20819 boolean printedHeader = false; 20820 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20821 while (it.hasNext()) { 20822 String libName = it.next(); 20823 LongSparseArray<SharedLibraryEntry> versionedLib 20824 = mSharedLibraries.get(libName); 20825 if (versionedLib == null) { 20826 continue; 20827 } 20828 final int versionCount = versionedLib.size(); 20829 for (int i = 0; i < versionCount; i++) { 20830 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20831 if (!checkin) { 20832 if (!printedHeader) { 20833 if (dumpState.onTitlePrinted()) 20834 pw.println(); 20835 pw.println("Libraries:"); 20836 printedHeader = true; 20837 } 20838 pw.print(" "); 20839 } else { 20840 pw.print("lib,"); 20841 } 20842 pw.print(libEntry.info.getName()); 20843 if (libEntry.info.isStatic()) { 20844 pw.print(" version=" + libEntry.info.getLongVersion()); 20845 } 20846 if (!checkin) { 20847 pw.print(" -> "); 20848 } 20849 if (libEntry.path != null) { 20850 pw.print(" (jar) "); 20851 pw.print(libEntry.path); 20852 } else { 20853 pw.print(" (apk) "); 20854 pw.print(libEntry.apk); 20855 } 20856 pw.println(); 20857 } 20858 } 20859 } 20860 20861 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20862 if (dumpState.onTitlePrinted()) 20863 pw.println(); 20864 if (!checkin) { 20865 pw.println("Features:"); 20866 } 20867 20868 synchronized (mAvailableFeatures) { 20869 for (FeatureInfo feat : mAvailableFeatures.values()) { 20870 if (checkin) { 20871 pw.print("feat,"); 20872 pw.print(feat.name); 20873 pw.print(","); 20874 pw.println(feat.version); 20875 } else { 20876 pw.print(" "); 20877 pw.print(feat.name); 20878 if (feat.version > 0) { 20879 pw.print(" version="); 20880 pw.print(feat.version); 20881 } 20882 pw.println(); 20883 } 20884 } 20885 } 20886 } 20887 20888 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20889 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20890 : "Activity Resolver Table:", " ", packageName, 20891 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20892 dumpState.setTitlePrinted(true); 20893 } 20894 } 20895 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20896 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20897 : "Receiver Resolver Table:", " ", packageName, 20898 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20899 dumpState.setTitlePrinted(true); 20900 } 20901 } 20902 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20903 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20904 : "Service Resolver Table:", " ", packageName, 20905 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20906 dumpState.setTitlePrinted(true); 20907 } 20908 } 20909 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20910 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20911 : "Provider Resolver Table:", " ", packageName, 20912 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20913 dumpState.setTitlePrinted(true); 20914 } 20915 } 20916 20917 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20918 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20919 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20920 int user = mSettings.mPreferredActivities.keyAt(i); 20921 if (pir.dump(pw, 20922 dumpState.getTitlePrinted() 20923 ? "\nPreferred Activities User " + user + ":" 20924 : "Preferred Activities User " + user + ":", " ", 20925 packageName, true, false)) { 20926 dumpState.setTitlePrinted(true); 20927 } 20928 } 20929 } 20930 20931 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20932 pw.flush(); 20933 FileOutputStream fout = new FileOutputStream(fd); 20934 BufferedOutputStream str = new BufferedOutputStream(fout); 20935 XmlSerializer serializer = new FastXmlSerializer(); 20936 try { 20937 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20938 serializer.startDocument(null, true); 20939 serializer.setFeature( 20940 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20941 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20942 serializer.endDocument(); 20943 serializer.flush(); 20944 } catch (IllegalArgumentException e) { 20945 pw.println("Failed writing: " + e); 20946 } catch (IllegalStateException e) { 20947 pw.println("Failed writing: " + e); 20948 } catch (IOException e) { 20949 pw.println("Failed writing: " + e); 20950 } 20951 } 20952 20953 if (!checkin 20954 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20955 && packageName == null) { 20956 pw.println(); 20957 int count = mSettings.mPackages.size(); 20958 if (count == 0) { 20959 pw.println("No applications!"); 20960 pw.println(); 20961 } else { 20962 final String prefix = " "; 20963 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20964 if (allPackageSettings.size() == 0) { 20965 pw.println("No domain preferred apps!"); 20966 pw.println(); 20967 } else { 20968 pw.println("App verification status:"); 20969 pw.println(); 20970 count = 0; 20971 for (PackageSetting ps : allPackageSettings) { 20972 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20973 if (ivi == null || ivi.getPackageName() == null) continue; 20974 pw.println(prefix + "Package: " + ivi.getPackageName()); 20975 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20976 pw.println(prefix + "Status: " + ivi.getStatusString()); 20977 pw.println(); 20978 count++; 20979 } 20980 if (count == 0) { 20981 pw.println(prefix + "No app verification established."); 20982 pw.println(); 20983 } 20984 for (int userId : sUserManager.getUserIds()) { 20985 pw.println("App linkages for user " + userId + ":"); 20986 pw.println(); 20987 count = 0; 20988 for (PackageSetting ps : allPackageSettings) { 20989 final long status = ps.getDomainVerificationStatusForUser(userId); 20990 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 20991 && !DEBUG_DOMAIN_VERIFICATION) { 20992 continue; 20993 } 20994 pw.println(prefix + "Package: " + ps.name); 20995 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 20996 String statusStr = IntentFilterVerificationInfo. 20997 getStatusStringFromValue(status); 20998 pw.println(prefix + "Status: " + statusStr); 20999 pw.println(); 21000 count++; 21001 } 21002 if (count == 0) { 21003 pw.println(prefix + "No configured app linkages."); 21004 pw.println(); 21005 } 21006 } 21007 } 21008 } 21009 } 21010 21011 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21012 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21013 } 21014 21015 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21016 boolean printedSomething = false; 21017 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21018 if (packageName != null && !packageName.equals(p.info.packageName)) { 21019 continue; 21020 } 21021 if (!printedSomething) { 21022 if (dumpState.onTitlePrinted()) 21023 pw.println(); 21024 pw.println("Registered ContentProviders:"); 21025 printedSomething = true; 21026 } 21027 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21028 pw.print(" "); pw.println(p.toString()); 21029 } 21030 printedSomething = false; 21031 for (Map.Entry<String, PackageParser.Provider> entry : 21032 mProvidersByAuthority.entrySet()) { 21033 PackageParser.Provider p = entry.getValue(); 21034 if (packageName != null && !packageName.equals(p.info.packageName)) { 21035 continue; 21036 } 21037 if (!printedSomething) { 21038 if (dumpState.onTitlePrinted()) 21039 pw.println(); 21040 pw.println("ContentProvider Authorities:"); 21041 printedSomething = true; 21042 } 21043 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21044 pw.print(" "); pw.println(p.toString()); 21045 if (p.info != null && p.info.applicationInfo != null) { 21046 final String appInfo = p.info.applicationInfo.toString(); 21047 pw.print(" applicationInfo="); pw.println(appInfo); 21048 } 21049 } 21050 } 21051 21052 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21053 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21054 } 21055 21056 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21057 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21058 } 21059 21060 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21061 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21062 } 21063 21064 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21065 if (dumpState.onTitlePrinted()) pw.println(); 21066 pw.println("Package Changes:"); 21067 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21068 final int K = mChangedPackages.size(); 21069 for (int i = 0; i < K; i++) { 21070 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21071 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21072 final int N = changes.size(); 21073 if (N == 0) { 21074 pw.print(" "); pw.println("No packages changed"); 21075 } else { 21076 for (int j = 0; j < N; j++) { 21077 final String pkgName = changes.valueAt(j); 21078 final int sequenceNumber = changes.keyAt(j); 21079 pw.print(" "); 21080 pw.print("seq="); 21081 pw.print(sequenceNumber); 21082 pw.print(", package="); 21083 pw.println(pkgName); 21084 } 21085 } 21086 } 21087 } 21088 21089 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21090 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21091 } 21092 21093 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21094 // XXX should handle packageName != null by dumping only install data that 21095 // the given package is involved with. 21096 if (dumpState.onTitlePrinted()) pw.println(); 21097 21098 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21099 ipw.println(); 21100 ipw.println("Frozen packages:"); 21101 ipw.increaseIndent(); 21102 if (mFrozenPackages.size() == 0) { 21103 ipw.println("(none)"); 21104 } else { 21105 for (int i = 0; i < mFrozenPackages.size(); i++) { 21106 ipw.println(mFrozenPackages.valueAt(i)); 21107 } 21108 } 21109 ipw.decreaseIndent(); 21110 } 21111 21112 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21113 if (dumpState.onTitlePrinted()) pw.println(); 21114 21115 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21116 ipw.println(); 21117 ipw.println("Loaded volumes:"); 21118 ipw.increaseIndent(); 21119 if (mLoadedVolumes.size() == 0) { 21120 ipw.println("(none)"); 21121 } else { 21122 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21123 ipw.println(mLoadedVolumes.valueAt(i)); 21124 } 21125 } 21126 ipw.decreaseIndent(); 21127 } 21128 21129 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21130 && packageName == null) { 21131 if (dumpState.onTitlePrinted()) pw.println(); 21132 pw.println("Service permissions:"); 21133 21134 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21135 while (filterIterator.hasNext()) { 21136 final ServiceIntentInfo info = filterIterator.next(); 21137 final ServiceInfo serviceInfo = info.service.info; 21138 final String permission = serviceInfo.permission; 21139 if (permission != null) { 21140 pw.print(" "); 21141 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21142 pw.print(": "); 21143 pw.println(permission); 21144 } 21145 } 21146 } 21147 21148 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21149 if (dumpState.onTitlePrinted()) pw.println(); 21150 dumpDexoptStateLPr(pw, packageName); 21151 } 21152 21153 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21154 if (dumpState.onTitlePrinted()) pw.println(); 21155 dumpCompilerStatsLPr(pw, packageName); 21156 } 21157 21158 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21159 if (dumpState.onTitlePrinted()) pw.println(); 21160 mSettings.dumpReadMessagesLPr(pw, dumpState); 21161 21162 pw.println(); 21163 pw.println("Package warning messages:"); 21164 dumpCriticalInfo(pw, null); 21165 } 21166 21167 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21168 dumpCriticalInfo(pw, "msg,"); 21169 } 21170 } 21171 21172 // PackageInstaller should be called outside of mPackages lock 21173 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21174 // XXX should handle packageName != null by dumping only install data that 21175 // the given package is involved with. 21176 if (dumpState.onTitlePrinted()) pw.println(); 21177 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21178 } 21179 } 21180 21181 private void dumpProto(FileDescriptor fd) { 21182 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21183 21184 synchronized (mPackages) { 21185 final long requiredVerifierPackageToken = 21186 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21187 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21188 proto.write( 21189 PackageServiceDumpProto.PackageShortProto.UID, 21190 getPackageUid( 21191 mRequiredVerifierPackage, 21192 MATCH_DEBUG_TRIAGED_MISSING, 21193 UserHandle.USER_SYSTEM)); 21194 proto.end(requiredVerifierPackageToken); 21195 21196 if (mIntentFilterVerifierComponent != null) { 21197 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21198 final long verifierPackageToken = 21199 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21200 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21201 proto.write( 21202 PackageServiceDumpProto.PackageShortProto.UID, 21203 getPackageUid( 21204 verifierPackageName, 21205 MATCH_DEBUG_TRIAGED_MISSING, 21206 UserHandle.USER_SYSTEM)); 21207 proto.end(verifierPackageToken); 21208 } 21209 21210 dumpSharedLibrariesProto(proto); 21211 dumpFeaturesProto(proto); 21212 mSettings.dumpPackagesProto(proto); 21213 mSettings.dumpSharedUsersProto(proto); 21214 dumpCriticalInfo(proto); 21215 } 21216 proto.flush(); 21217 } 21218 21219 private void dumpFeaturesProto(ProtoOutputStream proto) { 21220 synchronized (mAvailableFeatures) { 21221 final int count = mAvailableFeatures.size(); 21222 for (int i = 0; i < count; i++) { 21223 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21224 } 21225 } 21226 } 21227 21228 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21229 final int count = mSharedLibraries.size(); 21230 for (int i = 0; i < count; i++) { 21231 final String libName = mSharedLibraries.keyAt(i); 21232 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21233 if (versionedLib == null) { 21234 continue; 21235 } 21236 final int versionCount = versionedLib.size(); 21237 for (int j = 0; j < versionCount; j++) { 21238 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21239 final long sharedLibraryToken = 21240 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21241 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21242 final boolean isJar = (libEntry.path != null); 21243 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21244 if (isJar) { 21245 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21246 } else { 21247 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21248 } 21249 proto.end(sharedLibraryToken); 21250 } 21251 } 21252 } 21253 21254 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21255 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21256 ipw.println(); 21257 ipw.println("Dexopt state:"); 21258 ipw.increaseIndent(); 21259 Collection<PackageParser.Package> packages = null; 21260 if (packageName != null) { 21261 PackageParser.Package targetPackage = mPackages.get(packageName); 21262 if (targetPackage != null) { 21263 packages = Collections.singletonList(targetPackage); 21264 } else { 21265 ipw.println("Unable to find package: " + packageName); 21266 return; 21267 } 21268 } else { 21269 packages = mPackages.values(); 21270 } 21271 21272 for (PackageParser.Package pkg : packages) { 21273 ipw.println("[" + pkg.packageName + "]"); 21274 ipw.increaseIndent(); 21275 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21276 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21277 ipw.decreaseIndent(); 21278 } 21279 } 21280 21281 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21282 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21283 ipw.println(); 21284 ipw.println("Compiler stats:"); 21285 ipw.increaseIndent(); 21286 Collection<PackageParser.Package> packages = null; 21287 if (packageName != null) { 21288 PackageParser.Package targetPackage = mPackages.get(packageName); 21289 if (targetPackage != null) { 21290 packages = Collections.singletonList(targetPackage); 21291 } else { 21292 ipw.println("Unable to find package: " + packageName); 21293 return; 21294 } 21295 } else { 21296 packages = mPackages.values(); 21297 } 21298 21299 for (PackageParser.Package pkg : packages) { 21300 ipw.println("[" + pkg.packageName + "]"); 21301 ipw.increaseIndent(); 21302 21303 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21304 if (stats == null) { 21305 ipw.println("(No recorded stats)"); 21306 } else { 21307 stats.dump(ipw); 21308 } 21309 ipw.decreaseIndent(); 21310 } 21311 } 21312 21313 private String dumpDomainString(String packageName) { 21314 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21315 .getList(); 21316 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21317 21318 ArraySet<String> result = new ArraySet<>(); 21319 if (iviList.size() > 0) { 21320 for (IntentFilterVerificationInfo ivi : iviList) { 21321 for (String host : ivi.getDomains()) { 21322 result.add(host); 21323 } 21324 } 21325 } 21326 if (filters != null && filters.size() > 0) { 21327 for (IntentFilter filter : filters) { 21328 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21329 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21330 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21331 result.addAll(filter.getHostsList()); 21332 } 21333 } 21334 } 21335 21336 StringBuilder sb = new StringBuilder(result.size() * 16); 21337 for (String domain : result) { 21338 if (sb.length() > 0) sb.append(" "); 21339 sb.append(domain); 21340 } 21341 return sb.toString(); 21342 } 21343 21344 // ------- apps on sdcard specific code ------- 21345 static final boolean DEBUG_SD_INSTALL = false; 21346 21347 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21348 21349 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21350 21351 private boolean mMediaMounted = false; 21352 21353 static String getEncryptKey() { 21354 try { 21355 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21356 SD_ENCRYPTION_KEYSTORE_NAME); 21357 if (sdEncKey == null) { 21358 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21359 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21360 if (sdEncKey == null) { 21361 Slog.e(TAG, "Failed to create encryption keys"); 21362 return null; 21363 } 21364 } 21365 return sdEncKey; 21366 } catch (NoSuchAlgorithmException nsae) { 21367 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21368 return null; 21369 } catch (IOException ioe) { 21370 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21371 return null; 21372 } 21373 } 21374 21375 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21376 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21377 final int size = infos.size(); 21378 final String[] packageNames = new String[size]; 21379 final int[] packageUids = new int[size]; 21380 for (int i = 0; i < size; i++) { 21381 final ApplicationInfo info = infos.get(i); 21382 packageNames[i] = info.packageName; 21383 packageUids[i] = info.uid; 21384 } 21385 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21386 finishedReceiver); 21387 } 21388 21389 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21390 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21391 sendResourcesChangedBroadcast(mediaStatus, replacing, 21392 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21393 } 21394 21395 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21396 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21397 int size = pkgList.length; 21398 if (size > 0) { 21399 // Send broadcasts here 21400 Bundle extras = new Bundle(); 21401 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21402 if (uidArr != null) { 21403 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21404 } 21405 if (replacing) { 21406 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21407 } 21408 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21409 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21410 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21411 } 21412 } 21413 21414 private void loadPrivatePackages(final VolumeInfo vol) { 21415 mHandler.post(new Runnable() { 21416 @Override 21417 public void run() { 21418 loadPrivatePackagesInner(vol); 21419 } 21420 }); 21421 } 21422 21423 private void loadPrivatePackagesInner(VolumeInfo vol) { 21424 final String volumeUuid = vol.fsUuid; 21425 if (TextUtils.isEmpty(volumeUuid)) { 21426 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21427 return; 21428 } 21429 21430 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21431 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21432 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21433 21434 final VersionInfo ver; 21435 final List<PackageSetting> packages; 21436 synchronized (mPackages) { 21437 ver = mSettings.findOrCreateVersion(volumeUuid); 21438 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21439 } 21440 21441 for (PackageSetting ps : packages) { 21442 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21443 synchronized (mInstallLock) { 21444 final PackageParser.Package pkg; 21445 try { 21446 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21447 loaded.add(pkg.applicationInfo); 21448 21449 } catch (PackageManagerException e) { 21450 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21451 } 21452 21453 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21454 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21455 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21456 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21457 } 21458 } 21459 } 21460 21461 // Reconcile app data for all started/unlocked users 21462 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21463 final UserManager um = mContext.getSystemService(UserManager.class); 21464 UserManagerInternal umInternal = getUserManagerInternal(); 21465 for (UserInfo user : um.getUsers()) { 21466 final int flags; 21467 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21468 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21469 } else if (umInternal.isUserRunning(user.id)) { 21470 flags = StorageManager.FLAG_STORAGE_DE; 21471 } else { 21472 continue; 21473 } 21474 21475 try { 21476 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21477 synchronized (mInstallLock) { 21478 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21479 } 21480 } catch (IllegalStateException e) { 21481 // Device was probably ejected, and we'll process that event momentarily 21482 Slog.w(TAG, "Failed to prepare storage: " + e); 21483 } 21484 } 21485 21486 synchronized (mPackages) { 21487 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21488 if (sdkUpdated) { 21489 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21490 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21491 } 21492 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21493 mPermissionCallback); 21494 21495 // Yay, everything is now upgraded 21496 ver.forceCurrent(); 21497 21498 mSettings.writeLPr(); 21499 } 21500 21501 for (PackageFreezer freezer : freezers) { 21502 freezer.close(); 21503 } 21504 21505 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21506 sendResourcesChangedBroadcast(true, false, loaded, null); 21507 mLoadedVolumes.add(vol.getId()); 21508 } 21509 21510 private void unloadPrivatePackages(final VolumeInfo vol) { 21511 mHandler.post(new Runnable() { 21512 @Override 21513 public void run() { 21514 unloadPrivatePackagesInner(vol); 21515 } 21516 }); 21517 } 21518 21519 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21520 final String volumeUuid = vol.fsUuid; 21521 if (TextUtils.isEmpty(volumeUuid)) { 21522 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21523 return; 21524 } 21525 21526 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21527 synchronized (mInstallLock) { 21528 synchronized (mPackages) { 21529 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21530 for (PackageSetting ps : packages) { 21531 if (ps.pkg == null) continue; 21532 21533 final ApplicationInfo info = ps.pkg.applicationInfo; 21534 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21535 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21536 21537 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21538 "unloadPrivatePackagesInner")) { 21539 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21540 false, null)) { 21541 unloaded.add(info); 21542 } else { 21543 Slog.w(TAG, "Failed to unload " + ps.codePath); 21544 } 21545 } 21546 21547 // Try very hard to release any references to this package 21548 // so we don't risk the system server being killed due to 21549 // open FDs 21550 AttributeCache.instance().removePackage(ps.name); 21551 } 21552 21553 mSettings.writeLPr(); 21554 } 21555 } 21556 21557 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21558 sendResourcesChangedBroadcast(false, false, unloaded, null); 21559 mLoadedVolumes.remove(vol.getId()); 21560 21561 // Try very hard to release any references to this path so we don't risk 21562 // the system server being killed due to open FDs 21563 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21564 21565 for (int i = 0; i < 3; i++) { 21566 System.gc(); 21567 System.runFinalization(); 21568 } 21569 } 21570 21571 private void assertPackageKnown(String volumeUuid, String packageName) 21572 throws PackageManagerException { 21573 synchronized (mPackages) { 21574 // Normalize package name to handle renamed packages 21575 packageName = normalizePackageNameLPr(packageName); 21576 21577 final PackageSetting ps = mSettings.mPackages.get(packageName); 21578 if (ps == null) { 21579 throw new PackageManagerException("Package " + packageName + " is unknown"); 21580 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21581 throw new PackageManagerException( 21582 "Package " + packageName + " found on unknown volume " + volumeUuid 21583 + "; expected volume " + ps.volumeUuid); 21584 } 21585 } 21586 } 21587 21588 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21589 throws PackageManagerException { 21590 synchronized (mPackages) { 21591 // Normalize package name to handle renamed packages 21592 packageName = normalizePackageNameLPr(packageName); 21593 21594 final PackageSetting ps = mSettings.mPackages.get(packageName); 21595 if (ps == null) { 21596 throw new PackageManagerException("Package " + packageName + " is unknown"); 21597 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21598 throw new PackageManagerException( 21599 "Package " + packageName + " found on unknown volume " + volumeUuid 21600 + "; expected volume " + ps.volumeUuid); 21601 } else if (!ps.getInstalled(userId)) { 21602 throw new PackageManagerException( 21603 "Package " + packageName + " not installed for user " + userId); 21604 } 21605 } 21606 } 21607 21608 private List<String> collectAbsoluteCodePaths() { 21609 synchronized (mPackages) { 21610 List<String> codePaths = new ArrayList<>(); 21611 final int packageCount = mSettings.mPackages.size(); 21612 for (int i = 0; i < packageCount; i++) { 21613 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21614 codePaths.add(ps.codePath.getAbsolutePath()); 21615 } 21616 return codePaths; 21617 } 21618 } 21619 21620 /** 21621 * Examine all apps present on given mounted volume, and destroy apps that 21622 * aren't expected, either due to uninstallation or reinstallation on 21623 * another volume. 21624 */ 21625 private void reconcileApps(String volumeUuid) { 21626 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21627 List<File> filesToDelete = null; 21628 21629 final File[] files = FileUtils.listFilesOrEmpty( 21630 Environment.getDataAppDirectory(volumeUuid)); 21631 for (File file : files) { 21632 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21633 && !PackageInstallerService.isStageName(file.getName()); 21634 if (!isPackage) { 21635 // Ignore entries which are not packages 21636 continue; 21637 } 21638 21639 String absolutePath = file.getAbsolutePath(); 21640 21641 boolean pathValid = false; 21642 final int absoluteCodePathCount = absoluteCodePaths.size(); 21643 for (int i = 0; i < absoluteCodePathCount; i++) { 21644 String absoluteCodePath = absoluteCodePaths.get(i); 21645 if (absolutePath.startsWith(absoluteCodePath)) { 21646 pathValid = true; 21647 break; 21648 } 21649 } 21650 21651 if (!pathValid) { 21652 if (filesToDelete == null) { 21653 filesToDelete = new ArrayList<>(); 21654 } 21655 filesToDelete.add(file); 21656 } 21657 } 21658 21659 if (filesToDelete != null) { 21660 final int fileToDeleteCount = filesToDelete.size(); 21661 for (int i = 0; i < fileToDeleteCount; i++) { 21662 File fileToDelete = filesToDelete.get(i); 21663 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21664 synchronized (mInstallLock) { 21665 removeCodePathLI(fileToDelete); 21666 } 21667 } 21668 } 21669 } 21670 21671 /** 21672 * Reconcile all app data for the given user. 21673 * <p> 21674 * Verifies that directories exist and that ownership and labeling is 21675 * correct for all installed apps on all mounted volumes. 21676 */ 21677 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21678 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21679 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21680 final String volumeUuid = vol.getFsUuid(); 21681 synchronized (mInstallLock) { 21682 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21683 } 21684 } 21685 } 21686 21687 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21688 boolean migrateAppData) { 21689 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21690 } 21691 21692 /** 21693 * Reconcile all app data on given mounted volume. 21694 * <p> 21695 * Destroys app data that isn't expected, either due to uninstallation or 21696 * reinstallation on another volume. 21697 * <p> 21698 * Verifies that directories exist and that ownership and labeling is 21699 * correct for all installed apps. 21700 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21701 */ 21702 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21703 boolean migrateAppData, boolean onlyCoreApps) { 21704 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21705 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21706 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21707 21708 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21709 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21710 21711 // First look for stale data that doesn't belong, and check if things 21712 // have changed since we did our last restorecon 21713 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21714 if (StorageManager.isFileEncryptedNativeOrEmulated() 21715 && !StorageManager.isUserKeyUnlocked(userId)) { 21716 throw new RuntimeException( 21717 "Yikes, someone asked us to reconcile CE storage while " + userId 21718 + " was still locked; this would have caused massive data loss!"); 21719 } 21720 21721 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21722 for (File file : files) { 21723 final String packageName = file.getName(); 21724 try { 21725 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21726 } catch (PackageManagerException e) { 21727 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21728 try { 21729 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21730 StorageManager.FLAG_STORAGE_CE, 0); 21731 } catch (InstallerException e2) { 21732 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21733 } 21734 } 21735 } 21736 } 21737 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21738 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21739 for (File file : files) { 21740 final String packageName = file.getName(); 21741 try { 21742 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21743 } catch (PackageManagerException e) { 21744 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21745 try { 21746 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21747 StorageManager.FLAG_STORAGE_DE, 0); 21748 } catch (InstallerException e2) { 21749 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21750 } 21751 } 21752 } 21753 } 21754 21755 // Ensure that data directories are ready to roll for all packages 21756 // installed for this volume and user 21757 final List<PackageSetting> packages; 21758 synchronized (mPackages) { 21759 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21760 } 21761 int preparedCount = 0; 21762 for (PackageSetting ps : packages) { 21763 final String packageName = ps.name; 21764 if (ps.pkg == null) { 21765 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21766 // TODO: might be due to legacy ASEC apps; we should circle back 21767 // and reconcile again once they're scanned 21768 continue; 21769 } 21770 // Skip non-core apps if requested 21771 if (onlyCoreApps && !ps.pkg.coreApp) { 21772 result.add(packageName); 21773 continue; 21774 } 21775 21776 if (ps.getInstalled(userId)) { 21777 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21778 preparedCount++; 21779 } 21780 } 21781 21782 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21783 return result; 21784 } 21785 21786 /** 21787 * Prepare app data for the given app just after it was installed or 21788 * upgraded. This method carefully only touches users that it's installed 21789 * for, and it forces a restorecon to handle any seinfo changes. 21790 * <p> 21791 * Verifies that directories exist and that ownership and labeling is 21792 * correct for all installed apps. If there is an ownership mismatch, it 21793 * will try recovering system apps by wiping data; third-party app data is 21794 * left intact. 21795 * <p> 21796 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21797 */ 21798 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21799 final PackageSetting ps; 21800 synchronized (mPackages) { 21801 ps = mSettings.mPackages.get(pkg.packageName); 21802 mSettings.writeKernelMappingLPr(ps); 21803 } 21804 21805 final UserManager um = mContext.getSystemService(UserManager.class); 21806 UserManagerInternal umInternal = getUserManagerInternal(); 21807 for (UserInfo user : um.getUsers()) { 21808 final int flags; 21809 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21810 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21811 } else if (umInternal.isUserRunning(user.id)) { 21812 flags = StorageManager.FLAG_STORAGE_DE; 21813 } else { 21814 continue; 21815 } 21816 21817 if (ps.getInstalled(user.id)) { 21818 // TODO: when user data is locked, mark that we're still dirty 21819 prepareAppDataLIF(pkg, user.id, flags); 21820 } 21821 } 21822 } 21823 21824 /** 21825 * Prepare app data for the given app. 21826 * <p> 21827 * Verifies that directories exist and that ownership and labeling is 21828 * correct for all installed apps. If there is an ownership mismatch, this 21829 * will try recovering system apps by wiping data; third-party app data is 21830 * left intact. 21831 */ 21832 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21833 if (pkg == null) { 21834 Slog.wtf(TAG, "Package was null!", new Throwable()); 21835 return; 21836 } 21837 prepareAppDataLeafLIF(pkg, userId, flags); 21838 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21839 for (int i = 0; i < childCount; i++) { 21840 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21841 } 21842 } 21843 21844 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21845 boolean maybeMigrateAppData) { 21846 prepareAppDataLIF(pkg, userId, flags); 21847 21848 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21849 // We may have just shuffled around app data directories, so 21850 // prepare them one more time 21851 prepareAppDataLIF(pkg, userId, flags); 21852 } 21853 } 21854 21855 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21856 if (DEBUG_APP_DATA) { 21857 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21858 + Integer.toHexString(flags)); 21859 } 21860 21861 final String volumeUuid = pkg.volumeUuid; 21862 final String packageName = pkg.packageName; 21863 final ApplicationInfo app = pkg.applicationInfo; 21864 final int appId = UserHandle.getAppId(app.uid); 21865 21866 Preconditions.checkNotNull(app.seInfo); 21867 21868 long ceDataInode = -1; 21869 try { 21870 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21871 appId, app.seInfo, app.targetSdkVersion); 21872 } catch (InstallerException e) { 21873 if (app.isSystemApp()) { 21874 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21875 + ", but trying to recover: " + e); 21876 destroyAppDataLeafLIF(pkg, userId, flags); 21877 try { 21878 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21879 appId, app.seInfo, app.targetSdkVersion); 21880 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21881 } catch (InstallerException e2) { 21882 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21883 } 21884 } else { 21885 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21886 } 21887 } 21888 21889 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21890 // TODO: mark this structure as dirty so we persist it! 21891 synchronized (mPackages) { 21892 final PackageSetting ps = mSettings.mPackages.get(packageName); 21893 if (ps != null) { 21894 ps.setCeDataInode(ceDataInode, userId); 21895 } 21896 } 21897 } 21898 21899 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21900 } 21901 21902 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21903 if (pkg == null) { 21904 Slog.wtf(TAG, "Package was null!", new Throwable()); 21905 return; 21906 } 21907 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21908 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21909 for (int i = 0; i < childCount; i++) { 21910 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21911 } 21912 } 21913 21914 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21915 final String volumeUuid = pkg.volumeUuid; 21916 final String packageName = pkg.packageName; 21917 final ApplicationInfo app = pkg.applicationInfo; 21918 21919 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21920 // Create a native library symlink only if we have native libraries 21921 // and if the native libraries are 32 bit libraries. We do not provide 21922 // this symlink for 64 bit libraries. 21923 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21924 final String nativeLibPath = app.nativeLibraryDir; 21925 try { 21926 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21927 nativeLibPath, userId); 21928 } catch (InstallerException e) { 21929 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21930 } 21931 } 21932 } 21933 } 21934 21935 /** 21936 * For system apps on non-FBE devices, this method migrates any existing 21937 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21938 * requested by the app. 21939 */ 21940 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21941 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 21942 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21943 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21944 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21945 try { 21946 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21947 storageTarget); 21948 } catch (InstallerException e) { 21949 logCriticalInfo(Log.WARN, 21950 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21951 } 21952 return true; 21953 } else { 21954 return false; 21955 } 21956 } 21957 21958 public PackageFreezer freezePackage(String packageName, String killReason) { 21959 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21960 } 21961 21962 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21963 return new PackageFreezer(packageName, userId, killReason); 21964 } 21965 21966 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21967 String killReason) { 21968 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21969 } 21970 21971 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21972 String killReason) { 21973 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21974 return new PackageFreezer(); 21975 } else { 21976 return freezePackage(packageName, userId, killReason); 21977 } 21978 } 21979 21980 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 21981 String killReason) { 21982 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 21983 } 21984 21985 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 21986 String killReason) { 21987 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 21988 return new PackageFreezer(); 21989 } else { 21990 return freezePackage(packageName, userId, killReason); 21991 } 21992 } 21993 21994 /** 21995 * Class that freezes and kills the given package upon creation, and 21996 * unfreezes it upon closing. This is typically used when doing surgery on 21997 * app code/data to prevent the app from running while you're working. 21998 */ 21999 private class PackageFreezer implements AutoCloseable { 22000 private final String mPackageName; 22001 private final PackageFreezer[] mChildren; 22002 22003 private final boolean mWeFroze; 22004 22005 private final AtomicBoolean mClosed = new AtomicBoolean(); 22006 private final CloseGuard mCloseGuard = CloseGuard.get(); 22007 22008 /** 22009 * Create and return a stub freezer that doesn't actually do anything, 22010 * typically used when someone requested 22011 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22012 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22013 */ 22014 public PackageFreezer() { 22015 mPackageName = null; 22016 mChildren = null; 22017 mWeFroze = false; 22018 mCloseGuard.open("close"); 22019 } 22020 22021 public PackageFreezer(String packageName, int userId, String killReason) { 22022 synchronized (mPackages) { 22023 mPackageName = packageName; 22024 mWeFroze = mFrozenPackages.add(mPackageName); 22025 22026 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22027 if (ps != null) { 22028 killApplication(ps.name, ps.appId, userId, killReason); 22029 } 22030 22031 final PackageParser.Package p = mPackages.get(packageName); 22032 if (p != null && p.childPackages != null) { 22033 final int N = p.childPackages.size(); 22034 mChildren = new PackageFreezer[N]; 22035 for (int i = 0; i < N; i++) { 22036 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22037 userId, killReason); 22038 } 22039 } else { 22040 mChildren = null; 22041 } 22042 } 22043 mCloseGuard.open("close"); 22044 } 22045 22046 @Override 22047 protected void finalize() throws Throwable { 22048 try { 22049 if (mCloseGuard != null) { 22050 mCloseGuard.warnIfOpen(); 22051 } 22052 22053 close(); 22054 } finally { 22055 super.finalize(); 22056 } 22057 } 22058 22059 @Override 22060 public void close() { 22061 mCloseGuard.close(); 22062 if (mClosed.compareAndSet(false, true)) { 22063 synchronized (mPackages) { 22064 if (mWeFroze) { 22065 mFrozenPackages.remove(mPackageName); 22066 } 22067 22068 if (mChildren != null) { 22069 for (PackageFreezer freezer : mChildren) { 22070 freezer.close(); 22071 } 22072 } 22073 } 22074 } 22075 } 22076 } 22077 22078 /** 22079 * Verify that given package is currently frozen. 22080 */ 22081 private void checkPackageFrozen(String packageName) { 22082 synchronized (mPackages) { 22083 if (!mFrozenPackages.contains(packageName)) { 22084 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22085 } 22086 } 22087 } 22088 22089 @Override 22090 public int movePackage(final String packageName, final String volumeUuid) { 22091 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22092 22093 final int callingUid = Binder.getCallingUid(); 22094 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22095 final int moveId = mNextMoveId.getAndIncrement(); 22096 mHandler.post(new Runnable() { 22097 @Override 22098 public void run() { 22099 try { 22100 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22101 } catch (PackageManagerException e) { 22102 Slog.w(TAG, "Failed to move " + packageName, e); 22103 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22104 } 22105 } 22106 }); 22107 return moveId; 22108 } 22109 22110 private void movePackageInternal(final String packageName, final String volumeUuid, 22111 final int moveId, final int callingUid, UserHandle user) 22112 throws PackageManagerException { 22113 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22114 final PackageManager pm = mContext.getPackageManager(); 22115 22116 final boolean currentAsec; 22117 final String currentVolumeUuid; 22118 final File codeFile; 22119 final String installerPackageName; 22120 final String packageAbiOverride; 22121 final int appId; 22122 final String seinfo; 22123 final String label; 22124 final int targetSdkVersion; 22125 final PackageFreezer freezer; 22126 final int[] installedUserIds; 22127 22128 // reader 22129 synchronized (mPackages) { 22130 final PackageParser.Package pkg = mPackages.get(packageName); 22131 final PackageSetting ps = mSettings.mPackages.get(packageName); 22132 if (pkg == null 22133 || ps == null 22134 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22135 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22136 } 22137 if (pkg.applicationInfo.isSystemApp()) { 22138 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22139 "Cannot move system application"); 22140 } 22141 22142 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22143 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22144 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22145 if (isInternalStorage && !allow3rdPartyOnInternal) { 22146 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22147 "3rd party apps are not allowed on internal storage"); 22148 } 22149 22150 if (pkg.applicationInfo.isExternalAsec()) { 22151 currentAsec = true; 22152 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22153 } else if (pkg.applicationInfo.isForwardLocked()) { 22154 currentAsec = true; 22155 currentVolumeUuid = "forward_locked"; 22156 } else { 22157 currentAsec = false; 22158 currentVolumeUuid = ps.volumeUuid; 22159 22160 final File probe = new File(pkg.codePath); 22161 final File probeOat = new File(probe, "oat"); 22162 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22163 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22164 "Move only supported for modern cluster style installs"); 22165 } 22166 } 22167 22168 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22169 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22170 "Package already moved to " + volumeUuid); 22171 } 22172 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22173 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22174 "Device admin cannot be moved"); 22175 } 22176 22177 if (mFrozenPackages.contains(packageName)) { 22178 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22179 "Failed to move already frozen package"); 22180 } 22181 22182 codeFile = new File(pkg.codePath); 22183 installerPackageName = ps.installerPackageName; 22184 packageAbiOverride = ps.cpuAbiOverrideString; 22185 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22186 seinfo = pkg.applicationInfo.seInfo; 22187 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22188 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22189 freezer = freezePackage(packageName, "movePackageInternal"); 22190 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22191 } 22192 22193 final Bundle extras = new Bundle(); 22194 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22195 extras.putString(Intent.EXTRA_TITLE, label); 22196 mMoveCallbacks.notifyCreated(moveId, extras); 22197 22198 int installFlags; 22199 final boolean moveCompleteApp; 22200 final File measurePath; 22201 22202 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22203 installFlags = INSTALL_INTERNAL; 22204 moveCompleteApp = !currentAsec; 22205 measurePath = Environment.getDataAppDirectory(volumeUuid); 22206 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22207 installFlags = INSTALL_EXTERNAL; 22208 moveCompleteApp = false; 22209 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22210 } else { 22211 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22212 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22213 || !volume.isMountedWritable()) { 22214 freezer.close(); 22215 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22216 "Move location not mounted private volume"); 22217 } 22218 22219 Preconditions.checkState(!currentAsec); 22220 22221 installFlags = INSTALL_INTERNAL; 22222 moveCompleteApp = true; 22223 measurePath = Environment.getDataAppDirectory(volumeUuid); 22224 } 22225 22226 // If we're moving app data around, we need all the users unlocked 22227 if (moveCompleteApp) { 22228 for (int userId : installedUserIds) { 22229 if (StorageManager.isFileEncryptedNativeOrEmulated() 22230 && !StorageManager.isUserKeyUnlocked(userId)) { 22231 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22232 "User " + userId + " must be unlocked"); 22233 } 22234 } 22235 } 22236 22237 final PackageStats stats = new PackageStats(null, -1); 22238 synchronized (mInstaller) { 22239 for (int userId : installedUserIds) { 22240 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22241 freezer.close(); 22242 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22243 "Failed to measure package size"); 22244 } 22245 } 22246 } 22247 22248 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22249 + stats.dataSize); 22250 22251 final long startFreeBytes = measurePath.getUsableSpace(); 22252 final long sizeBytes; 22253 if (moveCompleteApp) { 22254 sizeBytes = stats.codeSize + stats.dataSize; 22255 } else { 22256 sizeBytes = stats.codeSize; 22257 } 22258 22259 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22260 freezer.close(); 22261 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22262 "Not enough free space to move"); 22263 } 22264 22265 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22266 22267 final CountDownLatch installedLatch = new CountDownLatch(1); 22268 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22269 @Override 22270 public void onUserActionRequired(Intent intent) throws RemoteException { 22271 throw new IllegalStateException(); 22272 } 22273 22274 @Override 22275 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22276 Bundle extras) throws RemoteException { 22277 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22278 + PackageManager.installStatusToString(returnCode, msg)); 22279 22280 installedLatch.countDown(); 22281 freezer.close(); 22282 22283 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22284 switch (status) { 22285 case PackageInstaller.STATUS_SUCCESS: 22286 mMoveCallbacks.notifyStatusChanged(moveId, 22287 PackageManager.MOVE_SUCCEEDED); 22288 break; 22289 case PackageInstaller.STATUS_FAILURE_STORAGE: 22290 mMoveCallbacks.notifyStatusChanged(moveId, 22291 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22292 break; 22293 default: 22294 mMoveCallbacks.notifyStatusChanged(moveId, 22295 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22296 break; 22297 } 22298 } 22299 }; 22300 22301 final MoveInfo move; 22302 if (moveCompleteApp) { 22303 // Kick off a thread to report progress estimates 22304 new Thread() { 22305 @Override 22306 public void run() { 22307 while (true) { 22308 try { 22309 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22310 break; 22311 } 22312 } catch (InterruptedException ignored) { 22313 } 22314 22315 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22316 final int progress = 10 + (int) MathUtils.constrain( 22317 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22318 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22319 } 22320 } 22321 }.start(); 22322 22323 final String dataAppName = codeFile.getName(); 22324 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22325 dataAppName, appId, seinfo, targetSdkVersion); 22326 } else { 22327 move = null; 22328 } 22329 22330 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22331 22332 final Message msg = mHandler.obtainMessage(INIT_COPY); 22333 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22334 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22335 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22336 packageAbiOverride, null /*grantedPermissions*/, 22337 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22338 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22339 msg.obj = params; 22340 22341 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22342 System.identityHashCode(msg.obj)); 22343 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22344 System.identityHashCode(msg.obj)); 22345 22346 mHandler.sendMessage(msg); 22347 } 22348 22349 @Override 22350 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22352 22353 final int realMoveId = mNextMoveId.getAndIncrement(); 22354 final Bundle extras = new Bundle(); 22355 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22356 mMoveCallbacks.notifyCreated(realMoveId, extras); 22357 22358 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22359 @Override 22360 public void onCreated(int moveId, Bundle extras) { 22361 // Ignored 22362 } 22363 22364 @Override 22365 public void onStatusChanged(int moveId, int status, long estMillis) { 22366 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22367 } 22368 }; 22369 22370 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22371 storage.setPrimaryStorageUuid(volumeUuid, callback); 22372 return realMoveId; 22373 } 22374 22375 @Override 22376 public int getMoveStatus(int moveId) { 22377 mContext.enforceCallingOrSelfPermission( 22378 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22379 return mMoveCallbacks.mLastStatus.get(moveId); 22380 } 22381 22382 @Override 22383 public void registerMoveCallback(IPackageMoveObserver callback) { 22384 mContext.enforceCallingOrSelfPermission( 22385 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22386 mMoveCallbacks.register(callback); 22387 } 22388 22389 @Override 22390 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22391 mContext.enforceCallingOrSelfPermission( 22392 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22393 mMoveCallbacks.unregister(callback); 22394 } 22395 22396 @Override 22397 public boolean setInstallLocation(int loc) { 22398 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22399 null); 22400 if (getInstallLocation() == loc) { 22401 return true; 22402 } 22403 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22404 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22405 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22406 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22407 return true; 22408 } 22409 return false; 22410 } 22411 22412 @Override 22413 public int getInstallLocation() { 22414 // allow instant app access 22415 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22416 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22417 PackageHelper.APP_INSTALL_AUTO); 22418 } 22419 22420 /** Called by UserManagerService */ 22421 void cleanUpUser(UserManagerService userManager, int userHandle) { 22422 synchronized (mPackages) { 22423 mDirtyUsers.remove(userHandle); 22424 mUserNeedsBadging.delete(userHandle); 22425 mSettings.removeUserLPw(userHandle); 22426 mPendingBroadcasts.remove(userHandle); 22427 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22428 removeUnusedPackagesLPw(userManager, userHandle); 22429 } 22430 } 22431 22432 /** 22433 * We're removing userHandle and would like to remove any downloaded packages 22434 * that are no longer in use by any other user. 22435 * @param userHandle the user being removed 22436 */ 22437 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22438 final boolean DEBUG_CLEAN_APKS = false; 22439 int [] users = userManager.getUserIds(); 22440 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22441 while (psit.hasNext()) { 22442 PackageSetting ps = psit.next(); 22443 if (ps.pkg == null) { 22444 continue; 22445 } 22446 final String packageName = ps.pkg.packageName; 22447 // Skip over if system app 22448 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22449 continue; 22450 } 22451 if (DEBUG_CLEAN_APKS) { 22452 Slog.i(TAG, "Checking package " + packageName); 22453 } 22454 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22455 if (keep) { 22456 if (DEBUG_CLEAN_APKS) { 22457 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22458 } 22459 } else { 22460 for (int i = 0; i < users.length; i++) { 22461 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22462 keep = true; 22463 if (DEBUG_CLEAN_APKS) { 22464 Slog.i(TAG, " Keeping package " + packageName + " for user " 22465 + users[i]); 22466 } 22467 break; 22468 } 22469 } 22470 } 22471 if (!keep) { 22472 if (DEBUG_CLEAN_APKS) { 22473 Slog.i(TAG, " Removing package " + packageName); 22474 } 22475 mHandler.post(new Runnable() { 22476 public void run() { 22477 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22478 userHandle, 0); 22479 } //end run 22480 }); 22481 } 22482 } 22483 } 22484 22485 /** Called by UserManagerService */ 22486 void createNewUser(int userId, String[] disallowedPackages) { 22487 synchronized (mInstallLock) { 22488 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22489 } 22490 synchronized (mPackages) { 22491 scheduleWritePackageRestrictionsLocked(userId); 22492 scheduleWritePackageListLocked(userId); 22493 applyFactoryDefaultBrowserLPw(userId); 22494 primeDomainVerificationsLPw(userId); 22495 } 22496 } 22497 22498 void onNewUserCreated(final int userId) { 22499 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22500 synchronized(mPackages) { 22501 // If permission review for legacy apps is required, we represent 22502 // dagerous permissions for such apps as always granted runtime 22503 // permissions to keep per user flag state whether review is needed. 22504 // Hence, if a new user is added we have to propagate dangerous 22505 // permission grants for these legacy apps. 22506 if (mSettings.mPermissions.mPermissionReviewRequired) { 22507// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22508 mPermissionManager.updateAllPermissions( 22509 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22510 mPermissionCallback); 22511 } 22512 } 22513 } 22514 22515 @Override 22516 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22517 mContext.enforceCallingOrSelfPermission( 22518 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22519 "Only package verification agents can read the verifier device identity"); 22520 22521 synchronized (mPackages) { 22522 return mSettings.getVerifierDeviceIdentityLPw(); 22523 } 22524 } 22525 22526 @Override 22527 public void setPermissionEnforced(String permission, boolean enforced) { 22528 // TODO: Now that we no longer change GID for storage, this should to away. 22529 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22530 "setPermissionEnforced"); 22531 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22532 synchronized (mPackages) { 22533 if (mSettings.mReadExternalStorageEnforced == null 22534 || mSettings.mReadExternalStorageEnforced != enforced) { 22535 mSettings.mReadExternalStorageEnforced = 22536 enforced ? Boolean.TRUE : Boolean.FALSE; 22537 mSettings.writeLPr(); 22538 } 22539 } 22540 // kill any non-foreground processes so we restart them and 22541 // grant/revoke the GID. 22542 final IActivityManager am = ActivityManager.getService(); 22543 if (am != null) { 22544 final long token = Binder.clearCallingIdentity(); 22545 try { 22546 am.killProcessesBelowForeground("setPermissionEnforcement"); 22547 } catch (RemoteException e) { 22548 } finally { 22549 Binder.restoreCallingIdentity(token); 22550 } 22551 } 22552 } else { 22553 throw new IllegalArgumentException("No selective enforcement for " + permission); 22554 } 22555 } 22556 22557 @Override 22558 @Deprecated 22559 public boolean isPermissionEnforced(String permission) { 22560 // allow instant applications 22561 return true; 22562 } 22563 22564 @Override 22565 public boolean isStorageLow() { 22566 // allow instant applications 22567 final long token = Binder.clearCallingIdentity(); 22568 try { 22569 final DeviceStorageMonitorInternal 22570 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22571 if (dsm != null) { 22572 return dsm.isMemoryLow(); 22573 } else { 22574 return false; 22575 } 22576 } finally { 22577 Binder.restoreCallingIdentity(token); 22578 } 22579 } 22580 22581 @Override 22582 public IPackageInstaller getPackageInstaller() { 22583 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22584 return null; 22585 } 22586 return mInstallerService; 22587 } 22588 22589 @Override 22590 public IArtManager getArtManager() { 22591 return mArtManagerService; 22592 } 22593 22594 private boolean userNeedsBadging(int userId) { 22595 int index = mUserNeedsBadging.indexOfKey(userId); 22596 if (index < 0) { 22597 final UserInfo userInfo; 22598 final long token = Binder.clearCallingIdentity(); 22599 try { 22600 userInfo = sUserManager.getUserInfo(userId); 22601 } finally { 22602 Binder.restoreCallingIdentity(token); 22603 } 22604 final boolean b; 22605 if (userInfo != null && userInfo.isManagedProfile()) { 22606 b = true; 22607 } else { 22608 b = false; 22609 } 22610 mUserNeedsBadging.put(userId, b); 22611 return b; 22612 } 22613 return mUserNeedsBadging.valueAt(index); 22614 } 22615 22616 @Override 22617 public KeySet getKeySetByAlias(String packageName, String alias) { 22618 if (packageName == null || alias == null) { 22619 return null; 22620 } 22621 synchronized(mPackages) { 22622 final PackageParser.Package pkg = mPackages.get(packageName); 22623 if (pkg == null) { 22624 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22625 throw new IllegalArgumentException("Unknown package: " + packageName); 22626 } 22627 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22628 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22629 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22630 throw new IllegalArgumentException("Unknown package: " + packageName); 22631 } 22632 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22633 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22634 } 22635 } 22636 22637 @Override 22638 public KeySet getSigningKeySet(String packageName) { 22639 if (packageName == null) { 22640 return null; 22641 } 22642 synchronized(mPackages) { 22643 final int callingUid = Binder.getCallingUid(); 22644 final int callingUserId = UserHandle.getUserId(callingUid); 22645 final PackageParser.Package pkg = mPackages.get(packageName); 22646 if (pkg == null) { 22647 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22648 throw new IllegalArgumentException("Unknown package: " + packageName); 22649 } 22650 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22651 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22652 // filter and pretend the package doesn't exist 22653 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22654 + ", uid:" + callingUid); 22655 throw new IllegalArgumentException("Unknown package: " + packageName); 22656 } 22657 if (pkg.applicationInfo.uid != callingUid 22658 && Process.SYSTEM_UID != callingUid) { 22659 throw new SecurityException("May not access signing KeySet of other apps."); 22660 } 22661 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22662 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22663 } 22664 } 22665 22666 @Override 22667 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22668 final int callingUid = Binder.getCallingUid(); 22669 if (getInstantAppPackageName(callingUid) != null) { 22670 return false; 22671 } 22672 if (packageName == null || ks == null) { 22673 return false; 22674 } 22675 synchronized(mPackages) { 22676 final PackageParser.Package pkg = mPackages.get(packageName); 22677 if (pkg == null 22678 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22679 UserHandle.getUserId(callingUid))) { 22680 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22681 throw new IllegalArgumentException("Unknown package: " + packageName); 22682 } 22683 IBinder ksh = ks.getToken(); 22684 if (ksh instanceof KeySetHandle) { 22685 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22686 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22687 } 22688 return false; 22689 } 22690 } 22691 22692 @Override 22693 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22694 final int callingUid = Binder.getCallingUid(); 22695 if (getInstantAppPackageName(callingUid) != null) { 22696 return false; 22697 } 22698 if (packageName == null || ks == null) { 22699 return false; 22700 } 22701 synchronized(mPackages) { 22702 final PackageParser.Package pkg = mPackages.get(packageName); 22703 if (pkg == null 22704 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22705 UserHandle.getUserId(callingUid))) { 22706 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22707 throw new IllegalArgumentException("Unknown package: " + packageName); 22708 } 22709 IBinder ksh = ks.getToken(); 22710 if (ksh instanceof KeySetHandle) { 22711 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22712 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22713 } 22714 return false; 22715 } 22716 } 22717 22718 private void deletePackageIfUnusedLPr(final String packageName) { 22719 PackageSetting ps = mSettings.mPackages.get(packageName); 22720 if (ps == null) { 22721 return; 22722 } 22723 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22724 // TODO Implement atomic delete if package is unused 22725 // It is currently possible that the package will be deleted even if it is installed 22726 // after this method returns. 22727 mHandler.post(new Runnable() { 22728 public void run() { 22729 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22730 0, PackageManager.DELETE_ALL_USERS); 22731 } 22732 }); 22733 } 22734 } 22735 22736 /** 22737 * Check and throw if the given before/after packages would be considered a 22738 * downgrade. 22739 */ 22740 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22741 throws PackageManagerException { 22742 if (after.getLongVersionCode() < before.getLongVersionCode()) { 22743 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22744 "Update version code " + after.versionCode + " is older than current " 22745 + before.getLongVersionCode()); 22746 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 22747 if (after.baseRevisionCode < before.baseRevisionCode) { 22748 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22749 "Update base revision code " + after.baseRevisionCode 22750 + " is older than current " + before.baseRevisionCode); 22751 } 22752 22753 if (!ArrayUtils.isEmpty(after.splitNames)) { 22754 for (int i = 0; i < after.splitNames.length; i++) { 22755 final String splitName = after.splitNames[i]; 22756 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22757 if (j != -1) { 22758 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22759 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22760 "Update split " + splitName + " revision code " 22761 + after.splitRevisionCodes[i] + " is older than current " 22762 + before.splitRevisionCodes[j]); 22763 } 22764 } 22765 } 22766 } 22767 } 22768 } 22769 22770 private static class MoveCallbacks extends Handler { 22771 private static final int MSG_CREATED = 1; 22772 private static final int MSG_STATUS_CHANGED = 2; 22773 22774 private final RemoteCallbackList<IPackageMoveObserver> 22775 mCallbacks = new RemoteCallbackList<>(); 22776 22777 private final SparseIntArray mLastStatus = new SparseIntArray(); 22778 22779 public MoveCallbacks(Looper looper) { 22780 super(looper); 22781 } 22782 22783 public void register(IPackageMoveObserver callback) { 22784 mCallbacks.register(callback); 22785 } 22786 22787 public void unregister(IPackageMoveObserver callback) { 22788 mCallbacks.unregister(callback); 22789 } 22790 22791 @Override 22792 public void handleMessage(Message msg) { 22793 final SomeArgs args = (SomeArgs) msg.obj; 22794 final int n = mCallbacks.beginBroadcast(); 22795 for (int i = 0; i < n; i++) { 22796 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22797 try { 22798 invokeCallback(callback, msg.what, args); 22799 } catch (RemoteException ignored) { 22800 } 22801 } 22802 mCallbacks.finishBroadcast(); 22803 args.recycle(); 22804 } 22805 22806 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22807 throws RemoteException { 22808 switch (what) { 22809 case MSG_CREATED: { 22810 callback.onCreated(args.argi1, (Bundle) args.arg2); 22811 break; 22812 } 22813 case MSG_STATUS_CHANGED: { 22814 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22815 break; 22816 } 22817 } 22818 } 22819 22820 private void notifyCreated(int moveId, Bundle extras) { 22821 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22822 22823 final SomeArgs args = SomeArgs.obtain(); 22824 args.argi1 = moveId; 22825 args.arg2 = extras; 22826 obtainMessage(MSG_CREATED, args).sendToTarget(); 22827 } 22828 22829 private void notifyStatusChanged(int moveId, int status) { 22830 notifyStatusChanged(moveId, status, -1); 22831 } 22832 22833 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22834 Slog.v(TAG, "Move " + moveId + " status " + status); 22835 22836 final SomeArgs args = SomeArgs.obtain(); 22837 args.argi1 = moveId; 22838 args.argi2 = status; 22839 args.arg3 = estMillis; 22840 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22841 22842 synchronized (mLastStatus) { 22843 mLastStatus.put(moveId, status); 22844 } 22845 } 22846 } 22847 22848 private final static class OnPermissionChangeListeners extends Handler { 22849 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22850 22851 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22852 new RemoteCallbackList<>(); 22853 22854 public OnPermissionChangeListeners(Looper looper) { 22855 super(looper); 22856 } 22857 22858 @Override 22859 public void handleMessage(Message msg) { 22860 switch (msg.what) { 22861 case MSG_ON_PERMISSIONS_CHANGED: { 22862 final int uid = msg.arg1; 22863 handleOnPermissionsChanged(uid); 22864 } break; 22865 } 22866 } 22867 22868 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22869 mPermissionListeners.register(listener); 22870 22871 } 22872 22873 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22874 mPermissionListeners.unregister(listener); 22875 } 22876 22877 public void onPermissionsChanged(int uid) { 22878 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22879 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22880 } 22881 } 22882 22883 private void handleOnPermissionsChanged(int uid) { 22884 final int count = mPermissionListeners.beginBroadcast(); 22885 try { 22886 for (int i = 0; i < count; i++) { 22887 IOnPermissionsChangeListener callback = mPermissionListeners 22888 .getBroadcastItem(i); 22889 try { 22890 callback.onPermissionsChanged(uid); 22891 } catch (RemoteException e) { 22892 Log.e(TAG, "Permission listener is dead", e); 22893 } 22894 } 22895 } finally { 22896 mPermissionListeners.finishBroadcast(); 22897 } 22898 } 22899 } 22900 22901 private class PackageManagerNative extends IPackageManagerNative.Stub { 22902 @Override 22903 public String[] getNamesForUids(int[] uids) throws RemoteException { 22904 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22905 // massage results so they can be parsed by the native binder 22906 for (int i = results.length - 1; i >= 0; --i) { 22907 if (results[i] == null) { 22908 results[i] = ""; 22909 } 22910 } 22911 return results; 22912 } 22913 22914 // NB: this differentiates between preloads and sideloads 22915 @Override 22916 public String getInstallerForPackage(String packageName) throws RemoteException { 22917 final String installerName = getInstallerPackageName(packageName); 22918 if (!TextUtils.isEmpty(installerName)) { 22919 return installerName; 22920 } 22921 // differentiate between preload and sideload 22922 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22923 ApplicationInfo appInfo = getApplicationInfo(packageName, 22924 /*flags*/ 0, 22925 /*userId*/ callingUser); 22926 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22927 return "preload"; 22928 } 22929 return ""; 22930 } 22931 22932 @Override 22933 public long getVersionCodeForPackage(String packageName) throws RemoteException { 22934 try { 22935 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22936 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 22937 if (pInfo != null) { 22938 return pInfo.getLongVersionCode(); 22939 } 22940 } catch (Exception e) { 22941 } 22942 return 0; 22943 } 22944 } 22945 22946 private class PackageManagerInternalImpl extends PackageManagerInternal { 22947 @Override 22948 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 22949 int flagValues, int userId) { 22950 PackageManagerService.this.updatePermissionFlags( 22951 permName, packageName, flagMask, flagValues, userId); 22952 } 22953 22954 @Override 22955 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 22956 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 22957 } 22958 22959 @Override 22960 public boolean isInstantApp(String packageName, int userId) { 22961 return PackageManagerService.this.isInstantApp(packageName, userId); 22962 } 22963 22964 @Override 22965 public String getInstantAppPackageName(int uid) { 22966 return PackageManagerService.this.getInstantAppPackageName(uid); 22967 } 22968 22969 @Override 22970 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 22971 synchronized (mPackages) { 22972 return PackageManagerService.this.filterAppAccessLPr( 22973 (PackageSetting) pkg.mExtras, callingUid, userId); 22974 } 22975 } 22976 22977 @Override 22978 public PackageParser.Package getPackage(String packageName) { 22979 synchronized (mPackages) { 22980 packageName = resolveInternalPackageNameLPr( 22981 packageName, PackageManager.VERSION_CODE_HIGHEST); 22982 return mPackages.get(packageName); 22983 } 22984 } 22985 22986 @Override 22987 public PackageList getPackageList(PackageListObserver observer) { 22988 synchronized (mPackages) { 22989 final int N = mPackages.size(); 22990 final ArrayList<String> list = new ArrayList<>(N); 22991 for (int i = 0; i < N; i++) { 22992 list.add(mPackages.keyAt(i)); 22993 } 22994 final PackageList packageList = new PackageList(list, observer); 22995 if (observer != null) { 22996 mPackageListObservers.add(packageList); 22997 } 22998 return packageList; 22999 } 23000 } 23001 23002 @Override 23003 public void removePackageListObserver(PackageListObserver observer) { 23004 synchronized (mPackages) { 23005 mPackageListObservers.remove(observer); 23006 } 23007 } 23008 23009 @Override 23010 public PackageParser.Package getDisabledPackage(String packageName) { 23011 synchronized (mPackages) { 23012 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23013 return (ps != null) ? ps.pkg : null; 23014 } 23015 } 23016 23017 @Override 23018 public String getKnownPackageName(int knownPackage, int userId) { 23019 switch(knownPackage) { 23020 case PackageManagerInternal.PACKAGE_BROWSER: 23021 return getDefaultBrowserPackageName(userId); 23022 case PackageManagerInternal.PACKAGE_INSTALLER: 23023 return mRequiredInstallerPackage; 23024 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23025 return mSetupWizardPackage; 23026 case PackageManagerInternal.PACKAGE_SYSTEM: 23027 return "android"; 23028 case PackageManagerInternal.PACKAGE_VERIFIER: 23029 return mRequiredVerifierPackage; 23030 } 23031 return null; 23032 } 23033 23034 @Override 23035 public boolean isResolveActivityComponent(ComponentInfo component) { 23036 return mResolveActivity.packageName.equals(component.packageName) 23037 && mResolveActivity.name.equals(component.name); 23038 } 23039 23040 @Override 23041 public void setLocationPackagesProvider(PackagesProvider provider) { 23042 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23043 } 23044 23045 @Override 23046 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23047 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23048 } 23049 23050 @Override 23051 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23052 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23053 } 23054 23055 @Override 23056 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23057 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23058 } 23059 23060 @Override 23061 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23062 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23063 } 23064 23065 @Override 23066 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23067 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23068 } 23069 23070 @Override 23071 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23072 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23073 } 23074 23075 @Override 23076 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23077 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23078 } 23079 23080 @Override 23081 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23082 synchronized (mPackages) { 23083 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23084 } 23085 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23086 } 23087 23088 @Override 23089 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23090 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23091 packageName, userId); 23092 } 23093 23094 @Override 23095 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23096 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23097 packageName, userId); 23098 } 23099 23100 @Override 23101 public void setKeepUninstalledPackages(final List<String> packageList) { 23102 Preconditions.checkNotNull(packageList); 23103 List<String> removedFromList = null; 23104 synchronized (mPackages) { 23105 if (mKeepUninstalledPackages != null) { 23106 final int packagesCount = mKeepUninstalledPackages.size(); 23107 for (int i = 0; i < packagesCount; i++) { 23108 String oldPackage = mKeepUninstalledPackages.get(i); 23109 if (packageList != null && packageList.contains(oldPackage)) { 23110 continue; 23111 } 23112 if (removedFromList == null) { 23113 removedFromList = new ArrayList<>(); 23114 } 23115 removedFromList.add(oldPackage); 23116 } 23117 } 23118 mKeepUninstalledPackages = new ArrayList<>(packageList); 23119 if (removedFromList != null) { 23120 final int removedCount = removedFromList.size(); 23121 for (int i = 0; i < removedCount; i++) { 23122 deletePackageIfUnusedLPr(removedFromList.get(i)); 23123 } 23124 } 23125 } 23126 } 23127 23128 @Override 23129 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23130 synchronized (mPackages) { 23131 return mPermissionManager.isPermissionsReviewRequired( 23132 mPackages.get(packageName), userId); 23133 } 23134 } 23135 23136 @Override 23137 public PackageInfo getPackageInfo( 23138 String packageName, int flags, int filterCallingUid, int userId) { 23139 return PackageManagerService.this 23140 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23141 flags, filterCallingUid, userId); 23142 } 23143 23144 @Override 23145 public int getPackageUid(String packageName, int flags, int userId) { 23146 return PackageManagerService.this 23147 .getPackageUid(packageName, flags, userId); 23148 } 23149 23150 @Override 23151 public ApplicationInfo getApplicationInfo( 23152 String packageName, int flags, int filterCallingUid, int userId) { 23153 return PackageManagerService.this 23154 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23155 } 23156 23157 @Override 23158 public ActivityInfo getActivityInfo( 23159 ComponentName component, int flags, int filterCallingUid, int userId) { 23160 return PackageManagerService.this 23161 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23162 } 23163 23164 @Override 23165 public List<ResolveInfo> queryIntentActivities( 23166 Intent intent, int flags, int filterCallingUid, int userId) { 23167 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23168 return PackageManagerService.this 23169 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23170 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23171 } 23172 23173 @Override 23174 public List<ResolveInfo> queryIntentServices( 23175 Intent intent, int flags, int callingUid, int userId) { 23176 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23177 return PackageManagerService.this 23178 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23179 false); 23180 } 23181 23182 @Override 23183 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23184 int userId) { 23185 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23186 } 23187 23188 @Override 23189 public void setDeviceAndProfileOwnerPackages( 23190 int deviceOwnerUserId, String deviceOwnerPackage, 23191 SparseArray<String> profileOwnerPackages) { 23192 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23193 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23194 } 23195 23196 @Override 23197 public boolean isPackageDataProtected(int userId, String packageName) { 23198 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23199 } 23200 23201 @Override 23202 public boolean isPackageEphemeral(int userId, String packageName) { 23203 synchronized (mPackages) { 23204 final PackageSetting ps = mSettings.mPackages.get(packageName); 23205 return ps != null ? ps.getInstantApp(userId) : false; 23206 } 23207 } 23208 23209 @Override 23210 public boolean wasPackageEverLaunched(String packageName, int userId) { 23211 synchronized (mPackages) { 23212 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23213 } 23214 } 23215 23216 @Override 23217 public void grantRuntimePermission(String packageName, String permName, int userId, 23218 boolean overridePolicy) { 23219 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23220 permName, packageName, overridePolicy, getCallingUid(), userId, 23221 mPermissionCallback); 23222 } 23223 23224 @Override 23225 public void revokeRuntimePermission(String packageName, String permName, int userId, 23226 boolean overridePolicy) { 23227 mPermissionManager.revokeRuntimePermission( 23228 permName, packageName, overridePolicy, getCallingUid(), userId, 23229 mPermissionCallback); 23230 } 23231 23232 @Override 23233 public String getNameForUid(int uid) { 23234 return PackageManagerService.this.getNameForUid(uid); 23235 } 23236 23237 @Override 23238 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23239 Intent origIntent, String resolvedType, String callingPackage, 23240 Bundle verificationBundle, int userId) { 23241 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23242 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23243 userId); 23244 } 23245 23246 @Override 23247 public void grantEphemeralAccess(int userId, Intent intent, 23248 int targetAppId, int ephemeralAppId) { 23249 synchronized (mPackages) { 23250 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23251 targetAppId, ephemeralAppId); 23252 } 23253 } 23254 23255 @Override 23256 public boolean isInstantAppInstallerComponent(ComponentName component) { 23257 synchronized (mPackages) { 23258 return mInstantAppInstallerActivity != null 23259 && mInstantAppInstallerActivity.getComponentName().equals(component); 23260 } 23261 } 23262 23263 @Override 23264 public void pruneInstantApps() { 23265 mInstantAppRegistry.pruneInstantApps(); 23266 } 23267 23268 @Override 23269 public String getSetupWizardPackageName() { 23270 return mSetupWizardPackage; 23271 } 23272 23273 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23274 if (policy != null) { 23275 mExternalSourcesPolicy = policy; 23276 } 23277 } 23278 23279 @Override 23280 public boolean isPackagePersistent(String packageName) { 23281 synchronized (mPackages) { 23282 PackageParser.Package pkg = mPackages.get(packageName); 23283 return pkg != null 23284 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23285 | ApplicationInfo.FLAG_PERSISTENT)) == 23286 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23287 : false; 23288 } 23289 } 23290 23291 @Override 23292 public boolean isLegacySystemApp(Package pkg) { 23293 synchronized (mPackages) { 23294 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23295 return mPromoteSystemApps 23296 && ps.isSystem() 23297 && mExistingSystemPackages.contains(ps.name); 23298 } 23299 } 23300 23301 @Override 23302 public List<PackageInfo> getOverlayPackages(int userId) { 23303 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23304 synchronized (mPackages) { 23305 for (PackageParser.Package p : mPackages.values()) { 23306 if (p.mOverlayTarget != null) { 23307 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23308 if (pkg != null) { 23309 overlayPackages.add(pkg); 23310 } 23311 } 23312 } 23313 } 23314 return overlayPackages; 23315 } 23316 23317 @Override 23318 public List<String> getTargetPackageNames(int userId) { 23319 List<String> targetPackages = new ArrayList<>(); 23320 synchronized (mPackages) { 23321 for (PackageParser.Package p : mPackages.values()) { 23322 if (p.mOverlayTarget == null) { 23323 targetPackages.add(p.packageName); 23324 } 23325 } 23326 } 23327 return targetPackages; 23328 } 23329 23330 @Override 23331 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23332 @Nullable List<String> overlayPackageNames) { 23333 synchronized (mPackages) { 23334 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23335 Slog.e(TAG, "failed to find package " + targetPackageName); 23336 return false; 23337 } 23338 ArrayList<String> overlayPaths = null; 23339 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23340 final int N = overlayPackageNames.size(); 23341 overlayPaths = new ArrayList<>(N); 23342 for (int i = 0; i < N; i++) { 23343 final String packageName = overlayPackageNames.get(i); 23344 final PackageParser.Package pkg = mPackages.get(packageName); 23345 if (pkg == null) { 23346 Slog.e(TAG, "failed to find package " + packageName); 23347 return false; 23348 } 23349 overlayPaths.add(pkg.baseCodePath); 23350 } 23351 } 23352 23353 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23354 ps.setOverlayPaths(overlayPaths, userId); 23355 return true; 23356 } 23357 } 23358 23359 @Override 23360 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23361 int flags, int userId, boolean resolveForStart) { 23362 return resolveIntentInternal( 23363 intent, resolvedType, flags, userId, resolveForStart); 23364 } 23365 23366 @Override 23367 public ResolveInfo resolveService(Intent intent, String resolvedType, 23368 int flags, int userId, int callingUid) { 23369 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23370 } 23371 23372 @Override 23373 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23374 return PackageManagerService.this.resolveContentProviderInternal( 23375 name, flags, userId); 23376 } 23377 23378 @Override 23379 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23380 synchronized (mPackages) { 23381 mIsolatedOwners.put(isolatedUid, ownerUid); 23382 } 23383 } 23384 23385 @Override 23386 public void removeIsolatedUid(int isolatedUid) { 23387 synchronized (mPackages) { 23388 mIsolatedOwners.delete(isolatedUid); 23389 } 23390 } 23391 23392 @Override 23393 public int getUidTargetSdkVersion(int uid) { 23394 synchronized (mPackages) { 23395 return getUidTargetSdkVersionLockedLPr(uid); 23396 } 23397 } 23398 23399 @Override 23400 public boolean canAccessInstantApps(int callingUid, int userId) { 23401 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23402 } 23403 23404 @Override 23405 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23406 synchronized (mPackages) { 23407 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23408 } 23409 } 23410 23411 @Override 23412 public void notifyPackageUse(String packageName, int reason) { 23413 synchronized (mPackages) { 23414 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23415 } 23416 } 23417 } 23418 23419 @Override 23420 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23421 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23422 synchronized (mPackages) { 23423 final long identity = Binder.clearCallingIdentity(); 23424 try { 23425 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23426 packageNames, userId); 23427 } finally { 23428 Binder.restoreCallingIdentity(identity); 23429 } 23430 } 23431 } 23432 23433 @Override 23434 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23435 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23436 synchronized (mPackages) { 23437 final long identity = Binder.clearCallingIdentity(); 23438 try { 23439 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23440 packageNames, userId); 23441 } finally { 23442 Binder.restoreCallingIdentity(identity); 23443 } 23444 } 23445 } 23446 23447 private static void enforceSystemOrPhoneCaller(String tag) { 23448 int callingUid = Binder.getCallingUid(); 23449 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23450 throw new SecurityException( 23451 "Cannot call " + tag + " from UID " + callingUid); 23452 } 23453 } 23454 23455 boolean isHistoricalPackageUsageAvailable() { 23456 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23457 } 23458 23459 /** 23460 * Return a <b>copy</b> of the collection of packages known to the package manager. 23461 * @return A copy of the values of mPackages. 23462 */ 23463 Collection<PackageParser.Package> getPackages() { 23464 synchronized (mPackages) { 23465 return new ArrayList<>(mPackages.values()); 23466 } 23467 } 23468 23469 /** 23470 * Logs process start information (including base APK hash) to the security log. 23471 * @hide 23472 */ 23473 @Override 23474 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23475 String apkFile, int pid) { 23476 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23477 return; 23478 } 23479 if (!SecurityLog.isLoggingEnabled()) { 23480 return; 23481 } 23482 Bundle data = new Bundle(); 23483 data.putLong("startTimestamp", System.currentTimeMillis()); 23484 data.putString("processName", processName); 23485 data.putInt("uid", uid); 23486 data.putString("seinfo", seinfo); 23487 data.putString("apkFile", apkFile); 23488 data.putInt("pid", pid); 23489 Message msg = mProcessLoggingHandler.obtainMessage( 23490 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23491 msg.setData(data); 23492 mProcessLoggingHandler.sendMessage(msg); 23493 } 23494 23495 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23496 return mCompilerStats.getPackageStats(pkgName); 23497 } 23498 23499 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23500 return getOrCreateCompilerPackageStats(pkg.packageName); 23501 } 23502 23503 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23504 return mCompilerStats.getOrCreatePackageStats(pkgName); 23505 } 23506 23507 public void deleteCompilerPackageStats(String pkgName) { 23508 mCompilerStats.deletePackageStats(pkgName); 23509 } 23510 23511 @Override 23512 public int getInstallReason(String packageName, int userId) { 23513 final int callingUid = Binder.getCallingUid(); 23514 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23515 true /* requireFullPermission */, false /* checkShell */, 23516 "get install reason"); 23517 synchronized (mPackages) { 23518 final PackageSetting ps = mSettings.mPackages.get(packageName); 23519 if (filterAppAccessLPr(ps, callingUid, userId)) { 23520 return PackageManager.INSTALL_REASON_UNKNOWN; 23521 } 23522 if (ps != null) { 23523 return ps.getInstallReason(userId); 23524 } 23525 } 23526 return PackageManager.INSTALL_REASON_UNKNOWN; 23527 } 23528 23529 @Override 23530 public boolean canRequestPackageInstalls(String packageName, int userId) { 23531 return canRequestPackageInstallsInternal(packageName, 0, userId, 23532 true /* throwIfPermNotDeclared*/); 23533 } 23534 23535 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23536 boolean throwIfPermNotDeclared) { 23537 int callingUid = Binder.getCallingUid(); 23538 int uid = getPackageUid(packageName, 0, userId); 23539 if (callingUid != uid && callingUid != Process.ROOT_UID 23540 && callingUid != Process.SYSTEM_UID) { 23541 throw new SecurityException( 23542 "Caller uid " + callingUid + " does not own package " + packageName); 23543 } 23544 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23545 if (info == null) { 23546 return false; 23547 } 23548 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23549 return false; 23550 } 23551 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23552 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23553 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23554 if (throwIfPermNotDeclared) { 23555 throw new SecurityException("Need to declare " + appOpPermission 23556 + " to call this api"); 23557 } else { 23558 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23559 return false; 23560 } 23561 } 23562 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23563 return false; 23564 } 23565 if (mExternalSourcesPolicy != null) { 23566 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23567 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23568 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23569 } 23570 } 23571 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23572 } 23573 23574 @Override 23575 public ComponentName getInstantAppResolverSettingsComponent() { 23576 return mInstantAppResolverSettingsComponent; 23577 } 23578 23579 @Override 23580 public ComponentName getInstantAppInstallerComponent() { 23581 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23582 return null; 23583 } 23584 return mInstantAppInstallerActivity == null 23585 ? null : mInstantAppInstallerActivity.getComponentName(); 23586 } 23587 23588 @Override 23589 public String getInstantAppAndroidId(String packageName, int userId) { 23590 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23591 "getInstantAppAndroidId"); 23592 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23593 true /* requireFullPermission */, false /* checkShell */, 23594 "getInstantAppAndroidId"); 23595 // Make sure the target is an Instant App. 23596 if (!isInstantApp(packageName, userId)) { 23597 return null; 23598 } 23599 synchronized (mPackages) { 23600 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23601 } 23602 } 23603 23604 boolean canHaveOatDir(String packageName) { 23605 synchronized (mPackages) { 23606 PackageParser.Package p = mPackages.get(packageName); 23607 if (p == null) { 23608 return false; 23609 } 23610 return p.canHaveOatDir(); 23611 } 23612 } 23613 23614 private String getOatDir(PackageParser.Package pkg) { 23615 if (!pkg.canHaveOatDir()) { 23616 return null; 23617 } 23618 File codePath = new File(pkg.codePath); 23619 if (codePath.isDirectory()) { 23620 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23621 } 23622 return null; 23623 } 23624 23625 void deleteOatArtifactsOfPackage(String packageName) { 23626 final String[] instructionSets; 23627 final List<String> codePaths; 23628 final String oatDir; 23629 final PackageParser.Package pkg; 23630 synchronized (mPackages) { 23631 pkg = mPackages.get(packageName); 23632 } 23633 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23634 codePaths = pkg.getAllCodePaths(); 23635 oatDir = getOatDir(pkg); 23636 23637 for (String codePath : codePaths) { 23638 for (String isa : instructionSets) { 23639 try { 23640 mInstaller.deleteOdex(codePath, isa, oatDir); 23641 } catch (InstallerException e) { 23642 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23643 } 23644 } 23645 } 23646 } 23647 23648 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23649 Set<String> unusedPackages = new HashSet<>(); 23650 long currentTimeInMillis = System.currentTimeMillis(); 23651 synchronized (mPackages) { 23652 for (PackageParser.Package pkg : mPackages.values()) { 23653 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23654 if (ps == null) { 23655 continue; 23656 } 23657 PackageDexUsage.PackageUseInfo packageUseInfo = 23658 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23659 if (PackageManagerServiceUtils 23660 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23661 downgradeTimeThresholdMillis, packageUseInfo, 23662 pkg.getLatestPackageUseTimeInMills(), 23663 pkg.getLatestForegroundPackageUseTimeInMills())) { 23664 unusedPackages.add(pkg.packageName); 23665 } 23666 } 23667 } 23668 return unusedPackages; 23669 } 23670 23671 @Override 23672 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 23673 int userId) { 23674 final int callingUid = Binder.getCallingUid(); 23675 final int callingAppId = UserHandle.getAppId(callingUid); 23676 23677 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23678 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 23679 23680 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23681 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23682 throw new SecurityException("Caller must have the " 23683 + SET_HARMFUL_APP_WARNINGS + " permission."); 23684 } 23685 23686 synchronized(mPackages) { 23687 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 23688 scheduleWritePackageRestrictionsLocked(userId); 23689 } 23690 } 23691 23692 @Nullable 23693 @Override 23694 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 23695 final int callingUid = Binder.getCallingUid(); 23696 final int callingAppId = UserHandle.getAppId(callingUid); 23697 23698 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23699 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 23700 23701 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23702 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23703 throw new SecurityException("Caller must have the " 23704 + SET_HARMFUL_APP_WARNINGS + " permission."); 23705 } 23706 23707 synchronized(mPackages) { 23708 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 23709 } 23710 } 23711} 23712 23713interface PackageSender { 23714 /** 23715 * @param userIds User IDs where the action occurred on a full application 23716 * @param instantUserIds User IDs where the action occurred on an instant application 23717 */ 23718 void sendPackageBroadcast(final String action, final String pkg, 23719 final Bundle extras, final int flags, final String targetPkg, 23720 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 23721 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23722 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 23723 void notifyPackageAdded(String packageName); 23724 void notifyPackageRemoved(String packageName); 23725} 23726