PackageManagerService.java revision aef1221d259d752c20454f3a03d499a20c5f52ad
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_PACKAGE_CHANGED; 52import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 53import static android.content.pm.PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 55import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 56import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 57import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 58import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 62import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 63import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 64import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 65import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 66import static android.content.pm.PackageManager.MATCH_ALL; 67import static android.content.pm.PackageManager.MATCH_ANY_USER; 68import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 69import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 70import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 71import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 72import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 73import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 74import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 75import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 76import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 77import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 78import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 79import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 80import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 81import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 82import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 83import static android.content.pm.PackageManager.PERMISSION_DENIED; 84import static android.content.pm.PackageManager.PERMISSION_GRANTED; 85import static android.content.pm.PackageParser.isApkFile; 86import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 87import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 88import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 89import static android.system.OsConstants.O_CREAT; 90import static android.system.OsConstants.O_RDWR; 91import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 92import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 93import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 94import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 95import static com.android.internal.util.ArrayUtils.appendInt; 96import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 97import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 98import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 99import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 100import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 101import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 102import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 103import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 104import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 105import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 106import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 107import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 108import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 109import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 110import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 111import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 112import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_FAILURE; 113import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS; 114import static com.android.server.pm.permission.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 115 116import android.Manifest; 117import android.annotation.IntDef; 118import android.annotation.NonNull; 119import android.annotation.Nullable; 120import android.app.ActivityManager; 121import android.app.AppOpsManager; 122import android.app.IActivityManager; 123import android.app.ResourcesManager; 124import android.app.admin.IDevicePolicyManager; 125import android.app.admin.SecurityLog; 126import android.app.backup.IBackupManager; 127import android.content.BroadcastReceiver; 128import android.content.ComponentName; 129import android.content.ContentResolver; 130import android.content.Context; 131import android.content.IIntentReceiver; 132import android.content.Intent; 133import android.content.IntentFilter; 134import android.content.IntentSender; 135import android.content.IntentSender.SendIntentException; 136import android.content.ServiceConnection; 137import android.content.pm.ActivityInfo; 138import android.content.pm.ApplicationInfo; 139import android.content.pm.AppsQueryHelper; 140import android.content.pm.AuxiliaryResolveInfo; 141import android.content.pm.ChangedPackages; 142import android.content.pm.ComponentInfo; 143import android.content.pm.FallbackCategoryProvider; 144import android.content.pm.FeatureInfo; 145import android.content.pm.IDexModuleRegisterCallback; 146import android.content.pm.IOnPermissionsChangeListener; 147import android.content.pm.IPackageDataObserver; 148import android.content.pm.IPackageDeleteObserver; 149import android.content.pm.IPackageDeleteObserver2; 150import android.content.pm.IPackageInstallObserver2; 151import android.content.pm.IPackageInstaller; 152import android.content.pm.IPackageManager; 153import android.content.pm.IPackageManagerNative; 154import android.content.pm.IPackageMoveObserver; 155import android.content.pm.IPackageStatsObserver; 156import android.content.pm.InstantAppInfo; 157import android.content.pm.InstantAppRequest; 158import android.content.pm.InstantAppResolveInfo; 159import android.content.pm.InstrumentationInfo; 160import android.content.pm.IntentFilterVerificationInfo; 161import android.content.pm.KeySet; 162import android.content.pm.PackageCleanItem; 163import android.content.pm.PackageInfo; 164import android.content.pm.PackageInfoLite; 165import android.content.pm.PackageInstaller; 166import android.content.pm.PackageList; 167import android.content.pm.PackageManager; 168import android.content.pm.PackageManagerInternal; 169import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 170import android.content.pm.PackageManagerInternal.PackageListObserver; 171import android.content.pm.PackageParser; 172import android.content.pm.PackageParser.ActivityIntentInfo; 173import android.content.pm.PackageParser.Package; 174import android.content.pm.PackageParser.PackageLite; 175import android.content.pm.PackageParser.PackageParserException; 176import android.content.pm.PackageParser.ParseFlags; 177import android.content.pm.PackageParser.ServiceIntentInfo; 178import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 179import android.content.pm.PackageStats; 180import android.content.pm.PackageUserState; 181import android.content.pm.ParceledListSlice; 182import android.content.pm.PermissionGroupInfo; 183import android.content.pm.PermissionInfo; 184import android.content.pm.ProviderInfo; 185import android.content.pm.ResolveInfo; 186import android.content.pm.ServiceInfo; 187import android.content.pm.SharedLibraryInfo; 188import android.content.pm.Signature; 189import android.content.pm.UserInfo; 190import android.content.pm.VerifierDeviceIdentity; 191import android.content.pm.VerifierInfo; 192import android.content.pm.VersionedPackage; 193import android.content.pm.dex.DexMetadataHelper; 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 // Verify that packages sharing a user with a privileged app are marked as privileged. 10769 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 10770 SharedUserSetting sharedUserSetting = null; 10771 try { 10772 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10773 } catch (PackageManagerException ignore) {} 10774 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10775 // Exempt SharedUsers signed with the platform key. 10776 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10777 if ((platformPkgSetting.signatures.mSignatures != null) && 10778 (compareSignatures(platformPkgSetting.signatures.mSignatures, 10779 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 10780 throw new PackageManagerException("Apps that share a user with a " + 10781 "privileged app must themselves be marked as privileged. " + 10782 pkg.packageName + " shares privileged user " + 10783 pkg.mSharedUserId + "."); 10784 } 10785 } 10786 } 10787 } 10788 } 10789 10790 private boolean addSharedLibraryLPw(String path, String apk, String name, long version, 10791 int type, String declaringPackageName, long declaringVersionCode) { 10792 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10793 if (versionedLib == null) { 10794 versionedLib = new LongSparseArray<>(); 10795 mSharedLibraries.put(name, versionedLib); 10796 if (type == SharedLibraryInfo.TYPE_STATIC) { 10797 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 10798 } 10799 } else if (versionedLib.indexOfKey(version) >= 0) { 10800 return false; 10801 } 10802 SharedLibraryEntry libEntry = new SharedLibraryEntry(path, apk, name, 10803 version, type, declaringPackageName, declaringVersionCode); 10804 versionedLib.put(version, libEntry); 10805 return true; 10806 } 10807 10808 private boolean removeSharedLibraryLPw(String name, long version) { 10809 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(name); 10810 if (versionedLib == null) { 10811 return false; 10812 } 10813 final int libIdx = versionedLib.indexOfKey(version); 10814 if (libIdx < 0) { 10815 return false; 10816 } 10817 SharedLibraryEntry libEntry = versionedLib.valueAt(libIdx); 10818 versionedLib.remove(version); 10819 if (versionedLib.size() <= 0) { 10820 mSharedLibraries.remove(name); 10821 if (libEntry.info.getType() == SharedLibraryInfo.TYPE_STATIC) { 10822 mStaticLibsByDeclaringPackage.remove(libEntry.info.getDeclaringPackage() 10823 .getPackageName()); 10824 } 10825 } 10826 return true; 10827 } 10828 10829 /** 10830 * Adds a scanned package to the system. When this method is finished, the package will 10831 * be available for query, resolution, etc... 10832 */ 10833 private void commitPackageSettings(PackageParser.Package pkg, PackageSetting pkgSetting, 10834 UserHandle user, final @ScanFlags int scanFlags, boolean chatty) { 10835 final String pkgName = pkg.packageName; 10836 if (mCustomResolverComponentName != null && 10837 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 10838 setUpCustomResolverActivity(pkg); 10839 } 10840 10841 if (pkg.packageName.equals("android")) { 10842 synchronized (mPackages) { 10843 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10844 // Set up information for our fall-back user intent resolution activity. 10845 mPlatformPackage = pkg; 10846 pkg.mVersionCode = mSdkVersion; 10847 pkg.mVersionCodeMajor = 0; 10848 mAndroidApplication = pkg.applicationInfo; 10849 if (!mResolverReplaced) { 10850 mResolveActivity.applicationInfo = mAndroidApplication; 10851 mResolveActivity.name = ResolverActivity.class.getName(); 10852 mResolveActivity.packageName = mAndroidApplication.packageName; 10853 mResolveActivity.processName = "system:ui"; 10854 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 10855 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 10856 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 10857 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 10858 mResolveActivity.exported = true; 10859 mResolveActivity.enabled = true; 10860 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 10861 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 10862 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 10863 | ActivityInfo.CONFIG_SCREEN_LAYOUT 10864 | ActivityInfo.CONFIG_ORIENTATION 10865 | ActivityInfo.CONFIG_KEYBOARD 10866 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 10867 mResolveInfo.activityInfo = mResolveActivity; 10868 mResolveInfo.priority = 0; 10869 mResolveInfo.preferredOrder = 0; 10870 mResolveInfo.match = 0; 10871 mResolveComponentName = new ComponentName( 10872 mAndroidApplication.packageName, mResolveActivity.name); 10873 } 10874 } 10875 } 10876 } 10877 10878 ArrayList<PackageParser.Package> clientLibPkgs = null; 10879 // writer 10880 synchronized (mPackages) { 10881 boolean hasStaticSharedLibs = false; 10882 10883 // Any app can add new static shared libraries 10884 if (pkg.staticSharedLibName != null) { 10885 // Static shared libs don't allow renaming as they have synthetic package 10886 // names to allow install of multiple versions, so use name from manifest. 10887 if (addSharedLibraryLPw(null, pkg.packageName, pkg.staticSharedLibName, 10888 pkg.staticSharedLibVersion, SharedLibraryInfo.TYPE_STATIC, 10889 pkg.manifestPackageName, pkg.getLongVersionCode())) { 10890 hasStaticSharedLibs = true; 10891 } else { 10892 Slog.w(TAG, "Package " + pkg.packageName + " library " 10893 + pkg.staticSharedLibName + " already exists; skipping"); 10894 } 10895 // Static shared libs cannot be updated once installed since they 10896 // use synthetic package name which includes the version code, so 10897 // not need to update other packages's shared lib dependencies. 10898 } 10899 10900 if (!hasStaticSharedLibs 10901 && (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 10902 // Only system apps can add new dynamic shared libraries. 10903 if (pkg.libraryNames != null) { 10904 for (int i = 0; i < pkg.libraryNames.size(); i++) { 10905 String name = pkg.libraryNames.get(i); 10906 boolean allowed = false; 10907 if (pkg.isUpdatedSystemApp()) { 10908 // New library entries can only be added through the 10909 // system image. This is important to get rid of a lot 10910 // of nasty edge cases: for example if we allowed a non- 10911 // system update of the app to add a library, then uninstalling 10912 // the update would make the library go away, and assumptions 10913 // we made such as through app install filtering would now 10914 // have allowed apps on the device which aren't compatible 10915 // with it. Better to just have the restriction here, be 10916 // conservative, and create many fewer cases that can negatively 10917 // impact the user experience. 10918 final PackageSetting sysPs = mSettings 10919 .getDisabledSystemPkgLPr(pkg.packageName); 10920 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 10921 for (int j = 0; j < sysPs.pkg.libraryNames.size(); j++) { 10922 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 10923 allowed = true; 10924 break; 10925 } 10926 } 10927 } 10928 } else { 10929 allowed = true; 10930 } 10931 if (allowed) { 10932 if (!addSharedLibraryLPw(null, pkg.packageName, name, 10933 SharedLibraryInfo.VERSION_UNDEFINED, 10934 SharedLibraryInfo.TYPE_DYNAMIC, 10935 pkg.packageName, pkg.getLongVersionCode())) { 10936 Slog.w(TAG, "Package " + pkg.packageName + " library " 10937 + name + " already exists; skipping"); 10938 } 10939 } else { 10940 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 10941 + name + " that is not declared on system image; skipping"); 10942 } 10943 } 10944 10945 if ((scanFlags & SCAN_BOOTING) == 0) { 10946 // If we are not booting, we need to update any applications 10947 // that are clients of our shared library. If we are booting, 10948 // this will all be done once the scan is complete. 10949 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 10950 } 10951 } 10952 } 10953 } 10954 10955 if ((scanFlags & SCAN_BOOTING) != 0) { 10956 // No apps can run during boot scan, so they don't need to be frozen 10957 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 10958 // Caller asked to not kill app, so it's probably not frozen 10959 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 10960 // Caller asked us to ignore frozen check for some reason; they 10961 // probably didn't know the package name 10962 } else { 10963 // We're doing major surgery on this package, so it better be frozen 10964 // right now to keep it from launching 10965 checkPackageFrozen(pkgName); 10966 } 10967 10968 // Also need to kill any apps that are dependent on the library. 10969 if (clientLibPkgs != null) { 10970 for (int i=0; i<clientLibPkgs.size(); i++) { 10971 PackageParser.Package clientPkg = clientLibPkgs.get(i); 10972 killApplication(clientPkg.applicationInfo.packageName, 10973 clientPkg.applicationInfo.uid, "update lib"); 10974 } 10975 } 10976 10977 // writer 10978 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 10979 10980 synchronized (mPackages) { 10981 // We don't expect installation to fail beyond this point 10982 10983 // Add the new setting to mSettings 10984 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 10985 // Add the new setting to mPackages 10986 mPackages.put(pkg.applicationInfo.packageName, pkg); 10987 // Make sure we don't accidentally delete its data. 10988 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 10989 while (iter.hasNext()) { 10990 PackageCleanItem item = iter.next(); 10991 if (pkgName.equals(item.packageName)) { 10992 iter.remove(); 10993 } 10994 } 10995 10996 // Add the package's KeySets to the global KeySetManagerService 10997 KeySetManagerService ksms = mSettings.mKeySetManagerService; 10998 ksms.addScannedPackageLPw(pkg); 10999 11000 int N = pkg.providers.size(); 11001 StringBuilder r = null; 11002 int i; 11003 for (i=0; i<N; i++) { 11004 PackageParser.Provider p = pkg.providers.get(i); 11005 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 11006 p.info.processName); 11007 mProviders.addProvider(p); 11008 p.syncable = p.info.isSyncable; 11009 if (p.info.authority != null) { 11010 String names[] = p.info.authority.split(";"); 11011 p.info.authority = null; 11012 for (int j = 0; j < names.length; j++) { 11013 if (j == 1 && p.syncable) { 11014 // We only want the first authority for a provider to possibly be 11015 // syncable, so if we already added this provider using a different 11016 // authority clear the syncable flag. We copy the provider before 11017 // changing it because the mProviders object contains a reference 11018 // to a provider that we don't want to change. 11019 // Only do this for the second authority since the resulting provider 11020 // object can be the same for all future authorities for this provider. 11021 p = new PackageParser.Provider(p); 11022 p.syncable = false; 11023 } 11024 if (!mProvidersByAuthority.containsKey(names[j])) { 11025 mProvidersByAuthority.put(names[j], p); 11026 if (p.info.authority == null) { 11027 p.info.authority = names[j]; 11028 } else { 11029 p.info.authority = p.info.authority + ";" + names[j]; 11030 } 11031 if (DEBUG_PACKAGE_SCANNING) { 11032 if (chatty) 11033 Log.d(TAG, "Registered content provider: " + names[j] 11034 + ", className = " + p.info.name + ", isSyncable = " 11035 + p.info.isSyncable); 11036 } 11037 } else { 11038 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 11039 Slog.w(TAG, "Skipping provider name " + names[j] + 11040 " (in package " + pkg.applicationInfo.packageName + 11041 "): name already used by " 11042 + ((other != null && other.getComponentName() != null) 11043 ? other.getComponentName().getPackageName() : "?")); 11044 } 11045 } 11046 } 11047 if (chatty) { 11048 if (r == null) { 11049 r = new StringBuilder(256); 11050 } else { 11051 r.append(' '); 11052 } 11053 r.append(p.info.name); 11054 } 11055 } 11056 if (r != null) { 11057 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 11058 } 11059 11060 N = pkg.services.size(); 11061 r = null; 11062 for (i=0; i<N; i++) { 11063 PackageParser.Service s = pkg.services.get(i); 11064 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 11065 s.info.processName); 11066 mServices.addService(s); 11067 if (chatty) { 11068 if (r == null) { 11069 r = new StringBuilder(256); 11070 } else { 11071 r.append(' '); 11072 } 11073 r.append(s.info.name); 11074 } 11075 } 11076 if (r != null) { 11077 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 11078 } 11079 11080 N = pkg.receivers.size(); 11081 r = null; 11082 for (i=0; i<N; i++) { 11083 PackageParser.Activity a = pkg.receivers.get(i); 11084 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11085 a.info.processName); 11086 mReceivers.addActivity(a, "receiver"); 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, " Receivers: " + r); 11098 } 11099 11100 N = pkg.activities.size(); 11101 r = null; 11102 for (i=0; i<N; i++) { 11103 PackageParser.Activity a = pkg.activities.get(i); 11104 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 11105 a.info.processName); 11106 mActivities.addActivity(a, "activity"); 11107 if (chatty) { 11108 if (r == null) { 11109 r = new StringBuilder(256); 11110 } else { 11111 r.append(' '); 11112 } 11113 r.append(a.info.name); 11114 } 11115 } 11116 if (r != null) { 11117 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 11118 } 11119 11120 // Don't allow ephemeral applications to define new permissions groups. 11121 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11122 Slog.w(TAG, "Permission groups from package " + pkg.packageName 11123 + " ignored: instant apps cannot define new permission groups."); 11124 } else { 11125 mPermissionManager.addAllPermissionGroups(pkg, chatty); 11126 } 11127 11128 // Don't allow ephemeral applications to define new permissions. 11129 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11130 Slog.w(TAG, "Permissions from package " + pkg.packageName 11131 + " ignored: instant apps cannot define new permissions."); 11132 } else { 11133 mPermissionManager.addAllPermissions(pkg, chatty); 11134 } 11135 11136 N = pkg.instrumentation.size(); 11137 r = null; 11138 for (i=0; i<N; i++) { 11139 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11140 a.info.packageName = pkg.applicationInfo.packageName; 11141 a.info.sourceDir = pkg.applicationInfo.sourceDir; 11142 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 11143 a.info.splitNames = pkg.splitNames; 11144 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 11145 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 11146 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 11147 a.info.dataDir = pkg.applicationInfo.dataDir; 11148 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 11149 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 11150 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 11151 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 11152 mInstrumentation.put(a.getComponentName(), a); 11153 if (chatty) { 11154 if (r == null) { 11155 r = new StringBuilder(256); 11156 } else { 11157 r.append(' '); 11158 } 11159 r.append(a.info.name); 11160 } 11161 } 11162 if (r != null) { 11163 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 11164 } 11165 11166 if (pkg.protectedBroadcasts != null) { 11167 N = pkg.protectedBroadcasts.size(); 11168 synchronized (mProtectedBroadcasts) { 11169 for (i = 0; i < N; i++) { 11170 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 11171 } 11172 } 11173 } 11174 } 11175 11176 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11177 } 11178 11179 /** 11180 * Derive the ABI of a non-system package located at {@code scanFile}. This information 11181 * is derived purely on the basis of the contents of {@code scanFile} and 11182 * {@code cpuAbiOverride}. 11183 * 11184 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 11185 */ 11186 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 11187 boolean extractLibs) 11188 throws PackageManagerException { 11189 // Give ourselves some initial paths; we'll come back for another 11190 // pass once we've determined ABI below. 11191 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11192 11193 // We would never need to extract libs for forward-locked and external packages, 11194 // since the container service will do it for us. We shouldn't attempt to 11195 // extract libs from system app when it was not updated. 11196 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 11197 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 11198 extractLibs = false; 11199 } 11200 11201 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 11202 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 11203 11204 NativeLibraryHelper.Handle handle = null; 11205 try { 11206 handle = NativeLibraryHelper.Handle.create(pkg); 11207 // TODO(multiArch): This can be null for apps that didn't go through the 11208 // usual installation process. We can calculate it again, like we 11209 // do during install time. 11210 // 11211 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 11212 // unnecessary. 11213 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 11214 11215 // Null out the abis so that they can be recalculated. 11216 pkg.applicationInfo.primaryCpuAbi = null; 11217 pkg.applicationInfo.secondaryCpuAbi = null; 11218 if (isMultiArch(pkg.applicationInfo)) { 11219 // Warn if we've set an abiOverride for multi-lib packages.. 11220 // By definition, we need to copy both 32 and 64 bit libraries for 11221 // such packages. 11222 if (pkg.cpuAbiOverride != null 11223 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 11224 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 11225 } 11226 11227 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 11228 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 11229 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 11230 if (extractLibs) { 11231 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11232 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11233 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 11234 useIsaSpecificSubdirs); 11235 } else { 11236 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11237 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 11238 } 11239 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11240 } 11241 11242 // Shared library native code should be in the APK zip aligned 11243 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 11244 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11245 "Shared library native lib extraction not supported"); 11246 } 11247 11248 maybeThrowExceptionForMultiArchCopy( 11249 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 11250 11251 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 11252 if (extractLibs) { 11253 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11254 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11255 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 11256 useIsaSpecificSubdirs); 11257 } else { 11258 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11259 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 11260 } 11261 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11262 } 11263 11264 maybeThrowExceptionForMultiArchCopy( 11265 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 11266 11267 if (abi64 >= 0) { 11268 // Shared library native libs should be in the APK zip aligned 11269 if (extractLibs && pkg.isLibrary()) { 11270 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11271 "Shared library native lib extraction not supported"); 11272 } 11273 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 11274 } 11275 11276 if (abi32 >= 0) { 11277 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 11278 if (abi64 >= 0) { 11279 if (pkg.use32bitAbi) { 11280 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 11281 pkg.applicationInfo.primaryCpuAbi = abi; 11282 } else { 11283 pkg.applicationInfo.secondaryCpuAbi = abi; 11284 } 11285 } else { 11286 pkg.applicationInfo.primaryCpuAbi = abi; 11287 } 11288 } 11289 } else { 11290 String[] abiList = (cpuAbiOverride != null) ? 11291 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 11292 11293 // Enable gross and lame hacks for apps that are built with old 11294 // SDK tools. We must scan their APKs for renderscript bitcode and 11295 // not launch them if it's present. Don't bother checking on devices 11296 // that don't have 64 bit support. 11297 boolean needsRenderScriptOverride = false; 11298 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 11299 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 11300 abiList = Build.SUPPORTED_32_BIT_ABIS; 11301 needsRenderScriptOverride = true; 11302 } 11303 11304 final int copyRet; 11305 if (extractLibs) { 11306 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 11307 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 11308 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 11309 } else { 11310 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 11311 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 11312 } 11313 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11314 11315 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 11316 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11317 "Error unpackaging native libs for app, errorCode=" + copyRet); 11318 } 11319 11320 if (copyRet >= 0) { 11321 // Shared libraries that have native libs must be multi-architecture 11322 if (pkg.isLibrary()) { 11323 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 11324 "Shared library with native libs must be multiarch"); 11325 } 11326 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 11327 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 11328 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 11329 } else if (needsRenderScriptOverride) { 11330 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 11331 } 11332 } 11333 } catch (IOException ioe) { 11334 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 11335 } finally { 11336 IoUtils.closeQuietly(handle); 11337 } 11338 11339 // Now that we've calculated the ABIs and determined if it's an internal app, 11340 // we will go ahead and populate the nativeLibraryPath. 11341 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11342 } 11343 11344 /** 11345 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 11346 * i.e, so that all packages can be run inside a single process if required. 11347 * 11348 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 11349 * this function will either try and make the ABI for all packages in {@code packagesForUser} 11350 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 11351 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 11352 * updating a package that belongs to a shared user. 11353 * 11354 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 11355 * adds unnecessary complexity. 11356 */ 11357 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 11358 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 11359 List<String> changedAbiCodePath = null; 11360 String requiredInstructionSet = null; 11361 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 11362 requiredInstructionSet = VMRuntime.getInstructionSet( 11363 scannedPackage.applicationInfo.primaryCpuAbi); 11364 } 11365 11366 PackageSetting requirer = null; 11367 for (PackageSetting ps : packagesForUser) { 11368 // If packagesForUser contains scannedPackage, we skip it. This will happen 11369 // when scannedPackage is an update of an existing package. Without this check, 11370 // we will never be able to change the ABI of any package belonging to a shared 11371 // user, even if it's compatible with other packages. 11372 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11373 if (ps.primaryCpuAbiString == null) { 11374 continue; 11375 } 11376 11377 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 11378 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 11379 // We have a mismatch between instruction sets (say arm vs arm64) warn about 11380 // this but there's not much we can do. 11381 String errorMessage = "Instruction set mismatch, " 11382 + ((requirer == null) ? "[caller]" : requirer) 11383 + " requires " + requiredInstructionSet + " whereas " + ps 11384 + " requires " + instructionSet; 11385 Slog.w(TAG, errorMessage); 11386 } 11387 11388 if (requiredInstructionSet == null) { 11389 requiredInstructionSet = instructionSet; 11390 requirer = ps; 11391 } 11392 } 11393 } 11394 11395 if (requiredInstructionSet != null) { 11396 String adjustedAbi; 11397 if (requirer != null) { 11398 // requirer != null implies that either scannedPackage was null or that scannedPackage 11399 // did not require an ABI, in which case we have to adjust scannedPackage to match 11400 // the ABI of the set (which is the same as requirer's ABI) 11401 adjustedAbi = requirer.primaryCpuAbiString; 11402 if (scannedPackage != null) { 11403 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11404 } 11405 } else { 11406 // requirer == null implies that we're updating all ABIs in the set to 11407 // match scannedPackage. 11408 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 11409 } 11410 11411 for (PackageSetting ps : packagesForUser) { 11412 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11413 if (ps.primaryCpuAbiString != null) { 11414 continue; 11415 } 11416 11417 ps.primaryCpuAbiString = adjustedAbi; 11418 if (ps.pkg != null && ps.pkg.applicationInfo != null && 11419 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11420 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11421 if (DEBUG_ABI_SELECTION) { 11422 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11423 + " (requirer=" 11424 + (requirer != null ? requirer.pkg : "null") 11425 + ", scannedPackage=" 11426 + (scannedPackage != null ? scannedPackage : "null") 11427 + ")"); 11428 } 11429 if (changedAbiCodePath == null) { 11430 changedAbiCodePath = new ArrayList<>(); 11431 } 11432 changedAbiCodePath.add(ps.codePathString); 11433 } 11434 } 11435 } 11436 } 11437 return changedAbiCodePath; 11438 } 11439 11440 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 11441 synchronized (mPackages) { 11442 mResolverReplaced = true; 11443 // Set up information for custom user intent resolution activity. 11444 mResolveActivity.applicationInfo = pkg.applicationInfo; 11445 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 11446 mResolveActivity.packageName = pkg.applicationInfo.packageName; 11447 mResolveActivity.processName = pkg.applicationInfo.packageName; 11448 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 11449 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 11450 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11451 mResolveActivity.theme = 0; 11452 mResolveActivity.exported = true; 11453 mResolveActivity.enabled = true; 11454 mResolveInfo.activityInfo = mResolveActivity; 11455 mResolveInfo.priority = 0; 11456 mResolveInfo.preferredOrder = 0; 11457 mResolveInfo.match = 0; 11458 mResolveComponentName = mCustomResolverComponentName; 11459 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 11460 mResolveComponentName); 11461 } 11462 } 11463 11464 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 11465 if (installerActivity == null) { 11466 if (DEBUG_EPHEMERAL) { 11467 Slog.d(TAG, "Clear ephemeral installer activity"); 11468 } 11469 mInstantAppInstallerActivity = null; 11470 return; 11471 } 11472 11473 if (DEBUG_EPHEMERAL) { 11474 Slog.d(TAG, "Set ephemeral installer activity: " 11475 + installerActivity.getComponentName()); 11476 } 11477 // Set up information for ephemeral installer activity 11478 mInstantAppInstallerActivity = installerActivity; 11479 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 11480 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 11481 mInstantAppInstallerActivity.exported = true; 11482 mInstantAppInstallerActivity.enabled = true; 11483 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 11484 mInstantAppInstallerInfo.priority = 0; 11485 mInstantAppInstallerInfo.preferredOrder = 1; 11486 mInstantAppInstallerInfo.isDefault = true; 11487 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 11488 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 11489 } 11490 11491 private static String calculateBundledApkRoot(final String codePathString) { 11492 final File codePath = new File(codePathString); 11493 final File codeRoot; 11494 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 11495 codeRoot = Environment.getRootDirectory(); 11496 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 11497 codeRoot = Environment.getOemDirectory(); 11498 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 11499 codeRoot = Environment.getVendorDirectory(); 11500 } else { 11501 // Unrecognized code path; take its top real segment as the apk root: 11502 // e.g. /something/app/blah.apk => /something 11503 try { 11504 File f = codePath.getCanonicalFile(); 11505 File parent = f.getParentFile(); // non-null because codePath is a file 11506 File tmp; 11507 while ((tmp = parent.getParentFile()) != null) { 11508 f = parent; 11509 parent = tmp; 11510 } 11511 codeRoot = f; 11512 Slog.w(TAG, "Unrecognized code path " 11513 + codePath + " - using " + codeRoot); 11514 } catch (IOException e) { 11515 // Can't canonicalize the code path -- shenanigans? 11516 Slog.w(TAG, "Can't canonicalize code path " + codePath); 11517 return Environment.getRootDirectory().getPath(); 11518 } 11519 } 11520 return codeRoot.getPath(); 11521 } 11522 11523 /** 11524 * Derive and set the location of native libraries for the given package, 11525 * which varies depending on where and how the package was installed. 11526 */ 11527 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 11528 final ApplicationInfo info = pkg.applicationInfo; 11529 final String codePath = pkg.codePath; 11530 final File codeFile = new File(codePath); 11531 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 11532 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 11533 11534 info.nativeLibraryRootDir = null; 11535 info.nativeLibraryRootRequiresIsa = false; 11536 info.nativeLibraryDir = null; 11537 info.secondaryNativeLibraryDir = null; 11538 11539 if (isApkFile(codeFile)) { 11540 // Monolithic install 11541 if (bundledApp) { 11542 // If "/system/lib64/apkname" exists, assume that is the per-package 11543 // native library directory to use; otherwise use "/system/lib/apkname". 11544 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 11545 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 11546 getPrimaryInstructionSet(info)); 11547 11548 // This is a bundled system app so choose the path based on the ABI. 11549 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 11550 // is just the default path. 11551 final String apkName = deriveCodePathName(codePath); 11552 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 11553 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 11554 apkName).getAbsolutePath(); 11555 11556 if (info.secondaryCpuAbi != null) { 11557 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 11558 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 11559 secondaryLibDir, apkName).getAbsolutePath(); 11560 } 11561 } else if (asecApp) { 11562 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 11563 .getAbsolutePath(); 11564 } else { 11565 final String apkName = deriveCodePathName(codePath); 11566 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 11567 .getAbsolutePath(); 11568 } 11569 11570 info.nativeLibraryRootRequiresIsa = false; 11571 info.nativeLibraryDir = info.nativeLibraryRootDir; 11572 } else { 11573 // Cluster install 11574 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 11575 info.nativeLibraryRootRequiresIsa = true; 11576 11577 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 11578 getPrimaryInstructionSet(info)).getAbsolutePath(); 11579 11580 if (info.secondaryCpuAbi != null) { 11581 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 11582 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 11583 } 11584 } 11585 } 11586 11587 /** 11588 * Calculate the abis and roots for a bundled app. These can uniquely 11589 * be determined from the contents of the system partition, i.e whether 11590 * it contains 64 or 32 bit shared libraries etc. We do not validate any 11591 * of this information, and instead assume that the system was built 11592 * sensibly. 11593 */ 11594 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 11595 PackageSetting pkgSetting) { 11596 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 11597 11598 // If "/system/lib64/apkname" exists, assume that is the per-package 11599 // native library directory to use; otherwise use "/system/lib/apkname". 11600 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 11601 setBundledAppAbi(pkg, apkRoot, apkName); 11602 // pkgSetting might be null during rescan following uninstall of updates 11603 // to a bundled app, so accommodate that possibility. The settings in 11604 // that case will be established later from the parsed package. 11605 // 11606 // If the settings aren't null, sync them up with what we've just derived. 11607 // note that apkRoot isn't stored in the package settings. 11608 if (pkgSetting != null) { 11609 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11610 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11611 } 11612 } 11613 11614 /** 11615 * Deduces the ABI of a bundled app and sets the relevant fields on the 11616 * parsed pkg object. 11617 * 11618 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 11619 * under which system libraries are installed. 11620 * @param apkName the name of the installed package. 11621 */ 11622 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 11623 final File codeFile = new File(pkg.codePath); 11624 11625 final boolean has64BitLibs; 11626 final boolean has32BitLibs; 11627 if (isApkFile(codeFile)) { 11628 // Monolithic install 11629 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 11630 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 11631 } else { 11632 // Cluster install 11633 final File rootDir = new File(codeFile, LIB_DIR_NAME); 11634 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 11635 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 11636 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 11637 has64BitLibs = (new File(rootDir, isa)).exists(); 11638 } else { 11639 has64BitLibs = false; 11640 } 11641 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 11642 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 11643 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 11644 has32BitLibs = (new File(rootDir, isa)).exists(); 11645 } else { 11646 has32BitLibs = false; 11647 } 11648 } 11649 11650 if (has64BitLibs && !has32BitLibs) { 11651 // The package has 64 bit libs, but not 32 bit libs. Its primary 11652 // ABI should be 64 bit. We can safely assume here that the bundled 11653 // native libraries correspond to the most preferred ABI in the list. 11654 11655 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11656 pkg.applicationInfo.secondaryCpuAbi = null; 11657 } else if (has32BitLibs && !has64BitLibs) { 11658 // The package has 32 bit libs but not 64 bit libs. Its primary 11659 // ABI should be 32 bit. 11660 11661 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11662 pkg.applicationInfo.secondaryCpuAbi = null; 11663 } else if (has32BitLibs && has64BitLibs) { 11664 // The application has both 64 and 32 bit bundled libraries. We check 11665 // here that the app declares multiArch support, and warn if it doesn't. 11666 // 11667 // We will be lenient here and record both ABIs. The primary will be the 11668 // ABI that's higher on the list, i.e, a device that's configured to prefer 11669 // 64 bit apps will see a 64 bit primary ABI, 11670 11671 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 11672 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 11673 } 11674 11675 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 11676 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11677 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11678 } else { 11679 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 11680 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 11681 } 11682 } else { 11683 pkg.applicationInfo.primaryCpuAbi = null; 11684 pkg.applicationInfo.secondaryCpuAbi = null; 11685 } 11686 } 11687 11688 private void killApplication(String pkgName, int appId, String reason) { 11689 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 11690 } 11691 11692 private void killApplication(String pkgName, int appId, int userId, String reason) { 11693 // Request the ActivityManager to kill the process(only for existing packages) 11694 // so that we do not end up in a confused state while the user is still using the older 11695 // version of the application while the new one gets installed. 11696 final long token = Binder.clearCallingIdentity(); 11697 try { 11698 IActivityManager am = ActivityManager.getService(); 11699 if (am != null) { 11700 try { 11701 am.killApplication(pkgName, appId, userId, reason); 11702 } catch (RemoteException e) { 11703 } 11704 } 11705 } finally { 11706 Binder.restoreCallingIdentity(token); 11707 } 11708 } 11709 11710 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 11711 // Remove the parent package setting 11712 PackageSetting ps = (PackageSetting) pkg.mExtras; 11713 if (ps != null) { 11714 removePackageLI(ps, chatty); 11715 } 11716 // Remove the child package setting 11717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11718 for (int i = 0; i < childCount; i++) { 11719 PackageParser.Package childPkg = pkg.childPackages.get(i); 11720 ps = (PackageSetting) childPkg.mExtras; 11721 if (ps != null) { 11722 removePackageLI(ps, chatty); 11723 } 11724 } 11725 } 11726 11727 void removePackageLI(PackageSetting ps, boolean chatty) { 11728 if (DEBUG_INSTALL) { 11729 if (chatty) 11730 Log.d(TAG, "Removing package " + ps.name); 11731 } 11732 11733 // writer 11734 synchronized (mPackages) { 11735 mPackages.remove(ps.name); 11736 final PackageParser.Package pkg = ps.pkg; 11737 if (pkg != null) { 11738 cleanPackageDataStructuresLILPw(pkg, chatty); 11739 } 11740 } 11741 } 11742 11743 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 11744 if (DEBUG_INSTALL) { 11745 if (chatty) 11746 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 11747 } 11748 11749 // writer 11750 synchronized (mPackages) { 11751 // Remove the parent package 11752 mPackages.remove(pkg.applicationInfo.packageName); 11753 cleanPackageDataStructuresLILPw(pkg, chatty); 11754 11755 // Remove the child packages 11756 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 11757 for (int i = 0; i < childCount; i++) { 11758 PackageParser.Package childPkg = pkg.childPackages.get(i); 11759 mPackages.remove(childPkg.applicationInfo.packageName); 11760 cleanPackageDataStructuresLILPw(childPkg, chatty); 11761 } 11762 } 11763 } 11764 11765 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 11766 int N = pkg.providers.size(); 11767 StringBuilder r = null; 11768 int i; 11769 for (i=0; i<N; i++) { 11770 PackageParser.Provider p = pkg.providers.get(i); 11771 mProviders.removeProvider(p); 11772 if (p.info.authority == null) { 11773 11774 /* There was another ContentProvider with this authority when 11775 * this app was installed so this authority is null, 11776 * Ignore it as we don't have to unregister the provider. 11777 */ 11778 continue; 11779 } 11780 String names[] = p.info.authority.split(";"); 11781 for (int j = 0; j < names.length; j++) { 11782 if (mProvidersByAuthority.get(names[j]) == p) { 11783 mProvidersByAuthority.remove(names[j]); 11784 if (DEBUG_REMOVE) { 11785 if (chatty) 11786 Log.d(TAG, "Unregistered content provider: " + names[j] 11787 + ", className = " + p.info.name + ", isSyncable = " 11788 + p.info.isSyncable); 11789 } 11790 } 11791 } 11792 if (DEBUG_REMOVE && chatty) { 11793 if (r == null) { 11794 r = new StringBuilder(256); 11795 } else { 11796 r.append(' '); 11797 } 11798 r.append(p.info.name); 11799 } 11800 } 11801 if (r != null) { 11802 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 11803 } 11804 11805 N = pkg.services.size(); 11806 r = null; 11807 for (i=0; i<N; i++) { 11808 PackageParser.Service s = pkg.services.get(i); 11809 mServices.removeService(s); 11810 if (chatty) { 11811 if (r == null) { 11812 r = new StringBuilder(256); 11813 } else { 11814 r.append(' '); 11815 } 11816 r.append(s.info.name); 11817 } 11818 } 11819 if (r != null) { 11820 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 11821 } 11822 11823 N = pkg.receivers.size(); 11824 r = null; 11825 for (i=0; i<N; i++) { 11826 PackageParser.Activity a = pkg.receivers.get(i); 11827 mReceivers.removeActivity(a, "receiver"); 11828 if (DEBUG_REMOVE && chatty) { 11829 if (r == null) { 11830 r = new StringBuilder(256); 11831 } else { 11832 r.append(' '); 11833 } 11834 r.append(a.info.name); 11835 } 11836 } 11837 if (r != null) { 11838 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 11839 } 11840 11841 N = pkg.activities.size(); 11842 r = null; 11843 for (i=0; i<N; i++) { 11844 PackageParser.Activity a = pkg.activities.get(i); 11845 mActivities.removeActivity(a, "activity"); 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, " Activities: " + r); 11857 } 11858 11859 mPermissionManager.removeAllPermissions(pkg, chatty); 11860 11861 N = pkg.instrumentation.size(); 11862 r = null; 11863 for (i=0; i<N; i++) { 11864 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 11865 mInstrumentation.remove(a.getComponentName()); 11866 if (DEBUG_REMOVE && chatty) { 11867 if (r == null) { 11868 r = new StringBuilder(256); 11869 } else { 11870 r.append(' '); 11871 } 11872 r.append(a.info.name); 11873 } 11874 } 11875 if (r != null) { 11876 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 11877 } 11878 11879 r = null; 11880 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 11881 // Only system apps can hold shared libraries. 11882 if (pkg.libraryNames != null) { 11883 for (i = 0; i < pkg.libraryNames.size(); i++) { 11884 String name = pkg.libraryNames.get(i); 11885 if (removeSharedLibraryLPw(name, 0)) { 11886 if (DEBUG_REMOVE && chatty) { 11887 if (r == null) { 11888 r = new StringBuilder(256); 11889 } else { 11890 r.append(' '); 11891 } 11892 r.append(name); 11893 } 11894 } 11895 } 11896 } 11897 } 11898 11899 r = null; 11900 11901 // Any package can hold static shared libraries. 11902 if (pkg.staticSharedLibName != null) { 11903 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 11904 if (DEBUG_REMOVE && chatty) { 11905 if (r == null) { 11906 r = new StringBuilder(256); 11907 } else { 11908 r.append(' '); 11909 } 11910 r.append(pkg.staticSharedLibName); 11911 } 11912 } 11913 } 11914 11915 if (r != null) { 11916 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 11917 } 11918 } 11919 11920 11921 final class ActivityIntentResolver 11922 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 11923 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11924 boolean defaultOnly, int userId) { 11925 if (!sUserManager.exists(userId)) return null; 11926 mFlags = (defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0); 11927 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11928 } 11929 11930 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11931 int userId) { 11932 if (!sUserManager.exists(userId)) return null; 11933 mFlags = flags; 11934 return super.queryIntent(intent, resolvedType, 11935 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 11936 userId); 11937 } 11938 11939 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11940 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 11941 if (!sUserManager.exists(userId)) return null; 11942 if (packageActivities == null) { 11943 return null; 11944 } 11945 mFlags = flags; 11946 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11947 final int N = packageActivities.size(); 11948 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 11949 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 11950 11951 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 11952 for (int i = 0; i < N; ++i) { 11953 intentFilters = packageActivities.get(i).intents; 11954 if (intentFilters != null && intentFilters.size() > 0) { 11955 PackageParser.ActivityIntentInfo[] array = 11956 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 11957 intentFilters.toArray(array); 11958 listCut.add(array); 11959 } 11960 } 11961 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11962 } 11963 11964 /** 11965 * Finds a privileged activity that matches the specified activity names. 11966 */ 11967 private PackageParser.Activity findMatchingActivity( 11968 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 11969 for (PackageParser.Activity sysActivity : activityList) { 11970 if (sysActivity.info.name.equals(activityInfo.name)) { 11971 return sysActivity; 11972 } 11973 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 11974 return sysActivity; 11975 } 11976 if (sysActivity.info.targetActivity != null) { 11977 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 11978 return sysActivity; 11979 } 11980 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 11981 return sysActivity; 11982 } 11983 } 11984 } 11985 return null; 11986 } 11987 11988 public class IterGenerator<E> { 11989 public Iterator<E> generate(ActivityIntentInfo info) { 11990 return null; 11991 } 11992 } 11993 11994 public class ActionIterGenerator extends IterGenerator<String> { 11995 @Override 11996 public Iterator<String> generate(ActivityIntentInfo info) { 11997 return info.actionsIterator(); 11998 } 11999 } 12000 12001 public class CategoriesIterGenerator extends IterGenerator<String> { 12002 @Override 12003 public Iterator<String> generate(ActivityIntentInfo info) { 12004 return info.categoriesIterator(); 12005 } 12006 } 12007 12008 public class SchemesIterGenerator extends IterGenerator<String> { 12009 @Override 12010 public Iterator<String> generate(ActivityIntentInfo info) { 12011 return info.schemesIterator(); 12012 } 12013 } 12014 12015 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 12016 @Override 12017 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 12018 return info.authoritiesIterator(); 12019 } 12020 } 12021 12022 /** 12023 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 12024 * MODIFIED. Do not pass in a list that should not be changed. 12025 */ 12026 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 12027 IterGenerator<T> generator, Iterator<T> searchIterator) { 12028 // loop through the set of actions; every one must be found in the intent filter 12029 while (searchIterator.hasNext()) { 12030 // we must have at least one filter in the list to consider a match 12031 if (intentList.size() == 0) { 12032 break; 12033 } 12034 12035 final T searchAction = searchIterator.next(); 12036 12037 // loop through the set of intent filters 12038 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 12039 while (intentIter.hasNext()) { 12040 final ActivityIntentInfo intentInfo = intentIter.next(); 12041 boolean selectionFound = false; 12042 12043 // loop through the intent filter's selection criteria; at least one 12044 // of them must match the searched criteria 12045 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 12046 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 12047 final T intentSelection = intentSelectionIter.next(); 12048 if (intentSelection != null && intentSelection.equals(searchAction)) { 12049 selectionFound = true; 12050 break; 12051 } 12052 } 12053 12054 // the selection criteria wasn't found in this filter's set; this filter 12055 // is not a potential match 12056 if (!selectionFound) { 12057 intentIter.remove(); 12058 } 12059 } 12060 } 12061 } 12062 12063 private boolean isProtectedAction(ActivityIntentInfo filter) { 12064 final Iterator<String> actionsIter = filter.actionsIterator(); 12065 while (actionsIter != null && actionsIter.hasNext()) { 12066 final String filterAction = actionsIter.next(); 12067 if (PROTECTED_ACTIONS.contains(filterAction)) { 12068 return true; 12069 } 12070 } 12071 return false; 12072 } 12073 12074 /** 12075 * Adjusts the priority of the given intent filter according to policy. 12076 * <p> 12077 * <ul> 12078 * <li>The priority for non privileged applications is capped to '0'</li> 12079 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 12080 * <li>The priority for unbundled updates to privileged applications is capped to the 12081 * priority defined on the system partition</li> 12082 * </ul> 12083 * <p> 12084 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 12085 * allowed to obtain any priority on any action. 12086 */ 12087 private void adjustPriority( 12088 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 12089 // nothing to do; priority is fine as-is 12090 if (intent.getPriority() <= 0) { 12091 return; 12092 } 12093 12094 final ActivityInfo activityInfo = intent.activity.info; 12095 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 12096 12097 final boolean privilegedApp = 12098 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 12099 if (!privilegedApp) { 12100 // non-privileged applications can never define a priority >0 12101 if (DEBUG_FILTERS) { 12102 Slog.i(TAG, "Non-privileged app; cap priority to 0;" 12103 + " package: " + applicationInfo.packageName 12104 + " activity: " + intent.activity.className 12105 + " origPrio: " + intent.getPriority()); 12106 } 12107 intent.setPriority(0); 12108 return; 12109 } 12110 12111 if (systemActivities == null) { 12112 // the system package is not disabled; we're parsing the system partition 12113 if (isProtectedAction(intent)) { 12114 if (mDeferProtectedFilters) { 12115 // We can't deal with these just yet. No component should ever obtain a 12116 // >0 priority for a protected actions, with ONE exception -- the setup 12117 // wizard. The setup wizard, however, cannot be known until we're able to 12118 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 12119 // until all intent filters have been processed. Chicken, meet egg. 12120 // Let the filter temporarily have a high priority and rectify the 12121 // priorities after all system packages have been scanned. 12122 mProtectedFilters.add(intent); 12123 if (DEBUG_FILTERS) { 12124 Slog.i(TAG, "Protected action; save for later;" 12125 + " package: " + applicationInfo.packageName 12126 + " activity: " + intent.activity.className 12127 + " origPrio: " + intent.getPriority()); 12128 } 12129 return; 12130 } else { 12131 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 12132 Slog.i(TAG, "No setup wizard;" 12133 + " All protected intents capped to priority 0"); 12134 } 12135 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 12136 if (DEBUG_FILTERS) { 12137 Slog.i(TAG, "Found setup wizard;" 12138 + " allow priority " + intent.getPriority() + ";" 12139 + " package: " + intent.activity.info.packageName 12140 + " activity: " + intent.activity.className 12141 + " priority: " + intent.getPriority()); 12142 } 12143 // setup wizard gets whatever it wants 12144 return; 12145 } 12146 if (DEBUG_FILTERS) { 12147 Slog.i(TAG, "Protected action; cap priority to 0;" 12148 + " package: " + intent.activity.info.packageName 12149 + " activity: " + intent.activity.className 12150 + " origPrio: " + intent.getPriority()); 12151 } 12152 intent.setPriority(0); 12153 return; 12154 } 12155 } 12156 // privileged apps on the system image get whatever priority they request 12157 return; 12158 } 12159 12160 // privileged app unbundled update ... try to find the same activity 12161 final PackageParser.Activity foundActivity = 12162 findMatchingActivity(systemActivities, activityInfo); 12163 if (foundActivity == null) { 12164 // this is a new activity; it cannot obtain >0 priority 12165 if (DEBUG_FILTERS) { 12166 Slog.i(TAG, "New activity; cap priority to 0;" 12167 + " package: " + applicationInfo.packageName 12168 + " activity: " + intent.activity.className 12169 + " origPrio: " + intent.getPriority()); 12170 } 12171 intent.setPriority(0); 12172 return; 12173 } 12174 12175 // found activity, now check for filter equivalence 12176 12177 // a shallow copy is enough; we modify the list, not its contents 12178 final List<ActivityIntentInfo> intentListCopy = 12179 new ArrayList<>(foundActivity.intents); 12180 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 12181 12182 // find matching action subsets 12183 final Iterator<String> actionsIterator = intent.actionsIterator(); 12184 if (actionsIterator != null) { 12185 getIntentListSubset( 12186 intentListCopy, new ActionIterGenerator(), actionsIterator); 12187 if (intentListCopy.size() == 0) { 12188 // no more intents to match; we're not equivalent 12189 if (DEBUG_FILTERS) { 12190 Slog.i(TAG, "Mismatched action; cap priority to 0;" 12191 + " package: " + applicationInfo.packageName 12192 + " activity: " + intent.activity.className 12193 + " origPrio: " + intent.getPriority()); 12194 } 12195 intent.setPriority(0); 12196 return; 12197 } 12198 } 12199 12200 // find matching category subsets 12201 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 12202 if (categoriesIterator != null) { 12203 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 12204 categoriesIterator); 12205 if (intentListCopy.size() == 0) { 12206 // no more intents to match; we're not equivalent 12207 if (DEBUG_FILTERS) { 12208 Slog.i(TAG, "Mismatched category; cap priority to 0;" 12209 + " package: " + applicationInfo.packageName 12210 + " activity: " + intent.activity.className 12211 + " origPrio: " + intent.getPriority()); 12212 } 12213 intent.setPriority(0); 12214 return; 12215 } 12216 } 12217 12218 // find matching schemes subsets 12219 final Iterator<String> schemesIterator = intent.schemesIterator(); 12220 if (schemesIterator != null) { 12221 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 12222 schemesIterator); 12223 if (intentListCopy.size() == 0) { 12224 // no more intents to match; we're not equivalent 12225 if (DEBUG_FILTERS) { 12226 Slog.i(TAG, "Mismatched scheme; 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 // find matching authorities subsets 12237 final Iterator<IntentFilter.AuthorityEntry> 12238 authoritiesIterator = intent.authoritiesIterator(); 12239 if (authoritiesIterator != null) { 12240 getIntentListSubset(intentListCopy, 12241 new AuthoritiesIterGenerator(), 12242 authoritiesIterator); 12243 if (intentListCopy.size() == 0) { 12244 // no more intents to match; we're not equivalent 12245 if (DEBUG_FILTERS) { 12246 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 12247 + " package: " + applicationInfo.packageName 12248 + " activity: " + intent.activity.className 12249 + " origPrio: " + intent.getPriority()); 12250 } 12251 intent.setPriority(0); 12252 return; 12253 } 12254 } 12255 12256 // we found matching filter(s); app gets the max priority of all intents 12257 int cappedPriority = 0; 12258 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 12259 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 12260 } 12261 if (intent.getPriority() > cappedPriority) { 12262 if (DEBUG_FILTERS) { 12263 Slog.i(TAG, "Found matching filter(s);" 12264 + " cap priority to " + cappedPriority + ";" 12265 + " package: " + applicationInfo.packageName 12266 + " activity: " + intent.activity.className 12267 + " origPrio: " + intent.getPriority()); 12268 } 12269 intent.setPriority(cappedPriority); 12270 return; 12271 } 12272 // all this for nothing; the requested priority was <= what was on the system 12273 } 12274 12275 public final void addActivity(PackageParser.Activity a, String type) { 12276 mActivities.put(a.getComponentName(), a); 12277 if (DEBUG_SHOW_INFO) 12278 Log.v( 12279 TAG, " " + type + " " + 12280 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 12281 if (DEBUG_SHOW_INFO) 12282 Log.v(TAG, " Class=" + a.info.name); 12283 final int NI = a.intents.size(); 12284 for (int j=0; j<NI; j++) { 12285 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12286 if ("activity".equals(type)) { 12287 final PackageSetting ps = 12288 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 12289 final List<PackageParser.Activity> systemActivities = 12290 ps != null && ps.pkg != null ? ps.pkg.activities : null; 12291 adjustPriority(systemActivities, intent); 12292 } 12293 if (DEBUG_SHOW_INFO) { 12294 Log.v(TAG, " IntentFilter:"); 12295 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12296 } 12297 if (!intent.debugCheck()) { 12298 Log.w(TAG, "==> For Activity " + a.info.name); 12299 } 12300 addFilter(intent); 12301 } 12302 } 12303 12304 public final void removeActivity(PackageParser.Activity a, String type) { 12305 mActivities.remove(a.getComponentName()); 12306 if (DEBUG_SHOW_INFO) { 12307 Log.v(TAG, " " + type + " " 12308 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 12309 : a.info.name) + ":"); 12310 Log.v(TAG, " Class=" + a.info.name); 12311 } 12312 final int NI = a.intents.size(); 12313 for (int j=0; j<NI; j++) { 12314 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 12315 if (DEBUG_SHOW_INFO) { 12316 Log.v(TAG, " IntentFilter:"); 12317 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12318 } 12319 removeFilter(intent); 12320 } 12321 } 12322 12323 @Override 12324 protected boolean allowFilterResult( 12325 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 12326 ActivityInfo filterAi = filter.activity.info; 12327 for (int i=dest.size()-1; i>=0; i--) { 12328 ActivityInfo destAi = dest.get(i).activityInfo; 12329 if (destAi.name == filterAi.name 12330 && destAi.packageName == filterAi.packageName) { 12331 return false; 12332 } 12333 } 12334 return true; 12335 } 12336 12337 @Override 12338 protected ActivityIntentInfo[] newArray(int size) { 12339 return new ActivityIntentInfo[size]; 12340 } 12341 12342 @Override 12343 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 12344 if (!sUserManager.exists(userId)) return true; 12345 PackageParser.Package p = filter.activity.owner; 12346 if (p != null) { 12347 PackageSetting ps = (PackageSetting)p.mExtras; 12348 if (ps != null) { 12349 // System apps are never considered stopped for purposes of 12350 // filtering, because there may be no way for the user to 12351 // actually re-launch them. 12352 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 12353 && ps.getStopped(userId); 12354 } 12355 } 12356 return false; 12357 } 12358 12359 @Override 12360 protected boolean isPackageForFilter(String packageName, 12361 PackageParser.ActivityIntentInfo info) { 12362 return packageName.equals(info.activity.owner.packageName); 12363 } 12364 12365 @Override 12366 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 12367 int match, int userId) { 12368 if (!sUserManager.exists(userId)) return null; 12369 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 12370 return null; 12371 } 12372 final PackageParser.Activity activity = info.activity; 12373 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 12374 if (ps == null) { 12375 return null; 12376 } 12377 final PackageUserState userState = ps.readUserState(userId); 12378 ActivityInfo ai = 12379 PackageParser.generateActivityInfo(activity, mFlags, userState, userId); 12380 if (ai == null) { 12381 return null; 12382 } 12383 final boolean matchExplicitlyVisibleOnly = 12384 (mFlags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 12385 final boolean matchVisibleToInstantApp = 12386 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12387 final boolean componentVisible = 12388 matchVisibleToInstantApp 12389 && info.isVisibleToInstantApp() 12390 && (!matchExplicitlyVisibleOnly || info.isExplicitlyVisibleToInstantApp()); 12391 final boolean matchInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12392 // throw out filters that aren't visible to ephemeral apps 12393 if (matchVisibleToInstantApp && !(componentVisible || userState.instantApp)) { 12394 return null; 12395 } 12396 // throw out instant app filters if we're not explicitly requesting them 12397 if (!matchInstantApp && userState.instantApp) { 12398 return null; 12399 } 12400 // throw out instant app filters if updates are available; will trigger 12401 // instant app resolution 12402 if (userState.instantApp && ps.isUpdateAvailable()) { 12403 return null; 12404 } 12405 final ResolveInfo res = new ResolveInfo(); 12406 res.activityInfo = ai; 12407 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12408 res.filter = info; 12409 } 12410 if (info != null) { 12411 res.handleAllWebDataURI = info.handleAllWebDataURI(); 12412 } 12413 res.priority = info.getPriority(); 12414 res.preferredOrder = activity.owner.mPreferredOrder; 12415 //System.out.println("Result: " + res.activityInfo.className + 12416 // " = " + res.priority); 12417 res.match = match; 12418 res.isDefault = info.hasDefault; 12419 res.labelRes = info.labelRes; 12420 res.nonLocalizedLabel = info.nonLocalizedLabel; 12421 if (userNeedsBadging(userId)) { 12422 res.noResourceId = true; 12423 } else { 12424 res.icon = info.icon; 12425 } 12426 res.iconResourceId = info.icon; 12427 res.system = res.activityInfo.applicationInfo.isSystemApp(); 12428 res.isInstantAppAvailable = userState.instantApp; 12429 return res; 12430 } 12431 12432 @Override 12433 protected void sortResults(List<ResolveInfo> results) { 12434 Collections.sort(results, mResolvePrioritySorter); 12435 } 12436 12437 @Override 12438 protected void dumpFilter(PrintWriter out, String prefix, 12439 PackageParser.ActivityIntentInfo filter) { 12440 out.print(prefix); out.print( 12441 Integer.toHexString(System.identityHashCode(filter.activity))); 12442 out.print(' '); 12443 filter.activity.printComponentShortName(out); 12444 out.print(" filter "); 12445 out.println(Integer.toHexString(System.identityHashCode(filter))); 12446 } 12447 12448 @Override 12449 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 12450 return filter.activity; 12451 } 12452 12453 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12454 PackageParser.Activity activity = (PackageParser.Activity)label; 12455 out.print(prefix); out.print( 12456 Integer.toHexString(System.identityHashCode(activity))); 12457 out.print(' '); 12458 activity.printComponentShortName(out); 12459 if (count > 1) { 12460 out.print(" ("); out.print(count); out.print(" filters)"); 12461 } 12462 out.println(); 12463 } 12464 12465 // Keys are String (activity class name), values are Activity. 12466 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 12467 = new ArrayMap<ComponentName, PackageParser.Activity>(); 12468 private int mFlags; 12469 } 12470 12471 private final class ServiceIntentResolver 12472 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 12473 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12474 boolean defaultOnly, int userId) { 12475 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12476 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12477 } 12478 12479 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12480 int userId) { 12481 if (!sUserManager.exists(userId)) return null; 12482 mFlags = flags; 12483 return super.queryIntent(intent, resolvedType, 12484 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12485 userId); 12486 } 12487 12488 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12489 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 12490 if (!sUserManager.exists(userId)) return null; 12491 if (packageServices == null) { 12492 return null; 12493 } 12494 mFlags = flags; 12495 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 12496 final int N = packageServices.size(); 12497 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 12498 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 12499 12500 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 12501 for (int i = 0; i < N; ++i) { 12502 intentFilters = packageServices.get(i).intents; 12503 if (intentFilters != null && intentFilters.size() > 0) { 12504 PackageParser.ServiceIntentInfo[] array = 12505 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 12506 intentFilters.toArray(array); 12507 listCut.add(array); 12508 } 12509 } 12510 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12511 } 12512 12513 public final void addService(PackageParser.Service s) { 12514 mServices.put(s.getComponentName(), s); 12515 if (DEBUG_SHOW_INFO) { 12516 Log.v(TAG, " " 12517 + (s.info.nonLocalizedLabel != null 12518 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12519 Log.v(TAG, " Class=" + s.info.name); 12520 } 12521 final int NI = s.intents.size(); 12522 int j; 12523 for (j=0; j<NI; j++) { 12524 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12525 if (DEBUG_SHOW_INFO) { 12526 Log.v(TAG, " IntentFilter:"); 12527 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12528 } 12529 if (!intent.debugCheck()) { 12530 Log.w(TAG, "==> For Service " + s.info.name); 12531 } 12532 addFilter(intent); 12533 } 12534 } 12535 12536 public final void removeService(PackageParser.Service s) { 12537 mServices.remove(s.getComponentName()); 12538 if (DEBUG_SHOW_INFO) { 12539 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 12540 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 12541 Log.v(TAG, " Class=" + s.info.name); 12542 } 12543 final int NI = s.intents.size(); 12544 int j; 12545 for (j=0; j<NI; j++) { 12546 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 12547 if (DEBUG_SHOW_INFO) { 12548 Log.v(TAG, " IntentFilter:"); 12549 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12550 } 12551 removeFilter(intent); 12552 } 12553 } 12554 12555 @Override 12556 protected boolean allowFilterResult( 12557 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 12558 ServiceInfo filterSi = filter.service.info; 12559 for (int i=dest.size()-1; i>=0; i--) { 12560 ServiceInfo destAi = dest.get(i).serviceInfo; 12561 if (destAi.name == filterSi.name 12562 && destAi.packageName == filterSi.packageName) { 12563 return false; 12564 } 12565 } 12566 return true; 12567 } 12568 12569 @Override 12570 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 12571 return new PackageParser.ServiceIntentInfo[size]; 12572 } 12573 12574 @Override 12575 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 12576 if (!sUserManager.exists(userId)) return true; 12577 PackageParser.Package p = filter.service.owner; 12578 if (p != null) { 12579 PackageSetting ps = (PackageSetting)p.mExtras; 12580 if (ps != null) { 12581 // System apps are never considered stopped for purposes of 12582 // filtering, because there may be no way for the user to 12583 // actually re-launch them. 12584 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12585 && ps.getStopped(userId); 12586 } 12587 } 12588 return false; 12589 } 12590 12591 @Override 12592 protected boolean isPackageForFilter(String packageName, 12593 PackageParser.ServiceIntentInfo info) { 12594 return packageName.equals(info.service.owner.packageName); 12595 } 12596 12597 @Override 12598 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 12599 int match, int userId) { 12600 if (!sUserManager.exists(userId)) return null; 12601 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 12602 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 12603 return null; 12604 } 12605 final PackageParser.Service service = info.service; 12606 PackageSetting ps = (PackageSetting) service.owner.mExtras; 12607 if (ps == null) { 12608 return null; 12609 } 12610 final PackageUserState userState = ps.readUserState(userId); 12611 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 12612 userState, userId); 12613 if (si == null) { 12614 return null; 12615 } 12616 final boolean matchVisibleToInstantApp = 12617 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12618 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12619 // throw out filters that aren't visible to ephemeral apps 12620 if (matchVisibleToInstantApp 12621 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12622 return null; 12623 } 12624 // throw out ephemeral filters if we're not explicitly requesting them 12625 if (!isInstantApp && userState.instantApp) { 12626 return null; 12627 } 12628 // throw out instant app filters if updates are available; will trigger 12629 // instant app resolution 12630 if (userState.instantApp && ps.isUpdateAvailable()) { 12631 return null; 12632 } 12633 final ResolveInfo res = new ResolveInfo(); 12634 res.serviceInfo = si; 12635 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 12636 res.filter = filter; 12637 } 12638 res.priority = info.getPriority(); 12639 res.preferredOrder = service.owner.mPreferredOrder; 12640 res.match = match; 12641 res.isDefault = info.hasDefault; 12642 res.labelRes = info.labelRes; 12643 res.nonLocalizedLabel = info.nonLocalizedLabel; 12644 res.icon = info.icon; 12645 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 12646 return res; 12647 } 12648 12649 @Override 12650 protected void sortResults(List<ResolveInfo> results) { 12651 Collections.sort(results, mResolvePrioritySorter); 12652 } 12653 12654 @Override 12655 protected void dumpFilter(PrintWriter out, String prefix, 12656 PackageParser.ServiceIntentInfo filter) { 12657 out.print(prefix); out.print( 12658 Integer.toHexString(System.identityHashCode(filter.service))); 12659 out.print(' '); 12660 filter.service.printComponentShortName(out); 12661 out.print(" filter "); 12662 out.print(Integer.toHexString(System.identityHashCode(filter))); 12663 if (filter.service.info.permission != null) { 12664 out.print(" permission "); out.println(filter.service.info.permission); 12665 } else { 12666 out.println(); 12667 } 12668 } 12669 12670 @Override 12671 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 12672 return filter.service; 12673 } 12674 12675 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12676 PackageParser.Service service = (PackageParser.Service)label; 12677 out.print(prefix); out.print( 12678 Integer.toHexString(System.identityHashCode(service))); 12679 out.print(' '); 12680 service.printComponentShortName(out); 12681 if (count > 1) { 12682 out.print(" ("); out.print(count); out.print(" filters)"); 12683 } 12684 out.println(); 12685 } 12686 12687// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 12688// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 12689// final List<ResolveInfo> retList = Lists.newArrayList(); 12690// while (i.hasNext()) { 12691// final ResolveInfo resolveInfo = (ResolveInfo) i; 12692// if (isEnabledLP(resolveInfo.serviceInfo)) { 12693// retList.add(resolveInfo); 12694// } 12695// } 12696// return retList; 12697// } 12698 12699 // Keys are String (activity class name), values are Activity. 12700 private final ArrayMap<ComponentName, PackageParser.Service> mServices 12701 = new ArrayMap<ComponentName, PackageParser.Service>(); 12702 private int mFlags; 12703 } 12704 12705 private final class ProviderIntentResolver 12706 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 12707 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 12708 boolean defaultOnly, int userId) { 12709 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 12710 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 12711 } 12712 12713 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 12714 int userId) { 12715 if (!sUserManager.exists(userId)) 12716 return null; 12717 mFlags = flags; 12718 return super.queryIntent(intent, resolvedType, 12719 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 12720 userId); 12721 } 12722 12723 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 12724 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 12725 if (!sUserManager.exists(userId)) 12726 return null; 12727 if (packageProviders == null) { 12728 return null; 12729 } 12730 mFlags = flags; 12731 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 12732 final int N = packageProviders.size(); 12733 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 12734 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 12735 12736 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 12737 for (int i = 0; i < N; ++i) { 12738 intentFilters = packageProviders.get(i).intents; 12739 if (intentFilters != null && intentFilters.size() > 0) { 12740 PackageParser.ProviderIntentInfo[] array = 12741 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 12742 intentFilters.toArray(array); 12743 listCut.add(array); 12744 } 12745 } 12746 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 12747 } 12748 12749 public final void addProvider(PackageParser.Provider p) { 12750 if (mProviders.containsKey(p.getComponentName())) { 12751 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 12752 return; 12753 } 12754 12755 mProviders.put(p.getComponentName(), p); 12756 if (DEBUG_SHOW_INFO) { 12757 Log.v(TAG, " " 12758 + (p.info.nonLocalizedLabel != null 12759 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12760 Log.v(TAG, " Class=" + p.info.name); 12761 } 12762 final int NI = p.intents.size(); 12763 int j; 12764 for (j = 0; j < NI; j++) { 12765 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12766 if (DEBUG_SHOW_INFO) { 12767 Log.v(TAG, " IntentFilter:"); 12768 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12769 } 12770 if (!intent.debugCheck()) { 12771 Log.w(TAG, "==> For Provider " + p.info.name); 12772 } 12773 addFilter(intent); 12774 } 12775 } 12776 12777 public final void removeProvider(PackageParser.Provider p) { 12778 mProviders.remove(p.getComponentName()); 12779 if (DEBUG_SHOW_INFO) { 12780 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 12781 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 12782 Log.v(TAG, " Class=" + p.info.name); 12783 } 12784 final int NI = p.intents.size(); 12785 int j; 12786 for (j = 0; j < NI; j++) { 12787 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 12788 if (DEBUG_SHOW_INFO) { 12789 Log.v(TAG, " IntentFilter:"); 12790 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 12791 } 12792 removeFilter(intent); 12793 } 12794 } 12795 12796 @Override 12797 protected boolean allowFilterResult( 12798 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 12799 ProviderInfo filterPi = filter.provider.info; 12800 for (int i = dest.size() - 1; i >= 0; i--) { 12801 ProviderInfo destPi = dest.get(i).providerInfo; 12802 if (destPi.name == filterPi.name 12803 && destPi.packageName == filterPi.packageName) { 12804 return false; 12805 } 12806 } 12807 return true; 12808 } 12809 12810 @Override 12811 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 12812 return new PackageParser.ProviderIntentInfo[size]; 12813 } 12814 12815 @Override 12816 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 12817 if (!sUserManager.exists(userId)) 12818 return true; 12819 PackageParser.Package p = filter.provider.owner; 12820 if (p != null) { 12821 PackageSetting ps = (PackageSetting) p.mExtras; 12822 if (ps != null) { 12823 // System apps are never considered stopped for purposes of 12824 // filtering, because there may be no way for the user to 12825 // actually re-launch them. 12826 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 12827 && ps.getStopped(userId); 12828 } 12829 } 12830 return false; 12831 } 12832 12833 @Override 12834 protected boolean isPackageForFilter(String packageName, 12835 PackageParser.ProviderIntentInfo info) { 12836 return packageName.equals(info.provider.owner.packageName); 12837 } 12838 12839 @Override 12840 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 12841 int match, int userId) { 12842 if (!sUserManager.exists(userId)) 12843 return null; 12844 final PackageParser.ProviderIntentInfo info = filter; 12845 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 12846 return null; 12847 } 12848 final PackageParser.Provider provider = info.provider; 12849 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 12850 if (ps == null) { 12851 return null; 12852 } 12853 final PackageUserState userState = ps.readUserState(userId); 12854 final boolean matchVisibleToInstantApp = 12855 (mFlags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 12856 final boolean isInstantApp = (mFlags & PackageManager.MATCH_INSTANT) != 0; 12857 // throw out filters that aren't visible to instant applications 12858 if (matchVisibleToInstantApp 12859 && !(info.isVisibleToInstantApp() || userState.instantApp)) { 12860 return null; 12861 } 12862 // throw out instant application filters if we're not explicitly requesting them 12863 if (!isInstantApp && userState.instantApp) { 12864 return null; 12865 } 12866 // throw out instant application filters if updates are available; will trigger 12867 // instant application resolution 12868 if (userState.instantApp && ps.isUpdateAvailable()) { 12869 return null; 12870 } 12871 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 12872 userState, userId); 12873 if (pi == null) { 12874 return null; 12875 } 12876 final ResolveInfo res = new ResolveInfo(); 12877 res.providerInfo = pi; 12878 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 12879 res.filter = filter; 12880 } 12881 res.priority = info.getPriority(); 12882 res.preferredOrder = provider.owner.mPreferredOrder; 12883 res.match = match; 12884 res.isDefault = info.hasDefault; 12885 res.labelRes = info.labelRes; 12886 res.nonLocalizedLabel = info.nonLocalizedLabel; 12887 res.icon = info.icon; 12888 res.system = res.providerInfo.applicationInfo.isSystemApp(); 12889 return res; 12890 } 12891 12892 @Override 12893 protected void sortResults(List<ResolveInfo> results) { 12894 Collections.sort(results, mResolvePrioritySorter); 12895 } 12896 12897 @Override 12898 protected void dumpFilter(PrintWriter out, String prefix, 12899 PackageParser.ProviderIntentInfo filter) { 12900 out.print(prefix); 12901 out.print( 12902 Integer.toHexString(System.identityHashCode(filter.provider))); 12903 out.print(' '); 12904 filter.provider.printComponentShortName(out); 12905 out.print(" filter "); 12906 out.println(Integer.toHexString(System.identityHashCode(filter))); 12907 } 12908 12909 @Override 12910 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 12911 return filter.provider; 12912 } 12913 12914 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 12915 PackageParser.Provider provider = (PackageParser.Provider)label; 12916 out.print(prefix); out.print( 12917 Integer.toHexString(System.identityHashCode(provider))); 12918 out.print(' '); 12919 provider.printComponentShortName(out); 12920 if (count > 1) { 12921 out.print(" ("); out.print(count); out.print(" filters)"); 12922 } 12923 out.println(); 12924 } 12925 12926 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 12927 = new ArrayMap<ComponentName, PackageParser.Provider>(); 12928 private int mFlags; 12929 } 12930 12931 static final class EphemeralIntentResolver 12932 extends IntentResolver<AuxiliaryResolveInfo, AuxiliaryResolveInfo> { 12933 /** 12934 * The result that has the highest defined order. Ordering applies on a 12935 * per-package basis. Mapping is from package name to Pair of order and 12936 * EphemeralResolveInfo. 12937 * <p> 12938 * NOTE: This is implemented as a field variable for convenience and efficiency. 12939 * By having a field variable, we're able to track filter ordering as soon as 12940 * a non-zero order is defined. Otherwise, multiple loops across the result set 12941 * would be needed to apply ordering. If the intent resolver becomes re-entrant, 12942 * this needs to be contained entirely within {@link #filterResults}. 12943 */ 12944 final ArrayMap<String, Pair<Integer, InstantAppResolveInfo>> mOrderResult = new ArrayMap<>(); 12945 12946 @Override 12947 protected AuxiliaryResolveInfo[] newArray(int size) { 12948 return new AuxiliaryResolveInfo[size]; 12949 } 12950 12951 @Override 12952 protected boolean isPackageForFilter(String packageName, AuxiliaryResolveInfo responseObj) { 12953 return true; 12954 } 12955 12956 @Override 12957 protected AuxiliaryResolveInfo newResult(AuxiliaryResolveInfo responseObj, int match, 12958 int userId) { 12959 if (!sUserManager.exists(userId)) { 12960 return null; 12961 } 12962 final String packageName = responseObj.resolveInfo.getPackageName(); 12963 final Integer order = responseObj.getOrder(); 12964 final Pair<Integer, InstantAppResolveInfo> lastOrderResult = 12965 mOrderResult.get(packageName); 12966 // ordering is enabled and this item's order isn't high enough 12967 if (lastOrderResult != null && lastOrderResult.first >= order) { 12968 return null; 12969 } 12970 final InstantAppResolveInfo res = responseObj.resolveInfo; 12971 if (order > 0) { 12972 // non-zero order, enable ordering 12973 mOrderResult.put(packageName, new Pair<>(order, res)); 12974 } 12975 return responseObj; 12976 } 12977 12978 @Override 12979 protected void filterResults(List<AuxiliaryResolveInfo> results) { 12980 // only do work if ordering is enabled [most of the time it won't be] 12981 if (mOrderResult.size() == 0) { 12982 return; 12983 } 12984 int resultSize = results.size(); 12985 for (int i = 0; i < resultSize; i++) { 12986 final InstantAppResolveInfo info = results.get(i).resolveInfo; 12987 final String packageName = info.getPackageName(); 12988 final Pair<Integer, InstantAppResolveInfo> savedInfo = mOrderResult.get(packageName); 12989 if (savedInfo == null) { 12990 // package doesn't having ordering 12991 continue; 12992 } 12993 if (savedInfo.second == info) { 12994 // circled back to the highest ordered item; remove from order list 12995 mOrderResult.remove(packageName); 12996 if (mOrderResult.size() == 0) { 12997 // no more ordered items 12998 break; 12999 } 13000 continue; 13001 } 13002 // item has a worse order, remove it from the result list 13003 results.remove(i); 13004 resultSize--; 13005 i--; 13006 } 13007 } 13008 } 13009 13010 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 13011 new Comparator<ResolveInfo>() { 13012 public int compare(ResolveInfo r1, ResolveInfo r2) { 13013 int v1 = r1.priority; 13014 int v2 = r2.priority; 13015 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 13016 if (v1 != v2) { 13017 return (v1 > v2) ? -1 : 1; 13018 } 13019 v1 = r1.preferredOrder; 13020 v2 = r2.preferredOrder; 13021 if (v1 != v2) { 13022 return (v1 > v2) ? -1 : 1; 13023 } 13024 if (r1.isDefault != r2.isDefault) { 13025 return r1.isDefault ? -1 : 1; 13026 } 13027 v1 = r1.match; 13028 v2 = r2.match; 13029 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 13030 if (v1 != v2) { 13031 return (v1 > v2) ? -1 : 1; 13032 } 13033 if (r1.system != r2.system) { 13034 return r1.system ? -1 : 1; 13035 } 13036 if (r1.activityInfo != null) { 13037 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 13038 } 13039 if (r1.serviceInfo != null) { 13040 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 13041 } 13042 if (r1.providerInfo != null) { 13043 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 13044 } 13045 return 0; 13046 } 13047 }; 13048 13049 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 13050 new Comparator<ProviderInfo>() { 13051 public int compare(ProviderInfo p1, ProviderInfo p2) { 13052 final int v1 = p1.initOrder; 13053 final int v2 = p2.initOrder; 13054 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13055 } 13056 }; 13057 13058 @Override 13059 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 13060 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 13061 final int[] userIds, int[] instantUserIds) { 13062 mHandler.post(new Runnable() { 13063 @Override 13064 public void run() { 13065 try { 13066 final IActivityManager am = ActivityManager.getService(); 13067 if (am == null) return; 13068 final int[] resolvedUserIds; 13069 if (userIds == null) { 13070 resolvedUserIds = am.getRunningUserIds(); 13071 } else { 13072 resolvedUserIds = userIds; 13073 } 13074 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13075 resolvedUserIds, false); 13076 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 13077 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 13078 instantUserIds, true); 13079 } 13080 } catch (RemoteException ex) { 13081 } 13082 } 13083 }); 13084 } 13085 13086 @Override 13087 public void notifyPackageAdded(String packageName) { 13088 final PackageListObserver[] observers; 13089 synchronized (mPackages) { 13090 if (mPackageListObservers.size() == 0) { 13091 return; 13092 } 13093 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13094 } 13095 for (int i = observers.length - 1; i >= 0; --i) { 13096 observers[i].onPackageAdded(packageName); 13097 } 13098 } 13099 13100 @Override 13101 public void notifyPackageRemoved(String packageName) { 13102 final PackageListObserver[] observers; 13103 synchronized (mPackages) { 13104 if (mPackageListObservers.size() == 0) { 13105 return; 13106 } 13107 observers = (PackageListObserver[]) mPackageListObservers.toArray(); 13108 } 13109 for (int i = observers.length - 1; i >= 0; --i) { 13110 observers[i].onPackageRemoved(packageName); 13111 } 13112 } 13113 13114 /** 13115 * Sends a broadcast for the given action. 13116 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13117 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13118 * the system and applications allowed to see instant applications to receive package 13119 * lifecycle events for instant applications. 13120 */ 13121 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13122 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13123 int[] userIds, boolean isInstantApp) 13124 throws RemoteException { 13125 for (int id : userIds) { 13126 final Intent intent = new Intent(action, 13127 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13128 final String[] requiredPermissions = 13129 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13130 if (extras != null) { 13131 intent.putExtras(extras); 13132 } 13133 if (targetPkg != null) { 13134 intent.setPackage(targetPkg); 13135 } 13136 // Modify the UID when posting to other users 13137 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13138 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13139 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13140 intent.putExtra(Intent.EXTRA_UID, uid); 13141 } 13142 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13143 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13144 if (DEBUG_BROADCASTS) { 13145 RuntimeException here = new RuntimeException("here"); 13146 here.fillInStackTrace(); 13147 Slog.d(TAG, "Sending to user " + id + ": " 13148 + intent.toShortString(false, true, false, false) 13149 + " " + intent.getExtras(), here); 13150 } 13151 am.broadcastIntent(null, intent, null, finishedReceiver, 13152 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13153 null, finishedReceiver != null, false, id); 13154 } 13155 } 13156 13157 /** 13158 * Check if the external storage media is available. This is true if there 13159 * is a mounted external storage medium or if the external storage is 13160 * emulated. 13161 */ 13162 private boolean isExternalMediaAvailable() { 13163 return mMediaMounted || Environment.isExternalStorageEmulated(); 13164 } 13165 13166 @Override 13167 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 13168 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13169 return null; 13170 } 13171 if (!isExternalMediaAvailable()) { 13172 // If the external storage is no longer mounted at this point, 13173 // the caller may not have been able to delete all of this 13174 // packages files and can not delete any more. Bail. 13175 return null; 13176 } 13177 synchronized (mPackages) { 13178 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 13179 if (lastPackage != null) { 13180 pkgs.remove(lastPackage); 13181 } 13182 if (pkgs.size() > 0) { 13183 return pkgs.get(0); 13184 } 13185 } 13186 return null; 13187 } 13188 13189 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 13190 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 13191 userId, andCode ? 1 : 0, packageName); 13192 if (mSystemReady) { 13193 msg.sendToTarget(); 13194 } else { 13195 if (mPostSystemReadyMessages == null) { 13196 mPostSystemReadyMessages = new ArrayList<>(); 13197 } 13198 mPostSystemReadyMessages.add(msg); 13199 } 13200 } 13201 13202 void startCleaningPackages() { 13203 // reader 13204 if (!isExternalMediaAvailable()) { 13205 return; 13206 } 13207 synchronized (mPackages) { 13208 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 13209 return; 13210 } 13211 } 13212 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 13213 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 13214 IActivityManager am = ActivityManager.getService(); 13215 if (am != null) { 13216 int dcsUid = -1; 13217 synchronized (mPackages) { 13218 if (!mDefaultContainerWhitelisted) { 13219 mDefaultContainerWhitelisted = true; 13220 PackageSetting ps = mSettings.mPackages.get(DEFAULT_CONTAINER_PACKAGE); 13221 dcsUid = UserHandle.getUid(UserHandle.USER_SYSTEM, ps.appId); 13222 } 13223 } 13224 try { 13225 if (dcsUid > 0) { 13226 am.backgroundWhitelistUid(dcsUid); 13227 } 13228 am.startService(null, intent, null, false, mContext.getOpPackageName(), 13229 UserHandle.USER_SYSTEM); 13230 } catch (RemoteException e) { 13231 } 13232 } 13233 } 13234 13235 /** 13236 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13237 * it is acting on behalf on an enterprise or the user). 13238 * 13239 * Note that the ordering of the conditionals in this method is important. The checks we perform 13240 * are as follows, in this order: 13241 * 13242 * 1) If the install is being performed by a system app, we can trust the app to have set the 13243 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13244 * what it is. 13245 * 2) If the install is being performed by a device or profile owner app, the install reason 13246 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13247 * set the install reason correctly. If the app targets an older SDK version where install 13248 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13249 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13250 * 3) In all other cases, the install is being performed by a regular app that is neither part 13251 * of the system nor a device or profile owner. We have no reason to believe that this app is 13252 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13253 * set to enterprise policy and if so, change it to unknown instead. 13254 */ 13255 private int fixUpInstallReason(String installerPackageName, int installerUid, 13256 int installReason) { 13257 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13258 == PERMISSION_GRANTED) { 13259 // If the install is being performed by a system app, we trust that app to have set the 13260 // install reason correctly. 13261 return installReason; 13262 } 13263 13264 final IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 13265 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 13266 if (dpm != null) { 13267 ComponentName owner = null; 13268 try { 13269 owner = dpm.getDeviceOwnerComponent(true /* callingUserOnly */); 13270 if (owner == null) { 13271 owner = dpm.getProfileOwner(UserHandle.getUserId(installerUid)); 13272 } 13273 } catch (RemoteException e) { 13274 } 13275 if (owner != null && owner.getPackageName().equals(installerPackageName)) { 13276 // If the install is being performed by a device or profile owner, the install 13277 // reason should be enterprise policy. 13278 return PackageManager.INSTALL_REASON_POLICY; 13279 } 13280 } 13281 13282 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13283 // If the install is being performed by a regular app (i.e. neither system app nor 13284 // device or profile owner), we have no reason to believe that the app is acting on 13285 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13286 // change it to unknown instead. 13287 return PackageManager.INSTALL_REASON_UNKNOWN; 13288 } 13289 13290 // If the install is being performed by a regular app and the install reason was set to any 13291 // value but enterprise policy, leave the install reason unchanged. 13292 return installReason; 13293 } 13294 13295 void installStage(String packageName, File stagedDir, 13296 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 13297 String installerPackageName, int installerUid, UserHandle user, 13298 PackageParser.SigningDetails signingDetails) { 13299 if (DEBUG_EPHEMERAL) { 13300 if ((sessionParams.installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13301 Slog.d(TAG, "Ephemeral install of " + packageName); 13302 } 13303 } 13304 final VerificationInfo verificationInfo = new VerificationInfo( 13305 sessionParams.originatingUri, sessionParams.referrerUri, 13306 sessionParams.originatingUid, installerUid); 13307 13308 final OriginInfo origin = OriginInfo.fromStagedFile(stagedDir); 13309 13310 final Message msg = mHandler.obtainMessage(INIT_COPY); 13311 final int installReason = fixUpInstallReason(installerPackageName, installerUid, 13312 sessionParams.installReason); 13313 final InstallParams params = new InstallParams(origin, null, observer, 13314 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 13315 verificationInfo, user, sessionParams.abiOverride, 13316 sessionParams.grantedRuntimePermissions, signingDetails, installReason); 13317 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13318 msg.obj = params; 13319 13320 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13321 System.identityHashCode(msg.obj)); 13322 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13323 System.identityHashCode(msg.obj)); 13324 13325 mHandler.sendMessage(msg); 13326 } 13327 13328 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13329 int userId) { 13330 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13331 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13332 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13333 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13334 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13335 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13336 13337 // Send a session commit broadcast 13338 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13339 info.installReason = pkgSetting.getInstallReason(userId); 13340 info.appPackageName = packageName; 13341 sendSessionCommitBroadcast(info, userId); 13342 } 13343 13344 @Override 13345 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13346 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13347 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13348 return; 13349 } 13350 Bundle extras = new Bundle(1); 13351 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13352 final int uid = UserHandle.getUid( 13353 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13354 extras.putInt(Intent.EXTRA_UID, uid); 13355 13356 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13357 packageName, extras, 0, null, null, userIds, instantUserIds); 13358 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13359 mHandler.post(() -> { 13360 for (int userId : userIds) { 13361 sendBootCompletedBroadcastToSystemApp( 13362 packageName, includeStopped, userId); 13363 } 13364 } 13365 ); 13366 } 13367 } 13368 13369 /** 13370 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13371 * automatically without needing an explicit launch. 13372 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13373 */ 13374 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13375 int userId) { 13376 // If user is not running, the app didn't miss any broadcast 13377 if (!mUserManagerInternal.isUserRunning(userId)) { 13378 return; 13379 } 13380 final IActivityManager am = ActivityManager.getService(); 13381 try { 13382 // Deliver LOCKED_BOOT_COMPLETED first 13383 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13384 .setPackage(packageName); 13385 if (includeStopped) { 13386 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13387 } 13388 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13389 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13390 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13391 13392 // Deliver BOOT_COMPLETED only if user is unlocked 13393 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13394 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13395 if (includeStopped) { 13396 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13397 } 13398 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13399 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13400 } 13401 } catch (RemoteException e) { 13402 throw e.rethrowFromSystemServer(); 13403 } 13404 } 13405 13406 @Override 13407 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13408 int userId) { 13409 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13410 PackageSetting pkgSetting; 13411 final int callingUid = Binder.getCallingUid(); 13412 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13413 true /* requireFullPermission */, true /* checkShell */, 13414 "setApplicationHiddenSetting for user " + userId); 13415 13416 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13417 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13418 return false; 13419 } 13420 13421 long callingId = Binder.clearCallingIdentity(); 13422 try { 13423 boolean sendAdded = false; 13424 boolean sendRemoved = false; 13425 // writer 13426 synchronized (mPackages) { 13427 pkgSetting = mSettings.mPackages.get(packageName); 13428 if (pkgSetting == null) { 13429 return false; 13430 } 13431 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13432 return false; 13433 } 13434 // Do not allow "android" is being disabled 13435 if ("android".equals(packageName)) { 13436 Slog.w(TAG, "Cannot hide package: android"); 13437 return false; 13438 } 13439 // Cannot hide static shared libs as they are considered 13440 // a part of the using app (emulating static linking). Also 13441 // static libs are installed always on internal storage. 13442 PackageParser.Package pkg = mPackages.get(packageName); 13443 if (pkg != null && pkg.staticSharedLibName != null) { 13444 Slog.w(TAG, "Cannot hide package: " + packageName 13445 + " providing static shared library: " 13446 + pkg.staticSharedLibName); 13447 return false; 13448 } 13449 // Only allow protected packages to hide themselves. 13450 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13451 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13452 Slog.w(TAG, "Not hiding protected package: " + packageName); 13453 return false; 13454 } 13455 13456 if (pkgSetting.getHidden(userId) != hidden) { 13457 pkgSetting.setHidden(hidden, userId); 13458 mSettings.writePackageRestrictionsLPr(userId); 13459 if (hidden) { 13460 sendRemoved = true; 13461 } else { 13462 sendAdded = true; 13463 } 13464 } 13465 } 13466 if (sendAdded) { 13467 sendPackageAddedForUser(packageName, pkgSetting, userId); 13468 return true; 13469 } 13470 if (sendRemoved) { 13471 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13472 "hiding pkg"); 13473 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13474 return true; 13475 } 13476 } finally { 13477 Binder.restoreCallingIdentity(callingId); 13478 } 13479 return false; 13480 } 13481 13482 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13483 int userId) { 13484 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13485 info.removedPackage = packageName; 13486 info.installerPackageName = pkgSetting.installerPackageName; 13487 info.removedUsers = new int[] {userId}; 13488 info.broadcastUsers = new int[] {userId}; 13489 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13490 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13491 } 13492 13493 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 13494 if (pkgList.length > 0) { 13495 Bundle extras = new Bundle(1); 13496 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13497 13498 sendPackageBroadcast( 13499 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13500 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13501 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13502 new int[] {userId}, null); 13503 } 13504 } 13505 13506 /** 13507 * Returns true if application is not found or there was an error. Otherwise it returns 13508 * the hidden state of the package for the given user. 13509 */ 13510 @Override 13511 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13512 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13513 final int callingUid = Binder.getCallingUid(); 13514 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13515 true /* requireFullPermission */, false /* checkShell */, 13516 "getApplicationHidden for user " + userId); 13517 PackageSetting ps; 13518 long callingId = Binder.clearCallingIdentity(); 13519 try { 13520 // writer 13521 synchronized (mPackages) { 13522 ps = mSettings.mPackages.get(packageName); 13523 if (ps == null) { 13524 return true; 13525 } 13526 if (filterAppAccessLPr(ps, callingUid, userId)) { 13527 return true; 13528 } 13529 return ps.getHidden(userId); 13530 } 13531 } finally { 13532 Binder.restoreCallingIdentity(callingId); 13533 } 13534 } 13535 13536 /** 13537 * @hide 13538 */ 13539 @Override 13540 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13541 int installReason) { 13542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 13543 null); 13544 PackageSetting pkgSetting; 13545 final int callingUid = Binder.getCallingUid(); 13546 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13547 true /* requireFullPermission */, true /* checkShell */, 13548 "installExistingPackage for user " + userId); 13549 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13550 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13551 } 13552 13553 long callingId = Binder.clearCallingIdentity(); 13554 try { 13555 boolean installed = false; 13556 final boolean instantApp = 13557 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13558 final boolean fullApp = 13559 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13560 13561 // writer 13562 synchronized (mPackages) { 13563 pkgSetting = mSettings.mPackages.get(packageName); 13564 if (pkgSetting == null) { 13565 return PackageManager.INSTALL_FAILED_INVALID_URI; 13566 } 13567 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13568 // only allow the existing package to be used if it's installed as a full 13569 // application for at least one user 13570 boolean installAllowed = false; 13571 for (int checkUserId : sUserManager.getUserIds()) { 13572 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13573 if (installAllowed) { 13574 break; 13575 } 13576 } 13577 if (!installAllowed) { 13578 return PackageManager.INSTALL_FAILED_INVALID_URI; 13579 } 13580 } 13581 if (!pkgSetting.getInstalled(userId)) { 13582 pkgSetting.setInstalled(true, userId); 13583 pkgSetting.setHidden(false, userId); 13584 pkgSetting.setInstallReason(installReason, userId); 13585 mSettings.writePackageRestrictionsLPr(userId); 13586 mSettings.writeKernelMappingLPr(pkgSetting); 13587 installed = true; 13588 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13589 // upgrade app from instant to full; we don't allow app downgrade 13590 installed = true; 13591 } 13592 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13593 } 13594 13595 if (installed) { 13596 if (pkgSetting.pkg != null) { 13597 synchronized (mInstallLock) { 13598 // We don't need to freeze for a brand new install 13599 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13600 } 13601 } 13602 sendPackageAddedForUser(packageName, pkgSetting, userId); 13603 synchronized (mPackages) { 13604 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13605 } 13606 } 13607 } finally { 13608 Binder.restoreCallingIdentity(callingId); 13609 } 13610 13611 return PackageManager.INSTALL_SUCCEEDED; 13612 } 13613 13614 void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13615 boolean instantApp, boolean fullApp) { 13616 // no state specified; do nothing 13617 if (!instantApp && !fullApp) { 13618 return; 13619 } 13620 if (userId != UserHandle.USER_ALL) { 13621 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13622 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13623 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13624 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13625 } 13626 } else { 13627 for (int currentUserId : sUserManager.getUserIds()) { 13628 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13629 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13630 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13631 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13632 } 13633 } 13634 } 13635 } 13636 13637 boolean isUserRestricted(int userId, String restrictionKey) { 13638 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13639 if (restrictions.getBoolean(restrictionKey, false)) { 13640 Log.w(TAG, "User is restricted: " + restrictionKey); 13641 return true; 13642 } 13643 return false; 13644 } 13645 13646 @Override 13647 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13648 int userId) { 13649 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13650 final int callingUid = Binder.getCallingUid(); 13651 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13652 true /* requireFullPermission */, true /* checkShell */, 13653 "setPackagesSuspended for user " + userId); 13654 13655 if (ArrayUtils.isEmpty(packageNames)) { 13656 return packageNames; 13657 } 13658 13659 // List of package names for whom the suspended state has changed. 13660 List<String> changedPackages = new ArrayList<>(packageNames.length); 13661 // List of package names for whom the suspended state is not set as requested in this 13662 // method. 13663 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13664 long callingId = Binder.clearCallingIdentity(); 13665 try { 13666 for (int i = 0; i < packageNames.length; i++) { 13667 String packageName = packageNames[i]; 13668 boolean changed = false; 13669 final int appId; 13670 synchronized (mPackages) { 13671 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13672 if (pkgSetting == null 13673 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13674 Slog.w(TAG, "Could not find package setting for package \"" + packageName 13675 + "\". Skipping suspending/un-suspending."); 13676 unactionedPackages.add(packageName); 13677 continue; 13678 } 13679 appId = pkgSetting.appId; 13680 if (pkgSetting.getSuspended(userId) != suspended) { 13681 if (!canSuspendPackageForUserLocked(packageName, userId)) { 13682 unactionedPackages.add(packageName); 13683 continue; 13684 } 13685 pkgSetting.setSuspended(suspended, userId); 13686 mSettings.writePackageRestrictionsLPr(userId); 13687 changed = true; 13688 changedPackages.add(packageName); 13689 } 13690 } 13691 13692 if (changed && suspended) { 13693 killApplication(packageName, UserHandle.getUid(userId, appId), 13694 "suspending package"); 13695 } 13696 } 13697 } finally { 13698 Binder.restoreCallingIdentity(callingId); 13699 } 13700 13701 if (!changedPackages.isEmpty()) { 13702 sendPackagesSuspendedForUser(changedPackages.toArray( 13703 new String[changedPackages.size()]), userId, suspended); 13704 } 13705 13706 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13707 } 13708 13709 @Override 13710 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13711 final int callingUid = Binder.getCallingUid(); 13712 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13713 true /* requireFullPermission */, false /* checkShell */, 13714 "isPackageSuspendedForUser for user " + userId); 13715 synchronized (mPackages) { 13716 final PackageSetting ps = mSettings.mPackages.get(packageName); 13717 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13718 throw new IllegalArgumentException("Unknown target package: " + packageName); 13719 } 13720 return ps.getSuspended(userId); 13721 } 13722 } 13723 13724 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 13725 if (isPackageDeviceAdmin(packageName, userId)) { 13726 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13727 + "\": has an active device admin"); 13728 return false; 13729 } 13730 13731 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13732 if (packageName.equals(activeLauncherPackageName)) { 13733 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13734 + "\": contains the active launcher"); 13735 return false; 13736 } 13737 13738 if (packageName.equals(mRequiredInstallerPackage)) { 13739 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13740 + "\": required for package installation"); 13741 return false; 13742 } 13743 13744 if (packageName.equals(mRequiredUninstallerPackage)) { 13745 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13746 + "\": required for package uninstallation"); 13747 return false; 13748 } 13749 13750 if (packageName.equals(mRequiredVerifierPackage)) { 13751 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13752 + "\": required for package verification"); 13753 return false; 13754 } 13755 13756 if (packageName.equals(getDefaultDialerPackageName(userId))) { 13757 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13758 + "\": is the default dialer"); 13759 return false; 13760 } 13761 13762 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13763 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 13764 + "\": protected package"); 13765 return false; 13766 } 13767 13768 // Cannot suspend static shared libs as they are considered 13769 // a part of the using app (emulating static linking). Also 13770 // static libs are installed always on internal storage. 13771 PackageParser.Package pkg = mPackages.get(packageName); 13772 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13773 Slog.w(TAG, "Cannot suspend package: " + packageName 13774 + " providing static shared library: " 13775 + pkg.staticSharedLibName); 13776 return false; 13777 } 13778 13779 return true; 13780 } 13781 13782 private String getActiveLauncherPackageName(int userId) { 13783 Intent intent = new Intent(Intent.ACTION_MAIN); 13784 intent.addCategory(Intent.CATEGORY_HOME); 13785 ResolveInfo resolveInfo = resolveIntent( 13786 intent, 13787 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13788 PackageManager.MATCH_DEFAULT_ONLY, 13789 userId); 13790 13791 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13792 } 13793 13794 private String getDefaultDialerPackageName(int userId) { 13795 synchronized (mPackages) { 13796 return mSettings.getDefaultDialerPackageNameLPw(userId); 13797 } 13798 } 13799 13800 @Override 13801 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13802 mContext.enforceCallingOrSelfPermission( 13803 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13804 "Only package verification agents can verify applications"); 13805 13806 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13807 final PackageVerificationResponse response = new PackageVerificationResponse( 13808 verificationCode, Binder.getCallingUid()); 13809 msg.arg1 = id; 13810 msg.obj = response; 13811 mHandler.sendMessage(msg); 13812 } 13813 13814 @Override 13815 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13816 long millisecondsToDelay) { 13817 mContext.enforceCallingOrSelfPermission( 13818 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13819 "Only package verification agents can extend verification timeouts"); 13820 13821 final PackageVerificationState state = mPendingVerification.get(id); 13822 final PackageVerificationResponse response = new PackageVerificationResponse( 13823 verificationCodeAtTimeout, Binder.getCallingUid()); 13824 13825 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13826 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13827 } 13828 if (millisecondsToDelay < 0) { 13829 millisecondsToDelay = 0; 13830 } 13831 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13832 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13833 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13834 } 13835 13836 if ((state != null) && !state.timeoutExtended()) { 13837 state.extendTimeout(); 13838 13839 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13840 msg.arg1 = id; 13841 msg.obj = response; 13842 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13843 } 13844 } 13845 13846 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13847 int verificationCode, UserHandle user) { 13848 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13849 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13850 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13851 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13852 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13853 13854 mContext.sendBroadcastAsUser(intent, user, 13855 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13856 } 13857 13858 private ComponentName matchComponentForVerifier(String packageName, 13859 List<ResolveInfo> receivers) { 13860 ActivityInfo targetReceiver = null; 13861 13862 final int NR = receivers.size(); 13863 for (int i = 0; i < NR; i++) { 13864 final ResolveInfo info = receivers.get(i); 13865 if (info.activityInfo == null) { 13866 continue; 13867 } 13868 13869 if (packageName.equals(info.activityInfo.packageName)) { 13870 targetReceiver = info.activityInfo; 13871 break; 13872 } 13873 } 13874 13875 if (targetReceiver == null) { 13876 return null; 13877 } 13878 13879 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13880 } 13881 13882 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13883 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13884 if (pkgInfo.verifiers.length == 0) { 13885 return null; 13886 } 13887 13888 final int N = pkgInfo.verifiers.length; 13889 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 13890 for (int i = 0; i < N; i++) { 13891 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13892 13893 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13894 receivers); 13895 if (comp == null) { 13896 continue; 13897 } 13898 13899 final int verifierUid = getUidForVerifier(verifierInfo); 13900 if (verifierUid == -1) { 13901 continue; 13902 } 13903 13904 if (DEBUG_VERIFY) { 13905 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13906 + " with the correct signature"); 13907 } 13908 sufficientVerifiers.add(comp); 13909 verificationState.addSufficientVerifier(verifierUid); 13910 } 13911 13912 return sufficientVerifiers; 13913 } 13914 13915 private int getUidForVerifier(VerifierInfo verifierInfo) { 13916 synchronized (mPackages) { 13917 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13918 if (pkg == null) { 13919 return -1; 13920 } else if (pkg.mSigningDetails.signatures.length != 1) { 13921 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13922 + " has more than one signature; ignoring"); 13923 return -1; 13924 } 13925 13926 /* 13927 * If the public key of the package's signature does not match 13928 * our expected public key, then this is a different package and 13929 * we should skip. 13930 */ 13931 13932 final byte[] expectedPublicKey; 13933 try { 13934 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 13935 final PublicKey publicKey = verifierSig.getPublicKey(); 13936 expectedPublicKey = publicKey.getEncoded(); 13937 } catch (CertificateException e) { 13938 return -1; 13939 } 13940 13941 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13942 13943 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13944 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13945 + " does not have the expected public key; ignoring"); 13946 return -1; 13947 } 13948 13949 return pkg.applicationInfo.uid; 13950 } 13951 } 13952 13953 @Override 13954 public void finishPackageInstall(int token, boolean didLaunch) { 13955 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13956 13957 if (DEBUG_INSTALL) { 13958 Slog.v(TAG, "BM finishing package install for " + token); 13959 } 13960 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13961 13962 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13963 mHandler.sendMessage(msg); 13964 } 13965 13966 /** 13967 * Get the verification agent timeout. Used for both the APK verifier and the 13968 * intent filter verifier. 13969 * 13970 * @return verification timeout in milliseconds 13971 */ 13972 private long getVerificationTimeout() { 13973 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13974 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13975 DEFAULT_VERIFICATION_TIMEOUT); 13976 } 13977 13978 /** 13979 * Get the default verification agent response code. 13980 * 13981 * @return default verification response code 13982 */ 13983 private int getDefaultVerificationResponse(UserHandle user) { 13984 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13985 return PackageManager.VERIFICATION_REJECT; 13986 } 13987 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13988 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13989 DEFAULT_VERIFICATION_RESPONSE); 13990 } 13991 13992 /** 13993 * Check whether or not package verification has been enabled. 13994 * 13995 * @return true if verification should be performed 13996 */ 13997 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13998 if (!DEFAULT_VERIFY_ENABLE) { 13999 return false; 14000 } 14001 14002 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14003 14004 // Check if installing from ADB 14005 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14006 // Do not run verification in a test harness environment 14007 if (ActivityManager.isRunningInTestHarness()) { 14008 return false; 14009 } 14010 if (ensureVerifyAppsEnabled) { 14011 return true; 14012 } 14013 // Check if the developer does not want package verification for ADB installs 14014 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14015 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14016 return false; 14017 } 14018 } else { 14019 // only when not installed from ADB, skip verification for instant apps when 14020 // the installer and verifier are the same. 14021 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14022 if (mInstantAppInstallerActivity != null 14023 && mInstantAppInstallerActivity.packageName.equals( 14024 mRequiredVerifierPackage)) { 14025 try { 14026 mContext.getSystemService(AppOpsManager.class) 14027 .checkPackage(installerUid, mRequiredVerifierPackage); 14028 if (DEBUG_VERIFY) { 14029 Slog.i(TAG, "disable verification for instant app"); 14030 } 14031 return false; 14032 } catch (SecurityException ignore) { } 14033 } 14034 } 14035 } 14036 14037 if (ensureVerifyAppsEnabled) { 14038 return true; 14039 } 14040 14041 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14042 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14043 } 14044 14045 @Override 14046 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14047 throws RemoteException { 14048 mContext.enforceCallingOrSelfPermission( 14049 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14050 "Only intentfilter verification agents can verify applications"); 14051 14052 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14053 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14054 Binder.getCallingUid(), verificationCode, failedDomains); 14055 msg.arg1 = id; 14056 msg.obj = response; 14057 mHandler.sendMessage(msg); 14058 } 14059 14060 @Override 14061 public int getIntentVerificationStatus(String packageName, int userId) { 14062 final int callingUid = Binder.getCallingUid(); 14063 if (UserHandle.getUserId(callingUid) != userId) { 14064 mContext.enforceCallingOrSelfPermission( 14065 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14066 "getIntentVerificationStatus" + userId); 14067 } 14068 if (getInstantAppPackageName(callingUid) != null) { 14069 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14070 } 14071 synchronized (mPackages) { 14072 final PackageSetting ps = mSettings.mPackages.get(packageName); 14073 if (ps == null 14074 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14075 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14076 } 14077 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14078 } 14079 } 14080 14081 @Override 14082 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14083 mContext.enforceCallingOrSelfPermission( 14084 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14085 14086 boolean result = false; 14087 synchronized (mPackages) { 14088 final PackageSetting ps = mSettings.mPackages.get(packageName); 14089 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14090 return false; 14091 } 14092 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14093 } 14094 if (result) { 14095 scheduleWritePackageRestrictionsLocked(userId); 14096 } 14097 return result; 14098 } 14099 14100 @Override 14101 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14102 String packageName) { 14103 final int callingUid = Binder.getCallingUid(); 14104 if (getInstantAppPackageName(callingUid) != null) { 14105 return ParceledListSlice.emptyList(); 14106 } 14107 synchronized (mPackages) { 14108 final PackageSetting ps = mSettings.mPackages.get(packageName); 14109 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14110 return ParceledListSlice.emptyList(); 14111 } 14112 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14113 } 14114 } 14115 14116 @Override 14117 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14118 if (TextUtils.isEmpty(packageName)) { 14119 return ParceledListSlice.emptyList(); 14120 } 14121 final int callingUid = Binder.getCallingUid(); 14122 final int callingUserId = UserHandle.getUserId(callingUid); 14123 synchronized (mPackages) { 14124 PackageParser.Package pkg = mPackages.get(packageName); 14125 if (pkg == null || pkg.activities == null) { 14126 return ParceledListSlice.emptyList(); 14127 } 14128 if (pkg.mExtras == null) { 14129 return ParceledListSlice.emptyList(); 14130 } 14131 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14132 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14133 return ParceledListSlice.emptyList(); 14134 } 14135 final int count = pkg.activities.size(); 14136 ArrayList<IntentFilter> result = new ArrayList<>(); 14137 for (int n=0; n<count; n++) { 14138 PackageParser.Activity activity = pkg.activities.get(n); 14139 if (activity.intents != null && activity.intents.size() > 0) { 14140 result.addAll(activity.intents); 14141 } 14142 } 14143 return new ParceledListSlice<>(result); 14144 } 14145 } 14146 14147 @Override 14148 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14149 mContext.enforceCallingOrSelfPermission( 14150 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14151 if (UserHandle.getCallingUserId() != userId) { 14152 mContext.enforceCallingOrSelfPermission( 14153 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14154 } 14155 14156 synchronized (mPackages) { 14157 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 14158 if (packageName != null) { 14159 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser( 14160 packageName, userId); 14161 } 14162 return result; 14163 } 14164 } 14165 14166 @Override 14167 public String getDefaultBrowserPackageName(int userId) { 14168 if (UserHandle.getCallingUserId() != userId) { 14169 mContext.enforceCallingOrSelfPermission( 14170 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14171 } 14172 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14173 return null; 14174 } 14175 synchronized (mPackages) { 14176 return mSettings.getDefaultBrowserPackageNameLPw(userId); 14177 } 14178 } 14179 14180 /** 14181 * Get the "allow unknown sources" setting. 14182 * 14183 * @return the current "allow unknown sources" setting 14184 */ 14185 private int getUnknownSourcesSettings() { 14186 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14187 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14188 -1); 14189 } 14190 14191 @Override 14192 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14193 final int callingUid = Binder.getCallingUid(); 14194 if (getInstantAppPackageName(callingUid) != null) { 14195 return; 14196 } 14197 // writer 14198 synchronized (mPackages) { 14199 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14200 if (targetPackageSetting == null 14201 || filterAppAccessLPr( 14202 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14203 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14204 } 14205 14206 PackageSetting installerPackageSetting; 14207 if (installerPackageName != null) { 14208 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14209 if (installerPackageSetting == null) { 14210 throw new IllegalArgumentException("Unknown installer package: " 14211 + installerPackageName); 14212 } 14213 } else { 14214 installerPackageSetting = null; 14215 } 14216 14217 Signature[] callerSignature; 14218 Object obj = mSettings.getUserIdLPr(callingUid); 14219 if (obj != null) { 14220 if (obj instanceof SharedUserSetting) { 14221 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 14222 } else if (obj instanceof PackageSetting) { 14223 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 14224 } else { 14225 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14226 } 14227 } else { 14228 throw new SecurityException("Unknown calling UID: " + callingUid); 14229 } 14230 14231 // Verify: can't set installerPackageName to a package that is 14232 // not signed with the same cert as the caller. 14233 if (installerPackageSetting != null) { 14234 if (compareSignatures(callerSignature, 14235 installerPackageSetting.signatures.mSignatures) 14236 != PackageManager.SIGNATURE_MATCH) { 14237 throw new SecurityException( 14238 "Caller does not have same cert as new installer package " 14239 + installerPackageName); 14240 } 14241 } 14242 14243 // Verify: if target already has an installer package, it must 14244 // be signed with the same cert as the caller. 14245 if (targetPackageSetting.installerPackageName != null) { 14246 PackageSetting setting = mSettings.mPackages.get( 14247 targetPackageSetting.installerPackageName); 14248 // If the currently set package isn't valid, then it's always 14249 // okay to change it. 14250 if (setting != null) { 14251 if (compareSignatures(callerSignature, 14252 setting.signatures.mSignatures) 14253 != PackageManager.SIGNATURE_MATCH) { 14254 throw new SecurityException( 14255 "Caller does not have same cert as old installer package " 14256 + targetPackageSetting.installerPackageName); 14257 } 14258 } 14259 } 14260 14261 // Okay! 14262 targetPackageSetting.installerPackageName = installerPackageName; 14263 if (installerPackageName != null) { 14264 mSettings.mInstallerPackages.add(installerPackageName); 14265 } 14266 scheduleWriteSettingsLocked(); 14267 } 14268 } 14269 14270 @Override 14271 public void setApplicationCategoryHint(String packageName, int categoryHint, 14272 String callerPackageName) { 14273 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14274 throw new SecurityException("Instant applications don't have access to this method"); 14275 } 14276 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14277 callerPackageName); 14278 synchronized (mPackages) { 14279 PackageSetting ps = mSettings.mPackages.get(packageName); 14280 if (ps == null) { 14281 throw new IllegalArgumentException("Unknown target package " + packageName); 14282 } 14283 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14284 throw new IllegalArgumentException("Unknown target package " + packageName); 14285 } 14286 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14287 throw new IllegalArgumentException("Calling package " + callerPackageName 14288 + " is not installer for " + packageName); 14289 } 14290 14291 if (ps.categoryHint != categoryHint) { 14292 ps.categoryHint = categoryHint; 14293 scheduleWriteSettingsLocked(); 14294 } 14295 } 14296 } 14297 14298 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14299 // Queue up an async operation since the package installation may take a little while. 14300 mHandler.post(new Runnable() { 14301 public void run() { 14302 mHandler.removeCallbacks(this); 14303 // Result object to be returned 14304 PackageInstalledInfo res = new PackageInstalledInfo(); 14305 res.setReturnCode(currentStatus); 14306 res.uid = -1; 14307 res.pkg = null; 14308 res.removedInfo = null; 14309 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14310 args.doPreInstall(res.returnCode); 14311 synchronized (mInstallLock) { 14312 installPackageTracedLI(args, res); 14313 } 14314 args.doPostInstall(res.returnCode, res.uid); 14315 } 14316 14317 // A restore should be performed at this point if (a) the install 14318 // succeeded, (b) the operation is not an update, and (c) the new 14319 // package has not opted out of backup participation. 14320 final boolean update = res.removedInfo != null 14321 && res.removedInfo.removedPackage != null; 14322 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14323 boolean doRestore = !update 14324 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14325 14326 // Set up the post-install work request bookkeeping. This will be used 14327 // and cleaned up by the post-install event handling regardless of whether 14328 // there's a restore pass performed. Token values are >= 1. 14329 int token; 14330 if (mNextInstallToken < 0) mNextInstallToken = 1; 14331 token = mNextInstallToken++; 14332 14333 PostInstallData data = new PostInstallData(args, res); 14334 mRunningInstalls.put(token, data); 14335 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14336 14337 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14338 // Pass responsibility to the Backup Manager. It will perform a 14339 // restore if appropriate, then pass responsibility back to the 14340 // Package Manager to run the post-install observer callbacks 14341 // and broadcasts. 14342 IBackupManager bm = IBackupManager.Stub.asInterface( 14343 ServiceManager.getService(Context.BACKUP_SERVICE)); 14344 if (bm != null) { 14345 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 14346 + " to BM for possible restore"); 14347 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14348 try { 14349 // TODO: http://b/22388012 14350 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 14351 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 14352 } else { 14353 doRestore = false; 14354 } 14355 } catch (RemoteException e) { 14356 // can't happen; the backup manager is local 14357 } catch (Exception e) { 14358 Slog.e(TAG, "Exception trying to enqueue restore", e); 14359 doRestore = false; 14360 } 14361 } else { 14362 Slog.e(TAG, "Backup Manager not found!"); 14363 doRestore = false; 14364 } 14365 } 14366 14367 if (!doRestore) { 14368 // No restore possible, or the Backup Manager was mysteriously not 14369 // available -- just fire the post-install work request directly. 14370 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14371 14372 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14373 14374 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14375 mHandler.sendMessage(msg); 14376 } 14377 } 14378 }); 14379 } 14380 14381 /** 14382 * Callback from PackageSettings whenever an app is first transitioned out of the 14383 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14384 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14385 * here whether the app is the target of an ongoing install, and only send the 14386 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14387 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14388 * handling. 14389 */ 14390 void notifyFirstLaunch(final String packageName, final String installerPackage, 14391 final int userId) { 14392 // Serialize this with the rest of the install-process message chain. In the 14393 // restore-at-install case, this Runnable will necessarily run before the 14394 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14395 // are coherent. In the non-restore case, the app has already completed install 14396 // and been launched through some other means, so it is not in a problematic 14397 // state for observers to see the FIRST_LAUNCH signal. 14398 mHandler.post(new Runnable() { 14399 @Override 14400 public void run() { 14401 for (int i = 0; i < mRunningInstalls.size(); i++) { 14402 final PostInstallData data = mRunningInstalls.valueAt(i); 14403 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14404 continue; 14405 } 14406 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14407 // right package; but is it for the right user? 14408 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14409 if (userId == data.res.newUsers[uIndex]) { 14410 if (DEBUG_BACKUP) { 14411 Slog.i(TAG, "Package " + packageName 14412 + " being restored so deferring FIRST_LAUNCH"); 14413 } 14414 return; 14415 } 14416 } 14417 } 14418 } 14419 // didn't find it, so not being restored 14420 if (DEBUG_BACKUP) { 14421 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14422 } 14423 final boolean isInstantApp = isInstantApp(packageName, userId); 14424 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14425 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14426 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14427 } 14428 }); 14429 } 14430 14431 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14432 int[] userIds, int[] instantUserIds) { 14433 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14434 installerPkg, null, userIds, instantUserIds); 14435 } 14436 14437 private abstract class HandlerParams { 14438 private static final int MAX_RETRIES = 4; 14439 14440 /** 14441 * Number of times startCopy() has been attempted and had a non-fatal 14442 * error. 14443 */ 14444 private int mRetries = 0; 14445 14446 /** User handle for the user requesting the information or installation. */ 14447 private final UserHandle mUser; 14448 String traceMethod; 14449 int traceCookie; 14450 14451 HandlerParams(UserHandle user) { 14452 mUser = user; 14453 } 14454 14455 UserHandle getUser() { 14456 return mUser; 14457 } 14458 14459 HandlerParams setTraceMethod(String traceMethod) { 14460 this.traceMethod = traceMethod; 14461 return this; 14462 } 14463 14464 HandlerParams setTraceCookie(int traceCookie) { 14465 this.traceCookie = traceCookie; 14466 return this; 14467 } 14468 14469 final boolean startCopy() { 14470 boolean res; 14471 try { 14472 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14473 14474 if (++mRetries > MAX_RETRIES) { 14475 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 14476 mHandler.sendEmptyMessage(MCS_GIVE_UP); 14477 handleServiceError(); 14478 return false; 14479 } else { 14480 handleStartCopy(); 14481 res = true; 14482 } 14483 } catch (RemoteException e) { 14484 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 14485 mHandler.sendEmptyMessage(MCS_RECONNECT); 14486 res = false; 14487 } 14488 handleReturnCode(); 14489 return res; 14490 } 14491 14492 final void serviceError() { 14493 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 14494 handleServiceError(); 14495 handleReturnCode(); 14496 } 14497 14498 abstract void handleStartCopy() throws RemoteException; 14499 abstract void handleServiceError(); 14500 abstract void handleReturnCode(); 14501 } 14502 14503 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 14504 for (File path : paths) { 14505 try { 14506 mcs.clearDirectory(path.getAbsolutePath()); 14507 } catch (RemoteException e) { 14508 } 14509 } 14510 } 14511 14512 static class OriginInfo { 14513 /** 14514 * Location where install is coming from, before it has been 14515 * copied/renamed into place. This could be a single monolithic APK 14516 * file, or a cluster directory. This location may be untrusted. 14517 */ 14518 final File file; 14519 14520 /** 14521 * Flag indicating that {@link #file} or {@link #cid} has already been 14522 * staged, meaning downstream users don't need to defensively copy the 14523 * contents. 14524 */ 14525 final boolean staged; 14526 14527 /** 14528 * Flag indicating that {@link #file} or {@link #cid} is an already 14529 * installed app that is being moved. 14530 */ 14531 final boolean existing; 14532 14533 final String resolvedPath; 14534 final File resolvedFile; 14535 14536 static OriginInfo fromNothing() { 14537 return new OriginInfo(null, false, false); 14538 } 14539 14540 static OriginInfo fromUntrustedFile(File file) { 14541 return new OriginInfo(file, false, false); 14542 } 14543 14544 static OriginInfo fromExistingFile(File file) { 14545 return new OriginInfo(file, false, true); 14546 } 14547 14548 static OriginInfo fromStagedFile(File file) { 14549 return new OriginInfo(file, true, false); 14550 } 14551 14552 private OriginInfo(File file, boolean staged, boolean existing) { 14553 this.file = file; 14554 this.staged = staged; 14555 this.existing = existing; 14556 14557 if (file != null) { 14558 resolvedPath = file.getAbsolutePath(); 14559 resolvedFile = file; 14560 } else { 14561 resolvedPath = null; 14562 resolvedFile = null; 14563 } 14564 } 14565 } 14566 14567 static class MoveInfo { 14568 final int moveId; 14569 final String fromUuid; 14570 final String toUuid; 14571 final String packageName; 14572 final String dataAppName; 14573 final int appId; 14574 final String seinfo; 14575 final int targetSdkVersion; 14576 14577 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14578 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14579 this.moveId = moveId; 14580 this.fromUuid = fromUuid; 14581 this.toUuid = toUuid; 14582 this.packageName = packageName; 14583 this.dataAppName = dataAppName; 14584 this.appId = appId; 14585 this.seinfo = seinfo; 14586 this.targetSdkVersion = targetSdkVersion; 14587 } 14588 } 14589 14590 static class VerificationInfo { 14591 /** A constant used to indicate that a uid value is not present. */ 14592 public static final int NO_UID = -1; 14593 14594 /** URI referencing where the package was downloaded from. */ 14595 final Uri originatingUri; 14596 14597 /** HTTP referrer URI associated with the originatingURI. */ 14598 final Uri referrer; 14599 14600 /** UID of the application that the install request originated from. */ 14601 final int originatingUid; 14602 14603 /** UID of application requesting the install */ 14604 final int installerUid; 14605 14606 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14607 this.originatingUri = originatingUri; 14608 this.referrer = referrer; 14609 this.originatingUid = originatingUid; 14610 this.installerUid = installerUid; 14611 } 14612 } 14613 14614 class InstallParams extends HandlerParams { 14615 final OriginInfo origin; 14616 final MoveInfo move; 14617 final IPackageInstallObserver2 observer; 14618 int installFlags; 14619 final String installerPackageName; 14620 final String volumeUuid; 14621 private InstallArgs mArgs; 14622 private int mRet; 14623 final String packageAbiOverride; 14624 final String[] grantedRuntimePermissions; 14625 final VerificationInfo verificationInfo; 14626 final PackageParser.SigningDetails signingDetails; 14627 final int installReason; 14628 14629 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14630 int installFlags, String installerPackageName, String volumeUuid, 14631 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14632 String[] grantedPermissions, PackageParser.SigningDetails signingDetails, int installReason) { 14633 super(user); 14634 this.origin = origin; 14635 this.move = move; 14636 this.observer = observer; 14637 this.installFlags = installFlags; 14638 this.installerPackageName = installerPackageName; 14639 this.volumeUuid = volumeUuid; 14640 this.verificationInfo = verificationInfo; 14641 this.packageAbiOverride = packageAbiOverride; 14642 this.grantedRuntimePermissions = grantedPermissions; 14643 this.signingDetails = signingDetails; 14644 this.installReason = installReason; 14645 } 14646 14647 @Override 14648 public String toString() { 14649 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14650 + " file=" + origin.file + "}"; 14651 } 14652 14653 private int installLocationPolicy(PackageInfoLite pkgLite) { 14654 String packageName = pkgLite.packageName; 14655 int installLocation = pkgLite.installLocation; 14656 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14657 // reader 14658 synchronized (mPackages) { 14659 // Currently installed package which the new package is attempting to replace or 14660 // null if no such package is installed. 14661 PackageParser.Package installedPkg = mPackages.get(packageName); 14662 // Package which currently owns the data which the new package will own if installed. 14663 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14664 // will be null whereas dataOwnerPkg will contain information about the package 14665 // which was uninstalled while keeping its data. 14666 PackageParser.Package dataOwnerPkg = installedPkg; 14667 if (dataOwnerPkg == null) { 14668 PackageSetting ps = mSettings.mPackages.get(packageName); 14669 if (ps != null) { 14670 dataOwnerPkg = ps.pkg; 14671 } 14672 } 14673 14674 if (dataOwnerPkg != null) { 14675 // If installed, the package will get access to data left on the device by its 14676 // predecessor. As a security measure, this is permited only if this is not a 14677 // version downgrade or if the predecessor package is marked as debuggable and 14678 // a downgrade is explicitly requested. 14679 // 14680 // On debuggable platform builds, downgrades are permitted even for 14681 // non-debuggable packages to make testing easier. Debuggable platform builds do 14682 // not offer security guarantees and thus it's OK to disable some security 14683 // mechanisms to make debugging/testing easier on those builds. However, even on 14684 // debuggable builds downgrades of packages are permitted only if requested via 14685 // installFlags. This is because we aim to keep the behavior of debuggable 14686 // platform builds as close as possible to the behavior of non-debuggable 14687 // platform builds. 14688 final boolean downgradeRequested = 14689 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 14690 final boolean packageDebuggable = 14691 (dataOwnerPkg.applicationInfo.flags 14692 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 14693 final boolean downgradePermitted = 14694 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 14695 if (!downgradePermitted) { 14696 try { 14697 checkDowngrade(dataOwnerPkg, pkgLite); 14698 } catch (PackageManagerException e) { 14699 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14700 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14701 } 14702 } 14703 } 14704 14705 if (installedPkg != null) { 14706 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14707 // Check for updated system application. 14708 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14709 if (onSd) { 14710 Slog.w(TAG, "Cannot install update to system app on sdcard"); 14711 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 14712 } 14713 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14714 } else { 14715 if (onSd) { 14716 // Install flag overrides everything. 14717 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14718 } 14719 // If current upgrade specifies particular preference 14720 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14721 // Application explicitly specified internal. 14722 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14723 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14724 // App explictly prefers external. Let policy decide 14725 } else { 14726 // Prefer previous location 14727 if (isExternal(installedPkg)) { 14728 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14729 } 14730 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14731 } 14732 } 14733 } else { 14734 // Invalid install. Return error code 14735 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14736 } 14737 } 14738 } 14739 // All the special cases have been taken care of. 14740 // Return result based on recommended install location. 14741 if (onSd) { 14742 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14743 } 14744 return pkgLite.recommendedInstallLocation; 14745 } 14746 14747 /* 14748 * Invoke remote method to get package information and install 14749 * location values. Override install location based on default 14750 * policy if needed and then create install arguments based 14751 * on the install location. 14752 */ 14753 public void handleStartCopy() throws RemoteException { 14754 int ret = PackageManager.INSTALL_SUCCEEDED; 14755 14756 // If we're already staged, we've firmly committed to an install location 14757 if (origin.staged) { 14758 if (origin.file != null) { 14759 installFlags |= PackageManager.INSTALL_INTERNAL; 14760 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14761 } else { 14762 throw new IllegalStateException("Invalid stage location"); 14763 } 14764 } 14765 14766 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 14767 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14768 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14769 PackageInfoLite pkgLite = null; 14770 14771 if (onInt && onSd) { 14772 // Check if both bits are set. 14773 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 14774 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14775 } else if (onSd && ephemeral) { 14776 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 14777 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14778 } else { 14779 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 14780 packageAbiOverride); 14781 14782 if (DEBUG_EPHEMERAL && ephemeral) { 14783 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14784 } 14785 14786 /* 14787 * If we have too little free space, try to free cache 14788 * before giving up. 14789 */ 14790 if (!origin.staged && pkgLite.recommendedInstallLocation 14791 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14792 // TODO: focus freeing disk space on the target device 14793 final StorageManager storage = StorageManager.from(mContext); 14794 final long lowThreshold = storage.getStorageLowBytes( 14795 Environment.getDataDirectory()); 14796 14797 final long sizeBytes = mContainerService.calculateInstalledSize( 14798 origin.resolvedPath, packageAbiOverride); 14799 14800 try { 14801 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14802 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 14803 installFlags, packageAbiOverride); 14804 } catch (InstallerException e) { 14805 Slog.w(TAG, "Failed to free cache", e); 14806 } 14807 14808 /* 14809 * The cache free must have deleted the file we 14810 * downloaded to install. 14811 * 14812 * TODO: fix the "freeCache" call to not delete 14813 * the file we care about. 14814 */ 14815 if (pkgLite.recommendedInstallLocation 14816 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14817 pkgLite.recommendedInstallLocation 14818 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14819 } 14820 } 14821 } 14822 14823 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14824 int loc = pkgLite.recommendedInstallLocation; 14825 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14826 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14827 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14828 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14829 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14830 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14831 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14832 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14833 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14834 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14835 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14836 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14837 } else { 14838 // Override with defaults if needed. 14839 loc = installLocationPolicy(pkgLite); 14840 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14841 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14842 } else if (!onSd && !onInt) { 14843 // Override install location with flags 14844 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14845 // Set the flag to install on external media. 14846 installFlags |= PackageManager.INSTALL_EXTERNAL; 14847 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14848 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14849 if (DEBUG_EPHEMERAL) { 14850 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14851 } 14852 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14853 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 14854 |PackageManager.INSTALL_INTERNAL); 14855 } else { 14856 // Make sure the flag for installing on external 14857 // media is unset 14858 installFlags |= PackageManager.INSTALL_INTERNAL; 14859 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 14860 } 14861 } 14862 } 14863 } 14864 14865 final InstallArgs args = createInstallArgs(this); 14866 mArgs = args; 14867 14868 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14869 // TODO: http://b/22976637 14870 // Apps installed for "all" users use the device owner to verify the app 14871 UserHandle verifierUser = getUser(); 14872 if (verifierUser == UserHandle.ALL) { 14873 verifierUser = UserHandle.SYSTEM; 14874 } 14875 14876 /* 14877 * Determine if we have any installed package verifiers. If we 14878 * do, then we'll defer to them to verify the packages. 14879 */ 14880 final int requiredUid = mRequiredVerifierPackage == null ? -1 14881 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14882 verifierUser.getIdentifier()); 14883 final int installerUid = 14884 verificationInfo == null ? -1 : verificationInfo.installerUid; 14885 if (!origin.existing && requiredUid != -1 14886 && isVerificationEnabled( 14887 verifierUser.getIdentifier(), installFlags, installerUid)) { 14888 final Intent verification = new Intent( 14889 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14890 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14891 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14892 PACKAGE_MIME_TYPE); 14893 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14894 14895 // Query all live verifiers based on current user state 14896 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14897 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14898 false /*allowDynamicSplits*/); 14899 14900 if (DEBUG_VERIFY) { 14901 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14902 + verification.toString() + " with " + pkgLite.verifiers.length 14903 + " optional verifiers"); 14904 } 14905 14906 final int verificationId = mPendingVerificationToken++; 14907 14908 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14909 14910 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14911 installerPackageName); 14912 14913 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14914 installFlags); 14915 14916 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14917 pkgLite.packageName); 14918 14919 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14920 pkgLite.versionCode); 14921 14922 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 14923 pkgLite.getLongVersionCode()); 14924 14925 if (verificationInfo != null) { 14926 if (verificationInfo.originatingUri != null) { 14927 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14928 verificationInfo.originatingUri); 14929 } 14930 if (verificationInfo.referrer != null) { 14931 verification.putExtra(Intent.EXTRA_REFERRER, 14932 verificationInfo.referrer); 14933 } 14934 if (verificationInfo.originatingUid >= 0) { 14935 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14936 verificationInfo.originatingUid); 14937 } 14938 if (verificationInfo.installerUid >= 0) { 14939 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14940 verificationInfo.installerUid); 14941 } 14942 } 14943 14944 final PackageVerificationState verificationState = new PackageVerificationState( 14945 requiredUid, args); 14946 14947 mPendingVerification.append(verificationId, verificationState); 14948 14949 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14950 receivers, verificationState); 14951 14952 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14953 final long idleDuration = getVerificationTimeout(); 14954 14955 /* 14956 * If any sufficient verifiers were listed in the package 14957 * manifest, attempt to ask them. 14958 */ 14959 if (sufficientVerifiers != null) { 14960 final int N = sufficientVerifiers.size(); 14961 if (N == 0) { 14962 Slog.i(TAG, "Additional verifiers required, but none installed."); 14963 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14964 } else { 14965 for (int i = 0; i < N; i++) { 14966 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14967 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14968 verifierComponent.getPackageName(), idleDuration, 14969 verifierUser.getIdentifier(), false, "package verifier"); 14970 14971 final Intent sufficientIntent = new Intent(verification); 14972 sufficientIntent.setComponent(verifierComponent); 14973 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14974 } 14975 } 14976 } 14977 14978 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14979 mRequiredVerifierPackage, receivers); 14980 if (ret == PackageManager.INSTALL_SUCCEEDED 14981 && mRequiredVerifierPackage != null) { 14982 Trace.asyncTraceBegin( 14983 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14984 /* 14985 * Send the intent to the required verification agent, 14986 * but only start the verification timeout after the 14987 * target BroadcastReceivers have run. 14988 */ 14989 verification.setComponent(requiredVerifierComponent); 14990 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14991 mRequiredVerifierPackage, idleDuration, 14992 verifierUser.getIdentifier(), false, "package verifier"); 14993 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14994 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14995 new BroadcastReceiver() { 14996 @Override 14997 public void onReceive(Context context, Intent intent) { 14998 final Message msg = mHandler 14999 .obtainMessage(CHECK_PENDING_VERIFICATION); 15000 msg.arg1 = verificationId; 15001 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15002 } 15003 }, null, 0, null, null); 15004 15005 /* 15006 * We don't want the copy to proceed until verification 15007 * succeeds, so null out this field. 15008 */ 15009 mArgs = null; 15010 } 15011 } else { 15012 /* 15013 * No package verification is enabled, so immediately start 15014 * the remote call to initiate copy using temporary file. 15015 */ 15016 ret = args.copyApk(mContainerService, true); 15017 } 15018 } 15019 15020 mRet = ret; 15021 } 15022 15023 @Override 15024 void handleReturnCode() { 15025 // If mArgs is null, then MCS couldn't be reached. When it 15026 // reconnects, it will try again to install. At that point, this 15027 // will succeed. 15028 if (mArgs != null) { 15029 processPendingInstall(mArgs, mRet); 15030 } 15031 } 15032 15033 @Override 15034 void handleServiceError() { 15035 mArgs = createInstallArgs(this); 15036 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15037 } 15038 } 15039 15040 private InstallArgs createInstallArgs(InstallParams params) { 15041 if (params.move != null) { 15042 return new MoveInstallArgs(params); 15043 } else { 15044 return new FileInstallArgs(params); 15045 } 15046 } 15047 15048 /** 15049 * Create args that describe an existing installed package. Typically used 15050 * when cleaning up old installs, or used as a move source. 15051 */ 15052 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 15053 String resourcePath, String[] instructionSets) { 15054 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15055 } 15056 15057 static abstract class InstallArgs { 15058 /** @see InstallParams#origin */ 15059 final OriginInfo origin; 15060 /** @see InstallParams#move */ 15061 final MoveInfo move; 15062 15063 final IPackageInstallObserver2 observer; 15064 // Always refers to PackageManager flags only 15065 final int installFlags; 15066 final String installerPackageName; 15067 final String volumeUuid; 15068 final UserHandle user; 15069 final String abiOverride; 15070 final String[] installGrantPermissions; 15071 /** If non-null, drop an async trace when the install completes */ 15072 final String traceMethod; 15073 final int traceCookie; 15074 final PackageParser.SigningDetails signingDetails; 15075 final int installReason; 15076 15077 // The list of instruction sets supported by this app. This is currently 15078 // only used during the rmdex() phase to clean up resources. We can get rid of this 15079 // if we move dex files under the common app path. 15080 /* nullable */ String[] instructionSets; 15081 15082 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15083 int installFlags, String installerPackageName, String volumeUuid, 15084 UserHandle user, String[] instructionSets, 15085 String abiOverride, String[] installGrantPermissions, 15086 String traceMethod, int traceCookie, PackageParser.SigningDetails signingDetails, 15087 int installReason) { 15088 this.origin = origin; 15089 this.move = move; 15090 this.installFlags = installFlags; 15091 this.observer = observer; 15092 this.installerPackageName = installerPackageName; 15093 this.volumeUuid = volumeUuid; 15094 this.user = user; 15095 this.instructionSets = instructionSets; 15096 this.abiOverride = abiOverride; 15097 this.installGrantPermissions = installGrantPermissions; 15098 this.traceMethod = traceMethod; 15099 this.traceCookie = traceCookie; 15100 this.signingDetails = signingDetails; 15101 this.installReason = installReason; 15102 } 15103 15104 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 15105 abstract int doPreInstall(int status); 15106 15107 /** 15108 * Rename package into final resting place. All paths on the given 15109 * scanned package should be updated to reflect the rename. 15110 */ 15111 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 15112 abstract int doPostInstall(int status, int uid); 15113 15114 /** @see PackageSettingBase#codePathString */ 15115 abstract String getCodePath(); 15116 /** @see PackageSettingBase#resourcePathString */ 15117 abstract String getResourcePath(); 15118 15119 // Need installer lock especially for dex file removal. 15120 abstract void cleanUpResourcesLI(); 15121 abstract boolean doPostDeleteLI(boolean delete); 15122 15123 /** 15124 * Called before the source arguments are copied. This is used mostly 15125 * for MoveParams when it needs to read the source file to put it in the 15126 * destination. 15127 */ 15128 int doPreCopy() { 15129 return PackageManager.INSTALL_SUCCEEDED; 15130 } 15131 15132 /** 15133 * Called after the source arguments are copied. This is used mostly for 15134 * MoveParams when it needs to read the source file to put it in the 15135 * destination. 15136 */ 15137 int doPostCopy(int uid) { 15138 return PackageManager.INSTALL_SUCCEEDED; 15139 } 15140 15141 protected boolean isFwdLocked() { 15142 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 15143 } 15144 15145 protected boolean isExternalAsec() { 15146 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 15147 } 15148 15149 protected boolean isEphemeral() { 15150 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15151 } 15152 15153 UserHandle getUser() { 15154 return user; 15155 } 15156 } 15157 15158 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15159 if (!allCodePaths.isEmpty()) { 15160 if (instructionSets == null) { 15161 throw new IllegalStateException("instructionSet == null"); 15162 } 15163 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15164 for (String codePath : allCodePaths) { 15165 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15166 try { 15167 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15168 } catch (InstallerException ignored) { 15169 } 15170 } 15171 } 15172 } 15173 } 15174 15175 /** 15176 * Logic to handle installation of non-ASEC applications, including copying 15177 * and renaming logic. 15178 */ 15179 class FileInstallArgs extends InstallArgs { 15180 private File codeFile; 15181 private File resourceFile; 15182 15183 // Example topology: 15184 // /data/app/com.example/base.apk 15185 // /data/app/com.example/split_foo.apk 15186 // /data/app/com.example/lib/arm/libfoo.so 15187 // /data/app/com.example/lib/arm64/libfoo.so 15188 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15189 15190 /** New install */ 15191 FileInstallArgs(InstallParams params) { 15192 super(params.origin, params.move, params.observer, params.installFlags, 15193 params.installerPackageName, params.volumeUuid, 15194 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15195 params.grantedRuntimePermissions, 15196 params.traceMethod, params.traceCookie, params.signingDetails, 15197 params.installReason); 15198 if (isFwdLocked()) { 15199 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 15200 } 15201 } 15202 15203 /** Existing install */ 15204 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15205 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15206 null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15207 PackageManager.INSTALL_REASON_UNKNOWN); 15208 this.codeFile = (codePath != null) ? new File(codePath) : null; 15209 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15210 } 15211 15212 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15214 try { 15215 return doCopyApk(imcs, temp); 15216 } finally { 15217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15218 } 15219 } 15220 15221 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 15222 if (origin.staged) { 15223 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15224 codeFile = origin.file; 15225 resourceFile = origin.file; 15226 return PackageManager.INSTALL_SUCCEEDED; 15227 } 15228 15229 try { 15230 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15231 final File tempDir = 15232 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15233 codeFile = tempDir; 15234 resourceFile = tempDir; 15235 } catch (IOException e) { 15236 Slog.w(TAG, "Failed to create copy file: " + e); 15237 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15238 } 15239 15240 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 15241 @Override 15242 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 15243 if (!FileUtils.isValidExtFilename(name)) { 15244 throw new IllegalArgumentException("Invalid filename: " + name); 15245 } 15246 try { 15247 final File file = new File(codeFile, name); 15248 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 15249 O_RDWR | O_CREAT, 0644); 15250 Os.chmod(file.getAbsolutePath(), 0644); 15251 return new ParcelFileDescriptor(fd); 15252 } catch (ErrnoException e) { 15253 throw new RemoteException("Failed to open: " + e.getMessage()); 15254 } 15255 } 15256 }; 15257 15258 int ret = PackageManager.INSTALL_SUCCEEDED; 15259 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 15260 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15261 Slog.e(TAG, "Failed to copy package"); 15262 return ret; 15263 } 15264 15265 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15266 NativeLibraryHelper.Handle handle = null; 15267 try { 15268 handle = NativeLibraryHelper.Handle.create(codeFile); 15269 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15270 abiOverride); 15271 } catch (IOException e) { 15272 Slog.e(TAG, "Copying native libraries failed", e); 15273 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15274 } finally { 15275 IoUtils.closeQuietly(handle); 15276 } 15277 15278 return ret; 15279 } 15280 15281 int doPreInstall(int status) { 15282 if (status != PackageManager.INSTALL_SUCCEEDED) { 15283 cleanUp(); 15284 } 15285 return status; 15286 } 15287 15288 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15289 if (status != PackageManager.INSTALL_SUCCEEDED) { 15290 cleanUp(); 15291 return false; 15292 } 15293 15294 final File targetDir = codeFile.getParentFile(); 15295 final File beforeCodeFile = codeFile; 15296 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15297 15298 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15299 try { 15300 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15301 } catch (ErrnoException e) { 15302 Slog.w(TAG, "Failed to rename", e); 15303 return false; 15304 } 15305 15306 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15307 Slog.w(TAG, "Failed to restorecon"); 15308 return false; 15309 } 15310 15311 // Reflect the rename internally 15312 codeFile = afterCodeFile; 15313 resourceFile = afterCodeFile; 15314 15315 // Reflect the rename in scanned details 15316 try { 15317 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15318 } catch (IOException e) { 15319 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15320 return false; 15321 } 15322 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15323 afterCodeFile, pkg.baseCodePath)); 15324 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15325 afterCodeFile, pkg.splitCodePaths)); 15326 15327 // Reflect the rename in app info 15328 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15329 pkg.setApplicationInfoCodePath(pkg.codePath); 15330 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15331 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15332 pkg.setApplicationInfoResourcePath(pkg.codePath); 15333 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15334 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15335 15336 return true; 15337 } 15338 15339 int doPostInstall(int status, int uid) { 15340 if (status != PackageManager.INSTALL_SUCCEEDED) { 15341 cleanUp(); 15342 } 15343 return status; 15344 } 15345 15346 @Override 15347 String getCodePath() { 15348 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15349 } 15350 15351 @Override 15352 String getResourcePath() { 15353 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15354 } 15355 15356 private boolean cleanUp() { 15357 if (codeFile == null || !codeFile.exists()) { 15358 return false; 15359 } 15360 15361 removeCodePathLI(codeFile); 15362 15363 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15364 resourceFile.delete(); 15365 } 15366 15367 return true; 15368 } 15369 15370 void cleanUpResourcesLI() { 15371 // Try enumerating all code paths before deleting 15372 List<String> allCodePaths = Collections.EMPTY_LIST; 15373 if (codeFile != null && codeFile.exists()) { 15374 try { 15375 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15376 allCodePaths = pkg.getAllCodePaths(); 15377 } catch (PackageParserException e) { 15378 // Ignored; we tried our best 15379 } 15380 } 15381 15382 cleanUp(); 15383 removeDexFiles(allCodePaths, instructionSets); 15384 } 15385 15386 boolean doPostDeleteLI(boolean delete) { 15387 // XXX err, shouldn't we respect the delete flag? 15388 cleanUpResourcesLI(); 15389 return true; 15390 } 15391 } 15392 15393 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15394 PackageManagerException { 15395 if (copyRet < 0) { 15396 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15397 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15398 throw new PackageManagerException(copyRet, message); 15399 } 15400 } 15401 } 15402 15403 /** 15404 * Extract the StorageManagerService "container ID" from the full code path of an 15405 * .apk. 15406 */ 15407 static String cidFromCodePath(String fullCodePath) { 15408 int eidx = fullCodePath.lastIndexOf("/"); 15409 String subStr1 = fullCodePath.substring(0, eidx); 15410 int sidx = subStr1.lastIndexOf("/"); 15411 return subStr1.substring(sidx+1, eidx); 15412 } 15413 15414 /** 15415 * Logic to handle movement of existing installed applications. 15416 */ 15417 class MoveInstallArgs extends InstallArgs { 15418 private File codeFile; 15419 private File resourceFile; 15420 15421 /** New install */ 15422 MoveInstallArgs(InstallParams params) { 15423 super(params.origin, params.move, params.observer, params.installFlags, 15424 params.installerPackageName, params.volumeUuid, 15425 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15426 params.grantedRuntimePermissions, 15427 params.traceMethod, params.traceCookie, params.signingDetails, 15428 params.installReason); 15429 } 15430 15431 int copyApk(IMediaContainerService imcs, boolean temp) { 15432 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15433 + move.fromUuid + " to " + move.toUuid); 15434 synchronized (mInstaller) { 15435 try { 15436 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15437 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15438 } catch (InstallerException e) { 15439 Slog.w(TAG, "Failed to move app", e); 15440 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15441 } 15442 } 15443 15444 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15445 resourceFile = codeFile; 15446 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15447 15448 return PackageManager.INSTALL_SUCCEEDED; 15449 } 15450 15451 int doPreInstall(int status) { 15452 if (status != PackageManager.INSTALL_SUCCEEDED) { 15453 cleanUp(move.toUuid); 15454 } 15455 return status; 15456 } 15457 15458 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 15459 if (status != PackageManager.INSTALL_SUCCEEDED) { 15460 cleanUp(move.toUuid); 15461 return false; 15462 } 15463 15464 // Reflect the move in app info 15465 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15466 pkg.setApplicationInfoCodePath(pkg.codePath); 15467 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15468 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15469 pkg.setApplicationInfoResourcePath(pkg.codePath); 15470 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15471 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15472 15473 return true; 15474 } 15475 15476 int doPostInstall(int status, int uid) { 15477 if (status == PackageManager.INSTALL_SUCCEEDED) { 15478 cleanUp(move.fromUuid); 15479 } else { 15480 cleanUp(move.toUuid); 15481 } 15482 return status; 15483 } 15484 15485 @Override 15486 String getCodePath() { 15487 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15488 } 15489 15490 @Override 15491 String getResourcePath() { 15492 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15493 } 15494 15495 private boolean cleanUp(String volumeUuid) { 15496 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15497 move.dataAppName); 15498 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15499 final int[] userIds = sUserManager.getUserIds(); 15500 synchronized (mInstallLock) { 15501 // Clean up both app data and code 15502 // All package moves are frozen until finished 15503 for (int userId : userIds) { 15504 try { 15505 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15506 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15507 } catch (InstallerException e) { 15508 Slog.w(TAG, String.valueOf(e)); 15509 } 15510 } 15511 removeCodePathLI(codeFile); 15512 } 15513 return true; 15514 } 15515 15516 void cleanUpResourcesLI() { 15517 throw new UnsupportedOperationException(); 15518 } 15519 15520 boolean doPostDeleteLI(boolean delete) { 15521 throw new UnsupportedOperationException(); 15522 } 15523 } 15524 15525 static String getAsecPackageName(String packageCid) { 15526 int idx = packageCid.lastIndexOf("-"); 15527 if (idx == -1) { 15528 return packageCid; 15529 } 15530 return packageCid.substring(0, idx); 15531 } 15532 15533 // Utility method used to create code paths based on package name and available index. 15534 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 15535 String idxStr = ""; 15536 int idx = 1; 15537 // Fall back to default value of idx=1 if prefix is not 15538 // part of oldCodePath 15539 if (oldCodePath != null) { 15540 String subStr = oldCodePath; 15541 // Drop the suffix right away 15542 if (suffix != null && subStr.endsWith(suffix)) { 15543 subStr = subStr.substring(0, subStr.length() - suffix.length()); 15544 } 15545 // If oldCodePath already contains prefix find out the 15546 // ending index to either increment or decrement. 15547 int sidx = subStr.lastIndexOf(prefix); 15548 if (sidx != -1) { 15549 subStr = subStr.substring(sidx + prefix.length()); 15550 if (subStr != null) { 15551 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 15552 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 15553 } 15554 try { 15555 idx = Integer.parseInt(subStr); 15556 if (idx <= 1) { 15557 idx++; 15558 } else { 15559 idx--; 15560 } 15561 } catch(NumberFormatException e) { 15562 } 15563 } 15564 } 15565 } 15566 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 15567 return prefix + idxStr; 15568 } 15569 15570 private File getNextCodePath(File targetDir, String packageName) { 15571 File result; 15572 SecureRandom random = new SecureRandom(); 15573 byte[] bytes = new byte[16]; 15574 do { 15575 random.nextBytes(bytes); 15576 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15577 result = new File(targetDir, packageName + "-" + suffix); 15578 } while (result.exists()); 15579 return result; 15580 } 15581 15582 // Utility method that returns the relative package path with respect 15583 // to the installation directory. Like say for /data/data/com.test-1.apk 15584 // string com.test-1 is returned. 15585 static String deriveCodePathName(String codePath) { 15586 if (codePath == null) { 15587 return null; 15588 } 15589 final File codeFile = new File(codePath); 15590 final String name = codeFile.getName(); 15591 if (codeFile.isDirectory()) { 15592 return name; 15593 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 15594 final int lastDot = name.lastIndexOf('.'); 15595 return name.substring(0, lastDot); 15596 } else { 15597 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 15598 return null; 15599 } 15600 } 15601 15602 static class PackageInstalledInfo { 15603 String name; 15604 int uid; 15605 // The set of users that originally had this package installed. 15606 int[] origUsers; 15607 // The set of users that now have this package installed. 15608 int[] newUsers; 15609 PackageParser.Package pkg; 15610 int returnCode; 15611 String returnMsg; 15612 String installerPackageName; 15613 PackageRemovedInfo removedInfo; 15614 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15615 15616 public void setError(int code, String msg) { 15617 setReturnCode(code); 15618 setReturnMessage(msg); 15619 Slog.w(TAG, msg); 15620 } 15621 15622 public void setError(String msg, PackageParserException e) { 15623 setReturnCode(e.error); 15624 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15625 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15626 for (int i = 0; i < childCount; i++) { 15627 addedChildPackages.valueAt(i).setError(msg, e); 15628 } 15629 Slog.w(TAG, msg, e); 15630 } 15631 15632 public void setError(String msg, PackageManagerException e) { 15633 returnCode = e.error; 15634 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15635 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15636 for (int i = 0; i < childCount; i++) { 15637 addedChildPackages.valueAt(i).setError(msg, e); 15638 } 15639 Slog.w(TAG, msg, e); 15640 } 15641 15642 public void setReturnCode(int returnCode) { 15643 this.returnCode = returnCode; 15644 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15645 for (int i = 0; i < childCount; i++) { 15646 addedChildPackages.valueAt(i).returnCode = returnCode; 15647 } 15648 } 15649 15650 private void setReturnMessage(String returnMsg) { 15651 this.returnMsg = returnMsg; 15652 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15653 for (int i = 0; i < childCount; i++) { 15654 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15655 } 15656 } 15657 15658 // In some error cases we want to convey more info back to the observer 15659 String origPackage; 15660 String origPermission; 15661 } 15662 15663 /* 15664 * Install a non-existing package. 15665 */ 15666 private void installNewPackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15667 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15668 String volumeUuid, PackageInstalledInfo res, int installReason) { 15669 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 15670 15671 // Remember this for later, in case we need to rollback this install 15672 String pkgName = pkg.packageName; 15673 15674 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 15675 15676 synchronized(mPackages) { 15677 final String renamedPackage = mSettings.getRenamedPackageLPr(pkgName); 15678 if (renamedPackage != null) { 15679 // A package with the same name is already installed, though 15680 // it has been renamed to an older name. The package we 15681 // are trying to install should be installed as an update to 15682 // the existing one, but that has not been requested, so bail. 15683 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15684 + " without first uninstalling package running as " 15685 + renamedPackage); 15686 return; 15687 } 15688 if (mPackages.containsKey(pkgName)) { 15689 // Don't allow installation over an existing package with the same name. 15690 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 15691 + " without first uninstalling."); 15692 return; 15693 } 15694 } 15695 15696 try { 15697 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 15698 System.currentTimeMillis(), user); 15699 15700 updateSettingsLI(newPackage, installerPackageName, null, res, user, installReason); 15701 15702 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 15703 prepareAppDataAfterInstallLIF(newPackage); 15704 15705 } else { 15706 // Remove package from internal structures, but keep around any 15707 // data that might have already existed 15708 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 15709 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 15710 } 15711 } catch (PackageManagerException e) { 15712 res.setError("Package couldn't be installed in " + pkg.codePath, e); 15713 } 15714 15715 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15716 } 15717 15718 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15719 try (DigestInputStream digestStream = 15720 new DigestInputStream(new FileInputStream(file), digest)) { 15721 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15722 } 15723 } 15724 15725 private void replacePackageLIF(PackageParser.Package pkg, final @ParseFlags int parseFlags, 15726 final @ScanFlags int scanFlags, UserHandle user, String installerPackageName, 15727 PackageInstalledInfo res, int installReason) { 15728 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 15729 15730 final PackageParser.Package oldPackage; 15731 final PackageSetting ps; 15732 final String pkgName = pkg.packageName; 15733 final int[] allUsers; 15734 final int[] installedUsers; 15735 15736 synchronized(mPackages) { 15737 oldPackage = mPackages.get(pkgName); 15738 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 15739 15740 // don't allow upgrade to target a release SDK from a pre-release SDK 15741 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 15742 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15743 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 15744 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 15745 if (oldTargetsPreRelease 15746 && !newTargetsPreRelease 15747 && ((parseFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 15748 Slog.w(TAG, "Can't install package targeting released sdk"); 15749 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 15750 return; 15751 } 15752 15753 ps = mSettings.mPackages.get(pkgName); 15754 15755 // verify signatures are valid 15756 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 15757 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 15758 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 15759 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15760 "New package not signed by keys specified by upgrade-keysets: " 15761 + pkgName); 15762 return; 15763 } 15764 } else { 15765 // default to original signature matching 15766 if (compareSignatures(oldPackage.mSigningDetails.signatures, 15767 pkg.mSigningDetails.signatures) 15768 != PackageManager.SIGNATURE_MATCH) { 15769 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15770 "New package has a different signature: " + pkgName); 15771 return; 15772 } 15773 } 15774 15775 // don't allow a system upgrade unless the upgrade hash matches 15776 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 15777 byte[] digestBytes = null; 15778 try { 15779 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 15780 updateDigest(digest, new File(pkg.baseCodePath)); 15781 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 15782 for (String path : pkg.splitCodePaths) { 15783 updateDigest(digest, new File(path)); 15784 } 15785 } 15786 digestBytes = digest.digest(); 15787 } catch (NoSuchAlgorithmException | IOException e) { 15788 res.setError(INSTALL_FAILED_INVALID_APK, 15789 "Could not compute hash: " + pkgName); 15790 return; 15791 } 15792 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 15793 res.setError(INSTALL_FAILED_INVALID_APK, 15794 "New package fails restrict-update check: " + pkgName); 15795 return; 15796 } 15797 // retain upgrade restriction 15798 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 15799 } 15800 15801 // Check for shared user id changes 15802 String invalidPackageName = 15803 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 15804 if (invalidPackageName != null) { 15805 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 15806 "Package " + invalidPackageName + " tried to change user " 15807 + oldPackage.mSharedUserId); 15808 return; 15809 } 15810 15811 // check if the new package supports all of the abis which the old package supports 15812 boolean oldPkgSupportMultiArch = oldPackage.applicationInfo.secondaryCpuAbi != null; 15813 boolean newPkgSupportMultiArch = pkg.applicationInfo.secondaryCpuAbi != null; 15814 if (isSystemApp(oldPackage) && oldPkgSupportMultiArch && !newPkgSupportMultiArch) { 15815 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 15816 "Update to package " + pkgName + " doesn't support multi arch"); 15817 return; 15818 } 15819 15820 // In case of rollback, remember per-user/profile install state 15821 allUsers = sUserManager.getUserIds(); 15822 installedUsers = ps.queryInstalledUsers(allUsers, true); 15823 15824 // don't allow an upgrade from full to ephemeral 15825 if (isInstantApp) { 15826 if (user == null || user.getIdentifier() == UserHandle.USER_ALL) { 15827 for (int currentUser : allUsers) { 15828 if (!ps.getInstantApp(currentUser)) { 15829 // can't downgrade from full to instant 15830 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15831 + " for user: " + currentUser); 15832 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15833 return; 15834 } 15835 } 15836 } else if (!ps.getInstantApp(user.getIdentifier())) { 15837 // can't downgrade from full to instant 15838 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName 15839 + " for user: " + user.getIdentifier()); 15840 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 15841 return; 15842 } 15843 } 15844 } 15845 15846 // Update what is removed 15847 res.removedInfo = new PackageRemovedInfo(this); 15848 res.removedInfo.uid = oldPackage.applicationInfo.uid; 15849 res.removedInfo.removedPackage = oldPackage.packageName; 15850 res.removedInfo.installerPackageName = ps.installerPackageName; 15851 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 15852 res.removedInfo.isUpdate = true; 15853 res.removedInfo.origUsers = installedUsers; 15854 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 15855 for (int i = 0; i < installedUsers.length; i++) { 15856 final int userId = installedUsers[i]; 15857 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 15858 } 15859 15860 final int childCount = (oldPackage.childPackages != null) 15861 ? oldPackage.childPackages.size() : 0; 15862 for (int i = 0; i < childCount; i++) { 15863 boolean childPackageUpdated = false; 15864 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 15865 final PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 15866 if (res.addedChildPackages != null) { 15867 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15868 if (childRes != null) { 15869 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 15870 childRes.removedInfo.removedPackage = childPkg.packageName; 15871 if (childPs != null) { 15872 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 15873 } 15874 childRes.removedInfo.isUpdate = true; 15875 childRes.removedInfo.installReasons = res.removedInfo.installReasons; 15876 childPackageUpdated = true; 15877 } 15878 } 15879 if (!childPackageUpdated) { 15880 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 15881 childRemovedRes.removedPackage = childPkg.packageName; 15882 if (childPs != null) { 15883 childRemovedRes.installerPackageName = childPs.installerPackageName; 15884 } 15885 childRemovedRes.isUpdate = false; 15886 childRemovedRes.dataRemoved = true; 15887 synchronized (mPackages) { 15888 if (childPs != null) { 15889 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 15890 } 15891 } 15892 if (res.removedInfo.removedChildPackages == null) { 15893 res.removedInfo.removedChildPackages = new ArrayMap<>(); 15894 } 15895 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 15896 } 15897 } 15898 15899 boolean sysPkg = (isSystemApp(oldPackage)); 15900 if (sysPkg) { 15901 // Set the system/privileged/oem/vendor flags as needed 15902 final boolean privileged = 15903 (oldPackage.applicationInfo.privateFlags 15904 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15905 final boolean oem = 15906 (oldPackage.applicationInfo.privateFlags 15907 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 15908 final boolean vendor = 15909 (oldPackage.applicationInfo.privateFlags 15910 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 15911 final @ParseFlags int systemParseFlags = parseFlags; 15912 final @ScanFlags int systemScanFlags = scanFlags 15913 | SCAN_AS_SYSTEM 15914 | (privileged ? SCAN_AS_PRIVILEGED : 0) 15915 | (oem ? SCAN_AS_OEM : 0) 15916 | (vendor ? SCAN_AS_VENDOR : 0); 15917 15918 replaceSystemPackageLIF(oldPackage, pkg, systemParseFlags, systemScanFlags, 15919 user, allUsers, installerPackageName, res, installReason); 15920 } else { 15921 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 15922 user, allUsers, installerPackageName, res, installReason); 15923 } 15924 } 15925 15926 @Override 15927 public List<String> getPreviousCodePaths(String packageName) { 15928 final int callingUid = Binder.getCallingUid(); 15929 final List<String> result = new ArrayList<>(); 15930 if (getInstantAppPackageName(callingUid) != null) { 15931 return result; 15932 } 15933 final PackageSetting ps = mSettings.mPackages.get(packageName); 15934 if (ps != null 15935 && ps.oldCodePaths != null 15936 && !filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 15937 result.addAll(ps.oldCodePaths); 15938 } 15939 return result; 15940 } 15941 15942 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 15943 PackageParser.Package pkg, final @ParseFlags int parseFlags, 15944 final @ScanFlags int scanFlags, UserHandle user, int[] allUsers, 15945 String installerPackageName, PackageInstalledInfo res, int installReason) { 15946 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 15947 + deletedPackage); 15948 15949 String pkgName = deletedPackage.packageName; 15950 boolean deletedPkg = true; 15951 boolean addedPkg = false; 15952 boolean updatedSettings = false; 15953 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 15954 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 15955 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 15956 15957 final long origUpdateTime = (pkg.mExtras != null) 15958 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 15959 15960 // First delete the existing package while retaining the data directory 15961 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 15962 res.removedInfo, true, pkg)) { 15963 // If the existing package wasn't successfully deleted 15964 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 15965 deletedPkg = false; 15966 } else { 15967 // Successfully deleted the old package; proceed with replace. 15968 15969 // If deleted package lived in a container, give users a chance to 15970 // relinquish resources before killing. 15971 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 15972 if (DEBUG_INSTALL) { 15973 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 15974 } 15975 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 15976 final ArrayList<String> pkgList = new ArrayList<String>(1); 15977 pkgList.add(deletedPackage.applicationInfo.packageName); 15978 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 15979 } 15980 15981 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 15982 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 15983 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 15984 15985 try { 15986 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 15987 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 15988 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 15989 installReason); 15990 15991 // Update the in-memory copy of the previous code paths. 15992 PackageSetting ps = mSettings.mPackages.get(pkgName); 15993 if (!killApp) { 15994 if (ps.oldCodePaths == null) { 15995 ps.oldCodePaths = new ArraySet<>(); 15996 } 15997 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 15998 if (deletedPackage.splitCodePaths != null) { 15999 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 16000 } 16001 } else { 16002 ps.oldCodePaths = null; 16003 } 16004 if (ps.childPackageNames != null) { 16005 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 16006 final String childPkgName = ps.childPackageNames.get(i); 16007 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16008 childPs.oldCodePaths = ps.oldCodePaths; 16009 } 16010 } 16011 // set instant app status, but, only if it's explicitly specified 16012 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 16013 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 16014 setInstantAppForUser(ps, user.getIdentifier(), instantApp, fullApp); 16015 prepareAppDataAfterInstallLIF(newPackage); 16016 addedPkg = true; 16017 mDexManager.notifyPackageUpdated(newPackage.packageName, 16018 newPackage.baseCodePath, newPackage.splitCodePaths); 16019 } catch (PackageManagerException e) { 16020 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16021 } 16022 } 16023 16024 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16025 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 16026 16027 // Revert all internal state mutations and added folders for the failed install 16028 if (addedPkg) { 16029 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 16030 res.removedInfo, true, null); 16031 } 16032 16033 // Restore the old package 16034 if (deletedPkg) { 16035 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 16036 File restoreFile = new File(deletedPackage.codePath); 16037 // Parse old package 16038 boolean oldExternal = isExternal(deletedPackage); 16039 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 16040 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 16041 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16042 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 16043 try { 16044 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 16045 null); 16046 } catch (PackageManagerException e) { 16047 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 16048 + e.getMessage()); 16049 return; 16050 } 16051 16052 synchronized (mPackages) { 16053 // Ensure the installer package name up to date 16054 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16055 16056 // Update permissions for restored package 16057 mPermissionManager.updatePermissions( 16058 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16059 mPermissionCallback); 16060 16061 mSettings.writeLPr(); 16062 } 16063 16064 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 16065 } 16066 } else { 16067 synchronized (mPackages) { 16068 PackageSetting ps = mSettings.getPackageLPr(pkg.packageName); 16069 if (ps != null) { 16070 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16071 if (res.removedInfo.removedChildPackages != null) { 16072 final int childCount = res.removedInfo.removedChildPackages.size(); 16073 // Iterate in reverse as we may modify the collection 16074 for (int i = childCount - 1; i >= 0; i--) { 16075 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 16076 if (res.addedChildPackages.containsKey(childPackageName)) { 16077 res.removedInfo.removedChildPackages.removeAt(i); 16078 } else { 16079 PackageRemovedInfo childInfo = res.removedInfo 16080 .removedChildPackages.valueAt(i); 16081 childInfo.removedForAllUsers = mPackages.get( 16082 childInfo.removedPackage) == null; 16083 } 16084 } 16085 } 16086 } 16087 } 16088 } 16089 } 16090 16091 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 16092 PackageParser.Package pkg, final @ParseFlags int parseFlags, 16093 final @ScanFlags int scanFlags, UserHandle user, 16094 int[] allUsers, String installerPackageName, PackageInstalledInfo res, 16095 int installReason) { 16096 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 16097 + ", old=" + deletedPackage); 16098 16099 final boolean disabledSystem; 16100 16101 // Remove existing system package 16102 removePackageLI(deletedPackage, true); 16103 16104 synchronized (mPackages) { 16105 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 16106 } 16107 if (!disabledSystem) { 16108 // We didn't need to disable the .apk as a current system package, 16109 // which means we are replacing another update that is already 16110 // installed. We need to make sure to delete the older one's .apk. 16111 res.removedInfo.args = createInstallArgsForExisting(0, 16112 deletedPackage.applicationInfo.getCodePath(), 16113 deletedPackage.applicationInfo.getResourcePath(), 16114 getAppDexInstructionSets(deletedPackage.applicationInfo)); 16115 } else { 16116 res.removedInfo.args = null; 16117 } 16118 16119 // Successfully disabled the old package. Now proceed with re-installation 16120 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 16121 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16122 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 16123 16124 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16125 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 16126 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 16127 16128 PackageParser.Package newPackage = null; 16129 try { 16130 // Add the package to the internal data structures 16131 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 16132 16133 // Set the update and install times 16134 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 16135 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 16136 System.currentTimeMillis()); 16137 16138 // Update the package dynamic state if succeeded 16139 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16140 // Now that the install succeeded make sure we remove data 16141 // directories for any child package the update removed. 16142 final int deletedChildCount = (deletedPackage.childPackages != null) 16143 ? deletedPackage.childPackages.size() : 0; 16144 final int newChildCount = (newPackage.childPackages != null) 16145 ? newPackage.childPackages.size() : 0; 16146 for (int i = 0; i < deletedChildCount; i++) { 16147 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 16148 boolean childPackageDeleted = true; 16149 for (int j = 0; j < newChildCount; j++) { 16150 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 16151 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16152 childPackageDeleted = false; 16153 break; 16154 } 16155 } 16156 if (childPackageDeleted) { 16157 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 16158 deletedChildPkg.packageName); 16159 if (ps != null && res.removedInfo.removedChildPackages != null) { 16160 PackageRemovedInfo removedChildRes = res.removedInfo 16161 .removedChildPackages.get(deletedChildPkg.packageName); 16162 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 16163 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 16164 } 16165 } 16166 } 16167 16168 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user, 16169 installReason); 16170 prepareAppDataAfterInstallLIF(newPackage); 16171 16172 mDexManager.notifyPackageUpdated(newPackage.packageName, 16173 newPackage.baseCodePath, newPackage.splitCodePaths); 16174 } 16175 } catch (PackageManagerException e) { 16176 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 16177 res.setError("Package couldn't be installed in " + pkg.codePath, e); 16178 } 16179 16180 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 16181 // Re installation failed. Restore old information 16182 // Remove new pkg information 16183 if (newPackage != null) { 16184 removeInstalledPackageLI(newPackage, true); 16185 } 16186 // Add back the old system package 16187 try { 16188 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 16189 } catch (PackageManagerException e) { 16190 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 16191 } 16192 16193 synchronized (mPackages) { 16194 if (disabledSystem) { 16195 enableSystemPackageLPw(deletedPackage); 16196 } 16197 16198 // Ensure the installer package name up to date 16199 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 16200 16201 // Update permissions for restored package 16202 mPermissionManager.updatePermissions( 16203 deletedPackage.packageName, deletedPackage, false, mPackages.values(), 16204 mPermissionCallback); 16205 16206 mSettings.writeLPr(); 16207 } 16208 16209 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 16210 + " after failed upgrade"); 16211 } 16212 } 16213 16214 /** 16215 * Checks whether the parent or any of the child packages have a change shared 16216 * user. For a package to be a valid update the shred users of the parent and 16217 * the children should match. We may later support changing child shared users. 16218 * @param oldPkg The updated package. 16219 * @param newPkg The update package. 16220 * @return The shared user that change between the versions. 16221 */ 16222 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16223 PackageParser.Package newPkg) { 16224 // Check parent shared user 16225 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16226 return newPkg.packageName; 16227 } 16228 // Check child shared users 16229 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16230 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16231 for (int i = 0; i < newChildCount; i++) { 16232 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16233 // If this child was present, did it have the same shared user? 16234 for (int j = 0; j < oldChildCount; j++) { 16235 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16236 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16237 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16238 return newChildPkg.packageName; 16239 } 16240 } 16241 } 16242 return null; 16243 } 16244 16245 private void removeNativeBinariesLI(PackageSetting ps) { 16246 // Remove the lib path for the parent package 16247 if (ps != null) { 16248 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16249 // Remove the lib path for the child packages 16250 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16251 for (int i = 0; i < childCount; i++) { 16252 PackageSetting childPs = null; 16253 synchronized (mPackages) { 16254 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16255 } 16256 if (childPs != null) { 16257 NativeLibraryHelper.removeNativeBinariesLI(childPs 16258 .legacyNativeLibraryPathString); 16259 } 16260 } 16261 } 16262 } 16263 16264 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16265 // Enable the parent package 16266 mSettings.enableSystemPackageLPw(pkg.packageName); 16267 // Enable the child packages 16268 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16269 for (int i = 0; i < childCount; i++) { 16270 PackageParser.Package childPkg = pkg.childPackages.get(i); 16271 mSettings.enableSystemPackageLPw(childPkg.packageName); 16272 } 16273 } 16274 16275 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16276 PackageParser.Package newPkg) { 16277 // Disable the parent package (parent always replaced) 16278 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16279 // Disable the child packages 16280 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16281 for (int i = 0; i < childCount; i++) { 16282 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16283 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16284 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16285 } 16286 return disabled; 16287 } 16288 16289 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16290 String installerPackageName) { 16291 // Enable the parent package 16292 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16293 // Enable the child packages 16294 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16295 for (int i = 0; i < childCount; i++) { 16296 PackageParser.Package childPkg = pkg.childPackages.get(i); 16297 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16298 } 16299 } 16300 16301 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16302 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16303 // Update the parent package setting 16304 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16305 res, user, installReason); 16306 // Update the child packages setting 16307 final int childCount = (newPackage.childPackages != null) 16308 ? newPackage.childPackages.size() : 0; 16309 for (int i = 0; i < childCount; i++) { 16310 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16311 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16312 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16313 childRes.origUsers, childRes, user, installReason); 16314 } 16315 } 16316 16317 private void updateSettingsInternalLI(PackageParser.Package pkg, 16318 String installerPackageName, int[] allUsers, int[] installedForUsers, 16319 PackageInstalledInfo res, UserHandle user, int installReason) { 16320 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16321 16322 String pkgName = pkg.packageName; 16323 synchronized (mPackages) { 16324 //write settings. the installStatus will be incomplete at this stage. 16325 //note that the new package setting would have already been 16326 //added to mPackages. It hasn't been persisted yet. 16327 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 16328 // TODO: Remove this write? It's also written at the end of this method 16329 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16330 mSettings.writeLPr(); 16331 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16332 } 16333 16334 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16335 synchronized (mPackages) { 16336// NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16337 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16338 mPermissionCallback); 16339 // For system-bundled packages, we assume that installing an upgraded version 16340 // of the package implies that the user actually wants to run that new code, 16341 // so we enable the package. 16342 PackageSetting ps = mSettings.mPackages.get(pkgName); 16343 final int userId = user.getIdentifier(); 16344 if (ps != null) { 16345 if (isSystemApp(pkg)) { 16346 if (DEBUG_INSTALL) { 16347 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16348 } 16349 // Enable system package for requested users 16350 if (res.origUsers != null) { 16351 for (int origUserId : res.origUsers) { 16352 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16353 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16354 origUserId, installerPackageName); 16355 } 16356 } 16357 } 16358 // Also convey the prior install/uninstall state 16359 if (allUsers != null && installedForUsers != null) { 16360 for (int currentUserId : allUsers) { 16361 final boolean installed = ArrayUtils.contains( 16362 installedForUsers, currentUserId); 16363 if (DEBUG_INSTALL) { 16364 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16365 } 16366 ps.setInstalled(installed, currentUserId); 16367 } 16368 // these install state changes will be persisted in the 16369 // upcoming call to mSettings.writeLPr(). 16370 } 16371 } 16372 // It's implied that when a user requests installation, they want the app to be 16373 // installed and enabled. 16374 if (userId != UserHandle.USER_ALL) { 16375 ps.setInstalled(true, userId); 16376 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16377 } 16378 16379 // When replacing an existing package, preserve the original install reason for all 16380 // users that had the package installed before. 16381 final Set<Integer> previousUserIds = new ArraySet<>(); 16382 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16383 final int installReasonCount = res.removedInfo.installReasons.size(); 16384 for (int i = 0; i < installReasonCount; i++) { 16385 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16386 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16387 ps.setInstallReason(previousInstallReason, previousUserId); 16388 previousUserIds.add(previousUserId); 16389 } 16390 } 16391 16392 // Set install reason for users that are having the package newly installed. 16393 if (userId == UserHandle.USER_ALL) { 16394 for (int currentUserId : sUserManager.getUserIds()) { 16395 if (!previousUserIds.contains(currentUserId)) { 16396 ps.setInstallReason(installReason, currentUserId); 16397 } 16398 } 16399 } else if (!previousUserIds.contains(userId)) { 16400 ps.setInstallReason(installReason, userId); 16401 } 16402 mSettings.writeKernelMappingLPr(ps); 16403 } 16404 res.name = pkgName; 16405 res.uid = pkg.applicationInfo.uid; 16406 res.pkg = pkg; 16407 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 16408 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16409 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16410 //to update install status 16411 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16412 mSettings.writeLPr(); 16413 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16414 } 16415 16416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16417 } 16418 16419 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 16420 try { 16421 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 16422 installPackageLI(args, res); 16423 } finally { 16424 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16425 } 16426 } 16427 16428 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 16429 final int installFlags = args.installFlags; 16430 final String installerPackageName = args.installerPackageName; 16431 final String volumeUuid = args.volumeUuid; 16432 final File tmpPackageFile = new File(args.getCodePath()); 16433 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 16434 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 16435 || (args.volumeUuid != null)); 16436 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16437 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16438 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 16439 final boolean virtualPreload = 16440 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16441 boolean replace = false; 16442 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16443 if (args.move != null) { 16444 // moving a complete application; perform an initial scan on the new install location 16445 scanFlags |= SCAN_INITIAL; 16446 } 16447 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16448 scanFlags |= SCAN_DONT_KILL_APP; 16449 } 16450 if (instantApp) { 16451 scanFlags |= SCAN_AS_INSTANT_APP; 16452 } 16453 if (fullApp) { 16454 scanFlags |= SCAN_AS_FULL_APP; 16455 } 16456 if (virtualPreload) { 16457 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16458 } 16459 16460 // Result object to be returned 16461 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16462 res.installerPackageName = installerPackageName; 16463 16464 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16465 16466 // Sanity check 16467 if (instantApp && (forwardLocked || onExternal)) { 16468 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 16469 + " external=" + onExternal); 16470 res.setReturnCode(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16471 return; 16472 } 16473 16474 // Retrieve PackageSettings and parse package 16475 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16476 | PackageParser.PARSE_ENFORCE_CODE 16477 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 16478 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 16479 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 16480 PackageParser pp = new PackageParser(); 16481 pp.setSeparateProcesses(mSeparateProcesses); 16482 pp.setDisplayMetrics(mMetrics); 16483 pp.setCallback(mPackageParserCallback); 16484 16485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16486 final PackageParser.Package pkg; 16487 try { 16488 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16489 DexMetadataHelper.validatePackageDexMetadata(pkg); 16490 } catch (PackageParserException e) { 16491 res.setError("Failed parse during installPackageLI", e); 16492 return; 16493 } finally { 16494 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16495 } 16496 16497 // Instant apps have several additional install-time checks. 16498 if (instantApp) { 16499 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16500 Slog.w(TAG, 16501 "Instant app package " + pkg.packageName + " does not target at least O"); 16502 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16503 "Instant app package must target at least O"); 16504 return; 16505 } 16506 if (pkg.applicationInfo.targetSandboxVersion != 2) { 16507 Slog.w(TAG, "Instant app package " + pkg.packageName 16508 + " does not target targetSandboxVersion 2"); 16509 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16510 "Instant app package must use targetSandboxVersion 2"); 16511 return; 16512 } 16513 if (pkg.mSharedUserId != null) { 16514 Slog.w(TAG, "Instant app package " + pkg.packageName 16515 + " may not declare sharedUserId."); 16516 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16517 "Instant app package may not declare a sharedUserId"); 16518 return; 16519 } 16520 } 16521 16522 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16523 // Static shared libraries have synthetic package names 16524 renameStaticSharedLibraryPackage(pkg); 16525 16526 // No static shared libs on external storage 16527 if (onExternal) { 16528 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16529 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16530 "Packages declaring static-shared libs cannot be updated"); 16531 return; 16532 } 16533 } 16534 16535 // If we are installing a clustered package add results for the children 16536 if (pkg.childPackages != null) { 16537 synchronized (mPackages) { 16538 final int childCount = pkg.childPackages.size(); 16539 for (int i = 0; i < childCount; i++) { 16540 PackageParser.Package childPkg = pkg.childPackages.get(i); 16541 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16542 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16543 childRes.pkg = childPkg; 16544 childRes.name = childPkg.packageName; 16545 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16546 if (childPs != null) { 16547 childRes.origUsers = childPs.queryInstalledUsers( 16548 sUserManager.getUserIds(), true); 16549 } 16550 if ((mPackages.containsKey(childPkg.packageName))) { 16551 childRes.removedInfo = new PackageRemovedInfo(this); 16552 childRes.removedInfo.removedPackage = childPkg.packageName; 16553 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16554 } 16555 if (res.addedChildPackages == null) { 16556 res.addedChildPackages = new ArrayMap<>(); 16557 } 16558 res.addedChildPackages.put(childPkg.packageName, childRes); 16559 } 16560 } 16561 } 16562 16563 // If package doesn't declare API override, mark that we have an install 16564 // time CPU ABI override. 16565 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16566 pkg.cpuAbiOverride = args.abiOverride; 16567 } 16568 16569 String pkgName = res.name = pkg.packageName; 16570 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16571 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16572 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16573 return; 16574 } 16575 } 16576 16577 try { 16578 // either use what we've been given or parse directly from the APK 16579 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16580 pkg.setSigningDetails(args.signingDetails); 16581 } else { 16582 PackageParser.collectCertificates(pkg, parseFlags); 16583 } 16584 } catch (PackageParserException e) { 16585 res.setError("Failed collect during installPackageLI", e); 16586 return; 16587 } 16588 16589 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16590 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16591 Slog.w(TAG, "Instant app package " + pkg.packageName 16592 + " is not signed with at least APK Signature Scheme v2"); 16593 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16594 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16595 return; 16596 } 16597 16598 // Get rid of all references to package scan path via parser. 16599 pp = null; 16600 String oldCodePath = null; 16601 boolean systemApp = false; 16602 synchronized (mPackages) { 16603 // Check if installing already existing package 16604 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16605 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16606 if (pkg.mOriginalPackages != null 16607 && pkg.mOriginalPackages.contains(oldName) 16608 && mPackages.containsKey(oldName)) { 16609 // This package is derived from an original package, 16610 // and this device has been updating from that original 16611 // name. We must continue using the original name, so 16612 // rename the new package here. 16613 pkg.setPackageName(oldName); 16614 pkgName = pkg.packageName; 16615 replace = true; 16616 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 16617 + oldName + " pkgName=" + pkgName); 16618 } else if (mPackages.containsKey(pkgName)) { 16619 // This package, under its official name, already exists 16620 // on the device; we should replace it. 16621 replace = true; 16622 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16623 } 16624 16625 // Child packages are installed through the parent package 16626 if (pkg.parentPackage != null) { 16627 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16628 "Package " + pkg.packageName + " is child of package " 16629 + pkg.parentPackage.parentPackage + ". Child packages " 16630 + "can be updated only through the parent package."); 16631 return; 16632 } 16633 16634 if (replace) { 16635 // Prevent apps opting out from runtime permissions 16636 PackageParser.Package oldPackage = mPackages.get(pkgName); 16637 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16638 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16639 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16640 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16641 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16642 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16643 + " doesn't support runtime permissions but the old" 16644 + " target SDK " + oldTargetSdk + " does."); 16645 return; 16646 } 16647 // Prevent persistent apps from being updated 16648 if ((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) { 16649 res.setError(PackageManager.INSTALL_FAILED_INVALID_APK, 16650 "Package " + oldPackage.packageName + " is a persistent app. " 16651 + "Persistent apps are not updateable."); 16652 return; 16653 } 16654 // Prevent apps from downgrading their targetSandbox. 16655 final int oldTargetSandbox = oldPackage.applicationInfo.targetSandboxVersion; 16656 final int newTargetSandbox = pkg.applicationInfo.targetSandboxVersion; 16657 if (oldTargetSandbox == 2 && newTargetSandbox != 2) { 16658 res.setError(PackageManager.INSTALL_FAILED_SANDBOX_VERSION_DOWNGRADE, 16659 "Package " + pkg.packageName + " new target sandbox " 16660 + newTargetSandbox + " is incompatible with the previous value of" 16661 + oldTargetSandbox + "."); 16662 return; 16663 } 16664 16665 // Prevent installing of child packages 16666 if (oldPackage.parentPackage != null) { 16667 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16668 "Package " + pkg.packageName + " is child of package " 16669 + oldPackage.parentPackage + ". Child packages " 16670 + "can be updated only through the parent package."); 16671 return; 16672 } 16673 } 16674 } 16675 16676 PackageSetting ps = mSettings.mPackages.get(pkgName); 16677 if (ps != null) { 16678 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16679 16680 // Static shared libs have same package with different versions where 16681 // we internally use a synthetic package name to allow multiple versions 16682 // of the same package, therefore we need to compare signatures against 16683 // the package setting for the latest library version. 16684 PackageSetting signatureCheckPs = ps; 16685 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16686 SharedLibraryEntry libraryEntry = getLatestSharedLibraVersionLPr(pkg); 16687 if (libraryEntry != null) { 16688 signatureCheckPs = mSettings.getPackageLPr(libraryEntry.apk); 16689 } 16690 } 16691 16692 // Quick sanity check that we're signed correctly if updating; 16693 // we'll check this again later when scanning, but we want to 16694 // bail early here before tripping over redefined permissions. 16695 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16696 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16697 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16698 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16699 + pkg.packageName + " upgrade keys do not match the " 16700 + "previously installed version"); 16701 return; 16702 } 16703 } else { 16704 try { 16705 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16706 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16707 // We don't care about disabledPkgSetting on install for now. 16708 final boolean compatMatch = verifySignatures( 16709 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16710 compareRecover); 16711 // The new KeySets will be re-added later in the scanning process. 16712 if (compatMatch) { 16713 synchronized (mPackages) { 16714 ksms.removeAppKeySetDataLPw(pkg.packageName); 16715 } 16716 } 16717 } catch (PackageManagerException e) { 16718 res.setError(e.error, e.getMessage()); 16719 return; 16720 } 16721 } 16722 16723 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 16724 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 16725 systemApp = (ps.pkg.applicationInfo.flags & 16726 ApplicationInfo.FLAG_SYSTEM) != 0; 16727 } 16728 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16729 } 16730 16731 int N = pkg.permissions.size(); 16732 for (int i = N-1; i >= 0; i--) { 16733 final PackageParser.Permission perm = pkg.permissions.get(i); 16734 final BasePermission bp = 16735 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 16736 16737 // Don't allow anyone but the system to define ephemeral permissions. 16738 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 16739 && !systemApp) { 16740 Slog.w(TAG, "Non-System package " + pkg.packageName 16741 + " attempting to delcare ephemeral permission " 16742 + perm.info.name + "; Removing ephemeral."); 16743 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 16744 } 16745 16746 // Check whether the newly-scanned package wants to define an already-defined perm 16747 if (bp != null) { 16748 // If the defining package is signed with our cert, it's okay. This 16749 // also includes the "updating the same package" case, of course. 16750 // "updating same package" could also involve key-rotation. 16751 final boolean sigsOk; 16752 final String sourcePackageName = bp.getSourcePackageName(); 16753 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 16754 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16755 if (sourcePackageName.equals(pkg.packageName) 16756 && (ksms.shouldCheckUpgradeKeySetLocked( 16757 sourcePackageSetting, scanFlags))) { 16758 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 16759 } else { 16760 sigsOk = compareSignatures(sourcePackageSetting.signatures.mSignatures, 16761 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH; 16762 } 16763 if (!sigsOk) { 16764 // If the owning package is the system itself, we log but allow 16765 // install to proceed; we fail the install on all other permission 16766 // redefinitions. 16767 if (!sourcePackageName.equals("android")) { 16768 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 16769 + pkg.packageName + " attempting to redeclare permission " 16770 + perm.info.name + " already owned by " + sourcePackageName); 16771 res.origPermission = perm.info.name; 16772 res.origPackage = sourcePackageName; 16773 return; 16774 } else { 16775 Slog.w(TAG, "Package " + pkg.packageName 16776 + " attempting to redeclare system permission " 16777 + perm.info.name + "; ignoring new declaration"); 16778 pkg.permissions.remove(i); 16779 } 16780 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 16781 // Prevent apps to change protection level to dangerous from any other 16782 // type as this would allow a privilege escalation where an app adds a 16783 // normal/signature permission in other app's group and later redefines 16784 // it as dangerous leading to the group auto-grant. 16785 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 16786 == PermissionInfo.PROTECTION_DANGEROUS) { 16787 if (bp != null && !bp.isRuntime()) { 16788 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 16789 + "non-runtime permission " + perm.info.name 16790 + " to runtime; keeping old protection level"); 16791 perm.info.protectionLevel = bp.getProtectionLevel(); 16792 } 16793 } 16794 } 16795 } 16796 } 16797 } 16798 16799 if (systemApp) { 16800 if (onExternal) { 16801 // Abort update; system app can't be replaced with app on sdcard 16802 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16803 "Cannot install updates to system apps on sdcard"); 16804 return; 16805 } else if (instantApp) { 16806 // Abort update; system app can't be replaced with an instant app 16807 res.setError(INSTALL_FAILED_INSTANT_APP_INVALID, 16808 "Cannot update a system app with an instant app"); 16809 return; 16810 } 16811 } 16812 16813 if (args.move != null) { 16814 // We did an in-place move, so dex is ready to roll 16815 scanFlags |= SCAN_NO_DEX; 16816 scanFlags |= SCAN_MOVE; 16817 16818 synchronized (mPackages) { 16819 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16820 if (ps == null) { 16821 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 16822 "Missing settings for moved package " + pkgName); 16823 } 16824 16825 // We moved the entire application as-is, so bring over the 16826 // previously derived ABI information. 16827 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 16828 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 16829 } 16830 16831 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 16832 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 16833 scanFlags |= SCAN_NO_DEX; 16834 16835 try { 16836 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 16837 args.abiOverride : pkg.cpuAbiOverride); 16838 final boolean extractNativeLibs = !pkg.isLibrary(); 16839 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 16840 } catch (PackageManagerException pme) { 16841 Slog.e(TAG, "Error deriving application ABI", pme); 16842 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 16843 return; 16844 } 16845 16846 // Shared libraries for the package need to be updated. 16847 synchronized (mPackages) { 16848 try { 16849 updateSharedLibrariesLPr(pkg, null); 16850 } catch (PackageManagerException e) { 16851 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 16852 } 16853 } 16854 } 16855 16856 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 16857 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 16858 return; 16859 } 16860 16861 if (!instantApp) { 16862 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 16863 } else { 16864 if (DEBUG_DOMAIN_VERIFICATION) { 16865 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 16866 } 16867 } 16868 16869 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 16870 "installPackageLI")) { 16871 if (replace) { 16872 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16873 // Static libs have a synthetic package name containing the version 16874 // and cannot be updated as an update would get a new package name, 16875 // unless this is the exact same version code which is useful for 16876 // development. 16877 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 16878 if (existingPkg != null && 16879 existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 16880 res.setError(INSTALL_FAILED_DUPLICATE_PACKAGE, "Packages declaring " 16881 + "static-shared libs cannot be updated"); 16882 return; 16883 } 16884 } 16885 replacePackageLIF(pkg, parseFlags, scanFlags, args.user, 16886 installerPackageName, res, args.installReason); 16887 } else { 16888 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 16889 args.user, installerPackageName, volumeUuid, res, args.installReason); 16890 } 16891 } 16892 16893 // Check whether we need to dexopt the app. 16894 // 16895 // NOTE: it is IMPORTANT to call dexopt: 16896 // - after doRename which will sync the package data from PackageParser.Package and its 16897 // corresponding ApplicationInfo. 16898 // - after installNewPackageLIF or replacePackageLIF which will update result with the 16899 // uid of the application (pkg.applicationInfo.uid). 16900 // This update happens in place! 16901 // 16902 // We only need to dexopt if the package meets ALL of the following conditions: 16903 // 1) it is not forward locked. 16904 // 2) it is not on on an external ASEC container. 16905 // 3) it is not an instant app or if it is then dexopt is enabled via gservices. 16906 // 16907 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16908 // complete, so we skip this step during installation. Instead, we'll take extra time 16909 // the first time the instant app starts. It's preferred to do it this way to provide 16910 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16911 // middle of running an instant app. The default behaviour can be overridden 16912 // via gservices. 16913 final boolean performDexopt = (res.returnCode == PackageManager.INSTALL_SUCCEEDED) 16914 && !forwardLocked 16915 && !pkg.applicationInfo.isExternalAsec() 16916 && (!instantApp || Global.getInt(mContext.getContentResolver(), 16917 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0); 16918 16919 if (performDexopt) { 16920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16921 // Do not run PackageDexOptimizer through the local performDexOpt 16922 // method because `pkg` may not be in `mPackages` yet. 16923 // 16924 // Also, don't fail application installs if the dexopt step fails. 16925 DexoptOptions dexoptOptions = new DexoptOptions(pkg.packageName, 16926 REASON_INSTALL, 16927 DexoptOptions.DEXOPT_BOOT_COMPLETE); 16928 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 16929 null /* instructionSets */, 16930 getOrCreateCompilerPackageStats(pkg), 16931 mDexManager.getPackageUseInfoOrDefault(pkg.packageName), 16932 dexoptOptions); 16933 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16934 } 16935 16936 // Notify BackgroundDexOptService that the package has been changed. 16937 // If this is an update of a package which used to fail to compile, 16938 // BackgroundDexOptService will remove it from its blacklist. 16939 // TODO: Layering violation 16940 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 16941 16942 synchronized (mPackages) { 16943 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16944 if (ps != null) { 16945 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16946 ps.setUpdateAvailable(false /*updateAvailable*/); 16947 } 16948 16949 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16950 for (int i = 0; i < childCount; i++) { 16951 PackageParser.Package childPkg = pkg.childPackages.get(i); 16952 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 16953 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16954 if (childPs != null) { 16955 childRes.newUsers = childPs.queryInstalledUsers( 16956 sUserManager.getUserIds(), true); 16957 } 16958 } 16959 16960 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16961 updateSequenceNumberLP(ps, res.newUsers); 16962 updateInstantAppInstallerLocked(pkgName); 16963 } 16964 } 16965 } 16966 16967 private void startIntentFilterVerifications(int userId, boolean replacing, 16968 PackageParser.Package pkg) { 16969 if (mIntentFilterVerifierComponent == null) { 16970 Slog.w(TAG, "No IntentFilter verification will not be done as " 16971 + "there is no IntentFilterVerifier available!"); 16972 return; 16973 } 16974 16975 final int verifierUid = getPackageUid( 16976 mIntentFilterVerifierComponent.getPackageName(), 16977 MATCH_DEBUG_TRIAGED_MISSING, 16978 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 16979 16980 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16981 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 16982 mHandler.sendMessage(msg); 16983 16984 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16985 for (int i = 0; i < childCount; i++) { 16986 PackageParser.Package childPkg = pkg.childPackages.get(i); 16987 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 16988 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 16989 mHandler.sendMessage(msg); 16990 } 16991 } 16992 16993 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 16994 PackageParser.Package pkg) { 16995 int size = pkg.activities.size(); 16996 if (size == 0) { 16997 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 16998 "No activity, so no need to verify any IntentFilter!"); 16999 return; 17000 } 17001 17002 final boolean hasDomainURLs = hasDomainURLs(pkg); 17003 if (!hasDomainURLs) { 17004 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17005 "No domain URLs, so no need to verify any IntentFilter!"); 17006 return; 17007 } 17008 17009 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17010 + " if any IntentFilter from the " + size 17011 + " Activities needs verification ..."); 17012 17013 int count = 0; 17014 final String packageName = pkg.packageName; 17015 17016 synchronized (mPackages) { 17017 // If this is a new install and we see that we've already run verification for this 17018 // package, we have nothing to do: it means the state was restored from backup. 17019 if (!replacing) { 17020 IntentFilterVerificationInfo ivi = 17021 mSettings.getIntentFilterVerificationLPr(packageName); 17022 if (ivi != null) { 17023 if (DEBUG_DOMAIN_VERIFICATION) { 17024 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17025 + ivi.getStatusString()); 17026 } 17027 return; 17028 } 17029 } 17030 17031 // If any filters need to be verified, then all need to be. 17032 boolean needToVerify = false; 17033 for (PackageParser.Activity a : pkg.activities) { 17034 for (ActivityIntentInfo filter : a.intents) { 17035 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17036 if (DEBUG_DOMAIN_VERIFICATION) { 17037 Slog.d(TAG, 17038 "Intent filter needs verification, so processing all filters"); 17039 } 17040 needToVerify = true; 17041 break; 17042 } 17043 } 17044 } 17045 17046 if (needToVerify) { 17047 final int verificationId = mIntentFilterVerificationToken++; 17048 for (PackageParser.Activity a : pkg.activities) { 17049 for (ActivityIntentInfo filter : a.intents) { 17050 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 17051 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17052 "Verification needed for IntentFilter:" + filter.toString()); 17053 mIntentFilterVerifier.addOneIntentFilterVerification( 17054 verifierUid, userId, verificationId, filter, packageName); 17055 count++; 17056 } 17057 } 17058 } 17059 } 17060 } 17061 17062 if (count > 0) { 17063 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17064 + " IntentFilter verification" + (count > 1 ? "s" : "") 17065 + " for userId:" + userId); 17066 mIntentFilterVerifier.startVerifications(userId); 17067 } else { 17068 if (DEBUG_DOMAIN_VERIFICATION) { 17069 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17070 } 17071 } 17072 } 17073 17074 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17075 final ComponentName cn = filter.activity.getComponentName(); 17076 final String packageName = cn.getPackageName(); 17077 17078 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17079 packageName); 17080 if (ivi == null) { 17081 return true; 17082 } 17083 int status = ivi.getStatus(); 17084 switch (status) { 17085 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17086 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17087 return true; 17088 17089 default: 17090 // Nothing to do 17091 return false; 17092 } 17093 } 17094 17095 private static boolean isMultiArch(ApplicationInfo info) { 17096 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 17097 } 17098 17099 private static boolean isExternal(PackageParser.Package pkg) { 17100 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17101 } 17102 17103 private static boolean isExternal(PackageSetting ps) { 17104 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17105 } 17106 17107 private static boolean isSystemApp(PackageParser.Package pkg) { 17108 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17109 } 17110 17111 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17112 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17113 } 17114 17115 private static boolean isOemApp(PackageParser.Package pkg) { 17116 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17117 } 17118 17119 private static boolean isVendorApp(PackageParser.Package pkg) { 17120 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17121 } 17122 17123 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17124 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17125 } 17126 17127 private static boolean isSystemApp(PackageSetting ps) { 17128 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17129 } 17130 17131 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17132 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17133 } 17134 17135 private int packageFlagsToInstallFlags(PackageSetting ps) { 17136 int installFlags = 0; 17137 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 17138 // This existing package was an external ASEC install when we have 17139 // the external flag without a UUID 17140 installFlags |= PackageManager.INSTALL_EXTERNAL; 17141 } 17142 if (ps.isForwardLocked()) { 17143 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 17144 } 17145 return installFlags; 17146 } 17147 17148 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17149 if (isExternal(pkg)) { 17150 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17151 return mSettings.getExternalVersion(); 17152 } else { 17153 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17154 } 17155 } else { 17156 return mSettings.getInternalVersion(); 17157 } 17158 } 17159 17160 private void deleteTempPackageFiles() { 17161 final FilenameFilter filter = new FilenameFilter() { 17162 public boolean accept(File dir, String name) { 17163 return name.startsWith("vmdl") && name.endsWith(".tmp"); 17164 } 17165 }; 17166 for (File file : sDrmAppPrivateInstallDir.listFiles(filter)) { 17167 file.delete(); 17168 } 17169 } 17170 17171 @Override 17172 public void deletePackageAsUser(String packageName, int versionCode, 17173 IPackageDeleteObserver observer, int userId, int flags) { 17174 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17175 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17176 } 17177 17178 @Override 17179 public void deletePackageVersioned(VersionedPackage versionedPackage, 17180 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17181 final int callingUid = Binder.getCallingUid(); 17182 mContext.enforceCallingOrSelfPermission( 17183 android.Manifest.permission.DELETE_PACKAGES, null); 17184 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17185 Preconditions.checkNotNull(versionedPackage); 17186 Preconditions.checkNotNull(observer); 17187 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17188 PackageManager.VERSION_CODE_HIGHEST, 17189 Long.MAX_VALUE, "versionCode must be >= -1"); 17190 17191 final String packageName = versionedPackage.getPackageName(); 17192 final long versionCode = versionedPackage.getLongVersionCode(); 17193 final String internalPackageName; 17194 synchronized (mPackages) { 17195 // Normalize package name to handle renamed packages and static libs 17196 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17197 } 17198 17199 final int uid = Binder.getCallingUid(); 17200 if (!isOrphaned(internalPackageName) 17201 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17202 try { 17203 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17204 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17205 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17206 observer.onUserActionRequired(intent); 17207 } catch (RemoteException re) { 17208 } 17209 return; 17210 } 17211 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17212 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 17213 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17214 mContext.enforceCallingOrSelfPermission( 17215 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17216 "deletePackage for user " + userId); 17217 } 17218 17219 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17220 try { 17221 observer.onPackageDeleted(packageName, 17222 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17223 } catch (RemoteException re) { 17224 } 17225 return; 17226 } 17227 17228 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17229 try { 17230 observer.onPackageDeleted(packageName, 17231 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17232 } catch (RemoteException re) { 17233 } 17234 return; 17235 } 17236 17237 if (DEBUG_REMOVE) { 17238 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17239 + " deleteAllUsers: " + deleteAllUsers + " version=" 17240 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17241 ? "VERSION_CODE_HIGHEST" : versionCode)); 17242 } 17243 // Queue up an async operation since the package deletion may take a little while. 17244 mHandler.post(new Runnable() { 17245 public void run() { 17246 mHandler.removeCallbacks(this); 17247 int returnCode; 17248 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17249 boolean doDeletePackage = true; 17250 if (ps != null) { 17251 final boolean targetIsInstantApp = 17252 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17253 doDeletePackage = !targetIsInstantApp 17254 || canViewInstantApps; 17255 } 17256 if (doDeletePackage) { 17257 if (!deleteAllUsers) { 17258 returnCode = deletePackageX(internalPackageName, versionCode, 17259 userId, deleteFlags); 17260 } else { 17261 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17262 internalPackageName, users); 17263 // If nobody is blocking uninstall, proceed with delete for all users 17264 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17265 returnCode = deletePackageX(internalPackageName, versionCode, 17266 userId, deleteFlags); 17267 } else { 17268 // Otherwise uninstall individually for users with blockUninstalls=false 17269 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17270 for (int userId : users) { 17271 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 17272 returnCode = deletePackageX(internalPackageName, versionCode, 17273 userId, userFlags); 17274 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17275 Slog.w(TAG, "Package delete failed for user " + userId 17276 + ", returnCode " + returnCode); 17277 } 17278 } 17279 } 17280 // The app has only been marked uninstalled for certain users. 17281 // We still need to report that delete was blocked 17282 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17283 } 17284 } 17285 } else { 17286 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17287 } 17288 try { 17289 observer.onPackageDeleted(packageName, returnCode, null); 17290 } catch (RemoteException e) { 17291 Log.i(TAG, "Observer no longer exists."); 17292 } //end catch 17293 } //end run 17294 }); 17295 } 17296 17297 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17298 if (pkg.staticSharedLibName != null) { 17299 return pkg.manifestPackageName; 17300 } 17301 return pkg.packageName; 17302 } 17303 17304 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17305 // Handle renamed packages 17306 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17307 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17308 17309 // Is this a static library? 17310 LongSparseArray<SharedLibraryEntry> versionedLib = 17311 mStaticLibsByDeclaringPackage.get(packageName); 17312 if (versionedLib == null || versionedLib.size() <= 0) { 17313 return packageName; 17314 } 17315 17316 // Figure out which lib versions the caller can see 17317 LongSparseLongArray versionsCallerCanSee = null; 17318 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17319 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17320 && callingAppId != Process.ROOT_UID) { 17321 versionsCallerCanSee = new LongSparseLongArray(); 17322 String libName = versionedLib.valueAt(0).info.getName(); 17323 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17324 if (uidPackages != null) { 17325 for (String uidPackage : uidPackages) { 17326 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17327 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17328 if (libIdx >= 0) { 17329 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17330 versionsCallerCanSee.append(libVersion, libVersion); 17331 } 17332 } 17333 } 17334 } 17335 17336 // Caller can see nothing - done 17337 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17338 return packageName; 17339 } 17340 17341 // Find the version the caller can see and the app version code 17342 SharedLibraryEntry highestVersion = null; 17343 final int versionCount = versionedLib.size(); 17344 for (int i = 0; i < versionCount; i++) { 17345 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 17346 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17347 libEntry.info.getLongVersion()) < 0) { 17348 continue; 17349 } 17350 final long libVersionCode = libEntry.info.getDeclaringPackage().getLongVersionCode(); 17351 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17352 if (libVersionCode == versionCode) { 17353 return libEntry.apk; 17354 } 17355 } else if (highestVersion == null) { 17356 highestVersion = libEntry; 17357 } else if (libVersionCode > highestVersion.info 17358 .getDeclaringPackage().getLongVersionCode()) { 17359 highestVersion = libEntry; 17360 } 17361 } 17362 17363 if (highestVersion != null) { 17364 return highestVersion.apk; 17365 } 17366 17367 return packageName; 17368 } 17369 17370 boolean isCallerVerifier(int callingUid) { 17371 final int callingUserId = UserHandle.getUserId(callingUid); 17372 return mRequiredVerifierPackage != null && 17373 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17374 } 17375 17376 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17377 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17378 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17379 return true; 17380 } 17381 final int callingUserId = UserHandle.getUserId(callingUid); 17382 // If the caller installed the pkgName, then allow it to silently uninstall. 17383 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17384 return true; 17385 } 17386 17387 // Allow package verifier to silently uninstall. 17388 if (mRequiredVerifierPackage != null && 17389 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17390 return true; 17391 } 17392 17393 // Allow package uninstaller to silently uninstall. 17394 if (mRequiredUninstallerPackage != null && 17395 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17396 return true; 17397 } 17398 17399 // Allow storage manager to silently uninstall. 17400 if (mStorageManagerPackage != null && 17401 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17402 return true; 17403 } 17404 17405 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17406 // uninstall for device owner provisioning. 17407 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17408 == PERMISSION_GRANTED) { 17409 return true; 17410 } 17411 17412 return false; 17413 } 17414 17415 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17416 int[] result = EMPTY_INT_ARRAY; 17417 for (int userId : userIds) { 17418 if (getBlockUninstallForUser(packageName, userId)) { 17419 result = ArrayUtils.appendInt(result, userId); 17420 } 17421 } 17422 return result; 17423 } 17424 17425 @Override 17426 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17427 final int callingUid = Binder.getCallingUid(); 17428 if (getInstantAppPackageName(callingUid) != null 17429 && !isCallerSameApp(packageName, callingUid)) { 17430 return false; 17431 } 17432 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 17433 } 17434 17435 private boolean isPackageDeviceAdmin(String packageName, int userId) { 17436 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 17437 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 17438 try { 17439 if (dpm != null) { 17440 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 17441 /* callingUserOnly =*/ false); 17442 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 17443 : deviceOwnerComponentName.getPackageName(); 17444 // Does the package contains the device owner? 17445 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 17446 // this check is probably not needed, since DO should be registered as a device 17447 // admin on some user too. (Original bug for this: b/17657954) 17448 if (packageName.equals(deviceOwnerPackageName)) { 17449 return true; 17450 } 17451 // Does it contain a device admin for any user? 17452 int[] users; 17453 if (userId == UserHandle.USER_ALL) { 17454 users = sUserManager.getUserIds(); 17455 } else { 17456 users = new int[]{userId}; 17457 } 17458 for (int i = 0; i < users.length; ++i) { 17459 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 17460 return true; 17461 } 17462 } 17463 } 17464 } catch (RemoteException e) { 17465 } 17466 return false; 17467 } 17468 17469 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 17470 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 17471 } 17472 17473 /** 17474 * This method is an internal method that could be get invoked either 17475 * to delete an installed package or to clean up a failed installation. 17476 * After deleting an installed package, a broadcast is sent to notify any 17477 * listeners that the package has been removed. For cleaning up a failed 17478 * installation, the broadcast is not necessary since the package's 17479 * installation wouldn't have sent the initial broadcast either 17480 * The key steps in deleting a package are 17481 * deleting the package information in internal structures like mPackages, 17482 * deleting the packages base directories through installd 17483 * updating mSettings to reflect current status 17484 * persisting settings for later use 17485 * sending a broadcast if necessary 17486 */ 17487 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 17488 final PackageRemovedInfo info = new PackageRemovedInfo(this); 17489 final boolean res; 17490 17491 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 17492 ? UserHandle.USER_ALL : userId; 17493 17494 if (isPackageDeviceAdmin(packageName, removeUser)) { 17495 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 17496 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 17497 } 17498 17499 PackageSetting uninstalledPs = null; 17500 PackageParser.Package pkg = null; 17501 17502 // for the uninstall-updates case and restricted profiles, remember the per- 17503 // user handle installed state 17504 int[] allUsers; 17505 synchronized (mPackages) { 17506 uninstalledPs = mSettings.mPackages.get(packageName); 17507 if (uninstalledPs == null) { 17508 Slog.w(TAG, "Not removing non-existent package " + packageName); 17509 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17510 } 17511 17512 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 17513 && uninstalledPs.versionCode != versionCode) { 17514 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 17515 + uninstalledPs.versionCode + " != " + versionCode); 17516 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17517 } 17518 17519 // Static shared libs can be declared by any package, so let us not 17520 // allow removing a package if it provides a lib others depend on. 17521 pkg = mPackages.get(packageName); 17522 17523 allUsers = sUserManager.getUserIds(); 17524 17525 if (pkg != null && pkg.staticSharedLibName != null) { 17526 SharedLibraryEntry libEntry = getSharedLibraryEntryLPr(pkg.staticSharedLibName, 17527 pkg.staticSharedLibVersion); 17528 if (libEntry != null) { 17529 for (int currUserId : allUsers) { 17530 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 17531 continue; 17532 } 17533 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 17534 libEntry.info, 0, currUserId); 17535 if (!ArrayUtils.isEmpty(libClientPackages)) { 17536 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 17537 + " hosting lib " + libEntry.info.getName() + " version " 17538 + libEntry.info.getLongVersion() + " used by " + libClientPackages 17539 + " for user " + currUserId); 17540 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 17541 } 17542 } 17543 } 17544 } 17545 17546 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 17547 } 17548 17549 final int freezeUser; 17550 if (isUpdatedSystemApp(uninstalledPs) 17551 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 17552 // We're downgrading a system app, which will apply to all users, so 17553 // freeze them all during the downgrade 17554 freezeUser = UserHandle.USER_ALL; 17555 } else { 17556 freezeUser = removeUser; 17557 } 17558 17559 synchronized (mInstallLock) { 17560 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 17561 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 17562 deleteFlags, "deletePackageX")) { 17563 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 17564 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 17565 } 17566 synchronized (mPackages) { 17567 if (res) { 17568 if (pkg != null) { 17569 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 17570 } 17571 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 17572 updateInstantAppInstallerLocked(packageName); 17573 } 17574 } 17575 } 17576 17577 if (res) { 17578 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 17579 info.sendPackageRemovedBroadcasts(killApp); 17580 info.sendSystemPackageUpdatedBroadcasts(); 17581 info.sendSystemPackageAppearedBroadcasts(); 17582 } 17583 // Force a gc here. 17584 Runtime.getRuntime().gc(); 17585 // Delete the resources here after sending the broadcast to let 17586 // other processes clean up before deleting resources. 17587 if (info.args != null) { 17588 synchronized (mInstallLock) { 17589 info.args.doPostDeleteLI(true); 17590 } 17591 } 17592 17593 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17594 } 17595 17596 static class PackageRemovedInfo { 17597 final PackageSender packageSender; 17598 String removedPackage; 17599 String installerPackageName; 17600 int uid = -1; 17601 int removedAppId = -1; 17602 int[] origUsers; 17603 int[] removedUsers = null; 17604 int[] broadcastUsers = null; 17605 int[] instantUserIds = null; 17606 SparseArray<Integer> installReasons; 17607 boolean isRemovedPackageSystemUpdate = false; 17608 boolean isUpdate; 17609 boolean dataRemoved; 17610 boolean removedForAllUsers; 17611 boolean isStaticSharedLib; 17612 // Clean up resources deleted packages. 17613 InstallArgs args = null; 17614 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 17615 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 17616 17617 PackageRemovedInfo(PackageSender packageSender) { 17618 this.packageSender = packageSender; 17619 } 17620 17621 void sendPackageRemovedBroadcasts(boolean killApp) { 17622 sendPackageRemovedBroadcastInternal(killApp); 17623 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 17624 for (int i = 0; i < childCount; i++) { 17625 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17626 childInfo.sendPackageRemovedBroadcastInternal(killApp); 17627 } 17628 } 17629 17630 void sendSystemPackageUpdatedBroadcasts() { 17631 if (isRemovedPackageSystemUpdate) { 17632 sendSystemPackageUpdatedBroadcastsInternal(); 17633 final int childCount = (removedChildPackages != null) 17634 ? removedChildPackages.size() : 0; 17635 for (int i = 0; i < childCount; i++) { 17636 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 17637 if (childInfo.isRemovedPackageSystemUpdate) { 17638 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 17639 } 17640 } 17641 } 17642 } 17643 17644 void sendSystemPackageAppearedBroadcasts() { 17645 final int packageCount = (appearedChildPackages != null) 17646 ? appearedChildPackages.size() : 0; 17647 for (int i = 0; i < packageCount; i++) { 17648 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 17649 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 17650 true /*sendBootCompleted*/, false /*startReceiver*/, 17651 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 17652 } 17653 } 17654 17655 private void sendSystemPackageUpdatedBroadcastsInternal() { 17656 Bundle extras = new Bundle(2); 17657 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17658 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17659 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17660 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17661 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17662 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 17663 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 17664 null, null, 0, removedPackage, null, null, null); 17665 if (installerPackageName != null) { 17666 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 17667 removedPackage, extras, 0 /*flags*/, 17668 installerPackageName, null, null, null); 17669 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 17670 removedPackage, extras, 0 /*flags*/, 17671 installerPackageName, null, null, null); 17672 } 17673 } 17674 17675 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 17676 // Don't send static shared library removal broadcasts as these 17677 // libs are visible only the the apps that depend on them an one 17678 // cannot remove the library if it has a dependency. 17679 if (isStaticSharedLib) { 17680 return; 17681 } 17682 Bundle extras = new Bundle(2); 17683 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 17684 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 17685 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 17686 if (isUpdate || isRemovedPackageSystemUpdate) { 17687 extras.putBoolean(Intent.EXTRA_REPLACING, true); 17688 } 17689 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 17690 if (removedPackage != null) { 17691 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17692 removedPackage, extras, 0, null /*targetPackage*/, null, 17693 broadcastUsers, instantUserIds); 17694 if (installerPackageName != null) { 17695 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 17696 removedPackage, extras, 0 /*flags*/, 17697 installerPackageName, null, broadcastUsers, instantUserIds); 17698 } 17699 if (dataRemoved && !isRemovedPackageSystemUpdate) { 17700 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 17701 removedPackage, extras, 17702 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17703 null, null, broadcastUsers, instantUserIds); 17704 packageSender.notifyPackageRemoved(removedPackage); 17705 } 17706 } 17707 if (removedAppId >= 0) { 17708 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 17709 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 17710 null, null, broadcastUsers, instantUserIds); 17711 } 17712 } 17713 17714 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 17715 removedUsers = userIds; 17716 if (removedUsers == null) { 17717 broadcastUsers = null; 17718 return; 17719 } 17720 17721 broadcastUsers = EMPTY_INT_ARRAY; 17722 instantUserIds = EMPTY_INT_ARRAY; 17723 for (int i = userIds.length - 1; i >= 0; --i) { 17724 final int userId = userIds[i]; 17725 if (deletedPackageSetting.getInstantApp(userId)) { 17726 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 17727 } else { 17728 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 17729 } 17730 } 17731 } 17732 } 17733 17734 /* 17735 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 17736 * flag is not set, the data directory is removed as well. 17737 * make sure this flag is set for partially installed apps. If not its meaningless to 17738 * delete a partially installed application. 17739 */ 17740 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 17741 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 17742 String packageName = ps.name; 17743 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 17744 // Retrieve object to delete permissions for shared user later on 17745 final PackageParser.Package deletedPkg; 17746 final PackageSetting deletedPs; 17747 // reader 17748 synchronized (mPackages) { 17749 deletedPkg = mPackages.get(packageName); 17750 deletedPs = mSettings.mPackages.get(packageName); 17751 if (outInfo != null) { 17752 outInfo.removedPackage = packageName; 17753 outInfo.installerPackageName = ps.installerPackageName; 17754 outInfo.isStaticSharedLib = deletedPkg != null 17755 && deletedPkg.staticSharedLibName != null; 17756 outInfo.populateUsers(deletedPs == null ? null 17757 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 17758 } 17759 } 17760 17761 removePackageLI(ps, (flags & PackageManager.DELETE_CHATTY) != 0); 17762 17763 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 17764 final PackageParser.Package resolvedPkg; 17765 if (deletedPkg != null) { 17766 resolvedPkg = deletedPkg; 17767 } else { 17768 // We don't have a parsed package when it lives on an ejected 17769 // adopted storage device, so fake something together 17770 resolvedPkg = new PackageParser.Package(ps.name); 17771 resolvedPkg.setVolumeUuid(ps.volumeUuid); 17772 } 17773 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 17774 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 17775 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 17776 if (outInfo != null) { 17777 outInfo.dataRemoved = true; 17778 } 17779 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 17780 } 17781 17782 int removedAppId = -1; 17783 17784 // writer 17785 synchronized (mPackages) { 17786 boolean installedStateChanged = false; 17787 if (deletedPs != null) { 17788 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 17789 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 17790 clearDefaultBrowserIfNeeded(packageName); 17791 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 17792 removedAppId = mSettings.removePackageLPw(packageName); 17793 if (outInfo != null) { 17794 outInfo.removedAppId = removedAppId; 17795 } 17796 mPermissionManager.updatePermissions( 17797 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 17798 if (deletedPs.sharedUser != null) { 17799 // Remove permissions associated with package. Since runtime 17800 // permissions are per user we have to kill the removed package 17801 // or packages running under the shared user of the removed 17802 // package if revoking the permissions requested only by the removed 17803 // package is successful and this causes a change in gids. 17804 for (int userId : UserManagerService.getInstance().getUserIds()) { 17805 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 17806 userId); 17807 if (userIdToKill == UserHandle.USER_ALL 17808 || userIdToKill >= UserHandle.USER_SYSTEM) { 17809 // If gids changed for this user, kill all affected packages. 17810 mHandler.post(new Runnable() { 17811 @Override 17812 public void run() { 17813 // This has to happen with no lock held. 17814 killApplication(deletedPs.name, deletedPs.appId, 17815 KILL_APP_REASON_GIDS_CHANGED); 17816 } 17817 }); 17818 break; 17819 } 17820 } 17821 } 17822 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 17823 } 17824 // make sure to preserve per-user disabled state if this removal was just 17825 // a downgrade of a system app to the factory package 17826 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 17827 if (DEBUG_REMOVE) { 17828 Slog.d(TAG, "Propagating install state across downgrade"); 17829 } 17830 for (int userId : allUserHandles) { 17831 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 17832 if (DEBUG_REMOVE) { 17833 Slog.d(TAG, " user " + userId + " => " + installed); 17834 } 17835 if (installed != ps.getInstalled(userId)) { 17836 installedStateChanged = true; 17837 } 17838 ps.setInstalled(installed, userId); 17839 } 17840 } 17841 } 17842 // can downgrade to reader 17843 if (writeSettings) { 17844 // Save settings now 17845 mSettings.writeLPr(); 17846 } 17847 if (installedStateChanged) { 17848 mSettings.writeKernelMappingLPr(ps); 17849 } 17850 } 17851 if (removedAppId != -1) { 17852 // A user ID was deleted here. Go through all users and remove it 17853 // from KeyStore. 17854 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 17855 } 17856 } 17857 17858 static boolean locationIsPrivileged(String path) { 17859 try { 17860 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 17861 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 17862 return path.startsWith(privilegedAppDir.getCanonicalPath()) 17863 || path.startsWith(privilegedVendorAppDir.getCanonicalPath()); 17864 } catch (IOException e) { 17865 Slog.e(TAG, "Unable to access code path " + path); 17866 } 17867 return false; 17868 } 17869 17870 static boolean locationIsOem(String path) { 17871 try { 17872 return path.startsWith(Environment.getOemDirectory().getCanonicalPath()); 17873 } catch (IOException e) { 17874 Slog.e(TAG, "Unable to access code path " + path); 17875 } 17876 return false; 17877 } 17878 17879 static boolean locationIsVendor(String path) { 17880 try { 17881 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath()); 17882 } catch (IOException e) { 17883 Slog.e(TAG, "Unable to access code path " + path); 17884 } 17885 return false; 17886 } 17887 17888 /* 17889 * Tries to delete system package. 17890 */ 17891 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 17892 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 17893 boolean writeSettings) { 17894 if (deletedPs.parentPackageName != null) { 17895 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 17896 return false; 17897 } 17898 17899 final boolean applyUserRestrictions 17900 = (allUserHandles != null) && (outInfo.origUsers != null); 17901 final PackageSetting disabledPs; 17902 // Confirm if the system package has been updated 17903 // An updated system app can be deleted. This will also have to restore 17904 // the system pkg from system partition 17905 // reader 17906 synchronized (mPackages) { 17907 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 17908 } 17909 17910 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 17911 + " disabledPs=" + disabledPs); 17912 17913 if (disabledPs == null) { 17914 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 17915 return false; 17916 } else if (DEBUG_REMOVE) { 17917 Slog.d(TAG, "Deleting system pkg from data partition"); 17918 } 17919 17920 if (DEBUG_REMOVE) { 17921 if (applyUserRestrictions) { 17922 Slog.d(TAG, "Remembering install states:"); 17923 for (int userId : allUserHandles) { 17924 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 17925 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 17926 } 17927 } 17928 } 17929 17930 // Delete the updated package 17931 outInfo.isRemovedPackageSystemUpdate = true; 17932 if (outInfo.removedChildPackages != null) { 17933 final int childCount = (deletedPs.childPackageNames != null) 17934 ? deletedPs.childPackageNames.size() : 0; 17935 for (int i = 0; i < childCount; i++) { 17936 String childPackageName = deletedPs.childPackageNames.get(i); 17937 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 17938 .contains(childPackageName)) { 17939 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 17940 childPackageName); 17941 if (childInfo != null) { 17942 childInfo.isRemovedPackageSystemUpdate = true; 17943 } 17944 } 17945 } 17946 } 17947 17948 if (disabledPs.versionCode < deletedPs.versionCode) { 17949 // Delete data for downgrades 17950 flags &= ~PackageManager.DELETE_KEEP_DATA; 17951 } else { 17952 // Preserve data by setting flag 17953 flags |= PackageManager.DELETE_KEEP_DATA; 17954 } 17955 17956 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 17957 outInfo, writeSettings, disabledPs.pkg); 17958 if (!ret) { 17959 return false; 17960 } 17961 17962 // writer 17963 synchronized (mPackages) { 17964 // NOTE: The system package always needs to be enabled; even if it's for 17965 // a compressed stub. If we don't, installing the system package fails 17966 // during scan [scanning checks the disabled packages]. We will reverse 17967 // this later, after we've "installed" the stub. 17968 // Reinstate the old system package 17969 enableSystemPackageLPw(disabledPs.pkg); 17970 // Remove any native libraries from the upgraded package. 17971 removeNativeBinariesLI(deletedPs); 17972 } 17973 17974 // Install the system package 17975 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 17976 try { 17977 installPackageFromSystemLIF(disabledPs.codePathString, false, allUserHandles, 17978 outInfo.origUsers, deletedPs.getPermissionsState(), writeSettings); 17979 } catch (PackageManagerException e) { 17980 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 17981 + e.getMessage()); 17982 return false; 17983 } finally { 17984 if (disabledPs.pkg.isStub) { 17985 mSettings.disableSystemPackageLPw(disabledPs.name, true /*replaced*/); 17986 } 17987 } 17988 return true; 17989 } 17990 17991 /** 17992 * Installs a package that's already on the system partition. 17993 */ 17994 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 17995 boolean isPrivileged, @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 17996 @Nullable PermissionsState origPermissionState, boolean writeSettings) 17997 throws PackageManagerException { 17998 @ParseFlags int parseFlags = 17999 mDefParseFlags 18000 | PackageParser.PARSE_MUST_BE_APK 18001 | PackageParser.PARSE_IS_SYSTEM_DIR; 18002 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18003 if (isPrivileged || locationIsPrivileged(codePathString)) { 18004 scanFlags |= SCAN_AS_PRIVILEGED; 18005 } 18006 if (locationIsOem(codePathString)) { 18007 scanFlags |= SCAN_AS_OEM; 18008 } 18009 if (locationIsVendor(codePathString)) { 18010 scanFlags |= SCAN_AS_VENDOR; 18011 } 18012 18013 final File codePath = new File(codePathString); 18014 final PackageParser.Package pkg = 18015 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18016 18017 try { 18018 // update shared libraries for the newly re-installed system package 18019 updateSharedLibrariesLPr(pkg, null); 18020 } catch (PackageManagerException e) { 18021 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18022 } 18023 18024 prepareAppDataAfterInstallLIF(pkg); 18025 18026 // writer 18027 synchronized (mPackages) { 18028 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18029 18030 // Propagate the permissions state as we do not want to drop on the floor 18031 // runtime permissions. The update permissions method below will take 18032 // care of removing obsolete permissions and grant install permissions. 18033 if (origPermissionState != null) { 18034 ps.getPermissionsState().copyFrom(origPermissionState); 18035 } 18036 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18037 mPermissionCallback); 18038 18039 final boolean applyUserRestrictions 18040 = (allUserHandles != null) && (origUserHandles != null); 18041 if (applyUserRestrictions) { 18042 boolean installedStateChanged = false; 18043 if (DEBUG_REMOVE) { 18044 Slog.d(TAG, "Propagating install state across reinstall"); 18045 } 18046 for (int userId : allUserHandles) { 18047 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18048 if (DEBUG_REMOVE) { 18049 Slog.d(TAG, " user " + userId + " => " + installed); 18050 } 18051 if (installed != ps.getInstalled(userId)) { 18052 installedStateChanged = true; 18053 } 18054 ps.setInstalled(installed, userId); 18055 18056 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18057 } 18058 // Regardless of writeSettings we need to ensure that this restriction 18059 // state propagation is persisted 18060 mSettings.writeAllUsersPackageRestrictionsLPr(); 18061 if (installedStateChanged) { 18062 mSettings.writeKernelMappingLPr(ps); 18063 } 18064 } 18065 // can downgrade to reader here 18066 if (writeSettings) { 18067 mSettings.writeLPr(); 18068 } 18069 } 18070 return pkg; 18071 } 18072 18073 private boolean deleteInstalledPackageLIF(PackageSetting ps, 18074 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18075 PackageRemovedInfo outInfo, boolean writeSettings, 18076 PackageParser.Package replacingPackage) { 18077 synchronized (mPackages) { 18078 if (outInfo != null) { 18079 outInfo.uid = ps.appId; 18080 } 18081 18082 if (outInfo != null && outInfo.removedChildPackages != null) { 18083 final int childCount = (ps.childPackageNames != null) 18084 ? ps.childPackageNames.size() : 0; 18085 for (int i = 0; i < childCount; i++) { 18086 String childPackageName = ps.childPackageNames.get(i); 18087 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18088 if (childPs == null) { 18089 return false; 18090 } 18091 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18092 childPackageName); 18093 if (childInfo != null) { 18094 childInfo.uid = childPs.appId; 18095 } 18096 } 18097 } 18098 } 18099 18100 // Delete package data from internal structures and also remove data if flag is set 18101 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18102 18103 // Delete the child packages data 18104 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18105 for (int i = 0; i < childCount; i++) { 18106 PackageSetting childPs; 18107 synchronized (mPackages) { 18108 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18109 } 18110 if (childPs != null) { 18111 PackageRemovedInfo childOutInfo = (outInfo != null 18112 && outInfo.removedChildPackages != null) 18113 ? outInfo.removedChildPackages.get(childPs.name) : null; 18114 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18115 && (replacingPackage != null 18116 && !replacingPackage.hasChildPackage(childPs.name)) 18117 ? flags & ~DELETE_KEEP_DATA : flags; 18118 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18119 deleteFlags, writeSettings); 18120 } 18121 } 18122 18123 // Delete application code and resources only for parent packages 18124 if (ps.parentPackageName == null) { 18125 if (deleteCodeAndResources && (outInfo != null)) { 18126 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 18127 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18128 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18129 } 18130 } 18131 18132 return true; 18133 } 18134 18135 @Override 18136 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18137 int userId) { 18138 mContext.enforceCallingOrSelfPermission( 18139 android.Manifest.permission.DELETE_PACKAGES, null); 18140 synchronized (mPackages) { 18141 // Cannot block uninstall of static shared libs as they are 18142 // considered a part of the using app (emulating static linking). 18143 // Also static libs are installed always on internal storage. 18144 PackageParser.Package pkg = mPackages.get(packageName); 18145 if (pkg != null && pkg.staticSharedLibName != null) { 18146 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18147 + " providing static shared library: " + pkg.staticSharedLibName); 18148 return false; 18149 } 18150 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18151 mSettings.writePackageRestrictionsLPr(userId); 18152 } 18153 return true; 18154 } 18155 18156 @Override 18157 public boolean getBlockUninstallForUser(String packageName, int userId) { 18158 synchronized (mPackages) { 18159 final PackageSetting ps = mSettings.mPackages.get(packageName); 18160 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18161 return false; 18162 } 18163 return mSettings.getBlockUninstallLPr(userId, packageName); 18164 } 18165 } 18166 18167 @Override 18168 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18169 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18170 synchronized (mPackages) { 18171 PackageSetting ps = mSettings.mPackages.get(packageName); 18172 if (ps == null) { 18173 Log.w(TAG, "Package doesn't exist: " + packageName); 18174 return false; 18175 } 18176 if (systemUserApp) { 18177 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18178 } else { 18179 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18180 } 18181 mSettings.writeLPr(); 18182 } 18183 return true; 18184 } 18185 18186 /* 18187 * This method handles package deletion in general 18188 */ 18189 private boolean deletePackageLIF(String packageName, UserHandle user, 18190 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18191 PackageRemovedInfo outInfo, boolean writeSettings, 18192 PackageParser.Package replacingPackage) { 18193 if (packageName == null) { 18194 Slog.w(TAG, "Attempt to delete null packageName."); 18195 return false; 18196 } 18197 18198 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18199 18200 PackageSetting ps; 18201 synchronized (mPackages) { 18202 ps = mSettings.mPackages.get(packageName); 18203 if (ps == null) { 18204 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18205 return false; 18206 } 18207 18208 if (ps.parentPackageName != null && (!isSystemApp(ps) 18209 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18210 if (DEBUG_REMOVE) { 18211 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18212 + ((user == null) ? UserHandle.USER_ALL : user)); 18213 } 18214 final int removedUserId = (user != null) ? user.getIdentifier() 18215 : UserHandle.USER_ALL; 18216 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 18217 return false; 18218 } 18219 markPackageUninstalledForUserLPw(ps, user); 18220 scheduleWritePackageRestrictionsLocked(user); 18221 return true; 18222 } 18223 } 18224 18225 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 18226 && user.getIdentifier() != UserHandle.USER_ALL)) { 18227 // The caller is asking that the package only be deleted for a single 18228 // user. To do this, we just mark its uninstalled state and delete 18229 // its data. If this is a system app, we only allow this to happen if 18230 // they have set the special DELETE_SYSTEM_APP which requests different 18231 // semantics than normal for uninstalling system apps. 18232 markPackageUninstalledForUserLPw(ps, user); 18233 18234 if (!isSystemApp(ps)) { 18235 // Do not uninstall the APK if an app should be cached 18236 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18237 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18238 // Other user still have this package installed, so all 18239 // we need to do is clear this user's data and save that 18240 // it is uninstalled. 18241 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18242 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18243 return false; 18244 } 18245 scheduleWritePackageRestrictionsLocked(user); 18246 return true; 18247 } else { 18248 // We need to set it back to 'installed' so the uninstall 18249 // broadcasts will be sent correctly. 18250 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18251 ps.setInstalled(true, user.getIdentifier()); 18252 mSettings.writeKernelMappingLPr(ps); 18253 } 18254 } else { 18255 // This is a system app, so we assume that the 18256 // other users still have this package installed, so all 18257 // we need to do is clear this user's data and save that 18258 // it is uninstalled. 18259 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18260 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 18261 return false; 18262 } 18263 scheduleWritePackageRestrictionsLocked(user); 18264 return true; 18265 } 18266 } 18267 18268 // If we are deleting a composite package for all users, keep track 18269 // of result for each child. 18270 if (ps.childPackageNames != null && outInfo != null) { 18271 synchronized (mPackages) { 18272 final int childCount = ps.childPackageNames.size(); 18273 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18274 for (int i = 0; i < childCount; i++) { 18275 String childPackageName = ps.childPackageNames.get(i); 18276 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18277 childInfo.removedPackage = childPackageName; 18278 childInfo.installerPackageName = ps.installerPackageName; 18279 outInfo.removedChildPackages.put(childPackageName, childInfo); 18280 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18281 if (childPs != null) { 18282 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18283 } 18284 } 18285 } 18286 } 18287 18288 boolean ret = false; 18289 if (isSystemApp(ps)) { 18290 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18291 // When an updated system application is deleted we delete the existing resources 18292 // as well and fall back to existing code in system partition 18293 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 18294 } else { 18295 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18296 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18297 outInfo, writeSettings, replacingPackage); 18298 } 18299 18300 // Take a note whether we deleted the package for all users 18301 if (outInfo != null) { 18302 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18303 if (outInfo.removedChildPackages != null) { 18304 synchronized (mPackages) { 18305 final int childCount = outInfo.removedChildPackages.size(); 18306 for (int i = 0; i < childCount; i++) { 18307 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18308 if (childInfo != null) { 18309 childInfo.removedForAllUsers = mPackages.get( 18310 childInfo.removedPackage) == null; 18311 } 18312 } 18313 } 18314 } 18315 // If we uninstalled an update to a system app there may be some 18316 // child packages that appeared as they are declared in the system 18317 // app but were not declared in the update. 18318 if (isSystemApp(ps)) { 18319 synchronized (mPackages) { 18320 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18321 final int childCount = (updatedPs.childPackageNames != null) 18322 ? updatedPs.childPackageNames.size() : 0; 18323 for (int i = 0; i < childCount; i++) { 18324 String childPackageName = updatedPs.childPackageNames.get(i); 18325 if (outInfo.removedChildPackages == null 18326 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 18327 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18328 if (childPs == null) { 18329 continue; 18330 } 18331 PackageInstalledInfo installRes = new PackageInstalledInfo(); 18332 installRes.name = childPackageName; 18333 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 18334 installRes.pkg = mPackages.get(childPackageName); 18335 installRes.uid = childPs.pkg.applicationInfo.uid; 18336 if (outInfo.appearedChildPackages == null) { 18337 outInfo.appearedChildPackages = new ArrayMap<>(); 18338 } 18339 outInfo.appearedChildPackages.put(childPackageName, installRes); 18340 } 18341 } 18342 } 18343 } 18344 } 18345 18346 return ret; 18347 } 18348 18349 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 18350 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 18351 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 18352 for (int nextUserId : userIds) { 18353 if (DEBUG_REMOVE) { 18354 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 18355 } 18356 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 18357 false /*installed*/, 18358 true /*stopped*/, 18359 true /*notLaunched*/, 18360 false /*hidden*/, 18361 false /*suspended*/, 18362 false /*instantApp*/, 18363 false /*virtualPreload*/, 18364 null /*lastDisableAppCaller*/, 18365 null /*enabledComponents*/, 18366 null /*disabledComponents*/, 18367 ps.readUserState(nextUserId).domainVerificationStatus, 18368 0, PackageManager.INSTALL_REASON_UNKNOWN, 18369 null /*harmfulAppWarning*/); 18370 } 18371 mSettings.writeKernelMappingLPr(ps); 18372 } 18373 18374 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 18375 PackageRemovedInfo outInfo) { 18376 final PackageParser.Package pkg; 18377 synchronized (mPackages) { 18378 pkg = mPackages.get(ps.name); 18379 } 18380 18381 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 18382 : new int[] {userId}; 18383 for (int nextUserId : userIds) { 18384 if (DEBUG_REMOVE) { 18385 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 18386 + nextUserId); 18387 } 18388 18389 destroyAppDataLIF(pkg, userId, 18390 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18391 destroyAppProfilesLIF(pkg, userId); 18392 clearDefaultBrowserIfNeededForUser(ps.name, userId); 18393 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 18394 schedulePackageCleaning(ps.name, nextUserId, false); 18395 synchronized (mPackages) { 18396 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 18397 scheduleWritePackageRestrictionsLocked(nextUserId); 18398 } 18399 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 18400 } 18401 } 18402 18403 if (outInfo != null) { 18404 outInfo.removedPackage = ps.name; 18405 outInfo.installerPackageName = ps.installerPackageName; 18406 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 18407 outInfo.removedAppId = ps.appId; 18408 outInfo.removedUsers = userIds; 18409 outInfo.broadcastUsers = userIds; 18410 } 18411 18412 return true; 18413 } 18414 18415 private final class ClearStorageConnection implements ServiceConnection { 18416 IMediaContainerService mContainerService; 18417 18418 @Override 18419 public void onServiceConnected(ComponentName name, IBinder service) { 18420 synchronized (this) { 18421 mContainerService = IMediaContainerService.Stub 18422 .asInterface(Binder.allowBlocking(service)); 18423 notifyAll(); 18424 } 18425 } 18426 18427 @Override 18428 public void onServiceDisconnected(ComponentName name) { 18429 } 18430 } 18431 18432 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 18433 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 18434 18435 final boolean mounted; 18436 if (Environment.isExternalStorageEmulated()) { 18437 mounted = true; 18438 } else { 18439 final String status = Environment.getExternalStorageState(); 18440 18441 mounted = status.equals(Environment.MEDIA_MOUNTED) 18442 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 18443 } 18444 18445 if (!mounted) { 18446 return; 18447 } 18448 18449 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 18450 int[] users; 18451 if (userId == UserHandle.USER_ALL) { 18452 users = sUserManager.getUserIds(); 18453 } else { 18454 users = new int[] { userId }; 18455 } 18456 final ClearStorageConnection conn = new ClearStorageConnection(); 18457 if (mContext.bindServiceAsUser( 18458 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 18459 try { 18460 for (int curUser : users) { 18461 long timeout = SystemClock.uptimeMillis() + 5000; 18462 synchronized (conn) { 18463 long now; 18464 while (conn.mContainerService == null && 18465 (now = SystemClock.uptimeMillis()) < timeout) { 18466 try { 18467 conn.wait(timeout - now); 18468 } catch (InterruptedException e) { 18469 } 18470 } 18471 } 18472 if (conn.mContainerService == null) { 18473 return; 18474 } 18475 18476 final UserEnvironment userEnv = new UserEnvironment(curUser); 18477 clearDirectory(conn.mContainerService, 18478 userEnv.buildExternalStorageAppCacheDirs(packageName)); 18479 if (allData) { 18480 clearDirectory(conn.mContainerService, 18481 userEnv.buildExternalStorageAppDataDirs(packageName)); 18482 clearDirectory(conn.mContainerService, 18483 userEnv.buildExternalStorageAppMediaDirs(packageName)); 18484 } 18485 } 18486 } finally { 18487 mContext.unbindService(conn); 18488 } 18489 } 18490 } 18491 18492 @Override 18493 public void clearApplicationProfileData(String packageName) { 18494 enforceSystemOrRoot("Only the system can clear all profile data"); 18495 18496 final PackageParser.Package pkg; 18497 synchronized (mPackages) { 18498 pkg = mPackages.get(packageName); 18499 } 18500 18501 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 18502 synchronized (mInstallLock) { 18503 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 18504 } 18505 } 18506 } 18507 18508 @Override 18509 public void clearApplicationUserData(final String packageName, 18510 final IPackageDataObserver observer, final int userId) { 18511 mContext.enforceCallingOrSelfPermission( 18512 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 18513 18514 final int callingUid = Binder.getCallingUid(); 18515 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18516 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 18517 18518 final PackageSetting ps = mSettings.getPackageLPr(packageName); 18519 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 18520 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 18521 throw new SecurityException("Cannot clear data for a protected package: " 18522 + packageName); 18523 } 18524 // Queue up an async operation since the package deletion may take a little while. 18525 mHandler.post(new Runnable() { 18526 public void run() { 18527 mHandler.removeCallbacks(this); 18528 final boolean succeeded; 18529 if (!filterApp) { 18530 try (PackageFreezer freezer = freezePackage(packageName, 18531 "clearApplicationUserData")) { 18532 synchronized (mInstallLock) { 18533 succeeded = clearApplicationUserDataLIF(packageName, userId); 18534 } 18535 clearExternalStorageDataSync(packageName, userId, true); 18536 synchronized (mPackages) { 18537 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 18538 packageName, userId); 18539 } 18540 } 18541 if (succeeded) { 18542 // invoke DeviceStorageMonitor's update method to clear any notifications 18543 DeviceStorageMonitorInternal dsm = LocalServices 18544 .getService(DeviceStorageMonitorInternal.class); 18545 if (dsm != null) { 18546 dsm.checkMemory(); 18547 } 18548 } 18549 } else { 18550 succeeded = false; 18551 } 18552 if (observer != null) { 18553 try { 18554 observer.onRemoveCompleted(packageName, succeeded); 18555 } catch (RemoteException e) { 18556 Log.i(TAG, "Observer no longer exists."); 18557 } 18558 } //end if observer 18559 } //end run 18560 }); 18561 } 18562 18563 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 18564 if (packageName == null) { 18565 Slog.w(TAG, "Attempt to delete null packageName."); 18566 return false; 18567 } 18568 18569 // Try finding details about the requested package 18570 PackageParser.Package pkg; 18571 synchronized (mPackages) { 18572 pkg = mPackages.get(packageName); 18573 if (pkg == null) { 18574 final PackageSetting ps = mSettings.mPackages.get(packageName); 18575 if (ps != null) { 18576 pkg = ps.pkg; 18577 } 18578 } 18579 18580 if (pkg == null) { 18581 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 18582 return false; 18583 } 18584 18585 PackageSetting ps = (PackageSetting) pkg.mExtras; 18586 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18587 } 18588 18589 clearAppDataLIF(pkg, userId, 18590 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18591 18592 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 18593 removeKeystoreDataIfNeeded(userId, appId); 18594 18595 UserManagerInternal umInternal = getUserManagerInternal(); 18596 final int flags; 18597 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 18598 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18599 } else if (umInternal.isUserRunning(userId)) { 18600 flags = StorageManager.FLAG_STORAGE_DE; 18601 } else { 18602 flags = 0; 18603 } 18604 prepareAppDataContentsLIF(pkg, userId, flags); 18605 18606 return true; 18607 } 18608 18609 /** 18610 * Reverts user permission state changes (permissions and flags) in 18611 * all packages for a given user. 18612 * 18613 * @param userId The device user for which to do a reset. 18614 */ 18615 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 18616 final int packageCount = mPackages.size(); 18617 for (int i = 0; i < packageCount; i++) { 18618 PackageParser.Package pkg = mPackages.valueAt(i); 18619 PackageSetting ps = (PackageSetting) pkg.mExtras; 18620 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 18621 } 18622 } 18623 18624 private void resetNetworkPolicies(int userId) { 18625 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 18626 } 18627 18628 /** 18629 * Reverts user permission state changes (permissions and flags). 18630 * 18631 * @param ps The package for which to reset. 18632 * @param userId The device user for which to do a reset. 18633 */ 18634 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 18635 final PackageSetting ps, final int userId) { 18636 if (ps.pkg == null) { 18637 return; 18638 } 18639 18640 // These are flags that can change base on user actions. 18641 final int userSettableMask = FLAG_PERMISSION_USER_SET 18642 | FLAG_PERMISSION_USER_FIXED 18643 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 18644 | FLAG_PERMISSION_REVIEW_REQUIRED; 18645 18646 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 18647 | FLAG_PERMISSION_POLICY_FIXED; 18648 18649 boolean writeInstallPermissions = false; 18650 boolean writeRuntimePermissions = false; 18651 18652 final int permissionCount = ps.pkg.requestedPermissions.size(); 18653 for (int i = 0; i < permissionCount; i++) { 18654 final String permName = ps.pkg.requestedPermissions.get(i); 18655 final BasePermission bp = 18656 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 18657 if (bp == null) { 18658 continue; 18659 } 18660 18661 // If shared user we just reset the state to which only this app contributed. 18662 if (ps.sharedUser != null) { 18663 boolean used = false; 18664 final int packageCount = ps.sharedUser.packages.size(); 18665 for (int j = 0; j < packageCount; j++) { 18666 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 18667 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 18668 && pkg.pkg.requestedPermissions.contains(permName)) { 18669 used = true; 18670 break; 18671 } 18672 } 18673 if (used) { 18674 continue; 18675 } 18676 } 18677 18678 final PermissionsState permissionsState = ps.getPermissionsState(); 18679 18680 final int oldFlags = permissionsState.getPermissionFlags(permName, userId); 18681 18682 // Always clear the user settable flags. 18683 final boolean hasInstallState = 18684 permissionsState.getInstallPermissionState(permName) != null; 18685 // If permission review is enabled and this is a legacy app, mark the 18686 // permission as requiring a review as this is the initial state. 18687 int flags = 0; 18688 if (mSettings.mPermissions.mPermissionReviewRequired 18689 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 18690 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 18691 } 18692 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 18693 if (hasInstallState) { 18694 writeInstallPermissions = true; 18695 } else { 18696 writeRuntimePermissions = true; 18697 } 18698 } 18699 18700 // Below is only runtime permission handling. 18701 if (!bp.isRuntime()) { 18702 continue; 18703 } 18704 18705 // Never clobber system or policy. 18706 if ((oldFlags & policyOrSystemFlags) != 0) { 18707 continue; 18708 } 18709 18710 // If this permission was granted by default, make sure it is. 18711 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 18712 if (permissionsState.grantRuntimePermission(bp, userId) 18713 != PERMISSION_OPERATION_FAILURE) { 18714 writeRuntimePermissions = true; 18715 } 18716 // If permission review is enabled the permissions for a legacy apps 18717 // are represented as constantly granted runtime ones, so don't revoke. 18718 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 18719 // Otherwise, reset the permission. 18720 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 18721 switch (revokeResult) { 18722 case PERMISSION_OPERATION_SUCCESS: 18723 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 18724 writeRuntimePermissions = true; 18725 final int appId = ps.appId; 18726 mHandler.post(new Runnable() { 18727 @Override 18728 public void run() { 18729 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 18730 } 18731 }); 18732 } break; 18733 } 18734 } 18735 } 18736 18737 // Synchronously write as we are taking permissions away. 18738 if (writeRuntimePermissions) { 18739 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 18740 } 18741 18742 // Synchronously write as we are taking permissions away. 18743 if (writeInstallPermissions) { 18744 mSettings.writeLPr(); 18745 } 18746 } 18747 18748 /** 18749 * Remove entries from the keystore daemon. Will only remove it if the 18750 * {@code appId} is valid. 18751 */ 18752 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 18753 if (appId < 0) { 18754 return; 18755 } 18756 18757 final KeyStore keyStore = KeyStore.getInstance(); 18758 if (keyStore != null) { 18759 if (userId == UserHandle.USER_ALL) { 18760 for (final int individual : sUserManager.getUserIds()) { 18761 keyStore.clearUid(UserHandle.getUid(individual, appId)); 18762 } 18763 } else { 18764 keyStore.clearUid(UserHandle.getUid(userId, appId)); 18765 } 18766 } else { 18767 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 18768 } 18769 } 18770 18771 @Override 18772 public void deleteApplicationCacheFiles(final String packageName, 18773 final IPackageDataObserver observer) { 18774 final int userId = UserHandle.getCallingUserId(); 18775 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 18776 } 18777 18778 @Override 18779 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 18780 final IPackageDataObserver observer) { 18781 final int callingUid = Binder.getCallingUid(); 18782 mContext.enforceCallingOrSelfPermission( 18783 android.Manifest.permission.DELETE_CACHE_FILES, null); 18784 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18785 /* requireFullPermission= */ true, /* checkShell= */ false, 18786 "delete application cache files"); 18787 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 18788 android.Manifest.permission.ACCESS_INSTANT_APPS); 18789 18790 final PackageParser.Package pkg; 18791 synchronized (mPackages) { 18792 pkg = mPackages.get(packageName); 18793 } 18794 18795 // Queue up an async operation since the package deletion may take a little while. 18796 mHandler.post(new Runnable() { 18797 public void run() { 18798 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 18799 boolean doClearData = true; 18800 if (ps != null) { 18801 final boolean targetIsInstantApp = 18802 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18803 doClearData = !targetIsInstantApp 18804 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 18805 } 18806 if (doClearData) { 18807 synchronized (mInstallLock) { 18808 final int flags = StorageManager.FLAG_STORAGE_DE 18809 | StorageManager.FLAG_STORAGE_CE; 18810 // We're only clearing cache files, so we don't care if the 18811 // app is unfrozen and still able to run 18812 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 18813 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18814 } 18815 clearExternalStorageDataSync(packageName, userId, false); 18816 } 18817 if (observer != null) { 18818 try { 18819 observer.onRemoveCompleted(packageName, true); 18820 } catch (RemoteException e) { 18821 Log.i(TAG, "Observer no longer exists."); 18822 } 18823 } 18824 } 18825 }); 18826 } 18827 18828 @Override 18829 public void getPackageSizeInfo(final String packageName, int userHandle, 18830 final IPackageStatsObserver observer) { 18831 throw new UnsupportedOperationException( 18832 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 18833 } 18834 18835 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 18836 final PackageSetting ps; 18837 synchronized (mPackages) { 18838 ps = mSettings.mPackages.get(packageName); 18839 if (ps == null) { 18840 Slog.w(TAG, "Failed to find settings for " + packageName); 18841 return false; 18842 } 18843 } 18844 18845 final String[] packageNames = { packageName }; 18846 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 18847 final String[] codePaths = { ps.codePathString }; 18848 18849 try { 18850 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 18851 ps.appId, ceDataInodes, codePaths, stats); 18852 18853 // For now, ignore code size of packages on system partition 18854 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 18855 stats.codeSize = 0; 18856 } 18857 18858 // External clients expect these to be tracked separately 18859 stats.dataSize -= stats.cacheSize; 18860 18861 } catch (InstallerException e) { 18862 Slog.w(TAG, String.valueOf(e)); 18863 return false; 18864 } 18865 18866 return true; 18867 } 18868 18869 private int getUidTargetSdkVersionLockedLPr(int uid) { 18870 Object obj = mSettings.getUserIdLPr(uid); 18871 if (obj instanceof SharedUserSetting) { 18872 final SharedUserSetting sus = (SharedUserSetting) obj; 18873 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 18874 final Iterator<PackageSetting> it = sus.packages.iterator(); 18875 while (it.hasNext()) { 18876 final PackageSetting ps = it.next(); 18877 if (ps.pkg != null) { 18878 int v = ps.pkg.applicationInfo.targetSdkVersion; 18879 if (v < vers) vers = v; 18880 } 18881 } 18882 return vers; 18883 } else if (obj instanceof PackageSetting) { 18884 final PackageSetting ps = (PackageSetting) obj; 18885 if (ps.pkg != null) { 18886 return ps.pkg.applicationInfo.targetSdkVersion; 18887 } 18888 } 18889 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18890 } 18891 18892 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 18893 final PackageParser.Package p = mPackages.get(packageName); 18894 if (p != null) { 18895 return p.applicationInfo.targetSdkVersion; 18896 } 18897 return Build.VERSION_CODES.CUR_DEVELOPMENT; 18898 } 18899 18900 @Override 18901 public void addPreferredActivity(IntentFilter filter, int match, 18902 ComponentName[] set, ComponentName activity, int userId) { 18903 addPreferredActivityInternal(filter, match, set, activity, true, userId, 18904 "Adding preferred"); 18905 } 18906 18907 private void addPreferredActivityInternal(IntentFilter filter, int match, 18908 ComponentName[] set, ComponentName activity, boolean always, int userId, 18909 String opname) { 18910 // writer 18911 int callingUid = Binder.getCallingUid(); 18912 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18913 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 18914 if (filter.countActions() == 0) { 18915 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 18916 return; 18917 } 18918 synchronized (mPackages) { 18919 if (mContext.checkCallingOrSelfPermission( 18920 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18921 != PackageManager.PERMISSION_GRANTED) { 18922 if (getUidTargetSdkVersionLockedLPr(callingUid) 18923 < Build.VERSION_CODES.FROYO) { 18924 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 18925 + callingUid); 18926 return; 18927 } 18928 mContext.enforceCallingOrSelfPermission( 18929 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18930 } 18931 18932 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 18933 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 18934 + userId + ":"); 18935 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 18936 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 18937 scheduleWritePackageRestrictionsLocked(userId); 18938 postPreferredActivityChangedBroadcast(userId); 18939 } 18940 } 18941 18942 private void postPreferredActivityChangedBroadcast(int userId) { 18943 mHandler.post(() -> { 18944 final IActivityManager am = ActivityManager.getService(); 18945 if (am == null) { 18946 return; 18947 } 18948 18949 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 18950 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 18951 try { 18952 am.broadcastIntent(null, intent, null, null, 18953 0, null, null, null, android.app.AppOpsManager.OP_NONE, 18954 null, false, false, userId); 18955 } catch (RemoteException e) { 18956 } 18957 }); 18958 } 18959 18960 @Override 18961 public void replacePreferredActivity(IntentFilter filter, int match, 18962 ComponentName[] set, ComponentName activity, int userId) { 18963 if (filter.countActions() != 1) { 18964 throw new IllegalArgumentException( 18965 "replacePreferredActivity expects filter to have only 1 action."); 18966 } 18967 if (filter.countDataAuthorities() != 0 18968 || filter.countDataPaths() != 0 18969 || filter.countDataSchemes() > 1 18970 || filter.countDataTypes() != 0) { 18971 throw new IllegalArgumentException( 18972 "replacePreferredActivity expects filter to have no data authorities, " + 18973 "paths, or types; and at most one scheme."); 18974 } 18975 18976 final int callingUid = Binder.getCallingUid(); 18977 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 18978 true /* requireFullPermission */, false /* checkShell */, 18979 "replace preferred activity"); 18980 synchronized (mPackages) { 18981 if (mContext.checkCallingOrSelfPermission( 18982 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 18983 != PackageManager.PERMISSION_GRANTED) { 18984 if (getUidTargetSdkVersionLockedLPr(callingUid) 18985 < Build.VERSION_CODES.FROYO) { 18986 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 18987 + Binder.getCallingUid()); 18988 return; 18989 } 18990 mContext.enforceCallingOrSelfPermission( 18991 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 18992 } 18993 18994 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 18995 if (pir != null) { 18996 // Get all of the existing entries that exactly match this filter. 18997 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 18998 if (existing != null && existing.size() == 1) { 18999 PreferredActivity cur = existing.get(0); 19000 if (DEBUG_PREFERRED) { 19001 Slog.i(TAG, "Checking replace of preferred:"); 19002 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19003 if (!cur.mPref.mAlways) { 19004 Slog.i(TAG, " -- CUR; not mAlways!"); 19005 } else { 19006 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19007 Slog.i(TAG, " -- CUR: mSet=" 19008 + Arrays.toString(cur.mPref.mSetComponents)); 19009 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19010 Slog.i(TAG, " -- NEW: mMatch=" 19011 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19012 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19013 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19014 } 19015 } 19016 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19017 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19018 && cur.mPref.sameSet(set)) { 19019 // Setting the preferred activity to what it happens to be already 19020 if (DEBUG_PREFERRED) { 19021 Slog.i(TAG, "Replacing with same preferred activity " 19022 + cur.mPref.mShortComponent + " for user " 19023 + userId + ":"); 19024 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19025 } 19026 return; 19027 } 19028 } 19029 19030 if (existing != null) { 19031 if (DEBUG_PREFERRED) { 19032 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19033 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19034 } 19035 for (int i = 0; i < existing.size(); i++) { 19036 PreferredActivity pa = existing.get(i); 19037 if (DEBUG_PREFERRED) { 19038 Slog.i(TAG, "Removing existing preferred activity " 19039 + pa.mPref.mComponent + ":"); 19040 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19041 } 19042 pir.removeFilter(pa); 19043 } 19044 } 19045 } 19046 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19047 "Replacing preferred"); 19048 } 19049 } 19050 19051 @Override 19052 public void clearPackagePreferredActivities(String packageName) { 19053 final int callingUid = Binder.getCallingUid(); 19054 if (getInstantAppPackageName(callingUid) != null) { 19055 return; 19056 } 19057 // writer 19058 synchronized (mPackages) { 19059 PackageParser.Package pkg = mPackages.get(packageName); 19060 if (pkg == null || pkg.applicationInfo.uid != callingUid) { 19061 if (mContext.checkCallingOrSelfPermission( 19062 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19063 != PackageManager.PERMISSION_GRANTED) { 19064 if (getUidTargetSdkVersionLockedLPr(callingUid) 19065 < Build.VERSION_CODES.FROYO) { 19066 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19067 + callingUid); 19068 return; 19069 } 19070 mContext.enforceCallingOrSelfPermission( 19071 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19072 } 19073 } 19074 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19075 if (ps != null 19076 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19077 return; 19078 } 19079 int user = UserHandle.getCallingUserId(); 19080 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 19081 scheduleWritePackageRestrictionsLocked(user); 19082 } 19083 } 19084 } 19085 19086 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19087 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 19088 ArrayList<PreferredActivity> removed = null; 19089 boolean changed = false; 19090 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19091 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19092 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19093 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19094 continue; 19095 } 19096 Iterator<PreferredActivity> it = pir.filterIterator(); 19097 while (it.hasNext()) { 19098 PreferredActivity pa = it.next(); 19099 // Mark entry for removal only if it matches the package name 19100 // and the entry is of type "always". 19101 if (packageName == null || 19102 (pa.mPref.mComponent.getPackageName().equals(packageName) 19103 && pa.mPref.mAlways)) { 19104 if (removed == null) { 19105 removed = new ArrayList<PreferredActivity>(); 19106 } 19107 removed.add(pa); 19108 } 19109 } 19110 if (removed != null) { 19111 for (int j=0; j<removed.size(); j++) { 19112 PreferredActivity pa = removed.get(j); 19113 pir.removeFilter(pa); 19114 } 19115 changed = true; 19116 } 19117 } 19118 if (changed) { 19119 postPreferredActivityChangedBroadcast(userId); 19120 } 19121 return changed; 19122 } 19123 19124 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19125 private void clearIntentFilterVerificationsLPw(int userId) { 19126 final int packageCount = mPackages.size(); 19127 for (int i = 0; i < packageCount; i++) { 19128 PackageParser.Package pkg = mPackages.valueAt(i); 19129 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19130 } 19131 } 19132 19133 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19134 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19135 if (userId == UserHandle.USER_ALL) { 19136 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19137 sUserManager.getUserIds())) { 19138 for (int oneUserId : sUserManager.getUserIds()) { 19139 scheduleWritePackageRestrictionsLocked(oneUserId); 19140 } 19141 } 19142 } else { 19143 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19144 scheduleWritePackageRestrictionsLocked(userId); 19145 } 19146 } 19147 } 19148 19149 /** Clears state for all users, and touches intent filter verification policy */ 19150 void clearDefaultBrowserIfNeeded(String packageName) { 19151 for (int oneUserId : sUserManager.getUserIds()) { 19152 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19153 } 19154 } 19155 19156 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19157 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19158 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19159 if (packageName.equals(defaultBrowserPackageName)) { 19160 setDefaultBrowserPackageName(null, userId); 19161 } 19162 } 19163 } 19164 19165 @Override 19166 public void resetApplicationPreferences(int userId) { 19167 mContext.enforceCallingOrSelfPermission( 19168 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19169 final long identity = Binder.clearCallingIdentity(); 19170 // writer 19171 try { 19172 synchronized (mPackages) { 19173 clearPackagePreferredActivitiesLPw(null, userId); 19174 mSettings.applyDefaultPreferredAppsLPw(this, userId); 19175 // TODO: We have to reset the default SMS and Phone. This requires 19176 // significant refactoring to keep all default apps in the package 19177 // manager (cleaner but more work) or have the services provide 19178 // callbacks to the package manager to request a default app reset. 19179 applyFactoryDefaultBrowserLPw(userId); 19180 clearIntentFilterVerificationsLPw(userId); 19181 primeDomainVerificationsLPw(userId); 19182 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19183 scheduleWritePackageRestrictionsLocked(userId); 19184 } 19185 resetNetworkPolicies(userId); 19186 } finally { 19187 Binder.restoreCallingIdentity(identity); 19188 } 19189 } 19190 19191 @Override 19192 public int getPreferredActivities(List<IntentFilter> outFilters, 19193 List<ComponentName> outActivities, String packageName) { 19194 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19195 return 0; 19196 } 19197 int num = 0; 19198 final int userId = UserHandle.getCallingUserId(); 19199 // reader 19200 synchronized (mPackages) { 19201 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19202 if (pir != null) { 19203 final Iterator<PreferredActivity> it = pir.filterIterator(); 19204 while (it.hasNext()) { 19205 final PreferredActivity pa = it.next(); 19206 if (packageName == null 19207 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19208 && pa.mPref.mAlways)) { 19209 if (outFilters != null) { 19210 outFilters.add(new IntentFilter(pa)); 19211 } 19212 if (outActivities != null) { 19213 outActivities.add(pa.mPref.mComponent); 19214 } 19215 } 19216 } 19217 } 19218 } 19219 19220 return num; 19221 } 19222 19223 @Override 19224 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19225 int userId) { 19226 int callingUid = Binder.getCallingUid(); 19227 if (callingUid != Process.SYSTEM_UID) { 19228 throw new SecurityException( 19229 "addPersistentPreferredActivity can only be run by the system"); 19230 } 19231 if (filter.countActions() == 0) { 19232 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19233 return; 19234 } 19235 synchronized (mPackages) { 19236 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 19237 ":"); 19238 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19239 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19240 new PersistentPreferredActivity(filter, activity)); 19241 scheduleWritePackageRestrictionsLocked(userId); 19242 postPreferredActivityChangedBroadcast(userId); 19243 } 19244 } 19245 19246 @Override 19247 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19248 int callingUid = Binder.getCallingUid(); 19249 if (callingUid != Process.SYSTEM_UID) { 19250 throw new SecurityException( 19251 "clearPackagePersistentPreferredActivities can only be run by the system"); 19252 } 19253 ArrayList<PersistentPreferredActivity> removed = null; 19254 boolean changed = false; 19255 synchronized (mPackages) { 19256 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19257 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19258 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19259 .valueAt(i); 19260 if (userId != thisUserId) { 19261 continue; 19262 } 19263 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19264 while (it.hasNext()) { 19265 PersistentPreferredActivity ppa = it.next(); 19266 // Mark entry for removal only if it matches the package name. 19267 if (ppa.mComponent.getPackageName().equals(packageName)) { 19268 if (removed == null) { 19269 removed = new ArrayList<PersistentPreferredActivity>(); 19270 } 19271 removed.add(ppa); 19272 } 19273 } 19274 if (removed != null) { 19275 for (int j=0; j<removed.size(); j++) { 19276 PersistentPreferredActivity ppa = removed.get(j); 19277 ppir.removeFilter(ppa); 19278 } 19279 changed = true; 19280 } 19281 } 19282 19283 if (changed) { 19284 scheduleWritePackageRestrictionsLocked(userId); 19285 postPreferredActivityChangedBroadcast(userId); 19286 } 19287 } 19288 } 19289 19290 /** 19291 * Common machinery for picking apart a restored XML blob and passing 19292 * it to a caller-supplied functor to be applied to the running system. 19293 */ 19294 private void restoreFromXml(XmlPullParser parser, int userId, 19295 String expectedStartTag, BlobXmlRestorer functor) 19296 throws IOException, XmlPullParserException { 19297 int type; 19298 while ((type = parser.next()) != XmlPullParser.START_TAG 19299 && type != XmlPullParser.END_DOCUMENT) { 19300 } 19301 if (type != XmlPullParser.START_TAG) { 19302 // oops didn't find a start tag?! 19303 if (DEBUG_BACKUP) { 19304 Slog.e(TAG, "Didn't find start tag during restore"); 19305 } 19306 return; 19307 } 19308Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 19309 // this is supposed to be TAG_PREFERRED_BACKUP 19310 if (!expectedStartTag.equals(parser.getName())) { 19311 if (DEBUG_BACKUP) { 19312 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 19313 } 19314 return; 19315 } 19316 19317 // skip interfering stuff, then we're aligned with the backing implementation 19318 while ((type = parser.next()) == XmlPullParser.TEXT) { } 19319Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 19320 functor.apply(parser, userId); 19321 } 19322 19323 private interface BlobXmlRestorer { 19324 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 19325 } 19326 19327 /** 19328 * Non-Binder method, support for the backup/restore mechanism: write the 19329 * full set of preferred activities in its canonical XML format. Returns the 19330 * XML output as a byte array, or null if there is none. 19331 */ 19332 @Override 19333 public byte[] getPreferredActivityBackup(int userId) { 19334 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19335 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 19336 } 19337 19338 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19339 try { 19340 final XmlSerializer serializer = new FastXmlSerializer(); 19341 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19342 serializer.startDocument(null, true); 19343 serializer.startTag(null, TAG_PREFERRED_BACKUP); 19344 19345 synchronized (mPackages) { 19346 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 19347 } 19348 19349 serializer.endTag(null, TAG_PREFERRED_BACKUP); 19350 serializer.endDocument(); 19351 serializer.flush(); 19352 } catch (Exception e) { 19353 if (DEBUG_BACKUP) { 19354 Slog.e(TAG, "Unable to write preferred activities for backup", e); 19355 } 19356 return null; 19357 } 19358 19359 return dataStream.toByteArray(); 19360 } 19361 19362 @Override 19363 public void restorePreferredActivities(byte[] backup, int userId) { 19364 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19365 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19366 } 19367 19368 try { 19369 final XmlPullParser parser = Xml.newPullParser(); 19370 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19371 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 19372 new BlobXmlRestorer() { 19373 @Override 19374 public void apply(XmlPullParser parser, int userId) 19375 throws XmlPullParserException, IOException { 19376 synchronized (mPackages) { 19377 mSettings.readPreferredActivitiesLPw(parser, userId); 19378 } 19379 } 19380 } ); 19381 } catch (Exception e) { 19382 if (DEBUG_BACKUP) { 19383 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19384 } 19385 } 19386 } 19387 19388 /** 19389 * Non-Binder method, support for the backup/restore mechanism: write the 19390 * default browser (etc) settings in its canonical XML format. Returns the default 19391 * browser XML representation as a byte array, or null if there is none. 19392 */ 19393 @Override 19394 public byte[] getDefaultAppsBackup(int userId) { 19395 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19396 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 19397 } 19398 19399 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19400 try { 19401 final XmlSerializer serializer = new FastXmlSerializer(); 19402 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19403 serializer.startDocument(null, true); 19404 serializer.startTag(null, TAG_DEFAULT_APPS); 19405 19406 synchronized (mPackages) { 19407 mSettings.writeDefaultAppsLPr(serializer, userId); 19408 } 19409 19410 serializer.endTag(null, TAG_DEFAULT_APPS); 19411 serializer.endDocument(); 19412 serializer.flush(); 19413 } catch (Exception e) { 19414 if (DEBUG_BACKUP) { 19415 Slog.e(TAG, "Unable to write default apps for backup", e); 19416 } 19417 return null; 19418 } 19419 19420 return dataStream.toByteArray(); 19421 } 19422 19423 @Override 19424 public void restoreDefaultApps(byte[] backup, int userId) { 19425 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19426 throw new SecurityException("Only the system may call restoreDefaultApps()"); 19427 } 19428 19429 try { 19430 final XmlPullParser parser = Xml.newPullParser(); 19431 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19432 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 19433 new BlobXmlRestorer() { 19434 @Override 19435 public void apply(XmlPullParser parser, int userId) 19436 throws XmlPullParserException, IOException { 19437 synchronized (mPackages) { 19438 mSettings.readDefaultAppsLPw(parser, userId); 19439 } 19440 } 19441 } ); 19442 } catch (Exception e) { 19443 if (DEBUG_BACKUP) { 19444 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 19445 } 19446 } 19447 } 19448 19449 @Override 19450 public byte[] getIntentFilterVerificationBackup(int userId) { 19451 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19452 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 19453 } 19454 19455 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19456 try { 19457 final XmlSerializer serializer = new FastXmlSerializer(); 19458 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19459 serializer.startDocument(null, true); 19460 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 19461 19462 synchronized (mPackages) { 19463 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 19464 } 19465 19466 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 19467 serializer.endDocument(); 19468 serializer.flush(); 19469 } catch (Exception e) { 19470 if (DEBUG_BACKUP) { 19471 Slog.e(TAG, "Unable to write default apps for backup", e); 19472 } 19473 return null; 19474 } 19475 19476 return dataStream.toByteArray(); 19477 } 19478 19479 @Override 19480 public void restoreIntentFilterVerification(byte[] backup, int userId) { 19481 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19482 throw new SecurityException("Only the system may call restorePreferredActivities()"); 19483 } 19484 19485 try { 19486 final XmlPullParser parser = Xml.newPullParser(); 19487 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19488 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 19489 new BlobXmlRestorer() { 19490 @Override 19491 public void apply(XmlPullParser parser, int userId) 19492 throws XmlPullParserException, IOException { 19493 synchronized (mPackages) { 19494 mSettings.readAllDomainVerificationsLPr(parser, userId); 19495 mSettings.writeLPr(); 19496 } 19497 } 19498 } ); 19499 } catch (Exception e) { 19500 if (DEBUG_BACKUP) { 19501 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19502 } 19503 } 19504 } 19505 19506 @Override 19507 public byte[] getPermissionGrantBackup(int userId) { 19508 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19509 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 19510 } 19511 19512 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 19513 try { 19514 final XmlSerializer serializer = new FastXmlSerializer(); 19515 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 19516 serializer.startDocument(null, true); 19517 serializer.startTag(null, TAG_PERMISSION_BACKUP); 19518 19519 synchronized (mPackages) { 19520 serializeRuntimePermissionGrantsLPr(serializer, userId); 19521 } 19522 19523 serializer.endTag(null, TAG_PERMISSION_BACKUP); 19524 serializer.endDocument(); 19525 serializer.flush(); 19526 } catch (Exception e) { 19527 if (DEBUG_BACKUP) { 19528 Slog.e(TAG, "Unable to write default apps for backup", e); 19529 } 19530 return null; 19531 } 19532 19533 return dataStream.toByteArray(); 19534 } 19535 19536 @Override 19537 public void restorePermissionGrants(byte[] backup, int userId) { 19538 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 19539 throw new SecurityException("Only the system may call restorePermissionGrants()"); 19540 } 19541 19542 try { 19543 final XmlPullParser parser = Xml.newPullParser(); 19544 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 19545 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 19546 new BlobXmlRestorer() { 19547 @Override 19548 public void apply(XmlPullParser parser, int userId) 19549 throws XmlPullParserException, IOException { 19550 synchronized (mPackages) { 19551 processRestoredPermissionGrantsLPr(parser, userId); 19552 } 19553 } 19554 } ); 19555 } catch (Exception e) { 19556 if (DEBUG_BACKUP) { 19557 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 19558 } 19559 } 19560 } 19561 19562 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 19563 throws IOException { 19564 serializer.startTag(null, TAG_ALL_GRANTS); 19565 19566 final int N = mSettings.mPackages.size(); 19567 for (int i = 0; i < N; i++) { 19568 final PackageSetting ps = mSettings.mPackages.valueAt(i); 19569 boolean pkgGrantsKnown = false; 19570 19571 PermissionsState packagePerms = ps.getPermissionsState(); 19572 19573 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 19574 final int grantFlags = state.getFlags(); 19575 // only look at grants that are not system/policy fixed 19576 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 19577 final boolean isGranted = state.isGranted(); 19578 // And only back up the user-twiddled state bits 19579 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 19580 final String packageName = mSettings.mPackages.keyAt(i); 19581 if (!pkgGrantsKnown) { 19582 serializer.startTag(null, TAG_GRANT); 19583 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 19584 pkgGrantsKnown = true; 19585 } 19586 19587 final boolean userSet = 19588 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 19589 final boolean userFixed = 19590 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 19591 final boolean revoke = 19592 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 19593 19594 serializer.startTag(null, TAG_PERMISSION); 19595 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 19596 if (isGranted) { 19597 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 19598 } 19599 if (userSet) { 19600 serializer.attribute(null, ATTR_USER_SET, "true"); 19601 } 19602 if (userFixed) { 19603 serializer.attribute(null, ATTR_USER_FIXED, "true"); 19604 } 19605 if (revoke) { 19606 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 19607 } 19608 serializer.endTag(null, TAG_PERMISSION); 19609 } 19610 } 19611 } 19612 19613 if (pkgGrantsKnown) { 19614 serializer.endTag(null, TAG_GRANT); 19615 } 19616 } 19617 19618 serializer.endTag(null, TAG_ALL_GRANTS); 19619 } 19620 19621 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 19622 throws XmlPullParserException, IOException { 19623 String pkgName = null; 19624 int outerDepth = parser.getDepth(); 19625 int type; 19626 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 19627 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 19628 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 19629 continue; 19630 } 19631 19632 final String tagName = parser.getName(); 19633 if (tagName.equals(TAG_GRANT)) { 19634 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 19635 if (DEBUG_BACKUP) { 19636 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 19637 } 19638 } else if (tagName.equals(TAG_PERMISSION)) { 19639 19640 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 19641 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 19642 19643 int newFlagSet = 0; 19644 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 19645 newFlagSet |= FLAG_PERMISSION_USER_SET; 19646 } 19647 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 19648 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 19649 } 19650 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 19651 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19652 } 19653 if (DEBUG_BACKUP) { 19654 Slog.v(TAG, " + Restoring grant:" 19655 + " pkg=" + pkgName 19656 + " perm=" + permName 19657 + " granted=" + isGranted 19658 + " bits=0x" + Integer.toHexString(newFlagSet)); 19659 } 19660 final PackageSetting ps = mSettings.mPackages.get(pkgName); 19661 if (ps != null) { 19662 // Already installed so we apply the grant immediately 19663 if (DEBUG_BACKUP) { 19664 Slog.v(TAG, " + already installed; applying"); 19665 } 19666 PermissionsState perms = ps.getPermissionsState(); 19667 BasePermission bp = 19668 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19669 if (bp != null) { 19670 if (isGranted) { 19671 perms.grantRuntimePermission(bp, userId); 19672 } 19673 if (newFlagSet != 0) { 19674 perms.updatePermissionFlags( 19675 bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 19676 } 19677 } 19678 } else { 19679 // Need to wait for post-restore install to apply the grant 19680 if (DEBUG_BACKUP) { 19681 Slog.v(TAG, " - not yet installed; saving for later"); 19682 } 19683 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 19684 isGranted, newFlagSet, userId); 19685 } 19686 } else { 19687 PackageManagerService.reportSettingsProblem(Log.WARN, 19688 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 19689 XmlUtils.skipCurrentTag(parser); 19690 } 19691 } 19692 19693 scheduleWriteSettingsLocked(); 19694 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19695 } 19696 19697 @Override 19698 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 19699 int sourceUserId, int targetUserId, int flags) { 19700 mContext.enforceCallingOrSelfPermission( 19701 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19702 int callingUid = Binder.getCallingUid(); 19703 enforceOwnerRights(ownerPackage, callingUid); 19704 PackageManagerServiceUtils.enforceShellRestriction( 19705 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19706 if (intentFilter.countActions() == 0) { 19707 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 19708 return; 19709 } 19710 synchronized (mPackages) { 19711 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 19712 ownerPackage, targetUserId, flags); 19713 CrossProfileIntentResolver resolver = 19714 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19715 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 19716 // We have all those whose filter is equal. Now checking if the rest is equal as well. 19717 if (existing != null) { 19718 int size = existing.size(); 19719 for (int i = 0; i < size; i++) { 19720 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 19721 return; 19722 } 19723 } 19724 } 19725 resolver.addFilter(newFilter); 19726 scheduleWritePackageRestrictionsLocked(sourceUserId); 19727 } 19728 } 19729 19730 @Override 19731 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 19732 mContext.enforceCallingOrSelfPermission( 19733 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 19734 final int callingUid = Binder.getCallingUid(); 19735 enforceOwnerRights(ownerPackage, callingUid); 19736 PackageManagerServiceUtils.enforceShellRestriction( 19737 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 19738 synchronized (mPackages) { 19739 CrossProfileIntentResolver resolver = 19740 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 19741 ArraySet<CrossProfileIntentFilter> set = 19742 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 19743 for (CrossProfileIntentFilter filter : set) { 19744 if (filter.getOwnerPackage().equals(ownerPackage)) { 19745 resolver.removeFilter(filter); 19746 } 19747 } 19748 scheduleWritePackageRestrictionsLocked(sourceUserId); 19749 } 19750 } 19751 19752 // Enforcing that callingUid is owning pkg on userId 19753 private void enforceOwnerRights(String pkg, int callingUid) { 19754 // The system owns everything. 19755 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 19756 return; 19757 } 19758 final int callingUserId = UserHandle.getUserId(callingUid); 19759 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 19760 if (pi == null) { 19761 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 19762 + callingUserId); 19763 } 19764 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 19765 throw new SecurityException("Calling uid " + callingUid 19766 + " does not own package " + pkg); 19767 } 19768 } 19769 19770 @Override 19771 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 19772 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19773 return null; 19774 } 19775 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 19776 } 19777 19778 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 19779 UserManagerService ums = UserManagerService.getInstance(); 19780 if (ums != null) { 19781 final UserInfo parent = ums.getProfileParent(userId); 19782 final int launcherUid = (parent != null) ? parent.id : userId; 19783 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 19784 if (launcherComponent != null) { 19785 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 19786 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 19787 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 19788 .setPackage(launcherComponent.getPackageName()); 19789 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 19790 } 19791 } 19792 } 19793 19794 /** 19795 * Report the 'Home' activity which is currently set as "always use this one". If non is set 19796 * then reports the most likely home activity or null if there are more than one. 19797 */ 19798 private ComponentName getDefaultHomeActivity(int userId) { 19799 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 19800 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 19801 if (cn != null) { 19802 return cn; 19803 } 19804 19805 // Find the launcher with the highest priority and return that component if there are no 19806 // other home activity with the same priority. 19807 int lastPriority = Integer.MIN_VALUE; 19808 ComponentName lastComponent = null; 19809 final int size = allHomeCandidates.size(); 19810 for (int i = 0; i < size; i++) { 19811 final ResolveInfo ri = allHomeCandidates.get(i); 19812 if (ri.priority > lastPriority) { 19813 lastComponent = ri.activityInfo.getComponentName(); 19814 lastPriority = ri.priority; 19815 } else if (ri.priority == lastPriority) { 19816 // Two components found with same priority. 19817 lastComponent = null; 19818 } 19819 } 19820 return lastComponent; 19821 } 19822 19823 private Intent getHomeIntent() { 19824 Intent intent = new Intent(Intent.ACTION_MAIN); 19825 intent.addCategory(Intent.CATEGORY_HOME); 19826 intent.addCategory(Intent.CATEGORY_DEFAULT); 19827 return intent; 19828 } 19829 19830 private IntentFilter getHomeFilter() { 19831 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 19832 filter.addCategory(Intent.CATEGORY_HOME); 19833 filter.addCategory(Intent.CATEGORY_DEFAULT); 19834 return filter; 19835 } 19836 19837 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 19838 int userId) { 19839 Intent intent = getHomeIntent(); 19840 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 19841 PackageManager.GET_META_DATA, userId); 19842 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 19843 true, false, false, userId); 19844 19845 allHomeCandidates.clear(); 19846 if (list != null) { 19847 for (ResolveInfo ri : list) { 19848 allHomeCandidates.add(ri); 19849 } 19850 } 19851 return (preferred == null || preferred.activityInfo == null) 19852 ? null 19853 : new ComponentName(preferred.activityInfo.packageName, 19854 preferred.activityInfo.name); 19855 } 19856 19857 @Override 19858 public void setHomeActivity(ComponentName comp, int userId) { 19859 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19860 return; 19861 } 19862 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 19863 getHomeActivitiesAsUser(homeActivities, userId); 19864 19865 boolean found = false; 19866 19867 final int size = homeActivities.size(); 19868 final ComponentName[] set = new ComponentName[size]; 19869 for (int i = 0; i < size; i++) { 19870 final ResolveInfo candidate = homeActivities.get(i); 19871 final ActivityInfo info = candidate.activityInfo; 19872 final ComponentName activityName = new ComponentName(info.packageName, info.name); 19873 set[i] = activityName; 19874 if (!found && activityName.equals(comp)) { 19875 found = true; 19876 } 19877 } 19878 if (!found) { 19879 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 19880 + userId); 19881 } 19882 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 19883 set, comp, userId); 19884 } 19885 19886 private @Nullable String getSetupWizardPackageName() { 19887 final Intent intent = new Intent(Intent.ACTION_MAIN); 19888 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 19889 19890 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19891 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19892 | MATCH_DISABLED_COMPONENTS, 19893 UserHandle.myUserId()); 19894 if (matches.size() == 1) { 19895 return matches.get(0).getComponentInfo().packageName; 19896 } else { 19897 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 19898 + ": matches=" + matches); 19899 return null; 19900 } 19901 } 19902 19903 private @Nullable String getStorageManagerPackageName() { 19904 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 19905 19906 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 19907 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 19908 | MATCH_DISABLED_COMPONENTS, 19909 UserHandle.myUserId()); 19910 if (matches.size() == 1) { 19911 return matches.get(0).getComponentInfo().packageName; 19912 } else { 19913 Slog.e(TAG, "There should probably be exactly one storage manager; found " 19914 + matches.size() + ": matches=" + matches); 19915 return null; 19916 } 19917 } 19918 19919 @Override 19920 public void setApplicationEnabledSetting(String appPackageName, 19921 int newState, int flags, int userId, String callingPackage) { 19922 if (!sUserManager.exists(userId)) return; 19923 if (callingPackage == null) { 19924 callingPackage = Integer.toString(Binder.getCallingUid()); 19925 } 19926 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 19927 } 19928 19929 @Override 19930 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 19931 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 19932 synchronized (mPackages) { 19933 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 19934 if (pkgSetting != null) { 19935 pkgSetting.setUpdateAvailable(updateAvailable); 19936 } 19937 } 19938 } 19939 19940 @Override 19941 public void setComponentEnabledSetting(ComponentName componentName, 19942 int newState, int flags, int userId) { 19943 if (!sUserManager.exists(userId)) return; 19944 setEnabledSetting(componentName.getPackageName(), 19945 componentName.getClassName(), newState, flags, userId, null); 19946 } 19947 19948 private void setEnabledSetting(final String packageName, String className, int newState, 19949 final int flags, int userId, String callingPackage) { 19950 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 19951 || newState == COMPONENT_ENABLED_STATE_ENABLED 19952 || newState == COMPONENT_ENABLED_STATE_DISABLED 19953 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 19954 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 19955 throw new IllegalArgumentException("Invalid new component state: " 19956 + newState); 19957 } 19958 PackageSetting pkgSetting; 19959 final int callingUid = Binder.getCallingUid(); 19960 final int permission; 19961 if (callingUid == Process.SYSTEM_UID) { 19962 permission = PackageManager.PERMISSION_GRANTED; 19963 } else { 19964 permission = mContext.checkCallingOrSelfPermission( 19965 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 19966 } 19967 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19968 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 19969 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 19970 boolean sendNow = false; 19971 boolean isApp = (className == null); 19972 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 19973 String componentName = isApp ? packageName : className; 19974 int packageUid = -1; 19975 ArrayList<String> components; 19976 19977 // reader 19978 synchronized (mPackages) { 19979 pkgSetting = mSettings.mPackages.get(packageName); 19980 if (pkgSetting == null) { 19981 if (!isCallerInstantApp) { 19982 if (className == null) { 19983 throw new IllegalArgumentException("Unknown package: " + packageName); 19984 } 19985 throw new IllegalArgumentException( 19986 "Unknown component: " + packageName + "/" + className); 19987 } else { 19988 // throw SecurityException to prevent leaking package information 19989 throw new SecurityException( 19990 "Attempt to change component state; " 19991 + "pid=" + Binder.getCallingPid() 19992 + ", uid=" + callingUid 19993 + (className == null 19994 ? ", package=" + packageName 19995 : ", component=" + packageName + "/" + className)); 19996 } 19997 } 19998 } 19999 20000 // Limit who can change which apps 20001 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20002 // Don't allow apps that don't have permission to modify other apps 20003 if (!allowedByPermission 20004 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20005 throw new SecurityException( 20006 "Attempt to change component state; " 20007 + "pid=" + Binder.getCallingPid() 20008 + ", uid=" + callingUid 20009 + (className == null 20010 ? ", package=" + packageName 20011 : ", component=" + packageName + "/" + className)); 20012 } 20013 // Don't allow changing protected packages. 20014 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20015 throw new SecurityException("Cannot disable a protected package: " + packageName); 20016 } 20017 } 20018 20019 synchronized (mPackages) { 20020 if (callingUid == Process.SHELL_UID 20021 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20022 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20023 // unless it is a test package. 20024 int oldState = pkgSetting.getEnabled(userId); 20025 if (className == null 20026 && 20027 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20028 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20029 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20030 && 20031 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20032 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20033 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20034 // ok 20035 } else { 20036 throw new SecurityException( 20037 "Shell cannot change component state for " + packageName + "/" 20038 + className + " to " + newState); 20039 } 20040 } 20041 } 20042 if (className == null) { 20043 // We're dealing with an application/package level state change 20044 synchronized (mPackages) { 20045 if (pkgSetting.getEnabled(userId) == newState) { 20046 // Nothing to do 20047 return; 20048 } 20049 } 20050 // If we're enabling a system stub, there's a little more work to do. 20051 // Prior to enabling the package, we need to decompress the APK(s) to the 20052 // data partition and then replace the version on the system partition. 20053 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20054 final boolean isSystemStub = deletedPkg.isStub 20055 && deletedPkg.isSystem(); 20056 if (isSystemStub 20057 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20058 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20059 final File codePath = decompressPackage(deletedPkg); 20060 if (codePath == null) { 20061 Slog.e(TAG, "couldn't decompress pkg: " + pkgSetting.name); 20062 return; 20063 } 20064 // TODO remove direct parsing of the package object during internal cleanup 20065 // of scan package 20066 // We need to call parse directly here for no other reason than we need 20067 // the new package in order to disable the old one [we use the information 20068 // for some internal optimization to optionally create a new package setting 20069 // object on replace]. However, we can't get the package from the scan 20070 // because the scan modifies live structures and we need to remove the 20071 // old [system] package from the system before a scan can be attempted. 20072 // Once scan is indempotent we can remove this parse and use the package 20073 // object we scanned, prior to adding it to package settings. 20074 final PackageParser pp = new PackageParser(); 20075 pp.setSeparateProcesses(mSeparateProcesses); 20076 pp.setDisplayMetrics(mMetrics); 20077 pp.setCallback(mPackageParserCallback); 20078 final PackageParser.Package tmpPkg; 20079 try { 20080 final @ParseFlags int parseFlags = mDefParseFlags 20081 | PackageParser.PARSE_MUST_BE_APK 20082 | PackageParser.PARSE_IS_SYSTEM_DIR; 20083 tmpPkg = pp.parsePackage(codePath, parseFlags); 20084 } catch (PackageParserException e) { 20085 Slog.w(TAG, "Failed to parse compressed system package:" + pkgSetting.name, e); 20086 return; 20087 } 20088 synchronized (mInstallLock) { 20089 // Disable the stub and remove any package entries 20090 removePackageLI(deletedPkg, true); 20091 synchronized (mPackages) { 20092 disableSystemPackageLPw(deletedPkg, tmpPkg); 20093 } 20094 final PackageParser.Package pkg; 20095 try (PackageFreezer freezer = 20096 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20097 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 20098 | PackageParser.PARSE_ENFORCE_CODE; 20099 pkg = scanPackageTracedLI(codePath, parseFlags, 0 /*scanFlags*/, 20100 0 /*currentTime*/, null /*user*/); 20101 prepareAppDataAfterInstallLIF(pkg); 20102 synchronized (mPackages) { 20103 try { 20104 updateSharedLibrariesLPr(pkg, null); 20105 } catch (PackageManagerException e) { 20106 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 20107 } 20108 mPermissionManager.updatePermissions( 20109 pkg.packageName, pkg, true, mPackages.values(), 20110 mPermissionCallback); 20111 mSettings.writeLPr(); 20112 } 20113 } catch (PackageManagerException e) { 20114 // Whoops! Something went wrong; try to roll back to the stub 20115 Slog.w(TAG, "Failed to install compressed system package:" 20116 + pkgSetting.name, e); 20117 // Remove the failed install 20118 removeCodePathLI(codePath); 20119 20120 // Install the system package 20121 try (PackageFreezer freezer = 20122 freezePackage(deletedPkg.packageName, "setEnabledSetting")) { 20123 synchronized (mPackages) { 20124 // NOTE: The system package always needs to be enabled; even 20125 // if it's for a compressed stub. If we don't, installing the 20126 // system package fails during scan [scanning checks the disabled 20127 // packages]. We will reverse this later, after we've "installed" 20128 // the stub. 20129 // This leaves us in a fragile state; the stub should never be 20130 // enabled, so, cross your fingers and hope nothing goes wrong 20131 // until we can disable the package later. 20132 enableSystemPackageLPw(deletedPkg); 20133 } 20134 installPackageFromSystemLIF(deletedPkg.codePath, 20135 false /*isPrivileged*/, null /*allUserHandles*/, 20136 null /*origUserHandles*/, null /*origPermissionsState*/, 20137 true /*writeSettings*/); 20138 } catch (PackageManagerException pme) { 20139 Slog.w(TAG, "Failed to restore system package:" 20140 + deletedPkg.packageName, pme); 20141 } finally { 20142 synchronized (mPackages) { 20143 mSettings.disableSystemPackageLPw( 20144 deletedPkg.packageName, true /*replaced*/); 20145 mSettings.writeLPr(); 20146 } 20147 } 20148 return; 20149 } 20150 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE 20151 | FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20152 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 20153 mDexManager.notifyPackageUpdated(pkg.packageName, 20154 pkg.baseCodePath, pkg.splitCodePaths); 20155 } 20156 } 20157 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20158 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20159 // Don't care about who enables an app. 20160 callingPackage = null; 20161 } 20162 synchronized (mPackages) { 20163 pkgSetting.setEnabled(newState, userId, callingPackage); 20164 } 20165 } else { 20166 synchronized (mPackages) { 20167 // We're dealing with a component level state change 20168 // First, verify that this is a valid class name. 20169 PackageParser.Package pkg = pkgSetting.pkg; 20170 if (pkg == null || !pkg.hasComponentClassName(className)) { 20171 if (pkg != null && 20172 pkg.applicationInfo.targetSdkVersion >= 20173 Build.VERSION_CODES.JELLY_BEAN) { 20174 throw new IllegalArgumentException("Component class " + className 20175 + " does not exist in " + packageName); 20176 } else { 20177 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20178 + className + " does not exist in " + packageName); 20179 } 20180 } 20181 switch (newState) { 20182 case COMPONENT_ENABLED_STATE_ENABLED: 20183 if (!pkgSetting.enableComponentLPw(className, userId)) { 20184 return; 20185 } 20186 break; 20187 case COMPONENT_ENABLED_STATE_DISABLED: 20188 if (!pkgSetting.disableComponentLPw(className, userId)) { 20189 return; 20190 } 20191 break; 20192 case COMPONENT_ENABLED_STATE_DEFAULT: 20193 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20194 return; 20195 } 20196 break; 20197 default: 20198 Slog.e(TAG, "Invalid new component state: " + newState); 20199 return; 20200 } 20201 } 20202 } 20203 synchronized (mPackages) { 20204 scheduleWritePackageRestrictionsLocked(userId); 20205 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20206 final long callingId = Binder.clearCallingIdentity(); 20207 try { 20208 updateInstantAppInstallerLocked(packageName); 20209 } finally { 20210 Binder.restoreCallingIdentity(callingId); 20211 } 20212 components = mPendingBroadcasts.get(userId, packageName); 20213 final boolean newPackage = components == null; 20214 if (newPackage) { 20215 components = new ArrayList<String>(); 20216 } 20217 if (!components.contains(componentName)) { 20218 components.add(componentName); 20219 } 20220 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20221 sendNow = true; 20222 // Purge entry from pending broadcast list if another one exists already 20223 // since we are sending one right away. 20224 mPendingBroadcasts.remove(userId, packageName); 20225 } else { 20226 if (newPackage) { 20227 mPendingBroadcasts.put(userId, packageName, components); 20228 } 20229 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20230 // Schedule a message 20231 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 20232 } 20233 } 20234 } 20235 20236 long callingId = Binder.clearCallingIdentity(); 20237 try { 20238 if (sendNow) { 20239 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20240 sendPackageChangedBroadcast(packageName, 20241 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20242 } 20243 } finally { 20244 Binder.restoreCallingIdentity(callingId); 20245 } 20246 } 20247 20248 @Override 20249 public void flushPackageRestrictionsAsUser(int userId) { 20250 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20251 return; 20252 } 20253 if (!sUserManager.exists(userId)) { 20254 return; 20255 } 20256 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20257 false /* checkShell */, "flushPackageRestrictions"); 20258 synchronized (mPackages) { 20259 mSettings.writePackageRestrictionsLPr(userId); 20260 mDirtyUsers.remove(userId); 20261 if (mDirtyUsers.isEmpty()) { 20262 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20263 } 20264 } 20265 } 20266 20267 private void sendPackageChangedBroadcast(String packageName, 20268 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20269 if (DEBUG_INSTALL) 20270 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20271 + componentNames); 20272 Bundle extras = new Bundle(4); 20273 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20274 String nameList[] = new String[componentNames.size()]; 20275 componentNames.toArray(nameList); 20276 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20277 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20278 extras.putInt(Intent.EXTRA_UID, packageUid); 20279 // If this is not reporting a change of the overall package, then only send it 20280 // to registered receivers. We don't want to launch a swath of apps for every 20281 // little component state change. 20282 final int flags = !componentNames.contains(packageName) 20283 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20284 final int userId = UserHandle.getUserId(packageUid); 20285 final boolean isInstantApp = isInstantApp(packageName, userId); 20286 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20287 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20288 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20289 userIds, instantUserIds); 20290 } 20291 20292 @Override 20293 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20294 if (!sUserManager.exists(userId)) return; 20295 final int callingUid = Binder.getCallingUid(); 20296 if (getInstantAppPackageName(callingUid) != null) { 20297 return; 20298 } 20299 final int permission = mContext.checkCallingOrSelfPermission( 20300 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20301 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20302 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20303 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20304 // writer 20305 synchronized (mPackages) { 20306 final PackageSetting ps = mSettings.mPackages.get(packageName); 20307 if (!filterAppAccessLPr(ps, callingUid, userId) 20308 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20309 allowedByPermission, callingUid, userId)) { 20310 scheduleWritePackageRestrictionsLocked(userId); 20311 } 20312 } 20313 } 20314 20315 @Override 20316 public String getInstallerPackageName(String packageName) { 20317 final int callingUid = Binder.getCallingUid(); 20318 if (getInstantAppPackageName(callingUid) != null) { 20319 return null; 20320 } 20321 // reader 20322 synchronized (mPackages) { 20323 final PackageSetting ps = mSettings.mPackages.get(packageName); 20324 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20325 return null; 20326 } 20327 return mSettings.getInstallerPackageNameLPr(packageName); 20328 } 20329 } 20330 20331 public boolean isOrphaned(String packageName) { 20332 // reader 20333 synchronized (mPackages) { 20334 return mSettings.isOrphaned(packageName); 20335 } 20336 } 20337 20338 @Override 20339 public int getApplicationEnabledSetting(String packageName, int userId) { 20340 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20341 int callingUid = Binder.getCallingUid(); 20342 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20343 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 20344 // reader 20345 synchronized (mPackages) { 20346 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 20347 return COMPONENT_ENABLED_STATE_DISABLED; 20348 } 20349 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 20350 } 20351 } 20352 20353 @Override 20354 public int getComponentEnabledSetting(ComponentName component, int userId) { 20355 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 20356 int callingUid = Binder.getCallingUid(); 20357 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20358 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 20359 synchronized (mPackages) { 20360 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 20361 component, TYPE_UNKNOWN, userId)) { 20362 return COMPONENT_ENABLED_STATE_DISABLED; 20363 } 20364 return mSettings.getComponentEnabledSettingLPr(component, userId); 20365 } 20366 } 20367 20368 @Override 20369 public void enterSafeMode() { 20370 enforceSystemOrRoot("Only the system can request entering safe mode"); 20371 20372 if (!mSystemReady) { 20373 mSafeMode = true; 20374 } 20375 } 20376 20377 @Override 20378 public void systemReady() { 20379 enforceSystemOrRoot("Only the system can claim the system is ready"); 20380 20381 mSystemReady = true; 20382 final ContentResolver resolver = mContext.getContentResolver(); 20383 ContentObserver co = new ContentObserver(mHandler) { 20384 @Override 20385 public void onChange(boolean selfChange) { 20386 mEphemeralAppsDisabled = 20387 (Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0) || 20388 (Secure.getInt(resolver, Secure.INSTANT_APPS_ENABLED, 1) == 0); 20389 } 20390 }; 20391 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20392 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 20393 false, co, UserHandle.USER_SYSTEM); 20394 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 20395 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_SYSTEM); 20396 co.onChange(true); 20397 20398 // This observer provides an one directional mapping from Global.PRIV_APP_OOB_ENABLED to 20399 // pm.dexopt.priv-apps-oob property. This is only for experiment and should be removed once 20400 // it is done. 20401 ContentObserver privAppOobObserver = new ContentObserver(mHandler) { 20402 @Override 20403 public void onChange(boolean selfChange) { 20404 int oobEnabled = Global.getInt(resolver, Global.PRIV_APP_OOB_ENABLED, 0); 20405 SystemProperties.set(PROPERTY_NAME_PM_DEXOPT_PRIV_APPS_OOB, 20406 oobEnabled == 1 ? "true" : "false"); 20407 } 20408 }; 20409 mContext.getContentResolver().registerContentObserver( 20410 Global.getUriFor(Global.PRIV_APP_OOB_ENABLED), false, privAppOobObserver, 20411 UserHandle.USER_SYSTEM); 20412 // At boot, restore the value from the setting, which persists across reboot. 20413 privAppOobObserver.onChange(true); 20414 20415 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 20416 // disabled after already being started. 20417 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 20418 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 20419 20420 // Read the compatibilty setting when the system is ready. 20421 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 20422 mContext.getContentResolver(), 20423 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 20424 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 20425 if (DEBUG_SETTINGS) { 20426 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 20427 } 20428 20429 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 20430 20431 synchronized (mPackages) { 20432 // Verify that all of the preferred activity components actually 20433 // exist. It is possible for applications to be updated and at 20434 // that point remove a previously declared activity component that 20435 // had been set as a preferred activity. We try to clean this up 20436 // the next time we encounter that preferred activity, but it is 20437 // possible for the user flow to never be able to return to that 20438 // situation so here we do a sanity check to make sure we haven't 20439 // left any junk around. 20440 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 20441 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20442 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20443 removed.clear(); 20444 for (PreferredActivity pa : pir.filterSet()) { 20445 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 20446 removed.add(pa); 20447 } 20448 } 20449 if (removed.size() > 0) { 20450 for (int r=0; r<removed.size(); r++) { 20451 PreferredActivity pa = removed.get(r); 20452 Slog.w(TAG, "Removing dangling preferred activity: " 20453 + pa.mPref.mComponent); 20454 pir.removeFilter(pa); 20455 } 20456 mSettings.writePackageRestrictionsLPr( 20457 mSettings.mPreferredActivities.keyAt(i)); 20458 } 20459 } 20460 20461 for (int userId : UserManagerService.getInstance().getUserIds()) { 20462 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20463 grantPermissionsUserIds = ArrayUtils.appendInt( 20464 grantPermissionsUserIds, userId); 20465 } 20466 } 20467 } 20468 sUserManager.systemReady(); 20469 // If we upgraded grant all default permissions before kicking off. 20470 for (int userId : grantPermissionsUserIds) { 20471 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20472 } 20473 20474 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 20475 // If we did not grant default permissions, we preload from this the 20476 // default permission exceptions lazily to ensure we don't hit the 20477 // disk on a new user creation. 20478 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 20479 } 20480 20481 // Now that we've scanned all packages, and granted any default 20482 // permissions, ensure permissions are updated. Beware of dragons if you 20483 // try optimizing this. 20484 synchronized (mPackages) { 20485 mPermissionManager.updateAllPermissions( 20486 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 20487 mPermissionCallback); 20488 } 20489 20490 // Kick off any messages waiting for system ready 20491 if (mPostSystemReadyMessages != null) { 20492 for (Message msg : mPostSystemReadyMessages) { 20493 msg.sendToTarget(); 20494 } 20495 mPostSystemReadyMessages = null; 20496 } 20497 20498 // Watch for external volumes that come and go over time 20499 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20500 storage.registerListener(mStorageListener); 20501 20502 mInstallerService.systemReady(); 20503 mPackageDexOptimizer.systemReady(); 20504 20505 StorageManagerInternal StorageManagerInternal = LocalServices.getService( 20506 StorageManagerInternal.class); 20507 StorageManagerInternal.addExternalStoragePolicy( 20508 new StorageManagerInternal.ExternalStorageMountPolicy() { 20509 @Override 20510 public int getMountMode(int uid, String packageName) { 20511 if (Process.isIsolated(uid)) { 20512 return Zygote.MOUNT_EXTERNAL_NONE; 20513 } 20514 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 20515 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20516 } 20517 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20518 return Zygote.MOUNT_EXTERNAL_DEFAULT; 20519 } 20520 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 20521 return Zygote.MOUNT_EXTERNAL_READ; 20522 } 20523 return Zygote.MOUNT_EXTERNAL_WRITE; 20524 } 20525 20526 @Override 20527 public boolean hasExternalStorage(int uid, String packageName) { 20528 return true; 20529 } 20530 }); 20531 20532 // Now that we're mostly running, clean up stale users and apps 20533 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 20534 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 20535 20536 mPermissionManager.systemReady(); 20537 } 20538 20539 public void waitForAppDataPrepared() { 20540 if (mPrepareAppDataFuture == null) { 20541 return; 20542 } 20543 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 20544 mPrepareAppDataFuture = null; 20545 } 20546 20547 @Override 20548 public boolean isSafeMode() { 20549 // allow instant applications 20550 return mSafeMode; 20551 } 20552 20553 @Override 20554 public boolean hasSystemUidErrors() { 20555 // allow instant applications 20556 return mHasSystemUidErrors; 20557 } 20558 20559 static String arrayToString(int[] array) { 20560 StringBuffer buf = new StringBuffer(128); 20561 buf.append('['); 20562 if (array != null) { 20563 for (int i=0; i<array.length; i++) { 20564 if (i > 0) buf.append(", "); 20565 buf.append(array[i]); 20566 } 20567 } 20568 buf.append(']'); 20569 return buf.toString(); 20570 } 20571 20572 @Override 20573 public void onShellCommand(FileDescriptor in, FileDescriptor out, 20574 FileDescriptor err, String[] args, ShellCallback callback, 20575 ResultReceiver resultReceiver) { 20576 (new PackageManagerShellCommand(this)).exec( 20577 this, in, out, err, args, callback, resultReceiver); 20578 } 20579 20580 @Override 20581 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 20582 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 20583 20584 DumpState dumpState = new DumpState(); 20585 boolean fullPreferred = false; 20586 boolean checkin = false; 20587 20588 String packageName = null; 20589 ArraySet<String> permissionNames = null; 20590 20591 int opti = 0; 20592 while (opti < args.length) { 20593 String opt = args[opti]; 20594 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 20595 break; 20596 } 20597 opti++; 20598 20599 if ("-a".equals(opt)) { 20600 // Right now we only know how to print all. 20601 } else if ("-h".equals(opt)) { 20602 pw.println("Package manager dump options:"); 20603 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 20604 pw.println(" --checkin: dump for a checkin"); 20605 pw.println(" -f: print details of intent filters"); 20606 pw.println(" -h: print this help"); 20607 pw.println(" cmd may be one of:"); 20608 pw.println(" l[ibraries]: list known shared libraries"); 20609 pw.println(" f[eatures]: list device features"); 20610 pw.println(" k[eysets]: print known keysets"); 20611 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 20612 pw.println(" perm[issions]: dump permissions"); 20613 pw.println(" permission [name ...]: dump declaration and use of given permission"); 20614 pw.println(" pref[erred]: print preferred package settings"); 20615 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 20616 pw.println(" prov[iders]: dump content providers"); 20617 pw.println(" p[ackages]: dump installed packages"); 20618 pw.println(" s[hared-users]: dump shared user IDs"); 20619 pw.println(" m[essages]: print collected runtime messages"); 20620 pw.println(" v[erifiers]: print package verifier info"); 20621 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 20622 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 20623 pw.println(" version: print database version info"); 20624 pw.println(" write: write current settings now"); 20625 pw.println(" installs: details about install sessions"); 20626 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 20627 pw.println(" dexopt: dump dexopt state"); 20628 pw.println(" compiler-stats: dump compiler statistics"); 20629 pw.println(" enabled-overlays: dump list of enabled overlay packages"); 20630 pw.println(" service-permissions: dump permissions required by services"); 20631 pw.println(" <package.name>: info about given package"); 20632 return; 20633 } else if ("--checkin".equals(opt)) { 20634 checkin = true; 20635 } else if ("-f".equals(opt)) { 20636 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20637 } else if ("--proto".equals(opt)) { 20638 dumpProto(fd); 20639 return; 20640 } else { 20641 pw.println("Unknown argument: " + opt + "; use -h for help"); 20642 } 20643 } 20644 20645 // Is the caller requesting to dump a particular piece of data? 20646 if (opti < args.length) { 20647 String cmd = args[opti]; 20648 opti++; 20649 // Is this a package name? 20650 if ("android".equals(cmd) || cmd.contains(".")) { 20651 packageName = cmd; 20652 // When dumping a single package, we always dump all of its 20653 // filter information since the amount of data will be reasonable. 20654 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 20655 } else if ("check-permission".equals(cmd)) { 20656 if (opti >= args.length) { 20657 pw.println("Error: check-permission missing permission argument"); 20658 return; 20659 } 20660 String perm = args[opti]; 20661 opti++; 20662 if (opti >= args.length) { 20663 pw.println("Error: check-permission missing package argument"); 20664 return; 20665 } 20666 20667 String pkg = args[opti]; 20668 opti++; 20669 int user = UserHandle.getUserId(Binder.getCallingUid()); 20670 if (opti < args.length) { 20671 try { 20672 user = Integer.parseInt(args[opti]); 20673 } catch (NumberFormatException e) { 20674 pw.println("Error: check-permission user argument is not a number: " 20675 + args[opti]); 20676 return; 20677 } 20678 } 20679 20680 // Normalize package name to handle renamed packages and static libs 20681 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 20682 20683 pw.println(checkPermission(perm, pkg, user)); 20684 return; 20685 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 20686 dumpState.setDump(DumpState.DUMP_LIBS); 20687 } else if ("f".equals(cmd) || "features".equals(cmd)) { 20688 dumpState.setDump(DumpState.DUMP_FEATURES); 20689 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 20690 if (opti >= args.length) { 20691 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 20692 | DumpState.DUMP_SERVICE_RESOLVERS 20693 | DumpState.DUMP_RECEIVER_RESOLVERS 20694 | DumpState.DUMP_CONTENT_RESOLVERS); 20695 } else { 20696 while (opti < args.length) { 20697 String name = args[opti]; 20698 if ("a".equals(name) || "activity".equals(name)) { 20699 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 20700 } else if ("s".equals(name) || "service".equals(name)) { 20701 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 20702 } else if ("r".equals(name) || "receiver".equals(name)) { 20703 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 20704 } else if ("c".equals(name) || "content".equals(name)) { 20705 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 20706 } else { 20707 pw.println("Error: unknown resolver table type: " + name); 20708 return; 20709 } 20710 opti++; 20711 } 20712 } 20713 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 20714 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 20715 } else if ("permission".equals(cmd)) { 20716 if (opti >= args.length) { 20717 pw.println("Error: permission requires permission name"); 20718 return; 20719 } 20720 permissionNames = new ArraySet<>(); 20721 while (opti < args.length) { 20722 permissionNames.add(args[opti]); 20723 opti++; 20724 } 20725 dumpState.setDump(DumpState.DUMP_PERMISSIONS 20726 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 20727 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 20728 dumpState.setDump(DumpState.DUMP_PREFERRED); 20729 } else if ("preferred-xml".equals(cmd)) { 20730 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 20731 if (opti < args.length && "--full".equals(args[opti])) { 20732 fullPreferred = true; 20733 opti++; 20734 } 20735 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 20736 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 20737 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 20738 dumpState.setDump(DumpState.DUMP_PACKAGES); 20739 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 20740 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 20741 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 20742 dumpState.setDump(DumpState.DUMP_PROVIDERS); 20743 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 20744 dumpState.setDump(DumpState.DUMP_MESSAGES); 20745 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 20746 dumpState.setDump(DumpState.DUMP_VERIFIERS); 20747 } else if ("i".equals(cmd) || "ifv".equals(cmd) 20748 || "intent-filter-verifiers".equals(cmd)) { 20749 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 20750 } else if ("version".equals(cmd)) { 20751 dumpState.setDump(DumpState.DUMP_VERSION); 20752 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 20753 dumpState.setDump(DumpState.DUMP_KEYSETS); 20754 } else if ("installs".equals(cmd)) { 20755 dumpState.setDump(DumpState.DUMP_INSTALLS); 20756 } else if ("frozen".equals(cmd)) { 20757 dumpState.setDump(DumpState.DUMP_FROZEN); 20758 } else if ("volumes".equals(cmd)) { 20759 dumpState.setDump(DumpState.DUMP_VOLUMES); 20760 } else if ("dexopt".equals(cmd)) { 20761 dumpState.setDump(DumpState.DUMP_DEXOPT); 20762 } else if ("compiler-stats".equals(cmd)) { 20763 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 20764 } else if ("changes".equals(cmd)) { 20765 dumpState.setDump(DumpState.DUMP_CHANGES); 20766 } else if ("service-permissions".equals(cmd)) { 20767 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 20768 } else if ("write".equals(cmd)) { 20769 synchronized (mPackages) { 20770 mSettings.writeLPr(); 20771 pw.println("Settings written."); 20772 return; 20773 } 20774 } 20775 } 20776 20777 if (checkin) { 20778 pw.println("vers,1"); 20779 } 20780 20781 // reader 20782 synchronized (mPackages) { 20783 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 20784 if (!checkin) { 20785 if (dumpState.onTitlePrinted()) 20786 pw.println(); 20787 pw.println("Database versions:"); 20788 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 20789 } 20790 } 20791 20792 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 20793 if (!checkin) { 20794 if (dumpState.onTitlePrinted()) 20795 pw.println(); 20796 pw.println("Verifiers:"); 20797 pw.print(" Required: "); 20798 pw.print(mRequiredVerifierPackage); 20799 pw.print(" (uid="); 20800 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20801 UserHandle.USER_SYSTEM)); 20802 pw.println(")"); 20803 } else if (mRequiredVerifierPackage != null) { 20804 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 20805 pw.print(","); 20806 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 20807 UserHandle.USER_SYSTEM)); 20808 } 20809 } 20810 20811 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 20812 packageName == null) { 20813 if (mIntentFilterVerifierComponent != null) { 20814 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 20815 if (!checkin) { 20816 if (dumpState.onTitlePrinted()) 20817 pw.println(); 20818 pw.println("Intent Filter Verifier:"); 20819 pw.print(" Using: "); 20820 pw.print(verifierPackageName); 20821 pw.print(" (uid="); 20822 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20823 UserHandle.USER_SYSTEM)); 20824 pw.println(")"); 20825 } else if (verifierPackageName != null) { 20826 pw.print("ifv,"); pw.print(verifierPackageName); 20827 pw.print(","); 20828 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 20829 UserHandle.USER_SYSTEM)); 20830 } 20831 } else { 20832 pw.println(); 20833 pw.println("No Intent Filter Verifier available!"); 20834 } 20835 } 20836 20837 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 20838 boolean printedHeader = false; 20839 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 20840 while (it.hasNext()) { 20841 String libName = it.next(); 20842 LongSparseArray<SharedLibraryEntry> versionedLib 20843 = mSharedLibraries.get(libName); 20844 if (versionedLib == null) { 20845 continue; 20846 } 20847 final int versionCount = versionedLib.size(); 20848 for (int i = 0; i < versionCount; i++) { 20849 SharedLibraryEntry libEntry = versionedLib.valueAt(i); 20850 if (!checkin) { 20851 if (!printedHeader) { 20852 if (dumpState.onTitlePrinted()) 20853 pw.println(); 20854 pw.println("Libraries:"); 20855 printedHeader = true; 20856 } 20857 pw.print(" "); 20858 } else { 20859 pw.print("lib,"); 20860 } 20861 pw.print(libEntry.info.getName()); 20862 if (libEntry.info.isStatic()) { 20863 pw.print(" version=" + libEntry.info.getLongVersion()); 20864 } 20865 if (!checkin) { 20866 pw.print(" -> "); 20867 } 20868 if (libEntry.path != null) { 20869 pw.print(" (jar) "); 20870 pw.print(libEntry.path); 20871 } else { 20872 pw.print(" (apk) "); 20873 pw.print(libEntry.apk); 20874 } 20875 pw.println(); 20876 } 20877 } 20878 } 20879 20880 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 20881 if (dumpState.onTitlePrinted()) 20882 pw.println(); 20883 if (!checkin) { 20884 pw.println("Features:"); 20885 } 20886 20887 synchronized (mAvailableFeatures) { 20888 for (FeatureInfo feat : mAvailableFeatures.values()) { 20889 if (checkin) { 20890 pw.print("feat,"); 20891 pw.print(feat.name); 20892 pw.print(","); 20893 pw.println(feat.version); 20894 } else { 20895 pw.print(" "); 20896 pw.print(feat.name); 20897 if (feat.version > 0) { 20898 pw.print(" version="); 20899 pw.print(feat.version); 20900 } 20901 pw.println(); 20902 } 20903 } 20904 } 20905 } 20906 20907 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 20908 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 20909 : "Activity Resolver Table:", " ", packageName, 20910 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20911 dumpState.setTitlePrinted(true); 20912 } 20913 } 20914 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 20915 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 20916 : "Receiver Resolver Table:", " ", packageName, 20917 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20918 dumpState.setTitlePrinted(true); 20919 } 20920 } 20921 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 20922 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 20923 : "Service Resolver Table:", " ", packageName, 20924 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20925 dumpState.setTitlePrinted(true); 20926 } 20927 } 20928 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 20929 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 20930 : "Provider Resolver Table:", " ", packageName, 20931 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 20932 dumpState.setTitlePrinted(true); 20933 } 20934 } 20935 20936 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 20937 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20938 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20939 int user = mSettings.mPreferredActivities.keyAt(i); 20940 if (pir.dump(pw, 20941 dumpState.getTitlePrinted() 20942 ? "\nPreferred Activities User " + user + ":" 20943 : "Preferred Activities User " + user + ":", " ", 20944 packageName, true, false)) { 20945 dumpState.setTitlePrinted(true); 20946 } 20947 } 20948 } 20949 20950 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 20951 pw.flush(); 20952 FileOutputStream fout = new FileOutputStream(fd); 20953 BufferedOutputStream str = new BufferedOutputStream(fout); 20954 XmlSerializer serializer = new FastXmlSerializer(); 20955 try { 20956 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 20957 serializer.startDocument(null, true); 20958 serializer.setFeature( 20959 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 20960 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 20961 serializer.endDocument(); 20962 serializer.flush(); 20963 } catch (IllegalArgumentException e) { 20964 pw.println("Failed writing: " + e); 20965 } catch (IllegalStateException e) { 20966 pw.println("Failed writing: " + e); 20967 } catch (IOException e) { 20968 pw.println("Failed writing: " + e); 20969 } 20970 } 20971 20972 if (!checkin 20973 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 20974 && packageName == null) { 20975 pw.println(); 20976 int count = mSettings.mPackages.size(); 20977 if (count == 0) { 20978 pw.println("No applications!"); 20979 pw.println(); 20980 } else { 20981 final String prefix = " "; 20982 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 20983 if (allPackageSettings.size() == 0) { 20984 pw.println("No domain preferred apps!"); 20985 pw.println(); 20986 } else { 20987 pw.println("App verification status:"); 20988 pw.println(); 20989 count = 0; 20990 for (PackageSetting ps : allPackageSettings) { 20991 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 20992 if (ivi == null || ivi.getPackageName() == null) continue; 20993 pw.println(prefix + "Package: " + ivi.getPackageName()); 20994 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 20995 pw.println(prefix + "Status: " + ivi.getStatusString()); 20996 pw.println(); 20997 count++; 20998 } 20999 if (count == 0) { 21000 pw.println(prefix + "No app verification established."); 21001 pw.println(); 21002 } 21003 for (int userId : sUserManager.getUserIds()) { 21004 pw.println("App linkages for user " + userId + ":"); 21005 pw.println(); 21006 count = 0; 21007 for (PackageSetting ps : allPackageSettings) { 21008 final long status = ps.getDomainVerificationStatusForUser(userId); 21009 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21010 && !DEBUG_DOMAIN_VERIFICATION) { 21011 continue; 21012 } 21013 pw.println(prefix + "Package: " + ps.name); 21014 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21015 String statusStr = IntentFilterVerificationInfo. 21016 getStatusStringFromValue(status); 21017 pw.println(prefix + "Status: " + statusStr); 21018 pw.println(); 21019 count++; 21020 } 21021 if (count == 0) { 21022 pw.println(prefix + "No configured app linkages."); 21023 pw.println(); 21024 } 21025 } 21026 } 21027 } 21028 } 21029 21030 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21031 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21032 } 21033 21034 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21035 boolean printedSomething = false; 21036 for (PackageParser.Provider p : mProviders.mProviders.values()) { 21037 if (packageName != null && !packageName.equals(p.info.packageName)) { 21038 continue; 21039 } 21040 if (!printedSomething) { 21041 if (dumpState.onTitlePrinted()) 21042 pw.println(); 21043 pw.println("Registered ContentProviders:"); 21044 printedSomething = true; 21045 } 21046 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 21047 pw.print(" "); pw.println(p.toString()); 21048 } 21049 printedSomething = false; 21050 for (Map.Entry<String, PackageParser.Provider> entry : 21051 mProvidersByAuthority.entrySet()) { 21052 PackageParser.Provider p = entry.getValue(); 21053 if (packageName != null && !packageName.equals(p.info.packageName)) { 21054 continue; 21055 } 21056 if (!printedSomething) { 21057 if (dumpState.onTitlePrinted()) 21058 pw.println(); 21059 pw.println("ContentProvider Authorities:"); 21060 printedSomething = true; 21061 } 21062 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 21063 pw.print(" "); pw.println(p.toString()); 21064 if (p.info != null && p.info.applicationInfo != null) { 21065 final String appInfo = p.info.applicationInfo.toString(); 21066 pw.print(" applicationInfo="); pw.println(appInfo); 21067 } 21068 } 21069 } 21070 21071 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21072 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21073 } 21074 21075 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21076 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21077 } 21078 21079 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21080 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21081 } 21082 21083 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21084 if (dumpState.onTitlePrinted()) pw.println(); 21085 pw.println("Package Changes:"); 21086 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21087 final int K = mChangedPackages.size(); 21088 for (int i = 0; i < K; i++) { 21089 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21090 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21091 final int N = changes.size(); 21092 if (N == 0) { 21093 pw.print(" "); pw.println("No packages changed"); 21094 } else { 21095 for (int j = 0; j < N; j++) { 21096 final String pkgName = changes.valueAt(j); 21097 final int sequenceNumber = changes.keyAt(j); 21098 pw.print(" "); 21099 pw.print("seq="); 21100 pw.print(sequenceNumber); 21101 pw.print(", package="); 21102 pw.println(pkgName); 21103 } 21104 } 21105 } 21106 } 21107 21108 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 21109 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 21110 } 21111 21112 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21113 // XXX should handle packageName != null by dumping only install data that 21114 // the given package is involved with. 21115 if (dumpState.onTitlePrinted()) pw.println(); 21116 21117 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21118 ipw.println(); 21119 ipw.println("Frozen packages:"); 21120 ipw.increaseIndent(); 21121 if (mFrozenPackages.size() == 0) { 21122 ipw.println("(none)"); 21123 } else { 21124 for (int i = 0; i < mFrozenPackages.size(); i++) { 21125 ipw.println(mFrozenPackages.valueAt(i)); 21126 } 21127 } 21128 ipw.decreaseIndent(); 21129 } 21130 21131 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21132 if (dumpState.onTitlePrinted()) pw.println(); 21133 21134 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21135 ipw.println(); 21136 ipw.println("Loaded volumes:"); 21137 ipw.increaseIndent(); 21138 if (mLoadedVolumes.size() == 0) { 21139 ipw.println("(none)"); 21140 } else { 21141 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21142 ipw.println(mLoadedVolumes.valueAt(i)); 21143 } 21144 } 21145 ipw.decreaseIndent(); 21146 } 21147 21148 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21149 && packageName == null) { 21150 if (dumpState.onTitlePrinted()) pw.println(); 21151 pw.println("Service permissions:"); 21152 21153 final Iterator<ServiceIntentInfo> filterIterator = mServices.filterIterator(); 21154 while (filterIterator.hasNext()) { 21155 final ServiceIntentInfo info = filterIterator.next(); 21156 final ServiceInfo serviceInfo = info.service.info; 21157 final String permission = serviceInfo.permission; 21158 if (permission != null) { 21159 pw.print(" "); 21160 pw.print(serviceInfo.getComponentName().flattenToShortString()); 21161 pw.print(": "); 21162 pw.println(permission); 21163 } 21164 } 21165 } 21166 21167 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21168 if (dumpState.onTitlePrinted()) pw.println(); 21169 dumpDexoptStateLPr(pw, packageName); 21170 } 21171 21172 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21173 if (dumpState.onTitlePrinted()) pw.println(); 21174 dumpCompilerStatsLPr(pw, packageName); 21175 } 21176 21177 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21178 if (dumpState.onTitlePrinted()) pw.println(); 21179 mSettings.dumpReadMessagesLPr(pw, dumpState); 21180 21181 pw.println(); 21182 pw.println("Package warning messages:"); 21183 dumpCriticalInfo(pw, null); 21184 } 21185 21186 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21187 dumpCriticalInfo(pw, "msg,"); 21188 } 21189 } 21190 21191 // PackageInstaller should be called outside of mPackages lock 21192 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21193 // XXX should handle packageName != null by dumping only install data that 21194 // the given package is involved with. 21195 if (dumpState.onTitlePrinted()) pw.println(); 21196 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21197 } 21198 } 21199 21200 private void dumpProto(FileDescriptor fd) { 21201 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21202 21203 synchronized (mPackages) { 21204 final long requiredVerifierPackageToken = 21205 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21206 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21207 proto.write( 21208 PackageServiceDumpProto.PackageShortProto.UID, 21209 getPackageUid( 21210 mRequiredVerifierPackage, 21211 MATCH_DEBUG_TRIAGED_MISSING, 21212 UserHandle.USER_SYSTEM)); 21213 proto.end(requiredVerifierPackageToken); 21214 21215 if (mIntentFilterVerifierComponent != null) { 21216 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21217 final long verifierPackageToken = 21218 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21219 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21220 proto.write( 21221 PackageServiceDumpProto.PackageShortProto.UID, 21222 getPackageUid( 21223 verifierPackageName, 21224 MATCH_DEBUG_TRIAGED_MISSING, 21225 UserHandle.USER_SYSTEM)); 21226 proto.end(verifierPackageToken); 21227 } 21228 21229 dumpSharedLibrariesProto(proto); 21230 dumpFeaturesProto(proto); 21231 mSettings.dumpPackagesProto(proto); 21232 mSettings.dumpSharedUsersProto(proto); 21233 dumpCriticalInfo(proto); 21234 } 21235 proto.flush(); 21236 } 21237 21238 private void dumpFeaturesProto(ProtoOutputStream proto) { 21239 synchronized (mAvailableFeatures) { 21240 final int count = mAvailableFeatures.size(); 21241 for (int i = 0; i < count; i++) { 21242 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21243 } 21244 } 21245 } 21246 21247 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21248 final int count = mSharedLibraries.size(); 21249 for (int i = 0; i < count; i++) { 21250 final String libName = mSharedLibraries.keyAt(i); 21251 LongSparseArray<SharedLibraryEntry> versionedLib = mSharedLibraries.get(libName); 21252 if (versionedLib == null) { 21253 continue; 21254 } 21255 final int versionCount = versionedLib.size(); 21256 for (int j = 0; j < versionCount; j++) { 21257 final SharedLibraryEntry libEntry = versionedLib.valueAt(j); 21258 final long sharedLibraryToken = 21259 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21260 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libEntry.info.getName()); 21261 final boolean isJar = (libEntry.path != null); 21262 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21263 if (isJar) { 21264 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, libEntry.path); 21265 } else { 21266 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, libEntry.apk); 21267 } 21268 proto.end(sharedLibraryToken); 21269 } 21270 } 21271 } 21272 21273 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21274 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21275 ipw.println(); 21276 ipw.println("Dexopt state:"); 21277 ipw.increaseIndent(); 21278 Collection<PackageParser.Package> packages = null; 21279 if (packageName != null) { 21280 PackageParser.Package targetPackage = mPackages.get(packageName); 21281 if (targetPackage != null) { 21282 packages = Collections.singletonList(targetPackage); 21283 } else { 21284 ipw.println("Unable to find package: " + packageName); 21285 return; 21286 } 21287 } else { 21288 packages = mPackages.values(); 21289 } 21290 21291 for (PackageParser.Package pkg : packages) { 21292 ipw.println("[" + pkg.packageName + "]"); 21293 ipw.increaseIndent(); 21294 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21295 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21296 ipw.decreaseIndent(); 21297 } 21298 } 21299 21300 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21301 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21302 ipw.println(); 21303 ipw.println("Compiler stats:"); 21304 ipw.increaseIndent(); 21305 Collection<PackageParser.Package> packages = null; 21306 if (packageName != null) { 21307 PackageParser.Package targetPackage = mPackages.get(packageName); 21308 if (targetPackage != null) { 21309 packages = Collections.singletonList(targetPackage); 21310 } else { 21311 ipw.println("Unable to find package: " + packageName); 21312 return; 21313 } 21314 } else { 21315 packages = mPackages.values(); 21316 } 21317 21318 for (PackageParser.Package pkg : packages) { 21319 ipw.println("[" + pkg.packageName + "]"); 21320 ipw.increaseIndent(); 21321 21322 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21323 if (stats == null) { 21324 ipw.println("(No recorded stats)"); 21325 } else { 21326 stats.dump(ipw); 21327 } 21328 ipw.decreaseIndent(); 21329 } 21330 } 21331 21332 private String dumpDomainString(String packageName) { 21333 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 21334 .getList(); 21335 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 21336 21337 ArraySet<String> result = new ArraySet<>(); 21338 if (iviList.size() > 0) { 21339 for (IntentFilterVerificationInfo ivi : iviList) { 21340 for (String host : ivi.getDomains()) { 21341 result.add(host); 21342 } 21343 } 21344 } 21345 if (filters != null && filters.size() > 0) { 21346 for (IntentFilter filter : filters) { 21347 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 21348 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 21349 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 21350 result.addAll(filter.getHostsList()); 21351 } 21352 } 21353 } 21354 21355 StringBuilder sb = new StringBuilder(result.size() * 16); 21356 for (String domain : result) { 21357 if (sb.length() > 0) sb.append(" "); 21358 sb.append(domain); 21359 } 21360 return sb.toString(); 21361 } 21362 21363 // ------- apps on sdcard specific code ------- 21364 static final boolean DEBUG_SD_INSTALL = false; 21365 21366 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 21367 21368 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 21369 21370 private boolean mMediaMounted = false; 21371 21372 static String getEncryptKey() { 21373 try { 21374 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 21375 SD_ENCRYPTION_KEYSTORE_NAME); 21376 if (sdEncKey == null) { 21377 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 21378 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 21379 if (sdEncKey == null) { 21380 Slog.e(TAG, "Failed to create encryption keys"); 21381 return null; 21382 } 21383 } 21384 return sdEncKey; 21385 } catch (NoSuchAlgorithmException nsae) { 21386 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 21387 return null; 21388 } catch (IOException ioe) { 21389 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 21390 return null; 21391 } 21392 } 21393 21394 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21395 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 21396 final int size = infos.size(); 21397 final String[] packageNames = new String[size]; 21398 final int[] packageUids = new int[size]; 21399 for (int i = 0; i < size; i++) { 21400 final ApplicationInfo info = infos.get(i); 21401 packageNames[i] = info.packageName; 21402 packageUids[i] = info.uid; 21403 } 21404 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 21405 finishedReceiver); 21406 } 21407 21408 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21409 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21410 sendResourcesChangedBroadcast(mediaStatus, replacing, 21411 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 21412 } 21413 21414 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 21415 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 21416 int size = pkgList.length; 21417 if (size > 0) { 21418 // Send broadcasts here 21419 Bundle extras = new Bundle(); 21420 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 21421 if (uidArr != null) { 21422 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 21423 } 21424 if (replacing) { 21425 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 21426 } 21427 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 21428 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 21429 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 21430 } 21431 } 21432 21433 private void loadPrivatePackages(final VolumeInfo vol) { 21434 mHandler.post(new Runnable() { 21435 @Override 21436 public void run() { 21437 loadPrivatePackagesInner(vol); 21438 } 21439 }); 21440 } 21441 21442 private void loadPrivatePackagesInner(VolumeInfo vol) { 21443 final String volumeUuid = vol.fsUuid; 21444 if (TextUtils.isEmpty(volumeUuid)) { 21445 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 21446 return; 21447 } 21448 21449 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 21450 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 21451 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 21452 21453 final VersionInfo ver; 21454 final List<PackageSetting> packages; 21455 synchronized (mPackages) { 21456 ver = mSettings.findOrCreateVersion(volumeUuid); 21457 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21458 } 21459 21460 for (PackageSetting ps : packages) { 21461 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 21462 synchronized (mInstallLock) { 21463 final PackageParser.Package pkg; 21464 try { 21465 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 21466 loaded.add(pkg.applicationInfo); 21467 21468 } catch (PackageManagerException e) { 21469 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 21470 } 21471 21472 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 21473 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 21474 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 21475 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 21476 } 21477 } 21478 } 21479 21480 // Reconcile app data for all started/unlocked users 21481 final StorageManager sm = mContext.getSystemService(StorageManager.class); 21482 final UserManager um = mContext.getSystemService(UserManager.class); 21483 UserManagerInternal umInternal = getUserManagerInternal(); 21484 for (UserInfo user : um.getUsers()) { 21485 final int flags; 21486 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21487 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21488 } else if (umInternal.isUserRunning(user.id)) { 21489 flags = StorageManager.FLAG_STORAGE_DE; 21490 } else { 21491 continue; 21492 } 21493 21494 try { 21495 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 21496 synchronized (mInstallLock) { 21497 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 21498 } 21499 } catch (IllegalStateException e) { 21500 // Device was probably ejected, and we'll process that event momentarily 21501 Slog.w(TAG, "Failed to prepare storage: " + e); 21502 } 21503 } 21504 21505 synchronized (mPackages) { 21506 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 21507 if (sdkUpdated) { 21508 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 21509 + mSdkVersion + "; regranting permissions for " + volumeUuid); 21510 } 21511 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 21512 mPermissionCallback); 21513 21514 // Yay, everything is now upgraded 21515 ver.forceCurrent(); 21516 21517 mSettings.writeLPr(); 21518 } 21519 21520 for (PackageFreezer freezer : freezers) { 21521 freezer.close(); 21522 } 21523 21524 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 21525 sendResourcesChangedBroadcast(true, false, loaded, null); 21526 mLoadedVolumes.add(vol.getId()); 21527 } 21528 21529 private void unloadPrivatePackages(final VolumeInfo vol) { 21530 mHandler.post(new Runnable() { 21531 @Override 21532 public void run() { 21533 unloadPrivatePackagesInner(vol); 21534 } 21535 }); 21536 } 21537 21538 private void unloadPrivatePackagesInner(VolumeInfo vol) { 21539 final String volumeUuid = vol.fsUuid; 21540 if (TextUtils.isEmpty(volumeUuid)) { 21541 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 21542 return; 21543 } 21544 21545 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 21546 synchronized (mInstallLock) { 21547 synchronized (mPackages) { 21548 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 21549 for (PackageSetting ps : packages) { 21550 if (ps.pkg == null) continue; 21551 21552 final ApplicationInfo info = ps.pkg.applicationInfo; 21553 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 21554 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 21555 21556 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 21557 "unloadPrivatePackagesInner")) { 21558 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 21559 false, null)) { 21560 unloaded.add(info); 21561 } else { 21562 Slog.w(TAG, "Failed to unload " + ps.codePath); 21563 } 21564 } 21565 21566 // Try very hard to release any references to this package 21567 // so we don't risk the system server being killed due to 21568 // open FDs 21569 AttributeCache.instance().removePackage(ps.name); 21570 } 21571 21572 mSettings.writeLPr(); 21573 } 21574 } 21575 21576 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 21577 sendResourcesChangedBroadcast(false, false, unloaded, null); 21578 mLoadedVolumes.remove(vol.getId()); 21579 21580 // Try very hard to release any references to this path so we don't risk 21581 // the system server being killed due to open FDs 21582 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 21583 21584 for (int i = 0; i < 3; i++) { 21585 System.gc(); 21586 System.runFinalization(); 21587 } 21588 } 21589 21590 private void assertPackageKnown(String volumeUuid, String packageName) 21591 throws PackageManagerException { 21592 synchronized (mPackages) { 21593 // Normalize package name to handle renamed packages 21594 packageName = normalizePackageNameLPr(packageName); 21595 21596 final PackageSetting ps = mSettings.mPackages.get(packageName); 21597 if (ps == null) { 21598 throw new PackageManagerException("Package " + packageName + " is unknown"); 21599 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21600 throw new PackageManagerException( 21601 "Package " + packageName + " found on unknown volume " + volumeUuid 21602 + "; expected volume " + ps.volumeUuid); 21603 } 21604 } 21605 } 21606 21607 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 21608 throws PackageManagerException { 21609 synchronized (mPackages) { 21610 // Normalize package name to handle renamed packages 21611 packageName = normalizePackageNameLPr(packageName); 21612 21613 final PackageSetting ps = mSettings.mPackages.get(packageName); 21614 if (ps == null) { 21615 throw new PackageManagerException("Package " + packageName + " is unknown"); 21616 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 21617 throw new PackageManagerException( 21618 "Package " + packageName + " found on unknown volume " + volumeUuid 21619 + "; expected volume " + ps.volumeUuid); 21620 } else if (!ps.getInstalled(userId)) { 21621 throw new PackageManagerException( 21622 "Package " + packageName + " not installed for user " + userId); 21623 } 21624 } 21625 } 21626 21627 private List<String> collectAbsoluteCodePaths() { 21628 synchronized (mPackages) { 21629 List<String> codePaths = new ArrayList<>(); 21630 final int packageCount = mSettings.mPackages.size(); 21631 for (int i = 0; i < packageCount; i++) { 21632 final PackageSetting ps = mSettings.mPackages.valueAt(i); 21633 codePaths.add(ps.codePath.getAbsolutePath()); 21634 } 21635 return codePaths; 21636 } 21637 } 21638 21639 /** 21640 * Examine all apps present on given mounted volume, and destroy apps that 21641 * aren't expected, either due to uninstallation or reinstallation on 21642 * another volume. 21643 */ 21644 private void reconcileApps(String volumeUuid) { 21645 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 21646 List<File> filesToDelete = null; 21647 21648 final File[] files = FileUtils.listFilesOrEmpty( 21649 Environment.getDataAppDirectory(volumeUuid)); 21650 for (File file : files) { 21651 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 21652 && !PackageInstallerService.isStageName(file.getName()); 21653 if (!isPackage) { 21654 // Ignore entries which are not packages 21655 continue; 21656 } 21657 21658 String absolutePath = file.getAbsolutePath(); 21659 21660 boolean pathValid = false; 21661 final int absoluteCodePathCount = absoluteCodePaths.size(); 21662 for (int i = 0; i < absoluteCodePathCount; i++) { 21663 String absoluteCodePath = absoluteCodePaths.get(i); 21664 if (absolutePath.startsWith(absoluteCodePath)) { 21665 pathValid = true; 21666 break; 21667 } 21668 } 21669 21670 if (!pathValid) { 21671 if (filesToDelete == null) { 21672 filesToDelete = new ArrayList<>(); 21673 } 21674 filesToDelete.add(file); 21675 } 21676 } 21677 21678 if (filesToDelete != null) { 21679 final int fileToDeleteCount = filesToDelete.size(); 21680 for (int i = 0; i < fileToDeleteCount; i++) { 21681 File fileToDelete = filesToDelete.get(i); 21682 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 21683 synchronized (mInstallLock) { 21684 removeCodePathLI(fileToDelete); 21685 } 21686 } 21687 } 21688 } 21689 21690 /** 21691 * Reconcile all app data for the given user. 21692 * <p> 21693 * Verifies that directories exist and that ownership and labeling is 21694 * correct for all installed apps on all mounted volumes. 21695 */ 21696 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 21697 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21698 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 21699 final String volumeUuid = vol.getFsUuid(); 21700 synchronized (mInstallLock) { 21701 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 21702 } 21703 } 21704 } 21705 21706 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21707 boolean migrateAppData) { 21708 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 21709 } 21710 21711 /** 21712 * Reconcile all app data on given mounted volume. 21713 * <p> 21714 * Destroys app data that isn't expected, either due to uninstallation or 21715 * reinstallation on another volume. 21716 * <p> 21717 * Verifies that directories exist and that ownership and labeling is 21718 * correct for all installed apps. 21719 * @returns list of skipped non-core packages (if {@code onlyCoreApps} is true) 21720 */ 21721 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 21722 boolean migrateAppData, boolean onlyCoreApps) { 21723 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 21724 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 21725 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 21726 21727 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 21728 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 21729 21730 // First look for stale data that doesn't belong, and check if things 21731 // have changed since we did our last restorecon 21732 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21733 if (StorageManager.isFileEncryptedNativeOrEmulated() 21734 && !StorageManager.isUserKeyUnlocked(userId)) { 21735 throw new RuntimeException( 21736 "Yikes, someone asked us to reconcile CE storage while " + userId 21737 + " was still locked; this would have caused massive data loss!"); 21738 } 21739 21740 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 21741 for (File file : files) { 21742 final String packageName = file.getName(); 21743 try { 21744 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21745 } catch (PackageManagerException e) { 21746 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21747 try { 21748 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21749 StorageManager.FLAG_STORAGE_CE, 0); 21750 } catch (InstallerException e2) { 21751 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21752 } 21753 } 21754 } 21755 } 21756 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 21757 final File[] files = FileUtils.listFilesOrEmpty(deDir); 21758 for (File file : files) { 21759 final String packageName = file.getName(); 21760 try { 21761 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 21762 } catch (PackageManagerException e) { 21763 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 21764 try { 21765 mInstaller.destroyAppData(volumeUuid, packageName, userId, 21766 StorageManager.FLAG_STORAGE_DE, 0); 21767 } catch (InstallerException e2) { 21768 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 21769 } 21770 } 21771 } 21772 } 21773 21774 // Ensure that data directories are ready to roll for all packages 21775 // installed for this volume and user 21776 final List<PackageSetting> packages; 21777 synchronized (mPackages) { 21778 packages = mSettings.getVolumePackagesLPr(volumeUuid); 21779 } 21780 int preparedCount = 0; 21781 for (PackageSetting ps : packages) { 21782 final String packageName = ps.name; 21783 if (ps.pkg == null) { 21784 Slog.w(TAG, "Odd, missing scanned package " + packageName); 21785 // TODO: might be due to legacy ASEC apps; we should circle back 21786 // and reconcile again once they're scanned 21787 continue; 21788 } 21789 // Skip non-core apps if requested 21790 if (onlyCoreApps && !ps.pkg.coreApp) { 21791 result.add(packageName); 21792 continue; 21793 } 21794 21795 if (ps.getInstalled(userId)) { 21796 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 21797 preparedCount++; 21798 } 21799 } 21800 21801 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 21802 return result; 21803 } 21804 21805 /** 21806 * Prepare app data for the given app just after it was installed or 21807 * upgraded. This method carefully only touches users that it's installed 21808 * for, and it forces a restorecon to handle any seinfo changes. 21809 * <p> 21810 * Verifies that directories exist and that ownership and labeling is 21811 * correct for all installed apps. If there is an ownership mismatch, it 21812 * will try recovering system apps by wiping data; third-party app data is 21813 * left intact. 21814 * <p> 21815 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 21816 */ 21817 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 21818 final PackageSetting ps; 21819 synchronized (mPackages) { 21820 ps = mSettings.mPackages.get(pkg.packageName); 21821 mSettings.writeKernelMappingLPr(ps); 21822 } 21823 21824 final UserManager um = mContext.getSystemService(UserManager.class); 21825 UserManagerInternal umInternal = getUserManagerInternal(); 21826 for (UserInfo user : um.getUsers()) { 21827 final int flags; 21828 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 21829 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 21830 } else if (umInternal.isUserRunning(user.id)) { 21831 flags = StorageManager.FLAG_STORAGE_DE; 21832 } else { 21833 continue; 21834 } 21835 21836 if (ps.getInstalled(user.id)) { 21837 // TODO: when user data is locked, mark that we're still dirty 21838 prepareAppDataLIF(pkg, user.id, flags); 21839 } 21840 } 21841 } 21842 21843 /** 21844 * Prepare app data for the given app. 21845 * <p> 21846 * Verifies that directories exist and that ownership and labeling is 21847 * correct for all installed apps. If there is an ownership mismatch, this 21848 * will try recovering system apps by wiping data; third-party app data is 21849 * left intact. 21850 */ 21851 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 21852 if (pkg == null) { 21853 Slog.wtf(TAG, "Package was null!", new Throwable()); 21854 return; 21855 } 21856 prepareAppDataLeafLIF(pkg, userId, flags); 21857 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21858 for (int i = 0; i < childCount; i++) { 21859 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 21860 } 21861 } 21862 21863 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 21864 boolean maybeMigrateAppData) { 21865 prepareAppDataLIF(pkg, userId, flags); 21866 21867 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 21868 // We may have just shuffled around app data directories, so 21869 // prepare them one more time 21870 prepareAppDataLIF(pkg, userId, flags); 21871 } 21872 } 21873 21874 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21875 if (DEBUG_APP_DATA) { 21876 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 21877 + Integer.toHexString(flags)); 21878 } 21879 21880 final String volumeUuid = pkg.volumeUuid; 21881 final String packageName = pkg.packageName; 21882 final ApplicationInfo app = pkg.applicationInfo; 21883 final int appId = UserHandle.getAppId(app.uid); 21884 21885 Preconditions.checkNotNull(app.seInfo); 21886 21887 long ceDataInode = -1; 21888 try { 21889 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21890 appId, app.seInfo, app.targetSdkVersion); 21891 } catch (InstallerException e) { 21892 if (app.isSystemApp()) { 21893 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 21894 + ", but trying to recover: " + e); 21895 destroyAppDataLeafLIF(pkg, userId, flags); 21896 try { 21897 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 21898 appId, app.seInfo, app.targetSdkVersion); 21899 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 21900 } catch (InstallerException e2) { 21901 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 21902 } 21903 } else { 21904 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 21905 } 21906 } 21907 21908 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 21909 // TODO: mark this structure as dirty so we persist it! 21910 synchronized (mPackages) { 21911 final PackageSetting ps = mSettings.mPackages.get(packageName); 21912 if (ps != null) { 21913 ps.setCeDataInode(ceDataInode, userId); 21914 } 21915 } 21916 } 21917 21918 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21919 } 21920 21921 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 21922 if (pkg == null) { 21923 Slog.wtf(TAG, "Package was null!", new Throwable()); 21924 return; 21925 } 21926 prepareAppDataContentsLeafLIF(pkg, userId, flags); 21927 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 21928 for (int i = 0; i < childCount; i++) { 21929 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 21930 } 21931 } 21932 21933 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 21934 final String volumeUuid = pkg.volumeUuid; 21935 final String packageName = pkg.packageName; 21936 final ApplicationInfo app = pkg.applicationInfo; 21937 21938 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 21939 // Create a native library symlink only if we have native libraries 21940 // and if the native libraries are 32 bit libraries. We do not provide 21941 // this symlink for 64 bit libraries. 21942 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 21943 final String nativeLibPath = app.nativeLibraryDir; 21944 try { 21945 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 21946 nativeLibPath, userId); 21947 } catch (InstallerException e) { 21948 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 21949 } 21950 } 21951 } 21952 } 21953 21954 /** 21955 * For system apps on non-FBE devices, this method migrates any existing 21956 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 21957 * requested by the app. 21958 */ 21959 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 21960 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 21961 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 21962 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 21963 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 21964 try { 21965 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 21966 storageTarget); 21967 } catch (InstallerException e) { 21968 logCriticalInfo(Log.WARN, 21969 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 21970 } 21971 return true; 21972 } else { 21973 return false; 21974 } 21975 } 21976 21977 public PackageFreezer freezePackage(String packageName, String killReason) { 21978 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 21979 } 21980 21981 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 21982 return new PackageFreezer(packageName, userId, killReason); 21983 } 21984 21985 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 21986 String killReason) { 21987 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 21988 } 21989 21990 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 21991 String killReason) { 21992 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 21993 return new PackageFreezer(); 21994 } else { 21995 return freezePackage(packageName, userId, killReason); 21996 } 21997 } 21998 21999 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22000 String killReason) { 22001 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22002 } 22003 22004 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22005 String killReason) { 22006 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22007 return new PackageFreezer(); 22008 } else { 22009 return freezePackage(packageName, userId, killReason); 22010 } 22011 } 22012 22013 /** 22014 * Class that freezes and kills the given package upon creation, and 22015 * unfreezes it upon closing. This is typically used when doing surgery on 22016 * app code/data to prevent the app from running while you're working. 22017 */ 22018 private class PackageFreezer implements AutoCloseable { 22019 private final String mPackageName; 22020 private final PackageFreezer[] mChildren; 22021 22022 private final boolean mWeFroze; 22023 22024 private final AtomicBoolean mClosed = new AtomicBoolean(); 22025 private final CloseGuard mCloseGuard = CloseGuard.get(); 22026 22027 /** 22028 * Create and return a stub freezer that doesn't actually do anything, 22029 * typically used when someone requested 22030 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22031 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22032 */ 22033 public PackageFreezer() { 22034 mPackageName = null; 22035 mChildren = null; 22036 mWeFroze = false; 22037 mCloseGuard.open("close"); 22038 } 22039 22040 public PackageFreezer(String packageName, int userId, String killReason) { 22041 synchronized (mPackages) { 22042 mPackageName = packageName; 22043 mWeFroze = mFrozenPackages.add(mPackageName); 22044 22045 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22046 if (ps != null) { 22047 killApplication(ps.name, ps.appId, userId, killReason); 22048 } 22049 22050 final PackageParser.Package p = mPackages.get(packageName); 22051 if (p != null && p.childPackages != null) { 22052 final int N = p.childPackages.size(); 22053 mChildren = new PackageFreezer[N]; 22054 for (int i = 0; i < N; i++) { 22055 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22056 userId, killReason); 22057 } 22058 } else { 22059 mChildren = null; 22060 } 22061 } 22062 mCloseGuard.open("close"); 22063 } 22064 22065 @Override 22066 protected void finalize() throws Throwable { 22067 try { 22068 if (mCloseGuard != null) { 22069 mCloseGuard.warnIfOpen(); 22070 } 22071 22072 close(); 22073 } finally { 22074 super.finalize(); 22075 } 22076 } 22077 22078 @Override 22079 public void close() { 22080 mCloseGuard.close(); 22081 if (mClosed.compareAndSet(false, true)) { 22082 synchronized (mPackages) { 22083 if (mWeFroze) { 22084 mFrozenPackages.remove(mPackageName); 22085 } 22086 22087 if (mChildren != null) { 22088 for (PackageFreezer freezer : mChildren) { 22089 freezer.close(); 22090 } 22091 } 22092 } 22093 } 22094 } 22095 } 22096 22097 /** 22098 * Verify that given package is currently frozen. 22099 */ 22100 private void checkPackageFrozen(String packageName) { 22101 synchronized (mPackages) { 22102 if (!mFrozenPackages.contains(packageName)) { 22103 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22104 } 22105 } 22106 } 22107 22108 @Override 22109 public int movePackage(final String packageName, final String volumeUuid) { 22110 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22111 22112 final int callingUid = Binder.getCallingUid(); 22113 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22114 final int moveId = mNextMoveId.getAndIncrement(); 22115 mHandler.post(new Runnable() { 22116 @Override 22117 public void run() { 22118 try { 22119 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22120 } catch (PackageManagerException e) { 22121 Slog.w(TAG, "Failed to move " + packageName, e); 22122 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22123 } 22124 } 22125 }); 22126 return moveId; 22127 } 22128 22129 private void movePackageInternal(final String packageName, final String volumeUuid, 22130 final int moveId, final int callingUid, UserHandle user) 22131 throws PackageManagerException { 22132 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22133 final PackageManager pm = mContext.getPackageManager(); 22134 22135 final boolean currentAsec; 22136 final String currentVolumeUuid; 22137 final File codeFile; 22138 final String installerPackageName; 22139 final String packageAbiOverride; 22140 final int appId; 22141 final String seinfo; 22142 final String label; 22143 final int targetSdkVersion; 22144 final PackageFreezer freezer; 22145 final int[] installedUserIds; 22146 22147 // reader 22148 synchronized (mPackages) { 22149 final PackageParser.Package pkg = mPackages.get(packageName); 22150 final PackageSetting ps = mSettings.mPackages.get(packageName); 22151 if (pkg == null 22152 || ps == null 22153 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22154 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22155 } 22156 if (pkg.applicationInfo.isSystemApp()) { 22157 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22158 "Cannot move system application"); 22159 } 22160 22161 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22162 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22163 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22164 if (isInternalStorage && !allow3rdPartyOnInternal) { 22165 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22166 "3rd party apps are not allowed on internal storage"); 22167 } 22168 22169 if (pkg.applicationInfo.isExternalAsec()) { 22170 currentAsec = true; 22171 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 22172 } else if (pkg.applicationInfo.isForwardLocked()) { 22173 currentAsec = true; 22174 currentVolumeUuid = "forward_locked"; 22175 } else { 22176 currentAsec = false; 22177 currentVolumeUuid = ps.volumeUuid; 22178 22179 final File probe = new File(pkg.codePath); 22180 final File probeOat = new File(probe, "oat"); 22181 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22182 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22183 "Move only supported for modern cluster style installs"); 22184 } 22185 } 22186 22187 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22188 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22189 "Package already moved to " + volumeUuid); 22190 } 22191 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22192 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22193 "Device admin cannot be moved"); 22194 } 22195 22196 if (mFrozenPackages.contains(packageName)) { 22197 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22198 "Failed to move already frozen package"); 22199 } 22200 22201 codeFile = new File(pkg.codePath); 22202 installerPackageName = ps.installerPackageName; 22203 packageAbiOverride = ps.cpuAbiOverrideString; 22204 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22205 seinfo = pkg.applicationInfo.seInfo; 22206 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22207 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22208 freezer = freezePackage(packageName, "movePackageInternal"); 22209 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22210 } 22211 22212 final Bundle extras = new Bundle(); 22213 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22214 extras.putString(Intent.EXTRA_TITLE, label); 22215 mMoveCallbacks.notifyCreated(moveId, extras); 22216 22217 int installFlags; 22218 final boolean moveCompleteApp; 22219 final File measurePath; 22220 22221 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22222 installFlags = INSTALL_INTERNAL; 22223 moveCompleteApp = !currentAsec; 22224 measurePath = Environment.getDataAppDirectory(volumeUuid); 22225 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22226 installFlags = INSTALL_EXTERNAL; 22227 moveCompleteApp = false; 22228 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22229 } else { 22230 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22231 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22232 || !volume.isMountedWritable()) { 22233 freezer.close(); 22234 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22235 "Move location not mounted private volume"); 22236 } 22237 22238 Preconditions.checkState(!currentAsec); 22239 22240 installFlags = INSTALL_INTERNAL; 22241 moveCompleteApp = true; 22242 measurePath = Environment.getDataAppDirectory(volumeUuid); 22243 } 22244 22245 // If we're moving app data around, we need all the users unlocked 22246 if (moveCompleteApp) { 22247 for (int userId : installedUserIds) { 22248 if (StorageManager.isFileEncryptedNativeOrEmulated() 22249 && !StorageManager.isUserKeyUnlocked(userId)) { 22250 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22251 "User " + userId + " must be unlocked"); 22252 } 22253 } 22254 } 22255 22256 final PackageStats stats = new PackageStats(null, -1); 22257 synchronized (mInstaller) { 22258 for (int userId : installedUserIds) { 22259 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22260 freezer.close(); 22261 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22262 "Failed to measure package size"); 22263 } 22264 } 22265 } 22266 22267 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22268 + stats.dataSize); 22269 22270 final long startFreeBytes = measurePath.getUsableSpace(); 22271 final long sizeBytes; 22272 if (moveCompleteApp) { 22273 sizeBytes = stats.codeSize + stats.dataSize; 22274 } else { 22275 sizeBytes = stats.codeSize; 22276 } 22277 22278 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22279 freezer.close(); 22280 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22281 "Not enough free space to move"); 22282 } 22283 22284 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22285 22286 final CountDownLatch installedLatch = new CountDownLatch(1); 22287 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22288 @Override 22289 public void onUserActionRequired(Intent intent) throws RemoteException { 22290 throw new IllegalStateException(); 22291 } 22292 22293 @Override 22294 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22295 Bundle extras) throws RemoteException { 22296 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22297 + PackageManager.installStatusToString(returnCode, msg)); 22298 22299 installedLatch.countDown(); 22300 freezer.close(); 22301 22302 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22303 switch (status) { 22304 case PackageInstaller.STATUS_SUCCESS: 22305 mMoveCallbacks.notifyStatusChanged(moveId, 22306 PackageManager.MOVE_SUCCEEDED); 22307 break; 22308 case PackageInstaller.STATUS_FAILURE_STORAGE: 22309 mMoveCallbacks.notifyStatusChanged(moveId, 22310 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22311 break; 22312 default: 22313 mMoveCallbacks.notifyStatusChanged(moveId, 22314 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22315 break; 22316 } 22317 } 22318 }; 22319 22320 final MoveInfo move; 22321 if (moveCompleteApp) { 22322 // Kick off a thread to report progress estimates 22323 new Thread() { 22324 @Override 22325 public void run() { 22326 while (true) { 22327 try { 22328 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22329 break; 22330 } 22331 } catch (InterruptedException ignored) { 22332 } 22333 22334 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22335 final int progress = 10 + (int) MathUtils.constrain( 22336 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22337 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22338 } 22339 } 22340 }.start(); 22341 22342 final String dataAppName = codeFile.getName(); 22343 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22344 dataAppName, appId, seinfo, targetSdkVersion); 22345 } else { 22346 move = null; 22347 } 22348 22349 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 22350 22351 final Message msg = mHandler.obtainMessage(INIT_COPY); 22352 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 22353 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 22354 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 22355 packageAbiOverride, null /*grantedPermissions*/, 22356 PackageParser.SigningDetails.UNKNOWN, PackageManager.INSTALL_REASON_UNKNOWN); 22357 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 22358 msg.obj = params; 22359 22360 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 22361 System.identityHashCode(msg.obj)); 22362 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 22363 System.identityHashCode(msg.obj)); 22364 22365 mHandler.sendMessage(msg); 22366 } 22367 22368 @Override 22369 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 22370 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22371 22372 final int realMoveId = mNextMoveId.getAndIncrement(); 22373 final Bundle extras = new Bundle(); 22374 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 22375 mMoveCallbacks.notifyCreated(realMoveId, extras); 22376 22377 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 22378 @Override 22379 public void onCreated(int moveId, Bundle extras) { 22380 // Ignored 22381 } 22382 22383 @Override 22384 public void onStatusChanged(int moveId, int status, long estMillis) { 22385 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 22386 } 22387 }; 22388 22389 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22390 storage.setPrimaryStorageUuid(volumeUuid, callback); 22391 return realMoveId; 22392 } 22393 22394 @Override 22395 public int getMoveStatus(int moveId) { 22396 mContext.enforceCallingOrSelfPermission( 22397 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22398 return mMoveCallbacks.mLastStatus.get(moveId); 22399 } 22400 22401 @Override 22402 public void registerMoveCallback(IPackageMoveObserver callback) { 22403 mContext.enforceCallingOrSelfPermission( 22404 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22405 mMoveCallbacks.register(callback); 22406 } 22407 22408 @Override 22409 public void unregisterMoveCallback(IPackageMoveObserver callback) { 22410 mContext.enforceCallingOrSelfPermission( 22411 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 22412 mMoveCallbacks.unregister(callback); 22413 } 22414 22415 @Override 22416 public boolean setInstallLocation(int loc) { 22417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 22418 null); 22419 if (getInstallLocation() == loc) { 22420 return true; 22421 } 22422 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 22423 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 22424 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 22425 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 22426 return true; 22427 } 22428 return false; 22429 } 22430 22431 @Override 22432 public int getInstallLocation() { 22433 // allow instant app access 22434 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 22435 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 22436 PackageHelper.APP_INSTALL_AUTO); 22437 } 22438 22439 /** Called by UserManagerService */ 22440 void cleanUpUser(UserManagerService userManager, int userHandle) { 22441 synchronized (mPackages) { 22442 mDirtyUsers.remove(userHandle); 22443 mUserNeedsBadging.delete(userHandle); 22444 mSettings.removeUserLPw(userHandle); 22445 mPendingBroadcasts.remove(userHandle); 22446 mInstantAppRegistry.onUserRemovedLPw(userHandle); 22447 removeUnusedPackagesLPw(userManager, userHandle); 22448 } 22449 } 22450 22451 /** 22452 * We're removing userHandle and would like to remove any downloaded packages 22453 * that are no longer in use by any other user. 22454 * @param userHandle the user being removed 22455 */ 22456 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 22457 final boolean DEBUG_CLEAN_APKS = false; 22458 int [] users = userManager.getUserIds(); 22459 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 22460 while (psit.hasNext()) { 22461 PackageSetting ps = psit.next(); 22462 if (ps.pkg == null) { 22463 continue; 22464 } 22465 final String packageName = ps.pkg.packageName; 22466 // Skip over if system app 22467 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22468 continue; 22469 } 22470 if (DEBUG_CLEAN_APKS) { 22471 Slog.i(TAG, "Checking package " + packageName); 22472 } 22473 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 22474 if (keep) { 22475 if (DEBUG_CLEAN_APKS) { 22476 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 22477 } 22478 } else { 22479 for (int i = 0; i < users.length; i++) { 22480 if (users[i] != userHandle && ps.getInstalled(users[i])) { 22481 keep = true; 22482 if (DEBUG_CLEAN_APKS) { 22483 Slog.i(TAG, " Keeping package " + packageName + " for user " 22484 + users[i]); 22485 } 22486 break; 22487 } 22488 } 22489 } 22490 if (!keep) { 22491 if (DEBUG_CLEAN_APKS) { 22492 Slog.i(TAG, " Removing package " + packageName); 22493 } 22494 mHandler.post(new Runnable() { 22495 public void run() { 22496 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22497 userHandle, 0); 22498 } //end run 22499 }); 22500 } 22501 } 22502 } 22503 22504 /** Called by UserManagerService */ 22505 void createNewUser(int userId, String[] disallowedPackages) { 22506 synchronized (mInstallLock) { 22507 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 22508 } 22509 synchronized (mPackages) { 22510 scheduleWritePackageRestrictionsLocked(userId); 22511 scheduleWritePackageListLocked(userId); 22512 applyFactoryDefaultBrowserLPw(userId); 22513 primeDomainVerificationsLPw(userId); 22514 } 22515 } 22516 22517 void onNewUserCreated(final int userId) { 22518 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 22519 synchronized(mPackages) { 22520 // If permission review for legacy apps is required, we represent 22521 // dagerous permissions for such apps as always granted runtime 22522 // permissions to keep per user flag state whether review is needed. 22523 // Hence, if a new user is added we have to propagate dangerous 22524 // permission grants for these legacy apps. 22525 if (mSettings.mPermissions.mPermissionReviewRequired) { 22526// NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 22527 mPermissionManager.updateAllPermissions( 22528 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 22529 mPermissionCallback); 22530 } 22531 } 22532 } 22533 22534 @Override 22535 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 22536 mContext.enforceCallingOrSelfPermission( 22537 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 22538 "Only package verification agents can read the verifier device identity"); 22539 22540 synchronized (mPackages) { 22541 return mSettings.getVerifierDeviceIdentityLPw(); 22542 } 22543 } 22544 22545 @Override 22546 public void setPermissionEnforced(String permission, boolean enforced) { 22547 // TODO: Now that we no longer change GID for storage, this should to away. 22548 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 22549 "setPermissionEnforced"); 22550 if (READ_EXTERNAL_STORAGE.equals(permission)) { 22551 synchronized (mPackages) { 22552 if (mSettings.mReadExternalStorageEnforced == null 22553 || mSettings.mReadExternalStorageEnforced != enforced) { 22554 mSettings.mReadExternalStorageEnforced = 22555 enforced ? Boolean.TRUE : Boolean.FALSE; 22556 mSettings.writeLPr(); 22557 } 22558 } 22559 // kill any non-foreground processes so we restart them and 22560 // grant/revoke the GID. 22561 final IActivityManager am = ActivityManager.getService(); 22562 if (am != null) { 22563 final long token = Binder.clearCallingIdentity(); 22564 try { 22565 am.killProcessesBelowForeground("setPermissionEnforcement"); 22566 } catch (RemoteException e) { 22567 } finally { 22568 Binder.restoreCallingIdentity(token); 22569 } 22570 } 22571 } else { 22572 throw new IllegalArgumentException("No selective enforcement for " + permission); 22573 } 22574 } 22575 22576 @Override 22577 @Deprecated 22578 public boolean isPermissionEnforced(String permission) { 22579 // allow instant applications 22580 return true; 22581 } 22582 22583 @Override 22584 public boolean isStorageLow() { 22585 // allow instant applications 22586 final long token = Binder.clearCallingIdentity(); 22587 try { 22588 final DeviceStorageMonitorInternal 22589 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 22590 if (dsm != null) { 22591 return dsm.isMemoryLow(); 22592 } else { 22593 return false; 22594 } 22595 } finally { 22596 Binder.restoreCallingIdentity(token); 22597 } 22598 } 22599 22600 @Override 22601 public IPackageInstaller getPackageInstaller() { 22602 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 22603 return null; 22604 } 22605 return mInstallerService; 22606 } 22607 22608 @Override 22609 public IArtManager getArtManager() { 22610 return mArtManagerService; 22611 } 22612 22613 private boolean userNeedsBadging(int userId) { 22614 int index = mUserNeedsBadging.indexOfKey(userId); 22615 if (index < 0) { 22616 final UserInfo userInfo; 22617 final long token = Binder.clearCallingIdentity(); 22618 try { 22619 userInfo = sUserManager.getUserInfo(userId); 22620 } finally { 22621 Binder.restoreCallingIdentity(token); 22622 } 22623 final boolean b; 22624 if (userInfo != null && userInfo.isManagedProfile()) { 22625 b = true; 22626 } else { 22627 b = false; 22628 } 22629 mUserNeedsBadging.put(userId, b); 22630 return b; 22631 } 22632 return mUserNeedsBadging.valueAt(index); 22633 } 22634 22635 @Override 22636 public KeySet getKeySetByAlias(String packageName, String alias) { 22637 if (packageName == null || alias == null) { 22638 return null; 22639 } 22640 synchronized(mPackages) { 22641 final PackageParser.Package pkg = mPackages.get(packageName); 22642 if (pkg == null) { 22643 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22644 throw new IllegalArgumentException("Unknown package: " + packageName); 22645 } 22646 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22647 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 22648 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 22649 throw new IllegalArgumentException("Unknown package: " + packageName); 22650 } 22651 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22652 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 22653 } 22654 } 22655 22656 @Override 22657 public KeySet getSigningKeySet(String packageName) { 22658 if (packageName == null) { 22659 return null; 22660 } 22661 synchronized(mPackages) { 22662 final int callingUid = Binder.getCallingUid(); 22663 final int callingUserId = UserHandle.getUserId(callingUid); 22664 final PackageParser.Package pkg = mPackages.get(packageName); 22665 if (pkg == null) { 22666 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22667 throw new IllegalArgumentException("Unknown package: " + packageName); 22668 } 22669 final PackageSetting ps = (PackageSetting) pkg.mExtras; 22670 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 22671 // filter and pretend the package doesn't exist 22672 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 22673 + ", uid:" + callingUid); 22674 throw new IllegalArgumentException("Unknown package: " + packageName); 22675 } 22676 if (pkg.applicationInfo.uid != callingUid 22677 && Process.SYSTEM_UID != callingUid) { 22678 throw new SecurityException("May not access signing KeySet of other apps."); 22679 } 22680 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22681 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 22682 } 22683 } 22684 22685 @Override 22686 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 22687 final int callingUid = Binder.getCallingUid(); 22688 if (getInstantAppPackageName(callingUid) != null) { 22689 return false; 22690 } 22691 if (packageName == null || ks == null) { 22692 return false; 22693 } 22694 synchronized(mPackages) { 22695 final PackageParser.Package pkg = mPackages.get(packageName); 22696 if (pkg == null 22697 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22698 UserHandle.getUserId(callingUid))) { 22699 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22700 throw new IllegalArgumentException("Unknown package: " + packageName); 22701 } 22702 IBinder ksh = ks.getToken(); 22703 if (ksh instanceof KeySetHandle) { 22704 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22705 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 22706 } 22707 return false; 22708 } 22709 } 22710 22711 @Override 22712 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 22713 final int callingUid = Binder.getCallingUid(); 22714 if (getInstantAppPackageName(callingUid) != null) { 22715 return false; 22716 } 22717 if (packageName == null || ks == null) { 22718 return false; 22719 } 22720 synchronized(mPackages) { 22721 final PackageParser.Package pkg = mPackages.get(packageName); 22722 if (pkg == null 22723 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 22724 UserHandle.getUserId(callingUid))) { 22725 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 22726 throw new IllegalArgumentException("Unknown package: " + packageName); 22727 } 22728 IBinder ksh = ks.getToken(); 22729 if (ksh instanceof KeySetHandle) { 22730 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 22731 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 22732 } 22733 return false; 22734 } 22735 } 22736 22737 private void deletePackageIfUnusedLPr(final String packageName) { 22738 PackageSetting ps = mSettings.mPackages.get(packageName); 22739 if (ps == null) { 22740 return; 22741 } 22742 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 22743 // TODO Implement atomic delete if package is unused 22744 // It is currently possible that the package will be deleted even if it is installed 22745 // after this method returns. 22746 mHandler.post(new Runnable() { 22747 public void run() { 22748 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 22749 0, PackageManager.DELETE_ALL_USERS); 22750 } 22751 }); 22752 } 22753 } 22754 22755 /** 22756 * Check and throw if the given before/after packages would be considered a 22757 * downgrade. 22758 */ 22759 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 22760 throws PackageManagerException { 22761 if (after.getLongVersionCode() < before.getLongVersionCode()) { 22762 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22763 "Update version code " + after.versionCode + " is older than current " 22764 + before.getLongVersionCode()); 22765 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 22766 if (after.baseRevisionCode < before.baseRevisionCode) { 22767 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22768 "Update base revision code " + after.baseRevisionCode 22769 + " is older than current " + before.baseRevisionCode); 22770 } 22771 22772 if (!ArrayUtils.isEmpty(after.splitNames)) { 22773 for (int i = 0; i < after.splitNames.length; i++) { 22774 final String splitName = after.splitNames[i]; 22775 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 22776 if (j != -1) { 22777 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 22778 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 22779 "Update split " + splitName + " revision code " 22780 + after.splitRevisionCodes[i] + " is older than current " 22781 + before.splitRevisionCodes[j]); 22782 } 22783 } 22784 } 22785 } 22786 } 22787 } 22788 22789 private static class MoveCallbacks extends Handler { 22790 private static final int MSG_CREATED = 1; 22791 private static final int MSG_STATUS_CHANGED = 2; 22792 22793 private final RemoteCallbackList<IPackageMoveObserver> 22794 mCallbacks = new RemoteCallbackList<>(); 22795 22796 private final SparseIntArray mLastStatus = new SparseIntArray(); 22797 22798 public MoveCallbacks(Looper looper) { 22799 super(looper); 22800 } 22801 22802 public void register(IPackageMoveObserver callback) { 22803 mCallbacks.register(callback); 22804 } 22805 22806 public void unregister(IPackageMoveObserver callback) { 22807 mCallbacks.unregister(callback); 22808 } 22809 22810 @Override 22811 public void handleMessage(Message msg) { 22812 final SomeArgs args = (SomeArgs) msg.obj; 22813 final int n = mCallbacks.beginBroadcast(); 22814 for (int i = 0; i < n; i++) { 22815 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 22816 try { 22817 invokeCallback(callback, msg.what, args); 22818 } catch (RemoteException ignored) { 22819 } 22820 } 22821 mCallbacks.finishBroadcast(); 22822 args.recycle(); 22823 } 22824 22825 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 22826 throws RemoteException { 22827 switch (what) { 22828 case MSG_CREATED: { 22829 callback.onCreated(args.argi1, (Bundle) args.arg2); 22830 break; 22831 } 22832 case MSG_STATUS_CHANGED: { 22833 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 22834 break; 22835 } 22836 } 22837 } 22838 22839 private void notifyCreated(int moveId, Bundle extras) { 22840 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 22841 22842 final SomeArgs args = SomeArgs.obtain(); 22843 args.argi1 = moveId; 22844 args.arg2 = extras; 22845 obtainMessage(MSG_CREATED, args).sendToTarget(); 22846 } 22847 22848 private void notifyStatusChanged(int moveId, int status) { 22849 notifyStatusChanged(moveId, status, -1); 22850 } 22851 22852 private void notifyStatusChanged(int moveId, int status, long estMillis) { 22853 Slog.v(TAG, "Move " + moveId + " status " + status); 22854 22855 final SomeArgs args = SomeArgs.obtain(); 22856 args.argi1 = moveId; 22857 args.argi2 = status; 22858 args.arg3 = estMillis; 22859 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 22860 22861 synchronized (mLastStatus) { 22862 mLastStatus.put(moveId, status); 22863 } 22864 } 22865 } 22866 22867 private final static class OnPermissionChangeListeners extends Handler { 22868 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 22869 22870 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 22871 new RemoteCallbackList<>(); 22872 22873 public OnPermissionChangeListeners(Looper looper) { 22874 super(looper); 22875 } 22876 22877 @Override 22878 public void handleMessage(Message msg) { 22879 switch (msg.what) { 22880 case MSG_ON_PERMISSIONS_CHANGED: { 22881 final int uid = msg.arg1; 22882 handleOnPermissionsChanged(uid); 22883 } break; 22884 } 22885 } 22886 22887 public void addListenerLocked(IOnPermissionsChangeListener listener) { 22888 mPermissionListeners.register(listener); 22889 22890 } 22891 22892 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 22893 mPermissionListeners.unregister(listener); 22894 } 22895 22896 public void onPermissionsChanged(int uid) { 22897 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 22898 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 22899 } 22900 } 22901 22902 private void handleOnPermissionsChanged(int uid) { 22903 final int count = mPermissionListeners.beginBroadcast(); 22904 try { 22905 for (int i = 0; i < count; i++) { 22906 IOnPermissionsChangeListener callback = mPermissionListeners 22907 .getBroadcastItem(i); 22908 try { 22909 callback.onPermissionsChanged(uid); 22910 } catch (RemoteException e) { 22911 Log.e(TAG, "Permission listener is dead", e); 22912 } 22913 } 22914 } finally { 22915 mPermissionListeners.finishBroadcast(); 22916 } 22917 } 22918 } 22919 22920 private class PackageManagerNative extends IPackageManagerNative.Stub { 22921 @Override 22922 public String[] getNamesForUids(int[] uids) throws RemoteException { 22923 final String[] results = PackageManagerService.this.getNamesForUids(uids); 22924 // massage results so they can be parsed by the native binder 22925 for (int i = results.length - 1; i >= 0; --i) { 22926 if (results[i] == null) { 22927 results[i] = ""; 22928 } 22929 } 22930 return results; 22931 } 22932 22933 // NB: this differentiates between preloads and sideloads 22934 @Override 22935 public String getInstallerForPackage(String packageName) throws RemoteException { 22936 final String installerName = getInstallerPackageName(packageName); 22937 if (!TextUtils.isEmpty(installerName)) { 22938 return installerName; 22939 } 22940 // differentiate between preload and sideload 22941 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22942 ApplicationInfo appInfo = getApplicationInfo(packageName, 22943 /*flags*/ 0, 22944 /*userId*/ callingUser); 22945 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 22946 return "preload"; 22947 } 22948 return ""; 22949 } 22950 22951 @Override 22952 public long getVersionCodeForPackage(String packageName) throws RemoteException { 22953 try { 22954 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 22955 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 22956 if (pInfo != null) { 22957 return pInfo.getLongVersionCode(); 22958 } 22959 } catch (Exception e) { 22960 } 22961 return 0; 22962 } 22963 } 22964 22965 private class PackageManagerInternalImpl extends PackageManagerInternal { 22966 @Override 22967 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 22968 int flagValues, int userId) { 22969 PackageManagerService.this.updatePermissionFlags( 22970 permName, packageName, flagMask, flagValues, userId); 22971 } 22972 22973 @Override 22974 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 22975 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 22976 } 22977 22978 @Override 22979 public boolean isInstantApp(String packageName, int userId) { 22980 return PackageManagerService.this.isInstantApp(packageName, userId); 22981 } 22982 22983 @Override 22984 public String getInstantAppPackageName(int uid) { 22985 return PackageManagerService.this.getInstantAppPackageName(uid); 22986 } 22987 22988 @Override 22989 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 22990 synchronized (mPackages) { 22991 return PackageManagerService.this.filterAppAccessLPr( 22992 (PackageSetting) pkg.mExtras, callingUid, userId); 22993 } 22994 } 22995 22996 @Override 22997 public PackageParser.Package getPackage(String packageName) { 22998 synchronized (mPackages) { 22999 packageName = resolveInternalPackageNameLPr( 23000 packageName, PackageManager.VERSION_CODE_HIGHEST); 23001 return mPackages.get(packageName); 23002 } 23003 } 23004 23005 @Override 23006 public PackageList getPackageList(PackageListObserver observer) { 23007 synchronized (mPackages) { 23008 final int N = mPackages.size(); 23009 final ArrayList<String> list = new ArrayList<>(N); 23010 for (int i = 0; i < N; i++) { 23011 list.add(mPackages.keyAt(i)); 23012 } 23013 final PackageList packageList = new PackageList(list, observer); 23014 if (observer != null) { 23015 mPackageListObservers.add(packageList); 23016 } 23017 return packageList; 23018 } 23019 } 23020 23021 @Override 23022 public void removePackageListObserver(PackageListObserver observer) { 23023 synchronized (mPackages) { 23024 mPackageListObservers.remove(observer); 23025 } 23026 } 23027 23028 @Override 23029 public PackageParser.Package getDisabledPackage(String packageName) { 23030 synchronized (mPackages) { 23031 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23032 return (ps != null) ? ps.pkg : null; 23033 } 23034 } 23035 23036 @Override 23037 public String getKnownPackageName(int knownPackage, int userId) { 23038 switch(knownPackage) { 23039 case PackageManagerInternal.PACKAGE_BROWSER: 23040 return getDefaultBrowserPackageName(userId); 23041 case PackageManagerInternal.PACKAGE_INSTALLER: 23042 return mRequiredInstallerPackage; 23043 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23044 return mSetupWizardPackage; 23045 case PackageManagerInternal.PACKAGE_SYSTEM: 23046 return "android"; 23047 case PackageManagerInternal.PACKAGE_VERIFIER: 23048 return mRequiredVerifierPackage; 23049 } 23050 return null; 23051 } 23052 23053 @Override 23054 public boolean isResolveActivityComponent(ComponentInfo component) { 23055 return mResolveActivity.packageName.equals(component.packageName) 23056 && mResolveActivity.name.equals(component.name); 23057 } 23058 23059 @Override 23060 public void setLocationPackagesProvider(PackagesProvider provider) { 23061 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23062 } 23063 23064 @Override 23065 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23066 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23067 } 23068 23069 @Override 23070 public void setSmsAppPackagesProvider(PackagesProvider provider) { 23071 mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider); 23072 } 23073 23074 @Override 23075 public void setDialerAppPackagesProvider(PackagesProvider provider) { 23076 mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider); 23077 } 23078 23079 @Override 23080 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 23081 mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider); 23082 } 23083 23084 @Override 23085 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23086 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23087 } 23088 23089 @Override 23090 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23091 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23092 } 23093 23094 @Override 23095 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 23096 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId); 23097 } 23098 23099 @Override 23100 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 23101 synchronized (mPackages) { 23102 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 23103 } 23104 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId); 23105 } 23106 23107 @Override 23108 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 23109 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager( 23110 packageName, userId); 23111 } 23112 23113 @Override 23114 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23115 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23116 packageName, userId); 23117 } 23118 23119 @Override 23120 public void setKeepUninstalledPackages(final List<String> packageList) { 23121 Preconditions.checkNotNull(packageList); 23122 List<String> removedFromList = null; 23123 synchronized (mPackages) { 23124 if (mKeepUninstalledPackages != null) { 23125 final int packagesCount = mKeepUninstalledPackages.size(); 23126 for (int i = 0; i < packagesCount; i++) { 23127 String oldPackage = mKeepUninstalledPackages.get(i); 23128 if (packageList != null && packageList.contains(oldPackage)) { 23129 continue; 23130 } 23131 if (removedFromList == null) { 23132 removedFromList = new ArrayList<>(); 23133 } 23134 removedFromList.add(oldPackage); 23135 } 23136 } 23137 mKeepUninstalledPackages = new ArrayList<>(packageList); 23138 if (removedFromList != null) { 23139 final int removedCount = removedFromList.size(); 23140 for (int i = 0; i < removedCount; i++) { 23141 deletePackageIfUnusedLPr(removedFromList.get(i)); 23142 } 23143 } 23144 } 23145 } 23146 23147 @Override 23148 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23149 synchronized (mPackages) { 23150 return mPermissionManager.isPermissionsReviewRequired( 23151 mPackages.get(packageName), userId); 23152 } 23153 } 23154 23155 @Override 23156 public PackageInfo getPackageInfo( 23157 String packageName, int flags, int filterCallingUid, int userId) { 23158 return PackageManagerService.this 23159 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23160 flags, filterCallingUid, userId); 23161 } 23162 23163 @Override 23164 public int getPackageUid(String packageName, int flags, int userId) { 23165 return PackageManagerService.this 23166 .getPackageUid(packageName, flags, userId); 23167 } 23168 23169 @Override 23170 public ApplicationInfo getApplicationInfo( 23171 String packageName, int flags, int filterCallingUid, int userId) { 23172 return PackageManagerService.this 23173 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 23174 } 23175 23176 @Override 23177 public ActivityInfo getActivityInfo( 23178 ComponentName component, int flags, int filterCallingUid, int userId) { 23179 return PackageManagerService.this 23180 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 23181 } 23182 23183 @Override 23184 public List<ResolveInfo> queryIntentActivities( 23185 Intent intent, int flags, int filterCallingUid, int userId) { 23186 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23187 return PackageManagerService.this 23188 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 23189 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 23190 } 23191 23192 @Override 23193 public List<ResolveInfo> queryIntentServices( 23194 Intent intent, int flags, int callingUid, int userId) { 23195 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 23196 return PackageManagerService.this 23197 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 23198 false); 23199 } 23200 23201 @Override 23202 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 23203 int userId) { 23204 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 23205 } 23206 23207 @Override 23208 public void setDeviceAndProfileOwnerPackages( 23209 int deviceOwnerUserId, String deviceOwnerPackage, 23210 SparseArray<String> profileOwnerPackages) { 23211 mProtectedPackages.setDeviceAndProfileOwnerPackages( 23212 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 23213 } 23214 23215 @Override 23216 public boolean isPackageDataProtected(int userId, String packageName) { 23217 return mProtectedPackages.isPackageDataProtected(userId, packageName); 23218 } 23219 23220 @Override 23221 public boolean isPackageEphemeral(int userId, String packageName) { 23222 synchronized (mPackages) { 23223 final PackageSetting ps = mSettings.mPackages.get(packageName); 23224 return ps != null ? ps.getInstantApp(userId) : false; 23225 } 23226 } 23227 23228 @Override 23229 public boolean wasPackageEverLaunched(String packageName, int userId) { 23230 synchronized (mPackages) { 23231 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 23232 } 23233 } 23234 23235 @Override 23236 public void grantRuntimePermission(String packageName, String permName, int userId, 23237 boolean overridePolicy) { 23238 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 23239 permName, packageName, overridePolicy, getCallingUid(), userId, 23240 mPermissionCallback); 23241 } 23242 23243 @Override 23244 public void revokeRuntimePermission(String packageName, String permName, int userId, 23245 boolean overridePolicy) { 23246 mPermissionManager.revokeRuntimePermission( 23247 permName, packageName, overridePolicy, getCallingUid(), userId, 23248 mPermissionCallback); 23249 } 23250 23251 @Override 23252 public String getNameForUid(int uid) { 23253 return PackageManagerService.this.getNameForUid(uid); 23254 } 23255 23256 @Override 23257 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 23258 Intent origIntent, String resolvedType, String callingPackage, 23259 Bundle verificationBundle, int userId) { 23260 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 23261 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 23262 userId); 23263 } 23264 23265 @Override 23266 public void grantEphemeralAccess(int userId, Intent intent, 23267 int targetAppId, int ephemeralAppId) { 23268 synchronized (mPackages) { 23269 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 23270 targetAppId, ephemeralAppId); 23271 } 23272 } 23273 23274 @Override 23275 public boolean isInstantAppInstallerComponent(ComponentName component) { 23276 synchronized (mPackages) { 23277 return mInstantAppInstallerActivity != null 23278 && mInstantAppInstallerActivity.getComponentName().equals(component); 23279 } 23280 } 23281 23282 @Override 23283 public void pruneInstantApps() { 23284 mInstantAppRegistry.pruneInstantApps(); 23285 } 23286 23287 @Override 23288 public String getSetupWizardPackageName() { 23289 return mSetupWizardPackage; 23290 } 23291 23292 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 23293 if (policy != null) { 23294 mExternalSourcesPolicy = policy; 23295 } 23296 } 23297 23298 @Override 23299 public boolean isPackagePersistent(String packageName) { 23300 synchronized (mPackages) { 23301 PackageParser.Package pkg = mPackages.get(packageName); 23302 return pkg != null 23303 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 23304 | ApplicationInfo.FLAG_PERSISTENT)) == 23305 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 23306 : false; 23307 } 23308 } 23309 23310 @Override 23311 public boolean isLegacySystemApp(Package pkg) { 23312 synchronized (mPackages) { 23313 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23314 return mPromoteSystemApps 23315 && ps.isSystem() 23316 && mExistingSystemPackages.contains(ps.name); 23317 } 23318 } 23319 23320 @Override 23321 public List<PackageInfo> getOverlayPackages(int userId) { 23322 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 23323 synchronized (mPackages) { 23324 for (PackageParser.Package p : mPackages.values()) { 23325 if (p.mOverlayTarget != null) { 23326 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 23327 if (pkg != null) { 23328 overlayPackages.add(pkg); 23329 } 23330 } 23331 } 23332 } 23333 return overlayPackages; 23334 } 23335 23336 @Override 23337 public List<String> getTargetPackageNames(int userId) { 23338 List<String> targetPackages = new ArrayList<>(); 23339 synchronized (mPackages) { 23340 for (PackageParser.Package p : mPackages.values()) { 23341 if (p.mOverlayTarget == null) { 23342 targetPackages.add(p.packageName); 23343 } 23344 } 23345 } 23346 return targetPackages; 23347 } 23348 23349 @Override 23350 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 23351 @Nullable List<String> overlayPackageNames) { 23352 synchronized (mPackages) { 23353 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 23354 Slog.e(TAG, "failed to find package " + targetPackageName); 23355 return false; 23356 } 23357 ArrayList<String> overlayPaths = null; 23358 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 23359 final int N = overlayPackageNames.size(); 23360 overlayPaths = new ArrayList<>(N); 23361 for (int i = 0; i < N; i++) { 23362 final String packageName = overlayPackageNames.get(i); 23363 final PackageParser.Package pkg = mPackages.get(packageName); 23364 if (pkg == null) { 23365 Slog.e(TAG, "failed to find package " + packageName); 23366 return false; 23367 } 23368 overlayPaths.add(pkg.baseCodePath); 23369 } 23370 } 23371 23372 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 23373 ps.setOverlayPaths(overlayPaths, userId); 23374 return true; 23375 } 23376 } 23377 23378 @Override 23379 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 23380 int flags, int userId, boolean resolveForStart) { 23381 return resolveIntentInternal( 23382 intent, resolvedType, flags, userId, resolveForStart); 23383 } 23384 23385 @Override 23386 public ResolveInfo resolveService(Intent intent, String resolvedType, 23387 int flags, int userId, int callingUid) { 23388 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 23389 } 23390 23391 @Override 23392 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 23393 return PackageManagerService.this.resolveContentProviderInternal( 23394 name, flags, userId); 23395 } 23396 23397 @Override 23398 public void addIsolatedUid(int isolatedUid, int ownerUid) { 23399 synchronized (mPackages) { 23400 mIsolatedOwners.put(isolatedUid, ownerUid); 23401 } 23402 } 23403 23404 @Override 23405 public void removeIsolatedUid(int isolatedUid) { 23406 synchronized (mPackages) { 23407 mIsolatedOwners.delete(isolatedUid); 23408 } 23409 } 23410 23411 @Override 23412 public int getUidTargetSdkVersion(int uid) { 23413 synchronized (mPackages) { 23414 return getUidTargetSdkVersionLockedLPr(uid); 23415 } 23416 } 23417 23418 @Override 23419 public int getPackageTargetSdkVersion(String packageName) { 23420 synchronized (mPackages) { 23421 return getPackageTargetSdkVersionLockedLPr(packageName); 23422 } 23423 } 23424 23425 @Override 23426 public boolean canAccessInstantApps(int callingUid, int userId) { 23427 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 23428 } 23429 23430 @Override 23431 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 23432 synchronized (mPackages) { 23433 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 23434 } 23435 } 23436 23437 @Override 23438 public void notifyPackageUse(String packageName, int reason) { 23439 synchronized (mPackages) { 23440 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 23441 } 23442 } 23443 } 23444 23445 @Override 23446 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 23447 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 23448 synchronized (mPackages) { 23449 final long identity = Binder.clearCallingIdentity(); 23450 try { 23451 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 23452 packageNames, userId); 23453 } finally { 23454 Binder.restoreCallingIdentity(identity); 23455 } 23456 } 23457 } 23458 23459 @Override 23460 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 23461 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 23462 synchronized (mPackages) { 23463 final long identity = Binder.clearCallingIdentity(); 23464 try { 23465 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 23466 packageNames, userId); 23467 } finally { 23468 Binder.restoreCallingIdentity(identity); 23469 } 23470 } 23471 } 23472 23473 private static void enforceSystemOrPhoneCaller(String tag) { 23474 int callingUid = Binder.getCallingUid(); 23475 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 23476 throw new SecurityException( 23477 "Cannot call " + tag + " from UID " + callingUid); 23478 } 23479 } 23480 23481 boolean isHistoricalPackageUsageAvailable() { 23482 return mPackageUsage.isHistoricalPackageUsageAvailable(); 23483 } 23484 23485 /** 23486 * Return a <b>copy</b> of the collection of packages known to the package manager. 23487 * @return A copy of the values of mPackages. 23488 */ 23489 Collection<PackageParser.Package> getPackages() { 23490 synchronized (mPackages) { 23491 return new ArrayList<>(mPackages.values()); 23492 } 23493 } 23494 23495 /** 23496 * Logs process start information (including base APK hash) to the security log. 23497 * @hide 23498 */ 23499 @Override 23500 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 23501 String apkFile, int pid) { 23502 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23503 return; 23504 } 23505 if (!SecurityLog.isLoggingEnabled()) { 23506 return; 23507 } 23508 Bundle data = new Bundle(); 23509 data.putLong("startTimestamp", System.currentTimeMillis()); 23510 data.putString("processName", processName); 23511 data.putInt("uid", uid); 23512 data.putString("seinfo", seinfo); 23513 data.putString("apkFile", apkFile); 23514 data.putInt("pid", pid); 23515 Message msg = mProcessLoggingHandler.obtainMessage( 23516 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 23517 msg.setData(data); 23518 mProcessLoggingHandler.sendMessage(msg); 23519 } 23520 23521 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 23522 return mCompilerStats.getPackageStats(pkgName); 23523 } 23524 23525 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 23526 return getOrCreateCompilerPackageStats(pkg.packageName); 23527 } 23528 23529 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 23530 return mCompilerStats.getOrCreatePackageStats(pkgName); 23531 } 23532 23533 public void deleteCompilerPackageStats(String pkgName) { 23534 mCompilerStats.deletePackageStats(pkgName); 23535 } 23536 23537 @Override 23538 public int getInstallReason(String packageName, int userId) { 23539 final int callingUid = Binder.getCallingUid(); 23540 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23541 true /* requireFullPermission */, false /* checkShell */, 23542 "get install reason"); 23543 synchronized (mPackages) { 23544 final PackageSetting ps = mSettings.mPackages.get(packageName); 23545 if (filterAppAccessLPr(ps, callingUid, userId)) { 23546 return PackageManager.INSTALL_REASON_UNKNOWN; 23547 } 23548 if (ps != null) { 23549 return ps.getInstallReason(userId); 23550 } 23551 } 23552 return PackageManager.INSTALL_REASON_UNKNOWN; 23553 } 23554 23555 @Override 23556 public boolean canRequestPackageInstalls(String packageName, int userId) { 23557 return canRequestPackageInstallsInternal(packageName, 0, userId, 23558 true /* throwIfPermNotDeclared*/); 23559 } 23560 23561 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 23562 boolean throwIfPermNotDeclared) { 23563 int callingUid = Binder.getCallingUid(); 23564 int uid = getPackageUid(packageName, 0, userId); 23565 if (callingUid != uid && callingUid != Process.ROOT_UID 23566 && callingUid != Process.SYSTEM_UID) { 23567 throw new SecurityException( 23568 "Caller uid " + callingUid + " does not own package " + packageName); 23569 } 23570 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 23571 if (info == null) { 23572 return false; 23573 } 23574 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 23575 return false; 23576 } 23577 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 23578 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 23579 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 23580 if (throwIfPermNotDeclared) { 23581 throw new SecurityException("Need to declare " + appOpPermission 23582 + " to call this api"); 23583 } else { 23584 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 23585 return false; 23586 } 23587 } 23588 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId)) { 23589 return false; 23590 } 23591 if (mExternalSourcesPolicy != null) { 23592 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 23593 if (isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_DEFAULT) { 23594 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 23595 } 23596 } 23597 return checkUidPermission(appOpPermission, uid) == PERMISSION_GRANTED; 23598 } 23599 23600 @Override 23601 public ComponentName getInstantAppResolverSettingsComponent() { 23602 return mInstantAppResolverSettingsComponent; 23603 } 23604 23605 @Override 23606 public ComponentName getInstantAppInstallerComponent() { 23607 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23608 return null; 23609 } 23610 return mInstantAppInstallerActivity == null 23611 ? null : mInstantAppInstallerActivity.getComponentName(); 23612 } 23613 23614 @Override 23615 public String getInstantAppAndroidId(String packageName, int userId) { 23616 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 23617 "getInstantAppAndroidId"); 23618 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 23619 true /* requireFullPermission */, false /* checkShell */, 23620 "getInstantAppAndroidId"); 23621 // Make sure the target is an Instant App. 23622 if (!isInstantApp(packageName, userId)) { 23623 return null; 23624 } 23625 synchronized (mPackages) { 23626 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 23627 } 23628 } 23629 23630 boolean canHaveOatDir(String packageName) { 23631 synchronized (mPackages) { 23632 PackageParser.Package p = mPackages.get(packageName); 23633 if (p == null) { 23634 return false; 23635 } 23636 return p.canHaveOatDir(); 23637 } 23638 } 23639 23640 private String getOatDir(PackageParser.Package pkg) { 23641 if (!pkg.canHaveOatDir()) { 23642 return null; 23643 } 23644 File codePath = new File(pkg.codePath); 23645 if (codePath.isDirectory()) { 23646 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 23647 } 23648 return null; 23649 } 23650 23651 void deleteOatArtifactsOfPackage(String packageName) { 23652 final String[] instructionSets; 23653 final List<String> codePaths; 23654 final String oatDir; 23655 final PackageParser.Package pkg; 23656 synchronized (mPackages) { 23657 pkg = mPackages.get(packageName); 23658 } 23659 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 23660 codePaths = pkg.getAllCodePaths(); 23661 oatDir = getOatDir(pkg); 23662 23663 for (String codePath : codePaths) { 23664 for (String isa : instructionSets) { 23665 try { 23666 mInstaller.deleteOdex(codePath, isa, oatDir); 23667 } catch (InstallerException e) { 23668 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 23669 } 23670 } 23671 } 23672 } 23673 23674 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 23675 Set<String> unusedPackages = new HashSet<>(); 23676 long currentTimeInMillis = System.currentTimeMillis(); 23677 synchronized (mPackages) { 23678 for (PackageParser.Package pkg : mPackages.values()) { 23679 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 23680 if (ps == null) { 23681 continue; 23682 } 23683 PackageDexUsage.PackageUseInfo packageUseInfo = 23684 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 23685 if (PackageManagerServiceUtils 23686 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 23687 downgradeTimeThresholdMillis, packageUseInfo, 23688 pkg.getLatestPackageUseTimeInMills(), 23689 pkg.getLatestForegroundPackageUseTimeInMills())) { 23690 unusedPackages.add(pkg.packageName); 23691 } 23692 } 23693 } 23694 return unusedPackages; 23695 } 23696 23697 @Override 23698 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 23699 int userId) { 23700 final int callingUid = Binder.getCallingUid(); 23701 final int callingAppId = UserHandle.getAppId(callingUid); 23702 23703 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23704 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 23705 23706 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23707 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23708 throw new SecurityException("Caller must have the " 23709 + SET_HARMFUL_APP_WARNINGS + " permission."); 23710 } 23711 23712 synchronized(mPackages) { 23713 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 23714 scheduleWritePackageRestrictionsLocked(userId); 23715 } 23716 } 23717 23718 @Nullable 23719 @Override 23720 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 23721 final int callingUid = Binder.getCallingUid(); 23722 final int callingAppId = UserHandle.getAppId(callingUid); 23723 23724 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 23725 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 23726 23727 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 23728 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 23729 throw new SecurityException("Caller must have the " 23730 + SET_HARMFUL_APP_WARNINGS + " permission."); 23731 } 23732 23733 synchronized(mPackages) { 23734 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 23735 } 23736 } 23737} 23738 23739interface PackageSender { 23740 /** 23741 * @param userIds User IDs where the action occurred on a full application 23742 * @param instantUserIds User IDs where the action occurred on an instant application 23743 */ 23744 void sendPackageBroadcast(final String action, final String pkg, 23745 final Bundle extras, final int flags, final String targetPkg, 23746 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 23747 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 23748 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 23749 void notifyPackageAdded(String packageName); 23750 void notifyPackageRemoved(String packageName); 23751} 23752