1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 package com.android.server.pm; 17 18 import static android.Manifest.permission.GET_APP_METADATA; 19 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS; 20 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 21 import static android.app.AppOpsManager.MODE_IGNORED; 22 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 28 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 29 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 30 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 31 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 32 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 33 import static android.content.pm.PackageManager.USER_MIN_ASPECT_RATIO_UNSET; 34 import static android.os.Process.INVALID_UID; 35 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 36 import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 37 import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 38 import static android.os.storage.StorageManager.FLAG_STORAGE_EXTERNAL; 39 import static android.provider.DeviceConfig.NAMESPACE_PACKAGE_MANAGER_SERVICE; 40 41 import static com.android.internal.annotations.VisibleForTesting.Visibility; 42 import static com.android.internal.util.FrameworkStatsLog.BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_INIT_TIME; 43 import static com.android.server.pm.DexOptHelper.useArtService; 44 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 45 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 46 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 47 import static com.android.server.pm.PackageManagerServiceUtils.isInstalledByAdb; 48 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 49 50 import android.Manifest; 51 import android.annotation.AppIdInt; 52 import android.annotation.IntDef; 53 import android.annotation.NonNull; 54 import android.annotation.Nullable; 55 import android.annotation.StringRes; 56 import android.annotation.UserIdInt; 57 import android.annotation.WorkerThread; 58 import android.app.ActivityManager; 59 import android.app.AppOpsManager; 60 import android.app.ApplicationExitInfo; 61 import android.app.ApplicationPackageManager; 62 import android.app.BroadcastOptions; 63 import android.app.IActivityManager; 64 import android.app.admin.IDevicePolicyManager; 65 import android.app.admin.SecurityLog; 66 import android.app.backup.IBackupManager; 67 import android.app.role.RoleManager; 68 import android.compat.annotation.ChangeId; 69 import android.compat.annotation.EnabledAfter; 70 import android.content.BroadcastReceiver; 71 import android.content.ComponentName; 72 import android.content.ContentResolver; 73 import android.content.Context; 74 import android.content.IIntentReceiver; 75 import android.content.Intent; 76 import android.content.IntentFilter; 77 import android.content.IntentSender; 78 import android.content.IntentSender.SendIntentException; 79 import android.content.pm.ActivityInfo; 80 import android.content.pm.ApplicationInfo; 81 import android.content.pm.AuxiliaryResolveInfo; 82 import android.content.pm.ChangedPackages; 83 import android.content.pm.Checksum; 84 import android.content.pm.ComponentInfo; 85 import android.content.pm.DataLoaderType; 86 import android.content.pm.FallbackCategoryProvider; 87 import android.content.pm.FeatureInfo; 88 import android.content.pm.IDexModuleRegisterCallback; 89 import android.content.pm.IOnChecksumsReadyListener; 90 import android.content.pm.IPackageDataObserver; 91 import android.content.pm.IPackageDeleteObserver2; 92 import android.content.pm.IPackageLoadingProgressCallback; 93 import android.content.pm.IPackageMoveObserver; 94 import android.content.pm.IncrementalStatesInfo; 95 import android.content.pm.InstallSourceInfo; 96 import android.content.pm.InstantAppInfo; 97 import android.content.pm.InstantAppRequest; 98 import android.content.pm.ModuleInfo; 99 import android.content.pm.PackageInfo; 100 import android.content.pm.PackageInfoLite; 101 import android.content.pm.PackageInstaller; 102 import android.content.pm.PackageManager; 103 import android.content.pm.PackageManager.ComponentEnabledSetting; 104 import android.content.pm.PackageManagerInternal; 105 import android.content.pm.PackagePartitions; 106 import android.content.pm.ParceledListSlice; 107 import android.content.pm.PermissionGroupInfo; 108 import android.content.pm.ProviderInfo; 109 import android.content.pm.ResolveInfo; 110 import android.content.pm.SharedLibraryInfo; 111 import android.content.pm.Signature; 112 import android.content.pm.SigningDetails; 113 import android.content.pm.SuspendDialogInfo; 114 import android.content.pm.TestUtilityService; 115 import android.content.pm.UserInfo; 116 import android.content.pm.UserPackage; 117 import android.content.pm.VerifierDeviceIdentity; 118 import android.content.pm.VersionedPackage; 119 import android.content.pm.overlay.OverlayPaths; 120 import android.content.pm.parsing.PackageLite; 121 import android.content.res.Resources; 122 import android.database.ContentObserver; 123 import android.graphics.Bitmap; 124 import android.hardware.display.DisplayManager; 125 import android.net.Uri; 126 import android.os.Binder; 127 import android.os.Build; 128 import android.os.Bundle; 129 import android.os.Environment; 130 import android.os.FileUtils; 131 import android.os.Handler; 132 import android.os.HandlerThread; 133 import android.os.IBinder; 134 import android.os.Message; 135 import android.os.Parcel; 136 import android.os.ParcelFileDescriptor; 137 import android.os.ParcelableException; 138 import android.os.PersistableBundle; 139 import android.os.Process; 140 import android.os.ReconcileSdkDataArgs; 141 import android.os.RemoteException; 142 import android.os.ResultReceiver; 143 import android.os.ServiceManager; 144 import android.os.ShellCallback; 145 import android.os.SystemClock; 146 import android.os.SystemProperties; 147 import android.os.Trace; 148 import android.os.UserHandle; 149 import android.os.UserManager; 150 import android.os.incremental.IncrementalManager; 151 import android.os.incremental.PerUidReadTimeouts; 152 import android.os.storage.IStorageManager; 153 import android.os.storage.StorageManager; 154 import android.os.storage.StorageManagerInternal; 155 import android.os.storage.VolumeRecord; 156 import android.permission.PermissionManager; 157 import android.provider.DeviceConfig; 158 import android.provider.Settings.Global; 159 import android.provider.Settings.Secure; 160 import android.text.TextUtils; 161 import android.text.format.DateUtils; 162 import android.util.ArrayMap; 163 import android.util.ArraySet; 164 import android.util.DisplayMetrics; 165 import android.util.EventLog; 166 import android.util.ExceptionUtils; 167 import android.util.Log; 168 import android.util.Pair; 169 import android.util.Slog; 170 import android.util.SparseArray; 171 import android.util.SparseBooleanArray; 172 import android.util.Xml; 173 import android.view.Display; 174 175 import com.android.internal.R; 176 import com.android.internal.annotations.GuardedBy; 177 import com.android.internal.annotations.VisibleForTesting; 178 import com.android.internal.app.ResolverActivity; 179 import com.android.internal.content.F2fsUtils; 180 import com.android.internal.content.InstallLocationUtils; 181 import com.android.internal.content.om.OverlayConfig; 182 import com.android.internal.telephony.CarrierAppUtils; 183 import com.android.internal.util.ArrayUtils; 184 import com.android.internal.util.CollectionUtils; 185 import com.android.internal.util.ConcurrentUtils; 186 import com.android.internal.util.DumpUtils; 187 import com.android.internal.util.FrameworkStatsLog; 188 import com.android.internal.util.FunctionalUtils; 189 import com.android.internal.util.Preconditions; 190 import com.android.modules.utils.TypedXmlPullParser; 191 import com.android.modules.utils.TypedXmlSerializer; 192 import com.android.permission.persistence.RuntimePermissionsPersistence; 193 import com.android.server.EventLogTags; 194 import com.android.server.FgThread; 195 import com.android.server.LocalManagerRegistry; 196 import com.android.server.LocalServices; 197 import com.android.server.LockGuard; 198 import com.android.server.PackageWatchdog; 199 import com.android.server.ServiceThread; 200 import com.android.server.SystemConfig; 201 import com.android.server.Watchdog; 202 import com.android.server.apphibernation.AppHibernationManagerInternal; 203 import com.android.server.art.DexUseManagerLocal; 204 import com.android.server.art.model.DeleteResult; 205 import com.android.server.compat.CompatChange; 206 import com.android.server.compat.PlatformCompat; 207 import com.android.server.pm.Installer.InstallerException; 208 import com.android.server.pm.Installer.LegacyDexoptDisabledException; 209 import com.android.server.pm.Settings.VersionInfo; 210 import com.android.server.pm.dex.ArtManagerService; 211 import com.android.server.pm.dex.ArtUtils; 212 import com.android.server.pm.dex.DexManager; 213 import com.android.server.pm.dex.DynamicCodeLogger; 214 import com.android.server.pm.dex.ViewCompiler; 215 import com.android.server.pm.local.PackageManagerLocalImpl; 216 import com.android.server.pm.parsing.PackageInfoUtils; 217 import com.android.server.pm.parsing.PackageParser2; 218 import com.android.server.pm.parsing.pkg.AndroidPackageInternal; 219 import com.android.server.pm.parsing.pkg.AndroidPackageUtils; 220 import com.android.server.pm.parsing.pkg.ParsedPackage; 221 import com.android.server.pm.permission.LegacyPermissionManagerInternal; 222 import com.android.server.pm.permission.LegacyPermissionManagerService; 223 import com.android.server.pm.permission.PermissionManagerService; 224 import com.android.server.pm.permission.PermissionManagerServiceInternal; 225 import com.android.server.pm.pkg.AndroidPackage; 226 import com.android.server.pm.pkg.PackageState; 227 import com.android.server.pm.pkg.PackageStateInternal; 228 import com.android.server.pm.pkg.PackageUserState; 229 import com.android.server.pm.pkg.PackageUserStateInternal; 230 import com.android.server.pm.pkg.SharedUserApi; 231 import com.android.server.pm.pkg.component.ParsedInstrumentation; 232 import com.android.server.pm.pkg.component.ParsedMainComponent; 233 import com.android.server.pm.pkg.mutate.PackageStateMutator; 234 import com.android.server.pm.pkg.mutate.PackageStateWrite; 235 import com.android.server.pm.pkg.mutate.PackageUserStateWrite; 236 import com.android.server.pm.pkg.parsing.ParsingPackageUtils; 237 import com.android.server.pm.resolution.ComponentResolver; 238 import com.android.server.pm.resolution.ComponentResolverApi; 239 import com.android.server.pm.verify.domain.DomainVerificationManagerInternal; 240 import com.android.server.pm.verify.domain.DomainVerificationService; 241 import com.android.server.pm.verify.domain.proxy.DomainVerificationProxy; 242 import com.android.server.sdksandbox.SdkSandboxManagerLocal; 243 import com.android.server.storage.DeviceStorageMonitorInternal; 244 import com.android.server.utils.SnapshotCache; 245 import com.android.server.utils.TimingsTraceAndSlog; 246 import com.android.server.utils.Watchable; 247 import com.android.server.utils.Watched; 248 import com.android.server.utils.WatchedArrayMap; 249 import com.android.server.utils.WatchedSparseBooleanArray; 250 import com.android.server.utils.WatchedSparseIntArray; 251 import com.android.server.utils.Watcher; 252 253 import dalvik.system.VMRuntime; 254 255 import libcore.util.EmptyArray; 256 import libcore.util.HexEncoding; 257 258 import java.io.ByteArrayInputStream; 259 import java.io.ByteArrayOutputStream; 260 import java.io.File; 261 import java.io.FileDescriptor; 262 import java.io.FileNotFoundException; 263 import java.io.IOException; 264 import java.io.InputStream; 265 import java.io.PrintWriter; 266 import java.lang.annotation.Retention; 267 import java.lang.annotation.RetentionPolicy; 268 import java.security.MessageDigest; 269 import java.security.NoSuchAlgorithmException; 270 import java.security.cert.Certificate; 271 import java.security.cert.CertificateException; 272 import java.security.cert.CertificateFactory; 273 import java.security.cert.X509Certificate; 274 import java.util.ArrayList; 275 import java.util.Arrays; 276 import java.util.Collections; 277 import java.util.HashMap; 278 import java.util.Iterator; 279 import java.util.List; 280 import java.util.Map; 281 import java.util.Objects; 282 import java.util.Set; 283 import java.util.concurrent.CountDownLatch; 284 import java.util.concurrent.Executor; 285 import java.util.concurrent.Future; 286 import java.util.concurrent.TimeUnit; 287 import java.util.concurrent.atomic.AtomicInteger; 288 import java.util.concurrent.atomic.AtomicReference; 289 import java.util.function.Consumer; 290 291 /** 292 * Keep track of all those APKs everywhere. 293 * <p> 294 * Internally there are three important locks: 295 * <ul> 296 * <li>{@link #mLock} is used to guard all in-memory parsed package details 297 * and other related state. It is a fine-grained lock that should only be held 298 * momentarily, as it's one of the most contended locks in the system. 299 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 300 * operations typically involve heavy lifting of application data on disk. Since 301 * {@code installd} is single-threaded, and it's operations can often be slow, 302 * this lock should never be acquired while already holding {@link #mLock}. 303 * Conversely, it's safe to acquire {@link #mLock} momentarily while already 304 * holding {@link #mInstallLock}. 305 * <li>{@link #mSnapshotLock} is used to guard access to two snapshot fields: the snapshot 306 * itself and the snapshot invalidation flag. This lock should never be acquired while 307 * already holding {@link #mLock}. Conversely, it's safe to acquire {@link #mLock} 308 * momentarily while already holding {@link #mSnapshotLock}. 309 * </ul> 310 * Many internal methods rely on the caller to hold the appropriate locks, and 311 * this contract is expressed through method name suffixes: 312 * <ul> 313 * <li>fooLI(): the caller must hold {@link #mInstallLock} 314 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 315 * being modified must be frozen 316 * <li>fooLPr(): the caller must hold {@link #mLock} for reading 317 * <li>fooLPw(): the caller must hold {@link #mLock} for writing 318 * </ul> 319 * {@link #mSnapshotLock} is taken in exactly one place - {@code snapshotComputer()}. It 320 * should not be taken anywhere else or used for any other purpose. 321 * <p> 322 * Because this class is very central to the platform's security; please run all 323 * CTS and unit tests whenever making modifications: 324 * 325 * <pre> 326 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 327 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 328 * </pre> 329 */ 330 public class PackageManagerService implements PackageSender, TestUtilityService { 331 332 static final String TAG = "PackageManager"; 333 public static final boolean DEBUG_SETTINGS = false; 334 static final boolean DEBUG_PREFERRED = false; 335 static final boolean DEBUG_UPGRADE = false; 336 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 337 static final boolean DEBUG_BACKUP = false; 338 public static final boolean DEBUG_INSTALL = false; 339 public static final boolean DEBUG_REMOVE = false; 340 static final boolean DEBUG_PACKAGE_INFO = false; 341 static final boolean DEBUG_INTENT_MATCHING = false; 342 public static final boolean DEBUG_PACKAGE_SCANNING = false; 343 static final boolean DEBUG_VERIFY = false; 344 public static final boolean DEBUG_PERMISSIONS = false; 345 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 346 public static final boolean TRACE_SNAPSHOTS = false; 347 private static final boolean DEBUG_PER_UID_READ_TIMEOUTS = false; 348 349 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 350 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 351 // user, but by default initialize to this. 352 public static final boolean DEBUG_DEXOPT = false; 353 354 static final boolean DEBUG_ABI_SELECTION = false; 355 public static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 356 357 static final String SHELL_PACKAGE_NAME = "com.android.shell"; 358 359 static final boolean HIDE_EPHEMERAL_APIS = false; 360 361 static final String PRECOMPILE_LAYOUTS = "pm.precompile_layouts"; 362 363 private static final int RADIO_UID = Process.PHONE_UID; 364 private static final int LOG_UID = Process.LOG_UID; 365 private static final int NFC_UID = Process.NFC_UID; 366 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 367 private static final int SHELL_UID = Process.SHELL_UID; 368 private static final int SE_UID = Process.SE_UID; 369 private static final int NETWORKSTACK_UID = Process.NETWORK_STACK_UID; 370 private static final int UWB_UID = Process.UWB_UID; 371 372 static final int SCAN_NO_DEX = 1 << 0; 373 static final int SCAN_UPDATE_SIGNATURE = 1 << 1; 374 static final int SCAN_NEW_INSTALL = 1 << 2; 375 static final int SCAN_UPDATE_TIME = 1 << 3; 376 static final int SCAN_BOOTING = 1 << 4; 377 static final int SCAN_REQUIRE_KNOWN = 1 << 7; 378 static final int SCAN_MOVE = 1 << 8; 379 static final int SCAN_INITIAL = 1 << 9; 380 static final int SCAN_DONT_KILL_APP = 1 << 10; 381 static final int SCAN_IGNORE_FROZEN = 1 << 11; 382 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1 << 12; 383 static final int SCAN_AS_INSTANT_APP = 1 << 13; 384 static final int SCAN_AS_FULL_APP = 1 << 14; 385 static final int SCAN_AS_VIRTUAL_PRELOAD = 1 << 15; 386 static final int SCAN_AS_SYSTEM = 1 << 16; 387 static final int SCAN_AS_PRIVILEGED = 1 << 17; 388 static final int SCAN_AS_OEM = 1 << 18; 389 static final int SCAN_AS_VENDOR = 1 << 19; 390 static final int SCAN_AS_PRODUCT = 1 << 20; 391 static final int SCAN_AS_SYSTEM_EXT = 1 << 21; 392 static final int SCAN_AS_ODM = 1 << 22; 393 static final int SCAN_AS_APK_IN_APEX = 1 << 23; 394 static final int SCAN_DROP_CACHE = 1 << 24; 395 static final int SCAN_AS_FACTORY = 1 << 25; 396 static final int SCAN_AS_APEX = 1 << 26; 397 static final int SCAN_AS_STOPPED_SYSTEM_APP = 1 << 27; 398 399 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 400 SCAN_NO_DEX, 401 SCAN_UPDATE_SIGNATURE, 402 SCAN_NEW_INSTALL, 403 SCAN_UPDATE_TIME, 404 SCAN_BOOTING, 405 SCAN_REQUIRE_KNOWN, 406 SCAN_MOVE, 407 SCAN_INITIAL, 408 SCAN_DONT_KILL_APP, 409 SCAN_IGNORE_FROZEN, 410 SCAN_FIRST_BOOT_OR_UPGRADE, 411 SCAN_AS_INSTANT_APP, 412 SCAN_AS_FULL_APP, 413 SCAN_AS_VIRTUAL_PRELOAD, 414 SCAN_AS_STOPPED_SYSTEM_APP, 415 }) 416 @Retention(RetentionPolicy.SOURCE) 417 public @interface ScanFlags {} 418 419 /** 420 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 421 * int)}. 422 */ 423 @IntDef(value = { 424 PACKAGE_STARTABILITY_OK, 425 PACKAGE_STARTABILITY_NOT_FOUND, 426 PACKAGE_STARTABILITY_NOT_SYSTEM, 427 PACKAGE_STARTABILITY_FROZEN, 428 PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED, 429 }) 430 @Retention(RetentionPolicy.SOURCE) 431 public @interface PackageStartability {} 432 433 /** 434 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 435 * int)} to indicate the given package is allowed to start. 436 */ 437 public static final int PACKAGE_STARTABILITY_OK = 0; 438 439 /** 440 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 441 * int)} to indicate the given package is <b>not</b> allowed to start because it's not found 442 * (could be due to that package is invisible to the given user). 443 */ 444 public static final int PACKAGE_STARTABILITY_NOT_FOUND = 1; 445 446 /** 447 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 448 * int)} to indicate the given package is <b>not</b> allowed to start because it's not a system 449 * app and the system is running in safe mode. 450 */ 451 public static final int PACKAGE_STARTABILITY_NOT_SYSTEM = 2; 452 453 /** 454 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 455 * int)} to indicate the given package is <b>not</b> allowed to start because it's currently 456 * frozen. 457 */ 458 public static final int PACKAGE_STARTABILITY_FROZEN = 3; 459 460 /** 461 * Used as the result code of the {@link Computer#getPackageStartability(boolean, String, int, 462 * int)} to indicate the given package is <b>not</b> allowed to start because it doesn't support 463 * direct boot. 464 */ 465 public static final int PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED = 4; 466 467 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 468 /** 469 * Extension of the compressed packages 470 */ 471 public final static String COMPRESSED_EXTENSION = ".gz"; 472 /** Suffix of stub packages on the system partition */ 473 public final static String STUB_SUFFIX = "-Stub"; 474 475 static final int[] EMPTY_INT_ARRAY = new int[0]; 476 477 /** 478 * Timeout (in milliseconds) after which the watchdog should declare that 479 * our handler thread is wedged. The usual default for such things is one 480 * minute but we sometimes do very lengthy I/O operations on this thread, 481 * such as installing multi-gigabyte applications, so ours needs to be longer. 482 */ 483 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 484 485 /** 486 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 487 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 488 * settings entry if available, otherwise we use the hardcoded default. If it's been 489 * more than this long since the last fstrim, we force one during the boot sequence. 490 * 491 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 492 * one gets run at the next available charging+idle time. This final mandatory 493 * no-fstrim check kicks in only of the other scheduling criteria is never met. 494 */ 495 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 496 497 /** 498 * Default IncFs timeouts. Maximum values in IncFs is 1hr. 499 * 500 * <p>If flag value is empty, the default value will be assigned. 501 * 502 * Flag type: {@code String} 503 * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE 504 */ 505 private static final String PROPERTY_INCFS_DEFAULT_TIMEOUTS = "incfs_default_timeouts"; 506 507 /** 508 * Known digesters with optional timeouts. 509 * 510 * Flag type: {@code String} 511 * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE 512 */ 513 private static final String PROPERTY_KNOWN_DIGESTERS_LIST = "known_digesters_list"; 514 515 /** 516 * Whether or not requesting the approval before committing sessions is available. 517 * 518 * Flag type: {@code boolean} 519 * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE 520 */ 521 private static final String PROPERTY_IS_PRE_APPROVAL_REQUEST_AVAILABLE = 522 "is_preapproval_available"; 523 524 /** 525 * Whether or not the update ownership enforcement is available. 526 * 527 * Flag type: {@code boolean} 528 * Namespace: NAMESPACE_PACKAGE_MANAGER_SERVICE 529 */ 530 private static final String PROPERTY_IS_UPDATE_OWNERSHIP_ENFORCEMENT_AVAILABLE = 531 "is_update_ownership_enforcement_available"; 532 533 /** 534 * The default response for package verification timeout. 535 * 536 * This can be either PackageManager.VERIFICATION_ALLOW or 537 * PackageManager.VERIFICATION_REJECT. 538 */ 539 static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 540 541 /** 542 * Adding an installer package name to a package that does not have one set requires the 543 * INSTALL_PACKAGES permission. 544 * 545 * If the caller targets R, this will throw a SecurityException. Otherwise the request will 546 * fail silently. In both cases, and regardless of whether this change is enabled, the 547 * installer package will remain unchanged. 548 */ 549 @ChangeId 550 @EnabledAfter(targetSdkVersion = Build.VERSION_CODES.Q) 551 private static final long THROW_EXCEPTION_ON_REQUIRE_INSTALL_PACKAGES_TO_ADD_INSTALLER_PACKAGE = 552 150857253; 553 554 public static final String PLATFORM_PACKAGE_NAME = "android"; 555 556 static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 557 558 static final String PACKAGE_SCHEME = "package"; 559 560 private static final String COMPANION_PACKAGE_NAME = "com.android.companiondevicemanager"; 561 562 // How many required verifiers can be on the system. 563 private static final int REQUIRED_VERIFIERS_MAX_COUNT = 2; 564 565 /** 566 * Specifies the minimum target SDK version an apk must specify in order to be installed 567 * on the system. This improves security and privacy by blocking low 568 * target sdk apps as malware can target older sdk versions to avoid 569 * the enforcement of new API behavior. 570 */ 571 public static final int MIN_INSTALLABLE_TARGET_SDK = Build.VERSION_CODES.M; 572 573 // Compilation reasons. 574 // TODO(b/260124949): Clean this up with the legacy dexopt code. 575 public static final int REASON_FIRST_BOOT = 0; 576 public static final int REASON_BOOT_AFTER_OTA = 1; 577 public static final int REASON_POST_BOOT = 2; 578 public static final int REASON_INSTALL = 3; 579 public static final int REASON_INSTALL_FAST = 4; 580 public static final int REASON_INSTALL_BULK = 5; 581 public static final int REASON_INSTALL_BULK_SECONDARY = 6; 582 public static final int REASON_INSTALL_BULK_DOWNGRADED = 7; 583 public static final int REASON_INSTALL_BULK_SECONDARY_DOWNGRADED = 8; 584 public static final int REASON_BACKGROUND_DEXOPT = 9; 585 public static final int REASON_AB_OTA = 10; 586 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 11; 587 public static final int REASON_CMDLINE = 12; 588 public static final int REASON_BOOT_AFTER_MAINLINE_UPDATE = 13; 589 public static final int REASON_SHARED = 14; 590 591 public static final int REASON_LAST = REASON_SHARED; 592 593 static final String RANDOM_DIR_PREFIX = "~~"; 594 static final char RANDOM_CODEPATH_PREFIX = '-'; 595 596 static final String APP_METADATA_FILE_NAME = "app.metadata"; 597 598 final Handler mHandler; 599 final Handler mBackgroundHandler; 600 601 final ProcessLoggingHandler mProcessLoggingHandler; 602 603 private final boolean mEnableFreeCacheV2; 604 605 private final int mSdkVersion; 606 final Context mContext; 607 final boolean mFactoryTest; 608 final DisplayMetrics mMetrics; 609 private final int mDefParseFlags; 610 private final String[] mSeparateProcesses; 611 private final boolean mIsUpgrade; 612 private final boolean mIsPreNMR1Upgrade; 613 private final boolean mIsPreQUpgrade; 614 615 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 616 // LOCK HELD. Can be called with mInstallLock held. 617 @GuardedBy("mInstallLock") 618 final Installer mInstaller; 619 620 /** Directory where installed applications are stored */ 621 private final File mAppInstallDir; 622 623 // ---------------------------------------------------------------- 624 625 // Lock for state used when installing and doing other long running 626 // operations. Methods that must be called with this lock held have 627 // the suffix "LI". 628 final Object mInstallLock; 629 630 // ---------------------------------------------------------------- 631 632 // Lock for global state used when modifying package state or settings. 633 // Methods that must be called with this lock held have 634 // the suffix "Locked". Some methods may use the legacy suffix "LP" 635 final PackageManagerTracedLock mLock; 636 637 // Ensures order of overlay updates until data storage can be moved to overlay code 638 private final PackageManagerTracedLock mOverlayPathsLock = new PackageManagerTracedLock(); 639 640 // Lock alias for doing package state mutation 641 private final PackageManagerTracedLock mPackageStateWriteLock; 642 643 private final PackageStateMutator mPackageStateMutator = new PackageStateMutator( 644 this::getPackageSettingForMutation, 645 this::getDisabledPackageSettingForMutation); 646 647 // Keys are String (package name), values are Package. 648 @Watched 649 @GuardedBy("mLock") 650 final WatchedArrayMap<String, AndroidPackage> mPackages = new WatchedArrayMap<>(); 651 private final SnapshotCache<WatchedArrayMap<String, AndroidPackage>> mPackagesSnapshot = 652 new SnapshotCache.Auto(mPackages, mPackages, "PackageManagerService.mPackages"); 653 654 // Keys are isolated uids and values are the uid of the application 655 // that created the isolated process. 656 @Watched 657 @GuardedBy("mLock") 658 final WatchedSparseIntArray mIsolatedOwners = new WatchedSparseIntArray(); 659 private final SnapshotCache<WatchedSparseIntArray> mIsolatedOwnersSnapshot = 660 new SnapshotCache.Auto(mIsolatedOwners, mIsolatedOwners, 661 "PackageManagerService.mIsolatedOwners"); 662 663 /** 664 * Tracks existing packages prior to receiving an OTA. Keys are package name. 665 * Only non-null during an OTA, and even then it is nulled again once systemReady(). 666 */ 667 private @Nullable ArraySet<String> mExistingPackages = null; 668 669 /** 670 * List of code paths that need to be released when the system becomes ready. 671 * <p> 672 * NOTE: We have to delay releasing cblocks for no other reason than we cannot 673 * retrieve the setting {@link Secure#RELEASE_COMPRESS_BLOCKS_ON_INSTALL}. When 674 * we no longer need to read that setting, cblock release can occur in the 675 * constructor. 676 * 677 * @see Secure#RELEASE_COMPRESS_BLOCKS_ON_INSTALL 678 * @see #systemReady() 679 */ 680 @Nullable List<File> mReleaseOnSystemReady; 681 682 /** 683 * Whether or not system app permissions should be promoted from install to runtime. 684 */ 685 boolean mPromoteSystemApps; 686 687 private final TestUtilityService mTestUtilityService; 688 689 @Watched 690 @GuardedBy("mLock") 691 final Settings mSettings; 692 693 /** 694 * Map of package names to frozen counts that are currently "frozen", 695 * which means active surgery is being done on the code/data for that 696 * package. The platform will refuse to launch frozen packages to avoid 697 * race conditions. 698 * 699 * @see PackageFreezer 700 */ 701 @GuardedBy("mLock") 702 final WatchedArrayMap<String, Integer> mFrozenPackages = new WatchedArrayMap<>(); 703 private final SnapshotCache<WatchedArrayMap<String, Integer>> mFrozenPackagesSnapshot = 704 new SnapshotCache.Auto(mFrozenPackages, mFrozenPackages, 705 "PackageManagerService.mFrozenPackages"); 706 707 final ProtectedPackages mProtectedPackages; 708 709 private boolean mFirstBoot; 710 711 final boolean mIsEngBuild; 712 private final boolean mIsUserDebugBuild; 713 private final String mIncrementalVersion; 714 715 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 716 717 @GuardedBy("mAvailableFeatures") 718 private final ArrayMap<String, FeatureInfo> mAvailableFeatures; 719 720 @Watched 721 final InstantAppRegistry mInstantAppRegistry; 722 723 @NonNull 724 final ChangedPackagesTracker mChangedPackagesTracker; 725 726 @NonNull 727 private final PackageObserverHelper mPackageObserverHelper = new PackageObserverHelper(); 728 729 private final ModuleInfoProvider mModuleInfoProvider; 730 731 final ApexManager mApexManager; 732 733 final PackageManagerServiceInjector mInjector; 734 735 /** 736 * The list of all system partitions that may contain packages in ascending order of 737 * specificity (the more generic, the earlier in the list a partition appears). 738 */ 739 @VisibleForTesting(visibility = Visibility.PACKAGE) 740 public static final List<ScanPartition> SYSTEM_PARTITIONS = Collections.unmodifiableList( 741 PackagePartitions.getOrderedPartitions(ScanPartition::new)); 742 743 private @NonNull final OverlayConfig mOverlayConfig; 744 745 // Cached parsed flag value. Invalidated on each flag change. 746 PerUidReadTimeouts[] mPerUidReadTimeoutsCache; 747 748 private static final PerUidReadTimeouts[] EMPTY_PER_UID_READ_TIMEOUTS_ARRAY = {}; 749 750 private static class DefaultSystemWrapper implements 751 PackageManagerServiceInjector.SystemWrapper { 752 753 @Override disablePackageCaches()754 public void disablePackageCaches() { 755 // disable all package caches that shouldn't apply within system server 756 PackageManager.disableApplicationInfoCache(); 757 PackageManager.disablePackageInfoCache(); 758 ApplicationPackageManager.invalidateGetPackagesForUidCache(); 759 ApplicationPackageManager.disableGetPackagesForUidCache(); 760 ApplicationPackageManager.invalidateHasSystemFeatureCache(); 761 PackageManager.corkPackageInfoCache(); 762 } 763 764 @Override enablePackageCaches()765 public void enablePackageCaches() { 766 PackageManager.uncorkPackageInfoCache(); 767 } 768 } 769 770 @Watched 771 final AppsFilterImpl mAppsFilter; 772 773 final PackageParser2.Callback mPackageParserCallback; 774 775 // Currently known shared libraries. 776 @Watched 777 private final SharedLibrariesImpl mSharedLibraries; 778 779 // Mapping from instrumentation class names to info about them. 780 @Watched 781 private final WatchedArrayMap<ComponentName, ParsedInstrumentation> mInstrumentation = 782 new WatchedArrayMap<>(); 783 private final SnapshotCache<WatchedArrayMap<ComponentName, ParsedInstrumentation>> 784 mInstrumentationSnapshot = 785 new SnapshotCache.Auto<>(mInstrumentation, mInstrumentation, 786 "PackageManagerService.mInstrumentation"); 787 788 // Packages whose data we have transfered into another package, thus 789 // should no longer exist. 790 final ArraySet<String> mTransferredPackages = new ArraySet<>(); 791 792 // Broadcast actions that are only available to the system. 793 @GuardedBy("mProtectedBroadcasts") 794 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 795 796 /** 797 * List of packages waiting for verification. 798 * Handler thread only! 799 */ 800 final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<>(); 801 802 /** 803 * List of packages waiting for rollback to be enabled. 804 * Handler thread only! 805 */ 806 final SparseArray<VerifyingSession> mPendingEnableRollback = new SparseArray<>(); 807 808 final PackageInstallerService mInstallerService; 809 810 final ArtManagerService mArtManagerService; 811 812 // TODO(b/260124949): Remove these. 813 final PackageDexOptimizer mPackageDexOptimizer; 814 @Nullable 815 final BackgroundDexOptService mBackgroundDexOptService; // null when ART Service is in use. 816 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 817 // is used by other apps). 818 private final DexManager mDexManager; 819 private final DynamicCodeLogger mDynamicCodeLogger; 820 821 final ViewCompiler mViewCompiler; 822 823 private final AtomicInteger mNextMoveId = new AtomicInteger(); 824 final MovePackageHelper.MoveCallbacks mMoveCallbacks; 825 826 /** 827 * Token for keys in mPendingVerification. 828 * Handler thread only! 829 */ 830 int mPendingVerificationToken = 0; 831 832 /** 833 * Token for keys in mPendingEnableRollback. 834 * Handler thread only! 835 */ 836 int mPendingEnableRollbackToken = 0; 837 838 @Watched(manual = true) 839 private volatile boolean mSystemReady; 840 @Watched(manual = true) 841 private volatile boolean mSafeMode; 842 @Watched 843 private final WatchedSparseBooleanArray mWebInstantAppsDisabled = 844 new WatchedSparseBooleanArray(); 845 846 @Watched(manual = true) 847 private ApplicationInfo mAndroidApplication; 848 @Watched(manual = true) 849 private final ActivityInfo mResolveActivity = new ActivityInfo(); 850 private final ResolveInfo mResolveInfo = new ResolveInfo(); 851 @Watched(manual = true) 852 ComponentName mResolveComponentName; 853 private AndroidPackage mPlatformPackage; 854 ComponentName mCustomResolverComponentName; 855 856 // Recorded overlay paths configuration for the Android app info. 857 private String[] mPlatformPackageOverlayPaths = null; 858 private String[] mPlatformPackageOverlayResourceDirs = null; 859 // And the same paths for the replaced resolver activity package 860 private String[] mReplacedResolverPackageOverlayPaths = null; 861 private String[] mReplacedResolverPackageOverlayResourceDirs = null; 862 863 private boolean mResolverReplaced = false; 864 865 @NonNull 866 final DomainVerificationManagerInternal mDomainVerificationManager; 867 868 /** The service connection to the ephemeral resolver */ 869 final InstantAppResolverConnection mInstantAppResolverConnection; 870 /** Component used to show resolver settings for Instant Apps */ 871 final ComponentName mInstantAppResolverSettingsComponent; 872 873 /** Activity used to install instant applications */ 874 @Watched(manual = true) 875 ActivityInfo mInstantAppInstallerActivity; 876 @Watched(manual = true) 877 private final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 878 879 private final Map<String, InstallRequest> 880 mNoKillInstallObservers = Collections.synchronizedMap(new HashMap<>()); 881 882 private final Map<String, InstallRequest> 883 mPendingKillInstallObservers = Collections.synchronizedMap(new HashMap<>()); 884 885 // Internal interface for permission manager 886 final PermissionManagerServiceInternal mPermissionManager; 887 888 @Watched 889 final ComponentResolver mComponentResolver; 890 891 // Set of packages names to keep cached, even if they are uninstalled for all users 892 @GuardedBy("mKeepUninstalledPackages") 893 @NonNull 894 private final ArraySet<String> mKeepUninstalledPackages = new ArraySet<>(); 895 896 // Cached reference to IDevicePolicyManager. 897 private IDevicePolicyManager mDevicePolicyManager = null; 898 899 private File mCacheDir; 900 901 private Future<?> mPrepareAppDataFuture; 902 903 final IncrementalManager mIncrementalManager; 904 905 private final DefaultAppProvider mDefaultAppProvider; 906 907 private final LegacyPermissionManagerInternal mLegacyPermissionManager; 908 909 private final PackageProperty mPackageProperty = new PackageProperty(); 910 911 final PendingPackageBroadcasts mPendingBroadcasts; 912 913 static final int SEND_PENDING_BROADCAST = 1; 914 // public static final int UNUSED = 5; 915 static final int POST_INSTALL = 9; 916 static final int WRITE_SETTINGS = 13; 917 static final int WRITE_DIRTY_PACKAGE_RESTRICTIONS = 14; 918 static final int PACKAGE_VERIFIED = 15; 919 static final int CHECK_PENDING_VERIFICATION = 16; 920 // public static final int UNUSED = 17; 921 // public static final int UNUSED = 18; 922 static final int WRITE_PACKAGE_LIST = 19; 923 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 924 static final int ENABLE_ROLLBACK_STATUS = 21; 925 static final int ENABLE_ROLLBACK_TIMEOUT = 22; 926 static final int DEFERRED_NO_KILL_POST_DELETE = 23; 927 static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24; 928 static final int INTEGRITY_VERIFICATION_COMPLETE = 25; 929 static final int CHECK_PENDING_INTEGRITY_VERIFICATION = 26; 930 static final int DOMAIN_VERIFICATION = 27; 931 static final int PRUNE_UNUSED_STATIC_SHARED_LIBRARIES = 28; 932 static final int DEFERRED_PENDING_KILL_INSTALL_OBSERVER = 29; 933 934 static final int WRITE_USER_PACKAGE_RESTRICTIONS = 30; 935 936 static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000; 937 private static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500; 938 private static final int DEFERRED_PENDING_KILL_INSTALL_OBSERVER_DELAY_MS = 1000; 939 940 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 941 942 private static final long BROADCAST_DELAY_DURING_STARTUP = 10 * 1000L; // 10 seconds (in millis) 943 private static final long BROADCAST_DELAY = 1 * 1000L; // 1 second (in millis) 944 945 private static final long PRUNE_UNUSED_SHARED_LIBRARIES_DELAY = 946 TimeUnit.MINUTES.toMillis(3); // 3 minutes 947 948 // When the service constructor finished plus a delay (used for broadcast delay computation) 949 private long mServiceStartWithDelay; 950 951 private static final long FREE_STORAGE_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 952 TimeUnit.HOURS.toMillis(2); /* two hours */ 953 static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 954 TimeUnit.DAYS.toMillis(7); /* 7 days */ 955 956 final UserManagerService mUserManager; 957 958 final UserNeedsBadgingCache mUserNeedsBadging; 959 960 // Stores a list of users whose package restrictions file needs to be updated 961 final ArraySet<Integer> mDirtyUsers = new ArraySet<>(); 962 963 final SparseArray<InstallRequest> mRunningInstalls = new SparseArray<>(); 964 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 965 966 final @NonNull String[] mRequiredVerifierPackages; 967 final @NonNull String mRequiredInstallerPackage; 968 final @NonNull String mRequiredUninstallerPackage; 969 final @NonNull String mRequiredPermissionControllerPackage; 970 final @Nullable String mSetupWizardPackage; 971 final @Nullable String mStorageManagerPackage; 972 final @Nullable String mDefaultTextClassifierPackage; 973 final @Nullable String mSystemTextClassifierPackageName; 974 final @Nullable String mConfiguratorPackage; 975 final @Nullable String mAppPredictionServicePackage; 976 final @Nullable String mIncidentReportApproverPackage; 977 final @Nullable String mServicesExtensionPackageName; 978 final @Nullable String mSharedSystemSharedLibraryPackageName; 979 final @Nullable String mRetailDemoPackage; 980 final @Nullable String mOverlayConfigSignaturePackage; 981 final @Nullable String mRecentsPackage; 982 final @Nullable String mAmbientContextDetectionPackage; 983 final @Nullable String mWearableSensingPackage; 984 final @NonNull Set<String> mInitialNonStoppedSystemPackages; 985 final boolean mShouldStopSystemPackagesByDefault; 986 private final @NonNull String mRequiredSdkSandboxPackage; 987 988 @GuardedBy("mLock") 989 private final PackageUsage mPackageUsage = new PackageUsage(); 990 final CompilerStats mCompilerStats = new CompilerStats(); 991 992 private final DomainVerificationConnection mDomainVerificationConnection; 993 994 private final BroadcastHelper mBroadcastHelper; 995 private final RemovePackageHelper mRemovePackageHelper; 996 private final DeletePackageHelper mDeletePackageHelper; 997 private final InitAppsHelper mInitAppsHelper; 998 private final AppDataHelper mAppDataHelper; 999 private final InstallPackageHelper mInstallPackageHelper; 1000 private final PreferredActivityHelper mPreferredActivityHelper; 1001 private final ResolveIntentHelper mResolveIntentHelper; 1002 private final DexOptHelper mDexOptHelper; 1003 private final SuspendPackageHelper mSuspendPackageHelper; 1004 private final DistractingPackageHelper mDistractingPackageHelper; 1005 private final StorageEventHelper mStorageEventHelper; 1006 1007 /** 1008 * Invalidate the package info cache, which includes updating the cached computer. 1009 * @hide 1010 */ invalidatePackageInfoCache()1011 public static void invalidatePackageInfoCache() { 1012 PackageManager.invalidatePackageInfoCache(); 1013 onChanged(); 1014 } 1015 1016 private final Watcher mWatcher = new Watcher() { 1017 @Override 1018 public void onChange(@Nullable Watchable what) { 1019 PackageManagerService.onChange(what); 1020 } 1021 }; 1022 1023 /** 1024 * A Snapshot is a subset of PackageManagerService state. A snapshot is either live 1025 * or snapped. Live snapshots directly reference PackageManagerService attributes. 1026 * Snapped snapshots contain deep copies of the attributes. 1027 */ 1028 class Snapshot { 1029 public static final int LIVE = 1; 1030 public static final int SNAPPED = 2; 1031 1032 public final Settings settings; 1033 public final WatchedSparseIntArray isolatedOwners; 1034 public final WatchedArrayMap<String, AndroidPackage> packages; 1035 public final WatchedArrayMap<ComponentName, ParsedInstrumentation> instrumentation; 1036 public final WatchedSparseBooleanArray webInstantAppsDisabled; 1037 public final ComponentName resolveComponentName; 1038 public final ActivityInfo resolveActivity; 1039 public final ActivityInfo instantAppInstallerActivity; 1040 public final ResolveInfo instantAppInstallerInfo; 1041 public final InstantAppRegistry instantAppRegistry; 1042 public final ApplicationInfo androidApplication; 1043 public final String appPredictionServicePackage; 1044 public final AppsFilterSnapshot appsFilter; 1045 public final ComponentResolverApi componentResolver; 1046 public final PackageManagerService service; 1047 public final WatchedArrayMap<String, Integer> frozenPackages; 1048 public final SharedLibrariesRead sharedLibraries; 1049 Snapshot(int type)1050 Snapshot(int type) { 1051 if (type == Snapshot.SNAPPED) { 1052 settings = mSettings.snapshot(); 1053 isolatedOwners = mIsolatedOwnersSnapshot.snapshot(); 1054 packages = mPackagesSnapshot.snapshot(); 1055 instrumentation = mInstrumentationSnapshot.snapshot(); 1056 resolveComponentName = mResolveComponentName == null 1057 ? null : mResolveComponentName.clone(); 1058 resolveActivity = new ActivityInfo(mResolveActivity); 1059 instantAppInstallerActivity = 1060 (mInstantAppInstallerActivity == null) 1061 ? null 1062 : new ActivityInfo(mInstantAppInstallerActivity); 1063 instantAppInstallerInfo = new ResolveInfo(mInstantAppInstallerInfo); 1064 webInstantAppsDisabled = mWebInstantAppsDisabled.snapshot(); 1065 instantAppRegistry = mInstantAppRegistry.snapshot(); 1066 androidApplication = 1067 (mAndroidApplication == null) 1068 ? null 1069 : new ApplicationInfo(mAndroidApplication); 1070 appPredictionServicePackage = mAppPredictionServicePackage; 1071 appsFilter = mAppsFilter.snapshot(); 1072 componentResolver = mComponentResolver.snapshot(); 1073 frozenPackages = mFrozenPackagesSnapshot.snapshot(); 1074 sharedLibraries = mSharedLibraries.snapshot(); 1075 } else if (type == Snapshot.LIVE) { 1076 settings = mSettings; 1077 isolatedOwners = mIsolatedOwners; 1078 packages = mPackages; 1079 instrumentation = mInstrumentation; 1080 resolveComponentName = mResolveComponentName; 1081 resolveActivity = mResolveActivity; 1082 instantAppInstallerActivity = mInstantAppInstallerActivity; 1083 instantAppInstallerInfo = mInstantAppInstallerInfo; 1084 webInstantAppsDisabled = mWebInstantAppsDisabled; 1085 instantAppRegistry = mInstantAppRegistry; 1086 androidApplication = mAndroidApplication; 1087 appPredictionServicePackage = mAppPredictionServicePackage; 1088 appsFilter = mAppsFilter; 1089 componentResolver = mComponentResolver; 1090 frozenPackages = mFrozenPackages; 1091 sharedLibraries = mSharedLibraries; 1092 } else { 1093 throw new IllegalArgumentException(); 1094 } 1095 service = PackageManagerService.this; 1096 } 1097 } 1098 1099 // Compute read-only functions, based on live data. This attribute may be modified multiple 1100 // times during the PackageManagerService constructor but it should not be modified thereafter. 1101 private ComputerLocked mLiveComputer; 1102 1103 private static final AtomicReference<Computer> sSnapshot = new AtomicReference<>(); 1104 1105 // If this differs from Computer#getVersion, the snapshot is invalid (stale). 1106 private static final AtomicInteger sSnapshotPendingVersion = new AtomicInteger(1); 1107 1108 /** 1109 * This lock is used to make reads from {@link #sSnapshotPendingVersion} and 1110 * {@link #sSnapshot} atomic inside {@code snapshotComputer()} when the versions mismatch. 1111 * This lock is not meant to be used outside that method. This lock must be taken before 1112 * {@link #mLock} is taken. 1113 */ 1114 private final Object mSnapshotLock = new Object(); 1115 1116 /** 1117 * The snapshot statistics. These are collected to track performance and to identify 1118 * situations in which the snapshots are misbehaving. 1119 */ 1120 @Nullable 1121 private final SnapshotStatistics mSnapshotStatistics; 1122 1123 /** 1124 * Return the cached computer. The method will rebuild the cached computer if necessary. 1125 * The live computer will be returned if snapshots are disabled. 1126 */ 1127 @VisibleForTesting(visibility = Visibility.PACKAGE) 1128 @NonNull snapshotComputer()1129 public Computer snapshotComputer() { 1130 return snapshotComputer(true /*allowLiveComputer*/); 1131 } 1132 1133 /** 1134 * This method should only ever be called from {@link PackageManagerLocal#snapshot()}. 1135 * 1136 * @param allowLiveComputer Whether to allow a live computer instance based on caller {@link 1137 * #mLock} hold state. In certain cases, like for {@link 1138 * PackageManagerLocal} API, it must be enforced that the caller gets 1139 * a snapshot at time, and never the live variant. 1140 * @deprecated Use {@link #snapshotComputer()} 1141 */ 1142 @Deprecated 1143 @NonNull snapshotComputer(boolean allowLiveComputer)1144 public Computer snapshotComputer(boolean allowLiveComputer) { 1145 var isHoldingPackageLock = Thread.holdsLock(mLock); 1146 if (allowLiveComputer) { 1147 if (isHoldingPackageLock) { 1148 // If the current thread holds mLock then it may have modified state but not 1149 // yet invalidated the snapshot. Always give the thread the live computer. 1150 return mLiveComputer; 1151 } 1152 } 1153 1154 var oldSnapshot = sSnapshot.get(); 1155 var pendingVersion = sSnapshotPendingVersion.get(); 1156 1157 if (oldSnapshot != null && oldSnapshot.getVersion() == pendingVersion) { 1158 return oldSnapshot.use(); 1159 } 1160 1161 if (isHoldingPackageLock) { 1162 // If the current thread holds mLock then it already has exclusive write access to the 1163 // two snapshot fields, and we can just go ahead and rebuild the snapshot. 1164 @SuppressWarnings("GuardedBy") 1165 var newSnapshot = rebuildSnapshot(oldSnapshot, pendingVersion); 1166 sSnapshot.set(newSnapshot); 1167 return newSnapshot.use(); 1168 } 1169 1170 synchronized (mSnapshotLock) { 1171 // Re-capture pending version in case a new invalidation occurred since last check 1172 var rebuildSnapshot = sSnapshot.get(); 1173 var rebuildVersion = sSnapshotPendingVersion.get(); 1174 1175 // Check the versions again while the lock is held, in case the rebuild time caused 1176 // multiple threads to wait on the snapshot lock. When the first thread finishes 1177 // a rebuild, the snapshot is now valid and the other waiting threads can use it 1178 // without kicking off their own rebuilds. 1179 if (rebuildSnapshot != null && rebuildSnapshot.getVersion() == rebuildVersion) { 1180 return rebuildSnapshot.use(); 1181 } 1182 1183 synchronized (mLock) { 1184 // Fetch version one last time to ensure that the rebuilt snapshot matches 1185 // the latest invalidation, which could have come in between entering the 1186 // SnapshotLock and mLock sync blocks. 1187 rebuildSnapshot = sSnapshot.get(); 1188 rebuildVersion = sSnapshotPendingVersion.get(); 1189 if (rebuildSnapshot != null && rebuildSnapshot.getVersion() == rebuildVersion) { 1190 return rebuildSnapshot.use(); 1191 } 1192 1193 // Build the snapshot for this version 1194 var newSnapshot = rebuildSnapshot(rebuildSnapshot, rebuildVersion); 1195 sSnapshot.set(newSnapshot); 1196 return newSnapshot.use(); 1197 } 1198 } 1199 } 1200 1201 @GuardedBy("mLock") rebuildSnapshot(@ullable Computer oldSnapshot, int newVersion)1202 private Computer rebuildSnapshot(@Nullable Computer oldSnapshot, int newVersion) { 1203 var now = SystemClock.currentTimeMicro(); 1204 var hits = oldSnapshot == null ? -1 : oldSnapshot.getUsed(); 1205 var args = new Snapshot(Snapshot.SNAPPED); 1206 var newSnapshot = new ComputerEngine(args, newVersion); 1207 var done = SystemClock.currentTimeMicro(); 1208 1209 if (mSnapshotStatistics != null) { 1210 mSnapshotStatistics.rebuild(now, done, hits, newSnapshot.getPackageStates().size()); 1211 } 1212 return newSnapshot; 1213 } 1214 1215 /** 1216 * Create a live computer 1217 */ createLiveComputer()1218 private ComputerLocked createLiveComputer() { 1219 return new ComputerLocked(new Snapshot(Snapshot.LIVE)); 1220 } 1221 1222 /** 1223 * This method is called when the state of PackageManagerService changes so as to 1224 * invalidate the current snapshot. 1225 * @param what The {@link Watchable} that reported the change 1226 * @hide 1227 */ onChange(@ullable Watchable what)1228 public static void onChange(@Nullable Watchable what) { 1229 if (TRACE_SNAPSHOTS) { 1230 Log.i(TAG, "snapshot: onChange(" + what + ")"); 1231 } 1232 sSnapshotPendingVersion.incrementAndGet(); 1233 } 1234 1235 /** 1236 * Report a locally-detected change to observers. The <what> parameter is left null, 1237 * but it signifies that the change was detected by PackageManagerService itself. 1238 */ onChanged()1239 static void onChanged() { 1240 onChange(null); 1241 } 1242 notifyInstallObserver(String packageName, boolean killApp)1243 void notifyInstallObserver(String packageName, boolean killApp) { 1244 final InstallRequest installRequest = 1245 killApp ? mPendingKillInstallObservers.remove(packageName) 1246 : mNoKillInstallObservers.remove(packageName); 1247 1248 if (installRequest != null) { 1249 notifyInstallObserver(installRequest); 1250 } 1251 } 1252 notifyInstallObserver(InstallRequest request)1253 void notifyInstallObserver(InstallRequest request) { 1254 if (request.getObserver() != null) { 1255 try { 1256 Bundle extras = extrasForInstallResult(request); 1257 request.getObserver().onPackageInstalled(request.getName(), 1258 request.getReturnCode(), request.getReturnMsg(), extras); 1259 } catch (RemoteException e) { 1260 Slog.i(TAG, "Observer no longer exists."); 1261 } 1262 } 1263 } 1264 scheduleDeferredNoKillInstallObserver(InstallRequest request)1265 void scheduleDeferredNoKillInstallObserver(InstallRequest request) { 1266 String packageName = request.getPkg().getPackageName(); 1267 mNoKillInstallObservers.put(packageName, request); 1268 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_INSTALL_OBSERVER, packageName); 1269 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS); 1270 } 1271 scheduleDeferredNoKillPostDelete(InstallArgs args)1272 void scheduleDeferredNoKillPostDelete(InstallArgs args) { 1273 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_POST_DELETE, args); 1274 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_POST_DELETE_DELAY_MS); 1275 } 1276 schedulePruneUnusedStaticSharedLibraries(boolean delay)1277 void schedulePruneUnusedStaticSharedLibraries(boolean delay) { 1278 mHandler.removeMessages(PRUNE_UNUSED_STATIC_SHARED_LIBRARIES); 1279 mHandler.sendEmptyMessageDelayed(PRUNE_UNUSED_STATIC_SHARED_LIBRARIES, 1280 delay ? getPruneUnusedSharedLibrariesDelay() : 0); 1281 } 1282 scheduleDeferredPendingKillInstallObserver(InstallRequest request)1283 void scheduleDeferredPendingKillInstallObserver(InstallRequest request) { 1284 final String packageName = request.getPkg().getPackageName(); 1285 mPendingKillInstallObservers.put(packageName, request); 1286 final Message message = mHandler.obtainMessage(DEFERRED_PENDING_KILL_INSTALL_OBSERVER, 1287 packageName); 1288 mHandler.sendMessageDelayed(message, DEFERRED_PENDING_KILL_INSTALL_OBSERVER_DELAY_MS); 1289 } 1290 getPruneUnusedSharedLibrariesDelay()1291 private static long getPruneUnusedSharedLibrariesDelay() { 1292 return SystemProperties.getLong("debug.pm.prune_unused_shared_libraries_delay", 1293 PRUNE_UNUSED_SHARED_LIBRARIES_DELAY); 1294 } 1295 1296 /** 1297 * Requests checksums for the APK file. 1298 * See {@link PackageInstaller.Session#requestChecksums} for details. 1299 */ requestFileChecksums(@onNull File file, @NonNull String installerPackageName, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener)1300 public void requestFileChecksums(@NonNull File file, 1301 @NonNull String installerPackageName, @Checksum.TypeMask int optional, 1302 @Checksum.TypeMask int required, @Nullable List trustedInstallers, 1303 @NonNull IOnChecksumsReadyListener onChecksumsReadyListener) 1304 throws FileNotFoundException { 1305 if (!file.exists()) { 1306 throw new FileNotFoundException(file.getAbsolutePath()); 1307 } 1308 1309 final Executor executor = mInjector.getBackgroundExecutor(); 1310 final Handler handler = mInjector.getBackgroundHandler(); 1311 final Certificate[] trustedCerts = (trustedInstallers != null) ? decodeCertificates( 1312 trustedInstallers) : null; 1313 1314 final List<Pair<String, File>> filesToChecksum = new ArrayList<>(1); 1315 filesToChecksum.add(Pair.create(null, file)); 1316 1317 executor.execute(() -> { 1318 ApkChecksums.Injector injector = new ApkChecksums.Injector( 1319 () -> mContext, 1320 () -> handler, 1321 mInjector::getIncrementalManager, 1322 () -> mInjector.getLocalService(PackageManagerInternal.class)); 1323 ApkChecksums.getChecksums(filesToChecksum, optional, required, installerPackageName, 1324 trustedCerts, onChecksumsReadyListener, injector); 1325 }); 1326 } 1327 requestChecksumsInternal(@onNull Computer snapshot, @NonNull String packageName, boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, @Nullable List trustedInstallers, @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId, @NonNull Executor executor, @NonNull Handler handler)1328 void requestChecksumsInternal(@NonNull Computer snapshot, @NonNull String packageName, 1329 boolean includeSplits, @Checksum.TypeMask int optional, @Checksum.TypeMask int required, 1330 @Nullable List trustedInstallers, 1331 @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId, 1332 @NonNull Executor executor, @NonNull Handler handler) { 1333 Objects.requireNonNull(packageName); 1334 Objects.requireNonNull(onChecksumsReadyListener); 1335 Objects.requireNonNull(executor); 1336 Objects.requireNonNull(handler); 1337 1338 final ApplicationInfo applicationInfo = snapshot.getApplicationInfoInternal(packageName, 0, 1339 Binder.getCallingUid(), userId); 1340 if (applicationInfo == null) { 1341 throw new ParcelableException(new PackageManager.NameNotFoundException(packageName)); 1342 } 1343 1344 final InstallSourceInfo installSourceInfo = snapshot.getInstallSourceInfo(packageName, 1345 userId); 1346 final String initiatingPackageName = installSourceInfo.getInitiatingPackageName(); 1347 final String installerPackageName; 1348 if (installSourceInfo != null) { 1349 if (!isInstalledByAdb(initiatingPackageName)) { 1350 installerPackageName = initiatingPackageName; 1351 } else { 1352 installerPackageName = installSourceInfo.getInstallingPackageName(); 1353 } 1354 } else { 1355 installerPackageName = null; 1356 } 1357 1358 List<Pair<String, File>> filesToChecksum = new ArrayList<>(); 1359 1360 // Adding base split. 1361 filesToChecksum.add(Pair.create(null, new File(applicationInfo.sourceDir))); 1362 1363 // Adding other splits. 1364 if (includeSplits && applicationInfo.splitNames != null) { 1365 for (int i = 0, size = applicationInfo.splitNames.length; i < size; ++i) { 1366 filesToChecksum.add(Pair.create(applicationInfo.splitNames[i], 1367 new File(applicationInfo.splitSourceDirs[i]))); 1368 } 1369 } 1370 1371 final Certificate[] trustedCerts = (trustedInstallers != null) ? decodeCertificates( 1372 trustedInstallers) : null; 1373 1374 executor.execute(() -> { 1375 ApkChecksums.Injector injector = new ApkChecksums.Injector( 1376 () -> mContext, 1377 () -> handler, 1378 mInjector::getIncrementalManager, 1379 () -> mInjector.getLocalService(PackageManagerInternal.class)); 1380 ApkChecksums.getChecksums(filesToChecksum, optional, required, installerPackageName, 1381 trustedCerts, onChecksumsReadyListener, injector); 1382 }); 1383 } 1384 decodeCertificates(@onNull List certs)1385 private static @NonNull Certificate[] decodeCertificates(@NonNull List certs) { 1386 try { 1387 final CertificateFactory cf = CertificateFactory.getInstance("X.509"); 1388 final Certificate[] result = new Certificate[certs.size()]; 1389 for (int i = 0, size = certs.size(); i < size; ++i) { 1390 final InputStream is = new ByteArrayInputStream((byte[]) certs.get(i)); 1391 final X509Certificate cert = (X509Certificate) cf.generateCertificate(is); 1392 result[i] = cert; 1393 } 1394 return result; 1395 } catch (CertificateException e) { 1396 throw ExceptionUtils.propagate(e); 1397 } 1398 } 1399 extrasForInstallResult(InstallRequest request)1400 private static Bundle extrasForInstallResult(InstallRequest request) { 1401 Bundle extras = null; 1402 switch (request.getReturnCode()) { 1403 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 1404 extras = new Bundle(); 1405 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 1406 request.getOrigPermission()); 1407 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 1408 request.getOrigPackage()); 1409 break; 1410 } 1411 case PackageManager.INSTALL_SUCCEEDED: { 1412 extras = new Bundle(); 1413 extras.putBoolean(Intent.EXTRA_REPLACING, 1414 request.getRemovedInfo() != null 1415 && request.getRemovedInfo().mRemovedPackage != null); 1416 break; 1417 } 1418 } 1419 return extras; 1420 } 1421 scheduleWriteSettings()1422 void scheduleWriteSettings() { 1423 // We normally invalidate when we write settings, but in cases where we delay and 1424 // coalesce settings writes, this strategy would have us invalidate the cache too late. 1425 // Invalidating on schedule addresses this problem. 1426 invalidatePackageInfoCache(); 1427 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 1428 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 1429 } 1430 } 1431 scheduleWritePackageListLocked(int userId)1432 private void scheduleWritePackageListLocked(int userId) { 1433 invalidatePackageInfoCache(); 1434 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 1435 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 1436 msg.arg1 = userId; 1437 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 1438 } 1439 } 1440 scheduleWritePackageRestrictions(UserHandle user)1441 void scheduleWritePackageRestrictions(UserHandle user) { 1442 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 1443 scheduleWritePackageRestrictions(userId); 1444 } 1445 scheduleWritePackageRestrictions(int userId)1446 void scheduleWritePackageRestrictions(int userId) { 1447 invalidatePackageInfoCache(); 1448 if (userId == UserHandle.USER_ALL) { 1449 synchronized (mDirtyUsers) { 1450 for (int aUserId : mUserManager.getUserIds()) { 1451 mDirtyUsers.add(aUserId); 1452 } 1453 } 1454 } else { 1455 if (!mUserManager.exists(userId)) { 1456 return; 1457 } 1458 synchronized (mDirtyUsers) { 1459 mDirtyUsers.add(userId); 1460 } 1461 } 1462 if (!mBackgroundHandler.hasMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS)) { 1463 mBackgroundHandler.sendMessageDelayed( 1464 mBackgroundHandler.obtainMessage(WRITE_DIRTY_PACKAGE_RESTRICTIONS, this), 1465 WRITE_SETTINGS_DELAY); 1466 } 1467 } 1468 writePendingRestrictions()1469 void writePendingRestrictions() { 1470 final Integer[] dirtyUsers; 1471 synchronized (mLock) { 1472 mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS); 1473 synchronized (mDirtyUsers) { 1474 if (mDirtyUsers.isEmpty()) { 1475 return; 1476 } 1477 dirtyUsers = mDirtyUsers.toArray(Integer[]::new); 1478 mDirtyUsers.clear(); 1479 } 1480 } 1481 mSettings.writePackageRestrictions(dirtyUsers); 1482 } 1483 writeSettings(boolean sync)1484 void writeSettings(boolean sync) { 1485 synchronized (mLock) { 1486 mHandler.removeMessages(WRITE_SETTINGS); 1487 mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS); 1488 writeSettingsLPrTEMP(sync); 1489 synchronized (mDirtyUsers) { 1490 mDirtyUsers.clear(); 1491 } 1492 } 1493 } 1494 writePackageList(int userId)1495 void writePackageList(int userId) { 1496 synchronized (mLock) { 1497 mHandler.removeMessages(WRITE_PACKAGE_LIST); 1498 mSettings.writePackageListLPr(userId); 1499 } 1500 } 1501 1502 private static final Handler.Callback BACKGROUND_HANDLER_CALLBACK = new Handler.Callback() { 1503 @Override 1504 public boolean handleMessage(@NonNull Message msg) { 1505 switch (msg.what) { 1506 case WRITE_DIRTY_PACKAGE_RESTRICTIONS: { 1507 PackageManagerService pm = (PackageManagerService) msg.obj; 1508 pm.writePendingRestrictions(); 1509 return true; 1510 } 1511 case WRITE_USER_PACKAGE_RESTRICTIONS: { 1512 final Runnable r = (Runnable) msg.obj; 1513 r.run(); 1514 return true; 1515 } 1516 } 1517 return false; 1518 } 1519 }; 1520 1521 /** Starts PackageManagerService. */ main(Context context, Installer installer, @NonNull DomainVerificationService domainVerificationService, boolean factoryTest)1522 public static PackageManagerService main(Context context, 1523 Installer installer, @NonNull DomainVerificationService domainVerificationService, 1524 boolean factoryTest) { 1525 // Self-check for initial settings. 1526 PackageManagerServiceCompilerMapping.checkProperties(); 1527 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 1528 Trace.TRACE_TAG_PACKAGE_MANAGER); 1529 t.traceBegin("create package manager"); 1530 final PackageManagerTracedLock lock = new PackageManagerTracedLock(); 1531 final Object installLock = new Object(); 1532 1533 HandlerThread backgroundThread = new ServiceThread("PackageManagerBg", 1534 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 1535 backgroundThread.start(); 1536 Handler backgroundHandler = new Handler(backgroundThread.getLooper(), 1537 BACKGROUND_HANDLER_CALLBACK); 1538 1539 PackageManagerServiceInjector injector = new PackageManagerServiceInjector( 1540 context, lock, installer, installLock, new PackageAbiHelperImpl(), 1541 backgroundHandler, 1542 SYSTEM_PARTITIONS, 1543 (i, pm) -> new ComponentResolver(i.getUserManagerService(), pm.mUserNeedsBadging), 1544 (i, pm) -> PermissionManagerService.create(context, 1545 i.getSystemConfig().getAvailableFeatures()), 1546 (i, pm) -> new UserManagerService(context, pm, 1547 new UserDataPreparer(installer, installLock, context), lock), 1548 (i, pm) -> new Settings(Environment.getDataDirectory(), 1549 RuntimePermissionsPersistence.createInstance(), 1550 i.getPermissionManagerServiceInternal(), 1551 domainVerificationService, backgroundHandler, 1552 lock), 1553 (i, pm) -> AppsFilterImpl.create(i, 1554 i.getLocalService(PackageManagerInternal.class)), 1555 (i, pm) -> (PlatformCompat) ServiceManager.getService("platform_compat"), 1556 (i, pm) -> SystemConfig.getInstance(), 1557 (i, pm) -> new PackageDexOptimizer(i.getInstaller(), i.getInstallLock(), 1558 i.getContext(), "*dexopt*"), 1559 (i, pm) -> new DexManager(i.getContext(), i.getPackageDexOptimizer(), 1560 i.getInstaller(), i.getInstallLock(), i.getDynamicCodeLogger()), 1561 (i, pm) -> new DynamicCodeLogger(i.getInstaller()), 1562 (i, pm) -> new ArtManagerService(i.getContext(), i.getInstaller(), 1563 i.getInstallLock()), 1564 (i, pm) -> ApexManager.getInstance(), 1565 (i, pm) -> new ViewCompiler(i.getInstallLock(), i.getInstaller()), 1566 (i, pm) -> (IncrementalManager) 1567 i.getContext().getSystemService(Context.INCREMENTAL_SERVICE), 1568 (i, pm) -> new DefaultAppProvider(() -> context.getSystemService(RoleManager.class), 1569 () -> LocalServices.getService(UserManagerInternal.class)), 1570 (i, pm) -> new DisplayMetrics(), 1571 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(), 1572 pm.mCacheDir, 1573 pm.mPackageParserCallback) /* scanningCachingPackageParserProducer */, 1574 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(), null, 1575 pm.mPackageParserCallback) /* scanningPackageParserProducer */, 1576 (i, pm) -> new PackageParser2(pm.mSeparateProcesses, i.getDisplayMetrics(), null, 1577 pm.mPackageParserCallback) /* preparingPackageParserProducer */, 1578 // Prepare a supplier of package parser for the staging manager to parse apex file 1579 // during the staging installation. 1580 (i, pm) -> new PackageInstallerService( 1581 i.getContext(), pm, i::getScanningPackageParser), 1582 (i, pm, cn) -> new InstantAppResolverConnection( 1583 i.getContext(), cn, Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE), 1584 (i, pm) -> new ModuleInfoProvider(i.getContext()), 1585 (i, pm) -> LegacyPermissionManagerService.create(i.getContext()), 1586 (i, pm) -> domainVerificationService, 1587 (i, pm) -> { 1588 HandlerThread thread = new ServiceThread(TAG, 1589 Process.THREAD_PRIORITY_DEFAULT, true /*allowIo*/); 1590 thread.start(); 1591 return new PackageHandler(thread.getLooper(), pm); 1592 }, 1593 new DefaultSystemWrapper(), 1594 LocalServices::getService, 1595 context::getSystemService, 1596 (i, pm) -> { 1597 if (useArtService()) { 1598 return null; 1599 } 1600 try { 1601 return new BackgroundDexOptService(i.getContext(), i.getDexManager(), pm); 1602 } catch (LegacyDexoptDisabledException e) { 1603 throw new RuntimeException(e); 1604 } 1605 }, 1606 (i, pm) -> IBackupManager.Stub.asInterface(ServiceManager.getService( 1607 Context.BACKUP_SERVICE)), 1608 (i, pm) -> new SharedLibrariesImpl(pm, i), 1609 (i, pm) -> new CrossProfileIntentFilterHelper(i.getSettings(), 1610 i.getUserManagerService(), i.getLock(), i.getUserManagerInternal(), 1611 context), 1612 (i, pm) -> new UpdateOwnershipHelper()); 1613 1614 if (Build.VERSION.SDK_INT <= 0) { 1615 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 1616 } 1617 1618 PackageManagerService m = new PackageManagerService(injector, factoryTest, 1619 PackagePartitions.FINGERPRINT, Build.IS_ENG, Build.IS_USERDEBUG, 1620 Build.VERSION.SDK_INT, Build.VERSION.INCREMENTAL); 1621 t.traceEnd(); // "create package manager" 1622 1623 final CompatChange.ChangeListener selinuxChangeListener = packageName -> { 1624 synchronized (m.mInstallLock) { 1625 final Computer snapshot = m.snapshotComputer(); 1626 final PackageStateInternal packageState = 1627 snapshot.getPackageStateInternal(packageName); 1628 if (packageState == null) { 1629 Slog.e(TAG, "Failed to find package setting " + packageName); 1630 return; 1631 } 1632 AndroidPackage pkg = packageState.getPkg(); 1633 SharedUserApi sharedUser = snapshot.getSharedUser( 1634 packageState.getSharedUserAppId()); 1635 String oldSeInfo = packageState.getSeInfo(); 1636 1637 if (pkg == null) { 1638 Slog.e(TAG, "Failed to find package " + packageName); 1639 return; 1640 } 1641 final String newSeInfo = SELinuxMMAC.getSeInfo(packageState, pkg, sharedUser, 1642 m.mInjector.getCompatibility()); 1643 1644 if (!newSeInfo.equals(oldSeInfo)) { 1645 Slog.i(TAG, "Updating seInfo for package " + packageName + " from: " 1646 + oldSeInfo + " to: " + newSeInfo); 1647 m.commitPackageStateMutation(null, packageName, 1648 state -> state.setOverrideSeInfo(newSeInfo)); 1649 m.mAppDataHelper.prepareAppDataAfterInstallLIF(pkg); 1650 } 1651 } 1652 }; 1653 1654 injector.getCompatibility().registerListener(SELinuxMMAC.SELINUX_LATEST_CHANGES, 1655 selinuxChangeListener); 1656 injector.getCompatibility().registerListener(SELinuxMMAC.SELINUX_R_CHANGES, 1657 selinuxChangeListener); 1658 1659 m.installAllowlistedSystemPackages(); 1660 IPackageManagerImpl iPackageManager = m.new IPackageManagerImpl(); 1661 ServiceManager.addService("package", iPackageManager); 1662 final PackageManagerNative pmn = new PackageManagerNative(m); 1663 ServiceManager.addService("package_native", pmn); 1664 return m; 1665 } 1666 1667 /** Install/uninstall system packages for all users based on their user-type, as applicable. */ installAllowlistedSystemPackages()1668 private void installAllowlistedSystemPackages() { 1669 if (mUserManager.installWhitelistedSystemPackages(isFirstBoot(), isDeviceUpgrading(), 1670 mExistingPackages)) { 1671 scheduleWritePackageRestrictions(UserHandle.USER_ALL); 1672 scheduleWriteSettings(); 1673 } 1674 } 1675 1676 // Link watchables to the class 1677 @SuppressWarnings("GuardedBy") registerObservers(boolean verify)1678 private void registerObservers(boolean verify) { 1679 // Null check to handle nullable test parameters 1680 if (mPackages != null) { 1681 mPackages.registerObserver(mWatcher); 1682 } 1683 if (mSharedLibraries != null) { 1684 mSharedLibraries.registerObserver(mWatcher); 1685 } 1686 if (mInstrumentation != null) { 1687 mInstrumentation.registerObserver(mWatcher); 1688 } 1689 if (mWebInstantAppsDisabled != null) { 1690 mWebInstantAppsDisabled.registerObserver(mWatcher); 1691 } 1692 if (mAppsFilter != null) { 1693 mAppsFilter.registerObserver(mWatcher); 1694 } 1695 if (mInstantAppRegistry != null) { 1696 mInstantAppRegistry.registerObserver(mWatcher); 1697 } 1698 if (mSettings != null) { 1699 mSettings.registerObserver(mWatcher); 1700 } 1701 if (mIsolatedOwners != null) { 1702 mIsolatedOwners.registerObserver(mWatcher); 1703 } 1704 if (mComponentResolver != null) { 1705 mComponentResolver.registerObserver(mWatcher); 1706 } 1707 if (mFrozenPackages != null) { 1708 mFrozenPackages.registerObserver(mWatcher); 1709 } 1710 if (verify) { 1711 // If neither "build" attribute is true then this may be a mockito test, 1712 // and verification can fail as a false positive. 1713 Watchable.verifyWatchedAttributes(this, mWatcher, !(mIsEngBuild || mIsUserDebugBuild)); 1714 } 1715 } 1716 1717 /** 1718 * An extremely minimal constructor designed to start up a PackageManagerService instance for 1719 * testing. 1720 * 1721 * It is assumed that all methods under test will mock the internal fields and thus 1722 * none of the initialization is needed. 1723 */ 1724 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE) PackageManagerService(@onNull PackageManagerServiceInjector injector, @NonNull PackageManagerServiceTestParams testParams)1725 public PackageManagerService(@NonNull PackageManagerServiceInjector injector, 1726 @NonNull PackageManagerServiceTestParams testParams) { 1727 mInjector = injector; 1728 mInjector.bootstrap(this); 1729 mAppsFilter = injector.getAppsFilter(); 1730 mComponentResolver = injector.getComponentResolver(); 1731 mContext = injector.getContext(); 1732 mInstaller = injector.getInstaller(); 1733 mInstallLock = injector.getInstallLock(); 1734 mLock = injector.getLock(); 1735 mPackageStateWriteLock = mLock; 1736 mPermissionManager = injector.getPermissionManagerServiceInternal(); 1737 mSettings = injector.getSettings(); 1738 mUserManager = injector.getUserManagerService(); 1739 mUserNeedsBadging = new UserNeedsBadgingCache(mUserManager); 1740 mDomainVerificationManager = injector.getDomainVerificationManagerInternal(); 1741 mHandler = injector.getHandler(); 1742 mBackgroundHandler = injector.getBackgroundHandler(); 1743 mSharedLibraries = injector.getSharedLibrariesImpl(); 1744 1745 mApexManager = testParams.apexManager; 1746 mArtManagerService = testParams.artManagerService; 1747 mAvailableFeatures = testParams.availableFeatures; 1748 mBackgroundDexOptService = testParams.backgroundDexOptService; 1749 mDefParseFlags = testParams.defParseFlags; 1750 mDefaultAppProvider = testParams.defaultAppProvider; 1751 mLegacyPermissionManager = testParams.legacyPermissionManagerInternal; 1752 mDexManager = testParams.dexManager; 1753 mDynamicCodeLogger = testParams.dynamicCodeLogger; 1754 mFactoryTest = testParams.factoryTest; 1755 mIncrementalManager = testParams.incrementalManager; 1756 mInstallerService = testParams.installerService; 1757 mInstantAppRegistry = testParams.instantAppRegistry; 1758 mChangedPackagesTracker = testParams.changedPackagesTracker; 1759 mInstantAppResolverConnection = testParams.instantAppResolverConnection; 1760 mInstantAppResolverSettingsComponent = testParams.instantAppResolverSettingsComponent; 1761 mIsPreNMR1Upgrade = testParams.isPreNmr1Upgrade; 1762 mIsPreQUpgrade = testParams.isPreQupgrade; 1763 mIsUpgrade = testParams.isUpgrade; 1764 mMetrics = testParams.Metrics; 1765 mModuleInfoProvider = testParams.moduleInfoProvider; 1766 mMoveCallbacks = testParams.moveCallbacks; 1767 mOverlayConfig = testParams.overlayConfig; 1768 mPackageDexOptimizer = testParams.packageDexOptimizer; 1769 mPackageParserCallback = testParams.packageParserCallback; 1770 mPendingBroadcasts = testParams.pendingPackageBroadcasts; 1771 mTestUtilityService = testParams.testUtilityService; 1772 mProcessLoggingHandler = testParams.processLoggingHandler; 1773 mProtectedPackages = testParams.protectedPackages; 1774 mSeparateProcesses = testParams.separateProcesses; 1775 mViewCompiler = testParams.viewCompiler; 1776 mRequiredVerifierPackages = testParams.requiredVerifierPackages; 1777 mRequiredInstallerPackage = testParams.requiredInstallerPackage; 1778 mRequiredUninstallerPackage = testParams.requiredUninstallerPackage; 1779 mRequiredPermissionControllerPackage = testParams.requiredPermissionControllerPackage; 1780 mSetupWizardPackage = testParams.setupWizardPackage; 1781 mStorageManagerPackage = testParams.storageManagerPackage; 1782 mDefaultTextClassifierPackage = testParams.defaultTextClassifierPackage; 1783 mSystemTextClassifierPackageName = testParams.systemTextClassifierPackage; 1784 mRetailDemoPackage = testParams.retailDemoPackage; 1785 mRecentsPackage = testParams.recentsPackage; 1786 mAmbientContextDetectionPackage = testParams.ambientContextDetectionPackage; 1787 mWearableSensingPackage = testParams.wearableSensingPackage; 1788 mConfiguratorPackage = testParams.configuratorPackage; 1789 mAppPredictionServicePackage = testParams.appPredictionServicePackage; 1790 mIncidentReportApproverPackage = testParams.incidentReportApproverPackage; 1791 mServicesExtensionPackageName = testParams.servicesExtensionPackageName; 1792 mSharedSystemSharedLibraryPackageName = testParams.sharedSystemSharedLibraryPackageName; 1793 mOverlayConfigSignaturePackage = testParams.overlayConfigSignaturePackage; 1794 mResolveComponentName = testParams.resolveComponentName; 1795 mRequiredSdkSandboxPackage = testParams.requiredSdkSandboxPackage; 1796 mInitialNonStoppedSystemPackages = testParams.initialNonStoppedSystemPackages; 1797 mShouldStopSystemPackagesByDefault = testParams.shouldStopSystemPackagesByDefault; 1798 1799 mLiveComputer = createLiveComputer(); 1800 mSnapshotStatistics = null; 1801 1802 mPackages.putAll(testParams.packages); 1803 mEnableFreeCacheV2 = testParams.enableFreeCacheV2; 1804 mSdkVersion = testParams.sdkVersion; 1805 mAppInstallDir = testParams.appInstallDir; 1806 mIsEngBuild = testParams.isEngBuild; 1807 mIsUserDebugBuild = testParams.isUserDebugBuild; 1808 mIncrementalVersion = testParams.incrementalVersion; 1809 mDomainVerificationConnection = new DomainVerificationConnection(this); 1810 1811 mBroadcastHelper = testParams.broadcastHelper; 1812 mAppDataHelper = testParams.appDataHelper; 1813 mInstallPackageHelper = testParams.installPackageHelper; 1814 mRemovePackageHelper = testParams.removePackageHelper; 1815 mInitAppsHelper = testParams.initAndSystemPackageHelper; 1816 mDeletePackageHelper = testParams.deletePackageHelper; 1817 mPreferredActivityHelper = testParams.preferredActivityHelper; 1818 mResolveIntentHelper = testParams.resolveIntentHelper; 1819 mDexOptHelper = testParams.dexOptHelper; 1820 mSuspendPackageHelper = testParams.suspendPackageHelper; 1821 mDistractingPackageHelper = testParams.distractingPackageHelper; 1822 1823 mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper); 1824 1825 mStorageEventHelper = testParams.storageEventHelper; 1826 1827 registerObservers(false); 1828 invalidatePackageInfoCache(); 1829 } 1830 PackageManagerService(PackageManagerServiceInjector injector, boolean factoryTest, final String partitionsFingerprint, final boolean isEngBuild, final boolean isUserDebugBuild, final int sdkVersion, final String incrementalVersion)1831 public PackageManagerService(PackageManagerServiceInjector injector, boolean factoryTest, 1832 final String partitionsFingerprint, final boolean isEngBuild, 1833 final boolean isUserDebugBuild, final int sdkVersion, final String incrementalVersion) { 1834 mIsEngBuild = isEngBuild; 1835 mIsUserDebugBuild = isUserDebugBuild; 1836 mSdkVersion = sdkVersion; 1837 mIncrementalVersion = incrementalVersion; 1838 mInjector = injector; 1839 mInjector.getSystemWrapper().disablePackageCaches(); 1840 1841 final TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG + "Timing", 1842 Trace.TRACE_TAG_PACKAGE_MANAGER); 1843 mPendingBroadcasts = new PendingPackageBroadcasts(); 1844 1845 mInjector.bootstrap(this); 1846 mLock = injector.getLock(); 1847 mPackageStateWriteLock = mLock; 1848 mInstallLock = injector.getInstallLock(); 1849 LockGuard.installLock(mLock, LockGuard.INDEX_PACKAGES); 1850 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 1851 SystemClock.uptimeMillis()); 1852 1853 mContext = injector.getContext(); 1854 mFactoryTest = factoryTest; 1855 mMetrics = injector.getDisplayMetrics(); 1856 mInstaller = injector.getInstaller(); 1857 mEnableFreeCacheV2 = SystemProperties.getBoolean("fw.free_cache_v2", true); 1858 1859 // Create sub-components that provide services / data. Order here is important. 1860 t.traceBegin("createSubComponents"); 1861 1862 // Expose private service for system components to use. 1863 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 1864 LocalManagerRegistry.addManager(PackageManagerLocal.class, 1865 new PackageManagerLocalImpl(this)); 1866 LocalServices.addService(TestUtilityService.class, this); 1867 mTestUtilityService = LocalServices.getService(TestUtilityService.class); 1868 mUserManager = injector.getUserManagerService(); 1869 mUserNeedsBadging = new UserNeedsBadgingCache(mUserManager); 1870 mComponentResolver = injector.getComponentResolver(); 1871 mPermissionManager = injector.getPermissionManagerServiceInternal(); 1872 mSettings = injector.getSettings(); 1873 mIncrementalManager = mInjector.getIncrementalManager(); 1874 mDefaultAppProvider = mInjector.getDefaultAppProvider(); 1875 mLegacyPermissionManager = mInjector.getLegacyPermissionManagerInternal(); 1876 PlatformCompat platformCompat = mInjector.getCompatibility(); 1877 mPackageParserCallback = new PackageParser2.Callback() { 1878 @Override 1879 public boolean isChangeEnabled(long changeId, @NonNull ApplicationInfo appInfo) { 1880 return platformCompat.isChangeEnabled(changeId, appInfo); 1881 } 1882 1883 @Override 1884 public boolean hasFeature(String feature) { 1885 return PackageManagerService.this.hasSystemFeature(feature, 0); 1886 } 1887 }; 1888 1889 // CHECKSTYLE:ON IndentationCheck 1890 t.traceEnd(); 1891 1892 t.traceBegin("addSharedUsers"); 1893 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 1894 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1895 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 1896 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1897 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 1898 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1899 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 1900 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1901 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 1902 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1903 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 1904 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1905 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 1906 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1907 mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID, 1908 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1909 mSettings.addSharedUserLPw("android.uid.uwb", UWB_UID, 1910 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 1911 t.traceEnd(); 1912 1913 String separateProcesses = SystemProperties.get("debug.separate_processes"); 1914 1915 if (separateProcesses != null && separateProcesses.length() > 0) { 1916 if ("*".equals(separateProcesses)) { 1917 mDefParseFlags = ParsingPackageUtils.PARSE_IGNORE_PROCESSES; 1918 mSeparateProcesses = null; 1919 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 1920 } else { 1921 mDefParseFlags = 0; 1922 mSeparateProcesses = separateProcesses.split(","); 1923 Slog.w(TAG, "Running with debug.separate_processes: " 1924 + separateProcesses); 1925 } 1926 } else { 1927 mDefParseFlags = 0; 1928 mSeparateProcesses = null; 1929 } 1930 1931 mPackageDexOptimizer = injector.getPackageDexOptimizer(); 1932 mDexManager = injector.getDexManager(); 1933 mDynamicCodeLogger = injector.getDynamicCodeLogger(); 1934 mBackgroundDexOptService = injector.getBackgroundDexOptService(); 1935 mArtManagerService = injector.getArtManagerService(); 1936 mMoveCallbacks = new MovePackageHelper.MoveCallbacks(FgThread.get().getLooper()); 1937 mViewCompiler = injector.getViewCompiler(); 1938 mSharedLibraries = mInjector.getSharedLibrariesImpl(); 1939 mBackgroundHandler = injector.getBackgroundHandler(); 1940 1941 mContext.getSystemService(DisplayManager.class) 1942 .getDisplay(Display.DEFAULT_DISPLAY).getMetrics(mMetrics); 1943 1944 t.traceBegin("get system config"); 1945 SystemConfig systemConfig = injector.getSystemConfig(); 1946 mAvailableFeatures = systemConfig.getAvailableFeatures(); 1947 t.traceEnd(); 1948 1949 mProtectedPackages = new ProtectedPackages(mContext); 1950 1951 mApexManager = injector.getApexManager(); 1952 mAppsFilter = mInjector.getAppsFilter(); 1953 1954 mInstantAppRegistry = new InstantAppRegistry(mContext, mPermissionManager, 1955 mInjector.getUserManagerInternal(), new DeletePackageHelper(this)); 1956 1957 mChangedPackagesTracker = new ChangedPackagesTracker(); 1958 1959 mAppInstallDir = new File(Environment.getDataDirectory(), "app"); 1960 1961 mDomainVerificationConnection = new DomainVerificationConnection(this); 1962 mDomainVerificationManager = injector.getDomainVerificationManagerInternal(); 1963 mDomainVerificationManager.setConnection(mDomainVerificationConnection); 1964 1965 mBroadcastHelper = new BroadcastHelper(mInjector); 1966 mAppDataHelper = new AppDataHelper(this); 1967 mInstallPackageHelper = new InstallPackageHelper(this, mAppDataHelper); 1968 mRemovePackageHelper = new RemovePackageHelper(this, mAppDataHelper); 1969 mDeletePackageHelper = new DeletePackageHelper(this, mRemovePackageHelper, 1970 mAppDataHelper); 1971 mSharedLibraries.setDeletePackageHelper(mDeletePackageHelper); 1972 mPreferredActivityHelper = new PreferredActivityHelper(this); 1973 mResolveIntentHelper = new ResolveIntentHelper(mContext, mPreferredActivityHelper, 1974 injector.getCompatibility(), mUserManager, mDomainVerificationManager, 1975 mUserNeedsBadging, () -> mResolveInfo, () -> mInstantAppInstallerActivity, 1976 injector.getBackgroundHandler()); 1977 mDexOptHelper = new DexOptHelper(this); 1978 mSuspendPackageHelper = new SuspendPackageHelper(this, mInjector, mUserManager, 1979 mBroadcastHelper, mProtectedPackages); 1980 mDistractingPackageHelper = new DistractingPackageHelper(this, mInjector, mBroadcastHelper, 1981 mSuspendPackageHelper); 1982 mStorageEventHelper = new StorageEventHelper(this, mDeletePackageHelper, 1983 mRemovePackageHelper); 1984 1985 synchronized (mLock) { 1986 // Create the computer as soon as the state objects have been installed. The 1987 // cached computer is the same as the live computer until the end of the 1988 // constructor, at which time the invalidation method updates it. 1989 mSnapshotStatistics = new SnapshotStatistics(); 1990 sSnapshotPendingVersion.incrementAndGet(); 1991 mLiveComputer = createLiveComputer(); 1992 registerObservers(true); 1993 } 1994 1995 Computer computer = mLiveComputer; 1996 // CHECKSTYLE:OFF IndentationCheck 1997 synchronized (mInstallLock) { 1998 // writer 1999 synchronized (mLock) { 2000 mHandler = injector.getHandler(); 2001 mProcessLoggingHandler = new ProcessLoggingHandler(); 2002 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2003 2004 ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig 2005 = systemConfig.getSharedLibraries(); 2006 final int builtInLibCount = libConfig.size(); 2007 for (int i = 0; i < builtInLibCount; i++) { 2008 mSharedLibraries.addBuiltInSharedLibraryLPw(libConfig.valueAt(i)); 2009 } 2010 2011 // Now that we have added all the libraries, iterate again to add dependency 2012 // information IFF their dependencies are added. 2013 long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED; 2014 for (int i = 0; i < builtInLibCount; i++) { 2015 String name = libConfig.keyAt(i); 2016 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i); 2017 final int dependencyCount = entry.dependencies.length; 2018 for (int j = 0; j < dependencyCount; j++) { 2019 final SharedLibraryInfo dependency = 2020 computer.getSharedLibraryInfo(entry.dependencies[j], undefinedVersion); 2021 if (dependency != null) { 2022 computer.getSharedLibraryInfo(name, undefinedVersion) 2023 .addDependency(dependency); 2024 } 2025 } 2026 } 2027 2028 SELinuxMMAC.readInstallPolicy(); 2029 2030 t.traceBegin("loadFallbacks"); 2031 FallbackCategoryProvider.loadFallbacks(); 2032 t.traceEnd(); 2033 2034 t.traceBegin("read user settings"); 2035 mFirstBoot = !mSettings.readLPw(computer, 2036 mInjector.getUserManagerInternal().getUsers( 2037 /* excludePartial= */ true, 2038 /* excludeDying= */ false, 2039 /* excludePreCreated= */ false)); 2040 t.traceEnd(); 2041 2042 if (mFirstBoot) { 2043 t.traceBegin("setFirstBoot: "); 2044 try { 2045 mInstaller.setFirstBoot(); 2046 } catch (InstallerException e) { 2047 Slog.w(TAG, "Could not set First Boot: ", e); 2048 } 2049 t.traceEnd(); 2050 } 2051 2052 mPermissionManager.readLegacyPermissionsTEMP(mSettings.mPermissions); 2053 mPermissionManager.readLegacyPermissionStateTEMP(); 2054 2055 if (mFirstBoot) { 2056 DexOptHelper.requestCopyPreoptedFiles(); 2057 } 2058 2059 String customResolverActivityName = Resources.getSystem().getString( 2060 R.string.config_customResolverActivity); 2061 if (!TextUtils.isEmpty(customResolverActivityName)) { 2062 mCustomResolverComponentName = ComponentName.unflattenFromString( 2063 customResolverActivityName); 2064 } 2065 2066 long startTime = SystemClock.uptimeMillis(); 2067 2068 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2069 startTime); 2070 2071 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2072 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2073 2074 if (bootClassPath == null) { 2075 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2076 } 2077 2078 if (systemServerClassPath == null) { 2079 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2080 } 2081 2082 final VersionInfo ver = mSettings.getInternalVersion(); 2083 mIsUpgrade = 2084 !partitionsFingerprint.equals(ver.fingerprint); 2085 if (mIsUpgrade) { 2086 PackageManagerServiceUtils.logCriticalInfo(Log.INFO, 2087 "Upgrading from " + ver.fingerprint + " (" + ver.buildFingerprint + ") to " 2088 + PackagePartitions.FINGERPRINT + " (" + Build.FINGERPRINT + ")"); 2089 } 2090 2091 mInitAppsHelper = new InitAppsHelper(this, mApexManager, mInstallPackageHelper, 2092 mInjector.getSystemPartitions()); 2093 2094 // when upgrading from pre-M, promote system app permissions from install to runtime 2095 mPromoteSystemApps = 2096 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2097 2098 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2099 mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q; 2100 2101 final WatchedArrayMap<String, PackageSetting> packageSettings = 2102 mSettings.getPackagesLocked(); 2103 2104 if (isDeviceUpgrading()) { 2105 // Save the names of pre-existing packages prior to scanning, so we can determine 2106 // which system packages are completely new due to an upgrade. 2107 mExistingPackages = new ArraySet<>(packageSettings.size()); 2108 for (PackageSetting ps : packageSettings.values()) { 2109 mExistingPackages.add(ps.getPackageName()); 2110 } 2111 2112 // Triggering {@link com.android.server.pm.crossprofile. 2113 // CrossProfileIntentFilterHelper.updateDefaultCrossProfileIntentFilter} to update 2114 // {@link CrossProfileIntentFilter}s between eligible users and their parent 2115 t.traceBegin("cross profile intent filter update"); 2116 mInjector.getCrossProfileIntentFilterHelper() 2117 .updateDefaultCrossProfileIntentFilter(); 2118 t.traceEnd(); 2119 } 2120 2121 mCacheDir = PackageManagerServiceUtils.preparePackageParserCache( 2122 mIsEngBuild, mIsUserDebugBuild, mIncrementalVersion); 2123 2124 mInitialNonStoppedSystemPackages = mInjector.getSystemConfig() 2125 .getInitialNonStoppedSystemPackages(); 2126 mShouldStopSystemPackagesByDefault = mContext.getResources() 2127 .getBoolean(R.bool.config_stopSystemPackagesByDefault); 2128 2129 final int[] userIds = mUserManager.getUserIds(); 2130 PackageParser2 packageParser = mInjector.getScanningCachingPackageParser(); 2131 mOverlayConfig = mInitAppsHelper.initSystemApps(packageParser, packageSettings, userIds, 2132 startTime); 2133 mInitAppsHelper.initNonSystemApps(packageParser, userIds, startTime); 2134 packageParser.close(); 2135 2136 mRequiredVerifierPackages = getRequiredButNotReallyRequiredVerifiersLPr(computer); 2137 mRequiredInstallerPackage = getRequiredInstallerLPr(computer); 2138 mRequiredUninstallerPackage = getRequiredUninstallerLPr(computer); 2139 2140 // PermissionController hosts default permission granting and role management, so it's a 2141 // critical part of the core system. 2142 mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr(computer); 2143 2144 // Resolve the storage manager. 2145 mStorageManagerPackage = getStorageManagerPackageName(computer); 2146 2147 // Resolve protected action filters. Only the setup wizard is allowed to 2148 // have a high priority filter for these actions. 2149 mSetupWizardPackage = getSetupWizardPackageNameImpl(computer); 2150 mComponentResolver.fixProtectedFilterPriorities(mSetupWizardPackage); 2151 2152 mDefaultTextClassifierPackage = ensureSystemPackageName(computer, 2153 mContext.getString(R.string.config_servicesExtensionPackage)); 2154 mSystemTextClassifierPackageName = ensureSystemPackageName(computer, 2155 mContext.getString(R.string.config_defaultTextClassifierPackage)); 2156 mConfiguratorPackage = ensureSystemPackageName(computer, 2157 mContext.getString(R.string.config_deviceConfiguratorPackageName)); 2158 mAppPredictionServicePackage = ensureSystemPackageName(computer, 2159 getPackageFromComponentString(R.string.config_defaultAppPredictionService)); 2160 mIncidentReportApproverPackage = ensureSystemPackageName(computer, 2161 mContext.getString(R.string.config_incidentReportApproverPackage)); 2162 mRetailDemoPackage = getRetailDemoPackageName(); 2163 mOverlayConfigSignaturePackage = ensureSystemPackageName(computer, 2164 mInjector.getSystemConfig().getOverlayConfigSignaturePackage()); 2165 mRecentsPackage = ensureSystemPackageName(computer, 2166 getPackageFromComponentString(R.string.config_recentsComponentName)); 2167 mAmbientContextDetectionPackage = ensureSystemPackageName(computer, 2168 getPackageFromComponentString( 2169 R.string.config_defaultAmbientContextDetectionService)); 2170 mWearableSensingPackage = ensureSystemPackageName(computer, 2171 getPackageFromComponentString( 2172 R.string.config_defaultWearableSensingService)); 2173 2174 // Now that we know all of the shared libraries, update all clients to have 2175 // the correct library paths. 2176 mSharedLibraries.updateAllSharedLibrariesLPw( 2177 null, null, Collections.unmodifiableMap(mPackages)); 2178 2179 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2180 // NOTE: We ignore potential failures here during a system scan (like 2181 // the rest of the commands above) because there's precious little we 2182 // can do about it. A settings error is reported, though. 2183 final List<String> changedAbiCodePath = 2184 ScanPackageUtils.applyAdjustedAbiToSharedUser(setting, 2185 null /*scannedPackage*/, 2186 mInjector.getAbiHelper().getAdjustedAbiForSharedUser( 2187 setting.getPackageStates(), null /*scannedPackage*/)); 2188 if (!useArtService() && // Skip for ART Service since it has its own dex file GC. 2189 changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 2190 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 2191 final String codePathString = changedAbiCodePath.get(i); 2192 try { 2193 mInstaller.rmdex(codePathString, 2194 getDexCodeInstructionSet(getPreferredInstructionSet())); 2195 } catch (LegacyDexoptDisabledException e) { 2196 throw new RuntimeException(e); 2197 } catch (InstallerException ignored) { 2198 } 2199 } 2200 } 2201 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 2202 // SELinux domain. 2203 setting.fixSeInfoLocked(); 2204 setting.updateProcesses(); 2205 } 2206 2207 // Now that we know all the packages we are keeping, 2208 // read and update their last usage times. 2209 mPackageUsage.read(packageSettings); 2210 mCompilerStats.read(); 2211 2212 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2213 SystemClock.uptimeMillis()); 2214 Slog.i(TAG, "Time to scan packages: " 2215 + ((SystemClock.uptimeMillis() - startTime) / 1000f) 2216 + " seconds"); 2217 2218 // If the partitions fingerprint has changed since the last time we booted, 2219 // we need to re-grant app permission to catch any new ones that 2220 // appear. This is really a hack, and means that apps can in some 2221 // cases get permissions that the user didn't initially explicitly 2222 // allow... it would be nice to have some better way to handle 2223 // this situation. 2224 if (mIsUpgrade) { 2225 Slog.i(TAG, "Partitions fingerprint changed from " + ver.fingerprint + " to " 2226 + PackagePartitions.FINGERPRINT 2227 + "; regranting permissions for internal storage"); 2228 } 2229 mPermissionManager.onStorageVolumeMounted( 2230 StorageManager.UUID_PRIVATE_INTERNAL, mIsUpgrade); 2231 ver.sdkVersion = mSdkVersion; 2232 2233 // If this is the first boot or an update from pre-M, then we need to initialize the 2234 // default preferred apps across all defined users. 2235 if (mPromoteSystemApps || mFirstBoot) { 2236 for (UserInfo user : mInjector.getUserManagerInternal().getUsers(true)) { 2237 mSettings.applyDefaultPreferredAppsLPw(user.id); 2238 } 2239 } 2240 2241 // If this is first boot after an OTA, then we need to clear code cache directories. 2242 // Note that we do *not* clear the application profiles. These remain valid 2243 // across OTAs and are used to drive profile verification (post OTA) and 2244 // profile compilation (without waiting to collect a fresh set of profiles). 2245 if (mIsUpgrade) { 2246 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2247 for (int i = 0; i < packageSettings.size(); i++) { 2248 final PackageSetting ps = packageSettings.valueAt(i); 2249 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.getVolumeUuid())) { 2250 // No apps are running this early, so no need to freeze 2251 mAppDataHelper.clearAppDataLIF(ps.getPkg(), UserHandle.USER_ALL, 2252 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL 2253 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY 2254 | Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES); 2255 } 2256 } 2257 ver.buildFingerprint = Build.FINGERPRINT; 2258 ver.fingerprint = PackagePartitions.FINGERPRINT; 2259 } 2260 2261 // Defer the app data fixup until we are done with app data clearing above. 2262 mPrepareAppDataFuture = mAppDataHelper.fixAppsDataOnBoot(); 2263 2264 // Legacy existing (installed before Q) non-system apps to hide 2265 // their icons in launcher. 2266 if (mIsPreQUpgrade) { 2267 Slog.i(TAG, "Allowlisting all existing apps to hide their icons"); 2268 int size = packageSettings.size(); 2269 for (int i = 0; i < size; i++) { 2270 final PackageSetting ps = packageSettings.valueAt(i); 2271 if ((ps.getFlags() & ApplicationInfo.FLAG_SYSTEM) != 0) { 2272 continue; 2273 } 2274 ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME, 2275 UserHandle.USER_SYSTEM); 2276 } 2277 } 2278 2279 // clear only after permissions and other defaults have been updated 2280 mPromoteSystemApps = false; 2281 2282 // All the changes are done during package scanning. 2283 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2284 2285 // can downgrade to reader 2286 t.traceBegin("write settings"); 2287 writeSettingsLPrTEMP(); 2288 t.traceEnd(); 2289 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2290 SystemClock.uptimeMillis()); 2291 2292 ComponentName intentFilterVerifierComponent = 2293 getIntentFilterVerifierComponentNameLPr(computer); 2294 ComponentName domainVerificationAgent = 2295 getDomainVerificationAgentComponentNameLPr(computer); 2296 2297 DomainVerificationProxy domainVerificationProxy = DomainVerificationProxy.makeProxy( 2298 intentFilterVerifierComponent, domainVerificationAgent, mContext, 2299 mDomainVerificationManager, mDomainVerificationManager.getCollector(), 2300 mDomainVerificationConnection); 2301 2302 mDomainVerificationManager.setProxy(domainVerificationProxy); 2303 2304 mServicesExtensionPackageName = getRequiredServicesExtensionPackageLPr(computer); 2305 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibrary(computer, 2306 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 2307 SharedLibraryInfo.VERSION_UNDEFINED); 2308 2309 mSettings.setPermissionControllerVersion( 2310 computer.getPackageInfo(mRequiredPermissionControllerPackage, 0, 2311 UserHandle.USER_SYSTEM).getLongVersionCode()); 2312 2313 // Resolve the sdk sandbox package 2314 mRequiredSdkSandboxPackage = getRequiredSdkSandboxPackageName(computer); 2315 2316 // Initialize InstantAppRegistry's Instant App list for all users. 2317 forEachPackageState(computer, packageState -> { 2318 var pkg = packageState.getAndroidPackage(); 2319 if (pkg == null || packageState.isSystem()) { 2320 return; 2321 } 2322 for (int userId : userIds) { 2323 if (!packageState.getUserStateOrDefault(userId).isInstantApp() 2324 || !packageState.getUserStateOrDefault(userId).isInstalled()) { 2325 continue; 2326 } 2327 mInstantAppRegistry.addInstantApp(userId, packageState.getAppId()); 2328 } 2329 }); 2330 2331 mInstallerService = mInjector.getPackageInstallerService(); 2332 final ComponentName instantAppResolverComponent = getInstantAppResolver(computer); 2333 if (instantAppResolverComponent != null) { 2334 if (DEBUG_INSTANT) { 2335 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 2336 } 2337 mInstantAppResolverConnection = 2338 mInjector.getInstantAppResolverConnection(instantAppResolverComponent); 2339 mInstantAppResolverSettingsComponent = 2340 getInstantAppResolverSettingsLPr(computer, 2341 instantAppResolverComponent); 2342 } else { 2343 mInstantAppResolverConnection = null; 2344 mInstantAppResolverSettingsComponent = null; 2345 } 2346 updateInstantAppInstallerLocked(null); 2347 2348 // Read and update the usage of dex files. 2349 // Do this at the end of PM init so that all the packages have their 2350 // data directory reconciled. 2351 // At this point we know the code paths of the packages, so we can validate 2352 // the disk file and build the internal cache. 2353 // The usage file is expected to be small so loading and verifying it 2354 // should take a fairly small time compare to the other activities (e.g. package 2355 // scanning). 2356 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 2357 for (int userId : userIds) { 2358 userPackages.put(userId, computer.getInstalledPackages(/*flags*/ 0, userId) 2359 .getList()); 2360 } 2361 mDexManager.load(userPackages); 2362 mDynamicCodeLogger.load(userPackages); 2363 if (mIsUpgrade) { 2364 FrameworkStatsLog.write( 2365 FrameworkStatsLog.BOOT_TIME_EVENT_DURATION_REPORTED, 2366 BOOT_TIME_EVENT_DURATION__EVENT__OTA_PACKAGE_MANAGER_INIT_TIME, 2367 SystemClock.uptimeMillis() - startTime); 2368 } 2369 2370 // If this is first boot or first boot after OTA then set the file path to the app 2371 // metadata files for preloaded packages. 2372 if (mFirstBoot || isDeviceUpgrading()) { 2373 ArrayMap<String, String> paths = systemConfig.getAppMetadataFilePaths(); 2374 for (Map.Entry<String, String> entry : paths.entrySet()) { 2375 String pkgName = entry.getKey(); 2376 String path = entry.getValue(); 2377 File file = new File(path); 2378 if (!file.exists()) { 2379 path = null; 2380 } 2381 PackageSetting disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(pkgName); 2382 if (disabledPkgSetting == null) { 2383 PackageSetting pkgSetting = mSettings.getPackageLPr(pkgName); 2384 if (pkgSetting != null) { 2385 pkgSetting.setAppMetadataFilePath(path); 2386 } else { 2387 Slog.w(TAG, "Cannot set app metadata file for nonexistent package " 2388 + pkgName); 2389 } 2390 } else { 2391 disabledPkgSetting.setAppMetadataFilePath(path); 2392 } 2393 } 2394 } 2395 2396 // Rebuild the live computer since some attributes have been rebuilt. 2397 mLiveComputer = createLiveComputer(); 2398 2399 } // synchronized (mLock) 2400 } // synchronized (mInstallLock) 2401 // CHECKSTYLE:ON IndentationCheck 2402 2403 mModuleInfoProvider = mInjector.getModuleInfoProvider(); 2404 2405 mInjector.getSystemWrapper().enablePackageCaches(); 2406 2407 // Now after opening every single application zip, make sure they 2408 // are all flushed. Not really needed, but keeps things nice and 2409 // tidy. 2410 t.traceBegin("GC"); 2411 VMRuntime.getRuntime().requestConcurrentGC(); 2412 t.traceEnd(); 2413 2414 // The initial scanning above does many calls into installd while 2415 // holding the mPackages lock, but we're mostly interested in yelling 2416 // once we have a booted system. 2417 mInstaller.setWarnIfHeld(mLock); 2418 2419 ParsingPackageUtils.readConfigUseRoundIcon(mContext.getResources()); 2420 2421 mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L); 2422 2423 Slog.i(TAG, "Fix for b/169414761 is applied"); 2424 } 2425 2426 @GuardedBy("mLock") 2427 void updateInstantAppInstallerLocked(String modifiedPackage) { 2428 // we're only interested in updating the installer application when 1) it's not 2429 // already set or 2) the modified package is the installer 2430 if (mInstantAppInstallerActivity != null 2431 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 2432 .equals(modifiedPackage)) { 2433 return; 2434 } 2435 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 2436 } 2437 2438 public boolean isFirstBoot() { 2439 // allow instant applications 2440 return mFirstBoot; 2441 } 2442 2443 public boolean isDeviceUpgrading() { 2444 // allow instant applications 2445 // The system property allows testing ota flow when upgraded to the same image. 2446 return mIsUpgrade || SystemProperties.getBoolean( 2447 "persist.pm.mock-upgrade", false /* default */); 2448 } 2449 2450 @NonNull 2451 private String[] getRequiredButNotReallyRequiredVerifiersLPr(@NonNull Computer computer) { 2452 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2453 2454 final List<ResolveInfo> matches = 2455 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent, 2456 PACKAGE_MIME_TYPE, 2457 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2458 UserHandle.USER_SYSTEM, Binder.getCallingUid()); 2459 final int size = matches.size(); 2460 if (size == 0) { 2461 Log.w(TAG, "There should probably be a verifier, but, none were found"); 2462 return EmptyArray.STRING; 2463 } else if (size <= REQUIRED_VERIFIERS_MAX_COUNT) { 2464 String[] verifiers = new String[size]; 2465 for (int i = 0; i < size; ++i) { 2466 verifiers[i] = matches.get(i).getComponentInfo().packageName; 2467 if (TextUtils.isEmpty(verifiers[i])) { 2468 throw new RuntimeException("Invalid verifier: " + matches); 2469 } 2470 } 2471 return verifiers; 2472 } 2473 throw new RuntimeException( 2474 "There must be no more than " + REQUIRED_VERIFIERS_MAX_COUNT + " verifiers; found " 2475 + matches); 2476 } 2477 2478 @NonNull 2479 private String getRequiredSharedLibrary(@NonNull Computer snapshot, @NonNull String name, 2480 int version) { 2481 SharedLibraryInfo libraryInfo = snapshot.getSharedLibraryInfo(name, version); 2482 if (libraryInfo == null) { 2483 throw new IllegalStateException("Missing required shared library:" + name); 2484 } 2485 String packageName = libraryInfo.getPackageName(); 2486 if (packageName == null) { 2487 throw new IllegalStateException("Expected a package for shared library " + name); 2488 } 2489 return packageName; 2490 } 2491 2492 @NonNull 2493 private String getRequiredServicesExtensionPackageLPr(@NonNull Computer computer) { 2494 String servicesExtensionPackage = 2495 ensureSystemPackageName(computer, 2496 mContext.getString(R.string.config_servicesExtensionPackage)); 2497 if (TextUtils.isEmpty(servicesExtensionPackage)) { 2498 throw new RuntimeException( 2499 "Required services extension package is missing, check " 2500 + "config_servicesExtensionPackage."); 2501 } 2502 return servicesExtensionPackage; 2503 } 2504 2505 private @NonNull String getRequiredInstallerLPr(@NonNull Computer computer) { 2506 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2507 intent.addCategory(Intent.CATEGORY_DEFAULT); 2508 intent.setDataAndType(Uri.parse("content://com.example/foo.apk"), PACKAGE_MIME_TYPE); 2509 2510 final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, 2511 PACKAGE_MIME_TYPE, 2512 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2513 UserHandle.USER_SYSTEM); 2514 if (matches.size() == 1) { 2515 ResolveInfo resolveInfo = matches.get(0); 2516 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2517 throw new RuntimeException("The installer must be a privileged app"); 2518 } 2519 return matches.get(0).getComponentInfo().packageName; 2520 } else { 2521 throw new RuntimeException("There must be exactly one installer; found " + matches); 2522 } 2523 } 2524 2525 private @NonNull String getRequiredUninstallerLPr(@NonNull Computer computer) { 2526 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 2527 intent.addCategory(Intent.CATEGORY_DEFAULT); 2528 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 2529 2530 final ResolveInfo resolveInfo = mResolveIntentHelper.resolveIntentInternal(computer, intent, 2531 null, MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2532 0 /*privateResolveFlags*/, UserHandle.USER_SYSTEM, false, Binder.getCallingUid()); 2533 if (resolveInfo == null || 2534 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 2535 throw new RuntimeException("There must be exactly one uninstaller; found " 2536 + resolveInfo); 2537 } 2538 return resolveInfo.getComponentInfo().packageName; 2539 } 2540 2541 private @NonNull String getRequiredPermissionControllerLPr(@NonNull Computer computer) { 2542 final Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSIONS); 2543 intent.addCategory(Intent.CATEGORY_DEFAULT); 2544 2545 final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null, 2546 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2547 UserHandle.USER_SYSTEM); 2548 if (matches.size() == 1) { 2549 ResolveInfo resolveInfo = matches.get(0); 2550 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2551 throw new RuntimeException("The permissions manager must be a privileged app"); 2552 } 2553 return matches.get(0).getComponentInfo().packageName; 2554 } else { 2555 throw new RuntimeException("There must be exactly one permissions manager; found " 2556 + matches); 2557 } 2558 } 2559 2560 @NonNull 2561 private ComponentName getIntentFilterVerifierComponentNameLPr(@NonNull Computer computer) { 2562 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2563 2564 final List<ResolveInfo> matches = 2565 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent, 2566 PACKAGE_MIME_TYPE, 2567 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2568 UserHandle.USER_SYSTEM, Binder.getCallingUid()); 2569 ResolveInfo best = null; 2570 final int N = matches.size(); 2571 for (int i = 0; i < N; i++) { 2572 final ResolveInfo cur = matches.get(i); 2573 final String packageName = cur.getComponentInfo().packageName; 2574 if (checkPermission( 2575 android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, packageName, 2576 UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2577 continue; 2578 } 2579 2580 if (best == null || cur.priority > best.priority) { 2581 best = cur; 2582 } 2583 } 2584 2585 if (best != null) { 2586 return best.getComponentInfo().getComponentName(); 2587 } 2588 Slog.w(TAG, "Intent filter verifier not found"); 2589 return null; 2590 } 2591 2592 @Nullable 2593 private ComponentName getDomainVerificationAgentComponentNameLPr(@NonNull Computer computer) { 2594 Intent intent = new Intent(Intent.ACTION_DOMAINS_NEED_VERIFICATION); 2595 List<ResolveInfo> matches = 2596 mResolveIntentHelper.queryIntentReceiversInternal(computer, intent, null, 2597 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2598 UserHandle.USER_SYSTEM, Binder.getCallingUid()); 2599 ResolveInfo best = null; 2600 final int N = matches.size(); 2601 for (int i = 0; i < N; i++) { 2602 final ResolveInfo cur = matches.get(i); 2603 final String packageName = cur.getComponentInfo().packageName; 2604 if (checkPermission( 2605 android.Manifest.permission.DOMAIN_VERIFICATION_AGENT, packageName, 2606 UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2607 Slog.w(TAG, "Domain verification agent found but does not hold permission: " 2608 + packageName); 2609 continue; 2610 } 2611 2612 if (best == null || cur.priority > best.priority) { 2613 if (computer.isComponentEffectivelyEnabled(cur.getComponentInfo(), 2614 UserHandle.SYSTEM)) { 2615 best = cur; 2616 } else { 2617 Slog.w(TAG, "Domain verification agent found but not enabled"); 2618 } 2619 } 2620 } 2621 2622 if (best != null) { 2623 return best.getComponentInfo().getComponentName(); 2624 } 2625 Slog.w(TAG, "Domain verification agent not found"); 2626 return null; 2627 } 2628 2629 @Nullable ComponentName getInstantAppResolver(@NonNull Computer snapshot) { 2630 final String[] packageArray = 2631 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2632 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2633 if (DEBUG_INSTANT) { 2634 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2635 } 2636 return null; 2637 } 2638 2639 final int callingUid = Binder.getCallingUid(); 2640 final int resolveFlags = 2641 MATCH_DIRECT_BOOT_AWARE 2642 | MATCH_DIRECT_BOOT_UNAWARE 2643 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2644 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE); 2645 List<ResolveInfo> resolvers = snapshot.queryIntentServicesInternal(resolverIntent, null, 2646 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 2647 final int N = resolvers.size(); 2648 if (N == 0) { 2649 if (DEBUG_INSTANT) { 2650 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2651 } 2652 return null; 2653 } 2654 2655 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2656 for (int i = 0; i < N; i++) { 2657 final ResolveInfo info = resolvers.get(i); 2658 2659 if (info.serviceInfo == null) { 2660 continue; 2661 } 2662 2663 final String packageName = info.serviceInfo.packageName; 2664 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2665 if (DEBUG_INSTANT) { 2666 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2667 + " pkg: " + packageName + ", info:" + info); 2668 } 2669 continue; 2670 } 2671 2672 if (DEBUG_INSTANT) { 2673 Slog.v(TAG, "Ephemeral resolver found;" 2674 + " pkg: " + packageName + ", info:" + info); 2675 } 2676 return new ComponentName(packageName, info.serviceInfo.name); 2677 } 2678 if (DEBUG_INSTANT) { 2679 Slog.v(TAG, "Ephemeral resolver NOT found"); 2680 } 2681 return null; 2682 } 2683 2684 @GuardedBy("mLock") 2685 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 2686 String[] orderedActions = mIsEngBuild 2687 ? new String[]{ 2688 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 2689 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 2690 : new String[]{ 2691 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 2692 2693 final int resolveFlags = 2694 MATCH_DIRECT_BOOT_AWARE 2695 | MATCH_DIRECT_BOOT_UNAWARE 2696 | Intent.FLAG_IGNORE_EPHEMERAL 2697 | (mIsEngBuild ? 0 : MATCH_SYSTEM_ONLY); 2698 final Computer computer = snapshotComputer(); 2699 final Intent intent = new Intent(); 2700 intent.addCategory(Intent.CATEGORY_DEFAULT); 2701 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2702 List<ResolveInfo> matches = null; 2703 for (String action : orderedActions) { 2704 intent.setAction(action); 2705 matches = computer.queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2706 resolveFlags, UserHandle.USER_SYSTEM); 2707 if (matches.isEmpty()) { 2708 if (DEBUG_INSTANT) { 2709 Slog.d(TAG, "Instant App installer not found with " + action); 2710 } 2711 } else { 2712 break; 2713 } 2714 } 2715 Iterator<ResolveInfo> iter = matches.iterator(); 2716 while (iter.hasNext()) { 2717 final ResolveInfo rInfo = iter.next(); 2718 if (checkPermission( 2719 Manifest.permission.INSTALL_PACKAGES, 2720 rInfo.activityInfo.packageName, 0) == PERMISSION_GRANTED || mIsEngBuild) { 2721 continue; 2722 } 2723 iter.remove(); 2724 } 2725 if (matches.size() == 0) { 2726 return null; 2727 } else if (matches.size() == 1) { 2728 return (ActivityInfo) matches.get(0).getComponentInfo(); 2729 } else { 2730 throw new RuntimeException( 2731 "There must be at most one ephemeral installer; found " + matches); 2732 } 2733 } 2734 2735 private @Nullable ComponentName getInstantAppResolverSettingsLPr(@NonNull Computer computer, 2736 @NonNull ComponentName resolver) { 2737 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 2738 .addCategory(Intent.CATEGORY_DEFAULT) 2739 .setPackage(resolver.getPackageName()); 2740 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 2741 List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null, 2742 resolveFlags, UserHandle.USER_SYSTEM); 2743 if (matches.isEmpty()) { 2744 return null; 2745 } 2746 return matches.get(0).getComponentInfo().getComponentName(); 2747 } 2748 2749 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 2750 // Because this is accessed via the package manager service AIDL, 2751 // go through the permission manager service AIDL 2752 return mContext.getSystemService(PermissionManager.class) 2753 .getPermissionGroupInfo(groupName, flags); 2754 } 2755 2756 /** 2757 * Blocking call to clear all cached app data above quota. 2758 */ 2759 public void freeAllAppCacheAboveQuota(String volumeUuid) throws IOException { 2760 synchronized (mInstallLock) { 2761 // To avoid refactoring Installer.freeCache() and InstalldNativeService.freeCache(), 2762 // Long.MAX_VALUE is passed as an argument which is used in neither of two methods 2763 // when FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES is set 2764 try { 2765 mInstaller.freeCache(volumeUuid, Long.MAX_VALUE, Installer.FLAG_FREE_CACHE_V2 2766 | Installer.FLAG_FREE_CACHE_DEFY_TARGET_FREE_BYTES); 2767 } catch (InstallerException ignored) { 2768 } 2769 } 2770 return; 2771 } 2772 2773 /** 2774 * Blocking call to clear various types of cached data across the system 2775 * until the requested bytes are available. 2776 */ 2777 public void freeStorage(String volumeUuid, long bytes, 2778 @StorageManager.AllocateFlags int flags) throws IOException { 2779 final StorageManager storage = mInjector.getSystemService(StorageManager.class); 2780 final File file = storage.findPathForUuid(volumeUuid); 2781 if (file.getUsableSpace() >= bytes) return; 2782 2783 if (mEnableFreeCacheV2) { 2784 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 2785 volumeUuid); 2786 final boolean aggressive = (flags & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 2787 2788 // 1. Pre-flight to determine if we have any chance to succeed 2789 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 2790 if (internalVolume && (aggressive || SystemProperties 2791 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 2792 deletePreloadsFileCache(); 2793 if (file.getUsableSpace() >= bytes) return; 2794 } 2795 2796 // 3. Consider parsed APK data (aggressive only) 2797 if (internalVolume && aggressive) { 2798 FileUtils.deleteContents(mCacheDir); 2799 if (file.getUsableSpace() >= bytes) return; 2800 } 2801 2802 // 4. Consider cached app data (above quotas) 2803 synchronized (mInstallLock) { 2804 try { 2805 mInstaller.freeCache(volumeUuid, bytes, Installer.FLAG_FREE_CACHE_V2); 2806 } catch (InstallerException ignored) { 2807 } 2808 } 2809 if (file.getUsableSpace() >= bytes) return; 2810 2811 Computer computer = snapshotComputer(); 2812 // 5. Consider shared libraries with refcount=0 and age>min cache period 2813 if (internalVolume && mSharedLibraries.pruneUnusedStaticSharedLibraries(computer, bytes, 2814 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 2815 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 2816 FREE_STORAGE_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 2817 return; 2818 } 2819 2820 // 6. Consider dexopt output (aggressive only) 2821 // TODO: Implement 2822 2823 // 7. Consider installed instant apps unused longer than min cache period 2824 if (internalVolume) { 2825 if (mInstantAppRegistry.pruneInstalledInstantApps(computer, bytes, 2826 android.provider.Settings.Global.getLong( 2827 mContext.getContentResolver(), 2828 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 2829 InstantAppRegistry 2830 .DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 2831 return; 2832 } 2833 } 2834 2835 // 8. Consider cached app data (below quotas) 2836 synchronized (mInstallLock) { 2837 try { 2838 mInstaller.freeCache(volumeUuid, bytes, 2839 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 2840 } catch (InstallerException ignored) { 2841 } 2842 } 2843 if (file.getUsableSpace() >= bytes) return; 2844 2845 // 9. Consider DropBox entries 2846 // TODO: Implement 2847 2848 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 2849 if (internalVolume) { 2850 if (mInstantAppRegistry.pruneUninstalledInstantApps(computer, bytes, 2851 android.provider.Settings.Global.getLong( 2852 mContext.getContentResolver(), 2853 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 2854 InstantAppRegistry 2855 .DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 2856 return; 2857 } 2858 } 2859 2860 // 11. Free storage service cache 2861 StorageManagerInternal smInternal = 2862 mInjector.getLocalService(StorageManagerInternal.class); 2863 long freeBytesRequired = bytes - file.getUsableSpace(); 2864 if (freeBytesRequired > 0) { 2865 smInternal.freeCache(volumeUuid, freeBytesRequired); 2866 } 2867 2868 // 12. Clear temp install session files 2869 mInstallerService.freeStageDirs(volumeUuid); 2870 } else { 2871 synchronized (mInstallLock) { 2872 try { 2873 mInstaller.freeCache(volumeUuid, bytes, 0); 2874 } catch (InstallerException ignored) { 2875 } 2876 } 2877 } 2878 if (file.getUsableSpace() >= bytes) return; 2879 2880 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 2881 } 2882 2883 int freeCacheForInstallation(int recommendedInstallLocation, PackageLite pkgLite, 2884 String resolvedPath, String mPackageAbiOverride, int installFlags) { 2885 // TODO: focus freeing disk space on the target device 2886 final StorageManager storage = StorageManager.from(mContext); 2887 final long lowThreshold = storage.getStorageLowBytes(Environment.getDataDirectory()); 2888 2889 final long sizeBytes = PackageManagerServiceUtils.calculateInstalledSize(resolvedPath, 2890 mPackageAbiOverride); 2891 if (sizeBytes >= 0) { 2892 synchronized (mInstallLock) { 2893 try { 2894 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0); 2895 PackageInfoLite pkgInfoLite = PackageManagerServiceUtils.getMinimalPackageInfo( 2896 mContext, pkgLite, resolvedPath, installFlags, 2897 mPackageAbiOverride); 2898 // The cache free must have deleted the file we downloaded to install. 2899 if (pkgInfoLite.recommendedInstallLocation 2900 == InstallLocationUtils.RECOMMEND_FAILED_INVALID_URI) { 2901 pkgInfoLite.recommendedInstallLocation = 2902 InstallLocationUtils.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 2903 } 2904 return pkgInfoLite.recommendedInstallLocation; 2905 } catch (Installer.InstallerException e) { 2906 Slog.w(TAG, "Failed to free cache", e); 2907 } 2908 } 2909 } 2910 return recommendedInstallLocation; 2911 } 2912 2913 public ModuleInfo getModuleInfo(String packageName, @PackageManager.ModuleInfoFlags int flags) { 2914 return mModuleInfoProvider.getModuleInfo(packageName, flags); 2915 } 2916 2917 void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 2918 mChangedPackagesTracker.updateSequenceNumber(pkgSetting.getPackageName(), userList); 2919 } 2920 2921 public boolean hasSystemFeature(String name, int version) { 2922 // allow instant applications 2923 synchronized (mAvailableFeatures) { 2924 final FeatureInfo feat = mAvailableFeatures.get(name); 2925 if (feat == null) { 2926 return false; 2927 } else { 2928 return feat.version >= version; 2929 } 2930 } 2931 } 2932 2933 // NOTE: Can't remove due to unsupported app usage 2934 public int checkPermission(String permName, String pkgName, int userId) { 2935 return mPermissionManager.checkPermission(pkgName, permName, userId); 2936 } 2937 2938 public String getSdkSandboxPackageName() { 2939 return mRequiredSdkSandboxPackage; 2940 } 2941 2942 String getPackageInstallerPackageName() { 2943 return mRequiredInstallerPackage; 2944 } 2945 2946 void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 2947 Intent origIntent, String resolvedType, String callingPackage, 2948 @Nullable String callingFeatureId, boolean isRequesterInstantApp, 2949 Bundle verificationBundle, int userId) { 2950 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 2951 new InstantAppRequest(responseObj, origIntent, resolvedType, 2952 callingPackage, callingFeatureId, isRequesterInstantApp, userId, 2953 verificationBundle, false /*resolveForStart*/, 2954 responseObj.hostDigestPrefixSecure, responseObj.token)); 2955 mHandler.sendMessage(msg); 2956 } 2957 2958 // findPreferredActivityBody returns two items: a "things changed" flag and a 2959 // ResolveInfo, which is the preferred activity itself. 2960 static class FindPreferredActivityBodyResult { 2961 boolean mChanged; 2962 ResolveInfo mPreferredResolveInfo; 2963 } 2964 2965 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(@NonNull Computer snapshot, 2966 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 2967 @UserIdInt int userId) { 2968 return new ParceledListSlice<>(mResolveIntentHelper.queryIntentReceiversInternal( 2969 snapshot, intent, resolvedType, flags, userId, Binder.getCallingUid())); 2970 } 2971 2972 public static void reportSettingsProblem(int priority, String msg) { 2973 logCriticalInfo(priority, msg); 2974 } 2975 2976 // TODO:(b/135203078): Move to parsing 2977 static void renameStaticSharedLibraryPackage(ParsedPackage parsedPackage) { 2978 // Derive the new package synthetic package name 2979 parsedPackage.setPackageName(toStaticSharedLibraryPackageName( 2980 parsedPackage.getPackageName(), parsedPackage.getStaticSharedLibraryVersion())); 2981 } 2982 2983 private static String toStaticSharedLibraryPackageName( 2984 String packageName, long libraryVersion) { 2985 return packageName + STATIC_SHARED_LIB_DELIMITER + libraryVersion; 2986 } 2987 2988 public void performFstrimIfNeeded() { 2989 PackageManagerServiceUtils.enforceSystemOrRoot("Only the system can request fstrim"); 2990 2991 // Before everything else, see whether we need to fstrim. 2992 try { 2993 IStorageManager sm = InstallLocationUtils.getStorageManager(); 2994 if (sm != null) { 2995 boolean doTrim = false; 2996 final long interval = android.provider.Settings.Global.getLong( 2997 mContext.getContentResolver(), 2998 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 2999 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 3000 if (interval > 0) { 3001 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 3002 if (timeSinceLast > interval) { 3003 doTrim = true; 3004 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 3005 + "; running immediately"); 3006 } 3007 } 3008 if (doTrim) { 3009 sm.runMaintenance(); 3010 } 3011 } else { 3012 Slog.e(TAG, "storageManager service unavailable!"); 3013 } 3014 } catch (RemoteException e) { 3015 // Can't happen; StorageManagerService is local 3016 } 3017 } 3018 3019 public void updatePackagesIfNeeded() { 3020 mDexOptHelper.performPackageDexOptUpgradeIfNeeded(); 3021 } 3022 3023 private void notifyPackageUseInternal(String packageName, int reason) { 3024 long time = System.currentTimeMillis(); 3025 synchronized (mLock) { 3026 final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName); 3027 if (pkgSetting == null) { 3028 return; 3029 } 3030 pkgSetting.getPkgState().setLastPackageUsageTimeInMills(reason, time); 3031 } 3032 } 3033 3034 /*package*/ DexManager getDexManager() { 3035 return mDexManager; 3036 } 3037 3038 /*package*/ DexOptHelper getDexOptHelper() { 3039 return mDexOptHelper; 3040 } 3041 3042 /*package*/ DynamicCodeLogger getDynamicCodeLogger() { 3043 return mDynamicCodeLogger; 3044 } 3045 3046 public void shutdown() { 3047 mCompilerStats.writeNow(); 3048 mDexManager.writePackageDexUsageNow(); 3049 mDynamicCodeLogger.writeNow(); 3050 PackageWatchdog.getInstance(mContext).writeNow(); 3051 3052 synchronized (mLock) { 3053 mPackageUsage.writeNow(mSettings.getPackagesLocked()); 3054 3055 if (mHandler.hasMessages(WRITE_SETTINGS) 3056 || mBackgroundHandler.hasMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS) 3057 || mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 3058 writeSettings(/*sync=*/true); 3059 } 3060 } 3061 } 3062 3063 int[] resolveUserIds(int userId) { 3064 return (userId == UserHandle.USER_ALL) ? mUserManager.getUserIds() : new int[] { userId }; 3065 } 3066 3067 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 3068 if (installerActivity == null) { 3069 if (DEBUG_INSTANT) { 3070 Slog.d(TAG, "Clear ephemeral installer activity"); 3071 } 3072 mInstantAppInstallerActivity = null; 3073 onChanged(); 3074 return; 3075 } 3076 3077 if (DEBUG_INSTANT) { 3078 Slog.d(TAG, "Set ephemeral installer activity: " 3079 + installerActivity.getComponentName()); 3080 } 3081 // Set up information for ephemeral installer activity 3082 mInstantAppInstallerActivity = installerActivity; 3083 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 3084 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 3085 mInstantAppInstallerActivity.exported = true; 3086 mInstantAppInstallerActivity.enabled = true; 3087 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 3088 mInstantAppInstallerInfo.priority = 1; 3089 mInstantAppInstallerInfo.preferredOrder = 1; 3090 mInstantAppInstallerInfo.isDefault = true; 3091 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 3092 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 3093 onChanged(); 3094 } 3095 3096 void killApplication(String pkgName, @AppIdInt int appId, String reason, int exitInfoReason) { 3097 killApplication(pkgName, appId, UserHandle.USER_ALL, reason, exitInfoReason); 3098 } 3099 3100 void killApplication(String pkgName, @AppIdInt int appId, 3101 @UserIdInt int userId, String reason, int exitInfoReason) { 3102 // Request the ActivityManager to kill the process(only for existing packages) 3103 // so that we do not end up in a confused state while the user is still using the older 3104 // version of the application while the new one gets installed. 3105 final long token = Binder.clearCallingIdentity(); 3106 try { 3107 IActivityManager am = ActivityManager.getService(); 3108 if (am != null) { 3109 try { 3110 am.killApplication(pkgName, appId, userId, reason, exitInfoReason); 3111 } catch (RemoteException e) { 3112 } 3113 } 3114 } finally { 3115 Binder.restoreCallingIdentity(token); 3116 } 3117 } 3118 3119 @Override 3120 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 3121 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 3122 final int[] userIds, int[] instantUserIds, 3123 @Nullable SparseArray<int[]> broadcastAllowList, 3124 @Nullable Bundle bOptions) { 3125 mHandler.post(() -> mBroadcastHelper.sendPackageBroadcast(action, pkg, extras, flags, 3126 targetPkg, finishedReceiver, userIds, instantUserIds, broadcastAllowList, 3127 null /* filterExtrasForReceiver */, bOptions)); 3128 } 3129 3130 @Override 3131 public void notifyPackageAdded(String packageName, int uid) { 3132 mPackageObserverHelper.notifyAdded(packageName, uid); 3133 } 3134 3135 @Override 3136 public void notifyPackageChanged(String packageName, int uid) { 3137 mPackageObserverHelper.notifyChanged(packageName, uid); 3138 } 3139 3140 @Override 3141 public void notifyPackageRemoved(String packageName, int uid) { 3142 mPackageObserverHelper.notifyRemoved(packageName, uid); 3143 UserPackage.removeFromCache(UserHandle.getUserId(uid), packageName); 3144 } 3145 3146 void sendPackageAddedForUser(@NonNull Computer snapshot, String packageName, 3147 @NonNull PackageStateInternal packageState, int userId, int dataLoaderType) { 3148 final PackageUserStateInternal userState = packageState.getUserStateOrDefault(userId); 3149 final boolean isSystem = packageState.isSystem(); 3150 final boolean isInstantApp = userState.isInstantApp(); 3151 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 3152 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 3153 sendPackageAddedForNewUsers(snapshot, packageName, isSystem /*sendBootCompleted*/, 3154 false /*startReceiver*/, packageState.getAppId(), userIds, instantUserIds, 3155 dataLoaderType); 3156 3157 // Send a session commit broadcast 3158 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 3159 info.installReason = userState.getInstallReason(); 3160 info.appPackageName = packageName; 3161 sendSessionCommitBroadcast(info, userId); 3162 } 3163 3164 @Override 3165 public void sendPackageAddedForNewUsers(@NonNull Computer snapshot, String packageName, 3166 boolean sendBootCompleted, boolean includeStopped, @AppIdInt int appId, int[] userIds, 3167 int[] instantUserIds, int dataLoaderType) { 3168 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 3169 return; 3170 } 3171 SparseArray<int[]> broadcastAllowList = mAppsFilter.getVisibilityAllowList(snapshot, 3172 snapshot.getPackageStateInternal(packageName, Process.SYSTEM_UID), 3173 userIds, snapshot.getPackageStates()); 3174 mHandler.post(() -> mBroadcastHelper.sendPackageAddedForNewUsers( 3175 packageName, appId, userIds, instantUserIds, dataLoaderType, broadcastAllowList)); 3176 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 3177 mHandler.post(() -> { 3178 for (int userId : userIds) { 3179 mBroadcastHelper.sendBootCompletedBroadcastToSystemApp( 3180 packageName, includeStopped, userId); 3181 } 3182 } 3183 ); 3184 } 3185 } 3186 3187 private void sendApplicationHiddenForUser(String packageName, PackageStateInternal packageState, 3188 int userId) { 3189 final PackageRemovedInfo info = new PackageRemovedInfo(this); 3190 info.mRemovedPackage = packageName; 3191 info.mInstallerPackageName = packageState.getInstallSource().mInstallerPackageName; 3192 info.mRemovedUsers = new int[] {userId}; 3193 info.mBroadcastUsers = new int[] {userId}; 3194 info.mUid = UserHandle.getUid(userId, packageState.getAppId()); 3195 info.mRemovedPackageVersionCode = packageState.getVersionCode(); 3196 info.sendPackageRemovedBroadcasts(true /*killApp*/, false /*removedBySystem*/); 3197 } 3198 3199 boolean isUserRestricted(int userId, String restrictionKey) { 3200 Bundle restrictions = mUserManager.getUserRestrictions(userId); 3201 if (restrictions.getBoolean(restrictionKey, false)) { 3202 Log.w(TAG, "User is restricted: " + restrictionKey); 3203 return true; 3204 } 3205 return false; 3206 } 3207 3208 private void enforceCanSetPackagesSuspendedAsUser(@NonNull Computer snapshot, 3209 String callingPackage, int callingUid, int userId, String callingMethod) { 3210 if (callingUid == Process.ROOT_UID 3211 // Need to compare app-id to allow system dialogs access on secondary users 3212 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 3213 return; 3214 } 3215 3216 final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId); 3217 if (ownerPackage != null) { 3218 final int ownerUid = snapshot.getPackageUid(ownerPackage, 0, userId); 3219 if (ownerUid == callingUid) { 3220 return; 3221 } 3222 } 3223 3224 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, 3225 callingMethod); 3226 3227 final int packageUid = snapshot.getPackageUid(callingPackage, 0, userId); 3228 final boolean allowedPackageUid = packageUid == callingUid; 3229 // TODO(b/139383163): remove special casing for shell and enforce INTERACT_ACROSS_USERS_FULL 3230 final boolean allowedShell = callingUid == SHELL_UID 3231 && UserHandle.isSameApp(packageUid, callingUid); 3232 3233 if (!allowedShell && !allowedPackageUid) { 3234 throw new SecurityException("Calling package " + callingPackage + " in user " 3235 + userId + " does not belong to calling uid " + callingUid); 3236 } 3237 } 3238 3239 void unsuspendForSuspendingPackage(@NonNull Computer computer, String suspendingPackage, 3240 @UserIdInt int userId) { 3241 // TODO: This can be replaced by a special parameter to iterate all packages, rather than 3242 // this weird pre-collect of all packages. 3243 final String[] allPackages = computer.getPackageStates().keySet().toArray(new String[0]); 3244 mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(computer, 3245 allPackages, suspendingPackage::equals, userId); 3246 } 3247 3248 void removeAllDistractingPackageRestrictions(@NonNull Computer snapshot, int userId) { 3249 final String[] allPackages = snapshot.getAllAvailablePackageNames(); 3250 mDistractingPackageHelper.removeDistractingPackageRestrictions(snapshot, allPackages, 3251 userId); 3252 } 3253 3254 private void enforceCanSetDistractingPackageRestrictionsAsUser(int callingUid, int userId, 3255 String callingMethod) { 3256 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 3257 callingMethod); 3258 3259 if (!PackageManagerServiceUtils.isSystemOrRoot(callingUid) 3260 && UserHandle.getUserId(callingUid) != userId) { 3261 throw new SecurityException("Calling uid " + callingUid + " cannot call for user " 3262 + userId); 3263 } 3264 } 3265 3266 void setEnableRollbackCode(int token, int enableRollbackCode) { 3267 final Message msg = mHandler.obtainMessage(ENABLE_ROLLBACK_STATUS); 3268 msg.arg1 = token; 3269 msg.arg2 = enableRollbackCode; 3270 mHandler.sendMessage(msg); 3271 } 3272 3273 /** 3274 * Callback from PackageSettings whenever an app is first transitioned out of the 3275 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 3276 * the app was "launched" for a restoreAtInstall operation. Therefore we check 3277 * here whether the app is the target of an ongoing install, and only send the 3278 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 3279 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 3280 * handling. 3281 */ 3282 void notifyFirstLaunch(final String packageName, final String installerPackage, 3283 final int userId) { 3284 // Serialize this with the rest of the install-process message chain. In the 3285 // restore-at-install case, this Runnable will necessarily run before the 3286 // POST_INSTALL message is processed, so the contents of mRunningInstalls 3287 // are coherent. In the non-restore case, the app has already completed install 3288 // and been launched through some other means, so it is not in a problematic 3289 // state for observers to see the FIRST_LAUNCH signal. 3290 mHandler.post(() -> { 3291 for (int i = 0; i < mRunningInstalls.size(); i++) { 3292 final InstallRequest installRequest = mRunningInstalls.valueAt(i); 3293 if (installRequest.getReturnCode() != PackageManager.INSTALL_SUCCEEDED) { 3294 continue; 3295 } 3296 if (packageName.equals(installRequest.getPkg().getPackageName())) { 3297 // right package; but is it for the right user? 3298 for (int uIndex = 0; uIndex < installRequest.getNewUsers().length; uIndex++) { 3299 if (userId == installRequest.getNewUsers()[uIndex]) { 3300 if (DEBUG_BACKUP) { 3301 Slog.i(TAG, "Package " + packageName 3302 + " being restored so deferring FIRST_LAUNCH"); 3303 } 3304 return; 3305 } 3306 } 3307 } 3308 } 3309 // didn't find it, so not being restored 3310 if (DEBUG_BACKUP) { 3311 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 3312 } 3313 final boolean isInstantApp = snapshotComputer().isInstantAppInternal( 3314 packageName, userId, Process.SYSTEM_UID); 3315 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 3316 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 3317 mBroadcastHelper.sendFirstLaunchBroadcast( 3318 packageName, installerPackage, userIds, instantUserIds); 3319 }); 3320 } 3321 3322 @SuppressWarnings("GuardedBy") 3323 VersionInfo getSettingsVersionForPackage(AndroidPackage pkg) { 3324 if (pkg.isExternalStorage()) { 3325 if (TextUtils.isEmpty(pkg.getVolumeUuid())) { 3326 return mSettings.getExternalVersion(); 3327 } else { 3328 return mSettings.findOrCreateVersion(pkg.getVolumeUuid()); 3329 } 3330 } else { 3331 return mSettings.getInternalVersion(); 3332 } 3333 } 3334 3335 public void deleteExistingPackageAsUser(VersionedPackage versionedPackage, 3336 final IPackageDeleteObserver2 observer, final int userId) { 3337 mDeletePackageHelper.deleteExistingPackageAsUser( 3338 versionedPackage, observer, userId); 3339 } 3340 3341 public void deletePackageVersioned(VersionedPackage versionedPackage, 3342 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 3343 mDeletePackageHelper.deletePackageVersionedInternal( 3344 versionedPackage, observer, userId, deleteFlags, false); 3345 } 3346 3347 boolean isCallerVerifier(@NonNull Computer snapshot, int callingUid) { 3348 final int callingUserId = UserHandle.getUserId(callingUid); 3349 for (String requiredVerifierPackage : mRequiredVerifierPackages) { 3350 if (callingUid == snapshot.getPackageUid(requiredVerifierPackage, 0, callingUserId)) { 3351 return true; 3352 } 3353 } 3354 return false; 3355 } 3356 3357 public boolean isPackageDeviceAdminOnAnyUser(@NonNull Computer snapshot, String packageName) { 3358 final int callingUid = Binder.getCallingUid(); 3359 if (snapshot.checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid) 3360 != PERMISSION_GRANTED) { 3361 EventLog.writeEvent(0x534e4554, "128599183", -1, ""); 3362 throw new SecurityException(android.Manifest.permission.MANAGE_USERS 3363 + " permission is required to call this API"); 3364 } 3365 if (snapshot.getInstantAppPackageName(callingUid) != null 3366 && !snapshot.isCallerSameApp(packageName, callingUid)) { 3367 return false; 3368 } 3369 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 3370 } 3371 3372 // TODO(b/261957226): centralise this logic in DPM 3373 boolean isPackageDeviceAdmin(String packageName, int userId) { 3374 final IDevicePolicyManager dpm = getDevicePolicyManager(); 3375 try { 3376 if (dpm != null) { 3377 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 3378 /* callingUserOnly =*/ false); 3379 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 3380 : deviceOwnerComponentName.getPackageName(); 3381 // Does the package contains the device owner? 3382 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 3383 // this check is probably not needed, since DO should be registered as a device 3384 // admin on some user too. (Original bug for this: b/17657954) 3385 if (packageName.equals(deviceOwnerPackageName)) { 3386 return true; 3387 } 3388 // Does it contain a device admin for any user? 3389 int[] users; 3390 if (userId == UserHandle.USER_ALL) { 3391 users = mUserManager.getUserIds(); 3392 } else { 3393 users = new int[]{userId}; 3394 } 3395 for (int i = 0; i < users.length; ++i) { 3396 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 3397 return true; 3398 } 3399 if (isDeviceManagementRoleHolder(packageName, users[i])) { 3400 return true; 3401 } 3402 } 3403 } 3404 } catch (RemoteException e) { 3405 } 3406 return false; 3407 } 3408 3409 private boolean isDeviceManagementRoleHolder(String packageName, int userId) { 3410 return Objects.equals(packageName, getDevicePolicyManagementRoleHolderPackageName(userId)); 3411 } 3412 3413 @Nullable 3414 public String getDevicePolicyManagementRoleHolderPackageName(int userId) { 3415 return Binder.withCleanCallingIdentity(() -> { 3416 RoleManager roleManager = mContext.getSystemService(RoleManager.class); 3417 List<String> roleHolders = 3418 roleManager.getRoleHoldersAsUser( 3419 RoleManager.ROLE_DEVICE_POLICY_MANAGEMENT, UserHandle.of(userId)); 3420 if (roleHolders.isEmpty()) { 3421 return null; 3422 } 3423 return roleHolders.get(0); 3424 }); 3425 } 3426 3427 /** Returns the device policy manager interface. */ 3428 private IDevicePolicyManager getDevicePolicyManager() { 3429 if (mDevicePolicyManager == null) { 3430 // No need to synchronize; worst-case scenario it will be fetched twice. 3431 mDevicePolicyManager = IDevicePolicyManager.Stub.asInterface( 3432 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 3433 } 3434 return mDevicePolicyManager; 3435 } 3436 3437 private boolean clearApplicationUserDataLIF(@NonNull Computer snapshot, String packageName, 3438 int userId) { 3439 if (packageName == null) { 3440 Slog.w(TAG, "Attempt to delete null packageName."); 3441 return false; 3442 } 3443 3444 // Try finding details about the requested package 3445 AndroidPackage pkg = snapshot.getPackage(packageName); 3446 if (pkg == null) { 3447 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 3448 return false; 3449 } 3450 mPermissionManager.resetRuntimePermissions(pkg, userId); 3451 3452 mAppDataHelper.clearAppDataLIF(pkg, userId, 3453 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 3454 3455 final int appId = UserHandle.getAppId(pkg.getUid()); 3456 mAppDataHelper.clearKeystoreData(userId, appId); 3457 3458 UserManagerInternal umInternal = mInjector.getUserManagerInternal(); 3459 StorageManagerInternal smInternal = mInjector.getLocalService(StorageManagerInternal.class); 3460 final int flags; 3461 if (StorageManager.isUserKeyUnlocked(userId) && smInternal.isCeStoragePrepared(userId)) { 3462 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3463 } else if (umInternal.isUserRunning(userId)) { 3464 flags = StorageManager.FLAG_STORAGE_DE; 3465 } else { 3466 flags = 0; 3467 } 3468 mAppDataHelper.prepareAppDataContentsLIF(pkg, snapshot.getPackageStateInternal(packageName), 3469 userId, flags); 3470 3471 return true; 3472 } 3473 3474 /** 3475 * Update component enabled settings to {@link PackageManager#COMPONENT_ENABLED_STATE_DEFAULT} 3476 * if the resetEnabledSettingsOnAppDataCleared is {@code true}. 3477 */ 3478 @GuardedBy("mLock") 3479 private void resetComponentEnabledSettingsIfNeededLPw(String packageName, int userId) { 3480 final AndroidPackage pkg = packageName != null ? mPackages.get(packageName) : null; 3481 if (pkg == null || !pkg.isResetEnabledSettingsOnAppDataCleared()) { 3482 return; 3483 } 3484 final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName); 3485 if (pkgSetting == null) { 3486 return; 3487 } 3488 final ArrayList<String> updatedComponents = new ArrayList<>(); 3489 final Consumer<? super ParsedMainComponent> resetSettings = (component) -> { 3490 if (pkgSetting.restoreComponentLPw(component.getClassName(), userId)) { 3491 updatedComponents.add(component.getClassName()); 3492 } 3493 }; 3494 for (int i = 0; i < pkg.getActivities().size(); i++) { 3495 resetSettings.accept(pkg.getActivities().get(i)); 3496 } 3497 for (int i = 0; i < pkg.getReceivers().size(); i++) { 3498 resetSettings.accept(pkg.getReceivers().get(i)); 3499 } 3500 for (int i = 0; i < pkg.getServices().size(); i++) { 3501 resetSettings.accept(pkg.getServices().get(i)); 3502 } 3503 for (int i = 0; i < pkg.getProviders().size(); i++) { 3504 resetSettings.accept(pkg.getProviders().get(i)); 3505 } 3506 if (ArrayUtils.isEmpty(updatedComponents)) { 3507 // nothing changed 3508 return; 3509 } 3510 3511 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 3512 updateInstantAppInstallerLocked(packageName); 3513 scheduleWritePackageRestrictions(userId); 3514 3515 mPendingBroadcasts.addComponents(userId, packageName, updatedComponents); 3516 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 3517 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 3518 } 3519 } 3520 3521 void postPreferredActivityChangedBroadcast(int userId) { 3522 mHandler.post(() -> mBroadcastHelper.sendPreferredActivityChangedBroadcast(userId)); 3523 } 3524 3525 3526 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 3527 @GuardedBy("mLock") 3528 void clearPackagePreferredActivitiesLPw(String packageName, 3529 @NonNull SparseBooleanArray outUserChanged, int userId) { 3530 mSettings.clearPackagePreferredActivities(packageName, outUserChanged, userId); 3531 } 3532 3533 void restorePermissionsAndUpdateRolesForNewUserInstall(String packageName, 3534 @UserIdInt int userId) { 3535 // We may also need to apply pending (restored) runtime permission grants 3536 // within these users. 3537 mPermissionManager.restoreDelayedRuntimePermissions(packageName, userId); 3538 3539 // Restore default browser setting if it is now installed. 3540 String defaultBrowser; 3541 synchronized (mLock) { 3542 defaultBrowser = mSettings.getPendingDefaultBrowserLPr(userId); 3543 } 3544 if (Objects.equals(packageName, defaultBrowser)) { 3545 mDefaultAppProvider.setDefaultBrowser(packageName, userId); 3546 synchronized (mLock) { 3547 mSettings.removePendingDefaultBrowserLPw(userId); 3548 } 3549 } 3550 3551 // Persistent preferred activity might have came into effect due to this 3552 // install. 3553 mPreferredActivityHelper.updateDefaultHomeNotLocked(snapshotComputer(), userId); 3554 } 3555 3556 /** 3557 * Variant that takes a {@link WatchedIntentFilter} 3558 */ 3559 public void addCrossProfileIntentFilter(@NonNull Computer snapshot, 3560 WatchedIntentFilter intentFilter, String ownerPackage, int sourceUserId, 3561 int targetUserId, int flags) { 3562 mContext.enforceCallingOrSelfPermission( 3563 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 3564 int callingUid = Binder.getCallingUid(); 3565 enforceOwnerRights(snapshot, ownerPackage, callingUid); 3566 3567 // Verifying that current calling uid should be able to add {@link CrossProfileIntentFilter} 3568 // for source and target user 3569 mUserManager.enforceCrossProfileIntentFilterAccess(sourceUserId, targetUserId, callingUid, 3570 /* addCrossProfileIntentFilter */ true); 3571 3572 PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(), 3573 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 3574 if (!intentFilter.checkDataPathAndSchemeSpecificParts()) { 3575 EventLog.writeEvent(0x534e4554, "246749936", callingUid); 3576 throw new IllegalArgumentException("Invalid intent data paths or scheme specific parts" 3577 + " in the filter."); 3578 } 3579 if (intentFilter.countActions() == 0) { 3580 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 3581 return; 3582 } 3583 synchronized (mLock) { 3584 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 3585 ownerPackage, targetUserId, flags, mUserManager 3586 .getCrossProfileIntentFilterAccessControl(sourceUserId, targetUserId)); 3587 CrossProfileIntentResolver resolver = 3588 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 3589 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 3590 // We have all those whose filter is equal. Now checking if the rest is equal as well. 3591 if (existing != null) { 3592 int size = existing.size(); 3593 for (int i = 0; i < size; i++) { 3594 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 3595 return; 3596 } 3597 } 3598 } 3599 resolver.addFilter(snapshotComputer(), newFilter); 3600 } 3601 scheduleWritePackageRestrictions(sourceUserId); 3602 } 3603 3604 3605 // Enforcing that callingUid is owning pkg on userId 3606 private void enforceOwnerRights(@NonNull Computer snapshot, String pkg, int callingUid) { 3607 // The system owns everything. 3608 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 3609 return; 3610 } 3611 final String[] callerPackageNames = snapshot.getPackagesForUid(callingUid); 3612 if (!ArrayUtils.contains(callerPackageNames, pkg)) { 3613 throw new SecurityException("Calling uid " + callingUid 3614 + " does not own package " + pkg); 3615 } 3616 final int callingUserId = UserHandle.getUserId(callingUid); 3617 PackageInfo pi = snapshot.getPackageInfo(pkg, 0, callingUserId); 3618 if (pi == null) { 3619 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 3620 + callingUserId); 3621 } 3622 } 3623 3624 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 3625 UserManagerService ums = UserManagerService.getInstance(); 3626 if (ums == null || sessionInfo.isStaged()) { 3627 return; 3628 } 3629 final UserInfo parent = ums.getProfileParent(userId); 3630 final int launcherUid = (parent != null) ? parent.id : userId; 3631 // TODO: Should this snapshot be moved further up? 3632 final ComponentName launcherComponent = snapshotComputer() 3633 .getDefaultHomeActivity(launcherUid); 3634 mBroadcastHelper.sendSessionCommitBroadcast(sessionInfo, userId, launcherUid, 3635 launcherComponent, mAppPredictionServicePackage); 3636 } 3637 3638 private @Nullable String getSetupWizardPackageNameImpl(@NonNull Computer computer) { 3639 final Intent intent = new Intent(Intent.ACTION_MAIN); 3640 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 3641 3642 final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null, 3643 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 3644 | MATCH_DISABLED_COMPONENTS, 3645 UserHandle.myUserId()); 3646 if (matches.size() == 1) { 3647 return matches.get(0).getComponentInfo().packageName; 3648 } else { 3649 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 3650 + ": matches=" + matches); 3651 return null; 3652 } 3653 } 3654 3655 private @Nullable String getStorageManagerPackageName(@NonNull Computer computer) { 3656 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 3657 3658 final List<ResolveInfo> matches = computer.queryIntentActivitiesInternal(intent, null, 3659 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 3660 | MATCH_DISABLED_COMPONENTS, 3661 UserHandle.myUserId()); 3662 if (matches.size() == 1) { 3663 return matches.get(0).getComponentInfo().packageName; 3664 } else { 3665 Slog.w(TAG, "There should probably be exactly one storage manager; found " 3666 + matches.size() + ": matches=" + matches); 3667 return null; 3668 } 3669 } 3670 3671 @NonNull 3672 private static String getRequiredSdkSandboxPackageName(@NonNull Computer computer) { 3673 final Intent intent = new Intent(SdkSandboxManagerLocal.SERVICE_INTERFACE); 3674 3675 final List<ResolveInfo> matches = computer.queryIntentServicesInternal( 3676 intent, 3677 /* resolvedType= */ null, 3678 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3679 UserHandle.USER_SYSTEM, 3680 /* callingUid= */ Process.myUid(), 3681 /* includeInstantApps= */ false); 3682 if (matches.size() == 1) { 3683 return matches.get(0).getComponentInfo().packageName; 3684 } else { 3685 throw new RuntimeException("There should exactly one sdk sandbox package; found " 3686 + matches.size() + ": matches=" + matches); 3687 } 3688 } 3689 3690 @Nullable 3691 private String getRetailDemoPackageName() { 3692 final String predefinedPkgName = mContext.getString(R.string.config_retailDemoPackage); 3693 final String predefinedSignature = mContext.getString( 3694 R.string.config_retailDemoPackageSignature); 3695 3696 if (TextUtils.isEmpty(predefinedPkgName) || TextUtils.isEmpty(predefinedSignature)) { 3697 return null; 3698 } 3699 3700 final AndroidPackage androidPkg = mPackages.get(predefinedPkgName); 3701 if (androidPkg != null) { 3702 final SigningDetails signingDetail = androidPkg.getSigningDetails(); 3703 if (signingDetail != null && signingDetail.getSignatures() != null) { 3704 try { 3705 final MessageDigest msgDigest = MessageDigest.getInstance("SHA-256"); 3706 for (Signature signature : signingDetail.getSignatures()) { 3707 if (TextUtils.equals(predefinedSignature, 3708 HexEncoding.encodeToString(msgDigest.digest( 3709 signature.toByteArray()), false))) { 3710 return predefinedPkgName; 3711 } 3712 } 3713 } catch (NoSuchAlgorithmException e) { 3714 Slog.e( 3715 TAG, 3716 "Unable to verify signatures as getting the retail demo package name", 3717 e); 3718 } 3719 } 3720 } 3721 3722 return null; 3723 } 3724 3725 @Nullable 3726 String getPackageFromComponentString(@StringRes int stringResId) { 3727 final String componentString = mContext.getString(stringResId); 3728 if (TextUtils.isEmpty(componentString)) { 3729 return null; 3730 } 3731 final ComponentName component = ComponentName.unflattenFromString(componentString); 3732 if (component == null) { 3733 return null; 3734 } 3735 return component.getPackageName(); 3736 } 3737 3738 @Nullable 3739 String ensureSystemPackageName(@NonNull Computer snapshot, 3740 @Nullable String packageName) { 3741 if (packageName == null) { 3742 return null; 3743 } 3744 final long token = Binder.clearCallingIdentity(); 3745 try { 3746 if (snapshot.getPackageInfo(packageName, MATCH_FACTORY_ONLY, 3747 UserHandle.USER_SYSTEM) == null) { 3748 PackageInfo packageInfo = 3749 snapshot.getPackageInfo(packageName, 0, UserHandle.USER_SYSTEM); 3750 if (packageInfo != null) { 3751 EventLog.writeEvent(0x534e4554, "145981139", packageInfo.applicationInfo.uid, 3752 ""); 3753 } 3754 Log.w(TAG, "Missing required system package: " + packageName + (packageInfo != null 3755 ? ", but found with extended search." : ".")); 3756 return null; 3757 } 3758 } finally { 3759 Binder.restoreCallingIdentity(token); 3760 } 3761 return packageName; 3762 } 3763 3764 @VisibleForTesting(visibility = Visibility.PRIVATE) 3765 public void updateComponentLabelIcon(/*@NonNull*/ ComponentName componentName, 3766 @Nullable String nonLocalizedLabel, @Nullable Integer icon, int userId) { 3767 if (componentName == null) { 3768 throw new IllegalArgumentException("Must specify a component"); 3769 } 3770 3771 int callingUid = Binder.getCallingUid(); 3772 String componentPkgName = componentName.getPackageName(); 3773 3774 Computer computer = snapshotComputer(); 3775 3776 int componentUid = computer.getPackageUid(componentPkgName, 0, userId); 3777 if (!UserHandle.isSameApp(callingUid, componentUid)) { 3778 throw new SecurityException("The calling UID (" + callingUid + ")" 3779 + " does not match the target UID"); 3780 } 3781 3782 String allowedCallerPkg = 3783 mContext.getString(R.string.config_overrideComponentUiPackage); 3784 if (TextUtils.isEmpty(allowedCallerPkg)) { 3785 throw new SecurityException( "There is no package defined as allowed to change a " 3786 + "component's label or icon"); 3787 } 3788 3789 int allowedCallerUid = computer.getPackageUid(allowedCallerPkg, 3790 PackageManager.MATCH_SYSTEM_ONLY, userId); 3791 if (allowedCallerUid == -1 || !UserHandle.isSameApp(callingUid, allowedCallerUid)) { 3792 throw new SecurityException("The calling UID (" + callingUid + ")" 3793 + " is not allowed to change a component's label or icon"); 3794 } 3795 PackageStateInternal packageState = computer.getPackageStateInternal(componentPkgName); 3796 if (packageState == null || packageState.getPkg() == null 3797 || (!packageState.isSystem() 3798 && !packageState.isUpdatedSystemApp())) { 3799 throw new SecurityException( 3800 "Changing the label is not allowed for " + componentName); 3801 } 3802 3803 if (!computer.getComponentResolver().componentExists(componentName)) { 3804 throw new IllegalArgumentException("Component " + componentName + " not found"); 3805 } 3806 3807 Pair<String, Integer> overrideLabelIcon = packageState.getUserStateOrDefault(userId) 3808 .getOverrideLabelIconForComponent(componentName); 3809 3810 String existingLabel = overrideLabelIcon == null ? null : overrideLabelIcon.first; 3811 Integer existingIcon = overrideLabelIcon == null ? null : overrideLabelIcon.second; 3812 3813 if (TextUtils.equals(existingLabel, nonLocalizedLabel) 3814 && Objects.equals(existingIcon, icon)) { 3815 // Nothing changed 3816 return; 3817 } 3818 3819 commitPackageStateMutation(null, componentPkgName, 3820 state -> state.userState(userId) 3821 .setComponentLabelIcon(componentName, nonLocalizedLabel, icon)); 3822 3823 mPendingBroadcasts.addComponent(userId, componentPkgName, componentName.getClassName()); 3824 3825 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 3826 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 3827 } 3828 } 3829 3830 private void setEnabledSettings(List<ComponentEnabledSetting> settings, int userId, 3831 @NonNull String callingPackage) { 3832 final int callingUid = Binder.getCallingUid(); 3833 // TODO: This method is not properly snapshotified beyond this call 3834 final Computer preLockSnapshot = snapshotComputer(); 3835 preLockSnapshot.enforceCrossUserPermission(callingUid, userId, 3836 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 3837 3838 final int targetSize = settings.size(); 3839 for (int i = 0; i < targetSize; i++) { 3840 final int newState = settings.get(i).getEnabledState(); 3841 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 3842 || newState == COMPONENT_ENABLED_STATE_ENABLED 3843 || newState == COMPONENT_ENABLED_STATE_DISABLED 3844 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 3845 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 3846 throw new IllegalArgumentException("Invalid new component state: " + newState); 3847 } 3848 } 3849 if (targetSize > 1) { 3850 final ArraySet<String> checkDuplicatedPackage = new ArraySet<>(); 3851 final ArraySet<ComponentName> checkDuplicatedComponent = new ArraySet<>(); 3852 final ArrayMap<String, Integer> checkConflictFlag = new ArrayMap<>(); 3853 for (int i = 0; i < targetSize; i++) { 3854 final ComponentEnabledSetting setting = settings.get(i); 3855 final String packageName = setting.getPackageName(); 3856 if (setting.isComponent()) { 3857 final ComponentName componentName = setting.getComponentName(); 3858 if (checkDuplicatedComponent.contains(componentName)) { 3859 throw new IllegalArgumentException("The component " + componentName 3860 + " is duplicated"); 3861 } 3862 checkDuplicatedComponent.add(componentName); 3863 3864 // check if there is a conflict of the DONT_KILL_APP flag between components 3865 // in the package 3866 final Integer enabledFlags = checkConflictFlag.get(packageName); 3867 if (enabledFlags == null) { 3868 checkConflictFlag.put(packageName, setting.getEnabledFlags()); 3869 } else if ((enabledFlags & PackageManager.DONT_KILL_APP) 3870 != (setting.getEnabledFlags() & PackageManager.DONT_KILL_APP)) { 3871 throw new IllegalArgumentException("A conflict of the DONT_KILL_APP flag " 3872 + "between components in the package " + packageName); 3873 } 3874 } else { 3875 if (checkDuplicatedPackage.contains(packageName)) { 3876 throw new IllegalArgumentException("The package " + packageName 3877 + " is duplicated"); 3878 } 3879 checkDuplicatedPackage.add(packageName); 3880 } 3881 } 3882 } 3883 3884 final boolean allowedByPermission = mContext.checkCallingOrSelfPermission( 3885 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE) == PERMISSION_GRANTED; 3886 final boolean[] updateAllowed = new boolean[targetSize]; 3887 Arrays.fill(updateAllowed, true); 3888 3889 final Map<String, PackageSetting> pkgSettings = new ArrayMap<>(targetSize); 3890 // reader 3891 synchronized (mLock) { 3892 final Computer snapshot = snapshotComputer(); 3893 // Checks for target packages 3894 for (int i = 0; i < targetSize; i++) { 3895 final ComponentEnabledSetting setting = settings.get(i); 3896 final String packageName = setting.getPackageName(); 3897 if (pkgSettings.containsKey(packageName)) { 3898 // this package has verified 3899 continue; 3900 } 3901 final boolean isCallerTargetApp = ArrayUtils.contains( 3902 snapshot.getPackagesForUid(callingUid), packageName); 3903 final PackageSetting pkgSetting = mSettings.getPackageLPr(packageName); 3904 // Limit who can change which apps 3905 if (!isCallerTargetApp && !allowedByPermission) { 3906 // Don't allow apps that don't have permission to modify other apps 3907 throw new SecurityException("Attempt to change component state; " 3908 + "pid=" + Binder.getCallingPid() 3909 + ", uid=" + callingUid 3910 + (!setting.isComponent() ? ", package=" + packageName 3911 : ", component=" + setting.getComponentName())); 3912 } 3913 if (pkgSetting == null || snapshot.shouldFilterApplicationIncludingUninstalled( 3914 pkgSetting, callingUid, userId)) { 3915 throw new IllegalArgumentException(setting.isComponent() 3916 ? "Unknown component: " + setting.getComponentName() 3917 : "Unknown package: " + packageName); 3918 } 3919 // Don't allow changing protected packages. 3920 if (!isCallerTargetApp 3921 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 3922 throw new SecurityException( 3923 "Cannot disable a protected package: " + packageName); 3924 } 3925 if (callingUid == Process.SHELL_UID 3926 && (pkgSetting.getFlags() & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 3927 // Shell can only change whole packages between ENABLED and DISABLED_USER states 3928 // unless it is a test package. 3929 final int oldState = pkgSetting.getEnabled(userId); 3930 final int newState = setting.getEnabledState(); 3931 if (!setting.isComponent() 3932 && 3933 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 3934 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 3935 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 3936 && 3937 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 3938 || newState == COMPONENT_ENABLED_STATE_DEFAULT 3939 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 3940 // ok 3941 } else { 3942 throw new SecurityException( 3943 "Shell cannot change component state for " 3944 + setting.getComponentName() + " to " + newState); 3945 } 3946 } 3947 pkgSettings.put(packageName, pkgSetting); 3948 } 3949 // Checks for target components 3950 for (int i = 0; i < targetSize; i++) { 3951 final ComponentEnabledSetting setting = settings.get(i); 3952 // skip if it's application 3953 if (!setting.isComponent()) continue; 3954 3955 // Only allow apps with CHANGE_COMPONENT_ENABLED_STATE permission to change hidden 3956 // app details activity 3957 final String packageName = setting.getPackageName(); 3958 final String className = setting.getClassName(); 3959 if (!allowedByPermission 3960 && PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME.equals(className)) { 3961 throw new SecurityException("Cannot disable a system-generated component"); 3962 } 3963 // Verify that this is a valid class name. 3964 final AndroidPackage pkg = pkgSettings.get(packageName).getPkg(); 3965 if (pkg == null || !AndroidPackageUtils.hasComponentClassName(pkg, className)) { 3966 if (pkg != null 3967 && pkg.getTargetSdkVersion() >= Build.VERSION_CODES.JELLY_BEAN) { 3968 throw new IllegalArgumentException("Component class " + className 3969 + " does not exist in " + packageName); 3970 } else { 3971 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 3972 + className + " does not exist in " + packageName); 3973 updateAllowed[i] = false; 3974 } 3975 } 3976 } 3977 } 3978 3979 // More work for application enabled setting updates 3980 for (int i = 0; i < targetSize; i++) { 3981 final ComponentEnabledSetting setting = settings.get(i); 3982 // skip if it's component 3983 if (setting.isComponent()) continue; 3984 3985 final PackageSetting pkgSetting = pkgSettings.get(setting.getPackageName()); 3986 final int newState = setting.getEnabledState(); 3987 synchronized (mLock) { 3988 if (pkgSetting.getEnabled(userId) == newState) { 3989 // Nothing to do 3990 updateAllowed[i] = false; 3991 continue; 3992 } 3993 } 3994 // If we're enabling a system stub, there's a little more work to do. 3995 // Prior to enabling the package, we need to decompress the APK(s) to the 3996 // data partition and then replace the version on the system partition. 3997 final AndroidPackage deletedPkg = pkgSetting.getPkg(); 3998 final boolean isSystemStub = (deletedPkg != null) 3999 && deletedPkg.isStub() 4000 && pkgSetting.isSystem(); 4001 if (isSystemStub 4002 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 4003 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 4004 if (!mInstallPackageHelper.enableCompressedPackage(deletedPkg, pkgSetting)) { 4005 Slog.w(TAG, "Failed setApplicationEnabledSetting: failed to enable " 4006 + "commpressed package " + setting.getPackageName()); 4007 updateAllowed[i] = false; 4008 } 4009 } 4010 } 4011 4012 // packageName -> list of components to send broadcasts now 4013 final ArrayMap<String, ArrayList<String>> sendNowBroadcasts = new ArrayMap<>(targetSize); 4014 synchronized (mLock) { 4015 Computer computer = snapshotComputer(); 4016 boolean scheduleBroadcastMessage = false; 4017 boolean isSynchronous = false; 4018 boolean anyChanged = false; 4019 4020 for (int i = 0; i < targetSize; i++) { 4021 if (!updateAllowed[i]) { 4022 continue; 4023 } 4024 // update enabled settings 4025 final ComponentEnabledSetting setting = settings.get(i); 4026 final String packageName = setting.getPackageName(); 4027 if (!setEnabledSettingInternalLocked(computer, pkgSettings.get(packageName), 4028 setting, userId, callingPackage)) { 4029 continue; 4030 } 4031 anyChanged = true; 4032 4033 if ((setting.getEnabledFlags() & PackageManager.SYNCHRONOUS) != 0) { 4034 isSynchronous = true; 4035 } 4036 // collect broadcast list for the package 4037 final String componentName = setting.isComponent() 4038 ? setting.getClassName() : packageName; 4039 if ((setting.getEnabledFlags() & PackageManager.DONT_KILL_APP) == 0) { 4040 ArrayList<String> componentList = sendNowBroadcasts.get(packageName); 4041 componentList = componentList == null ? new ArrayList<>() : componentList; 4042 if (!componentList.contains(componentName)) { 4043 componentList.add(componentName); 4044 } 4045 sendNowBroadcasts.put(packageName, componentList); 4046 // Purge entry from pending broadcast list if another one exists already 4047 // since we are sending one right away. 4048 mPendingBroadcasts.remove(userId, packageName); 4049 } else { 4050 mPendingBroadcasts.addComponent(userId, packageName, componentName); 4051 scheduleBroadcastMessage = true; 4052 } 4053 } 4054 if (!anyChanged) { 4055 // nothing changed, return immediately 4056 return; 4057 } 4058 4059 if (isSynchronous) { 4060 flushPackageRestrictionsAsUserInternalLocked(userId); 4061 } else { 4062 scheduleWritePackageRestrictions(userId); 4063 } 4064 if (scheduleBroadcastMessage) { 4065 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 4066 // Schedule a message - if it has been a "reasonably long time" since the 4067 // service started, send the broadcast with a delay of one second to avoid 4068 // delayed reactions from the receiver, else keep the default ten second delay 4069 // to avoid extreme thrashing on service startup. 4070 final long broadcastDelay = SystemClock.uptimeMillis() > mServiceStartWithDelay 4071 ? BROADCAST_DELAY 4072 : BROADCAST_DELAY_DURING_STARTUP; 4073 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, broadcastDelay); 4074 } 4075 } 4076 } 4077 4078 final long callingId = Binder.clearCallingIdentity(); 4079 try { 4080 final Computer newSnapshot = snapshotComputer(); 4081 for (int i = 0; i < sendNowBroadcasts.size(); i++) { 4082 final String packageName = sendNowBroadcasts.keyAt(i); 4083 final ArrayList<String> components = sendNowBroadcasts.valueAt(i); 4084 final int packageUid = UserHandle.getUid( 4085 userId, pkgSettings.get(packageName).getAppId()); 4086 sendPackageChangedBroadcast(newSnapshot, packageName, false /* dontKillApp */, 4087 components, packageUid, null /* reason */); 4088 } 4089 } finally { 4090 Binder.restoreCallingIdentity(callingId); 4091 } 4092 } 4093 4094 @GuardedBy("mLock") 4095 private boolean setEnabledSettingInternalLocked(@NonNull Computer computer, 4096 PackageSetting pkgSetting, ComponentEnabledSetting setting, @UserIdInt int userId, 4097 String callingPackage) { 4098 final int newState = setting.getEnabledState(); 4099 final String packageName = setting.getPackageName(); 4100 boolean success = false; 4101 if (!setting.isComponent()) { 4102 // We're dealing with an application/package level state change 4103 pkgSetting.setEnabled(newState, userId, callingPackage); 4104 if ((newState == COMPONENT_ENABLED_STATE_DISABLED_USER 4105 || newState == COMPONENT_ENABLED_STATE_DISABLED) 4106 && checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId) 4107 == PERMISSION_GRANTED) { 4108 // This app should not generally be allowed to get disabled by the UI, but 4109 // if it ever does, we don't want to end up with some of the user's apps 4110 // permanently suspended. 4111 unsuspendForSuspendingPackage(computer, packageName, userId); 4112 removeAllDistractingPackageRestrictions(computer, userId); 4113 } 4114 success = true; 4115 } else { 4116 // We're dealing with a component level state change 4117 final String className = setting.getClassName(); 4118 switch (newState) { 4119 case COMPONENT_ENABLED_STATE_ENABLED: 4120 success = pkgSetting.enableComponentLPw(className, userId); 4121 break; 4122 case COMPONENT_ENABLED_STATE_DISABLED: 4123 success = pkgSetting.disableComponentLPw(className, userId); 4124 break; 4125 case COMPONENT_ENABLED_STATE_DEFAULT: 4126 success = pkgSetting.restoreComponentLPw(className, userId); 4127 break; 4128 default: 4129 Slog.e(TAG, "Failed setComponentEnabledSetting: component " 4130 + packageName + "/" + className 4131 + " requested an invalid new component state: " + newState); 4132 break; 4133 } 4134 } 4135 if (!success) { 4136 return false; 4137 } 4138 4139 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 4140 final long callingId = Binder.clearCallingIdentity(); 4141 try { 4142 updateInstantAppInstallerLocked(packageName); 4143 } finally { 4144 Binder.restoreCallingIdentity(callingId); 4145 } 4146 4147 return true; 4148 } 4149 4150 @GuardedBy("mLock") 4151 private void flushPackageRestrictionsAsUserInternalLocked(int userId) { 4152 // NOTE: this invokes synchronous disk access, so callers using this 4153 // method should consider running on a background thread 4154 mSettings.writePackageRestrictionsLPr(userId); 4155 synchronized (mDirtyUsers) { 4156 mDirtyUsers.remove(userId); 4157 if (mDirtyUsers.isEmpty()) { 4158 mBackgroundHandler.removeMessages(WRITE_DIRTY_PACKAGE_RESTRICTIONS); 4159 } 4160 } 4161 } 4162 4163 void sendPackageChangedBroadcast(@NonNull Computer snapshot, String packageName, 4164 boolean dontKillApp, ArrayList<String> componentNames, int packageUid, String reason) { 4165 PackageStateInternal setting = snapshot.getPackageStateInternal(packageName, 4166 Process.SYSTEM_UID); 4167 if (setting == null) { 4168 return; 4169 } 4170 final int userId = UserHandle.getUserId(packageUid); 4171 final boolean isInstantApp = 4172 snapshot.isInstantAppInternal(packageName, userId, Process.SYSTEM_UID); 4173 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 4174 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 4175 final SparseArray<int[]> broadcastAllowList = 4176 isInstantApp ? null : snapshot.getVisibilityAllowLists(packageName, userIds); 4177 mHandler.post(() -> mBroadcastHelper.sendPackageChangedBroadcast( 4178 packageName, dontKillApp, componentNames, packageUid, reason, userIds, 4179 instantUserIds, broadcastAllowList)); 4180 } 4181 4182 /** 4183 * Used by SystemServer 4184 */ 4185 public void waitForAppDataPrepared() { 4186 if (mPrepareAppDataFuture == null) { 4187 return; 4188 } 4189 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 4190 mPrepareAppDataFuture = null; 4191 } 4192 4193 public void systemReady() { 4194 PackageManagerServiceUtils.enforceSystemOrRoot( 4195 "Only the system can claim the system is ready"); 4196 4197 final ContentResolver resolver = mContext.getContentResolver(); 4198 if (mReleaseOnSystemReady != null) { 4199 for (int i = mReleaseOnSystemReady.size() - 1; i >= 0; --i) { 4200 final File dstCodePath = mReleaseOnSystemReady.get(i); 4201 F2fsUtils.releaseCompressedBlocks(resolver, dstCodePath); 4202 } 4203 mReleaseOnSystemReady = null; 4204 } 4205 mSystemReady = true; 4206 ContentObserver co = new ContentObserver(mHandler) { 4207 @Override 4208 public void onChange(boolean selfChange) { 4209 final boolean ephemeralFeatureDisabled = 4210 Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0; 4211 for (int userId : UserManagerService.getInstance().getUserIds()) { 4212 final boolean instantAppsDisabledForUser = 4213 ephemeralFeatureDisabled || Secure.getIntForUser(resolver, 4214 Secure.INSTANT_APPS_ENABLED, 1, userId) == 0; 4215 mWebInstantAppsDisabled.put(userId, instantAppsDisabledForUser); 4216 } 4217 } 4218 }; 4219 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 4220 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 4221 false, co, UserHandle.USER_ALL); 4222 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 4223 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_ALL); 4224 co.onChange(true); 4225 4226 mAppsFilter.onSystemReady(LocalServices.getService(PackageManagerInternal.class)); 4227 4228 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 4229 // disabled after already being started. 4230 CarrierAppUtils.disableCarrierAppsUntilPrivileged( 4231 mContext.getOpPackageName(), UserHandle.USER_SYSTEM, mContext); 4232 4233 disableSkuSpecificApps(); 4234 4235 // Read the compatibilty setting when the system is ready. 4236 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 4237 mContext.getContentResolver(), 4238 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 4239 ParsingPackageUtils.setCompatibilityModeEnabled(compatibilityModeEnabled); 4240 4241 if (DEBUG_SETTINGS) { 4242 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 4243 } 4244 4245 synchronized (mLock) { 4246 ArrayList<Integer> changed = mSettings.systemReady(mComponentResolver); 4247 for (int i = 0; i < changed.size(); i++) { 4248 mSettings.writePackageRestrictionsLPr(changed.get(i)); 4249 } 4250 } 4251 4252 mUserManager.systemReady(); 4253 4254 // Watch for external volumes that come and go over time 4255 final StorageManager storage = mInjector.getSystemService(StorageManager.class); 4256 storage.registerListener(mStorageEventHelper); 4257 4258 mInstallerService.systemReady(); 4259 mPackageDexOptimizer.systemReady(); 4260 4261 // Now that we're mostly running, clean up stale users and apps 4262 mUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 4263 mStorageEventHelper.reconcileApps(snapshotComputer(), StorageManager.UUID_PRIVATE_INTERNAL); 4264 4265 mPermissionManager.onSystemReady(); 4266 4267 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 4268 final List<UserInfo> livingUsers = mInjector.getUserManagerInternal().getUsers( 4269 /* excludePartial= */ true, 4270 /* excludeDying= */ true, 4271 /* excludePreCreated= */ false); 4272 final int livingUserCount = livingUsers.size(); 4273 for (int i = 0; i < livingUserCount; i++) { 4274 final int userId = livingUsers.get(i).id; 4275 if (mSettings.isPermissionUpgradeNeeded(userId)) { 4276 grantPermissionsUserIds = ArrayUtils.appendInt( 4277 grantPermissionsUserIds, userId); 4278 } 4279 } 4280 // If we upgraded grant all default permissions before kicking off. 4281 for (int userId : grantPermissionsUserIds) { 4282 mLegacyPermissionManager.grantDefaultPermissions(userId); 4283 } 4284 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 4285 // If we did not grant default permissions, we preload from this the 4286 // default permission exceptions lazily to ensure we don't hit the 4287 // disk on a new user creation. 4288 mLegacyPermissionManager.scheduleReadDefaultPermissionExceptions(); 4289 } 4290 4291 if (mInstantAppResolverConnection != null) { 4292 mContext.registerReceiver(new BroadcastReceiver() { 4293 @Override 4294 public void onReceive(Context context, Intent intent) { 4295 mInstantAppResolverConnection.optimisticBind(); 4296 mContext.unregisterReceiver(this); 4297 } 4298 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 4299 } 4300 4301 IntentFilter overlayFilter = new IntentFilter(Intent.ACTION_OVERLAY_CHANGED); 4302 overlayFilter.addDataScheme("package"); 4303 mContext.registerReceiver(new BroadcastReceiver() { 4304 @Override 4305 public void onReceive(Context context, Intent intent) { 4306 if (intent == null) { 4307 return; 4308 } 4309 Uri data = intent.getData(); 4310 if (data == null) { 4311 return; 4312 } 4313 String packageName = data.getSchemeSpecificPart(); 4314 if (packageName == null) { 4315 return; 4316 } 4317 final Computer snapshot = snapshotComputer(); 4318 AndroidPackage pkg = snapshot.getPackage(packageName); 4319 if (pkg == null) { 4320 return; 4321 } 4322 sendPackageChangedBroadcast(snapshot, pkg.getPackageName(), 4323 true /* dontKillApp */, 4324 new ArrayList<>(Collections.singletonList(pkg.getPackageName())), 4325 pkg.getUid(), 4326 Intent.ACTION_OVERLAY_CHANGED); 4327 } 4328 }, overlayFilter); 4329 4330 mModuleInfoProvider.systemReady(); 4331 4332 // Installer service might attempt to install some packages that have been staged for 4333 // installation on reboot. Make sure this is the last component to be call since the 4334 // installation might require other components to be ready. 4335 mInstallerService.restoreAndApplyStagedSessionIfNeeded(); 4336 4337 mExistingPackages = null; 4338 4339 // Clear cache on flags changes. 4340 DeviceConfig.addOnPropertiesChangedListener( 4341 NAMESPACE_PACKAGE_MANAGER_SERVICE, mInjector.getBackgroundExecutor(), 4342 properties -> { 4343 final Set<String> keyset = properties.getKeyset(); 4344 if (keyset.contains(PROPERTY_INCFS_DEFAULT_TIMEOUTS) || keyset.contains( 4345 PROPERTY_KNOWN_DIGESTERS_LIST)) { 4346 mPerUidReadTimeoutsCache = null; 4347 } 4348 }); 4349 4350 if (!useArtService()) { 4351 // The background dexopt job is scheduled in DexOptHelper.initializeArtManagerLocal when 4352 // ART Service is in use. 4353 try { 4354 mBackgroundDexOptService.systemReady(); 4355 } catch (LegacyDexoptDisabledException e) { 4356 throw new RuntimeException(e); 4357 } 4358 } 4359 4360 // Prune unused static shared libraries which have been cached a period of time 4361 schedulePruneUnusedStaticSharedLibraries(false /* delay */); 4362 4363 DexUseManagerLocal dexUseManager = DexOptHelper.getDexUseManagerLocal(); 4364 if (dexUseManager != null) { 4365 dexUseManager.systemReady(); 4366 } 4367 } 4368 4369 //TODO: b/111402650 4370 private void disableSkuSpecificApps() { 4371 String[] apkList = mContext.getResources().getStringArray( 4372 R.array.config_disableApksUnlessMatchedSku_apk_list); 4373 String[] skuArray = mContext.getResources().getStringArray( 4374 R.array.config_disableApkUnlessMatchedSku_skus_list); 4375 if (ArrayUtils.isEmpty(apkList)) { 4376 return; 4377 } 4378 String sku = SystemProperties.get("ro.boot.hardware.sku"); 4379 if (!TextUtils.isEmpty(sku) && ArrayUtils.contains(skuArray, sku)) { 4380 return; 4381 } 4382 final Computer snapshot = snapshotComputer(); 4383 for (String packageName : apkList) { 4384 setSystemAppHiddenUntilInstalled(snapshot, packageName, true); 4385 for (UserInfo user : mInjector.getUserManagerInternal().getUsers(false)) { 4386 setSystemAppInstallState(snapshot, packageName, false, user.id); 4387 } 4388 } 4389 } 4390 4391 public PackageFreezer freezePackage(String packageName, int userId, String killReason, 4392 int exitInfoReason) { 4393 return new PackageFreezer(packageName, userId, killReason, this, exitInfoReason); 4394 } 4395 4396 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 4397 String killReason, int exitInfoReason) { 4398 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 4399 return new PackageFreezer(this); 4400 } else { 4401 return freezePackage(packageName, userId, killReason, exitInfoReason); 4402 } 4403 } 4404 4405 /** Called by UserManagerService */ 4406 void cleanUpUser(UserManagerService userManager, @UserIdInt int userId) { 4407 synchronized (mLock) { 4408 synchronized (mDirtyUsers) { 4409 mDirtyUsers.remove(userId); 4410 } 4411 mUserNeedsBadging.delete(userId); 4412 mPermissionManager.onUserRemoved(userId); 4413 mSettings.removeUserLPw(userId); 4414 mPendingBroadcasts.remove(userId); 4415 mDeletePackageHelper.removeUnusedPackagesLPw(userManager, userId); 4416 mAppsFilter.onUserDeleted(snapshotComputer(), userId); 4417 } 4418 mInstantAppRegistry.onUserRemoved(userId); 4419 } 4420 4421 /** 4422 * Called by UserManagerService. 4423 * 4424 * @param userTypeInstallablePackages system packages that should be initially installed for 4425 * this type of user, or {@code null} if all system packages 4426 * should be installed 4427 * @param disallowedPackages packages that should not be initially installed. Takes precedence 4428 * over installablePackages. 4429 */ 4430 void createNewUser(int userId, @Nullable Set<String> userTypeInstallablePackages, 4431 String[] disallowedPackages) { 4432 synchronized (mInstallLock) { 4433 mSettings.createNewUserLI(this, mInstaller, userId, 4434 userTypeInstallablePackages, disallowedPackages); 4435 } 4436 synchronized (mLock) { 4437 scheduleWritePackageRestrictions(userId); 4438 scheduleWritePackageListLocked(userId); 4439 mAppsFilter.onUserCreated(snapshotComputer(), userId); 4440 } 4441 } 4442 4443 void onNewUserCreated(@UserIdInt int userId, boolean convertedFromPreCreated) { 4444 if (DEBUG_PERMISSIONS) { 4445 Slog.d(TAG, "onNewUserCreated(id=" + userId 4446 + ", convertedFromPreCreated=" + convertedFromPreCreated + ")"); 4447 } 4448 if (!convertedFromPreCreated || !readPermissionStateForUser(userId)) { 4449 mPermissionManager.onUserCreated(userId); 4450 mLegacyPermissionManager.grantDefaultPermissions(userId); 4451 mDomainVerificationManager.clearUser(userId); 4452 } 4453 } 4454 4455 private boolean readPermissionStateForUser(@UserIdInt int userId) { 4456 synchronized (mLock) { 4457 mPermissionManager.writeLegacyPermissionStateTEMP(); 4458 mSettings.readPermissionStateForUserSyncLPr(userId); 4459 mPermissionManager.readLegacyPermissionStateTEMP(); 4460 return mSettings.isPermissionUpgradeNeeded(userId); 4461 } 4462 } 4463 4464 public boolean isStorageLow() { 4465 // allow instant applications 4466 final long token = Binder.clearCallingIdentity(); 4467 try { 4468 final DeviceStorageMonitorInternal 4469 dsm = mInjector.getLocalService(DeviceStorageMonitorInternal.class); 4470 if (dsm != null) { 4471 return dsm.isMemoryLow(); 4472 } else { 4473 return false; 4474 } 4475 } finally { 4476 Binder.restoreCallingIdentity(token); 4477 } 4478 } 4479 4480 private void deletePackageIfUnused(@NonNull Computer snapshot, final String packageName) { 4481 PackageStateInternal ps = snapshot.getPackageStateInternal(packageName); 4482 if (ps == null) { 4483 return; 4484 } 4485 final SparseArray<? extends PackageUserStateInternal> userStates = ps.getUserStates(); 4486 for (int index = 0; index < userStates.size(); index++) { 4487 if (userStates.valueAt(index).isInstalled()) { 4488 return; 4489 } 4490 } 4491 // TODO Implement atomic delete if package is unused 4492 // It is currently possible that the package will be deleted even if it is installed 4493 // after this method returns. 4494 mHandler.post(() -> mDeletePackageHelper.deletePackageX( 4495 packageName, PackageManager.VERSION_CODE_HIGHEST, 4496 0, PackageManager.DELETE_ALL_USERS, true /*removedBySystem*/)); 4497 } 4498 4499 void deletePreloadsFileCache() { 4500 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CLEAR_APP_CACHE, 4501 "deletePreloadsFileCache"); 4502 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4503 Slog.i(PackageManagerService.TAG, "Deleting preloaded file cache " + dir); 4504 FileUtils.deleteContents(dir); 4505 } 4506 4507 void setSystemAppHiddenUntilInstalled(@NonNull Computer snapshot, String packageName, 4508 boolean hidden) { 4509 final int callingUid = Binder.getCallingUid(); 4510 final boolean calledFromSystemOrPhone = callingUid == Process.PHONE_UID 4511 || callingUid == Process.SYSTEM_UID; 4512 if (!calledFromSystemOrPhone) { 4513 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 4514 "setSystemAppHiddenUntilInstalled"); 4515 } 4516 4517 final PackageStateInternal stateRead = snapshot.getPackageStateInternal(packageName); 4518 if (stateRead == null || !stateRead.isSystem() || stateRead.getPkg() == null) { 4519 return; 4520 } 4521 if (stateRead.getPkg().isCoreApp() && !calledFromSystemOrPhone) { 4522 throw new SecurityException("Only system or phone callers can modify core apps"); 4523 } 4524 4525 commitPackageStateMutation(null, mutator -> { 4526 mutator.forPackage(packageName) 4527 .setHiddenUntilInstalled(hidden); 4528 mutator.forDisabledSystemPackage(packageName) 4529 .setHiddenUntilInstalled(hidden); 4530 }); 4531 } 4532 4533 boolean setSystemAppInstallState(@NonNull Computer snapshot, String packageName, 4534 boolean installed, int userId) { 4535 final int callingUid = Binder.getCallingUid(); 4536 final boolean calledFromSystemOrPhone = callingUid == Process.PHONE_UID 4537 || callingUid == Process.SYSTEM_UID; 4538 if (!calledFromSystemOrPhone) { 4539 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 4540 "setSystemAppHiddenUntilInstalled"); 4541 } 4542 4543 final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 4544 // The target app should always be in system 4545 if (packageState == null || !packageState.isSystem() || packageState.getPkg() == null) { 4546 return false; 4547 } 4548 if (packageState.getPkg().isCoreApp() && !calledFromSystemOrPhone) { 4549 throw new SecurityException("Only system or phone callers can modify core apps"); 4550 } 4551 // Check if the install state is the same 4552 if (packageState.getUserStateOrDefault(userId).isInstalled() == installed) { 4553 return false; 4554 } 4555 4556 final long callingId = Binder.clearCallingIdentity(); 4557 try { 4558 if (installed) { 4559 // install the app from uninstalled state 4560 mInstallPackageHelper.installExistingPackageAsUser( 4561 packageName, 4562 userId, 4563 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 4564 PackageManager.INSTALL_REASON_DEVICE_SETUP, 4565 null, 4566 null); 4567 return true; 4568 } 4569 4570 // uninstall the app from installed state 4571 deletePackageVersioned( 4572 new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST), 4573 new PackageManager.LegacyPackageDeleteObserver(null).getBinder(), 4574 userId, 4575 PackageManager.DELETE_SYSTEM_APP); 4576 return true; 4577 } finally { 4578 Binder.restoreCallingIdentity(callingId); 4579 } 4580 } 4581 4582 void finishPackageInstall(int token, boolean didLaunch) { 4583 PackageManagerServiceUtils.enforceSystemOrRoot( 4584 "Only the system is allowed to finish installs"); 4585 4586 if (PackageManagerService.DEBUG_INSTALL) { 4587 Slog.v(PackageManagerService.TAG, "BM finishing package install for " + token); 4588 } 4589 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 4590 4591 final Message msg = mHandler.obtainMessage(PackageManagerService.POST_INSTALL, token, 4592 didLaunch ? 1 : 0); 4593 mHandler.sendMessage(msg); 4594 } 4595 4596 void checkPackageStartable(@NonNull Computer snapshot, @NonNull String packageName, 4597 @UserIdInt int userId) { 4598 final int callingUid = Binder.getCallingUid(); 4599 if (snapshot.getInstantAppPackageName(callingUid) != null) { 4600 throw new SecurityException("Instant applications don't have access to this method"); 4601 } 4602 if (!mUserManager.exists(userId)) { 4603 throw new SecurityException("User doesn't exist"); 4604 } 4605 snapshot.enforceCrossUserPermission(callingUid, userId, false, false, 4606 "checkPackageStartable"); 4607 switch (snapshot.getPackageStartability(mSafeMode, packageName, callingUid, userId)) { 4608 case PACKAGE_STARTABILITY_NOT_FOUND: 4609 throw new SecurityException("Package " + packageName + " was not found!"); 4610 case PACKAGE_STARTABILITY_NOT_SYSTEM: 4611 throw new SecurityException("Package " + packageName + " not a system app!"); 4612 case PACKAGE_STARTABILITY_FROZEN: 4613 throw new SecurityException("Package " + packageName + " is currently frozen!"); 4614 case PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED: 4615 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 4616 case PACKAGE_STARTABILITY_OK: 4617 default: 4618 } 4619 } 4620 4621 void setPackageStoppedState(@NonNull Computer snapshot, @NonNull String packageName, 4622 boolean stopped, @UserIdInt int userId) { 4623 if (!mUserManager.exists(userId)) return; 4624 final int callingUid = Binder.getCallingUid(); 4625 if (snapshot.getInstantAppPackageName(callingUid) == null) { 4626 final int permission = mContext.checkCallingOrSelfPermission( 4627 Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 4628 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 4629 if (!allowedByPermission 4630 && !ArrayUtils.contains(snapshot.getPackagesForUid(callingUid), packageName)) { 4631 throw new SecurityException( 4632 "Permission Denial: attempt to change stopped state from pid=" 4633 + Binder.getCallingPid() 4634 + ", uid=" + callingUid + ", package=" + packageName); 4635 } 4636 snapshot.enforceCrossUserPermission(callingUid, userId, 4637 true /* requireFullPermission */, true /* checkShell */, "stop package"); 4638 4639 final PackageStateInternal packageState = 4640 snapshot.getPackageStateForInstalledAndFiltered( 4641 packageName, callingUid, userId); 4642 final PackageUserState packageUserState = packageState == null 4643 ? null : packageState.getUserStateOrDefault(userId); 4644 if (packageState != null && packageUserState.isStopped() != stopped) { 4645 boolean wasNotLaunched = packageUserState.isNotLaunched(); 4646 commitPackageStateMutation(null, packageName, state -> { 4647 PackageUserStateWrite userState = state.userState(userId); 4648 userState.setStopped(stopped); 4649 if (wasNotLaunched) { 4650 userState.setNotLaunched(false); 4651 } 4652 }); 4653 4654 if (wasNotLaunched) { 4655 final String installerPackageName = 4656 packageState.getInstallSource().mInstallerPackageName; 4657 if (installerPackageName != null) { 4658 notifyFirstLaunch(packageName, installerPackageName, userId); 4659 } 4660 } 4661 4662 scheduleWritePackageRestrictions(userId); 4663 } 4664 } 4665 4666 // If this would cause the app to leave force-stop, then also make sure to unhibernate the 4667 // app if needed. 4668 if (!stopped) { 4669 mHandler.post(() -> { 4670 AppHibernationManagerInternal ah = 4671 mInjector.getLocalService(AppHibernationManagerInternal.class); 4672 if (ah != null && ah.isHibernatingForUser(packageName, userId)) { 4673 ah.setHibernatingForUser(packageName, userId, false); 4674 ah.setHibernatingGlobally(packageName, false); 4675 } 4676 }); 4677 } 4678 } 4679 4680 public class IPackageManagerImpl extends IPackageManagerBase { 4681 4682 public IPackageManagerImpl() { 4683 super(PackageManagerService.this, mContext, mDexOptHelper, mModuleInfoProvider, 4684 mPreferredActivityHelper, mResolveIntentHelper, mDomainVerificationManager, 4685 mDomainVerificationConnection, mInstallerService, mPackageProperty, 4686 mResolveComponentName, mInstantAppResolverSettingsComponent, 4687 mRequiredSdkSandboxPackage, mServicesExtensionPackageName, 4688 mSharedSystemSharedLibraryPackageName); 4689 } 4690 4691 @Override 4692 public void checkPackageStartable(String packageName, int userId) { 4693 PackageManagerService.this 4694 .checkPackageStartable(snapshotComputer(), packageName, userId); 4695 } 4696 4697 @Override 4698 public void clearApplicationProfileData(String packageName) { 4699 PackageManagerServiceUtils.enforceSystemOrRootOrShell( 4700 "Only the system or shell can clear all profile data"); 4701 4702 final Computer snapshot = snapshotComputer(); 4703 final AndroidPackage pkg = snapshot.getPackage(packageName); 4704 try (PackageFreezer ignored = 4705 freezePackage(packageName, UserHandle.USER_ALL, 4706 "clearApplicationProfileData", 4707 ApplicationExitInfo.REASON_OTHER)) { 4708 synchronized (mInstallLock) { 4709 mAppDataHelper.clearAppProfilesLIF(pkg); 4710 } 4711 } 4712 } 4713 4714 @Override 4715 public void clearApplicationUserData(final String packageName, 4716 final IPackageDataObserver observer, final int userId) { 4717 mContext.enforceCallingOrSelfPermission( 4718 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 4719 4720 final int callingUid = Binder.getCallingUid(); 4721 final Computer snapshot = snapshotComputer(); 4722 snapshot.enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 4723 false /* checkShell */, "clear application data"); 4724 4725 if (snapshot.getPackageStateForInstalledAndFiltered( 4726 packageName, callingUid, userId) == null) { 4727 if (observer != null) { 4728 mHandler.post(() -> { 4729 try { 4730 observer.onRemoveCompleted(packageName, false); 4731 } catch (RemoteException e) { 4732 Log.i(TAG, "Observer no longer exists."); 4733 } 4734 }); 4735 } 4736 return; 4737 } 4738 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 4739 throw new SecurityException("Cannot clear data for a protected package: " 4740 + packageName); 4741 } 4742 4743 // Queue up an async operation since the package deletion may take a little while. 4744 mHandler.post(new Runnable() { 4745 public void run() { 4746 mHandler.removeCallbacks(this); 4747 final boolean succeeded; 4748 try (PackageFreezer freezer = freezePackage(packageName, UserHandle.USER_ALL, 4749 "clearApplicationUserData", 4750 ApplicationExitInfo.REASON_USER_REQUESTED)) { 4751 synchronized (mInstallLock) { 4752 succeeded = clearApplicationUserDataLIF(snapshotComputer(), packageName, 4753 userId); 4754 } 4755 mInstantAppRegistry.deleteInstantApplicationMetadata(packageName, userId); 4756 synchronized (mLock) { 4757 if (succeeded) { 4758 resetComponentEnabledSettingsIfNeededLPw(packageName, userId); 4759 } 4760 } 4761 } 4762 if (succeeded) { 4763 // invoke DeviceStorageMonitor's update method to clear any notifications 4764 DeviceStorageMonitorInternal dsm = LocalServices 4765 .getService(DeviceStorageMonitorInternal.class); 4766 if (dsm != null) { 4767 dsm.checkMemory(); 4768 } 4769 if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId) 4770 == PERMISSION_GRANTED) { 4771 final Computer snapshot = snapshotComputer(); 4772 unsuspendForSuspendingPackage(snapshot, packageName, userId); 4773 removeAllDistractingPackageRestrictions(snapshot, userId); 4774 synchronized (mLock) { 4775 flushPackageRestrictionsAsUserInternalLocked(userId); 4776 } 4777 } 4778 } 4779 if (observer != null) { 4780 try { 4781 observer.onRemoveCompleted(packageName, succeeded); 4782 } catch (RemoteException e) { 4783 Log.i(TAG, "Observer no longer exists."); 4784 } 4785 } //end if observer 4786 } //end run 4787 }); 4788 } 4789 4790 @Override 4791 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 4792 mContext.enforceCallingOrSelfPermission( 4793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4794 final int callingUid = Binder.getCallingUid(); 4795 final Computer snapshot = snapshotComputer(); 4796 enforceOwnerRights(snapshot, ownerPackage, callingUid); 4797 PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(), 4798 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 4799 PackageManagerService.this.mInjector.getCrossProfileIntentFilterHelper() 4800 .clearCrossProfileIntentFilters(sourceUserId, ownerPackage, 4801 null); 4802 scheduleWritePackageRestrictions(sourceUserId); 4803 } 4804 4805 @Override 4806 public boolean removeCrossProfileIntentFilter(IntentFilter intentFilter, 4807 String ownerPackage, 4808 int sourceUserId, 4809 int targetUserId, int flags) { 4810 mContext.enforceCallingOrSelfPermission( 4811 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 4812 final int callingUid = Binder.getCallingUid(); 4813 enforceOwnerRights(snapshotComputer(), ownerPackage, callingUid); 4814 mUserManager.enforceCrossProfileIntentFilterAccess(sourceUserId, targetUserId, 4815 callingUid, /* addCrossProfileIntentFilter */ false); 4816 PackageManagerServiceUtils.enforceShellRestriction(mInjector.getUserManagerInternal(), 4817 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 4818 4819 boolean removedMatchingFilter = false; 4820 synchronized (mLock) { 4821 CrossProfileIntentResolver resolver = 4822 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 4823 4824 ArraySet<CrossProfileIntentFilter> set = 4825 new ArraySet<>(resolver.filterSet()); 4826 for (CrossProfileIntentFilter filter : set) { 4827 if (IntentFilter.filterEquals(filter.mFilter, intentFilter) 4828 && filter.getOwnerPackage().equals(ownerPackage) 4829 && filter.getTargetUserId() == targetUserId 4830 && filter.getFlags() == flags) { 4831 resolver.removeFilter(filter); 4832 removedMatchingFilter = true; 4833 break; 4834 } 4835 } 4836 } 4837 if (removedMatchingFilter) { 4838 scheduleWritePackageRestrictions(sourceUserId); 4839 } 4840 return removedMatchingFilter; 4841 } 4842 4843 @Override 4844 public final void deleteApplicationCacheFiles(final String packageName, 4845 final IPackageDataObserver observer) { 4846 final int userId = UserHandle.getCallingUserId(); 4847 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 4848 } 4849 4850 @Override 4851 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 4852 final IPackageDataObserver observer) { 4853 final int callingUid = Binder.getCallingUid(); 4854 if (mContext.checkCallingOrSelfPermission( 4855 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 4856 != PackageManager.PERMISSION_GRANTED) { 4857 // If the caller has the old delete cache permission, silently ignore. Else throw. 4858 if (mContext.checkCallingOrSelfPermission( 4859 android.Manifest.permission.DELETE_CACHE_FILES) 4860 == PackageManager.PERMISSION_GRANTED) { 4861 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 4862 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 4863 ", silently ignoring"); 4864 return; 4865 } 4866 mContext.enforceCallingOrSelfPermission( 4867 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 4868 } 4869 final Computer snapshot = snapshotComputer(); 4870 snapshot.enforceCrossUserPermission(callingUid, userId, /* requireFullPermission= */ true, 4871 /* checkShell= */ false, "delete application cache files"); 4872 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 4873 android.Manifest.permission.ACCESS_INSTANT_APPS); 4874 4875 // Queue up an async operation since the package deletion may take a little while. 4876 mHandler.post(() -> { 4877 // Snapshot in the Handler Runnable since this may be deferred quite a bit 4878 // TODO: Is this and the later mInstallLock re-snapshot necessary? 4879 final Computer newSnapshot = snapshotComputer(); 4880 final PackageStateInternal ps = newSnapshot.getPackageStateInternal(packageName); 4881 boolean doClearData = true; 4882 if (ps != null) { 4883 final boolean targetIsInstantApp = 4884 ps.getUserStateOrDefault(UserHandle.getUserId(callingUid)).isInstantApp(); 4885 doClearData = !targetIsInstantApp 4886 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 4887 } 4888 if (doClearData) { 4889 synchronized (mInstallLock) { 4890 final int flags = FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL; 4891 // Snapshot again after mInstallLock? 4892 final AndroidPackage pkg = snapshotComputer().getPackage(packageName); 4893 // We're only clearing cache files, so we don't care if the 4894 // app is unfrozen and still able to run 4895 mAppDataHelper.clearAppDataLIF(pkg, userId, 4896 flags | Installer.FLAG_CLEAR_CACHE_ONLY); 4897 mAppDataHelper.clearAppDataLIF(pkg, userId, 4898 flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 4899 } 4900 } 4901 if (observer != null) { 4902 try { 4903 observer.onRemoveCompleted(packageName, true); 4904 } catch (RemoteException e) { 4905 Log.i(TAG, "Observer no longer exists."); 4906 } 4907 } 4908 }); 4909 } 4910 4911 @Override 4912 public void enterSafeMode() { 4913 PackageManagerServiceUtils.enforceSystemOrRoot( 4914 "Only the system can request entering safe mode"); 4915 4916 if (!mSystemReady) { 4917 mSafeMode = true; 4918 } 4919 } 4920 4921 @Override 4922 public void extendVerificationTimeout(int verificationId, int verificationCodeAtTimeout, 4923 long millisecondsToDelay) { 4924 // Negative ids correspond to testing verifiers and will be silently enforced in 4925 // the handler thread. 4926 if (verificationId >= 0) { 4927 mContext.enforceCallingOrSelfPermission( 4928 Manifest.permission.PACKAGE_VERIFICATION_AGENT, 4929 "Only package verification agents can extend verification timeouts"); 4930 } 4931 final int callingUid = Binder.getCallingUid(); 4932 4933 mHandler.post(() -> { 4934 final int id = verificationId >= 0 ? verificationId : -verificationId; 4935 final PackageVerificationState state = mPendingVerification.get(id); 4936 if (state == null || !state.extendTimeout(callingUid)) { 4937 // Invalid uid or already extended. 4938 return; 4939 } 4940 4941 final PackageVerificationResponse response = new PackageVerificationResponse( 4942 verificationCodeAtTimeout, callingUid); 4943 4944 long delay = millisecondsToDelay; 4945 if (delay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 4946 delay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 4947 } 4948 if (delay < 0) { 4949 delay = 0; 4950 } 4951 4952 final Message msg = mHandler.obtainMessage(PackageManagerService.PACKAGE_VERIFIED); 4953 msg.arg1 = id; 4954 msg.obj = response; 4955 mHandler.sendMessageDelayed(msg, delay); 4956 }); 4957 } 4958 4959 @WorkerThread 4960 @Override 4961 public void flushPackageRestrictionsAsUser(int userId) { 4962 final Computer snapshot = snapshotComputer(); 4963 final int callingUid = Binder.getCallingUid(); 4964 if (snapshot.getInstantAppPackageName(callingUid) != null) { 4965 return; 4966 } 4967 if (!mUserManager.exists(userId)) { 4968 return; 4969 } 4970 snapshot.enforceCrossUserPermission(callingUid, userId, 4971 false /* requireFullPermission*/, false /* checkShell */, 4972 "flushPackageRestrictions"); 4973 synchronized (mLock) { 4974 flushPackageRestrictionsAsUserInternalLocked(userId); 4975 } 4976 } 4977 4978 4979 @Override 4980 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4981 final @StorageManager.AllocateFlags int flags, final IntentSender pi) { 4982 mContext.enforceCallingOrSelfPermission( 4983 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4984 mHandler.post(() -> { 4985 boolean success = false; 4986 try { 4987 PackageManagerService.this.freeStorage(volumeUuid, freeStorageSize, flags); 4988 success = true; 4989 } catch (IOException e) { 4990 Slog.w(TAG, e); 4991 } 4992 if (pi != null) { 4993 try { 4994 final BroadcastOptions options = BroadcastOptions.makeBasic(); 4995 options.setPendingIntentBackgroundActivityLaunchAllowed(false); 4996 pi.sendIntent(null, success ? 1 : 0, null /* intent */, 4997 null /* onFinished*/, null /* handler */, 4998 null /* requiredPermission */, options.toBundle()); 4999 } catch (SendIntentException e) { 5000 Slog.w(TAG, e); 5001 } 5002 } 5003 }); 5004 } 5005 5006 @Override 5007 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 5008 final @StorageManager.AllocateFlags int flags, final IPackageDataObserver observer) { 5009 mContext.enforceCallingOrSelfPermission( 5010 android.Manifest.permission.CLEAR_APP_CACHE, null); 5011 mHandler.post(() -> { 5012 boolean success = false; 5013 try { 5014 PackageManagerService.this.freeStorage(volumeUuid, freeStorageSize, flags); 5015 success = true; 5016 } catch (IOException e) { 5017 Slog.w(PackageManagerService.TAG, e); 5018 } 5019 if (observer != null) { 5020 try { 5021 observer.onRemoveCompleted(null, success); 5022 } catch (RemoteException e) { 5023 Slog.w(PackageManagerService.TAG, e); 5024 } 5025 } 5026 }); 5027 } 5028 5029 @Override 5030 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5031 final int callingUid = Binder.getCallingUid(); 5032 final Computer snapshot = snapshotComputer(); 5033 if (snapshot.getInstantAppPackageName(callingUid) != null) { 5034 return null; 5035 } 5036 if (!mUserManager.exists(userId)) { 5037 return null; 5038 } 5039 snapshot.enforceCrossUserPermission(callingUid, userId, false, false, 5040 "getChangedPackages"); 5041 final ChangedPackages changedPackages = mChangedPackagesTracker.getChangedPackages( 5042 sequenceNumber, userId); 5043 5044 if (changedPackages != null) { 5045 final List<String> packageNames = changedPackages.getPackageNames(); 5046 for (int index = packageNames.size() - 1; index >= 0; index--) { 5047 // Filter out the changes if the calling package should not be able to see it. 5048 final PackageStateInternal packageState = 5049 snapshot.getPackageStateInternal(packageNames.get(index)); 5050 if (snapshot.shouldFilterApplication(packageState, callingUid, userId)) { 5051 packageNames.remove(index); 5052 } 5053 } 5054 } 5055 5056 return changedPackages; 5057 } 5058 5059 @Override 5060 public byte[] getDomainVerificationBackup(int userId) { 5061 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 5062 throw new SecurityException("Only the system may call getDomainVerificationBackup()"); 5063 } 5064 5065 try { 5066 try (ByteArrayOutputStream output = new ByteArrayOutputStream()) { 5067 TypedXmlSerializer serializer = Xml.resolveSerializer(output); 5068 mDomainVerificationManager.writeSettings(snapshotComputer(), serializer, true, 5069 userId); 5070 return output.toByteArray(); 5071 } 5072 } catch (Exception e) { 5073 if (PackageManagerService.DEBUG_BACKUP) { 5074 Slog.e(PackageManagerService.TAG, "Unable to write domain verification for backup", e); 5075 } 5076 return null; 5077 } 5078 } 5079 5080 @Override 5081 public IBinder getHoldLockToken() { 5082 if (!Build.IS_DEBUGGABLE) { 5083 throw new SecurityException("getHoldLockToken requires a debuggable build"); 5084 } 5085 5086 mContext.enforceCallingPermission( 5087 Manifest.permission.INJECT_EVENTS, 5088 "getHoldLockToken requires INJECT_EVENTS permission"); 5089 5090 final Binder token = new Binder(); 5091 token.attachInterface(this, "holdLock:" + Binder.getCallingUid()); 5092 return token; 5093 } 5094 5095 @Override 5096 public String getInstantAppAndroidId(String packageName, int userId) { 5097 mContext.enforceCallingOrSelfPermission( 5098 android.Manifest.permission.ACCESS_INSTANT_APPS, "getInstantAppAndroidId"); 5099 final Computer snapshot = snapshotComputer(); 5100 snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5101 true /* requireFullPermission */, false /* checkShell */, 5102 "getInstantAppAndroidId"); 5103 // Make sure the target is an Instant App. 5104 if (!snapshot.isInstantApp(packageName, userId)) { 5105 return null; 5106 } 5107 return mInstantAppRegistry.getInstantAppAndroidId(packageName, userId); 5108 } 5109 5110 @Override 5111 public byte[] getInstantAppCookie(String packageName, int userId) { 5112 if (HIDE_EPHEMERAL_APIS) { 5113 return null; 5114 } 5115 5116 final Computer snapshot = snapshotComputer(); 5117 snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5118 true /* requireFullPermission */, false /* checkShell */, 5119 "getInstantAppCookie"); 5120 if (!snapshot.isCallerSameApp(packageName, Binder.getCallingUid())) { 5121 return null; 5122 } 5123 PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 5124 if (packageState == null || packageState.getPkg() == null) { 5125 return null; 5126 } 5127 return mInstantAppRegistry.getInstantAppCookie(packageState.getPkg(), userId); 5128 } 5129 5130 @Override 5131 public Bitmap getInstantAppIcon(String packageName, int userId) { 5132 if (HIDE_EPHEMERAL_APIS) { 5133 return null; 5134 } 5135 5136 final Computer snapshot = snapshotComputer(); 5137 if (!snapshot.canViewInstantApps(Binder.getCallingUid(), userId)) { 5138 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 5139 "getInstantAppIcon"); 5140 } 5141 snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5142 true /* requireFullPermission */, false /* checkShell */, 5143 "getInstantAppIcon"); 5144 5145 return mInstantAppRegistry.getInstantAppIcon(packageName, userId); 5146 } 5147 5148 @Override 5149 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 5150 if (HIDE_EPHEMERAL_APIS) { 5151 return null; 5152 } 5153 5154 final Computer snapshot = snapshotComputer(); 5155 if (!snapshot.canViewInstantApps(Binder.getCallingUid(), userId)) { 5156 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 5157 "getEphemeralApplications"); 5158 } 5159 snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5160 true /* requireFullPermission */, false /* checkShell */, 5161 "getEphemeralApplications"); 5162 5163 List<InstantAppInfo> instantApps = mInstantAppRegistry.getInstantApps(snapshot, userId); 5164 if (instantApps != null) { 5165 return new ParceledListSlice<>(instantApps); 5166 } 5167 return null; 5168 } 5169 5170 @Override 5171 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 5172 return mPreferredActivityHelper.getLastChosenActivity(snapshotComputer(), intent, 5173 resolvedType, flags); 5174 } 5175 5176 @Override 5177 public IntentSender getLaunchIntentSenderForPackage(String packageName, String callingPackage, 5178 String featureId, int userId) throws RemoteException { 5179 return mResolveIntentHelper.getLaunchIntentSenderForPackage(snapshotComputer(), 5180 packageName, callingPackage, featureId, userId); 5181 } 5182 5183 @Override 5184 public List<String> getMimeGroup(String packageName, String mimeGroup) { 5185 final Computer snapshot = snapshotComputer(); 5186 enforceOwnerRights(snapshot, packageName, Binder.getCallingUid()); 5187 return getMimeGroupInternal(snapshot, packageName, mimeGroup); 5188 } 5189 5190 @Override 5191 public int getMoveStatus(int moveId) { 5192 mContext.enforceCallingOrSelfPermission( 5193 Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 5194 return mMoveCallbacks.mLastStatus.get(moveId); 5195 } 5196 5197 @Override 5198 public ParcelFileDescriptor getAppMetadataFd(String packageName, int userId) { 5199 mContext.enforceCallingOrSelfPermission(GET_APP_METADATA, "getAppMetadataFd"); 5200 final int callingUid = Binder.getCallingUid(); 5201 final Computer snapshot = snapshotComputer(); 5202 final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered( 5203 packageName, callingUid, userId); 5204 if (ps == null) { 5205 throw new ParcelableException( 5206 new PackageManager.NameNotFoundException(packageName)); 5207 } 5208 String filePath = ps.getAppMetadataFilePath(); 5209 if (filePath != null) { 5210 File file = new File(filePath); 5211 try { 5212 return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY); 5213 } catch (FileNotFoundException e) { 5214 return null; 5215 } 5216 } 5217 return null; 5218 } 5219 5220 @Override 5221 public String getPermissionControllerPackageName() { 5222 final int callingUid = Binder.getCallingUid(); 5223 final int callingUserId = UserHandle.getUserId(callingUid); 5224 final Computer snapshot = snapshotComputer(); 5225 if (snapshot.getPackageStateForInstalledAndFiltered( 5226 mRequiredPermissionControllerPackage, callingUid, callingUserId) != null) { 5227 return mRequiredPermissionControllerPackage; 5228 } 5229 5230 throw new IllegalStateException("PermissionController is not found"); 5231 } 5232 5233 @Override 5234 @SuppressWarnings("GuardedBy") 5235 public int getRuntimePermissionsVersion(@UserIdInt int userId) { 5236 Preconditions.checkArgumentNonnegative(userId); 5237 enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions( 5238 "getRuntimePermissionVersion"); 5239 return mSettings.getDefaultRuntimePermissionsVersion(userId); 5240 } 5241 5242 @Override 5243 public String getSplashScreenTheme(@NonNull String packageName, int userId) { 5244 final Computer snapshot = snapshotComputer(); 5245 final int callingUid = Binder.getCallingUid(); 5246 snapshot.enforceCrossUserPermission( 5247 callingUid, userId, false /* requireFullPermission */, 5248 false /* checkShell */, "getSplashScreenTheme"); 5249 PackageStateInternal packageState = snapshot.getPackageStateForInstalledAndFiltered( 5250 packageName, callingUid, userId); 5251 return packageState == null ? null 5252 : packageState.getUserStateOrDefault(userId).getSplashScreenTheme(); 5253 } 5254 5255 @Override 5256 @PackageManager.UserMinAspectRatio 5257 public int getUserMinAspectRatio(@NonNull String packageName, int userId) { 5258 final Computer snapshot = snapshotComputer(); 5259 final int callingUid = Binder.getCallingUid(); 5260 final PackageStateInternal packageState = snapshot 5261 .getPackageStateForInstalledAndFiltered(packageName, callingUid, userId); 5262 return packageState == null ? USER_MIN_ASPECT_RATIO_UNSET 5263 : packageState.getUserStateOrDefault(userId).getMinAspectRatio(); 5264 } 5265 5266 @Override 5267 public Bundle getSuspendedPackageAppExtras(String packageName, int userId) { 5268 final int callingUid = Binder.getCallingUid(); 5269 final Computer snapshot = snapshot(); 5270 if (snapshot.getPackageUid(packageName, 0, userId) != callingUid) { 5271 throw new SecurityException("Calling package " + packageName 5272 + " does not belong to calling uid " + callingUid); 5273 } 5274 return mSuspendPackageHelper 5275 .getSuspendedPackageAppExtras(snapshot, packageName, userId, callingUid); 5276 } 5277 5278 @Override 5279 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5280 // allow instant applications 5281 ArrayList<FeatureInfo> res; 5282 synchronized (mAvailableFeatures) { 5283 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5284 res.addAll(mAvailableFeatures.values()); 5285 } 5286 final FeatureInfo fi = new FeatureInfo(); 5287 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5288 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5289 res.add(fi); 5290 5291 return new ParceledListSlice<>(res); 5292 } 5293 5294 @Override 5295 public @NonNull List<String> getInitialNonStoppedSystemPackages() { 5296 return mInitialNonStoppedSystemPackages != null 5297 ? new ArrayList<>(mInitialNonStoppedSystemPackages) : new ArrayList<>(); 5298 } 5299 5300 @Override 5301 public String[] getUnsuspendablePackagesForUser(String[] packageNames, int userId) { 5302 Objects.requireNonNull(packageNames, "packageNames cannot be null"); 5303 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 5304 "getUnsuspendablePackagesForUser"); 5305 final int callingUid = Binder.getCallingUid(); 5306 if (UserHandle.getUserId(callingUid) != userId) { 5307 mContext.enforceCallingOrSelfPermission( 5308 Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5309 "Calling uid " + callingUid 5310 + " cannot query getUnsuspendablePackagesForUser for user " 5311 + userId); 5312 } 5313 return mSuspendPackageHelper.getUnsuspendablePackagesForUser(snapshotComputer(), 5314 packageNames, userId, callingUid); 5315 } 5316 5317 @Override 5318 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 5319 mContext.enforceCallingOrSelfPermission( 5320 Manifest.permission.PACKAGE_VERIFICATION_AGENT, 5321 "Only package verification agents can read the verifier device identity"); 5322 5323 synchronized (mLock) { 5324 return mSettings.getVerifierDeviceIdentityLPw(mLiveComputer); 5325 } 5326 } 5327 5328 @Override 5329 public void makeProviderVisible(int recipientUid, @NonNull String visibleAuthority) { 5330 final Computer snapshot = snapshotComputer(); 5331 final int recipientUserId = UserHandle.getUserId(recipientUid); 5332 final ProviderInfo providerInfo = 5333 snapshot.getGrantImplicitAccessProviderInfo(recipientUid, visibleAuthority); 5334 if (providerInfo == null) { 5335 return; 5336 } 5337 int visibleUid = providerInfo.applicationInfo.uid; 5338 PackageManagerService.this.grantImplicitAccess(snapshot, recipientUserId, 5339 null /*Intent*/, UserHandle.getAppId(recipientUid), visibleUid, 5340 false /*direct*/, false /* retainOnUpdate */); 5341 } 5342 5343 @Override 5344 public void makeUidVisible(int recipientUid, int visibleUid) { 5345 mContext.enforceCallingOrSelfPermission( 5346 android.Manifest.permission.MAKE_UID_VISIBLE, "makeUidVisible"); 5347 final int callingUid = Binder.getCallingUid(); 5348 final int recipientUserId = UserHandle.getUserId(recipientUid); 5349 final int visibleUserId = UserHandle.getUserId(visibleUid); 5350 final Computer snapshot = snapshotComputer(); 5351 snapshot.enforceCrossUserPermission(callingUid, recipientUserId, 5352 false /* requireFullPermission */, false /* checkShell */, "makeUidVisible"); 5353 snapshot.enforceCrossUserPermission(callingUid, visibleUserId, 5354 false /* requireFullPermission */, false /* checkShell */, "makeUidVisible"); 5355 snapshot.enforceCrossUserPermission(recipientUid, visibleUserId, 5356 false /* requireFullPermission */, false /* checkShell */, "makeUidVisible"); 5357 5358 PackageManagerService.this.grantImplicitAccess(snapshot, recipientUserId, 5359 null /*Intent*/, UserHandle.getAppId(recipientUid), visibleUid, 5360 false /*direct*/, false /* retainOnUpdate */); 5361 } 5362 5363 @Override 5364 public void holdLock(IBinder token, int durationMs) { 5365 mTestUtilityService.verifyHoldLockToken(token); 5366 5367 synchronized (mLock) { 5368 SystemClock.sleep(durationMs); 5369 } 5370 } 5371 5372 /** 5373 * @hide 5374 */ 5375 @Override 5376 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 5377 int installReason, List<String> whiteListedPermissions) { 5378 return mInstallPackageHelper.installExistingPackageAsUser(packageName, userId, installFlags, 5379 installReason, whiteListedPermissions, null).first; 5380 } 5381 5382 @Override 5383 public boolean isAutoRevokeWhitelisted(String packageName) { 5384 int mode = mInjector.getSystemService(AppOpsManager.class).checkOpNoThrow( 5385 AppOpsManager.OP_AUTO_REVOKE_PERMISSIONS_IF_UNUSED, 5386 Binder.getCallingUid(), packageName); 5387 return mode == MODE_IGNORED; 5388 } 5389 5390 @Override 5391 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 5392 final int callingUid = Binder.getCallingUid(); 5393 final int callingAppId = UserHandle.getAppId(callingUid); 5394 5395 final Computer snapshot = snapshotComputer(); 5396 snapshot.enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 5397 true /*checkShell*/, "isPackageStateProtected"); 5398 5399 if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId) 5400 && snapshot.checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) 5401 != PERMISSION_GRANTED) { 5402 throw new SecurityException("Caller must have the " 5403 + MANAGE_DEVICE_ADMINS + " permission."); 5404 } 5405 5406 return mProtectedPackages.isPackageStateProtected(userId, packageName); 5407 } 5408 5409 @Override 5410 public boolean isProtectedBroadcast(String actionName) { 5411 if (actionName != null) { 5412 // TODO: remove these terrible hacks 5413 if (actionName.startsWith("android.net.netmon.lingerExpired") 5414 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 5415 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 5416 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 5417 return true; 5418 } 5419 } 5420 // allow instant applications 5421 synchronized (mProtectedBroadcasts) { 5422 return mProtectedBroadcasts.contains(actionName); 5423 } 5424 } 5425 5426 /** 5427 * Logs process start information (including base APK hash) to the security log. 5428 * @hide 5429 */ 5430 @Override 5431 public void logAppProcessStartIfNeeded(String packageName, String processName, int uid, 5432 String seinfo, String apkFile, int pid) { 5433 final Computer snapshot = snapshotComputer(); 5434 if (snapshot.getInstantAppPackageName(Binder.getCallingUid()) != null) { 5435 return; 5436 } 5437 if (!SecurityLog.isLoggingEnabled()) { 5438 return; 5439 } 5440 mProcessLoggingHandler.logAppProcessStart(mContext, 5441 LocalServices.getService(PackageManagerInternal.class), apkFile, packageName, 5442 processName, uid, seinfo, pid); 5443 } 5444 5445 @Override 5446 public int movePackage(final String packageName, final String volumeUuid) { 5447 mContext.enforceCallingOrSelfPermission(Manifest.permission.MOVE_PACKAGE, null); 5448 5449 final int callingUid = Binder.getCallingUid(); 5450 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 5451 final int moveId = mNextMoveId.getAndIncrement(); 5452 mHandler.post(() -> { 5453 try { 5454 MovePackageHelper movePackageHelper = 5455 new MovePackageHelper(PackageManagerService.this); 5456 movePackageHelper.movePackageInternal( 5457 packageName, volumeUuid, moveId, callingUid, user); 5458 } catch (PackageManagerException e) { 5459 Slog.w(PackageManagerService.TAG, "Failed to move " + packageName, e); 5460 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 5461 } 5462 }); 5463 return moveId; 5464 } 5465 5466 @Override 5467 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 5468 mContext.enforceCallingOrSelfPermission(Manifest.permission.MOVE_PACKAGE, null); 5469 5470 final int realMoveId = mNextMoveId.getAndIncrement(); 5471 final Bundle extras = new Bundle(); 5472 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 5473 mMoveCallbacks.notifyCreated(realMoveId, extras); 5474 5475 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 5476 @Override 5477 public void onCreated(int moveId, Bundle extras) { 5478 // Ignored 5479 } 5480 5481 @Override 5482 public void onStatusChanged(int moveId, int status, long estMillis) { 5483 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 5484 } 5485 }; 5486 5487 final StorageManager storage = mInjector.getSystemService(StorageManager.class); 5488 storage.setPrimaryStorageUuid(volumeUuid, callback); 5489 return realMoveId; 5490 } 5491 5492 @Override 5493 public void notifyDexLoad(String loadingPackageName, 5494 Map<String, String> classLoaderContextMap, 5495 String loaderIsa) { 5496 int callingUid = Binder.getCallingUid(); 5497 Computer snapshot = snapshot(); 5498 5499 // System server should be able to report dex load on behalf of other apps. E.g., it 5500 // could potentially resend the notifications in order to migrate the existing dex load 5501 // info to ART Service. 5502 if (!PackageManagerServiceUtils.isSystemOrRoot() 5503 && !snapshot.isCallerSameApp( 5504 loadingPackageName, callingUid, true /* resolveIsolatedUid */)) { 5505 Slog.w(PackageManagerService.TAG, 5506 TextUtils.formatSimple( 5507 "Invalid dex load report. loadingPackageName=%s, uid=%d", 5508 loadingPackageName, callingUid)); 5509 return; 5510 } 5511 5512 UserHandle user = Binder.getCallingUserHandle(); 5513 int userId = user.getIdentifier(); 5514 5515 // Proxy the call to either ART Service or the legacy implementation. If the 5516 // implementation is switched with the system property, the dex usage info will be 5517 // incomplete, with these effects: 5518 // 5519 // - Shared dex files may temporarily get compiled for private use. 5520 // - Secondary dex files may not get compiled at all. 5521 // - Stale compiled artifacts for secondary dex files may not get cleaned up. 5522 // 5523 // This recovers in the first background dexopt after the depending apps have been 5524 // loaded for the first time. 5525 5526 DexUseManagerLocal dexUseManager = DexOptHelper.getDexUseManagerLocal(); 5527 if (dexUseManager != null) { 5528 // TODO(chiuwinson): Retrieve filtered snapshot from Computer instance instead. 5529 try (PackageManagerLocal.FilteredSnapshot filteredSnapshot = 5530 LocalManagerRegistry.getManager(PackageManagerLocal.class) 5531 .withFilteredSnapshot(callingUid, user)) { 5532 if (loaderIsa != null) { 5533 // Check that loaderIsa agrees with the ISA that dexUseManager will 5534 // determine. 5535 PackageState loadingPkgState = 5536 filteredSnapshot.getPackageState(loadingPackageName); 5537 // If we don't find the loading package just pass it through and let 5538 // dexUseManager throw on it. 5539 if (loadingPkgState != null) { 5540 String loadingPkgAbi = loadingPkgState.getPrimaryCpuAbi(); 5541 if (loadingPkgAbi == null) { 5542 loadingPkgAbi = Build.SUPPORTED_ABIS[0]; 5543 } 5544 String loadingPkgDexCodeIsa = InstructionSets.getDexCodeInstructionSet( 5545 VMRuntime.getInstructionSet(loadingPkgAbi)); 5546 if (!loaderIsa.equals(loadingPkgDexCodeIsa)) { 5547 // TODO(b/251903639): We make this a wtf to surface any situations 5548 // where this argument doesn't correspond to our expectations. Later 5549 // it should be turned into an IllegalArgumentException, when we can 5550 // assume it's the caller that's wrong rather than us. 5551 Log.wtf(TAG, 5552 "Invalid loaderIsa in notifyDexLoad call from " 5553 + loadingPackageName + ", uid " + callingUid 5554 + ": expected " + loadingPkgDexCodeIsa + ", got " 5555 + loaderIsa); 5556 return; 5557 } 5558 } 5559 } 5560 5561 // This is called from binder, so exceptions thrown here are caught and handled 5562 // by it. 5563 dexUseManager.notifyDexContainersLoaded( 5564 filteredSnapshot, loadingPackageName, classLoaderContextMap); 5565 } 5566 } else { 5567 ApplicationInfo ai = 5568 snapshot.getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 5569 if (ai == null) { 5570 Slog.w(PackageManagerService.TAG, 5571 "Loading a package that does not exist for the calling user. package=" 5572 + loadingPackageName + ", user=" + userId); 5573 return; 5574 } 5575 mDexManager.notifyDexLoad(ai, classLoaderContextMap, loaderIsa, userId, 5576 Process.isIsolated(callingUid)); 5577 } 5578 } 5579 5580 @Override 5581 public void notifyPackageUse(String packageName, int reason) { 5582 final int callingUid = Binder.getCallingUid(); 5583 final int callingUserId = UserHandle.getUserId(callingUid); 5584 Computer snapshot = snapshotComputer(); 5585 final boolean notify; 5586 if (snapshot.getInstantAppPackageName(callingUid) != null) { 5587 notify = snapshot.isCallerSameApp(packageName, callingUid); 5588 } else { 5589 notify = !snapshot.isInstantAppInternal(packageName, callingUserId, 5590 Process.SYSTEM_UID); 5591 } 5592 if (!notify) { 5593 return; 5594 } 5595 5596 notifyPackageUseInternal(packageName, reason); 5597 } 5598 5599 @Override 5600 public void overrideLabelAndIcon(@NonNull ComponentName componentName, 5601 @NonNull String nonLocalizedLabel, int icon, int userId) { 5602 if (TextUtils.isEmpty(nonLocalizedLabel)) { 5603 throw new IllegalArgumentException("Override label should be a valid String"); 5604 } 5605 updateComponentLabelIcon(componentName, nonLocalizedLabel, icon, userId); 5606 } 5607 5608 @Override 5609 public ParceledListSlice<PackageManager.Property> queryProperty( 5610 String propertyName, @PackageManager.PropertyLocation int componentType) { 5611 Objects.requireNonNull(propertyName); 5612 final int callingUid = Binder.getCallingUid(); 5613 final int callingUserId = UserHandle.getCallingUserId(); 5614 final Computer snapshot = snapshotComputer(); 5615 final List<PackageManager.Property> result = 5616 mPackageProperty.queryProperty(propertyName, componentType, 5617 packageName -> snapshot.getPackageStateForInstalledAndFiltered( 5618 packageName, callingUid, callingUserId) == null 5619 ); 5620 if (result == null) { 5621 return ParceledListSlice.emptyList(); 5622 } 5623 return new ParceledListSlice<>(result); 5624 } 5625 5626 @Override 5627 public void registerDexModule(String packageName, String dexModulePath, 5628 boolean isSharedModule, 5629 IDexModuleRegisterCallback callback) { 5630 // ART Service doesn't support this explicit dexopting and instead relies on background 5631 // dexopt for secondary dex files. For compat parity between ART Service and the legacy 5632 // code it's disabled for both. 5633 // 5634 // Also, this API is problematic anyway since it doesn't provide the correct classloader 5635 // context, so it is hard to produce dexopt artifacts that the runtime can load 5636 // successfully. 5637 Slog.i(TAG, 5638 "Ignored unsupported registerDexModule call for " + dexModulePath + " in " 5639 + packageName); 5640 DexManager.RegisterDexModuleResult result = new DexManager.RegisterDexModuleResult( 5641 false, "registerDexModule call not supported since Android U"); 5642 5643 if (callback != null) { 5644 mHandler.post(() -> { 5645 try { 5646 callback.onDexModuleRegistered(dexModulePath, result.success, 5647 result.message); 5648 } catch (RemoteException e) { 5649 Slog.w(PackageManagerService.TAG, 5650 "Failed to callback after module registration " + dexModulePath, e); 5651 } 5652 }); 5653 } 5654 } 5655 5656 @Override 5657 public void registerMoveCallback(IPackageMoveObserver callback) { 5658 mContext.enforceCallingOrSelfPermission( 5659 Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 5660 mMoveCallbacks.register(callback); 5661 } 5662 5663 @Override 5664 public void restoreDomainVerification(byte[] backup, int userId) { 5665 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 5666 throw new SecurityException("Only the system may call restorePreferredActivities()"); 5667 } 5668 5669 try { 5670 ByteArrayInputStream input = new ByteArrayInputStream(backup); 5671 TypedXmlPullParser parser = Xml.resolvePullParser(input); 5672 5673 // User ID input isn't necessary here as it assumes the user integers match and that 5674 // the only states inside the backup XML are for the target user. 5675 mDomainVerificationManager.restoreSettings(snapshotComputer(), parser); 5676 input.close(); 5677 } catch (Exception e) { 5678 if (PackageManagerService.DEBUG_BACKUP) { 5679 Slog.e(PackageManagerService.TAG, "Exception restoring domain verification: " + e.getMessage()); 5680 } 5681 } 5682 } 5683 5684 @Override 5685 public void restoreLabelAndIcon(@NonNull ComponentName componentName, int userId) { 5686 updateComponentLabelIcon(componentName, null, null, userId); 5687 } 5688 5689 @Override 5690 public void sendDeviceCustomizationReadyBroadcast() { 5691 mContext.enforceCallingPermission(Manifest.permission.SEND_DEVICE_CUSTOMIZATION_READY, 5692 "sendDeviceCustomizationReadyBroadcast"); 5693 5694 final long ident = Binder.clearCallingIdentity(); 5695 try { 5696 BroadcastHelper.sendDeviceCustomizationReadyBroadcast(); 5697 } finally { 5698 Binder.restoreCallingIdentity(ident); 5699 } 5700 } 5701 5702 @Override 5703 public void setApplicationCategoryHint(String packageName, int categoryHint, 5704 String callerPackageName) { 5705 final FunctionalUtils.ThrowingBiFunction<PackageStateMutator.InitialState, Computer, 5706 PackageStateMutator.Result> implementation = (initialState, computer) -> { 5707 if (computer.getInstantAppPackageName(Binder.getCallingUid()) != null) { 5708 throw new SecurityException( 5709 "Instant applications don't have access to this method"); 5710 } 5711 mInjector.getSystemService(AppOpsManager.class) 5712 .checkPackage(Binder.getCallingUid(), callerPackageName); 5713 5714 PackageStateInternal packageState = computer.getPackageStateForInstalledAndFiltered( 5715 packageName, Binder.getCallingUid(), UserHandle.getCallingUserId()); 5716 if (packageState == null) { 5717 throw new IllegalArgumentException("Unknown target package " + packageName); 5718 } 5719 5720 if (!Objects.equals(callerPackageName, 5721 packageState.getInstallSource().mInstallerPackageName)) { 5722 throw new IllegalArgumentException("Calling package " + callerPackageName 5723 + " is not installer for " + packageName); 5724 } 5725 5726 if (packageState.getCategoryOverride() != categoryHint) { 5727 return commitPackageStateMutation(initialState, 5728 packageName, state -> state.setCategoryOverride(categoryHint)); 5729 } else { 5730 return null; 5731 } 5732 }; 5733 5734 PackageStateMutator.Result result = 5735 implementation.apply(recordInitialState(), snapshotComputer()); 5736 if (result != null && result.isStateChanged() && !result.isSpecificPackageNull()) { 5737 // TODO: Specific return value of what state changed? 5738 // The installer on record might have changed, retry with lock 5739 synchronized (mPackageStateWriteLock) { 5740 result = implementation.apply(recordInitialState(), snapshotComputer()); 5741 } 5742 } 5743 5744 if (result != null && result.isCommitted()) { 5745 scheduleWriteSettings(); 5746 } 5747 } 5748 5749 @Override 5750 public void setApplicationEnabledSetting(String appPackageName, 5751 int newState, int flags, int userId, String callingPackage) { 5752 if (!mUserManager.exists(userId)) return; 5753 if (callingPackage == null) { 5754 callingPackage = Integer.toString(Binder.getCallingUid()); 5755 } 5756 5757 setEnabledSettings(List.of(new PackageManager.ComponentEnabledSetting(appPackageName, newState, flags)), 5758 userId, callingPackage); 5759 } 5760 5761 @Override 5762 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 5763 int userId) { 5764 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 5765 final int callingUid = Binder.getCallingUid(); 5766 final Computer snapshot = snapshotComputer(); 5767 snapshot.enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 5768 true /* checkShell */, "setApplicationHiddenSetting for user " + userId); 5769 5770 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 5771 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 5772 return false; 5773 } 5774 5775 // Do not allow "android" is being disabled 5776 if ("android".equals(packageName)) { 5777 Slog.w(TAG, "Cannot hide package: android"); 5778 return false; 5779 } 5780 5781 final long callingId = Binder.clearCallingIdentity(); 5782 try { 5783 final PackageStateInternal packageState = snapshot.getPackageStateInternal( 5784 packageName); 5785 if (packageState == null) { 5786 return false; 5787 } 5788 5789 final PackageUserStateInternal userState = packageState.getUserStateOrDefault( 5790 userId); 5791 if (userState.isHidden() == hidden || !userState.isInstalled() 5792 || snapshot.shouldFilterApplication(packageState, callingUid, userId)) { 5793 return false; 5794 } 5795 5796 // Cannot hide static shared libs as they are considered 5797 // a part of the using app (emulating static linking). Also 5798 // static libs are installed always on internal storage. 5799 AndroidPackage pkg = packageState.getPkg(); 5800 if (pkg != null) { 5801 // Cannot hide SDK libs as they are controlled by SDK manager. 5802 if (pkg.getSdkLibraryName() != null) { 5803 Slog.w(TAG, "Cannot hide package: " + packageName 5804 + " providing SDK library: " 5805 + pkg.getSdkLibraryName()); 5806 return false; 5807 } 5808 // Cannot hide static shared libs as they are considered 5809 // a part of the using app (emulating static linking). Also 5810 // static libs are installed always on internal storage. 5811 if (pkg.getStaticSharedLibraryName() != null) { 5812 Slog.w(TAG, "Cannot hide package: " + packageName 5813 + " providing static shared library: " 5814 + pkg.getStaticSharedLibraryName()); 5815 return false; 5816 } 5817 } 5818 // Only allow protected packages to hide themselves. 5819 if (hidden && !UserHandle.isSameApp(callingUid, packageState.getAppId()) 5820 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 5821 Slog.w(TAG, "Not hiding protected package: " + packageName); 5822 return false; 5823 } 5824 5825 commitPackageStateMutation(null, packageName, packageState1 -> 5826 packageState1.userState(userId).setHidden(hidden)); 5827 5828 final Computer newSnapshot = snapshotComputer(); 5829 final PackageStateInternal newPackageState = 5830 newSnapshot.getPackageStateInternal(packageName); 5831 5832 if (hidden) { 5833 killApplication(packageName, newPackageState.getAppId(), userId, "hiding pkg", 5834 ApplicationExitInfo.REASON_OTHER); 5835 sendApplicationHiddenForUser(packageName, newPackageState, userId); 5836 } else { 5837 sendPackageAddedForUser(newSnapshot, packageName, newPackageState, userId, 5838 DataLoaderType.NONE); 5839 } 5840 5841 scheduleWritePackageRestrictions(userId); 5842 return true; 5843 } finally { 5844 Binder.restoreCallingIdentity(callingId); 5845 } 5846 } 5847 5848 @Override 5849 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 5850 int userId) { 5851 mContext.enforceCallingOrSelfPermission( 5852 Manifest.permission.DELETE_PACKAGES, null); 5853 final Computer snapshot = snapshotComputer(); 5854 PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 5855 if (packageState != null && packageState.getPkg() != null) { 5856 AndroidPackage pkg = packageState.getPkg(); 5857 // Cannot block uninstall SDK libs as they are controlled by SDK manager. 5858 if (pkg.getSdkLibraryName() != null) { 5859 Slog.w(PackageManagerService.TAG, "Cannot block uninstall of package: " + packageName 5860 + " providing SDK library: " + pkg.getSdkLibraryName()); 5861 return false; 5862 } 5863 // Cannot block uninstall of static shared libs as they are 5864 // considered a part of the using app (emulating static linking). 5865 // Also static libs are installed always on internal storage. 5866 if (pkg.getStaticSharedLibraryName() != null) { 5867 Slog.w(PackageManagerService.TAG, "Cannot block uninstall of package: " + packageName 5868 + " providing static shared library: " + pkg.getStaticSharedLibraryName()); 5869 return false; 5870 } 5871 } 5872 synchronized (mLock) { 5873 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 5874 } 5875 5876 scheduleWritePackageRestrictions(userId); 5877 return true; 5878 } 5879 5880 @Override 5881 public void setComponentEnabledSetting(ComponentName componentName, 5882 int newState, int flags, int userId, String callingPackage) { 5883 if (!mUserManager.exists(userId)) return; 5884 if (callingPackage == null) { 5885 callingPackage = Integer.toString(Binder.getCallingUid()); 5886 } 5887 5888 setEnabledSettings(List.of(new PackageManager.ComponentEnabledSetting(componentName, newState, flags)), 5889 userId, callingPackage); 5890 } 5891 5892 @Override 5893 public void setComponentEnabledSettings( 5894 List<PackageManager.ComponentEnabledSetting> settings, int userId, 5895 String callingPackage) { 5896 if (!mUserManager.exists(userId)) return; 5897 if (settings == null || settings.isEmpty()) { 5898 throw new IllegalArgumentException("The list of enabled settings is empty"); 5899 } 5900 if (callingPackage == null) { 5901 callingPackage = Integer.toString(Binder.getCallingUid()); 5902 } 5903 setEnabledSettings(settings, userId, callingPackage); 5904 } 5905 5906 @Override 5907 public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames, 5908 int restrictionFlags, int userId) { 5909 final int callingUid = Binder.getCallingUid(); 5910 final Computer snapshot = snapshotComputer(); 5911 enforceCanSetDistractingPackageRestrictionsAsUser(callingUid, userId, 5912 "setDistractingPackageRestrictionsAsUser"); 5913 Objects.requireNonNull(packageNames, "packageNames cannot be null"); 5914 return mDistractingPackageHelper.setDistractingPackageRestrictionsAsUser(snapshot, 5915 packageNames, restrictionFlags, userId, callingUid); 5916 } 5917 5918 @Override 5919 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 5920 int userId) { 5921 final int callingUid = Binder.getCallingUid(); 5922 final int callingAppId = UserHandle.getAppId(callingUid); 5923 5924 final Computer snapshot = snapshotComputer(); 5925 snapshot.enforceCrossUserPermission(callingUid, userId, true /*requireFullPermission*/, 5926 true /*checkShell*/, "setHarmfulAppInfo"); 5927 5928 if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId) 5929 && snapshot.checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) 5930 != PERMISSION_GRANTED) { 5931 throw new SecurityException("Caller must have the " 5932 + SET_HARMFUL_APP_WARNINGS + " permission."); 5933 } 5934 5935 PackageStateMutator.Result result = commitPackageStateMutation(null, packageName, 5936 packageState -> packageState.userState(userId) 5937 .setHarmfulAppWarning(warning == null ? null : warning.toString())); 5938 if (result.isSpecificPackageNull()) { 5939 throw new IllegalArgumentException("Unknown package: " + packageName); 5940 } 5941 scheduleWritePackageRestrictions(userId); 5942 } 5943 5944 @Override 5945 public boolean setInstallLocation(int loc) { 5946 mContext.enforceCallingOrSelfPermission(Manifest.permission.WRITE_SECURE_SETTINGS, 5947 null); 5948 if (getInstallLocation() == loc) { 5949 return true; 5950 } 5951 if (loc == InstallLocationUtils.APP_INSTALL_AUTO 5952 || loc == InstallLocationUtils.APP_INSTALL_INTERNAL 5953 || loc == InstallLocationUtils.APP_INSTALL_EXTERNAL) { 5954 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 5955 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 5956 return true; 5957 } 5958 return false; 5959 } 5960 5961 @Override 5962 public void setInstallerPackageName(String targetPackage, 5963 @Nullable String installerPackageName) { 5964 final int callingUid = Binder.getCallingUid(); 5965 final int callingUserId = UserHandle.getUserId(callingUid); 5966 final FunctionalUtils.ThrowingCheckedFunction<Computer, Boolean, RuntimeException> 5967 implementation = snapshot -> { 5968 if (snapshot.getInstantAppPackageName(callingUid) != null) { 5969 return false; 5970 } 5971 5972 PackageStateInternal targetPackageState = 5973 snapshot.getPackageStateForInstalledAndFiltered( 5974 targetPackage, callingUid, callingUserId); 5975 if (targetPackageState == null) { 5976 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 5977 } 5978 5979 PackageStateInternal installerPackageState = null; 5980 if (installerPackageName != null) { 5981 installerPackageState = snapshot.getPackageStateForInstalledAndFiltered( 5982 installerPackageName, callingUid, callingUserId); 5983 if (installerPackageState == null) { 5984 throw new IllegalArgumentException("Unknown installer package: " 5985 + installerPackageName); 5986 } 5987 } 5988 5989 Signature[] callerSignature; 5990 final int appId = UserHandle.getAppId(callingUid); 5991 Pair<PackageStateInternal, SharedUserApi> either = 5992 snapshot.getPackageOrSharedUser(appId); 5993 if (either != null) { 5994 if (either.first != null) { 5995 callerSignature = either.first.getSigningDetails().getSignatures(); 5996 } else { 5997 callerSignature = either.second.getSigningDetails().getSignatures(); 5998 } 5999 } else { 6000 throw new SecurityException("Unknown calling UID: " + callingUid); 6001 } 6002 6003 // Verify: can't set installerPackageName to a package that is 6004 // not signed with the same cert as the caller. 6005 if (installerPackageState != null) { 6006 if (compareSignatures(callerSignature, 6007 installerPackageState.getSigningDetails().getSignatures()) 6008 != PackageManager.SIGNATURE_MATCH) { 6009 throw new SecurityException( 6010 "Caller does not have same cert as new installer package " 6011 + installerPackageName); 6012 } 6013 } 6014 6015 // Verify: if target already has an installer package, it must 6016 // be signed with the same cert as the caller. 6017 String targetInstallerPackageName = 6018 targetPackageState.getInstallSource().mInstallerPackageName; 6019 PackageStateInternal targetInstallerPkgSetting = targetInstallerPackageName == null 6020 ? null : snapshot.getPackageStateInternal(targetInstallerPackageName); 6021 6022 if (targetInstallerPkgSetting != null) { 6023 if (compareSignatures(callerSignature, 6024 targetInstallerPkgSetting.getSigningDetails().getSignatures()) 6025 != PackageManager.SIGNATURE_MATCH) { 6026 throw new SecurityException( 6027 "Caller does not have same cert as old installer package " 6028 + targetInstallerPackageName); 6029 } 6030 } else if (mContext.checkCallingOrSelfPermission( 6031 Manifest.permission.INSTALL_PACKAGES) != PERMISSION_GRANTED) { 6032 // This is probably an attempt to exploit vulnerability b/150857253 of taking 6033 // privileged installer permissions when the installer has been uninstalled or 6034 // was never set. 6035 EventLog.writeEvent(0x534e4554, "150857253", callingUid, ""); 6036 6037 final long binderToken = Binder.clearCallingIdentity(); 6038 try { 6039 if (mInjector.getCompatibility().isChangeEnabledByUid( 6040 PackageManagerService.THROW_EXCEPTION_ON_REQUIRE_INSTALL_PACKAGES_TO_ADD_INSTALLER_PACKAGE, 6041 callingUid)) { 6042 throw new SecurityException("Neither user " + callingUid 6043 + " nor current process has " 6044 + Manifest.permission.INSTALL_PACKAGES); 6045 } else { 6046 // If change disabled, fail silently for backwards compatibility 6047 return false; 6048 } 6049 } finally { 6050 Binder.restoreCallingIdentity(binderToken); 6051 } 6052 } 6053 6054 return true; 6055 }; 6056 PackageStateMutator.InitialState initialState = recordInitialState(); 6057 boolean allowed = implementation.apply(snapshotComputer()); 6058 if (allowed) { 6059 // TODO: Need to lock around here to handle mSettings.addInstallerPackageNames, 6060 // should find an alternative which avoids any race conditions 6061 final int installerPackageUid = installerPackageName == null 6062 ? INVALID_UID : snapshotComputer().getPackageUid(installerPackageName, 6063 0 /* flags */, callingUserId); 6064 PackageStateInternal targetPackageState; 6065 synchronized (mLock) { 6066 PackageStateMutator.Result result = commitPackageStateMutation(initialState, 6067 targetPackage, state -> state.setInstaller(installerPackageName, 6068 installerPackageUid)); 6069 if (result.isPackagesChanged() || result.isStateChanged()) { 6070 synchronized (mPackageStateWriteLock) { 6071 allowed = implementation.apply(snapshotComputer()); 6072 if (allowed) { 6073 commitPackageStateMutation(null, targetPackage, 6074 state -> state.setInstaller(installerPackageName, 6075 installerPackageUid)); 6076 } else { 6077 return; 6078 } 6079 } 6080 } 6081 targetPackageState = snapshotComputer().getPackageStateInternal(targetPackage); 6082 mSettings.addInstallerPackageNames(targetPackageState.getInstallSource()); 6083 } 6084 mAppsFilter.addPackage(snapshotComputer(), targetPackageState); 6085 scheduleWriteSettings(); 6086 } 6087 } 6088 6089 @Override 6090 public void relinquishUpdateOwnership(String targetPackage) { 6091 final int callingUid = Binder.getCallingUid(); 6092 final int callingUserId = UserHandle.getUserId(callingUid); 6093 final Computer snapshot = snapshotComputer(); 6094 6095 final PackageStateInternal targetPackageState = 6096 snapshot.getPackageStateForInstalledAndFiltered(targetPackage, callingUid, 6097 callingUserId); 6098 if (targetPackageState == null) { 6099 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 6100 } 6101 6102 final String targetUpdateOwnerPackageName = 6103 targetPackageState.getInstallSource().mUpdateOwnerPackageName; 6104 final PackageStateInternal targetUpdateOwnerPkgSetting = 6105 targetUpdateOwnerPackageName == null ? null 6106 : snapshot.getPackageStateInternal(targetUpdateOwnerPackageName); 6107 6108 if (targetUpdateOwnerPkgSetting == null) { 6109 return; 6110 } 6111 6112 final int callingAppId = UserHandle.getAppId(callingUid); 6113 final int targetUpdateOwnerAppId = targetUpdateOwnerPkgSetting.getAppId(); 6114 if (callingAppId != Process.SYSTEM_UID 6115 && callingAppId != Process.SHELL_UID 6116 && callingAppId != targetUpdateOwnerAppId) { 6117 throw new SecurityException("Caller is not the current update owner."); 6118 } 6119 6120 commitPackageStateMutation(null /* initialState */, targetPackage, 6121 state -> state.setUpdateOwner(null /* updateOwnerPackageName */)); 6122 scheduleWriteSettings(); 6123 } 6124 6125 @Override 6126 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 6127 if (HIDE_EPHEMERAL_APIS) { 6128 return true; 6129 } 6130 6131 final Computer snapshot = snapshotComputer(); 6132 snapshot.enforceCrossUserPermission(Binder.getCallingUid(), userId, 6133 true /* requireFullPermission */, true /* checkShell */, 6134 "setInstantAppCookie"); 6135 if (!snapshot.isCallerSameApp(packageName, Binder.getCallingUid())) { 6136 return false; 6137 } 6138 6139 PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 6140 if (packageState == null || packageState.getPkg() == null) { 6141 return false; 6142 } 6143 return mInstantAppRegistry.setInstantAppCookie(packageState.getPkg(), cookie, 6144 mContext.getPackageManager().getInstantAppCookieMaxBytes(), userId); 6145 } 6146 6147 @Override 6148 public void setKeepUninstalledPackages(List<String> packageList) { 6149 mContext.enforceCallingPermission( 6150 Manifest.permission.KEEP_UNINSTALLED_PACKAGES, 6151 "setKeepUninstalledPackages requires KEEP_UNINSTALLED_PACKAGES permission"); 6152 Objects.requireNonNull(packageList); 6153 6154 setKeepUninstalledPackagesInternal(snapshot(), packageList); 6155 } 6156 6157 @Override 6158 public void setMimeGroup(String packageName, String mimeGroup, List<String> mimeTypes) { 6159 final Computer snapshot = snapshotComputer(); 6160 enforceOwnerRights(snapshot, packageName, Binder.getCallingUid()); 6161 mimeTypes = CollectionUtils.emptyIfNull(mimeTypes); 6162 for (String mimeType : mimeTypes) { 6163 if (mimeType.length() > 255) { 6164 throw new IllegalArgumentException("MIME type length exceeds 255 characters"); 6165 } 6166 } 6167 final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 6168 Set<String> existingMimeTypes = packageState.getMimeGroups().get(mimeGroup); 6169 if (existingMimeTypes == null) { 6170 throw new IllegalArgumentException("Unknown MIME group " + mimeGroup 6171 + " for package " + packageName); 6172 } 6173 if (existingMimeTypes.size() == mimeTypes.size() 6174 && existingMimeTypes.containsAll(mimeTypes)) { 6175 return; 6176 } 6177 if (mimeTypes.size() > 500) { 6178 throw new IllegalStateException("Max limit on MIME types for MIME group " 6179 + mimeGroup + " exceeded for package " + packageName); 6180 } 6181 6182 ArraySet<String> mimeTypesSet = new ArraySet<>(mimeTypes); 6183 commitPackageStateMutation(null, packageName, packageStateWrite -> { 6184 packageStateWrite.setMimeGroup(mimeGroup, mimeTypesSet); 6185 }); 6186 if (mComponentResolver.updateMimeGroup(snapshotComputer(), packageName, mimeGroup)) { 6187 Binder.withCleanCallingIdentity(() -> 6188 mPreferredActivityHelper.clearPackagePreferredActivities(packageName, 6189 UserHandle.USER_ALL)); 6190 } 6191 6192 scheduleWriteSettings(); 6193 } 6194 6195 @Override 6196 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 6197 PackageManagerService.this 6198 .setPackageStoppedState(snapshotComputer(), packageName, stopped, userId); 6199 } 6200 6201 @Override 6202 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 6203 PersistableBundle appExtras, PersistableBundle launcherExtras, 6204 SuspendDialogInfo dialogInfo, String callingPackage, int userId) { 6205 final int callingUid = Binder.getCallingUid(); 6206 final Computer snapshot = snapshotComputer(); 6207 enforceCanSetPackagesSuspendedAsUser(snapshot, callingPackage, callingUid, userId, 6208 "setPackagesSuspendedAsUser"); 6209 return mSuspendPackageHelper.setPackagesSuspended(snapshot, packageNames, suspended, 6210 appExtras, launcherExtras, dialogInfo, callingPackage, userId, callingUid, 6211 false /* forQuietMode */); 6212 } 6213 6214 @Override 6215 public boolean setRequiredForSystemUser(String packageName, boolean requiredForSystemUser) { 6216 PackageManagerServiceUtils.enforceSystemOrRoot( 6217 "setRequiredForSystemUser can only be run by the system or root"); 6218 6219 PackageStateMutator.Result result = commitPackageStateMutation(null, packageName, 6220 packageState -> packageState.setRequiredForSystemUser(requiredForSystemUser)); 6221 if (!result.isCommitted()) { 6222 return false; 6223 } 6224 6225 scheduleWriteSettings(); 6226 return true; 6227 } 6228 6229 @android.annotation.EnforcePermission(android.Manifest.permission.INSTALL_PACKAGES) 6230 @Override 6231 public void setUserMinAspectRatio(@NonNull String packageName, int userId, 6232 @PackageManager.UserMinAspectRatio int aspectRatio) { 6233 setUserMinAspectRatio_enforcePermission(); 6234 final int callingUid = Binder.getCallingUid(); 6235 final Computer snapshot = snapshotComputer(); 6236 snapshot.enforceCrossUserPermission(callingUid, userId, 6237 false /* requireFullPermission */, false /* checkShell */, 6238 "setUserMinAspectRatio"); 6239 enforceOwnerRights(snapshot, packageName, callingUid); 6240 6241 final PackageStateInternal packageState = snapshot 6242 .getPackageStateForInstalledAndFiltered(packageName, callingUid, userId); 6243 if (packageState == null) { 6244 return; 6245 } 6246 6247 if (packageState.getUserStateOrDefault(userId).getMinAspectRatio() == aspectRatio) { 6248 return; 6249 } 6250 6251 commitPackageStateMutation(null, packageName, state -> 6252 state.userState(userId).setMinAspectRatio(aspectRatio)); 6253 } 6254 6255 @Override 6256 @SuppressWarnings("GuardedBy") 6257 public void setRuntimePermissionsVersion(int version, @UserIdInt int userId) { 6258 Preconditions.checkArgumentNonnegative(version); 6259 Preconditions.checkArgumentNonnegative(userId); 6260 enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions( 6261 "setRuntimePermissionVersion"); 6262 mSettings.setDefaultRuntimePermissionsVersion(version, userId); 6263 } 6264 6265 @Override 6266 public void setSplashScreenTheme(@NonNull String packageName, @Nullable String themeId, 6267 int userId) { 6268 final int callingUid = Binder.getCallingUid(); 6269 final Computer snapshot = snapshotComputer(); 6270 snapshot.enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 6271 false /* checkShell */, "setSplashScreenTheme"); 6272 enforceOwnerRights(snapshot, packageName, callingUid); 6273 6274 PackageStateInternal packageState = snapshot.getPackageStateForInstalledAndFiltered( 6275 packageName, callingUid, userId); 6276 if (packageState == null) { 6277 return; 6278 } 6279 6280 commitPackageStateMutation(null, packageName, state -> 6281 state.userState(userId).setSplashScreenTheme(themeId)); 6282 } 6283 6284 @Override 6285 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 6286 mContext.enforceCallingOrSelfPermission(Manifest.permission.INSTALL_PACKAGES, null); 6287 commitPackageStateMutation(null, packageName, state -> 6288 state.setUpdateAvailable(updateAvailable)); 6289 } 6290 6291 @Override 6292 public void unregisterMoveCallback(IPackageMoveObserver callback) { 6293 mContext.enforceCallingOrSelfPermission( 6294 Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 6295 mMoveCallbacks.unregister(callback); 6296 } 6297 6298 @Override 6299 public void verifyPendingInstall(int verificationId, int verificationCode) 6300 throws RemoteException { 6301 // Negative ids correspond to testing verifiers and will be silently enforced in 6302 // the handler thread. 6303 if (verificationId >= 0) { 6304 mContext.enforceCallingOrSelfPermission( 6305 Manifest.permission.PACKAGE_VERIFICATION_AGENT, 6306 "Only package verification agents can verify applications"); 6307 } 6308 final int callingUid = Binder.getCallingUid(); 6309 6310 mHandler.post(() -> { 6311 final int id = verificationId >= 0 ? verificationId : -verificationId; 6312 final PackageVerificationState state = mPendingVerification.get(id); 6313 if (state == null) { 6314 return; 6315 } 6316 if (!state.checkRequiredVerifierUid(callingUid) 6317 && !state.checkSufficientVerifierUid(callingUid)) { 6318 // Only allow calls from verifiers. 6319 return; 6320 } 6321 6322 final Message msg = mHandler.obtainMessage(PackageManagerService.PACKAGE_VERIFIED); 6323 final PackageVerificationResponse response = new PackageVerificationResponse( 6324 verificationCode, callingUid); 6325 msg.arg1 = id; 6326 msg.obj = response; 6327 mHandler.sendMessage(msg); 6328 }); 6329 } 6330 6331 @Override 6332 public void requestPackageChecksums(@NonNull String packageName, boolean includeSplits, 6333 @Checksum.TypeMask int optional, @Checksum.TypeMask int required, 6334 @Nullable List trustedInstallers, 6335 @NonNull IOnChecksumsReadyListener onChecksumsReadyListener, int userId) { 6336 requestChecksumsInternal(snapshotComputer(), packageName, includeSplits, optional, 6337 required, trustedInstallers, onChecksumsReadyListener, userId, 6338 mInjector.getBackgroundExecutor(), mInjector.getBackgroundHandler()); 6339 } 6340 6341 @Override 6342 public void notifyPackagesReplacedReceived(String[] packages) { 6343 Computer computer = snapshotComputer(); 6344 ArraySet<String> packagesToNotify = computer.getNotifyPackagesForReplacedReceived(packages); 6345 for (int index = 0; index < packagesToNotify.size(); index++) { 6346 notifyInstallObserver(packagesToNotify.valueAt(index), false /* killApp */); 6347 } 6348 } 6349 6350 /** 6351 * Wait for the handler to finish handling all pending messages. 6352 * @param timeoutMillis Maximum time in milliseconds to wait. 6353 * @param forBackgroundHandler Whether to wait for the background handler instead. 6354 * @return True if all the waiting messages in the handler has been handled. 6355 * False if timeout. 6356 */ 6357 @Override 6358 public boolean waitForHandler(long timeoutMillis, boolean forBackgroundHandler) { 6359 final CountDownLatch latch = new CountDownLatch(1); 6360 if (forBackgroundHandler) { 6361 mBackgroundHandler.post(latch::countDown); 6362 } else { 6363 mHandler.post(latch::countDown); 6364 } 6365 final long endTimeMillis = System.currentTimeMillis() + timeoutMillis; 6366 while (latch.getCount() > 0) { 6367 try { 6368 final long remainingTimeMillis = endTimeMillis - System.currentTimeMillis(); 6369 if (remainingTimeMillis <= 0) { 6370 return false; 6371 } 6372 return latch.await(remainingTimeMillis, TimeUnit.MILLISECONDS); 6373 } catch (InterruptedException e) { 6374 // ignore and retry 6375 } 6376 } 6377 return true; 6378 } 6379 6380 @Override 6381 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 6382 throws RemoteException { 6383 try { 6384 return super.onTransact(code, data, reply, flags); 6385 } catch (RuntimeException e) { 6386 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException) 6387 && !(e instanceof ParcelableException)) { 6388 Slog.wtf(TAG, "Package Manager Unexpected Exception", e); 6389 } 6390 throw e; 6391 } 6392 } 6393 6394 @Override 6395 public void onShellCommand(FileDescriptor in, FileDescriptor out, 6396 FileDescriptor err, String[] args, ShellCallback callback, 6397 ResultReceiver resultReceiver) { 6398 (new PackageManagerShellCommand(this, mContext, 6399 mDomainVerificationManager.getShell())) 6400 .exec(this, in, out, err, args, callback, resultReceiver); 6401 } 6402 6403 @SuppressWarnings("resource") 6404 @Override 6405 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 6406 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 6407 final Computer snapshot = snapshotComputer(); 6408 final KnownPackages knownPackages = new KnownPackages( 6409 mDefaultAppProvider, 6410 mRequiredInstallerPackage, 6411 mRequiredUninstallerPackage, 6412 mSetupWizardPackage, 6413 mRequiredVerifierPackages, 6414 mDefaultTextClassifierPackage, 6415 mSystemTextClassifierPackageName, 6416 mRequiredPermissionControllerPackage, 6417 mConfiguratorPackage, 6418 mIncidentReportApproverPackage, 6419 mAmbientContextDetectionPackage, 6420 mWearableSensingPackage, 6421 mAppPredictionServicePackage, 6422 COMPANION_PACKAGE_NAME, 6423 mRetailDemoPackage, 6424 mOverlayConfigSignaturePackage, 6425 mRecentsPackage); 6426 final ArrayMap<String, FeatureInfo> availableFeatures; 6427 synchronized (mAvailableFeatures) { 6428 availableFeatures = new ArrayMap<>(mAvailableFeatures); 6429 } 6430 final ArraySet<String> protectedBroadcasts; 6431 synchronized (mProtectedBroadcasts) { 6432 protectedBroadcasts = new ArraySet<>(mProtectedBroadcasts); 6433 } 6434 new DumpHelper(mPermissionManager, mStorageEventHelper, 6435 mDomainVerificationManager, mInstallerService, mRequiredVerifierPackages, 6436 knownPackages, mChangedPackagesTracker, availableFeatures, protectedBroadcasts, 6437 getPerUidReadTimeouts(snapshot), mSnapshotStatistics 6438 ).doDump(snapshot, fd, pw, args); 6439 } 6440 } 6441 6442 private class PackageManagerInternalImpl extends PackageManagerInternalBase { 6443 6444 public PackageManagerInternalImpl() { 6445 super(PackageManagerService.this); 6446 } 6447 6448 @NonNull 6449 @Override 6450 protected Context getContext() { 6451 return mContext; 6452 } 6453 6454 @NonNull 6455 @Override 6456 protected PermissionManagerServiceInternal getPermissionManager() { 6457 return mPermissionManager; 6458 } 6459 6460 @NonNull 6461 @Override 6462 protected AppDataHelper getAppDataHelper() { 6463 return mAppDataHelper; 6464 } 6465 6466 @NonNull 6467 @Override 6468 protected PackageObserverHelper getPackageObserverHelper() { 6469 return mPackageObserverHelper; 6470 } 6471 6472 @NonNull 6473 @Override 6474 protected ResolveIntentHelper getResolveIntentHelper() { 6475 return mResolveIntentHelper; 6476 } 6477 6478 @NonNull 6479 @Override 6480 protected SuspendPackageHelper getSuspendPackageHelper() { 6481 return mSuspendPackageHelper; 6482 } 6483 6484 @NonNull 6485 @Override 6486 protected DistractingPackageHelper getDistractingPackageHelper() { 6487 return mDistractingPackageHelper; 6488 } 6489 6490 @NonNull 6491 @Override 6492 protected ProtectedPackages getProtectedPackages() { 6493 return mProtectedPackages; 6494 } 6495 6496 @NonNull 6497 @Override 6498 protected UserNeedsBadgingCache getUserNeedsBadging() { 6499 return mUserNeedsBadging; 6500 } 6501 6502 @NonNull 6503 @Override 6504 protected InstantAppRegistry getInstantAppRegistry() { 6505 return mInstantAppRegistry; 6506 } 6507 6508 @NonNull 6509 @Override 6510 protected ApexManager getApexManager() { 6511 return mApexManager; 6512 } 6513 6514 @NonNull 6515 @Override 6516 protected DexManager getDexManager() { 6517 return mDexManager; 6518 } 6519 6520 @NonNull 6521 @Override 6522 public DynamicCodeLogger getDynamicCodeLogger() { 6523 return mDynamicCodeLogger; 6524 } 6525 6526 @Override 6527 public boolean isPlatformSigned(String packageName) { 6528 PackageStateInternal packageState = snapshot().getPackageStateInternal(packageName); 6529 if (packageState == null) { 6530 return false; 6531 } 6532 SigningDetails signingDetails = packageState.getSigningDetails(); 6533 return signingDetails.hasAncestorOrSelf(mPlatformPackage.getSigningDetails()) 6534 || mPlatformPackage.getSigningDetails().checkCapability(signingDetails, 6535 SigningDetails.CertCapabilities.PERMISSION); 6536 } 6537 6538 @Override 6539 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 6540 final Computer snapshot = snapshot(); 6541 SigningDetails sd = snapshot.getSigningDetails(packageName); 6542 if (sd == null) { 6543 return false; 6544 } 6545 return sd.hasSha256Certificate(restoringFromSigHash, 6546 SigningDetails.CertCapabilities.INSTALLED_DATA); 6547 } 6548 6549 @Override 6550 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 6551 final Computer snapshot = snapshot(); 6552 SigningDetails sd = snapshot.getSigningDetails(packageName); 6553 if (sd == null) { 6554 return false; 6555 } 6556 return sd.hasCertificate(restoringFromSig, 6557 SigningDetails.CertCapabilities.INSTALLED_DATA); 6558 } 6559 6560 @Override 6561 public boolean hasSignatureCapability(int serverUid, int clientUid, 6562 @SigningDetails.CertCapabilities int capability) { 6563 final Computer snapshot = snapshot(); 6564 SigningDetails serverSigningDetails = snapshot.getSigningDetails(serverUid); 6565 SigningDetails clientSigningDetails = snapshot.getSigningDetails(clientUid); 6566 return serverSigningDetails.checkCapability(clientSigningDetails, capability) 6567 || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails); 6568 } 6569 6570 @Override 6571 public PackageList getPackageList(@Nullable PackageListObserver observer) { 6572 final ArrayList<String> list = new ArrayList<>(); 6573 PackageManagerService.this.forEachPackageState(snapshot(), packageState -> { 6574 AndroidPackage pkg = packageState.getPkg(); 6575 if (pkg != null) { 6576 list.add(pkg.getPackageName()); 6577 } 6578 }); 6579 final PackageList packageList = new PackageList(list, observer); 6580 if (observer != null) { 6581 mPackageObserverHelper.addObserver(packageList); 6582 } 6583 return packageList; 6584 } 6585 6586 @Override 6587 public @Nullable 6588 String getDisabledSystemPackageName(@NonNull String packageName) { 6589 PackageStateInternal disabledPkgSetting = snapshot().getDisabledSystemPackage( 6590 packageName); 6591 AndroidPackage disabledPkg = disabledPkgSetting == null 6592 ? null : disabledPkgSetting.getPkg(); 6593 return disabledPkg == null ? null : disabledPkg.getPackageName(); 6594 } 6595 6596 @Override 6597 public boolean isResolveActivityComponent(ComponentInfo component) { 6598 return mResolveActivity.packageName.equals(component.packageName) 6599 && mResolveActivity.name.equals(component.name); 6600 } 6601 6602 @Override 6603 public long getCeDataInode(String packageName, int userId) { 6604 final PackageStateInternal packageState = 6605 snapshot().getPackageStateInternal(packageName); 6606 if (packageState == null) { 6607 return 0; 6608 } else { 6609 return packageState.getUserStateOrDefault(userId).getCeDataInode(); 6610 } 6611 } 6612 6613 @Override 6614 public void removeAllNonSystemPackageSuspensions(int userId) { 6615 final Computer computer = snapshotComputer(); 6616 final String[] allPackages = computer.getAllAvailablePackageNames(); 6617 mSuspendPackageHelper.removeSuspensionsBySuspendingPackage(computer, allPackages, 6618 (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage), 6619 userId); 6620 } 6621 6622 @Override 6623 public void flushPackageRestrictions(int userId) { 6624 synchronized (mLock) { 6625 PackageManagerService.this.flushPackageRestrictionsAsUserInternalLocked(userId); 6626 } 6627 } 6628 6629 @Override 6630 public String[] setPackagesSuspendedByAdmin( 6631 @UserIdInt int userId, @NonNull String[] packageNames, boolean suspended) { 6632 return mSuspendPackageHelper.setPackagesSuspendedByAdmin( 6633 snapshotComputer(), userId, packageNames, suspended); 6634 } 6635 6636 @Override 6637 public void setPackagesSuspendedForQuietMode(int userId, boolean suspended) { 6638 mSuspendPackageHelper.setPackagesSuspendedForQuietMode( 6639 snapshotComputer(), userId, suspended); 6640 } 6641 6642 @Override 6643 public void setDeviceAndProfileOwnerPackages( 6644 int deviceOwnerUserId, String deviceOwnerPackage, 6645 SparseArray<String> profileOwnerPackages) { 6646 mProtectedPackages.setDeviceAndProfileOwnerPackages( 6647 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 6648 final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>(); 6649 if (deviceOwnerPackage != null) { 6650 usersWithPoOrDo.add(deviceOwnerUserId); 6651 } 6652 final int sz = profileOwnerPackages.size(); 6653 for (int i = 0; i < sz; i++) { 6654 if (profileOwnerPackages.valueAt(i) != null) { 6655 removeAllNonSystemPackageSuspensions(profileOwnerPackages.keyAt(i)); 6656 } 6657 } 6658 } 6659 6660 @Override 6661 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 6662 if (policy != null) { 6663 mExternalSourcesPolicy = policy; 6664 } 6665 } 6666 6667 @Override 6668 public boolean isPackagePersistent(String packageName) { 6669 final PackageStateInternal packageState = 6670 snapshot().getPackageStateInternal(packageName); 6671 if (packageState == null) { 6672 return false; 6673 } 6674 6675 AndroidPackage pkg = packageState.getPkg(); 6676 return pkg != null && packageState.isSystem() && pkg.isPersistent(); 6677 } 6678 6679 @Override 6680 public List<PackageInfo> getOverlayPackages(int userId) { 6681 final Computer snapshot = snapshotComputer(); 6682 final ArrayList<PackageInfo> overlayPackages = new ArrayList<>(); 6683 final ArrayMap<String, ? extends PackageStateInternal> packageStates = 6684 snapshot.getPackageStates(); 6685 for (int index = 0; index < packageStates.size(); index++) { 6686 final PackageStateInternal packageState = packageStates.valueAt(index); 6687 final AndroidPackage pkg = packageState.getPkg(); 6688 if (pkg != null && pkg.getOverlayTarget() != null) { 6689 PackageInfo pkgInfo = snapshot.generatePackageInfo(packageState, 0, userId); 6690 if (pkgInfo != null) { 6691 overlayPackages.add(pkgInfo); 6692 } 6693 } 6694 } 6695 6696 return overlayPackages; 6697 } 6698 6699 @Override 6700 public List<String> getTargetPackageNames(int userId) { 6701 List<String> targetPackages = new ArrayList<>(); 6702 PackageManagerService.this.forEachPackageState(snapshot(), packageState -> { 6703 final AndroidPackage pkg = packageState.getPkg(); 6704 if (pkg != null && !pkg.isResourceOverlay()) { 6705 targetPackages.add(pkg.getPackageName()); 6706 } 6707 }); 6708 return targetPackages; 6709 } 6710 6711 @Override 6712 public void setEnabledOverlayPackages(int userId, 6713 @NonNull ArrayMap<String, OverlayPaths> pendingChanges, 6714 @NonNull Set<String> outUpdatedPackageNames, 6715 @NonNull Set<String> outInvalidPackageNames) { 6716 PackageManagerService.this.setEnabledOverlayPackages(userId, 6717 pendingChanges, outUpdatedPackageNames, outInvalidPackageNames); 6718 } 6719 6720 @Override 6721 public void addIsolatedUid(int isolatedUid, int ownerUid) { 6722 synchronized (mLock) { 6723 mIsolatedOwners.put(isolatedUid, ownerUid); 6724 } 6725 } 6726 6727 @Override 6728 public void removeIsolatedUid(int isolatedUid) { 6729 synchronized (mLock) { 6730 mIsolatedOwners.delete(isolatedUid); 6731 } 6732 } 6733 6734 @Override 6735 public void notifyPackageUse(String packageName, int reason) { 6736 synchronized (mLock) { 6737 PackageManagerService.this.notifyPackageUseInternal(packageName, reason); 6738 } 6739 } 6740 6741 @Nullable 6742 @Override 6743 public String removeLegacyDefaultBrowserPackageName(int userId) { 6744 synchronized (mLock) { 6745 return mSettings.removePendingDefaultBrowserLPw(userId); 6746 } 6747 } 6748 6749 @Override 6750 public void uninstallApex(String packageName, long versionCode, int userId, 6751 IntentSender intentSender, int flags) { 6752 final int callerUid = Binder.getCallingUid(); 6753 if (!PackageManagerServiceUtils.isRootOrShell(callerUid)) { 6754 throw new SecurityException("Not allowed to uninstall apexes"); 6755 } 6756 PackageInstallerService.PackageDeleteObserverAdapter adapter = 6757 new PackageInstallerService.PackageDeleteObserverAdapter( 6758 PackageManagerService.this.mContext, intentSender, packageName, 6759 false, userId); 6760 if ((flags & PackageManager.DELETE_ALL_USERS) == 0) { 6761 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 6762 "Can't uninstall an apex for a single user"); 6763 return; 6764 } 6765 final ApexManager am = PackageManagerService.this.mApexManager; 6766 PackageInfo activePackage = snapshot().getPackageInfo( 6767 packageName, PackageManager.MATCH_APEX, UserHandle.USER_SYSTEM); 6768 if (activePackage == null) { 6769 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 6770 packageName + " is not an apex package"); 6771 return; 6772 } 6773 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 6774 && activePackage.getLongVersionCode() != versionCode) { 6775 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 6776 "Active version " + activePackage.getLongVersionCode() 6777 + " is not equal to " + versionCode + "]"); 6778 return; 6779 } 6780 if (!am.uninstallApex(activePackage.applicationInfo.sourceDir)) { 6781 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 6782 "Failed to uninstall apex " + packageName); 6783 } else { 6784 adapter.onPackageDeleted(packageName, PackageManager.DELETE_SUCCEEDED, 6785 null); 6786 } 6787 } 6788 6789 /** @deprecated For legacy shell command only. */ 6790 @Override 6791 @Deprecated 6792 public void legacyDumpProfiles(String packageName, boolean dumpClassesAndMethods) 6793 throws LegacyDexoptDisabledException { 6794 final Computer snapshot = snapshotComputer(); 6795 AndroidPackage pkg = snapshot.getPackage(packageName); 6796 if (pkg == null) { 6797 throw new IllegalArgumentException("Unknown package: " + packageName); 6798 } 6799 6800 synchronized (mInstallLock) { 6801 Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "dump profiles"); 6802 mArtManagerService.dumpProfiles(pkg, dumpClassesAndMethods); 6803 Trace.traceEnd(Trace.TRACE_TAG_DALVIK); 6804 } 6805 } 6806 6807 /** @deprecated For legacy shell command only. */ 6808 @Override 6809 @Deprecated 6810 public void legacyForceDexOpt(String packageName) throws LegacyDexoptDisabledException { 6811 mDexOptHelper.forceDexOpt(snapshotComputer(), packageName); 6812 } 6813 6814 /** @deprecated For legacy shell command only. */ 6815 @Override 6816 @Deprecated 6817 public void legacyReconcileSecondaryDexFiles(String packageName) 6818 throws LegacyDexoptDisabledException { 6819 final Computer snapshot = snapshotComputer(); 6820 if (snapshot.getInstantAppPackageName(Binder.getCallingUid()) != null) { 6821 return; 6822 } else if (snapshot.isInstantAppInternal( 6823 packageName, UserHandle.getCallingUserId(), Process.SYSTEM_UID)) { 6824 return; 6825 } 6826 mDexManager.reconcileSecondaryDexFiles(packageName); 6827 } 6828 6829 @Override 6830 @SuppressWarnings("GuardedBy") 6831 public void updateRuntimePermissionsFingerprint(@UserIdInt int userId) { 6832 mSettings.updateRuntimePermissionsFingerprint(userId); 6833 } 6834 6835 @Override 6836 public void migrateLegacyObbData() { 6837 try { 6838 mInstaller.migrateLegacyObbData(); 6839 } catch (Exception e) { 6840 Slog.wtf(TAG, e); 6841 } 6842 } 6843 6844 @Override 6845 public void writeSettings(boolean async) { 6846 synchronized (mLock) { 6847 if (async) { 6848 scheduleWriteSettings(); 6849 } else { 6850 writeSettingsLPrTEMP(); 6851 } 6852 } 6853 } 6854 6855 @Override 6856 public void writePermissionSettings(int[] userIds, boolean async) { 6857 synchronized (mLock) { 6858 for (int userId : userIds) { 6859 mSettings.writePermissionStateForUserLPr(userId, !async); 6860 } 6861 } 6862 } 6863 6864 @Override 6865 @SuppressWarnings("GuardedBy") 6866 public boolean isPermissionUpgradeNeeded(int userId) { 6867 return mSettings.isPermissionUpgradeNeeded(userId); 6868 } 6869 6870 @Override 6871 public void setIntegrityVerificationResult(int verificationId, int verificationResult) { 6872 final Message msg = mHandler.obtainMessage(INTEGRITY_VERIFICATION_COMPLETE); 6873 msg.arg1 = verificationId; 6874 msg.obj = verificationResult; 6875 mHandler.sendMessage(msg); 6876 } 6877 6878 @Override 6879 public void setVisibilityLogging(String packageName, boolean enable) { 6880 PackageManagerServiceUtils.enforceSystemOrRootOrShell( 6881 "Only the system or shell can set visibility logging."); 6882 final PackageStateInternal packageState = 6883 snapshot().getPackageStateInternal(packageName); 6884 if (packageState == null) { 6885 throw new IllegalStateException("No package found for " + packageName); 6886 } 6887 mAppsFilter.getFeatureConfig().enableLogging(packageState.getAppId(), enable); 6888 } 6889 6890 @Override 6891 public void clearBlockUninstallForUser(@UserIdInt int userId) { 6892 synchronized (mLock) { 6893 mSettings.clearBlockUninstallLPw(userId); 6894 mSettings.writePackageRestrictionsLPr(userId); 6895 } 6896 } 6897 6898 @Override 6899 public boolean registerInstalledLoadingProgressCallback(String packageName, 6900 PackageManagerInternal.InstalledLoadingProgressCallback callback, int userId) { 6901 final Computer snapshot = snapshotComputer(); 6902 final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered( 6903 packageName, Binder.getCallingUid(), userId); 6904 if (ps == null) { 6905 return false; 6906 } 6907 if (!ps.isLoading()) { 6908 Slog.w(TAG, 6909 "Failed registering loading progress callback. Package is fully loaded."); 6910 return false; 6911 } 6912 if (mIncrementalManager == null) { 6913 Slog.w(TAG, 6914 "Failed registering loading progress callback. Incremental is not enabled"); 6915 return false; 6916 } 6917 return mIncrementalManager.registerLoadingProgressCallback(ps.getPathString(), 6918 (IPackageLoadingProgressCallback) callback.getBinder()); 6919 } 6920 6921 @Override 6922 public IncrementalStatesInfo getIncrementalStatesInfo( 6923 @NonNull String packageName, int filterCallingUid, int userId) { 6924 final Computer snapshot = snapshotComputer(); 6925 final PackageStateInternal ps = snapshot.getPackageStateForInstalledAndFiltered( 6926 packageName, filterCallingUid, userId); 6927 if (ps == null) { 6928 return null; 6929 } 6930 return new IncrementalStatesInfo(ps.isLoading(), ps.getLoadingProgress(), 6931 ps.getLoadingCompletedTime()); 6932 } 6933 6934 @Override 6935 public boolean isSameApp(@Nullable String packageName, int callingUid, int userId) { 6936 return isSameApp(packageName, /*flags=*/0, callingUid, userId); 6937 } 6938 6939 @Override 6940 public boolean isSameApp(@Nullable String packageName, 6941 @PackageManager.PackageInfoFlagsBits long flags, int callingUid, int userId) { 6942 if (packageName == null) { 6943 return false; 6944 } 6945 6946 if (Process.isSdkSandboxUid(callingUid)) { 6947 return packageName.equals(mRequiredSdkSandboxPackage); 6948 } 6949 Computer snapshot = snapshot(); 6950 int uid = snapshot.getPackageUid(packageName, flags, userId); 6951 return UserHandle.isSameApp(uid, callingUid); 6952 } 6953 6954 @Override 6955 public void onPackageProcessKilledForUninstall(String packageName) { 6956 mHandler.post(() -> PackageManagerService.this.notifyInstallObserver(packageName, 6957 true /* killApp */)); 6958 } 6959 } 6960 6961 private void setEnabledOverlayPackages(@UserIdInt int userId, 6962 @NonNull ArrayMap<String, OverlayPaths> pendingChanges, 6963 @NonNull Set<String> outUpdatedPackageNames, 6964 @NonNull Set<String> outInvalidPackageNames) { 6965 final ArrayMap<String, ArrayMap<String, ArraySet<String>>> 6966 targetPkgToLibNameToModifiedDependents = new ArrayMap<>(); 6967 final int numberOfPendingChanges = pendingChanges.size(); 6968 6969 synchronized (mOverlayPathsLock) { 6970 Computer computer = snapshotComputer(); 6971 for (int i = 0; i < numberOfPendingChanges; i++) { 6972 final String targetPackageName = pendingChanges.keyAt(i); 6973 final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i); 6974 final PackageStateInternal packageState = computer.getPackageStateInternal( 6975 targetPackageName); 6976 final AndroidPackage targetPkg = 6977 packageState == null ? null : packageState.getPkg(); 6978 if (targetPackageName == null || targetPkg == null) { 6979 Slog.e(TAG, "failed to find package " + targetPackageName); 6980 outInvalidPackageNames.add(targetPackageName); 6981 continue; 6982 } 6983 6984 if (Objects.equals(packageState.getUserStateOrDefault(userId).getOverlayPaths(), 6985 newOverlayPaths)) { 6986 continue; 6987 } 6988 6989 if (targetPkg.getLibraryNames() != null) { 6990 // Set the overlay paths for dependencies of the shared library. 6991 for (final String libName : targetPkg.getLibraryNames()) { 6992 ArraySet<String> modifiedDependents = null; 6993 6994 final SharedLibraryInfo info = computer.getSharedLibraryInfo(libName, 6995 SharedLibraryInfo.VERSION_UNDEFINED); 6996 if (info == null) { 6997 continue; 6998 } 6999 final List<VersionedPackage> dependents = 7000 computer.getPackagesUsingSharedLibrary(info, 0, Process.SYSTEM_UID, 7001 userId); 7002 if (dependents == null) { 7003 continue; 7004 } 7005 for (final VersionedPackage dependent : dependents) { 7006 final PackageStateInternal dependentState = 7007 computer.getPackageStateInternal(dependent.getPackageName()); 7008 if (dependentState == null) { 7009 continue; 7010 } 7011 if (canSetOverlayPaths(dependentState.getUserStateOrDefault(userId) 7012 .getSharedLibraryOverlayPaths() 7013 .get(libName), newOverlayPaths)) { 7014 String dependentPackageName = dependent.getPackageName(); 7015 modifiedDependents = ArrayUtils.add(modifiedDependents, 7016 dependentPackageName); 7017 outUpdatedPackageNames.add(dependentPackageName); 7018 } 7019 } 7020 7021 if (modifiedDependents != null) { 7022 ArrayMap<String, ArraySet<String>> libNameToModifiedDependents = 7023 targetPkgToLibNameToModifiedDependents.get( 7024 targetPackageName); 7025 if (libNameToModifiedDependents == null) { 7026 libNameToModifiedDependents = new ArrayMap<>(); 7027 targetPkgToLibNameToModifiedDependents.put(targetPackageName, 7028 libNameToModifiedDependents); 7029 } 7030 libNameToModifiedDependents.put(libName, modifiedDependents); 7031 } 7032 } 7033 } 7034 7035 if (canSetOverlayPaths(packageState.getUserStateOrDefault(userId).getOverlayPaths(), 7036 newOverlayPaths)) { 7037 outUpdatedPackageNames.add(targetPackageName); 7038 } 7039 } 7040 7041 commitPackageStateMutation(null, mutator -> { 7042 for (int i = 0; i < numberOfPendingChanges; i++) { 7043 final String targetPackageName = pendingChanges.keyAt(i); 7044 final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i); 7045 7046 if (!outUpdatedPackageNames.contains(targetPackageName)) { 7047 continue; 7048 } 7049 7050 mutator.forPackage(targetPackageName) 7051 .userState(userId) 7052 .setOverlayPaths(newOverlayPaths); 7053 7054 final ArrayMap<String, ArraySet<String>> libNameToModifiedDependents = 7055 targetPkgToLibNameToModifiedDependents.get( 7056 targetPackageName); 7057 if (libNameToModifiedDependents == null) { 7058 continue; 7059 } 7060 7061 for (int mapIndex = 0; mapIndex < libNameToModifiedDependents.size(); 7062 mapIndex++) { 7063 String libName = libNameToModifiedDependents.keyAt(mapIndex); 7064 ArraySet<String> modifiedDependents = 7065 libNameToModifiedDependents.valueAt(mapIndex); 7066 for (int setIndex = 0; setIndex < modifiedDependents.size(); setIndex++) { 7067 mutator.forPackage(modifiedDependents.valueAt(setIndex)) 7068 .userState(userId) 7069 .setOverlayPathsForLibrary(libName, newOverlayPaths); 7070 } 7071 } 7072 } 7073 }); 7074 } 7075 7076 if (userId == UserHandle.USER_SYSTEM) { 7077 // Keep the overlays in the system application info (and anything special cased as well) 7078 // up to date to make sure system ui is themed correctly. 7079 for (int i = 0; i < numberOfPendingChanges; i++) { 7080 final String targetPackageName = pendingChanges.keyAt(i); 7081 final OverlayPaths newOverlayPaths = pendingChanges.valueAt(i); 7082 maybeUpdateSystemOverlays(targetPackageName, newOverlayPaths); 7083 } 7084 } 7085 7086 invalidatePackageInfoCache(); 7087 } 7088 7089 private boolean canSetOverlayPaths(OverlayPaths origPaths, OverlayPaths newPaths) { 7090 if (Objects.equals(origPaths, newPaths)) { 7091 return false; 7092 } 7093 if ((origPaths == null && newPaths.isEmpty()) 7094 || (newPaths == null && origPaths.isEmpty())) { 7095 return false; 7096 } 7097 return true; 7098 } 7099 7100 private void maybeUpdateSystemOverlays(String targetPackageName, OverlayPaths newOverlayPaths) { 7101 if (!mResolverReplaced) { 7102 if (targetPackageName.equals("android")) { 7103 if (newOverlayPaths == null) { 7104 mPlatformPackageOverlayPaths = null; 7105 mPlatformPackageOverlayResourceDirs = null; 7106 } else { 7107 mPlatformPackageOverlayPaths = newOverlayPaths.getOverlayPaths().toArray( 7108 new String[0]); 7109 mPlatformPackageOverlayResourceDirs = newOverlayPaths.getResourceDirs().toArray( 7110 new String[0]); 7111 } 7112 applyUpdatedSystemOverlayPaths(); 7113 } 7114 } else { 7115 if (targetPackageName.equals(mResolveActivity.applicationInfo.packageName)) { 7116 if (newOverlayPaths == null) { 7117 mReplacedResolverPackageOverlayPaths = null; 7118 mReplacedResolverPackageOverlayResourceDirs = null; 7119 } else { 7120 mReplacedResolverPackageOverlayPaths = 7121 newOverlayPaths.getOverlayPaths().toArray(new String[0]); 7122 mReplacedResolverPackageOverlayResourceDirs = 7123 newOverlayPaths.getResourceDirs().toArray(new String[0]); 7124 } 7125 applyUpdatedSystemOverlayPaths(); 7126 } 7127 } 7128 } 7129 7130 private void applyUpdatedSystemOverlayPaths() { 7131 if (mAndroidApplication == null) { 7132 Slog.i(TAG, "Skipped the AndroidApplication overlay paths update - no app yet"); 7133 } else { 7134 mAndroidApplication.overlayPaths = mPlatformPackageOverlayPaths; 7135 mAndroidApplication.resourceDirs = mPlatformPackageOverlayResourceDirs; 7136 } 7137 if (mResolverReplaced) { 7138 mResolveActivity.applicationInfo.overlayPaths = mReplacedResolverPackageOverlayPaths; 7139 mResolveActivity.applicationInfo.resourceDirs = 7140 mReplacedResolverPackageOverlayResourceDirs; 7141 } 7142 } 7143 7144 private void enforceAdjustRuntimePermissionsPolicyOrUpgradeRuntimePermissions( 7145 @NonNull String message) { 7146 if (mContext.checkCallingOrSelfPermission( 7147 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY) 7148 != PackageManager.PERMISSION_GRANTED 7149 && mContext.checkCallingOrSelfPermission( 7150 Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS) 7151 != PackageManager.PERMISSION_GRANTED) { 7152 throw new SecurityException(message + " requires " 7153 + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY + " or " 7154 + Manifest.permission.UPGRADE_RUNTIME_PERMISSIONS); 7155 } 7156 } 7157 7158 // TODO: Remove 7159 @Deprecated 7160 @Nullable 7161 @GuardedBy("mLock") 7162 PackageSetting getPackageSettingForMutation(String packageName) { 7163 return mSettings.getPackageLPr(packageName); 7164 } 7165 7166 // TODO: Remove 7167 @Deprecated 7168 @Nullable 7169 @GuardedBy("mLock") 7170 PackageSetting getDisabledPackageSettingForMutation(String packageName) { 7171 return mSettings.getDisabledSystemPkgLPr(packageName); 7172 } 7173 7174 @Deprecated 7175 void forEachPackageSetting(Consumer<PackageSetting> actionLocked) { 7176 synchronized (mLock) { 7177 int size = mSettings.getPackagesLocked().size(); 7178 for (int index = 0; index < size; index++) { 7179 actionLocked.accept(mSettings.getPackagesLocked().valueAt(index)); 7180 } 7181 } 7182 } 7183 7184 void forEachPackageState(@NonNull Computer snapshot, Consumer<PackageStateInternal> consumer) { 7185 forEachPackageState(snapshot.getPackageStates(), consumer); 7186 } 7187 7188 void forEachPackage(@NonNull Computer snapshot, Consumer<AndroidPackage> consumer) { 7189 final ArrayMap<String, ? extends PackageStateInternal> packageStates = 7190 snapshot.getPackageStates(); 7191 int size = packageStates.size(); 7192 for (int index = 0; index < size; index++) { 7193 PackageStateInternal packageState = packageStates.valueAt(index); 7194 if (packageState.getPkg() != null) { 7195 consumer.accept(packageState.getPkg()); 7196 } 7197 } 7198 } 7199 7200 void forEachPackageInternal(@NonNull Computer snapshot, 7201 @NonNull Consumer<AndroidPackageInternal> consumer) { 7202 final ArrayMap<String, ? extends PackageStateInternal> packageStates = 7203 snapshot.getPackageStates(); 7204 int size = packageStates.size(); 7205 for (int index = 0; index < size; index++) { 7206 PackageStateInternal packageState = packageStates.valueAt(index); 7207 if (packageState.getPkg() != null) { 7208 consumer.accept(packageState.getPkg()); 7209 } 7210 } 7211 } 7212 7213 private void forEachPackageState( 7214 @NonNull ArrayMap<String, ? extends PackageStateInternal> packageStates, 7215 @NonNull Consumer<PackageStateInternal> consumer) { 7216 int size = packageStates.size(); 7217 for (int index = 0; index < size; index++) { 7218 PackageStateInternal packageState = packageStates.valueAt(index); 7219 consumer.accept(packageState); 7220 } 7221 } 7222 7223 void forEachInstalledPackage(@NonNull Computer snapshot, @NonNull Consumer<AndroidPackage> action, 7224 @UserIdInt int userId) { 7225 Consumer<PackageStateInternal> actionWrapped = packageState -> { 7226 if (packageState.getPkg() != null 7227 && packageState.getUserStateOrDefault(userId).isInstalled()) { 7228 action.accept(packageState.getPkg()); 7229 } 7230 }; 7231 forEachPackageState(snapshot.getPackageStates(), actionWrapped); 7232 } 7233 7234 boolean isHistoricalPackageUsageAvailable() { 7235 return mPackageUsage.isHistoricalPackageUsageAvailable(); 7236 } 7237 7238 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(AndroidPackage pkg) { 7239 return getOrCreateCompilerPackageStats(pkg.getPackageName()); 7240 } 7241 7242 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 7243 return mCompilerStats.getOrCreatePackageStats(pkgName); 7244 } 7245 7246 void grantImplicitAccess(@NonNull Computer snapshot, @UserIdInt int userId, 7247 Intent intent, @AppIdInt int recipientAppId, int visibleUid, boolean direct, 7248 boolean retainOnUpdate) { 7249 final AndroidPackage visiblePackage = snapshot.getPackage(visibleUid); 7250 final int recipientUid = UserHandle.getUid(userId, recipientAppId); 7251 if (visiblePackage == null || snapshot.getPackage(recipientUid) == null) { 7252 return; 7253 } 7254 7255 final boolean instantApp = snapshot.isInstantAppInternal( 7256 visiblePackage.getPackageName(), userId, visibleUid); 7257 final boolean accessGranted; 7258 if (instantApp) { 7259 if (!direct) { 7260 // if the interaction that lead to this granting access to an instant app 7261 // was indirect (i.e.: URI permission grant), do not actually execute the 7262 // grant. 7263 return; 7264 } 7265 accessGranted = mInstantAppRegistry.grantInstantAccess(userId, intent, 7266 recipientAppId, UserHandle.getAppId(visibleUid) /*instantAppId*/); 7267 } else { 7268 accessGranted = mAppsFilter.grantImplicitAccess(recipientUid, visibleUid, 7269 retainOnUpdate); 7270 } 7271 7272 if (accessGranted) { 7273 ApplicationPackageManager.invalidateGetPackagesForUidCache(); 7274 } 7275 } 7276 7277 boolean canHaveOatDir(@NonNull Computer snapshot, String packageName) { 7278 final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 7279 if (packageState == null || packageState.getPkg() == null) { 7280 return false; 7281 } 7282 return AndroidPackageUtils.canHaveOatDir(packageState, packageState.getPkg()); 7283 } 7284 7285 long deleteOatArtifactsOfPackage(@NonNull Computer snapshot, String packageName) { 7286 PackageManagerServiceUtils.enforceSystemOrRootOrShell( 7287 "Only the system or shell can delete oat artifacts"); 7288 7289 if (DexOptHelper.useArtService()) { 7290 // TODO(chiuwinson): Retrieve filtered snapshot from Computer instance instead. 7291 try (PackageManagerLocal.FilteredSnapshot filteredSnapshot = 7292 PackageManagerServiceUtils.getPackageManagerLocal() 7293 .withFilteredSnapshot()) { 7294 try { 7295 DeleteResult res = DexOptHelper.getArtManagerLocal().deleteDexoptArtifacts( 7296 filteredSnapshot, packageName); 7297 return res.getFreedBytes(); 7298 } catch (IllegalArgumentException e) { 7299 Log.e(TAG, e.toString()); 7300 return -1; 7301 } catch (IllegalStateException e) { 7302 Slog.wtfStack(TAG, e.toString()); 7303 return -1; 7304 } 7305 } 7306 } else { 7307 PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 7308 if (packageState == null || packageState.getPkg() == null) { 7309 return -1; // error code of deleteOptimizedFiles 7310 } 7311 try { 7312 return mDexManager.deleteOptimizedFiles( 7313 ArtUtils.createArtPackageInfo(packageState.getPkg(), packageState)); 7314 } catch (LegacyDexoptDisabledException e) { 7315 throw new RuntimeException(e); 7316 } 7317 } 7318 } 7319 7320 List<String> getMimeGroupInternal(@NonNull Computer snapshot, String packageName, 7321 String mimeGroup) { 7322 final PackageStateInternal packageState = snapshot.getPackageStateInternal(packageName); 7323 if (packageState == null) { 7324 return Collections.emptyList(); 7325 } 7326 7327 final Map<String, Set<String>> mimeGroups = packageState.getMimeGroups(); 7328 Set<String> mimeTypes = mimeGroups != null ? mimeGroups.get(mimeGroup) : null; 7329 if (mimeTypes == null) { 7330 throw new IllegalArgumentException("Unknown MIME group " + mimeGroup 7331 + " for package " + packageName); 7332 } 7333 return new ArrayList<>(mimeTypes); 7334 } 7335 7336 /** 7337 * Temporary method that wraps mSettings.writeLPr() and calls mPermissionManager's 7338 * writeLegacyPermissionsTEMP() beforehand. 7339 * 7340 * TODO: In the meantime, can this be moved to a schedule call? 7341 * TODO(b/182523293): This should be removed once we finish migration of permission storage. 7342 */ 7343 @SuppressWarnings("GuardedBy") 7344 void writeSettingsLPrTEMP(boolean sync) { 7345 snapshotComputer(false); 7346 mPermissionManager.writeLegacyPermissionsTEMP(mSettings.mPermissions); 7347 mSettings.writeLPr(mLiveComputer, sync); 7348 } 7349 7350 // Default async version. 7351 void writeSettingsLPrTEMP() { 7352 writeSettingsLPrTEMP(/*sync=*/false); 7353 } 7354 7355 @Override 7356 public void verifyHoldLockToken(IBinder token) { 7357 if (!Build.IS_DEBUGGABLE) { 7358 throw new SecurityException("holdLock requires a debuggable build"); 7359 } 7360 7361 if (token == null) { 7362 throw new SecurityException("null holdLockToken"); 7363 } 7364 7365 if (token.queryLocalInterface("holdLock:" + Binder.getCallingUid()) != this) { 7366 throw new SecurityException("Invalid holdLock() token"); 7367 } 7368 } 7369 7370 static String getDefaultTimeouts() { 7371 final long token = Binder.clearCallingIdentity(); 7372 try { 7373 return DeviceConfig.getString(NAMESPACE_PACKAGE_MANAGER_SERVICE, 7374 PROPERTY_INCFS_DEFAULT_TIMEOUTS, ""); 7375 } finally { 7376 Binder.restoreCallingIdentity(token); 7377 } 7378 } 7379 7380 static String getKnownDigestersList() { 7381 final long token = Binder.clearCallingIdentity(); 7382 try { 7383 return DeviceConfig.getString(NAMESPACE_PACKAGE_MANAGER_SERVICE, 7384 PROPERTY_KNOWN_DIGESTERS_LIST, ""); 7385 } finally { 7386 Binder.restoreCallingIdentity(token); 7387 } 7388 } 7389 7390 static boolean isPreapprovalRequestAvailable() { 7391 final long token = Binder.clearCallingIdentity(); 7392 try { 7393 if (!Resources.getSystem().getBoolean( 7394 com.android.internal.R.bool.config_isPreApprovalRequestAvailable)) { 7395 return false; 7396 } 7397 return DeviceConfig.getBoolean(NAMESPACE_PACKAGE_MANAGER_SERVICE, 7398 PROPERTY_IS_PRE_APPROVAL_REQUEST_AVAILABLE, true /* defaultValue */); 7399 } finally { 7400 Binder.restoreCallingIdentity(token); 7401 } 7402 } 7403 7404 static boolean isUpdateOwnershipEnforcementAvailable() { 7405 final long token = Binder.clearCallingIdentity(); 7406 try { 7407 return DeviceConfig.getBoolean(NAMESPACE_PACKAGE_MANAGER_SERVICE, 7408 PROPERTY_IS_UPDATE_OWNERSHIP_ENFORCEMENT_AVAILABLE, true /* defaultValue */); 7409 } finally { 7410 Binder.restoreCallingIdentity(token); 7411 } 7412 } 7413 7414 /** 7415 * Returns the array containing per-uid timeout configuration. 7416 * This is derived from DeviceConfig flags. 7417 */ 7418 public @NonNull PerUidReadTimeouts[] getPerUidReadTimeouts(@NonNull Computer snapshot) { 7419 PerUidReadTimeouts[] result = mPerUidReadTimeoutsCache; 7420 if (result == null) { 7421 result = parsePerUidReadTimeouts(snapshot); 7422 mPerUidReadTimeoutsCache = result; 7423 } 7424 return result; 7425 } 7426 7427 private @NonNull PerUidReadTimeouts[] parsePerUidReadTimeouts(@NonNull Computer snapshot) { 7428 final String defaultTimeouts = getDefaultTimeouts(); 7429 final String knownDigestersList = getKnownDigestersList(); 7430 final List<PerPackageReadTimeouts> perPackageReadTimeouts = 7431 PerPackageReadTimeouts.parseDigestersList(defaultTimeouts, knownDigestersList); 7432 7433 if (perPackageReadTimeouts.size() == 0) { 7434 return EMPTY_PER_UID_READ_TIMEOUTS_ARRAY; 7435 } 7436 7437 final int[] allUsers = mInjector.getUserManagerService().getUserIds(); 7438 final List<PerUidReadTimeouts> result = new ArrayList<>(perPackageReadTimeouts.size()); 7439 for (int i = 0, size = perPackageReadTimeouts.size(); i < size; ++i) { 7440 final PerPackageReadTimeouts perPackage = perPackageReadTimeouts.get(i); 7441 final PackageStateInternal ps = 7442 snapshot.getPackageStateInternal(perPackage.packageName); 7443 if (ps == null) { 7444 if (DEBUG_PER_UID_READ_TIMEOUTS) { 7445 Slog.i(TAG, "PerUidReadTimeouts: package not found = " 7446 + perPackage.packageName); 7447 } 7448 continue; 7449 } 7450 if (ps.getAppId() < Process.FIRST_APPLICATION_UID) { 7451 if (DEBUG_PER_UID_READ_TIMEOUTS) { 7452 Slog.i(TAG, "PerUidReadTimeouts: package is system, appId=" 7453 + ps.getAppId()); 7454 } 7455 continue; 7456 } 7457 7458 final AndroidPackage pkg = ps.getPkg(); 7459 if (pkg.getLongVersionCode() < perPackage.versionCodes.minVersionCode 7460 || pkg.getLongVersionCode() > perPackage.versionCodes.maxVersionCode) { 7461 if (DEBUG_PER_UID_READ_TIMEOUTS) { 7462 Slog.i(TAG, "PerUidReadTimeouts: version code is not in range = " 7463 + perPackage.packageName + ":" + pkg.getLongVersionCode()); 7464 } 7465 continue; 7466 } 7467 if (perPackage.sha256certificate != null 7468 && !pkg.getSigningDetails().hasSha256Certificate( 7469 perPackage.sha256certificate)) { 7470 if (DEBUG_PER_UID_READ_TIMEOUTS) { 7471 Slog.i(TAG, "PerUidReadTimeouts: invalid certificate = " 7472 + perPackage.packageName + ":" + pkg.getLongVersionCode()); 7473 } 7474 continue; 7475 } 7476 for (int userId : allUsers) { 7477 if (!ps.getUserStateOrDefault(userId).isInstalled()) { 7478 continue; 7479 } 7480 final int uid = UserHandle.getUid(userId, ps.getAppId()); 7481 final PerUidReadTimeouts perUid = new PerUidReadTimeouts(); 7482 perUid.uid = uid; 7483 perUid.minTimeUs = perPackage.timeouts.minTimeUs; 7484 perUid.minPendingTimeUs = perPackage.timeouts.minPendingTimeUs; 7485 perUid.maxPendingTimeUs = perPackage.timeouts.maxPendingTimeUs; 7486 result.add(perUid); 7487 } 7488 } 7489 return result.toArray(new PerUidReadTimeouts[result.size()]); 7490 } 7491 7492 void setKeepUninstalledPackagesInternal(@NonNull Computer snapshot, List<String> packageList) { 7493 Preconditions.checkNotNull(packageList); 7494 synchronized (mKeepUninstalledPackages) { 7495 List<String> toRemove = new ArrayList<>(mKeepUninstalledPackages); 7496 toRemove.removeAll(packageList); // Do not remove anything still in the list 7497 7498 mKeepUninstalledPackages.clear(); 7499 mKeepUninstalledPackages.addAll(packageList); 7500 7501 for (int i = 0; i < toRemove.size(); i++) { 7502 deletePackageIfUnused(snapshot, toRemove.get(i)); 7503 } 7504 } 7505 } 7506 7507 boolean shouldKeepUninstalledPackageLPr(String packageName) { 7508 synchronized (mKeepUninstalledPackages) { 7509 return mKeepUninstalledPackages.contains(packageName); 7510 } 7511 } 7512 7513 boolean getSafeMode() { 7514 return mSafeMode; 7515 } 7516 7517 ComponentName getResolveComponentName() { 7518 return mResolveComponentName; 7519 } 7520 7521 DefaultAppProvider getDefaultAppProvider() { 7522 return mDefaultAppProvider; 7523 } 7524 7525 File getCacheDir() { 7526 return mCacheDir; 7527 } 7528 7529 PackageProperty getPackageProperty() { 7530 return mPackageProperty; 7531 } 7532 7533 WatchedArrayMap<ComponentName, ParsedInstrumentation> getInstrumentation() { 7534 return mInstrumentation; 7535 } 7536 7537 int getSdkVersion() { 7538 return mSdkVersion; 7539 } 7540 7541 void addAllPackageProperties(@NonNull AndroidPackage pkg) { 7542 mPackageProperty.addAllProperties(pkg); 7543 } 7544 7545 void addInstrumentation(ComponentName name, ParsedInstrumentation instrumentation) { 7546 mInstrumentation.put(name, instrumentation); 7547 } 7548 7549 String[] getKnownPackageNamesInternal(@NonNull Computer snapshot, int knownPackage, 7550 int userId) { 7551 return new KnownPackages( 7552 mDefaultAppProvider, 7553 mRequiredInstallerPackage, 7554 mRequiredUninstallerPackage, 7555 mSetupWizardPackage, 7556 mRequiredVerifierPackages, 7557 mDefaultTextClassifierPackage, 7558 mSystemTextClassifierPackageName, 7559 mRequiredPermissionControllerPackage, 7560 mConfiguratorPackage, 7561 mIncidentReportApproverPackage, 7562 mAmbientContextDetectionPackage, 7563 mWearableSensingPackage, 7564 mAppPredictionServicePackage, 7565 COMPANION_PACKAGE_NAME, 7566 mRetailDemoPackage, 7567 mOverlayConfigSignaturePackage, 7568 mRecentsPackage) 7569 .getKnownPackageNames(snapshot, knownPackage, userId); 7570 } 7571 7572 String getActiveLauncherPackageName(int userId) { 7573 return mDefaultAppProvider.getDefaultHome(userId); 7574 } 7575 7576 boolean setActiveLauncherPackage(@NonNull String packageName, @UserIdInt int userId, 7577 @NonNull Consumer<Boolean> callback) { 7578 return mDefaultAppProvider.setDefaultHome(packageName, userId, mContext.getMainExecutor(), 7579 callback); 7580 } 7581 7582 @Nullable 7583 String getDefaultBrowser(@UserIdInt int userId) { 7584 return mDefaultAppProvider.getDefaultBrowser(userId); 7585 } 7586 7587 void setDefaultBrowser(@Nullable String packageName, @UserIdInt int userId) { 7588 mDefaultAppProvider.setDefaultBrowser(packageName, userId); 7589 } 7590 7591 PackageUsage getPackageUsage() { 7592 return mPackageUsage; 7593 } 7594 7595 String getModuleMetadataPackageName() { 7596 return mModuleInfoProvider.getPackageName(); 7597 } 7598 7599 File getAppInstallDir() { 7600 return mAppInstallDir; 7601 } 7602 7603 boolean isExpectingBetter(String packageName) { 7604 return mInitAppsHelper.isExpectingBetter(packageName); 7605 } 7606 7607 int getDefParseFlags() { 7608 return mDefParseFlags; 7609 } 7610 7611 void setUpCustomResolverActivity(AndroidPackage pkg, PackageSetting pkgSetting) { 7612 synchronized (mLock) { 7613 mResolverReplaced = true; 7614 7615 // The instance created in PackageManagerService is special cased to be non-user 7616 // specific, so initialize all the needed fields here. 7617 ApplicationInfo appInfo = PackageInfoUtils.generateApplicationInfo(pkg, 0, 7618 PackageUserStateInternal.DEFAULT, UserHandle.USER_SYSTEM, pkgSetting); 7619 7620 // Set up information for custom user intent resolution activity. 7621 mResolveActivity.applicationInfo = appInfo; 7622 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 7623 mResolveActivity.packageName = pkg.getPackageName(); 7624 mResolveActivity.processName = pkg.getProcessName(); 7625 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7626 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 7627 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS 7628 | ActivityInfo.FLAG_CAN_DISPLAY_ON_REMOTE_DEVICES; 7629 mResolveActivity.theme = 0; 7630 mResolveActivity.exported = true; 7631 mResolveActivity.enabled = true; 7632 mResolveInfo.activityInfo = mResolveActivity; 7633 mResolveInfo.priority = 0; 7634 mResolveInfo.preferredOrder = 0; 7635 mResolveInfo.match = 0; 7636 mResolveComponentName = mCustomResolverComponentName; 7637 PackageManagerService.onChanged(); 7638 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " 7639 + mResolveComponentName); 7640 } 7641 } 7642 7643 void setPlatformPackage(AndroidPackage pkg, PackageSetting pkgSetting) { 7644 synchronized (mLock) { 7645 // Set up information for our fall-back user intent resolution activity. 7646 mPlatformPackage = pkg; 7647 7648 // The instance stored in PackageManagerService is special cased to be non-user 7649 // specific, so initialize all the needed fields here. 7650 mAndroidApplication = PackageInfoUtils.generateApplicationInfo(pkg, 0, 7651 PackageUserStateInternal.DEFAULT, UserHandle.USER_SYSTEM, pkgSetting); 7652 7653 if (!mResolverReplaced) { 7654 mResolveActivity.applicationInfo = mAndroidApplication; 7655 mResolveActivity.name = ResolverActivity.class.getName(); 7656 mResolveActivity.packageName = mAndroidApplication.packageName; 7657 mResolveActivity.processName = "system:ui"; 7658 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7659 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7660 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 7661 | ActivityInfo.FLAG_RELINQUISH_TASK_IDENTITY 7662 | ActivityInfo.FLAG_CAN_DISPLAY_ON_REMOTE_DEVICES; 7663 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7664 mResolveActivity.exported = true; 7665 mResolveActivity.enabled = true; 7666 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7667 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7668 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7669 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7670 | ActivityInfo.CONFIG_ORIENTATION 7671 | ActivityInfo.CONFIG_KEYBOARD 7672 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7673 mResolveInfo.activityInfo = mResolveActivity; 7674 mResolveInfo.priority = 0; 7675 mResolveInfo.preferredOrder = 0; 7676 mResolveInfo.match = 0; 7677 mResolveComponentName = new ComponentName( 7678 mAndroidApplication.packageName, mResolveActivity.name); 7679 } 7680 PackageManagerService.onChanged(); 7681 } 7682 applyUpdatedSystemOverlayPaths(); 7683 } 7684 7685 ApplicationInfo getCoreAndroidApplication() { 7686 return mAndroidApplication; 7687 } 7688 7689 boolean isSystemReady() { 7690 return mSystemReady; 7691 } 7692 7693 AndroidPackage getPlatformPackage() { 7694 return mPlatformPackage; 7695 } 7696 7697 boolean isPreNMR1Upgrade() { 7698 return mIsPreNMR1Upgrade; 7699 } 7700 7701 boolean isOverlayMutable(String packageName) { 7702 return mOverlayConfig.isMutable(packageName); 7703 } 7704 7705 @ScanFlags int getSystemPackageScanFlags(File codePath) { 7706 List<ScanPartition> dirsToScanAsSystem = 7707 mInitAppsHelper.getDirsToScanAsSystem(); 7708 @PackageManagerService.ScanFlags int scanFlags = SCAN_AS_SYSTEM; 7709 for (int i = dirsToScanAsSystem.size() - 1; i >= 0; i--) { 7710 ScanPartition partition = dirsToScanAsSystem.get(i); 7711 if (partition.containsFile(codePath)) { 7712 scanFlags |= partition.scanFlag; 7713 if (partition.containsPrivApp(codePath)) { 7714 scanFlags |= SCAN_AS_PRIVILEGED; 7715 } 7716 break; 7717 } 7718 } 7719 return scanFlags; 7720 } 7721 7722 Pair<Integer, Integer> getSystemPackageRescanFlagsAndReparseFlags(File scanFile, 7723 int systemScanFlags, int systemParseFlags) { 7724 List<ScanPartition> dirsToScanAsSystem = 7725 mInitAppsHelper.getDirsToScanAsSystem(); 7726 @ParsingPackageUtils.ParseFlags int reparseFlags = 0; 7727 @PackageManagerService.ScanFlags int rescanFlags = 0; 7728 for (int i1 = dirsToScanAsSystem.size() - 1; i1 >= 0; i1--) { 7729 final ScanPartition partition = dirsToScanAsSystem.get(i1); 7730 if (partition.containsPrivApp(scanFile)) { 7731 reparseFlags = systemParseFlags; 7732 rescanFlags = systemScanFlags | SCAN_AS_PRIVILEGED 7733 | partition.scanFlag; 7734 break; 7735 } 7736 if (partition.containsApp(scanFile)) { 7737 reparseFlags = systemParseFlags; 7738 rescanFlags = systemScanFlags | partition.scanFlag; 7739 break; 7740 } 7741 } 7742 return new Pair<>(rescanFlags, reparseFlags); 7743 } 7744 7745 7746 /** 7747 * @see PackageManagerInternal#recordInitialState() 7748 */ 7749 @NonNull 7750 public PackageStateMutator.InitialState recordInitialState() { 7751 return mPackageStateMutator.initialState(mChangedPackagesTracker.getSequenceNumber()); 7752 } 7753 7754 /** 7755 * @see PackageManagerInternal#commitPackageStateMutation(PackageStateMutator.InitialState, 7756 * Consumer) 7757 */ 7758 @NonNull 7759 public PackageStateMutator.Result commitPackageStateMutation( 7760 @Nullable PackageStateMutator.InitialState initialState, 7761 @NonNull Consumer<PackageStateMutator> consumer) { 7762 synchronized (mPackageStateWriteLock) { 7763 final PackageStateMutator.Result result = mPackageStateMutator.generateResult( 7764 initialState, mChangedPackagesTracker.getSequenceNumber()); 7765 if (result != PackageStateMutator.Result.SUCCESS) { 7766 return result; 7767 } 7768 7769 consumer.accept(mPackageStateMutator); 7770 mPackageStateMutator.onFinished(); 7771 onChanged(); 7772 } 7773 7774 return PackageStateMutator.Result.SUCCESS; 7775 } 7776 7777 /** 7778 * @see PackageManagerInternal#commitPackageStateMutation(PackageStateMutator.InitialState, 7779 * Consumer) 7780 */ 7781 @NonNull 7782 public PackageStateMutator.Result commitPackageStateMutation( 7783 @Nullable PackageStateMutator.InitialState initialState, @NonNull String packageName, 7784 @NonNull Consumer<PackageStateWrite> consumer) { 7785 PackageStateMutator.Result result = null; 7786 if (Thread.holdsLock(mPackageStateWriteLock)) { 7787 // If the thread is already holding the lock, this is likely a retry based on a prior 7788 // failure, and re-calculating whether a state change occurred can be skipped. 7789 result = PackageStateMutator.Result.SUCCESS; 7790 } 7791 synchronized (mPackageStateWriteLock) { 7792 if (result == null) { 7793 // If the thread wasn't previously holding, this is a first-try commit and so a 7794 // state change may have happened. 7795 result = mPackageStateMutator.generateResult( 7796 initialState, mChangedPackagesTracker.getSequenceNumber()); 7797 } 7798 if (result != PackageStateMutator.Result.SUCCESS) { 7799 return result; 7800 } 7801 7802 PackageStateWrite state = mPackageStateMutator.forPackage(packageName); 7803 if (state == null) { 7804 return PackageStateMutator.Result.SPECIFIC_PACKAGE_NULL; 7805 } else { 7806 consumer.accept(state); 7807 } 7808 7809 state.onChanged(); 7810 } 7811 7812 return PackageStateMutator.Result.SUCCESS; 7813 } 7814 7815 void notifyInstantAppPackageInstalled(String packageName, int[] newUsers) { 7816 mInstantAppRegistry.onPackageInstalled(snapshotComputer(), packageName, newUsers); 7817 } 7818 7819 void addInstallerPackageName(InstallSource installSource) { 7820 synchronized (mLock) { 7821 mSettings.addInstallerPackageNames(installSource); 7822 } 7823 } 7824 7825 public void reconcileSdkData(@Nullable String volumeUuid, @NonNull String packageName, 7826 @NonNull List<String> subDirNames, int userId, int appId, int previousAppId, 7827 @NonNull String seInfo, int flags) throws IOException { 7828 synchronized (mInstallLock) { 7829 ReconcileSdkDataArgs args = mInstaller.buildReconcileSdkDataArgs(volumeUuid, 7830 packageName, subDirNames, userId, appId, seInfo, 7831 flags); 7832 args.previousAppId = previousAppId; 7833 try { 7834 mInstaller.reconcileSdkData(args); 7835 } catch (InstallerException e) { 7836 throw new IOException(e.getMessage()); 7837 } 7838 } 7839 } 7840 } 7841