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