1 /* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package com.android.server.pm; 18 19 import static android.Manifest.permission.DELETE_PACKAGES; 20 import static android.Manifest.permission.INSTALL_PACKAGES; 21 import static android.Manifest.permission.MANAGE_DEVICE_ADMINS; 22 import static android.Manifest.permission.MANAGE_PROFILE_AND_DEVICE_OWNERS; 23 import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 24 import static android.Manifest.permission.REQUEST_DELETE_PACKAGES; 25 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 26 import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 27 import static android.content.Intent.ACTION_MAIN; 28 import static android.content.Intent.CATEGORY_DEFAULT; 29 import static android.content.Intent.CATEGORY_HOME; 30 import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 31 import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 32 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 33 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 34 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 35 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 36 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 37 import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 38 import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 39 import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 40 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 41 import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 42 import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 43 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 44 import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 45 import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 46 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 47 import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 48 import static android.content.pm.PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID; 49 import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 50 import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 51 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 52 import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 53 import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 54 import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 55 import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 56 import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 57 import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 58 import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 59 import static android.content.pm.PackageManager.INSTALL_INTERNAL; 60 import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 61 import static android.content.pm.PackageManager.INSTALL_SUCCEEDED; 62 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 63 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 64 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 65 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 66 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 67 import static android.content.pm.PackageManager.MATCH_ALL; 68 import static android.content.pm.PackageManager.MATCH_ANY_USER; 69 import static android.content.pm.PackageManager.MATCH_APEX; 70 import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 71 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 72 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 73 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 74 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 75 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 76 import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 77 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 78 import static android.content.pm.PackageManager.MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL; 79 import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 80 import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 81 import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 82 import static android.content.pm.PackageManager.MOVE_FAILED_LOCKED_USER; 83 import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 84 import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 85 import static android.content.pm.PackageManager.PERMISSION_DENIED; 86 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 87 import static android.content.pm.PackageManager.RESTRICTION_NONE; 88 import static android.content.pm.PackageParser.isApkFile; 89 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 90 import static android.os.storage.StorageManager.FLAG_STORAGE_CE; 91 import static android.os.storage.StorageManager.FLAG_STORAGE_DE; 92 import static android.os.storage.StorageManager.FLAG_STORAGE_EXTERNAL; 93 94 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 95 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 96 import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 97 import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 98 import static com.android.server.pm.ComponentResolver.RESOLVE_PRIORITY_SORTER; 99 import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 100 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 101 import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 102 import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 103 import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 104 import static com.android.server.pm.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 105 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 106 import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 107 import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 108 import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 109 import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 110 import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 111 import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 112 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 113 import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 114 115 import android.Manifest; 116 import android.annotation.IntDef; 117 import android.annotation.NonNull; 118 import android.annotation.Nullable; 119 import android.annotation.UserIdInt; 120 import android.app.ActivityManager; 121 import android.app.ActivityManagerInternal; 122 import android.app.AppOpsManager; 123 import android.app.BroadcastOptions; 124 import android.app.IActivityManager; 125 import android.app.ResourcesManager; 126 import android.app.admin.IDevicePolicyManager; 127 import android.app.admin.SecurityLog; 128 import android.app.backup.IBackupManager; 129 import android.content.BroadcastReceiver; 130 import android.content.ComponentName; 131 import android.content.ContentResolver; 132 import android.content.Context; 133 import android.content.IIntentReceiver; 134 import android.content.Intent; 135 import android.content.IntentFilter; 136 import android.content.IntentSender; 137 import android.content.IntentSender.SendIntentException; 138 import android.content.pm.ActivityInfo; 139 import android.content.pm.ApplicationInfo; 140 import android.content.pm.AppsQueryHelper; 141 import android.content.pm.AuxiliaryResolveInfo; 142 import android.content.pm.ChangedPackages; 143 import android.content.pm.ComponentInfo; 144 import android.content.pm.FallbackCategoryProvider; 145 import android.content.pm.FeatureInfo; 146 import android.content.pm.IDexModuleRegisterCallback; 147 import android.content.pm.IOnPermissionsChangeListener; 148 import android.content.pm.IPackageDataObserver; 149 import android.content.pm.IPackageDeleteObserver; 150 import android.content.pm.IPackageDeleteObserver2; 151 import android.content.pm.IPackageInstallObserver2; 152 import android.content.pm.IPackageInstaller; 153 import android.content.pm.IPackageManager; 154 import android.content.pm.IPackageManagerNative; 155 import android.content.pm.IPackageMoveObserver; 156 import android.content.pm.IPackageStatsObserver; 157 import android.content.pm.InstantAppInfo; 158 import android.content.pm.InstantAppRequest; 159 import android.content.pm.InstrumentationInfo; 160 import android.content.pm.IntentFilterVerificationInfo; 161 import android.content.pm.KeySet; 162 import android.content.pm.ModuleInfo; 163 import android.content.pm.PackageBackwardCompatibility; 164 import android.content.pm.PackageInfo; 165 import android.content.pm.PackageInfoLite; 166 import android.content.pm.PackageInstaller; 167 import android.content.pm.PackageList; 168 import android.content.pm.PackageManager; 169 import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 170 import android.content.pm.PackageManager.ModuleInfoFlags; 171 import android.content.pm.PackageManager.PermissionWhitelistFlags; 172 import android.content.pm.PackageManagerInternal; 173 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate; 174 import android.content.pm.PackageManagerInternal.PackageListObserver; 175 import android.content.pm.PackageParser; 176 import android.content.pm.PackageParser.ActivityIntentInfo; 177 import android.content.pm.PackageParser.PackageLite; 178 import android.content.pm.PackageParser.PackageParserException; 179 import android.content.pm.PackageParser.ParseFlags; 180 import android.content.pm.PackageParser.SigningDetails; 181 import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 182 import android.content.pm.PackageStats; 183 import android.content.pm.PackageUserState; 184 import android.content.pm.ParceledListSlice; 185 import android.content.pm.PermissionGroupInfo; 186 import android.content.pm.PermissionInfo; 187 import android.content.pm.ProviderInfo; 188 import android.content.pm.ResolveInfo; 189 import android.content.pm.SELinuxUtil; 190 import android.content.pm.ServiceInfo; 191 import android.content.pm.SharedLibraryInfo; 192 import android.content.pm.Signature; 193 import android.content.pm.SuspendDialogInfo; 194 import android.content.pm.UserInfo; 195 import android.content.pm.VerifierDeviceIdentity; 196 import android.content.pm.VerifierInfo; 197 import android.content.pm.VersionedPackage; 198 import android.content.pm.dex.ArtManager; 199 import android.content.pm.dex.DexMetadataHelper; 200 import android.content.pm.dex.IArtManager; 201 import android.content.res.Resources; 202 import android.content.rollback.IRollbackManager; 203 import android.database.ContentObserver; 204 import android.graphics.Bitmap; 205 import android.hardware.display.DisplayManager; 206 import android.net.Uri; 207 import android.os.AsyncTask; 208 import android.os.Binder; 209 import android.os.Build; 210 import android.os.Bundle; 211 import android.os.Debug; 212 import android.os.Environment; 213 import android.os.FileUtils; 214 import android.os.Handler; 215 import android.os.IBinder; 216 import android.os.Looper; 217 import android.os.Message; 218 import android.os.Parcel; 219 import android.os.PatternMatcher; 220 import android.os.PersistableBundle; 221 import android.os.Process; 222 import android.os.RemoteCallbackList; 223 import android.os.RemoteException; 224 import android.os.ResultReceiver; 225 import android.os.SELinux; 226 import android.os.ServiceManager; 227 import android.os.ShellCallback; 228 import android.os.SystemClock; 229 import android.os.SystemProperties; 230 import android.os.Trace; 231 import android.os.UserHandle; 232 import android.os.UserManager; 233 import android.os.UserManagerInternal; 234 import android.os.storage.DiskInfo; 235 import android.os.storage.IStorageManager; 236 import android.os.storage.StorageEventListener; 237 import android.os.storage.StorageManager; 238 import android.os.storage.StorageManagerInternal; 239 import android.os.storage.VolumeInfo; 240 import android.os.storage.VolumeRecord; 241 import android.provider.DeviceConfig; 242 import android.provider.MediaStore; 243 import android.provider.Settings.Global; 244 import android.provider.Settings.Secure; 245 import android.security.KeyStore; 246 import android.security.SystemKeyStore; 247 import android.service.pm.PackageServiceDumpProto; 248 import android.stats.storage.StorageEnums; 249 import android.system.ErrnoException; 250 import android.system.Os; 251 import android.text.TextUtils; 252 import android.text.format.DateUtils; 253 import android.util.ArrayMap; 254 import android.util.ArraySet; 255 import android.util.Base64; 256 import android.util.ByteStringUtils; 257 import android.util.DisplayMetrics; 258 import android.util.EventLog; 259 import android.util.ExceptionUtils; 260 import android.util.IntArray; 261 import android.util.Log; 262 import android.util.LogPrinter; 263 import android.util.LongSparseArray; 264 import android.util.LongSparseLongArray; 265 import android.util.MathUtils; 266 import android.util.PackageUtils; 267 import android.util.Pair; 268 import android.util.PrintStreamPrinter; 269 import android.util.Slog; 270 import android.util.SparseArray; 271 import android.util.SparseBooleanArray; 272 import android.util.SparseIntArray; 273 import android.util.StatsLog; 274 import android.util.TimingsTraceLog; 275 import android.util.Xml; 276 import android.util.jar.StrictJarFile; 277 import android.util.proto.ProtoOutputStream; 278 import android.view.Display; 279 280 import com.android.internal.R; 281 import com.android.internal.annotations.GuardedBy; 282 import com.android.internal.app.ResolverActivity; 283 import com.android.internal.content.NativeLibraryHelper; 284 import com.android.internal.content.PackageHelper; 285 import com.android.internal.logging.MetricsLogger; 286 import com.android.internal.os.SomeArgs; 287 import com.android.internal.os.Zygote; 288 import com.android.internal.telephony.CarrierAppUtils; 289 import com.android.internal.util.ArrayUtils; 290 import com.android.internal.util.ConcurrentUtils; 291 import com.android.internal.util.DumpUtils; 292 import com.android.internal.util.FastXmlSerializer; 293 import com.android.internal.util.IndentingPrintWriter; 294 import com.android.internal.util.IntPair; 295 import com.android.internal.util.Preconditions; 296 import com.android.server.AttributeCache; 297 import com.android.server.DeviceIdleController; 298 import com.android.server.EventLogTags; 299 import com.android.server.FgThread; 300 import com.android.server.LocalServices; 301 import com.android.server.LockGuard; 302 import com.android.server.PackageWatchdog; 303 import com.android.server.ServiceThread; 304 import com.android.server.SystemConfig; 305 import com.android.server.SystemServerInitThreadPool; 306 import com.android.server.Watchdog; 307 import com.android.server.net.NetworkPolicyManagerInternal; 308 import com.android.server.pm.Installer.InstallerException; 309 import com.android.server.pm.Settings.DatabaseVersion; 310 import com.android.server.pm.Settings.VersionInfo; 311 import com.android.server.pm.dex.ArtManagerService; 312 import com.android.server.pm.dex.DexManager; 313 import com.android.server.pm.dex.DexoptOptions; 314 import com.android.server.pm.dex.PackageDexUsage; 315 import com.android.server.pm.dex.ViewCompiler; 316 import com.android.server.pm.permission.BasePermission; 317 import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 318 import com.android.server.pm.permission.PermissionManagerService; 319 import com.android.server.pm.permission.PermissionManagerServiceInternal; 320 import com.android.server.pm.permission.PermissionManagerServiceInternal.PermissionCallback; 321 import com.android.server.pm.permission.PermissionsState; 322 import com.android.server.policy.PermissionPolicyInternal; 323 import com.android.server.security.VerityUtils; 324 import com.android.server.storage.DeviceStorageMonitorInternal; 325 import com.android.server.wm.ActivityTaskManagerInternal; 326 327 import dalvik.system.CloseGuard; 328 import dalvik.system.VMRuntime; 329 330 import libcore.io.IoUtils; 331 import libcore.util.EmptyArray; 332 333 import org.xmlpull.v1.XmlPullParser; 334 import org.xmlpull.v1.XmlPullParserException; 335 import org.xmlpull.v1.XmlSerializer; 336 337 import java.io.BufferedOutputStream; 338 import java.io.ByteArrayInputStream; 339 import java.io.ByteArrayOutputStream; 340 import java.io.File; 341 import java.io.FileDescriptor; 342 import java.io.FileInputStream; 343 import java.io.FileOutputStream; 344 import java.io.FilenameFilter; 345 import java.io.IOException; 346 import java.io.PrintWriter; 347 import java.lang.annotation.Retention; 348 import java.lang.annotation.RetentionPolicy; 349 import java.nio.charset.StandardCharsets; 350 import java.security.DigestException; 351 import java.security.DigestInputStream; 352 import java.security.MessageDigest; 353 import java.security.NoSuchAlgorithmException; 354 import java.security.PublicKey; 355 import java.security.SecureRandom; 356 import java.security.cert.CertificateException; 357 import java.util.ArrayList; 358 import java.util.Arrays; 359 import java.util.Collection; 360 import java.util.Collections; 361 import java.util.Comparator; 362 import java.util.HashMap; 363 import java.util.HashSet; 364 import java.util.Iterator; 365 import java.util.LinkedHashSet; 366 import java.util.List; 367 import java.util.Map; 368 import java.util.Objects; 369 import java.util.Set; 370 import java.util.concurrent.CountDownLatch; 371 import java.util.concurrent.Future; 372 import java.util.concurrent.TimeUnit; 373 import java.util.concurrent.atomic.AtomicBoolean; 374 import java.util.concurrent.atomic.AtomicInteger; 375 import java.util.function.BiConsumer; 376 import java.util.function.Consumer; 377 import java.util.function.Predicate; 378 379 /** 380 * Keep track of all those APKs everywhere. 381 * <p> 382 * Internally there are two important locks: 383 * <ul> 384 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 385 * and other related state. It is a fine-grained lock that should only be held 386 * momentarily, as it's one of the most contended locks in the system. 387 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 388 * operations typically involve heavy lifting of application data on disk. Since 389 * {@code installd} is single-threaded, and it's operations can often be slow, 390 * this lock should never be acquired while already holding {@link #mPackages}. 391 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 392 * holding {@link #mInstallLock}. 393 * </ul> 394 * Many internal methods rely on the caller to hold the appropriate locks, and 395 * this contract is expressed through method name suffixes: 396 * <ul> 397 * <li>fooLI(): the caller must hold {@link #mInstallLock} 398 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 399 * being modified must be frozen 400 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 401 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 402 * </ul> 403 * <p> 404 * Because this class is very central to the platform's security; please run all 405 * CTS and unit tests whenever making modifications: 406 * 407 * <pre> 408 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 409 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 410 * </pre> 411 */ 412 public class PackageManagerService extends IPackageManager.Stub 413 implements PackageSender { 414 static final String TAG = "PackageManager"; 415 public static final boolean DEBUG_SETTINGS = false; 416 static final boolean DEBUG_PREFERRED = false; 417 static final boolean DEBUG_UPGRADE = false; 418 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 419 private static final boolean DEBUG_BACKUP = false; 420 public static final boolean DEBUG_INSTALL = false; 421 public static final boolean DEBUG_REMOVE = false; 422 private static final boolean DEBUG_BROADCASTS = false; 423 private static final boolean DEBUG_PACKAGE_INFO = false; 424 private static final boolean DEBUG_INTENT_MATCHING = false; 425 public static final boolean DEBUG_PACKAGE_SCANNING = false; 426 private static final boolean DEBUG_VERIFY = false; 427 public static final boolean DEBUG_PERMISSIONS = false; 428 private static final boolean DEBUG_SHARED_LIBRARIES = false; 429 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 430 431 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 432 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 433 // user, but by default initialize to this. 434 public static final boolean DEBUG_DEXOPT = false; 435 436 private static final boolean DEBUG_ABI_SELECTION = false; 437 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 438 private static final boolean DEBUG_APP_DATA = false; 439 440 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 441 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 442 443 private static final boolean HIDE_EPHEMERAL_APIS = false; 444 445 private static final boolean ENABLE_FREE_CACHE_V2 = 446 SystemProperties.getBoolean("fw.free_cache_v2", true); 447 448 private static final String PRECOMPILE_LAYOUTS = "pm.precompile_layouts"; 449 450 private static final int RADIO_UID = Process.PHONE_UID; 451 private static final int LOG_UID = Process.LOG_UID; 452 private static final int NFC_UID = Process.NFC_UID; 453 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 454 private static final int SHELL_UID = Process.SHELL_UID; 455 private static final int SE_UID = Process.SE_UID; 456 private static final int NETWORKSTACK_UID = Process.NETWORK_STACK_UID; 457 458 static final int SCAN_NO_DEX = 1 << 0; 459 static final int SCAN_UPDATE_SIGNATURE = 1 << 1; 460 static final int SCAN_NEW_INSTALL = 1 << 2; 461 static final int SCAN_UPDATE_TIME = 1 << 3; 462 static final int SCAN_BOOTING = 1 << 4; 463 static final int SCAN_REQUIRE_KNOWN = 1 << 7; 464 static final int SCAN_MOVE = 1 << 8; 465 static final int SCAN_INITIAL = 1 << 9; 466 static final int SCAN_CHECK_ONLY = 1 << 10; 467 static final int SCAN_DONT_KILL_APP = 1 << 11; 468 static final int SCAN_IGNORE_FROZEN = 1 << 12; 469 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1 << 13; 470 static final int SCAN_AS_INSTANT_APP = 1 << 14; 471 static final int SCAN_AS_FULL_APP = 1 << 15; 472 static final int SCAN_AS_VIRTUAL_PRELOAD = 1 << 16; 473 static final int SCAN_AS_SYSTEM = 1 << 17; 474 static final int SCAN_AS_PRIVILEGED = 1 << 18; 475 static final int SCAN_AS_OEM = 1 << 19; 476 static final int SCAN_AS_VENDOR = 1 << 20; 477 static final int SCAN_AS_PRODUCT = 1 << 21; 478 static final int SCAN_AS_PRODUCT_SERVICES = 1 << 22; 479 static final int SCAN_AS_ODM = 1 << 23; 480 481 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 482 SCAN_NO_DEX, 483 SCAN_UPDATE_SIGNATURE, 484 SCAN_NEW_INSTALL, 485 SCAN_UPDATE_TIME, 486 SCAN_BOOTING, 487 SCAN_REQUIRE_KNOWN, 488 SCAN_MOVE, 489 SCAN_INITIAL, 490 SCAN_CHECK_ONLY, 491 SCAN_DONT_KILL_APP, 492 SCAN_IGNORE_FROZEN, 493 SCAN_FIRST_BOOT_OR_UPGRADE, 494 SCAN_AS_INSTANT_APP, 495 SCAN_AS_FULL_APP, 496 SCAN_AS_VIRTUAL_PRELOAD, 497 }) 498 @Retention(RetentionPolicy.SOURCE) 499 public @interface ScanFlags {} 500 501 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 502 /** Extension of the compressed packages */ 503 public final static String COMPRESSED_EXTENSION = ".gz"; 504 /** Suffix of stub packages on the system partition */ 505 public final static String STUB_SUFFIX = "-Stub"; 506 507 private static final int[] EMPTY_INT_ARRAY = new int[0]; 508 509 private static final int TYPE_UNKNOWN = 0; 510 private static final int TYPE_ACTIVITY = 1; 511 private static final int TYPE_RECEIVER = 2; 512 private static final int TYPE_SERVICE = 3; 513 private static final int TYPE_PROVIDER = 4; 514 @IntDef(prefix = { "TYPE_" }, value = { 515 TYPE_UNKNOWN, 516 TYPE_ACTIVITY, 517 TYPE_RECEIVER, 518 TYPE_SERVICE, 519 TYPE_PROVIDER, 520 }) 521 @Retention(RetentionPolicy.SOURCE) 522 public @interface ComponentType {} 523 524 /** 525 * Timeout (in milliseconds) after which the watchdog should declare that 526 * our handler thread is wedged. The usual default for such things is one 527 * minute but we sometimes do very lengthy I/O operations on this thread, 528 * such as installing multi-gigabyte applications, so ours needs to be longer. 529 */ 530 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 531 532 /** 533 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 534 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 535 * settings entry if available, otherwise we use the hardcoded default. If it's been 536 * more than this long since the last fstrim, we force one during the boot sequence. 537 * 538 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 539 * one gets run at the next available charging+idle time. This final mandatory 540 * no-fstrim check kicks in only of the other scheduling criteria is never met. 541 */ 542 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 543 544 /** 545 * Whether verification is enabled by default. 546 */ 547 private static final boolean DEFAULT_VERIFY_ENABLE = true; 548 549 /** 550 * The default maximum time to wait for the verification agent to return in 551 * milliseconds. 552 */ 553 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 554 555 /** 556 * Timeout duration in milliseconds for enabling package rollback. If we fail to enable 557 * rollback within that period, the install will proceed without rollback enabled. 558 * 559 * <p>If flag value is negative, the default value will be assigned. 560 * 561 * Flag type: {@code long} 562 * Namespace: NAMESPACE_ROLLBACK 563 */ 564 private static final String PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS = "enable_rollback_timeout"; 565 566 /** 567 * The default duration to wait for rollback to be enabled in 568 * milliseconds. 569 */ 570 private static final long DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS = 10 * 1000; 571 572 /** 573 * The default response for package verification timeout. 574 * 575 * This can be either PackageManager.VERIFICATION_ALLOW or 576 * PackageManager.VERIFICATION_REJECT. 577 */ 578 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 579 580 public static final String PLATFORM_PACKAGE_NAME = "android"; 581 582 private static final String KILL_APP_REASON_GIDS_CHANGED = 583 "permission grant or revoke changed gids"; 584 585 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 586 "permissions revoked"; 587 588 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 589 590 private static final String PACKAGE_SCHEME = "package"; 591 592 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 593 594 private static final String PRODUCT_OVERLAY_DIR = "/product/overlay"; 595 596 private static final String PRODUCT_SERVICES_OVERLAY_DIR = "/product_services/overlay"; 597 598 private static final String ODM_OVERLAY_DIR = "/odm/overlay"; 599 600 private static final String OEM_OVERLAY_DIR = "/oem/overlay"; 601 602 /** Canonical intent used to identify what counts as a "web browser" app */ 603 private static final Intent sBrowserIntent; 604 static { 605 sBrowserIntent = new Intent(); 606 sBrowserIntent.setAction(Intent.ACTION_VIEW); 607 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 608 sBrowserIntent.setData(Uri.parse("http:")); 609 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 610 } 611 612 // Compilation reasons. 613 public static final int REASON_UNKNOWN = -1; 614 public static final int REASON_FIRST_BOOT = 0; 615 public static final int REASON_BOOT = 1; 616 public static final int REASON_INSTALL = 2; 617 public static final int REASON_BACKGROUND_DEXOPT = 3; 618 public static final int REASON_AB_OTA = 4; 619 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 620 public static final int REASON_SHARED = 6; 621 622 public static final int REASON_LAST = REASON_SHARED; 623 624 /** 625 * Whether the package parser cache is enabled. 626 */ 627 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 628 629 /** 630 * Permissions required in order to receive instant application lifecycle broadcasts. 631 */ 632 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 633 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 634 635 final ServiceThread mHandlerThread; 636 637 final PackageHandler mHandler; 638 639 private final ProcessLoggingHandler mProcessLoggingHandler; 640 641 final int mSdkVersion = Build.VERSION.SDK_INT; 642 643 final Context mContext; 644 final boolean mFactoryTest; 645 final boolean mOnlyCore; 646 final DisplayMetrics mMetrics; 647 final int mDefParseFlags; 648 final String[] mSeparateProcesses; 649 final boolean mIsUpgrade; 650 final boolean mIsPreNUpgrade; 651 final boolean mIsPreNMR1Upgrade; 652 final boolean mIsPreQUpgrade; 653 654 @GuardedBy("mPackages") 655 private boolean mDexOptDialogShown; 656 657 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 658 // LOCK HELD. Can be called with mInstallLock held. 659 @GuardedBy("mInstallLock") 660 final Installer mInstaller; 661 662 /** Directory where installed applications are stored */ 663 private static final File sAppInstallDir = 664 new File(Environment.getDataDirectory(), "app"); 665 /** Directory where installed application's 32-bit native libraries are copied. */ 666 private static final File sAppLib32InstallDir = 667 new File(Environment.getDataDirectory(), "app-lib"); 668 669 // ---------------------------------------------------------------- 670 671 // Lock for state used when installing and doing other long running 672 // operations. Methods that must be called with this lock held have 673 // the suffix "LI". 674 final Object mInstallLock = new Object(); 675 676 // ---------------------------------------------------------------- 677 678 // Keys are String (package name), values are Package. This also serves 679 // as the lock for the global state. Methods that must be called with 680 // this lock held have the prefix "LP". 681 @GuardedBy("mPackages") 682 final ArrayMap<String, PackageParser.Package> mPackages = new ArrayMap<>(); 683 684 // Keys are isolated uids and values are the uid of the application 685 // that created the isolated proccess. 686 @GuardedBy("mPackages") 687 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 688 689 /** 690 * Tracks new system packages [received in an OTA] that we expect to 691 * find updated user-installed versions. Keys are package name, values 692 * are package location. 693 */ 694 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 695 696 /** 697 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 698 */ 699 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 700 /** 701 * Whether or not system app permissions should be promoted from install to runtime. 702 */ 703 boolean mPromoteSystemApps; 704 705 @GuardedBy("mPackages") 706 final Settings mSettings; 707 708 /** 709 * Set of package names that are currently "frozen", which means active 710 * surgery is being done on the code/data for that package. The platform 711 * will refuse to launch frozen packages to avoid race conditions. 712 * 713 * @see PackageFreezer 714 */ 715 @GuardedBy("mPackages") 716 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 717 718 final ProtectedPackages mProtectedPackages; 719 720 @GuardedBy("mLoadedVolumes") 721 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 722 723 boolean mFirstBoot; 724 725 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 726 727 @GuardedBy("mAvailableFeatures") 728 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 729 730 private final InstantAppRegistry mInstantAppRegistry; 731 732 @GuardedBy("mPackages") 733 int mChangedPackagesSequenceNumber; 734 /** 735 * List of changed [installed, removed or updated] packages. 736 * mapping from user id -> sequence number -> package name 737 */ 738 @GuardedBy("mPackages") 739 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 740 /** 741 * The sequence number of the last change to a package. 742 * mapping from user id -> package name -> sequence number 743 */ 744 @GuardedBy("mPackages") 745 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 746 747 @GuardedBy("mPackages") 748 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 749 750 @GuardedBy("mPackages") 751 private final SparseIntArray mDefaultPermissionsGrantedUsers = new SparseIntArray(); 752 753 private final ModuleInfoProvider mModuleInfoProvider; 754 755 private final ApexManager mApexManager; 756 757 class PackageParserCallback implements PackageParser.Callback { hasFeature(String feature)758 @Override public final boolean hasFeature(String feature) { 759 return PackageManagerService.this.hasSystemFeature(feature, 0); 760 } 761 getStaticOverlayPackages( Collection<PackageParser.Package> allPackages, String targetPackageName)762 final List<PackageParser.Package> getStaticOverlayPackages( 763 Collection<PackageParser.Package> allPackages, String targetPackageName) { 764 if ("android".equals(targetPackageName)) { 765 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 766 // native AssetManager. 767 return null; 768 } 769 770 List<PackageParser.Package> overlayPackages = null; 771 for (PackageParser.Package p : allPackages) { 772 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 773 if (overlayPackages == null) { 774 overlayPackages = new ArrayList<>(); 775 } 776 overlayPackages.add(p); 777 } 778 } 779 if (overlayPackages != null) { 780 Comparator<PackageParser.Package> cmp = 781 Comparator.comparingInt(p -> p.mOverlayPriority); 782 overlayPackages.sort(cmp); 783 } 784 return overlayPackages; 785 } 786 getStaticOverlayPaths(List<PackageParser.Package> overlayPackages, String targetPath)787 final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages, 788 String targetPath) { 789 if (overlayPackages == null || overlayPackages.isEmpty()) { 790 return null; 791 } 792 List<String> overlayPathList = null; 793 for (PackageParser.Package overlayPackage : overlayPackages) { 794 if (targetPath == null) { 795 if (overlayPathList == null) { 796 overlayPathList = new ArrayList<>(); 797 } 798 overlayPathList.add(overlayPackage.baseCodePath); 799 continue; 800 } 801 802 try { 803 // Creates idmaps for system to parse correctly the Android manifest of the 804 // target package. 805 // 806 // OverlayManagerService will update each of them with a correct gid from its 807 // target package app id. 808 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 809 UserHandle.getSharedAppGid( 810 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 811 if (overlayPathList == null) { 812 overlayPathList = new ArrayList<>(); 813 } 814 overlayPathList.add(overlayPackage.baseCodePath); 815 } catch (InstallerException e) { 816 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 817 overlayPackage.baseCodePath); 818 } 819 } 820 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 821 } 822 getStaticOverlayPaths(String targetPackageName, String targetPath)823 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 824 List<PackageParser.Package> overlayPackages; 825 synchronized (mInstallLock) { 826 synchronized (mPackages) { 827 overlayPackages = getStaticOverlayPackages( 828 mPackages.values(), targetPackageName); 829 } 830 // It is safe to keep overlayPackages without holding mPackages because static overlay 831 // packages can't be uninstalled or disabled. 832 return getStaticOverlayPaths(overlayPackages, targetPath); 833 } 834 } 835 getOverlayApks(String targetPackageName)836 @Override public final String[] getOverlayApks(String targetPackageName) { 837 return getStaticOverlayPaths(targetPackageName, null); 838 } 839 getOverlayPaths(String targetPackageName, String targetPath)840 @Override public final String[] getOverlayPaths(String targetPackageName, 841 String targetPath) { 842 return getStaticOverlayPaths(targetPackageName, targetPath); 843 } 844 } 845 846 class ParallelPackageParserCallback extends PackageParserCallback { 847 List<PackageParser.Package> mOverlayPackages = null; 848 findStaticOverlayPackages()849 void findStaticOverlayPackages() { 850 synchronized (mPackages) { 851 for (PackageParser.Package p : mPackages.values()) { 852 if (p.mOverlayIsStatic) { 853 if (mOverlayPackages == null) { 854 mOverlayPackages = new ArrayList<>(); 855 } 856 mOverlayPackages.add(p); 857 } 858 } 859 } 860 } 861 862 @Override getStaticOverlayPaths(String targetPackageName, String targetPath)863 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 864 // We can trust mOverlayPackages without holding mPackages because package uninstall 865 // can't happen while running parallel parsing. 866 // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock 867 // because mInstallLock is held before running parallel parsing. 868 // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock. 869 return mOverlayPackages == null ? null : 870 getStaticOverlayPaths( 871 getStaticOverlayPackages(mOverlayPackages, targetPackageName), 872 targetPath); 873 } 874 } 875 876 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 877 final ParallelPackageParserCallback mParallelPackageParserCallback = 878 new ParallelPackageParserCallback(); 879 880 // Currently known shared libraries. 881 final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mSharedLibraries = new ArrayMap<>(); 882 final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mStaticLibsByDeclaringPackage = 883 new ArrayMap<>(); 884 885 // Mapping from instrumentation class names to info about them. 886 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 887 new ArrayMap<>(); 888 889 // Packages whose data we have transfered into another package, thus 890 // should no longer exist. 891 final ArraySet<String> mTransferedPackages = new ArraySet<>(); 892 893 // Broadcast actions that are only available to the system. 894 @GuardedBy("mProtectedBroadcasts") 895 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 896 897 /** List of packages waiting for verification. */ 898 final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<>(); 899 900 /** List of packages waiting for rollback to be enabled. */ 901 final SparseArray<InstallParams> mPendingEnableRollback = new SparseArray<>(); 902 903 final PackageInstallerService mInstallerService; 904 905 final ArtManagerService mArtManagerService; 906 907 private final PackageDexOptimizer mPackageDexOptimizer; 908 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 909 // is used by other apps). 910 private final DexManager mDexManager; 911 912 private final ViewCompiler mViewCompiler; 913 914 private AtomicInteger mNextMoveId = new AtomicInteger(); 915 private final MoveCallbacks mMoveCallbacks; 916 917 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 918 919 // Cache of users who need badging. 920 private final SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 921 922 /** Token for keys in mPendingVerification. */ 923 private int mPendingVerificationToken = 0; 924 925 /** Token for keys in mPendingEnableRollback. */ 926 private int mPendingEnableRollbackToken = 0; 927 928 volatile boolean mSystemReady; 929 volatile boolean mSafeMode; 930 volatile boolean mHasSystemUidErrors; 931 private volatile SparseBooleanArray mWebInstantAppsDisabled = new SparseBooleanArray(); 932 933 ApplicationInfo mAndroidApplication; 934 final ActivityInfo mResolveActivity = new ActivityInfo(); 935 final ResolveInfo mResolveInfo = new ResolveInfo(); 936 ComponentName mResolveComponentName; 937 PackageParser.Package mPlatformPackage; 938 ComponentName mCustomResolverComponentName; 939 940 boolean mResolverReplaced = false; 941 942 private final @Nullable ComponentName mIntentFilterVerifierComponent; 943 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 944 945 private int mIntentFilterVerificationToken = 0; 946 947 /** The service connection to the ephemeral resolver */ 948 final InstantAppResolverConnection mInstantAppResolverConnection; 949 /** Component used to show resolver settings for Instant Apps */ 950 final ComponentName mInstantAppResolverSettingsComponent; 951 952 /** Activity used to install instant applications */ 953 ActivityInfo mInstantAppInstallerActivity; 954 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 955 956 private final Map<String, Pair<PackageInstalledInfo, IPackageInstallObserver2>> 957 mNoKillInstallObservers = Collections.synchronizedMap(new HashMap<>()); 958 959 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 960 = new SparseArray<>(); 961 962 // TODO remove this and go through mPermissonManager directly 963 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 964 private final PermissionManagerServiceInternal mPermissionManager; 965 966 private final ComponentResolver mComponentResolver; 967 // List of packages names to keep cached, even if they are uninstalled for all users 968 private List<String> mKeepUninstalledPackages; 969 970 private UserManagerInternal mUserManagerInternal; 971 private ActivityManagerInternal mActivityManagerInternal; 972 private ActivityTaskManagerInternal mActivityTaskManagerInternal; 973 private StorageManagerInternal mStorageManagerInternal; 974 975 private DeviceIdleController.LocalService mDeviceIdleController; 976 977 private File mCacheDir; 978 979 private Future<?> mPrepareAppDataFuture; 980 981 private static class IFVerificationParams { 982 PackageParser.Package pkg; 983 boolean replacing; 984 int userId; 985 int verifierUid; 986 IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, int _userId, int _verifierUid)987 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 988 int _userId, int _verifierUid) { 989 pkg = _pkg; 990 replacing = _replacing; 991 userId = _userId; 992 verifierUid = _verifierUid; 993 } 994 } 995 996 private interface IntentFilterVerifier<T extends IntentFilter> { addOneIntentFilterVerification(int verifierId, int userId, int verificationId, T filter, String packageName)997 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 998 T filter, String packageName); startVerifications(int userId)999 void startVerifications(int userId); receiveVerificationResponse(int verificationId)1000 void receiveVerificationResponse(int verificationId); 1001 } 1002 1003 @GuardedBy("mPackages") 1004 private CheckPermissionDelegate mCheckPermissionDelegate; 1005 1006 @GuardedBy("mPackages") 1007 private PackageManagerInternal.DefaultBrowserProvider mDefaultBrowserProvider; 1008 1009 @GuardedBy("mPackages") 1010 private PackageManagerInternal.DefaultDialerProvider mDefaultDialerProvider; 1011 1012 @GuardedBy("mPackages") 1013 private PackageManagerInternal.DefaultHomeProvider mDefaultHomeProvider; 1014 1015 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1016 private Context mContext; 1017 private ComponentName mIntentFilterVerifierComponent; 1018 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<>(); 1019 IntentVerifierProxy(Context context, ComponentName verifierComponent)1020 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1021 mContext = context; 1022 mIntentFilterVerifierComponent = verifierComponent; 1023 } 1024 getDefaultScheme()1025 private String getDefaultScheme() { 1026 return IntentFilter.SCHEME_HTTPS; 1027 } 1028 1029 @Override startVerifications(int userId)1030 public void startVerifications(int userId) { 1031 // Launch verifications requests 1032 int count = mCurrentIntentFilterVerifications.size(); 1033 for (int n=0; n<count; n++) { 1034 int verificationId = mCurrentIntentFilterVerifications.get(n); 1035 final IntentFilterVerificationState ivs = 1036 mIntentFilterVerificationStates.get(verificationId); 1037 1038 String packageName = ivs.getPackageName(); 1039 1040 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1041 final int filterCount = filters.size(); 1042 ArraySet<String> domainsSet = new ArraySet<>(); 1043 for (int m=0; m<filterCount; m++) { 1044 PackageParser.ActivityIntentInfo filter = filters.get(m); 1045 domainsSet.addAll(filter.getHostsList()); 1046 } 1047 synchronized (mPackages) { 1048 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1049 packageName, domainsSet) != null) { 1050 scheduleWriteSettingsLocked(); 1051 } 1052 } 1053 sendVerificationRequest(verificationId, ivs); 1054 } 1055 mCurrentIntentFilterVerifications.clear(); 1056 } 1057 sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs)1058 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1059 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1060 verificationIntent.putExtra( 1061 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1062 verificationId); 1063 verificationIntent.putExtra( 1064 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1065 getDefaultScheme()); 1066 verificationIntent.putExtra( 1067 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1068 ivs.getHostsString()); 1069 verificationIntent.putExtra( 1070 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1071 ivs.getPackageName()); 1072 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1073 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1074 1075 final long whitelistTimeout = getVerificationTimeout(); 1076 final BroadcastOptions options = BroadcastOptions.makeBasic(); 1077 options.setTemporaryAppWhitelistDuration(whitelistTimeout); 1078 1079 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1080 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1081 mIntentFilterVerifierComponent.getPackageName(), whitelistTimeout, 1082 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1083 1084 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM, 1085 null, options.toBundle()); 1086 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1087 "Sending IntentFilter verification broadcast"); 1088 } 1089 receiveVerificationResponse(int verificationId)1090 public void receiveVerificationResponse(int verificationId) { 1091 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1092 1093 final boolean verified = ivs.isVerified(); 1094 1095 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1096 final int count = filters.size(); 1097 if (DEBUG_DOMAIN_VERIFICATION) { 1098 Slog.i(TAG, "Received verification response " + verificationId 1099 + " for " + count + " filters, verified=" + verified); 1100 } 1101 for (int n=0; n<count; n++) { 1102 PackageParser.ActivityIntentInfo filter = filters.get(n); 1103 filter.setVerified(verified); 1104 1105 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1106 + " verified with result:" + verified + " and hosts:" 1107 + ivs.getHostsString()); 1108 } 1109 1110 mIntentFilterVerificationStates.remove(verificationId); 1111 1112 final String packageName = ivs.getPackageName(); 1113 IntentFilterVerificationInfo ivi; 1114 1115 synchronized (mPackages) { 1116 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1117 } 1118 if (ivi == null) { 1119 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1120 + verificationId + " packageName:" + packageName); 1121 return; 1122 } 1123 1124 synchronized (mPackages) { 1125 if (verified) { 1126 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1127 } else { 1128 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1129 } 1130 scheduleWriteSettingsLocked(); 1131 1132 final int userId = ivs.getUserId(); 1133 if (userId != UserHandle.USER_ALL) { 1134 final int userStatus = 1135 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1136 1137 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1138 boolean needUpdate = false; 1139 1140 // In a success case, we promote from undefined or ASK to ALWAYS. This 1141 // supports a flow where the app fails validation but then ships an updated 1142 // APK that passes, and therefore deserves to be in ALWAYS. 1143 // 1144 // If validation failed, the undefined state winds up in the basic ASK behavior, 1145 // but apps that previously passed and became ALWAYS are *demoted* out of 1146 // that state, since they would not deserve the ALWAYS behavior in case of a 1147 // clean install. 1148 switch (userStatus) { 1149 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS: 1150 if (!verified) { 1151 // Don't demote if sysconfig says 'always' 1152 SystemConfig systemConfig = SystemConfig.getInstance(); 1153 ArraySet<String> packages = systemConfig.getLinkedApps(); 1154 if (!packages.contains(packageName)) { 1155 // updatedStatus is already UNDEFINED 1156 needUpdate = true; 1157 1158 if (DEBUG_DOMAIN_VERIFICATION) { 1159 Slog.d(TAG, "Formerly validated but now failing; demoting"); 1160 } 1161 } else { 1162 if (DEBUG_DOMAIN_VERIFICATION) { 1163 Slog.d(TAG, "Updating bundled package " + packageName 1164 + " failed autoVerify, but sysconfig supersedes"); 1165 } 1166 // leave needUpdate == false here intentionally 1167 } 1168 } 1169 break; 1170 1171 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1172 // Stay in 'undefined' on verification failure 1173 if (verified) { 1174 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1175 } 1176 needUpdate = true; 1177 if (DEBUG_DOMAIN_VERIFICATION) { 1178 Slog.d(TAG, "Applying update; old=" + userStatus 1179 + " new=" + updatedStatus); 1180 } 1181 break; 1182 1183 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1184 // Keep in 'ask' on failure 1185 if (verified) { 1186 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1187 needUpdate = true; 1188 } 1189 break; 1190 1191 default: 1192 // Nothing to do 1193 } 1194 1195 if (needUpdate) { 1196 mSettings.updateIntentFilterVerificationStatusLPw( 1197 packageName, updatedStatus, userId); 1198 scheduleWritePackageRestrictionsLocked(userId); 1199 } 1200 } else { 1201 Slog.i(TAG, "autoVerify ignored when installing for all users"); 1202 } 1203 } 1204 } 1205 1206 @Override addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, ActivityIntentInfo filter, String packageName)1207 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1208 ActivityIntentInfo filter, String packageName) { 1209 if (!hasValidDomains(filter)) { 1210 return false; 1211 } 1212 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1213 if (ivs == null) { 1214 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1215 packageName); 1216 } 1217 if (DEBUG_DOMAIN_VERIFICATION) { 1218 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1219 } 1220 ivs.addFilter(filter); 1221 return true; 1222 } 1223 createDomainVerificationState(int verifierUid, int userId, int verificationId, String packageName)1224 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1225 int userId, int verificationId, String packageName) { 1226 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1227 verifierUid, userId, packageName); 1228 ivs.setPendingState(); 1229 synchronized (mPackages) { 1230 mIntentFilterVerificationStates.append(verificationId, ivs); 1231 mCurrentIntentFilterVerifications.add(verificationId); 1232 } 1233 return ivs; 1234 } 1235 } 1236 hasValidDomains(ActivityIntentInfo filter)1237 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1238 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1239 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1240 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1241 } 1242 1243 // Set of pending broadcasts for aggregating enable/disable of components. 1244 static class PendingPackageBroadcasts { 1245 // for each user id, a map of <package name -> components within that package> 1246 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1247 PendingPackageBroadcasts()1248 public PendingPackageBroadcasts() { 1249 mUidMap = new SparseArray<>(2); 1250 } 1251 get(int userId, String packageName)1252 public ArrayList<String> get(int userId, String packageName) { 1253 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1254 return packages.get(packageName); 1255 } 1256 put(int userId, String packageName, ArrayList<String> components)1257 public void put(int userId, String packageName, ArrayList<String> components) { 1258 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1259 packages.put(packageName, components); 1260 } 1261 remove(int userId, String packageName)1262 public void remove(int userId, String packageName) { 1263 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1264 if (packages != null) { 1265 packages.remove(packageName); 1266 } 1267 } 1268 remove(int userId)1269 public void remove(int userId) { 1270 mUidMap.remove(userId); 1271 } 1272 userIdCount()1273 public int userIdCount() { 1274 return mUidMap.size(); 1275 } 1276 userIdAt(int n)1277 public int userIdAt(int n) { 1278 return mUidMap.keyAt(n); 1279 } 1280 packagesForUserId(int userId)1281 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1282 return mUidMap.get(userId); 1283 } 1284 size()1285 public int size() { 1286 // total number of pending broadcast entries across all userIds 1287 int num = 0; 1288 for (int i = 0; i< mUidMap.size(); i++) { 1289 num += mUidMap.valueAt(i).size(); 1290 } 1291 return num; 1292 } 1293 clear()1294 public void clear() { 1295 mUidMap.clear(); 1296 } 1297 getOrAllocate(int userId)1298 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1299 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1300 if (map == null) { 1301 map = new ArrayMap<>(); 1302 mUidMap.put(userId, map); 1303 } 1304 return map; 1305 } 1306 } 1307 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1308 1309 static final int SEND_PENDING_BROADCAST = 1; 1310 static final int INIT_COPY = 5; 1311 static final int POST_INSTALL = 9; 1312 static final int WRITE_SETTINGS = 13; 1313 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1314 static final int PACKAGE_VERIFIED = 15; 1315 static final int CHECK_PENDING_VERIFICATION = 16; 1316 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1317 static final int INTENT_FILTER_VERIFIED = 18; 1318 static final int WRITE_PACKAGE_LIST = 19; 1319 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1320 static final int ENABLE_ROLLBACK_STATUS = 21; 1321 static final int ENABLE_ROLLBACK_TIMEOUT = 22; 1322 static final int DEFERRED_NO_KILL_POST_DELETE = 23; 1323 static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24; 1324 1325 static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000; 1326 static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500; 1327 1328 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1329 1330 private static final long BROADCAST_DELAY_DURING_STARTUP = 10 * 1000L; // 10 seconds (in millis) 1331 private static final long BROADCAST_DELAY = 1 * 1000L; // 1 second (in millis) 1332 1333 // When the service constructor finished plus a delay (used for broadcast delay computation) 1334 private long mServiceStartWithDelay; 1335 1336 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1337 2 * 60 * 60 * 1000L; /* two hours */ 1338 1339 static UserManagerService sUserManager; 1340 1341 // Stores a list of users whose package restrictions file needs to be updated 1342 private ArraySet<Integer> mDirtyUsers = new ArraySet<>(); 1343 1344 // Recordkeeping of restore-after-install operations that are currently in flight 1345 // between the Package Manager and the Backup Manager 1346 static class PostInstallData { 1347 public final InstallArgs args; 1348 public final PackageInstalledInfo res; 1349 public final Runnable mPostInstallRunnable; 1350 PostInstallData(InstallArgs _a, PackageInstalledInfo _r, Runnable postInstallRunnable)1351 PostInstallData(InstallArgs _a, PackageInstalledInfo _r, Runnable postInstallRunnable) { 1352 args = _a; 1353 res = _r; 1354 mPostInstallRunnable = postInstallRunnable; 1355 } 1356 } 1357 1358 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<>(); 1359 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1360 1361 // XML tags for backup/restore of various bits of state 1362 private static final String TAG_PREFERRED_BACKUP = "pa"; 1363 private static final String TAG_DEFAULT_APPS = "da"; 1364 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1365 1366 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1367 private static final String TAG_ALL_GRANTS = "rt-grants"; 1368 private static final String TAG_GRANT = "grant"; 1369 private static final String ATTR_PACKAGE_NAME = "pkg"; 1370 1371 private static final String TAG_PERMISSION = "perm"; 1372 private static final String ATTR_PERMISSION_NAME = "name"; 1373 private static final String ATTR_IS_GRANTED = "g"; 1374 private static final String ATTR_USER_SET = "set"; 1375 private static final String ATTR_USER_FIXED = "fixed"; 1376 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1377 1378 // System/policy permission grants are not backed up 1379 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1380 FLAG_PERMISSION_POLICY_FIXED 1381 | FLAG_PERMISSION_SYSTEM_FIXED 1382 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1383 1384 // And we back up these user-adjusted states 1385 private static final int USER_RUNTIME_GRANT_MASK = 1386 FLAG_PERMISSION_USER_SET 1387 | FLAG_PERMISSION_USER_FIXED 1388 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1389 1390 final @Nullable String mRequiredVerifierPackage; 1391 final @NonNull String mRequiredInstallerPackage; 1392 final @NonNull String mRequiredUninstallerPackage; 1393 final @NonNull String mRequiredPermissionControllerPackage; 1394 final @Nullable String mSetupWizardPackage; 1395 final @Nullable String mStorageManagerPackage; 1396 final @Nullable String mSystemTextClassifierPackage; 1397 final @Nullable String mWellbeingPackage; 1398 final @Nullable String mDocumenterPackage; 1399 final @Nullable String mConfiguratorPackage; 1400 final @Nullable String mAppPredictionServicePackage; 1401 final @Nullable String mIncidentReportApproverPackage; 1402 final @NonNull String mServicesSystemSharedLibraryPackageName; 1403 final @NonNull String mSharedSystemSharedLibraryPackageName; 1404 1405 private final PackageUsage mPackageUsage = new PackageUsage(); 1406 private final CompilerStats mCompilerStats = new CompilerStats(); 1407 1408 class PackageHandler extends Handler { 1409 PackageHandler(Looper looper)1410 PackageHandler(Looper looper) { 1411 super(looper); 1412 } 1413 handleMessage(Message msg)1414 public void handleMessage(Message msg) { 1415 try { 1416 doHandleMessage(msg); 1417 } finally { 1418 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1419 } 1420 } 1421 doHandleMessage(Message msg)1422 void doHandleMessage(Message msg) { 1423 switch (msg.what) { 1424 case INIT_COPY: { 1425 HandlerParams params = (HandlerParams) msg.obj; 1426 if (params != null) { 1427 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy: " + params); 1428 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1429 System.identityHashCode(params)); 1430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1431 params.startCopy(); 1432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1433 } 1434 break; 1435 } 1436 case SEND_PENDING_BROADCAST: { 1437 String packages[]; 1438 ArrayList<String> components[]; 1439 int size = 0; 1440 int uids[]; 1441 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1442 synchronized (mPackages) { 1443 size = mPendingBroadcasts.size(); 1444 if (size <= 0) { 1445 // Nothing to be done. Just return 1446 return; 1447 } 1448 packages = new String[size]; 1449 components = new ArrayList[size]; 1450 uids = new int[size]; 1451 int i = 0; // filling out the above arrays 1452 1453 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1454 int packageUserId = mPendingBroadcasts.userIdAt(n); 1455 Iterator<Map.Entry<String, ArrayList<String>>> it 1456 = mPendingBroadcasts.packagesForUserId(packageUserId) 1457 .entrySet().iterator(); 1458 while (it.hasNext() && i < size) { 1459 Map.Entry<String, ArrayList<String>> ent = it.next(); 1460 packages[i] = ent.getKey(); 1461 components[i] = ent.getValue(); 1462 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1463 uids[i] = (ps != null) 1464 ? UserHandle.getUid(packageUserId, ps.appId) 1465 : -1; 1466 i++; 1467 } 1468 } 1469 size = i; 1470 mPendingBroadcasts.clear(); 1471 } 1472 // Send broadcasts 1473 for (int i = 0; i < size; i++) { 1474 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1475 } 1476 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1477 break; 1478 } 1479 case POST_INSTALL: { 1480 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1481 1482 PostInstallData data = mRunningInstalls.get(msg.arg1); 1483 final boolean didRestore = (msg.arg2 != 0); 1484 mRunningInstalls.delete(msg.arg1); 1485 1486 if (data != null && data.mPostInstallRunnable != null) { 1487 data.mPostInstallRunnable.run(); 1488 } else if (data != null) { 1489 InstallArgs args = data.args; 1490 PackageInstalledInfo parentRes = data.res; 1491 1492 final boolean grantPermissions = (args.installFlags 1493 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1494 final boolean killApp = (args.installFlags 1495 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1496 final boolean virtualPreload = ((args.installFlags 1497 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1498 final String[] grantedPermissions = args.installGrantPermissions; 1499 final List<String> whitelistedRestrictedPermissions = ((args.installFlags 1500 & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) != 0 1501 && parentRes.pkg != null) 1502 ? parentRes.pkg.requestedPermissions 1503 : args.whitelistedRestrictedPermissions; 1504 1505 // Handle the parent package 1506 handlePackagePostInstall(parentRes, grantPermissions, 1507 killApp, virtualPreload, grantedPermissions, 1508 whitelistedRestrictedPermissions, didRestore, 1509 args.installerPackageName, args.observer); 1510 1511 // Handle the child packages 1512 final int childCount = (parentRes.addedChildPackages != null) 1513 ? parentRes.addedChildPackages.size() : 0; 1514 for (int i = 0; i < childCount; i++) { 1515 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1516 handlePackagePostInstall(childRes, grantPermissions, 1517 killApp, virtualPreload, grantedPermissions, 1518 whitelistedRestrictedPermissions, false /*didRestore*/, 1519 args.installerPackageName, args.observer); 1520 } 1521 1522 // Log tracing if needed 1523 if (args.traceMethod != null) { 1524 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1525 args.traceCookie); 1526 } 1527 } else if (DEBUG_INSTALL) { 1528 // No post-install when we run restore from installExistingPackageForUser 1529 Slog.i(TAG, "Nothing to do for post-install token " + msg.arg1); 1530 } 1531 1532 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1533 } break; 1534 case DEFERRED_NO_KILL_POST_DELETE: { 1535 synchronized (mInstallLock) { 1536 InstallArgs args = (InstallArgs) msg.obj; 1537 if (args != null) { 1538 args.doPostDeleteLI(true); 1539 } 1540 } 1541 } break; 1542 case DEFERRED_NO_KILL_INSTALL_OBSERVER: { 1543 String packageName = (String) msg.obj; 1544 if (packageName != null) { 1545 notifyInstallObserver(packageName); 1546 } 1547 } break; 1548 case WRITE_SETTINGS: { 1549 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1550 synchronized (mPackages) { 1551 removeMessages(WRITE_SETTINGS); 1552 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1553 mSettings.writeLPr(); 1554 mDirtyUsers.clear(); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 } break; 1558 case WRITE_PACKAGE_RESTRICTIONS: { 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1560 synchronized (mPackages) { 1561 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1562 for (int userId : mDirtyUsers) { 1563 mSettings.writePackageRestrictionsLPr(userId); 1564 } 1565 mDirtyUsers.clear(); 1566 } 1567 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1568 } break; 1569 case WRITE_PACKAGE_LIST: { 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1571 synchronized (mPackages) { 1572 removeMessages(WRITE_PACKAGE_LIST); 1573 mSettings.writePackageListLPr(msg.arg1); 1574 } 1575 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1576 } break; 1577 case CHECK_PENDING_VERIFICATION: { 1578 final int verificationId = msg.arg1; 1579 final PackageVerificationState state = mPendingVerification.get(verificationId); 1580 1581 if ((state != null) && !state.timeoutExtended()) { 1582 final InstallParams params = state.getInstallParams(); 1583 final InstallArgs args = params.mArgs; 1584 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1585 1586 Slog.i(TAG, "Verification timed out for " + originUri); 1587 mPendingVerification.remove(verificationId); 1588 1589 final UserHandle user = args.getUser(); 1590 if (getDefaultVerificationResponse(user) 1591 == PackageManager.VERIFICATION_ALLOW) { 1592 Slog.i(TAG, "Continuing with installation of " + originUri); 1593 state.setVerifierResponse(Binder.getCallingUid(), 1594 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1595 broadcastPackageVerified(verificationId, originUri, 1596 PackageManager.VERIFICATION_ALLOW, user); 1597 } else { 1598 broadcastPackageVerified(verificationId, originUri, 1599 PackageManager.VERIFICATION_REJECT, user); 1600 params.setReturnCode( 1601 PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE); 1602 } 1603 1604 Trace.asyncTraceEnd( 1605 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1606 params.handleVerificationFinished(); 1607 } 1608 break; 1609 } 1610 case PACKAGE_VERIFIED: { 1611 final int verificationId = msg.arg1; 1612 1613 final PackageVerificationState state = mPendingVerification.get(verificationId); 1614 if (state == null) { 1615 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1616 break; 1617 } 1618 1619 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1620 1621 state.setVerifierResponse(response.callerUid, response.code); 1622 1623 if (state.isVerificationComplete()) { 1624 mPendingVerification.remove(verificationId); 1625 1626 final InstallParams params = state.getInstallParams(); 1627 final InstallArgs args = params.mArgs; 1628 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1629 1630 if (state.isInstallAllowed()) { 1631 broadcastPackageVerified(verificationId, originUri, 1632 response.code, args.getUser()); 1633 } else { 1634 params.setReturnCode( 1635 PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE); 1636 } 1637 1638 Trace.asyncTraceEnd( 1639 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1640 1641 params.handleVerificationFinished(); 1642 } 1643 1644 break; 1645 } 1646 case START_INTENT_FILTER_VERIFICATIONS: { 1647 IFVerificationParams params = (IFVerificationParams) msg.obj; 1648 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1649 params.replacing, params.pkg); 1650 break; 1651 } 1652 case INTENT_FILTER_VERIFIED: { 1653 final int verificationId = msg.arg1; 1654 1655 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1656 verificationId); 1657 if (state == null) { 1658 Slog.w(TAG, "Invalid IntentFilter verification token " 1659 + verificationId + " received"); 1660 break; 1661 } 1662 1663 final int userId = state.getUserId(); 1664 1665 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1666 "Processing IntentFilter verification with token:" 1667 + verificationId + " and userId:" + userId); 1668 1669 final IntentFilterVerificationResponse response = 1670 (IntentFilterVerificationResponse) msg.obj; 1671 1672 state.setVerifierResponse(response.callerUid, response.code); 1673 1674 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1675 "IntentFilter verification with token:" + verificationId 1676 + " and userId:" + userId 1677 + " is settings verifier response with response code:" 1678 + response.code); 1679 1680 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1682 + response.getFailedDomainsString()); 1683 } 1684 1685 if (state.isVerificationComplete()) { 1686 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1687 } else { 1688 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1689 "IntentFilter verification with token:" + verificationId 1690 + " was not said to be complete"); 1691 } 1692 1693 break; 1694 } 1695 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1696 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1697 mInstantAppResolverConnection, 1698 (InstantAppRequest) msg.obj, 1699 mInstantAppInstallerActivity, 1700 mHandler); 1701 break; 1702 } 1703 case ENABLE_ROLLBACK_STATUS: { 1704 final int enableRollbackToken = msg.arg1; 1705 final int enableRollbackCode = msg.arg2; 1706 InstallParams params = mPendingEnableRollback.get(enableRollbackToken); 1707 if (params == null) { 1708 Slog.w(TAG, "Invalid rollback enabled token " 1709 + enableRollbackToken + " received"); 1710 break; 1711 } 1712 1713 mPendingEnableRollback.remove(enableRollbackToken); 1714 1715 if (enableRollbackCode != PackageManagerInternal.ENABLE_ROLLBACK_SUCCEEDED) { 1716 final InstallArgs args = params.mArgs; 1717 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1718 Slog.w(TAG, "Failed to enable rollback for " + originUri); 1719 Slog.w(TAG, "Continuing with installation of " + originUri); 1720 } 1721 1722 Trace.asyncTraceEnd( 1723 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 1724 1725 params.handleRollbackEnabled(); 1726 break; 1727 } 1728 case ENABLE_ROLLBACK_TIMEOUT: { 1729 final int enableRollbackToken = msg.arg1; 1730 final InstallParams params = mPendingEnableRollback.get(enableRollbackToken); 1731 if (params != null) { 1732 final InstallArgs args = params.mArgs; 1733 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1734 1735 Slog.w(TAG, "Enable rollback timed out for " + originUri); 1736 mPendingEnableRollback.remove(enableRollbackToken); 1737 1738 Slog.w(TAG, "Continuing with installation of " + originUri); 1739 Trace.asyncTraceEnd( 1740 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 1741 params.handleRollbackEnabled(); 1742 Intent rollbackTimeoutIntent = new Intent( 1743 Intent.ACTION_CANCEL_ENABLE_ROLLBACK); 1744 rollbackTimeoutIntent.putExtra( 1745 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN, 1746 enableRollbackToken); 1747 rollbackTimeoutIntent.addFlags( 1748 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1749 mContext.sendBroadcastAsUser(rollbackTimeoutIntent, UserHandle.SYSTEM, 1750 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT); 1751 } 1752 break; 1753 } 1754 } 1755 } 1756 } 1757 1758 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1759 @Override 1760 public void onGidsChanged(int appId, int userId) { 1761 mHandler.post(() -> killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED)); 1762 } 1763 @Override 1764 public void onPermissionGranted(int uid, int userId) { 1765 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1766 1767 // Not critical; if this is lost, the application has to request again. 1768 synchronized (mPackages) { 1769 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1770 } 1771 } 1772 @Override 1773 public void onInstallPermissionGranted() { 1774 synchronized (mPackages) { 1775 scheduleWriteSettingsLocked(); 1776 } 1777 } 1778 @Override 1779 public void onPermissionRevoked(int uid, int userId) { 1780 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1781 1782 synchronized (mPackages) { 1783 // Critical; after this call the application should never have the permission 1784 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1785 } 1786 1787 final int appId = UserHandle.getAppId(uid); 1788 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1789 } 1790 @Override 1791 public void onInstallPermissionRevoked() { 1792 synchronized (mPackages) { 1793 scheduleWriteSettingsLocked(); 1794 } 1795 } 1796 @Override 1797 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1798 synchronized (mPackages) { 1799 for (int userId : updatedUserIds) { 1800 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1801 } 1802 } 1803 } 1804 @Override 1805 public void onInstallPermissionUpdated() { 1806 synchronized (mPackages) { 1807 scheduleWriteSettingsLocked(); 1808 } 1809 } 1810 @Override 1811 public void onPermissionRemoved() { 1812 synchronized (mPackages) { 1813 mSettings.writeLPr(); 1814 } 1815 } 1816 }; 1817 handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, boolean killApp, boolean virtualPreload, String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, boolean launchedForRestore, String installerPackage, IPackageInstallObserver2 installObserver)1818 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1819 boolean killApp, boolean virtualPreload, 1820 String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, 1821 boolean launchedForRestore, String installerPackage, 1822 IPackageInstallObserver2 installObserver) { 1823 final boolean succeeded = res.returnCode == PackageManager.INSTALL_SUCCEEDED; 1824 final boolean update = res.removedInfo != null && res.removedInfo.removedPackage != null; 1825 1826 if (succeeded) { 1827 // Send the removed broadcasts 1828 if (res.removedInfo != null) { 1829 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1830 } 1831 1832 // Whitelist any restricted permissions first as some may be runtime 1833 // that the installer requested to be granted at install time. 1834 if (whitelistedRestrictedPermissions != null 1835 && !whitelistedRestrictedPermissions.isEmpty()) { 1836 mPermissionManager.setWhitelistedRestrictedPermissions( 1837 res.pkg, res.newUsers, whitelistedRestrictedPermissions, 1838 Process.myUid(), PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER, 1839 mPermissionCallback); 1840 } 1841 1842 // Now that we successfully installed the package, grant runtime 1843 // permissions if requested before broadcasting the install. Also 1844 // for legacy apps in permission review mode we clear the permission 1845 // review flag which is used to emulate runtime permissions for 1846 // legacy apps. 1847 if (grantPermissions) { 1848 final int callingUid = Binder.getCallingUid(); 1849 mPermissionManager.grantRequestedRuntimePermissions( 1850 res.pkg, res.newUsers, grantedPermissions, callingUid, 1851 mPermissionCallback); 1852 } 1853 1854 final String installerPackageName = 1855 res.installerPackageName != null 1856 ? res.installerPackageName 1857 : res.removedInfo != null 1858 ? res.removedInfo.installerPackageName 1859 : null; 1860 1861 // If this is the first time we have child packages for a disabled privileged 1862 // app that had no children, we grant requested runtime permissions to the new 1863 // children if the parent on the system image had them already granted. 1864 if (res.pkg.parentPackage != null) { 1865 final int callingUid = Binder.getCallingUid(); 1866 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1867 res.pkg, callingUid, mPermissionCallback); 1868 } 1869 1870 synchronized (mPackages) { 1871 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1872 } 1873 1874 final String packageName = res.pkg.applicationInfo.packageName; 1875 1876 // Determine the set of users who are adding this package for 1877 // the first time vs. those who are seeing an update. 1878 int[] firstUserIds = EMPTY_INT_ARRAY; 1879 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1880 int[] updateUserIds = EMPTY_INT_ARRAY; 1881 int[] instantUserIds = EMPTY_INT_ARRAY; 1882 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1883 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1884 for (int newUser : res.newUsers) { 1885 final boolean isInstantApp = ps.getInstantApp(newUser); 1886 if (allNewUsers) { 1887 if (isInstantApp) { 1888 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1889 } else { 1890 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1891 } 1892 continue; 1893 } 1894 boolean isNew = true; 1895 for (int origUser : res.origUsers) { 1896 if (origUser == newUser) { 1897 isNew = false; 1898 break; 1899 } 1900 } 1901 if (isNew) { 1902 if (isInstantApp) { 1903 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1904 } else { 1905 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1906 } 1907 } else { 1908 if (isInstantApp) { 1909 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 1910 } else { 1911 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 1912 } 1913 } 1914 } 1915 1916 // Send installed broadcasts if the package is not a static shared lib. 1917 if (res.pkg.staticSharedLibName == null) { 1918 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1919 1920 // Send added for users that see the package for the first time 1921 // sendPackageAddedForNewUsers also deals with system apps 1922 int appId = UserHandle.getAppId(res.uid); 1923 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1924 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 1925 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 1926 1927 // Send added for users that don't see the package for the first time 1928 Bundle extras = new Bundle(1); 1929 extras.putInt(Intent.EXTRA_UID, res.uid); 1930 if (update) { 1931 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1932 } 1933 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1934 extras, 0 /*flags*/, 1935 null /*targetPackage*/, null /*finishedReceiver*/, 1936 updateUserIds, instantUserIds); 1937 if (installerPackageName != null) { 1938 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1939 extras, 0 /*flags*/, 1940 installerPackageName, null /*finishedReceiver*/, 1941 updateUserIds, instantUserIds); 1942 } 1943 // if the required verifier is defined, but, is not the installer of record 1944 // for the package, it gets notified 1945 final boolean notifyVerifier = mRequiredVerifierPackage != null 1946 && !mRequiredVerifierPackage.equals(installerPackageName); 1947 if (notifyVerifier) { 1948 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1949 extras, 0 /*flags*/, 1950 mRequiredVerifierPackage, null /*finishedReceiver*/, 1951 updateUserIds, instantUserIds); 1952 } 1953 // If package installer is defined, notify package installer about new 1954 // app installed 1955 if (mRequiredInstallerPackage != null) { 1956 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1957 extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND /*flags*/, 1958 mRequiredInstallerPackage, null /*finishedReceiver*/, 1959 firstUserIds, instantUserIds); 1960 } 1961 1962 // Send replaced for users that don't see the package for the first time 1963 if (update) { 1964 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1965 packageName, extras, 0 /*flags*/, 1966 null /*targetPackage*/, null /*finishedReceiver*/, 1967 updateUserIds, instantUserIds); 1968 if (installerPackageName != null) { 1969 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1970 extras, 0 /*flags*/, 1971 installerPackageName, null /*finishedReceiver*/, 1972 updateUserIds, instantUserIds); 1973 } 1974 if (notifyVerifier) { 1975 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 1976 extras, 0 /*flags*/, 1977 mRequiredVerifierPackage, null /*finishedReceiver*/, 1978 updateUserIds, instantUserIds); 1979 } 1980 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1981 null /*package*/, null /*extras*/, 0 /*flags*/, 1982 packageName /*targetPackage*/, 1983 null /*finishedReceiver*/, updateUserIds, instantUserIds); 1984 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1985 // First-install and we did a restore, so we're responsible for the 1986 // first-launch broadcast. 1987 if (DEBUG_BACKUP) { 1988 Slog.i(TAG, "Post-restore of " + packageName 1989 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 1990 } 1991 sendFirstLaunchBroadcast(packageName, installerPackage, 1992 firstUserIds, firstInstantUserIds); 1993 } 1994 1995 // Send broadcast package appeared if external for all users 1996 if (isExternal(res.pkg)) { 1997 if (!update) { 1998 final StorageManager storage = 1999 mContext.getSystemService(StorageManager.class); 2000 VolumeInfo volume = 2001 storage.findVolumeByUuid( 2002 res.pkg.applicationInfo.storageUuid.toString()); 2003 int packageExternalStorageType = 2004 getPackageExternalStorageType(volume, isExternal(res.pkg)); 2005 // If the package was installed externally, log it. 2006 if (packageExternalStorageType != StorageEnums.UNKNOWN) { 2007 StatsLog.write(StatsLog.APP_INSTALL_ON_EXTERNAL_STORAGE_REPORTED, 2008 packageExternalStorageType, res.pkg.packageName); 2009 } 2010 } 2011 if (DEBUG_INSTALL) { 2012 Slog.i(TAG, "upgrading pkg " + res.pkg + " is external"); 2013 } 2014 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2015 ArrayList<String> pkgList = new ArrayList<>(1); 2016 pkgList.add(packageName); 2017 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2018 } 2019 } 2020 2021 // Work that needs to happen on first install within each user 2022 if (firstUserIds != null && firstUserIds.length > 0) { 2023 for (int userId : firstUserIds) { 2024 // If this app is a browser and it's newly-installed for some 2025 // users, clear any default-browser state in those users. The 2026 // app's nature doesn't depend on the user, so we can just check 2027 // its browser nature in any user and generalize. 2028 if (packageIsBrowser(packageName, userId)) { 2029 // If this browser is restored from user's backup, do not clear 2030 // default-browser state for this user 2031 synchronized (mPackages) { 2032 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 2033 if (pkgSetting.getInstallReason(userId) 2034 != PackageManager.INSTALL_REASON_DEVICE_RESTORE) { 2035 setDefaultBrowserAsyncLPw(null, userId); 2036 } 2037 } 2038 } 2039 2040 // We may also need to apply pending (restored) runtime permission grants 2041 // within these users. 2042 mPermissionManager.restoreDelayedRuntimePermissions(packageName, 2043 UserHandle.of(userId)); 2044 2045 // Persistent preferred activity might have came into effect due to this 2046 // install. 2047 updateDefaultHomeNotLocked(userId); 2048 } 2049 } 2050 2051 if (allNewUsers && !update) { 2052 notifyPackageAdded(packageName, res.uid); 2053 } else { 2054 notifyPackageChanged(packageName, res.uid); 2055 } 2056 2057 // Log current value of "unknown sources" setting 2058 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2059 getUnknownSourcesSettings()); 2060 2061 // Remove the replaced package's older resources safely now 2062 InstallArgs args = res.removedInfo != null ? res.removedInfo.args : null; 2063 if (args != null) { 2064 if (!killApp) { 2065 // If we didn't kill the app, defer the deletion of code/resource files, since 2066 // they may still be in use by the running application. This mitigates problems 2067 // in cases where resources or code is loaded by a new Activity before 2068 // ApplicationInfo changes have propagated to all application threads. 2069 scheduleDeferredNoKillPostDelete(args); 2070 } else { 2071 synchronized (mInstallLock) { 2072 args.doPostDeleteLI(true); 2073 } 2074 } 2075 } else { 2076 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2077 // and not block here. 2078 VMRuntime.getRuntime().requestConcurrentGC(); 2079 } 2080 2081 // Notify DexManager that the package was installed for new users. 2082 // The updated users should already be indexed and the package code paths 2083 // should not change. 2084 // Don't notify the manager for ephemeral apps as they are not expected to 2085 // survive long enough to benefit of background optimizations. 2086 for (int userId : firstUserIds) { 2087 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2088 // There's a race currently where some install events may interleave with an uninstall. 2089 // This can lead to package info being null (b/36642664). 2090 if (info != null) { 2091 mDexManager.notifyPackageInstalled(info, userId); 2092 } 2093 } 2094 } 2095 2096 final boolean deferInstallObserver = succeeded && update && !killApp; 2097 if (deferInstallObserver) { 2098 scheduleDeferredNoKillInstallObserver(res, installObserver); 2099 } else { 2100 notifyInstallObserver(res, installObserver); 2101 } 2102 } 2103 2104 @Override notifyPackagesReplacedReceived(String[] packages)2105 public void notifyPackagesReplacedReceived(String[] packages) { 2106 final int callingUid = Binder.getCallingUid(); 2107 final int callingUserId = UserHandle.getUserId(callingUid); 2108 2109 for (String packageName : packages) { 2110 PackageSetting setting = mSettings.mPackages.get(packageName); 2111 if (setting != null && filterAppAccessLPr(setting, callingUid, callingUserId)) { 2112 notifyInstallObserver(packageName); 2113 } 2114 } 2115 } 2116 notifyInstallObserver(String packageName)2117 private void notifyInstallObserver(String packageName) { 2118 Pair<PackageInstalledInfo, IPackageInstallObserver2> pair = 2119 mNoKillInstallObservers.remove(packageName); 2120 2121 if (pair != null) { 2122 notifyInstallObserver(pair.first, pair.second); 2123 } 2124 } 2125 notifyInstallObserver(PackageInstalledInfo info, IPackageInstallObserver2 installObserver)2126 private void notifyInstallObserver(PackageInstalledInfo info, 2127 IPackageInstallObserver2 installObserver) { 2128 if (installObserver != null) { 2129 try { 2130 Bundle extras = extrasForInstallResult(info); 2131 installObserver.onPackageInstalled(info.name, info.returnCode, 2132 info.returnMsg, extras); 2133 } catch (RemoteException e) { 2134 Slog.i(TAG, "Observer no longer exists."); 2135 } 2136 } 2137 } 2138 scheduleDeferredNoKillPostDelete(InstallArgs args)2139 private void scheduleDeferredNoKillPostDelete(InstallArgs args) { 2140 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_POST_DELETE, args); 2141 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_POST_DELETE_DELAY_MS); 2142 } 2143 scheduleDeferredNoKillInstallObserver(PackageInstalledInfo info, IPackageInstallObserver2 observer)2144 private void scheduleDeferredNoKillInstallObserver(PackageInstalledInfo info, 2145 IPackageInstallObserver2 observer) { 2146 String packageName = info.pkg.packageName; 2147 mNoKillInstallObservers.put(packageName, Pair.create(info, observer)); 2148 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_INSTALL_OBSERVER, packageName); 2149 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS); 2150 } 2151 2152 /** 2153 * Gets the type of the external storage a package is installed on. 2154 * @param packageVolume The storage volume of the package. 2155 * @param packageIsExternal true if the package is currently installed on 2156 * external/removable/unprotected storage. 2157 * @return {@link StorageEnum#TYPE_UNKNOWN} if the package is not stored externally or the 2158 * corresponding {@link StorageEnum} storage type value if it is. 2159 */ getPackageExternalStorageType(VolumeInfo packageVolume, boolean packageIsExternal)2160 private static int getPackageExternalStorageType(VolumeInfo packageVolume, 2161 boolean packageIsExternal) { 2162 if (packageVolume != null) { 2163 DiskInfo disk = packageVolume.getDisk(); 2164 if (disk != null) { 2165 if (disk.isSd()) { 2166 return StorageEnums.SD_CARD; 2167 } 2168 if (disk.isUsb()) { 2169 return StorageEnums.USB; 2170 } 2171 if (packageIsExternal) { 2172 return StorageEnums.OTHER; 2173 } 2174 } 2175 } 2176 return StorageEnums.UNKNOWN; 2177 } 2178 2179 private StorageEventListener mStorageListener = new StorageEventListener() { 2180 @Override 2181 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2182 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2183 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2184 final String volumeUuid = vol.getFsUuid(); 2185 2186 // Clean up any users or apps that were removed or recreated 2187 // while this volume was missing 2188 sUserManager.reconcileUsers(volumeUuid); 2189 reconcileApps(volumeUuid); 2190 2191 // Clean up any install sessions that expired or were 2192 // cancelled while this volume was missing 2193 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2194 2195 loadPrivatePackages(vol); 2196 2197 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2198 unloadPrivatePackages(vol); 2199 } 2200 } 2201 } 2202 2203 @Override 2204 public void onVolumeForgotten(String fsUuid) { 2205 if (TextUtils.isEmpty(fsUuid)) { 2206 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2207 return; 2208 } 2209 2210 // Remove any apps installed on the forgotten volume 2211 synchronized (mPackages) { 2212 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2213 for (PackageSetting ps : packages) { 2214 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2215 deletePackageVersioned(new VersionedPackage(ps.name, 2216 PackageManager.VERSION_CODE_HIGHEST), 2217 new LegacyPackageDeleteObserver(null).getBinder(), 2218 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2219 // Try very hard to release any references to this package 2220 // so we don't risk the system server being killed due to 2221 // open FDs 2222 AttributeCache.instance().removePackage(ps.name); 2223 } 2224 2225 mSettings.onVolumeForgotten(fsUuid); 2226 mSettings.writeLPr(); 2227 } 2228 } 2229 }; 2230 extrasForInstallResult(PackageInstalledInfo res)2231 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2232 Bundle extras = null; 2233 switch (res.returnCode) { 2234 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2235 extras = new Bundle(); 2236 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2237 res.origPermission); 2238 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2239 res.origPackage); 2240 break; 2241 } 2242 case PackageManager.INSTALL_SUCCEEDED: { 2243 extras = new Bundle(); 2244 extras.putBoolean(Intent.EXTRA_REPLACING, 2245 res.removedInfo != null && res.removedInfo.removedPackage != null); 2246 break; 2247 } 2248 } 2249 return extras; 2250 } 2251 scheduleWriteSettingsLocked()2252 void scheduleWriteSettingsLocked() { 2253 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2254 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2255 } 2256 } 2257 scheduleWritePackageListLocked(int userId)2258 void scheduleWritePackageListLocked(int userId) { 2259 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2260 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2261 msg.arg1 = userId; 2262 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2263 } 2264 } 2265 scheduleWritePackageRestrictionsLocked(UserHandle user)2266 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2267 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2268 scheduleWritePackageRestrictionsLocked(userId); 2269 } 2270 scheduleWritePackageRestrictionsLocked(int userId)2271 void scheduleWritePackageRestrictionsLocked(int userId) { 2272 final int[] userIds = (userId == UserHandle.USER_ALL) 2273 ? sUserManager.getUserIds() : new int[]{userId}; 2274 for (int nextUserId : userIds) { 2275 if (!sUserManager.exists(nextUserId)) return; 2276 mDirtyUsers.add(nextUserId); 2277 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2278 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2279 } 2280 } 2281 } 2282 main(Context context, Installer installer, boolean factoryTest, boolean onlyCore)2283 public static PackageManagerService main(Context context, Installer installer, 2284 boolean factoryTest, boolean onlyCore) { 2285 // Self-check for initial settings. 2286 PackageManagerServiceCompilerMapping.checkProperties(); 2287 2288 PackageManagerService m = new PackageManagerService(context, installer, 2289 factoryTest, onlyCore); 2290 m.enableSystemUserPackages(); 2291 ServiceManager.addService("package", m); 2292 final PackageManagerNative pmn = m.new PackageManagerNative(); 2293 ServiceManager.addService("package_native", pmn); 2294 return m; 2295 } 2296 enableSystemUserPackages()2297 private void enableSystemUserPackages() { 2298 if (!UserManager.isSplitSystemUser()) { 2299 return; 2300 } 2301 // For system user, enable apps based on the following conditions: 2302 // - app is whitelisted or belong to one of these groups: 2303 // -- system app which has no launcher icons 2304 // -- system app which has INTERACT_ACROSS_USERS permission 2305 // -- system IME app 2306 // - app is not in the blacklist 2307 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2308 Set<String> enableApps = new ArraySet<>(); 2309 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2310 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2311 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2312 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2313 enableApps.addAll(wlApps); 2314 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2315 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2316 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2317 enableApps.removeAll(blApps); 2318 Log.i(TAG, "Applications installed for system user: " + enableApps); 2319 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2320 UserHandle.SYSTEM); 2321 final int allAppsSize = allAps.size(); 2322 synchronized (mPackages) { 2323 for (int i = 0; i < allAppsSize; i++) { 2324 String pName = allAps.get(i); 2325 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2326 // Should not happen, but we shouldn't be failing if it does 2327 if (pkgSetting == null) { 2328 continue; 2329 } 2330 boolean install = enableApps.contains(pName); 2331 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2332 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2333 + " for system user"); 2334 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2335 } 2336 } 2337 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2338 } 2339 } 2340 getDefaultDisplayMetrics(Context context, DisplayMetrics metrics)2341 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2342 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2343 Context.DISPLAY_SERVICE); 2344 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2345 } 2346 2347 /** 2348 * Requests that files preopted on a secondary system partition be copied to the data partition 2349 * if possible. Note that the actual copying of the files is accomplished by init for security 2350 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2351 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2352 */ requestCopyPreoptedFiles()2353 private static void requestCopyPreoptedFiles() { 2354 final int WAIT_TIME_MS = 100; 2355 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2356 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2357 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2358 // We will wait for up to 100 seconds. 2359 final long timeStart = SystemClock.uptimeMillis(); 2360 final long timeEnd = timeStart + 100 * 1000; 2361 long timeNow = timeStart; 2362 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2363 try { 2364 Thread.sleep(WAIT_TIME_MS); 2365 } catch (InterruptedException e) { 2366 // Do nothing 2367 } 2368 timeNow = SystemClock.uptimeMillis(); 2369 if (timeNow > timeEnd) { 2370 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2371 Slog.wtf(TAG, "cppreopt did not finish!"); 2372 break; 2373 } 2374 } 2375 2376 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2377 } 2378 } 2379 PackageManagerService(Context context, Installer installer, boolean factoryTest, boolean onlyCore)2380 public PackageManagerService(Context context, Installer installer, 2381 boolean factoryTest, boolean onlyCore) { 2382 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2383 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2384 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2385 SystemClock.uptimeMillis()); 2386 2387 if (mSdkVersion <= 0) { 2388 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2389 } 2390 2391 mContext = context; 2392 2393 mFactoryTest = factoryTest; 2394 mOnlyCore = onlyCore; 2395 mMetrics = new DisplayMetrics(); 2396 mInstaller = installer; 2397 2398 // Create sub-components that provide services / data. Order here is important. 2399 synchronized (mInstallLock) { 2400 synchronized (mPackages) { 2401 // Expose private service for system components to use. 2402 LocalServices.addService( 2403 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2404 sUserManager = new UserManagerService(context, this, 2405 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2406 mComponentResolver = new ComponentResolver(sUserManager, 2407 LocalServices.getService(PackageManagerInternal.class), 2408 mPackages); 2409 mPermissionManager = PermissionManagerService.create(context, 2410 mPackages /*externalLock*/); 2411 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2412 mSettings = new Settings(Environment.getDataDirectory(), 2413 mPermissionManager.getPermissionSettings(), mPackages); 2414 } 2415 } 2416 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2417 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2418 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2419 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2420 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2421 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2422 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2423 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2424 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2425 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2426 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2427 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2428 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2429 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2430 mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID, 2431 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2432 2433 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2434 if (separateProcesses != null && separateProcesses.length() > 0) { 2435 if ("*".equals(separateProcesses)) { 2436 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2437 mSeparateProcesses = null; 2438 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2439 } else { 2440 mDefParseFlags = 0; 2441 mSeparateProcesses = separateProcesses.split(","); 2442 Slog.w(TAG, "Running with debug.separate_processes: " 2443 + separateProcesses); 2444 } 2445 } else { 2446 mDefParseFlags = 0; 2447 mSeparateProcesses = null; 2448 } 2449 2450 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2451 "*dexopt*"); 2452 mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock); 2453 mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock); 2454 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2455 2456 mViewCompiler = new ViewCompiler(mInstallLock, mInstaller); 2457 2458 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2459 FgThread.get().getLooper()); 2460 2461 getDefaultDisplayMetrics(context, mMetrics); 2462 2463 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2464 SystemConfig systemConfig = SystemConfig.getInstance(); 2465 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2466 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2467 2468 mProtectedPackages = new ProtectedPackages(mContext); 2469 2470 mApexManager = new ApexManager(context); 2471 synchronized (mInstallLock) { 2472 // writer 2473 synchronized (mPackages) { 2474 mHandlerThread = new ServiceThread(TAG, 2475 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2476 mHandlerThread.start(); 2477 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2478 mProcessLoggingHandler = new ProcessLoggingHandler(); 2479 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2480 mInstantAppRegistry = new InstantAppRegistry(this); 2481 2482 ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig 2483 = systemConfig.getSharedLibraries(); 2484 final int builtInLibCount = libConfig.size(); 2485 for (int i = 0; i < builtInLibCount; i++) { 2486 String name = libConfig.keyAt(i); 2487 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i); 2488 addBuiltInSharedLibraryLocked(entry.filename, name); 2489 } 2490 2491 // Now that we have added all the libraries, iterate again to add dependency 2492 // information IFF their dependencies are added. 2493 long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED; 2494 for (int i = 0; i < builtInLibCount; i++) { 2495 String name = libConfig.keyAt(i); 2496 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i); 2497 final int dependencyCount = entry.dependencies.length; 2498 for (int j = 0; j < dependencyCount; j++) { 2499 final SharedLibraryInfo dependency = 2500 getSharedLibraryInfoLPr(entry.dependencies[j], undefinedVersion); 2501 if (dependency != null) { 2502 getSharedLibraryInfoLPr(name, undefinedVersion).addDependency(dependency); 2503 } 2504 } 2505 } 2506 2507 SELinuxMMAC.readInstallPolicy(); 2508 2509 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2510 FallbackCategoryProvider.loadFallbacks(); 2511 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2512 2513 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2514 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2515 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2516 2517 // Clean up orphaned packages for which the code path doesn't exist 2518 // and they are an update to a system app - caused by bug/32321269 2519 final int packageSettingCount = mSettings.mPackages.size(); 2520 for (int i = packageSettingCount - 1; i >= 0; i--) { 2521 PackageSetting ps = mSettings.mPackages.valueAt(i); 2522 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2523 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2524 mSettings.mPackages.removeAt(i); 2525 mSettings.enableSystemPackageLPw(ps.name); 2526 } 2527 } 2528 2529 if (!mOnlyCore && mFirstBoot) { 2530 requestCopyPreoptedFiles(); 2531 } 2532 2533 String customResolverActivityName = Resources.getSystem().getString( 2534 R.string.config_customResolverActivity); 2535 if (!TextUtils.isEmpty(customResolverActivityName)) { 2536 mCustomResolverComponentName = ComponentName.unflattenFromString( 2537 customResolverActivityName); 2538 } 2539 2540 long startTime = SystemClock.uptimeMillis(); 2541 2542 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2543 startTime); 2544 2545 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2546 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2547 2548 if (bootClassPath == null) { 2549 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2550 } 2551 2552 if (systemServerClassPath == null) { 2553 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2554 } 2555 2556 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2557 2558 final VersionInfo ver = mSettings.getInternalVersion(); 2559 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2560 if (mIsUpgrade) { 2561 logCriticalInfo(Log.INFO, 2562 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2563 } 2564 2565 // when upgrading from pre-M, promote system app permissions from install to runtime 2566 mPromoteSystemApps = 2567 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2568 2569 // When upgrading from pre-N, we need to handle package extraction like first boot, 2570 // as there is no profiling data available. 2571 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2572 2573 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2574 mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q; 2575 2576 int preUpgradeSdkVersion = ver.sdkVersion; 2577 2578 // save off the names of pre-existing system packages prior to scanning; we don't 2579 // want to automatically grant runtime permissions for new system apps 2580 if (mPromoteSystemApps) { 2581 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2582 while (pkgSettingIter.hasNext()) { 2583 PackageSetting ps = pkgSettingIter.next(); 2584 if (isSystemApp(ps)) { 2585 mExistingSystemPackages.add(ps.name); 2586 } 2587 } 2588 } 2589 2590 mCacheDir = preparePackageParserCache(); 2591 2592 // Set flag to monitor and not change apk file paths when 2593 // scanning install directories. 2594 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2595 2596 if (mIsUpgrade || mFirstBoot) { 2597 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2598 } 2599 2600 // Collect vendor/product/product_services overlay packages. (Do this before scanning 2601 // any apps.) 2602 // For security and version matching reason, only consider overlay packages if they 2603 // reside in the right directory. 2604 scanDirTracedLI(new File(VENDOR_OVERLAY_DIR), 2605 mDefParseFlags 2606 | PackageParser.PARSE_IS_SYSTEM_DIR, 2607 scanFlags 2608 | SCAN_AS_SYSTEM 2609 | SCAN_AS_VENDOR, 2610 0); 2611 scanDirTracedLI(new File(PRODUCT_OVERLAY_DIR), 2612 mDefParseFlags 2613 | PackageParser.PARSE_IS_SYSTEM_DIR, 2614 scanFlags 2615 | SCAN_AS_SYSTEM 2616 | SCAN_AS_PRODUCT, 2617 0); 2618 scanDirTracedLI(new File(PRODUCT_SERVICES_OVERLAY_DIR), 2619 mDefParseFlags 2620 | PackageParser.PARSE_IS_SYSTEM_DIR, 2621 scanFlags 2622 | SCAN_AS_SYSTEM 2623 | SCAN_AS_PRODUCT_SERVICES, 2624 0); 2625 scanDirTracedLI(new File(ODM_OVERLAY_DIR), 2626 mDefParseFlags 2627 | PackageParser.PARSE_IS_SYSTEM_DIR, 2628 scanFlags 2629 | SCAN_AS_SYSTEM 2630 | SCAN_AS_ODM, 2631 0); 2632 scanDirTracedLI(new File(OEM_OVERLAY_DIR), 2633 mDefParseFlags 2634 | PackageParser.PARSE_IS_SYSTEM_DIR, 2635 scanFlags 2636 | SCAN_AS_SYSTEM 2637 | SCAN_AS_OEM, 2638 0); 2639 2640 mParallelPackageParserCallback.findStaticOverlayPackages(); 2641 2642 // Find base frameworks (resource packages without code). 2643 scanDirTracedLI(frameworkDir, 2644 mDefParseFlags 2645 | PackageParser.PARSE_IS_SYSTEM_DIR, 2646 scanFlags 2647 | SCAN_NO_DEX 2648 | SCAN_AS_SYSTEM 2649 | SCAN_AS_PRIVILEGED, 2650 0); 2651 if (!mPackages.containsKey("android")) { 2652 throw new IllegalStateException( 2653 "Failed to load frameworks package; check log for warnings"); 2654 } 2655 2656 // Collect privileged system packages. 2657 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2658 scanDirTracedLI(privilegedAppDir, 2659 mDefParseFlags 2660 | PackageParser.PARSE_IS_SYSTEM_DIR, 2661 scanFlags 2662 | SCAN_AS_SYSTEM 2663 | SCAN_AS_PRIVILEGED, 2664 0); 2665 2666 // Collect ordinary system packages. 2667 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2668 scanDirTracedLI(systemAppDir, 2669 mDefParseFlags 2670 | PackageParser.PARSE_IS_SYSTEM_DIR, 2671 scanFlags 2672 | SCAN_AS_SYSTEM, 2673 0); 2674 2675 // Collect privileged vendor packages. 2676 File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 2677 try { 2678 privilegedVendorAppDir = privilegedVendorAppDir.getCanonicalFile(); 2679 } catch (IOException e) { 2680 // failed to look up canonical path, continue with original one 2681 } 2682 scanDirTracedLI(privilegedVendorAppDir, 2683 mDefParseFlags 2684 | PackageParser.PARSE_IS_SYSTEM_DIR, 2685 scanFlags 2686 | SCAN_AS_SYSTEM 2687 | SCAN_AS_VENDOR 2688 | SCAN_AS_PRIVILEGED, 2689 0); 2690 2691 // Collect ordinary vendor packages. 2692 File vendorAppDir = new File(Environment.getVendorDirectory(), "app"); 2693 try { 2694 vendorAppDir = vendorAppDir.getCanonicalFile(); 2695 } catch (IOException e) { 2696 // failed to look up canonical path, continue with original one 2697 } 2698 scanDirTracedLI(vendorAppDir, 2699 mDefParseFlags 2700 | PackageParser.PARSE_IS_SYSTEM_DIR, 2701 scanFlags 2702 | SCAN_AS_SYSTEM 2703 | SCAN_AS_VENDOR, 2704 0); 2705 2706 // Collect privileged odm packages. /odm is another vendor partition 2707 // other than /vendor. 2708 File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), 2709 "priv-app"); 2710 try { 2711 privilegedOdmAppDir = privilegedOdmAppDir.getCanonicalFile(); 2712 } catch (IOException e) { 2713 // failed to look up canonical path, continue with original one 2714 } 2715 scanDirTracedLI(privilegedOdmAppDir, 2716 mDefParseFlags 2717 | PackageParser.PARSE_IS_SYSTEM_DIR, 2718 scanFlags 2719 | SCAN_AS_SYSTEM 2720 | SCAN_AS_VENDOR 2721 | SCAN_AS_PRIVILEGED, 2722 0); 2723 2724 // Collect ordinary odm packages. /odm is another vendor partition 2725 // other than /vendor. 2726 File odmAppDir = new File(Environment.getOdmDirectory(), "app"); 2727 try { 2728 odmAppDir = odmAppDir.getCanonicalFile(); 2729 } catch (IOException e) { 2730 // failed to look up canonical path, continue with original one 2731 } 2732 scanDirTracedLI(odmAppDir, 2733 mDefParseFlags 2734 | PackageParser.PARSE_IS_SYSTEM_DIR, 2735 scanFlags 2736 | SCAN_AS_SYSTEM 2737 | SCAN_AS_VENDOR, 2738 0); 2739 2740 // Collect all OEM packages. 2741 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2742 scanDirTracedLI(oemAppDir, 2743 mDefParseFlags 2744 | PackageParser.PARSE_IS_SYSTEM_DIR, 2745 scanFlags 2746 | SCAN_AS_SYSTEM 2747 | SCAN_AS_OEM, 2748 0); 2749 2750 // Collected privileged /product packages. 2751 File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 2752 try { 2753 privilegedProductAppDir = privilegedProductAppDir.getCanonicalFile(); 2754 } catch (IOException e) { 2755 // failed to look up canonical path, continue with original one 2756 } 2757 scanDirTracedLI(privilegedProductAppDir, 2758 mDefParseFlags 2759 | PackageParser.PARSE_IS_SYSTEM_DIR, 2760 scanFlags 2761 | SCAN_AS_SYSTEM 2762 | SCAN_AS_PRODUCT 2763 | SCAN_AS_PRIVILEGED, 2764 0); 2765 2766 // Collect ordinary /product packages. 2767 File productAppDir = new File(Environment.getProductDirectory(), "app"); 2768 try { 2769 productAppDir = productAppDir.getCanonicalFile(); 2770 } catch (IOException e) { 2771 // failed to look up canonical path, continue with original one 2772 } 2773 scanDirTracedLI(productAppDir, 2774 mDefParseFlags 2775 | PackageParser.PARSE_IS_SYSTEM_DIR, 2776 scanFlags 2777 | SCAN_AS_SYSTEM 2778 | SCAN_AS_PRODUCT, 2779 0); 2780 2781 // Collected privileged /product_services packages. 2782 File privilegedProductServicesAppDir = 2783 new File(Environment.getProductServicesDirectory(), "priv-app"); 2784 try { 2785 privilegedProductServicesAppDir = 2786 privilegedProductServicesAppDir.getCanonicalFile(); 2787 } catch (IOException e) { 2788 // failed to look up canonical path, continue with original one 2789 } 2790 scanDirTracedLI(privilegedProductServicesAppDir, 2791 mDefParseFlags 2792 | PackageParser.PARSE_IS_SYSTEM_DIR, 2793 scanFlags 2794 | SCAN_AS_SYSTEM 2795 | SCAN_AS_PRODUCT_SERVICES 2796 | SCAN_AS_PRIVILEGED, 2797 0); 2798 2799 // Collect ordinary /product_services packages. 2800 File productServicesAppDir = new File(Environment.getProductServicesDirectory(), "app"); 2801 try { 2802 productServicesAppDir = productServicesAppDir.getCanonicalFile(); 2803 } catch (IOException e) { 2804 // failed to look up canonical path, continue with original one 2805 } 2806 scanDirTracedLI(productServicesAppDir, 2807 mDefParseFlags 2808 | PackageParser.PARSE_IS_SYSTEM_DIR, 2809 scanFlags 2810 | SCAN_AS_SYSTEM 2811 | SCAN_AS_PRODUCT_SERVICES, 2812 0); 2813 2814 // Prune any system packages that no longer exist. 2815 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2816 // Stub packages must either be replaced with full versions in the /data 2817 // partition or be disabled. 2818 final List<String> stubSystemApps = new ArrayList<>(); 2819 if (!mOnlyCore) { 2820 // do this first before mucking with mPackages for the "expecting better" case 2821 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2822 while (pkgIterator.hasNext()) { 2823 final PackageParser.Package pkg = pkgIterator.next(); 2824 if (pkg.isStub) { 2825 stubSystemApps.add(pkg.packageName); 2826 } 2827 } 2828 2829 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2830 while (psit.hasNext()) { 2831 PackageSetting ps = psit.next(); 2832 2833 /* 2834 * If this is not a system app, it can't be a 2835 * disable system app. 2836 */ 2837 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2838 continue; 2839 } 2840 2841 /* 2842 * If the package is scanned, it's not erased. 2843 */ 2844 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2845 if (scannedPkg != null) { 2846 /* 2847 * If the system app is both scanned and in the 2848 * disabled packages list, then it must have been 2849 * added via OTA. Remove it from the currently 2850 * scanned package so the previously user-installed 2851 * application can be scanned. 2852 */ 2853 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2854 logCriticalInfo(Log.WARN, 2855 "Expecting better updated system app for " + ps.name 2856 + "; removing system app. Last known" 2857 + " codePath=" + ps.codePathString 2858 + ", versionCode=" + ps.versionCode 2859 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2860 removePackageLI(scannedPkg, true); 2861 mExpectingBetter.put(ps.name, ps.codePath); 2862 } 2863 2864 continue; 2865 } 2866 2867 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2868 psit.remove(); 2869 logCriticalInfo(Log.WARN, "System package " + ps.name 2870 + " no longer exists; it's data will be wiped"); 2871 // Actual deletion of code and data will be handled by later 2872 // reconciliation step 2873 } else { 2874 // we still have a disabled system package, but, it still might have 2875 // been removed. check the code path still exists and check there's 2876 // still a package. the latter can happen if an OTA keeps the same 2877 // code path, but, changes the package name. 2878 final PackageSetting disabledPs = 2879 mSettings.getDisabledSystemPkgLPr(ps.name); 2880 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2881 || disabledPs.pkg == null) { 2882 possiblyDeletedUpdatedSystemApps.add(ps.name); 2883 } else { 2884 // We're expecting that the system app should remain disabled, but add 2885 // it to expecting better to recover in case the data version cannot 2886 // be scanned. 2887 mExpectingBetter.put(disabledPs.name, disabledPs.codePath); 2888 } 2889 } 2890 } 2891 } 2892 2893 //delete tmp files 2894 deleteTempPackageFiles(); 2895 2896 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2897 2898 // Remove any shared userIDs that have no associated packages 2899 mSettings.pruneSharedUsersLPw(); 2900 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2901 final int systemPackagesCount = mPackages.size(); 2902 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2903 + " ms, packageCount: " + systemPackagesCount 2904 + " , timePerPackage: " 2905 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2906 + " , cached: " + cachedSystemApps); 2907 if (mIsUpgrade && systemPackagesCount > 0) { 2908 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2909 ((int) systemScanTime) / systemPackagesCount); 2910 } 2911 if (!mOnlyCore) { 2912 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2913 SystemClock.uptimeMillis()); 2914 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2915 2916 // Remove disable package settings for updated system apps that were 2917 // removed via an OTA. If the update is no longer present, remove the 2918 // app completely. Otherwise, revoke their system privileges. 2919 for (int i = possiblyDeletedUpdatedSystemApps.size() - 1; i >= 0; --i) { 2920 final String packageName = possiblyDeletedUpdatedSystemApps.get(i); 2921 final PackageParser.Package pkg = mPackages.get(packageName); 2922 final String msg; 2923 2924 // remove from the disabled system list; do this first so any future 2925 // scans of this package are performed without this state 2926 mSettings.removeDisabledSystemPackageLPw(packageName); 2927 2928 if (pkg == null) { 2929 // should have found an update, but, we didn't; remove everything 2930 msg = "Updated system package " + packageName 2931 + " no longer exists; removing its data"; 2932 // Actual deletion of code and data will be handled by later 2933 // reconciliation step 2934 } else { 2935 // found an update; revoke system privileges 2936 msg = "Updated system package " + packageName 2937 + " no longer exists; rescanning package on data"; 2938 2939 // NOTE: We don't do anything special if a stub is removed from the 2940 // system image. But, if we were [like removing the uncompressed 2941 // version from the /data partition], this is where it'd be done. 2942 2943 // remove the package from the system and re-scan it without any 2944 // special privileges 2945 removePackageLI(pkg, true); 2946 try { 2947 final File codePath = new File(pkg.applicationInfo.getCodePath()); 2948 scanPackageTracedLI(codePath, 0, scanFlags, 0, null); 2949 } catch (PackageManagerException e) { 2950 Slog.e(TAG, "Failed to parse updated, ex-system package: " 2951 + e.getMessage()); 2952 } 2953 } 2954 2955 // one final check. if we still have a package setting [ie. it was 2956 // previously scanned and known to the system], but, we don't have 2957 // a package [ie. there was an error scanning it from the /data 2958 // partition], completely remove the package data. 2959 final PackageSetting ps = mSettings.mPackages.get(packageName); 2960 if (ps != null && mPackages.get(packageName) == null) { 2961 removePackageDataLIF(ps, null, null, 0, false); 2962 2963 } 2964 logCriticalInfo(Log.WARN, msg); 2965 } 2966 2967 /* 2968 * Make sure all system apps that we expected to appear on 2969 * the userdata partition actually showed up. If they never 2970 * appeared, crawl back and revive the system version. 2971 */ 2972 for (int i = 0; i < mExpectingBetter.size(); i++) { 2973 final String packageName = mExpectingBetter.keyAt(i); 2974 if (!mPackages.containsKey(packageName)) { 2975 final File scanFile = mExpectingBetter.valueAt(i); 2976 2977 logCriticalInfo(Log.WARN, "Expected better " + packageName 2978 + " but never showed up; reverting to system"); 2979 2980 final @ParseFlags int reparseFlags; 2981 final @ScanFlags int rescanFlags; 2982 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2983 reparseFlags = 2984 mDefParseFlags | 2985 PackageParser.PARSE_IS_SYSTEM_DIR; 2986 rescanFlags = 2987 scanFlags 2988 | SCAN_AS_SYSTEM 2989 | SCAN_AS_PRIVILEGED; 2990 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2991 reparseFlags = 2992 mDefParseFlags | 2993 PackageParser.PARSE_IS_SYSTEM_DIR; 2994 rescanFlags = 2995 scanFlags 2996 | SCAN_AS_SYSTEM; 2997 } else if (FileUtils.contains(privilegedVendorAppDir, scanFile) 2998 || FileUtils.contains(privilegedOdmAppDir, scanFile)) { 2999 reparseFlags = 3000 mDefParseFlags | 3001 PackageParser.PARSE_IS_SYSTEM_DIR; 3002 rescanFlags = 3003 scanFlags 3004 | SCAN_AS_SYSTEM 3005 | SCAN_AS_VENDOR 3006 | SCAN_AS_PRIVILEGED; 3007 } else if (FileUtils.contains(vendorAppDir, scanFile) 3008 || FileUtils.contains(odmAppDir, scanFile)) { 3009 reparseFlags = 3010 mDefParseFlags | 3011 PackageParser.PARSE_IS_SYSTEM_DIR; 3012 rescanFlags = 3013 scanFlags 3014 | SCAN_AS_SYSTEM 3015 | SCAN_AS_VENDOR; 3016 } else if (FileUtils.contains(oemAppDir, scanFile)) { 3017 reparseFlags = 3018 mDefParseFlags | 3019 PackageParser.PARSE_IS_SYSTEM_DIR; 3020 rescanFlags = 3021 scanFlags 3022 | SCAN_AS_SYSTEM 3023 | SCAN_AS_OEM; 3024 } else if (FileUtils.contains(privilegedProductAppDir, scanFile)) { 3025 reparseFlags = 3026 mDefParseFlags | 3027 PackageParser.PARSE_IS_SYSTEM_DIR; 3028 rescanFlags = 3029 scanFlags 3030 | SCAN_AS_SYSTEM 3031 | SCAN_AS_PRODUCT 3032 | SCAN_AS_PRIVILEGED; 3033 } else if (FileUtils.contains(productAppDir, scanFile)) { 3034 reparseFlags = 3035 mDefParseFlags | 3036 PackageParser.PARSE_IS_SYSTEM_DIR; 3037 rescanFlags = 3038 scanFlags 3039 | SCAN_AS_SYSTEM 3040 | SCAN_AS_PRODUCT; 3041 } else if (FileUtils.contains(privilegedProductServicesAppDir, scanFile)) { 3042 reparseFlags = 3043 mDefParseFlags | 3044 PackageParser.PARSE_IS_SYSTEM_DIR; 3045 rescanFlags = 3046 scanFlags 3047 | SCAN_AS_SYSTEM 3048 | SCAN_AS_PRODUCT_SERVICES 3049 | SCAN_AS_PRIVILEGED; 3050 } else if (FileUtils.contains(productServicesAppDir, scanFile)) { 3051 reparseFlags = 3052 mDefParseFlags | 3053 PackageParser.PARSE_IS_SYSTEM_DIR; 3054 rescanFlags = 3055 scanFlags 3056 | SCAN_AS_SYSTEM 3057 | SCAN_AS_PRODUCT_SERVICES; 3058 } else { 3059 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 3060 continue; 3061 } 3062 3063 mSettings.enableSystemPackageLPw(packageName); 3064 3065 try { 3066 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 3067 } catch (PackageManagerException e) { 3068 Slog.e(TAG, "Failed to parse original system package: " 3069 + e.getMessage()); 3070 } 3071 } 3072 } 3073 3074 // Uncompress and install any stubbed system applications. 3075 // This must be done last to ensure all stubs are replaced or disabled. 3076 installSystemStubPackages(stubSystemApps, scanFlags); 3077 3078 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 3079 - cachedSystemApps; 3080 3081 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 3082 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 3083 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 3084 + " ms, packageCount: " + dataPackagesCount 3085 + " , timePerPackage: " 3086 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 3087 + " , cached: " + cachedNonSystemApps); 3088 if (mIsUpgrade && dataPackagesCount > 0) { 3089 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 3090 ((int) dataScanTime) / dataPackagesCount); 3091 } 3092 } 3093 mExpectingBetter.clear(); 3094 3095 // Resolve the storage manager. 3096 mStorageManagerPackage = getStorageManagerPackageName(); 3097 3098 // Resolve protected action filters. Only the setup wizard is allowed to 3099 // have a high priority filter for these actions. 3100 mSetupWizardPackage = getSetupWizardPackageName(); 3101 mComponentResolver.fixProtectedFilterPriorities(); 3102 3103 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 3104 3105 mWellbeingPackage = getWellbeingPackageName(); 3106 mDocumenterPackage = getDocumenterPackageName(); 3107 mConfiguratorPackage = getDeviceConfiguratorPackageName(); 3108 mAppPredictionServicePackage = getAppPredictionServicePackageName(); 3109 mIncidentReportApproverPackage = getIncidentReportApproverPackageName(); 3110 3111 // Now that we know all of the shared libraries, update all clients to have 3112 // the correct library paths. 3113 updateAllSharedLibrariesLocked(null, Collections.unmodifiableMap(mPackages)); 3114 3115 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3116 // NOTE: We ignore potential failures here during a system scan (like 3117 // the rest of the commands above) because there's precious little we 3118 // can do about it. A settings error is reported, though. 3119 final List<String> changedAbiCodePath = 3120 adjustCpuAbisForSharedUserLPw(setting.packages, null /*scannedPackage*/); 3121 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3122 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3123 final String codePathString = changedAbiCodePath.get(i); 3124 try { 3125 mInstaller.rmdex(codePathString, 3126 getDexCodeInstructionSet(getPreferredInstructionSet())); 3127 } catch (InstallerException ignored) { 3128 } 3129 } 3130 } 3131 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3132 // SELinux domain. 3133 setting.fixSeInfoLocked(); 3134 } 3135 3136 // Now that we know all the packages we are keeping, 3137 // read and update their last usage times. 3138 mPackageUsage.read(mPackages); 3139 mCompilerStats.read(); 3140 3141 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3142 SystemClock.uptimeMillis()); 3143 Slog.i(TAG, "Time to scan packages: " 3144 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3145 + " seconds"); 3146 3147 // If the platform SDK has changed since the last time we booted, 3148 // we need to re-grant app permission to catch any new ones that 3149 // appear. This is really a hack, and means that apps can in some 3150 // cases get permissions that the user didn't initially explicitly 3151 // allow... it would be nice to have some better way to handle 3152 // this situation. 3153 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3154 if (sdkUpdated) { 3155 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3156 + mSdkVersion + "; regranting permissions for internal storage"); 3157 } 3158 mPermissionManager.updateAllPermissions( 3159 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3160 mPermissionCallback); 3161 ver.sdkVersion = mSdkVersion; 3162 3163 // If this is the first boot or an update from pre-M, and it is a normal 3164 // boot, then we need to initialize the default preferred apps across 3165 // all defined users. 3166 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3167 for (UserInfo user : sUserManager.getUsers(true)) { 3168 mSettings.applyDefaultPreferredAppsLPw(user.id); 3169 primeDomainVerificationsLPw(user.id); 3170 } 3171 } 3172 3173 // Prepare storage for system user really early during boot, 3174 // since core system apps like SettingsProvider and SystemUI 3175 // can't wait for user to start 3176 final int storageFlags; 3177 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3178 storageFlags = StorageManager.FLAG_STORAGE_DE; 3179 } else { 3180 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3181 } 3182 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3183 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3184 true /* onlyCoreApps */); 3185 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3186 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3187 Trace.TRACE_TAG_PACKAGE_MANAGER); 3188 traceLog.traceBegin("AppDataFixup"); 3189 try { 3190 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3191 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3192 } catch (InstallerException e) { 3193 Slog.w(TAG, "Trouble fixing GIDs", e); 3194 } 3195 traceLog.traceEnd(); 3196 3197 traceLog.traceBegin("AppDataPrepare"); 3198 if (deferPackages == null || deferPackages.isEmpty()) { 3199 return; 3200 } 3201 int count = 0; 3202 for (String pkgName : deferPackages) { 3203 PackageParser.Package pkg = null; 3204 synchronized (mPackages) { 3205 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3206 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3207 pkg = ps.pkg; 3208 } 3209 } 3210 if (pkg != null) { 3211 synchronized (mInstallLock) { 3212 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3213 true /* maybeMigrateAppData */); 3214 } 3215 count++; 3216 } 3217 } 3218 traceLog.traceEnd(); 3219 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3220 }, "prepareAppData"); 3221 3222 // If this is first boot after an OTA, and a normal boot, then 3223 // we need to clear code cache directories. 3224 // Note that we do *not* clear the application profiles. These remain valid 3225 // across OTAs and are used to drive profile verification (post OTA) and 3226 // profile compilation (without waiting to collect a fresh set of profiles). 3227 if (mIsUpgrade && !onlyCore) { 3228 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3229 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3230 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3231 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3232 // No apps are running this early, so no need to freeze 3233 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3234 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL 3235 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3236 } 3237 } 3238 ver.fingerprint = Build.FINGERPRINT; 3239 } 3240 3241 // Grandfather existing (installed before Q) non-system apps to hide 3242 // their icons in launcher. 3243 if (!onlyCore && mIsPreQUpgrade) { 3244 Slog.i(TAG, "Whitelisting all existing apps to hide their icons"); 3245 int size = mSettings.mPackages.size(); 3246 for (int i = 0; i < size; i++) { 3247 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3248 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 3249 continue; 3250 } 3251 ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME, 3252 UserHandle.USER_SYSTEM); 3253 } 3254 } 3255 3256 // clear only after permissions and other defaults have been updated 3257 mExistingSystemPackages.clear(); 3258 mPromoteSystemApps = false; 3259 3260 // All the changes are done during package scanning. 3261 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3262 3263 // can downgrade to reader 3264 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3265 mSettings.writeLPr(); 3266 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3267 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3268 SystemClock.uptimeMillis()); 3269 3270 if (!mOnlyCore) { 3271 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3272 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3273 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3274 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3275 if (mIntentFilterVerifierComponent != null) { 3276 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3277 mIntentFilterVerifierComponent); 3278 } else { 3279 mIntentFilterVerifier = null; 3280 } 3281 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3282 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3283 SharedLibraryInfo.VERSION_UNDEFINED); 3284 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3285 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3286 SharedLibraryInfo.VERSION_UNDEFINED); 3287 } else { 3288 mRequiredVerifierPackage = null; 3289 mRequiredInstallerPackage = null; 3290 mRequiredUninstallerPackage = null; 3291 mIntentFilterVerifierComponent = null; 3292 mIntentFilterVerifier = null; 3293 mServicesSystemSharedLibraryPackageName = null; 3294 mSharedSystemSharedLibraryPackageName = null; 3295 } 3296 // PermissionController hosts default permission granting and role management, so it's a 3297 // critical part of the core system. 3298 mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr(); 3299 3300 // Initialize InstantAppRegistry's Instant App list for all users. 3301 final int[] userIds = UserManagerService.getInstance().getUserIds(); 3302 for (PackageParser.Package pkg : mPackages.values()) { 3303 if (pkg.isSystem()) { 3304 continue; 3305 } 3306 for (int userId : userIds) { 3307 final PackageSetting ps = (PackageSetting) pkg.mExtras; 3308 if (ps == null || !ps.getInstantApp(userId) || !ps.getInstalled(userId)) { 3309 continue; 3310 } 3311 mInstantAppRegistry.addInstantAppLPw(userId, ps.appId); 3312 } 3313 } 3314 3315 mInstallerService = new PackageInstallerService(context, this, mApexManager); 3316 final Pair<ComponentName, String> instantAppResolverComponent = 3317 getInstantAppResolverLPr(); 3318 if (instantAppResolverComponent != null) { 3319 if (DEBUG_INSTANT) { 3320 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3321 } 3322 mInstantAppResolverConnection = new InstantAppResolverConnection( 3323 mContext, instantAppResolverComponent.first, 3324 instantAppResolverComponent.second); 3325 mInstantAppResolverSettingsComponent = 3326 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3327 } else { 3328 mInstantAppResolverConnection = null; 3329 mInstantAppResolverSettingsComponent = null; 3330 } 3331 updateInstantAppInstallerLocked(null); 3332 3333 // Read and update the usage of dex files. 3334 // Do this at the end of PM init so that all the packages have their 3335 // data directory reconciled. 3336 // At this point we know the code paths of the packages, so we can validate 3337 // the disk file and build the internal cache. 3338 // The usage file is expected to be small so loading and verifying it 3339 // should take a fairly small time compare to the other activities (e.g. package 3340 // scanning). 3341 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3342 for (int userId : userIds) { 3343 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3344 } 3345 mDexManager.load(userPackages); 3346 if (mIsUpgrade) { 3347 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3348 (int) (SystemClock.uptimeMillis() - startTime)); 3349 } 3350 } // synchronized (mPackages) 3351 } // synchronized (mInstallLock) 3352 3353 mModuleInfoProvider = new ModuleInfoProvider(mContext, this); 3354 3355 // Now after opening every single application zip, make sure they 3356 // are all flushed. Not really needed, but keeps things nice and 3357 // tidy. 3358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3359 Runtime.getRuntime().gc(); 3360 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3361 3362 // The initial scanning above does many calls into installd while 3363 // holding the mPackages lock, but we're mostly interested in yelling 3364 // once we have a booted system. 3365 mInstaller.setWarnIfHeld(mPackages); 3366 3367 PackageParser.readConfigUseRoundIcon(mContext.getResources()); 3368 3369 mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L); 3370 3371 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3372 } 3373 3374 /** 3375 * Uncompress and install stub applications. 3376 * <p>In order to save space on the system partition, some applications are shipped in a 3377 * compressed form. In addition the compressed bits for the full application, the 3378 * system image contains a tiny stub comprised of only the Android manifest. 3379 * <p>During the first boot, attempt to uncompress and install the full application. If 3380 * the application can't be installed for any reason, disable the stub and prevent 3381 * uncompressing the full application during future boots. 3382 * <p>In order to forcefully attempt an installation of a full application, go to app 3383 * settings and enable the application. 3384 */ installSystemStubPackages(@onNull List<String> systemStubPackageNames, @ScanFlags int scanFlags)3385 private void installSystemStubPackages(@NonNull List<String> systemStubPackageNames, 3386 @ScanFlags int scanFlags) { 3387 for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) { 3388 final String packageName = systemStubPackageNames.get(i); 3389 // skip if the system package is already disabled 3390 if (mSettings.isDisabledSystemPackageLPr(packageName)) { 3391 systemStubPackageNames.remove(i); 3392 continue; 3393 } 3394 // skip if the package isn't installed (?!); this should never happen 3395 final PackageParser.Package pkg = mPackages.get(packageName); 3396 if (pkg == null) { 3397 systemStubPackageNames.remove(i); 3398 continue; 3399 } 3400 // skip if the package has been disabled by the user 3401 final PackageSetting ps = mSettings.mPackages.get(packageName); 3402 if (ps != null) { 3403 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3404 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3405 systemStubPackageNames.remove(i); 3406 continue; 3407 } 3408 } 3409 3410 // install the package to replace the stub on /system 3411 try { 3412 installStubPackageLI(pkg, 0, scanFlags); 3413 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3414 UserHandle.USER_SYSTEM, "android"); 3415 systemStubPackageNames.remove(i); 3416 } catch (PackageManagerException e) { 3417 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3418 } 3419 3420 // any failed attempt to install the package will be cleaned up later 3421 } 3422 3423 // disable any stub still left; these failed to install the full application 3424 for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) { 3425 final String pkgName = systemStubPackageNames.get(i); 3426 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3427 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3428 UserHandle.USER_SYSTEM, "android"); 3429 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3430 } 3431 } 3432 3433 /** 3434 * Extract, install and enable a stub package. 3435 * <p>If the compressed file can not be extracted / installed for any reason, the stub 3436 * APK will be installed and the package will be disabled. To recover from this situation, 3437 * the user will need to go into system settings and re-enable the package. 3438 */ enableCompressedPackage(PackageParser.Package stubPkg)3439 private boolean enableCompressedPackage(PackageParser.Package stubPkg) { 3440 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 3441 | PackageParser.PARSE_ENFORCE_CODE; 3442 synchronized (mInstallLock) { 3443 final PackageParser.Package pkg; 3444 try (PackageFreezer freezer = 3445 freezePackage(stubPkg.packageName, "setEnabledSetting")) { 3446 pkg = installStubPackageLI(stubPkg, parseFlags, 0 /*scanFlags*/); 3447 synchronized (mPackages) { 3448 prepareAppDataAfterInstallLIF(pkg); 3449 try { 3450 updateSharedLibrariesLocked(pkg, null, mPackages); 3451 } catch (PackageManagerException e) { 3452 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 3453 } 3454 mPermissionManager.updatePermissions( 3455 pkg.packageName, pkg, true, mPackages.values(), 3456 mPermissionCallback); 3457 mSettings.writeLPr(); 3458 } 3459 } catch (PackageManagerException e) { 3460 // Whoops! Something went very wrong; roll back to the stub and disable the package 3461 try (PackageFreezer freezer = 3462 freezePackage(stubPkg.packageName, "setEnabledSetting")) { 3463 synchronized (mPackages) { 3464 // NOTE: Ensure the system package is enabled; even for a compressed stub. 3465 // If we don't, installing the system package fails during scan 3466 enableSystemPackageLPw(stubPkg); 3467 } 3468 installPackageFromSystemLIF(stubPkg.codePath, 3469 null /*allUserHandles*/, null /*origUserHandles*/, 3470 null /*origPermissionsState*/, true /*writeSettings*/); 3471 } catch (PackageManagerException pme) { 3472 // Serious WTF; we have to be able to install the stub 3473 Slog.wtf(TAG, "Failed to restore system package:" + stubPkg.packageName, pme); 3474 } finally { 3475 // Disable the package; the stub by itself is not runnable 3476 synchronized (mPackages) { 3477 final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName); 3478 if (stubPs != null) { 3479 stubPs.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 3480 UserHandle.USER_SYSTEM, "android"); 3481 } 3482 mSettings.writeLPr(); 3483 } 3484 } 3485 return false; 3486 } 3487 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 3488 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3489 mDexManager.notifyPackageUpdated(pkg.packageName, 3490 pkg.baseCodePath, pkg.splitCodePaths); 3491 } 3492 return true; 3493 } 3494 installStubPackageLI(PackageParser.Package stubPkg, @ParseFlags int parseFlags, @ScanFlags int scanFlags)3495 private PackageParser.Package installStubPackageLI(PackageParser.Package stubPkg, 3496 @ParseFlags int parseFlags, @ScanFlags int scanFlags) 3497 throws PackageManagerException { 3498 if (DEBUG_COMPRESSION) { 3499 Slog.i(TAG, "Uncompressing system stub; pkg: " + stubPkg.packageName); 3500 } 3501 // uncompress the binary to its eventual destination on /data 3502 final File scanFile = decompressPackage(stubPkg.packageName, stubPkg.codePath); 3503 if (scanFile == null) { 3504 throw new PackageManagerException("Unable to decompress stub at " + stubPkg.codePath); 3505 } 3506 synchronized (mPackages) { 3507 mSettings.disableSystemPackageLPw(stubPkg.packageName, true /*replaced*/); 3508 } 3509 removePackageLI(stubPkg, true /*chatty*/); 3510 try { 3511 return scanPackageTracedLI(scanFile, parseFlags, scanFlags, 0, null); 3512 } catch (PackageManagerException e) { 3513 Slog.w(TAG, "Failed to install compressed system package:" + stubPkg.packageName, e); 3514 // Remove the failed install 3515 removeCodePathLI(scanFile); 3516 throw e; 3517 } 3518 } 3519 3520 /** 3521 * Decompresses the given package on the system image onto 3522 * the /data partition. 3523 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3524 */ decompressPackage(String packageName, String codePath)3525 private File decompressPackage(String packageName, String codePath) { 3526 final File[] compressedFiles = getCompressedFiles(codePath); 3527 if (compressedFiles == null || compressedFiles.length == 0) { 3528 if (DEBUG_COMPRESSION) { 3529 Slog.i(TAG, "No files to decompress: " + codePath); 3530 } 3531 return null; 3532 } 3533 final File dstCodePath = 3534 getNextCodePath(Environment.getDataAppDirectory(null), packageName); 3535 int ret = PackageManager.INSTALL_SUCCEEDED; 3536 try { 3537 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3538 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3539 for (File srcFile : compressedFiles) { 3540 final String srcFileName = srcFile.getName(); 3541 final String dstFileName = srcFileName.substring( 3542 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3543 final File dstFile = new File(dstCodePath, dstFileName); 3544 ret = decompressFile(srcFile, dstFile); 3545 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3546 logCriticalInfo(Log.ERROR, "Failed to decompress" 3547 + "; pkg: " + packageName 3548 + ", file: " + dstFileName); 3549 break; 3550 } 3551 } 3552 } catch (ErrnoException e) { 3553 logCriticalInfo(Log.ERROR, "Failed to decompress" 3554 + "; pkg: " + packageName 3555 + ", err: " + e.errno); 3556 } 3557 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3558 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3559 NativeLibraryHelper.Handle handle = null; 3560 try { 3561 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3562 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3563 null /*abiOverride*/); 3564 } catch (IOException e) { 3565 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3566 + "; pkg: " + packageName); 3567 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3568 } finally { 3569 IoUtils.closeQuietly(handle); 3570 } 3571 } 3572 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3573 if (!dstCodePath.exists()) { 3574 return null; 3575 } 3576 removeCodePathLI(dstCodePath); 3577 return null; 3578 } 3579 3580 return dstCodePath; 3581 } 3582 3583 @GuardedBy("mPackages") updateInstantAppInstallerLocked(String modifiedPackage)3584 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3585 // we're only interested in updating the installer appliction when 1) it's not 3586 // already set or 2) the modified package is the installer 3587 if (mInstantAppInstallerActivity != null 3588 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3589 .equals(modifiedPackage)) { 3590 return; 3591 } 3592 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3593 } 3594 preparePackageParserCache()3595 private static @Nullable File preparePackageParserCache() { 3596 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3597 return null; 3598 } 3599 3600 // Disable package parsing on eng builds to allow for faster incremental development. 3601 if (Build.IS_ENG) { 3602 return null; 3603 } 3604 3605 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3606 Slog.i(TAG, "Disabling package parser cache due to system property."); 3607 return null; 3608 } 3609 3610 // The base directory for the package parser cache lives under /data/system/. 3611 final File cacheBaseDir = Environment.getPackageCacheDirectory(); 3612 if (!FileUtils.createDir(cacheBaseDir)) { 3613 return null; 3614 } 3615 3616 // There are several items that need to be combined together to safely 3617 // identify cached items. In particular, changing the value of certain 3618 // feature flags should cause us to invalidate any caches. 3619 final String cacheName = SystemProperties.digestOf( 3620 "ro.build.fingerprint", 3621 StorageManager.PROP_ISOLATED_STORAGE, 3622 StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT); 3623 3624 // Reconcile cache directories, keeping only what we'd actually use. 3625 for (File cacheDir : FileUtils.listFilesOrEmpty(cacheBaseDir)) { 3626 if (Objects.equals(cacheName, cacheDir.getName())) { 3627 Slog.d(TAG, "Keeping known cache " + cacheDir.getName()); 3628 } else { 3629 Slog.d(TAG, "Destroying unknown cache " + cacheDir.getName()); 3630 FileUtils.deleteContentsAndDir(cacheDir); 3631 } 3632 } 3633 3634 // Return the versioned package cache directory. 3635 File cacheDir = FileUtils.createDir(cacheBaseDir, cacheName); 3636 3637 if (cacheDir == null) { 3638 // Something went wrong. Attempt to delete everything and return. 3639 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3640 FileUtils.deleteContentsAndDir(cacheBaseDir); 3641 return null; 3642 } 3643 3644 // The following is a workaround to aid development on non-numbered userdebug 3645 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3646 // the system partition is newer. 3647 // 3648 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3649 // that starts with "eng." to signify that this is an engineering build and not 3650 // destined for release. 3651 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3652 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3653 3654 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3655 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3656 // in general and should not be used for production changes. In this specific case, 3657 // we know that they will work. 3658 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3659 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3660 FileUtils.deleteContents(cacheBaseDir); 3661 cacheDir = FileUtils.createDir(cacheBaseDir, cacheName); 3662 } 3663 } 3664 3665 return cacheDir; 3666 } 3667 3668 @Override isFirstBoot()3669 public boolean isFirstBoot() { 3670 // allow instant applications 3671 return mFirstBoot; 3672 } 3673 3674 @Override isOnlyCoreApps()3675 public boolean isOnlyCoreApps() { 3676 // allow instant applications 3677 return mOnlyCore; 3678 } 3679 3680 @Override isDeviceUpgrading()3681 public boolean isDeviceUpgrading() { 3682 // allow instant applications 3683 // The system property allows testing ota flow when upgraded to the same image. 3684 return mIsUpgrade || SystemProperties.getBoolean( 3685 "persist.pm.mock-upgrade", false /* default */); 3686 } 3687 getRequiredButNotReallyRequiredVerifierLPr()3688 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3689 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3690 3691 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3692 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3693 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3694 if (matches.size() == 1) { 3695 return matches.get(0).getComponentInfo().packageName; 3696 } else if (matches.size() == 0) { 3697 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3698 return null; 3699 } 3700 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3701 } 3702 getRequiredSharedLibraryLPr(String name, int version)3703 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3704 synchronized (mPackages) { 3705 SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(name, version); 3706 if (libraryInfo == null) { 3707 throw new IllegalStateException("Missing required shared library:" + name); 3708 } 3709 String packageName = libraryInfo.getPackageName(); 3710 if (packageName == null) { 3711 throw new IllegalStateException("Expected a package for shared library " + name); 3712 } 3713 return packageName; 3714 } 3715 } 3716 getRequiredInstallerLPr()3717 private @NonNull String getRequiredInstallerLPr() { 3718 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3719 intent.addCategory(Intent.CATEGORY_DEFAULT); 3720 intent.setDataAndType(Uri.parse("content://com.example/foo.apk"), PACKAGE_MIME_TYPE); 3721 3722 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3723 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3724 UserHandle.USER_SYSTEM); 3725 if (matches.size() == 1) { 3726 ResolveInfo resolveInfo = matches.get(0); 3727 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3728 throw new RuntimeException("The installer must be a privileged app"); 3729 } 3730 return matches.get(0).getComponentInfo().packageName; 3731 } else { 3732 throw new RuntimeException("There must be exactly one installer; found " + matches); 3733 } 3734 } 3735 getRequiredUninstallerLPr()3736 private @NonNull String getRequiredUninstallerLPr() { 3737 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3738 intent.addCategory(Intent.CATEGORY_DEFAULT); 3739 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3740 3741 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3742 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3743 UserHandle.USER_SYSTEM); 3744 if (resolveInfo == null || 3745 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3746 throw new RuntimeException("There must be exactly one uninstaller; found " 3747 + resolveInfo); 3748 } 3749 return resolveInfo.getComponentInfo().packageName; 3750 } 3751 getRequiredPermissionControllerLPr()3752 private @NonNull String getRequiredPermissionControllerLPr() { 3753 final Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSIONS); 3754 intent.addCategory(Intent.CATEGORY_DEFAULT); 3755 3756 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 3757 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3758 UserHandle.USER_SYSTEM); 3759 if (matches.size() == 1) { 3760 ResolveInfo resolveInfo = matches.get(0); 3761 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3762 throw new RuntimeException("The permissions manager must be a privileged app"); 3763 } 3764 return matches.get(0).getComponentInfo().packageName; 3765 } else { 3766 throw new RuntimeException("There must be exactly one permissions manager; found " 3767 + matches); 3768 } 3769 } 3770 getIntentFilterVerifierComponentNameLPr()3771 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3772 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3773 3774 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3775 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3776 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3777 ResolveInfo best = null; 3778 final int N = matches.size(); 3779 for (int i = 0; i < N; i++) { 3780 final ResolveInfo cur = matches.get(i); 3781 final String packageName = cur.getComponentInfo().packageName; 3782 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3783 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3784 continue; 3785 } 3786 3787 if (best == null || cur.priority > best.priority) { 3788 best = cur; 3789 } 3790 } 3791 3792 if (best != null) { 3793 return best.getComponentInfo().getComponentName(); 3794 } 3795 Slog.w(TAG, "Intent filter verifier not found"); 3796 return null; 3797 } 3798 3799 @Override getInstantAppResolverComponent()3800 public @Nullable ComponentName getInstantAppResolverComponent() { 3801 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3802 return null; 3803 } 3804 synchronized (mPackages) { 3805 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3806 if (instantAppResolver == null) { 3807 return null; 3808 } 3809 return instantAppResolver.first; 3810 } 3811 } 3812 getInstantAppResolverLPr()3813 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3814 final String[] packageArray = 3815 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3816 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3817 if (DEBUG_INSTANT) { 3818 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3819 } 3820 return null; 3821 } 3822 3823 final int callingUid = Binder.getCallingUid(); 3824 final int resolveFlags = 3825 MATCH_DIRECT_BOOT_AWARE 3826 | MATCH_DIRECT_BOOT_UNAWARE 3827 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3828 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3829 final Intent resolverIntent = new Intent(actionName); 3830 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3831 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3832 final int N = resolvers.size(); 3833 if (N == 0) { 3834 if (DEBUG_INSTANT) { 3835 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3836 } 3837 return null; 3838 } 3839 3840 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3841 for (int i = 0; i < N; i++) { 3842 final ResolveInfo info = resolvers.get(i); 3843 3844 if (info.serviceInfo == null) { 3845 continue; 3846 } 3847 3848 final String packageName = info.serviceInfo.packageName; 3849 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3850 if (DEBUG_INSTANT) { 3851 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3852 + " pkg: " + packageName + ", info:" + info); 3853 } 3854 continue; 3855 } 3856 3857 if (DEBUG_INSTANT) { 3858 Slog.v(TAG, "Ephemeral resolver found;" 3859 + " pkg: " + packageName + ", info:" + info); 3860 } 3861 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3862 } 3863 if (DEBUG_INSTANT) { 3864 Slog.v(TAG, "Ephemeral resolver NOT found"); 3865 } 3866 return null; 3867 } 3868 3869 @GuardedBy("mPackages") getInstantAppInstallerLPr()3870 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3871 String[] orderedActions = Build.IS_ENG 3872 ? new String[]{ 3873 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3874 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3875 : new String[]{ 3876 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3877 3878 final int resolveFlags = 3879 MATCH_DIRECT_BOOT_AWARE 3880 | MATCH_DIRECT_BOOT_UNAWARE 3881 | Intent.FLAG_IGNORE_EPHEMERAL 3882 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3883 final Intent intent = new Intent(); 3884 intent.addCategory(Intent.CATEGORY_DEFAULT); 3885 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3886 List<ResolveInfo> matches = null; 3887 for (String action : orderedActions) { 3888 intent.setAction(action); 3889 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3890 resolveFlags, UserHandle.USER_SYSTEM); 3891 if (matches.isEmpty()) { 3892 if (DEBUG_INSTANT) { 3893 Slog.d(TAG, "Instant App installer not found with " + action); 3894 } 3895 } else { 3896 break; 3897 } 3898 } 3899 Iterator<ResolveInfo> iter = matches.iterator(); 3900 while (iter.hasNext()) { 3901 final ResolveInfo rInfo = iter.next(); 3902 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3903 if (ps != null) { 3904 final PermissionsState permissionsState = ps.getPermissionsState(); 3905 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3906 || Build.IS_ENG) { 3907 continue; 3908 } 3909 } 3910 iter.remove(); 3911 } 3912 if (matches.size() == 0) { 3913 return null; 3914 } else if (matches.size() == 1) { 3915 return (ActivityInfo) matches.get(0).getComponentInfo(); 3916 } else { 3917 throw new RuntimeException( 3918 "There must be at most one ephemeral installer; found " + matches); 3919 } 3920 } 3921 getInstantAppResolverSettingsLPr( @onNull ComponentName resolver)3922 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3923 @NonNull ComponentName resolver) { 3924 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3925 .addCategory(Intent.CATEGORY_DEFAULT) 3926 .setPackage(resolver.getPackageName()); 3927 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3928 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3929 UserHandle.USER_SYSTEM); 3930 if (matches.isEmpty()) { 3931 return null; 3932 } 3933 return matches.get(0).getComponentInfo().getComponentName(); 3934 } 3935 3936 @GuardedBy("mPackages") primeDomainVerificationsLPw(int userId)3937 private void primeDomainVerificationsLPw(int userId) { 3938 if (DEBUG_DOMAIN_VERIFICATION) { 3939 Slog.d(TAG, "Priming domain verifications in user " + userId); 3940 } 3941 3942 SystemConfig systemConfig = SystemConfig.getInstance(); 3943 ArraySet<String> packages = systemConfig.getLinkedApps(); 3944 3945 for (String packageName : packages) { 3946 PackageParser.Package pkg = mPackages.get(packageName); 3947 if (pkg != null) { 3948 if (!pkg.isSystem()) { 3949 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3950 continue; 3951 } 3952 3953 ArraySet<String> domains = null; 3954 for (PackageParser.Activity a : pkg.activities) { 3955 for (ActivityIntentInfo filter : a.intents) { 3956 if (hasValidDomains(filter)) { 3957 if (domains == null) { 3958 domains = new ArraySet<>(); 3959 } 3960 domains.addAll(filter.getHostsList()); 3961 } 3962 } 3963 } 3964 3965 if (domains != null && domains.size() > 0) { 3966 if (DEBUG_DOMAIN_VERIFICATION) { 3967 Slog.v(TAG, " + " + packageName); 3968 } 3969 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3970 // state w.r.t. the formal app-linkage "no verification attempted" state; 3971 // and then 'always' in the per-user state actually used for intent resolution. 3972 final IntentFilterVerificationInfo ivi; 3973 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3974 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3975 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3976 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3977 } else { 3978 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3979 + "' does not handle web links"); 3980 } 3981 } else { 3982 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3983 } 3984 } 3985 3986 scheduleWritePackageRestrictionsLocked(userId); 3987 scheduleWriteSettingsLocked(); 3988 } 3989 packageIsBrowser(String packageName, int userId)3990 private boolean packageIsBrowser(String packageName, int userId) { 3991 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3992 PackageManager.MATCH_ALL, userId); 3993 final int N = list.size(); 3994 for (int i = 0; i < N; i++) { 3995 ResolveInfo info = list.get(i); 3996 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3997 return true; 3998 } 3999 } 4000 return false; 4001 } 4002 4003 @Override onTransact(int code, Parcel data, Parcel reply, int flags)4004 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 4005 throws RemoteException { 4006 try { 4007 return super.onTransact(code, data, reply, flags); 4008 } catch (RuntimeException e) { 4009 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 4010 Slog.wtf(TAG, "Package Manager Crash", e); 4011 } 4012 throw e; 4013 } 4014 } 4015 4016 /** 4017 * Returns whether or not a full application can see an instant application. 4018 * <p> 4019 * Currently, there are four cases in which this can occur: 4020 * <ol> 4021 * <li>The calling application is a "special" process. Special processes 4022 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 4023 * <li>The calling application has the permission 4024 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 4025 * <li>The calling application is the default launcher on the 4026 * system partition.</li> 4027 * <li>The calling application is the default app prediction service.</li> 4028 * </ol> 4029 */ canViewInstantApps(int callingUid, int userId)4030 private boolean canViewInstantApps(int callingUid, int userId) { 4031 if (callingUid < Process.FIRST_APPLICATION_UID) { 4032 return true; 4033 } 4034 if (mContext.checkCallingOrSelfPermission( 4035 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 4036 return true; 4037 } 4038 if (mContext.checkCallingOrSelfPermission( 4039 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 4040 final ComponentName homeComponent = getDefaultHomeActivity(userId); 4041 if (homeComponent != null 4042 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 4043 return true; 4044 } 4045 // TODO(b/122900055) Change/Remove this and replace with new permission role. 4046 if (mAppPredictionServicePackage != null 4047 && isCallerSameApp(mAppPredictionServicePackage, callingUid)) { 4048 return true; 4049 } 4050 } 4051 return false; 4052 } 4053 generatePackageInfo(PackageSetting ps, int flags, int userId)4054 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 4055 if (!sUserManager.exists(userId)) return null; 4056 if (ps == null) { 4057 return null; 4058 } 4059 final int callingUid = Binder.getCallingUid(); 4060 // Filter out ephemeral app metadata: 4061 // * The system/shell/root can see metadata for any app 4062 // * An installed app can see metadata for 1) other installed apps 4063 // and 2) ephemeral apps that have explicitly interacted with it 4064 // * Ephemeral apps can only see their own data and exposed installed apps 4065 // * Holding a signature permission allows seeing instant apps 4066 if (filterAppAccessLPr(ps, callingUid, userId)) { 4067 return null; 4068 } 4069 4070 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 4071 && ps.isSystem()) { 4072 flags |= MATCH_ANY_USER; 4073 } 4074 4075 final PackageUserState state = ps.readUserState(userId); 4076 PackageParser.Package p = ps.pkg; 4077 if (p != null) { 4078 final PermissionsState permissionsState = ps.getPermissionsState(); 4079 4080 // Compute GIDs only if requested 4081 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 4082 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 4083 // Compute granted permissions only if package has requested permissions 4084 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 4085 ? Collections.emptySet() : permissionsState.getPermissions(userId); 4086 4087 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 4088 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 4089 4090 if (packageInfo == null) { 4091 return null; 4092 } 4093 4094 packageInfo.packageName = packageInfo.applicationInfo.packageName = 4095 resolveExternalPackageNameLPr(p); 4096 4097 return packageInfo; 4098 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 4099 PackageInfo pi = new PackageInfo(); 4100 pi.packageName = ps.name; 4101 pi.setLongVersionCode(ps.versionCode); 4102 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 4103 pi.firstInstallTime = ps.firstInstallTime; 4104 pi.lastUpdateTime = ps.lastUpdateTime; 4105 4106 ApplicationInfo ai = new ApplicationInfo(); 4107 ai.packageName = ps.name; 4108 ai.uid = UserHandle.getUid(userId, ps.appId); 4109 ai.primaryCpuAbi = ps.primaryCpuAbiString; 4110 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 4111 ai.setVersionCode(ps.versionCode); 4112 ai.flags = ps.pkgFlags; 4113 ai.privateFlags = ps.pkgPrivateFlags; 4114 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 4115 4116 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 4117 + ps.name + "]. Provides a minimum info."); 4118 return pi; 4119 } else { 4120 return null; 4121 } 4122 } 4123 4124 @Override checkPackageStartable(String packageName, int userId)4125 public void checkPackageStartable(String packageName, int userId) { 4126 final int callingUid = Binder.getCallingUid(); 4127 if (getInstantAppPackageName(callingUid) != null) { 4128 throw new SecurityException("Instant applications don't have access to this method"); 4129 } 4130 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 4131 synchronized (mPackages) { 4132 final PackageSetting ps = mSettings.mPackages.get(packageName); 4133 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 4134 throw new SecurityException("Package " + packageName + " was not found!"); 4135 } 4136 4137 if (!ps.getInstalled(userId)) { 4138 throw new SecurityException( 4139 "Package " + packageName + " was not installed for user " + userId + "!"); 4140 } 4141 4142 if (mSafeMode && !ps.isSystem()) { 4143 throw new SecurityException("Package " + packageName + " not a system app!"); 4144 } 4145 4146 if (mFrozenPackages.contains(packageName)) { 4147 throw new SecurityException("Package " + packageName + " is currently frozen!"); 4148 } 4149 4150 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 4151 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 4152 } 4153 } 4154 } 4155 4156 @Override isPackageAvailable(String packageName, int userId)4157 public boolean isPackageAvailable(String packageName, int userId) { 4158 if (!sUserManager.exists(userId)) return false; 4159 final int callingUid = Binder.getCallingUid(); 4160 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4161 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 4162 synchronized (mPackages) { 4163 PackageParser.Package p = mPackages.get(packageName); 4164 if (p != null) { 4165 final PackageSetting ps = (PackageSetting) p.mExtras; 4166 if (filterAppAccessLPr(ps, callingUid, userId)) { 4167 return false; 4168 } 4169 if (ps != null) { 4170 final PackageUserState state = ps.readUserState(userId); 4171 if (state != null) { 4172 return PackageParser.isAvailable(state); 4173 } 4174 } 4175 } 4176 } 4177 return false; 4178 } 4179 4180 @Override getPackageInfo(String packageName, int flags, int userId)4181 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 4182 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4183 flags, Binder.getCallingUid(), userId); 4184 } 4185 4186 @Override getPackageInfoVersioned(VersionedPackage versionedPackage, int flags, int userId)4187 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4188 int flags, int userId) { 4189 return getPackageInfoInternal(versionedPackage.getPackageName(), 4190 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4191 } 4192 4193 /** 4194 * Important: The provided filterCallingUid is used exclusively to filter out packages 4195 * that can be seen based on user state. It's typically the original caller uid prior 4196 * to clearing. Because it can only be provided by trusted code, it's value can be 4197 * trusted and will be used as-is; unlike userId which will be validated by this method. 4198 */ getPackageInfoInternal(String packageName, long versionCode, int flags, int filterCallingUid, int userId)4199 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4200 int flags, int filterCallingUid, int userId) { 4201 if (!sUserManager.exists(userId)) return null; 4202 flags = updateFlagsForPackage(flags, userId, packageName); 4203 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4204 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4205 4206 // reader 4207 synchronized (mPackages) { 4208 // Normalize package name to handle renamed packages and static libs 4209 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4210 4211 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4212 if (matchFactoryOnly) { 4213 // Instant app filtering for APEX modules is ignored 4214 if ((flags & MATCH_APEX) != 0) { 4215 return mApexManager.getPackageInfo(packageName, 4216 ApexManager.MATCH_FACTORY_PACKAGE); 4217 } 4218 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4219 if (ps != null) { 4220 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4221 return null; 4222 } 4223 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4224 return null; 4225 } 4226 return generatePackageInfo(ps, flags, userId); 4227 } 4228 } 4229 4230 PackageParser.Package p = mPackages.get(packageName); 4231 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4232 return null; 4233 } 4234 if (DEBUG_PACKAGE_INFO) 4235 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4236 if (p != null) { 4237 final PackageSetting ps = (PackageSetting) p.mExtras; 4238 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4239 return null; 4240 } 4241 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4242 return null; 4243 } 4244 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4245 } 4246 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4247 final PackageSetting ps = mSettings.mPackages.get(packageName); 4248 if (ps == null) return null; 4249 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4250 return null; 4251 } 4252 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4253 return null; 4254 } 4255 return generatePackageInfo(ps, flags, userId); 4256 } 4257 if (!matchFactoryOnly && (flags & MATCH_APEX) != 0) { 4258 return mApexManager.getPackageInfo(packageName, ApexManager.MATCH_ACTIVE_PACKAGE); 4259 } 4260 } 4261 return null; 4262 } 4263 isComponentVisibleToInstantApp(@ullable ComponentName component)4264 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4265 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4266 return true; 4267 } 4268 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4269 return true; 4270 } 4271 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4272 return true; 4273 } 4274 return false; 4275 } 4276 isComponentVisibleToInstantApp( @ullable ComponentName component, @ComponentType int type)4277 private boolean isComponentVisibleToInstantApp( 4278 @Nullable ComponentName component, @ComponentType int type) { 4279 if (type == TYPE_ACTIVITY) { 4280 final PackageParser.Activity activity = mComponentResolver.getActivity(component); 4281 if (activity == null) { 4282 return false; 4283 } 4284 final boolean visibleToInstantApp = 4285 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4286 final boolean explicitlyVisibleToInstantApp = 4287 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4288 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4289 } else if (type == TYPE_RECEIVER) { 4290 final PackageParser.Activity activity = mComponentResolver.getReceiver(component); 4291 if (activity == null) { 4292 return false; 4293 } 4294 final boolean visibleToInstantApp = 4295 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4296 final boolean explicitlyVisibleToInstantApp = 4297 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4298 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4299 } else if (type == TYPE_SERVICE) { 4300 final PackageParser.Service service = mComponentResolver.getService(component); 4301 return service != null 4302 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4303 : false; 4304 } else if (type == TYPE_PROVIDER) { 4305 final PackageParser.Provider provider = mComponentResolver.getProvider(component); 4306 return provider != null 4307 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4308 : false; 4309 } else if (type == TYPE_UNKNOWN) { 4310 return isComponentVisibleToInstantApp(component); 4311 } 4312 return false; 4313 } 4314 4315 /** 4316 * Returns whether or not access to the application should be filtered. 4317 * <p> 4318 * Access may be limited based upon whether the calling or target applications 4319 * are instant applications. 4320 * 4321 * @see #canViewInstantApps(int, int) 4322 */ 4323 @GuardedBy("mPackages") filterAppAccessLPr(@ullable PackageSetting ps, int callingUid, @Nullable ComponentName component, @ComponentType int componentType, int userId)4324 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4325 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4326 // if we're in an isolated process, get the real calling UID 4327 if (Process.isIsolated(callingUid)) { 4328 callingUid = mIsolatedOwners.get(callingUid); 4329 } 4330 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4331 final boolean callerIsInstantApp = instantAppPkgName != null; 4332 if (ps == null) { 4333 if (callerIsInstantApp) { 4334 // pretend the application exists, but, needs to be filtered 4335 return true; 4336 } 4337 return false; 4338 } 4339 // if the target and caller are the same application, don't filter 4340 if (isCallerSameApp(ps.name, callingUid)) { 4341 return false; 4342 } 4343 if (callerIsInstantApp) { 4344 // both caller and target are both instant, but, different applications, filter 4345 if (ps.getInstantApp(userId)) { 4346 return true; 4347 } 4348 // request for a specific component; if it hasn't been explicitly exposed through 4349 // property or instrumentation target, filter 4350 if (component != null) { 4351 final PackageParser.Instrumentation instrumentation = 4352 mInstrumentation.get(component); 4353 if (instrumentation != null 4354 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4355 return false; 4356 } 4357 return !isComponentVisibleToInstantApp(component, componentType); 4358 } 4359 // request for application; if no components have been explicitly exposed, filter 4360 return !ps.pkg.visibleToInstantApps; 4361 } 4362 if (ps.getInstantApp(userId)) { 4363 // caller can see all components of all instant applications, don't filter 4364 if (canViewInstantApps(callingUid, userId)) { 4365 return false; 4366 } 4367 // request for a specific instant application component, filter 4368 if (component != null) { 4369 return true; 4370 } 4371 // request for an instant application; if the caller hasn't been granted access, filter 4372 return !mInstantAppRegistry.isInstantAccessGranted( 4373 userId, UserHandle.getAppId(callingUid), ps.appId); 4374 } 4375 return false; 4376 } 4377 4378 /** 4379 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, int, int) 4380 */ 4381 @GuardedBy("mPackages") filterAppAccessLPr(@ullable PackageSetting ps, int callingUid, int userId)4382 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4383 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4384 } 4385 4386 @GuardedBy("mPackages") filterSharedLibPackageLPr(@ullable PackageSetting ps, int uid, int userId, int flags)4387 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4388 int flags) { 4389 // Callers can access only the libs they depend on, otherwise they need to explicitly 4390 // ask for the shared libraries given the caller is allowed to access all static libs. 4391 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4392 // System/shell/root get to see all static libs 4393 final int appId = UserHandle.getAppId(uid); 4394 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4395 || appId == Process.ROOT_UID) { 4396 return false; 4397 } 4398 // Installer gets to see all static libs. 4399 if (PackageManager.PERMISSION_GRANTED 4400 == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) { 4401 return false; 4402 } 4403 } 4404 4405 // No package means no static lib as it is always on internal storage 4406 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4407 return false; 4408 } 4409 4410 final SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(ps.pkg.staticSharedLibName, 4411 ps.pkg.staticSharedLibVersion); 4412 if (libraryInfo == null) { 4413 return false; 4414 } 4415 4416 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4417 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4418 if (uidPackageNames == null) { 4419 return true; 4420 } 4421 4422 for (String uidPackageName : uidPackageNames) { 4423 if (ps.name.equals(uidPackageName)) { 4424 return false; 4425 } 4426 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4427 if (uidPs != null) { 4428 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4429 libraryInfo.getName()); 4430 if (index < 0) { 4431 continue; 4432 } 4433 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libraryInfo.getLongVersion()) { 4434 return false; 4435 } 4436 } 4437 } 4438 return true; 4439 } 4440 4441 @Override currentToCanonicalPackageNames(String[] names)4442 public String[] currentToCanonicalPackageNames(String[] names) { 4443 final int callingUid = Binder.getCallingUid(); 4444 if (getInstantAppPackageName(callingUid) != null) { 4445 return names; 4446 } 4447 final String[] out = new String[names.length]; 4448 // reader 4449 synchronized (mPackages) { 4450 final int callingUserId = UserHandle.getUserId(callingUid); 4451 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4452 for (int i=names.length-1; i>=0; i--) { 4453 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4454 boolean translateName = false; 4455 if (ps != null && ps.realName != null) { 4456 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4457 translateName = !targetIsInstantApp 4458 || canViewInstantApps 4459 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4460 UserHandle.getAppId(callingUid), ps.appId); 4461 } 4462 out[i] = translateName ? ps.realName : names[i]; 4463 } 4464 } 4465 return out; 4466 } 4467 4468 @Override canonicalToCurrentPackageNames(String[] names)4469 public String[] canonicalToCurrentPackageNames(String[] names) { 4470 final int callingUid = Binder.getCallingUid(); 4471 if (getInstantAppPackageName(callingUid) != null) { 4472 return names; 4473 } 4474 final String[] out = new String[names.length]; 4475 // reader 4476 synchronized (mPackages) { 4477 final int callingUserId = UserHandle.getUserId(callingUid); 4478 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4479 for (int i=names.length-1; i>=0; i--) { 4480 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4481 boolean translateName = false; 4482 if (cur != null) { 4483 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4484 final boolean targetIsInstantApp = 4485 ps != null && ps.getInstantApp(callingUserId); 4486 translateName = !targetIsInstantApp 4487 || canViewInstantApps 4488 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4489 UserHandle.getAppId(callingUid), ps.appId); 4490 } 4491 out[i] = translateName ? cur : names[i]; 4492 } 4493 } 4494 return out; 4495 } 4496 4497 @Override getPackageUid(String packageName, int flags, int userId)4498 public int getPackageUid(String packageName, int flags, int userId) { 4499 if (!sUserManager.exists(userId)) return -1; 4500 final int callingUid = Binder.getCallingUid(); 4501 flags = updateFlagsForPackage(flags, userId, packageName); 4502 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4503 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4504 4505 // reader 4506 synchronized (mPackages) { 4507 final PackageParser.Package p = mPackages.get(packageName); 4508 if (p != null && p.isMatch(flags)) { 4509 PackageSetting ps = (PackageSetting) p.mExtras; 4510 if (filterAppAccessLPr(ps, callingUid, userId)) { 4511 return -1; 4512 } 4513 return UserHandle.getUid(userId, p.applicationInfo.uid); 4514 } 4515 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4516 final PackageSetting ps = mSettings.mPackages.get(packageName); 4517 if (ps != null && ps.isMatch(flags) 4518 && !filterAppAccessLPr(ps, callingUid, userId)) { 4519 return UserHandle.getUid(userId, ps.appId); 4520 } 4521 } 4522 } 4523 4524 return -1; 4525 } 4526 4527 /** 4528 * Check if any package sharing/holding a uid has a low enough target SDK. 4529 * 4530 * @param uid The uid of the packages 4531 * @param higherTargetSDK The target SDK that might be higher than the searched package 4532 * 4533 * @return {@code true} if there is a package sharing/holding the uid with 4534 * {@code package.targetSDK < higherTargetSDK} 4535 */ hasTargetSdkInUidLowerThan(int uid, int higherTargetSDK)4536 private boolean hasTargetSdkInUidLowerThan(int uid, int higherTargetSDK) { 4537 int userId = UserHandle.getUserId(uid); 4538 4539 synchronized (mPackages) { 4540 Object obj = mSettings.getSettingLPr(UserHandle.getAppId(uid)); 4541 if (obj == null) { 4542 return false; 4543 } 4544 4545 if (obj instanceof PackageSetting) { 4546 final PackageSetting ps = (PackageSetting) obj; 4547 4548 if (!ps.getInstalled(userId)) { 4549 return false; 4550 } 4551 4552 return ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK; 4553 } else if (obj instanceof SharedUserSetting) { 4554 final SharedUserSetting sus = (SharedUserSetting) obj; 4555 4556 final int numPkgs = sus.packages.size(); 4557 for (int i = 0; i < numPkgs; i++) { 4558 final PackageSetting ps = sus.packages.valueAt(i); 4559 4560 if (!ps.getInstalled(userId)) { 4561 continue; 4562 } 4563 4564 if (ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK) { 4565 return true; 4566 } 4567 } 4568 4569 return false; 4570 } else { 4571 return false; 4572 } 4573 } 4574 } 4575 4576 @Override getPackageGids(String packageName, int flags, int userId)4577 public int[] getPackageGids(String packageName, int flags, int userId) { 4578 if (!sUserManager.exists(userId)) return null; 4579 final int callingUid = Binder.getCallingUid(); 4580 flags = updateFlagsForPackage(flags, userId, packageName); 4581 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4582 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4583 4584 // reader 4585 synchronized (mPackages) { 4586 final PackageParser.Package p = mPackages.get(packageName); 4587 if (p != null && p.isMatch(flags)) { 4588 PackageSetting ps = (PackageSetting) p.mExtras; 4589 if (filterAppAccessLPr(ps, callingUid, userId)) { 4590 return null; 4591 } 4592 // TODO: Shouldn't this be checking for package installed state for userId and 4593 // return null? 4594 return ps.getPermissionsState().computeGids(userId); 4595 } 4596 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4597 final PackageSetting ps = mSettings.mPackages.get(packageName); 4598 if (ps != null && ps.isMatch(flags) 4599 && !filterAppAccessLPr(ps, callingUid, userId)) { 4600 return ps.getPermissionsState().computeGids(userId); 4601 } 4602 } 4603 } 4604 4605 return null; 4606 } 4607 4608 @Override getPermissionInfo(String name, String packageName, int flags)4609 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4610 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4611 } 4612 4613 @Override queryPermissionsByGroup(String groupName, int flags)4614 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4615 int flags) { 4616 final List<PermissionInfo> permissionList = 4617 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4618 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4619 } 4620 4621 @Override getPermissionGroupInfo(String groupName, int flags)4622 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4623 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4624 } 4625 4626 @Override getAllPermissionGroups(int flags)4627 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4628 final List<PermissionGroupInfo> permissionList = 4629 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4630 return (permissionList == null) 4631 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4632 } 4633 4634 @GuardedBy("mPackages") generateApplicationInfoFromSettingsLPw(String packageName, int flags, int filterCallingUid, int userId)4635 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4636 int filterCallingUid, int userId) { 4637 if (!sUserManager.exists(userId)) return null; 4638 PackageSetting ps = mSettings.mPackages.get(packageName); 4639 if (ps != null) { 4640 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4641 return null; 4642 } 4643 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4644 return null; 4645 } 4646 if (ps.pkg == null) { 4647 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4648 if (pInfo != null) { 4649 return pInfo.applicationInfo; 4650 } 4651 return null; 4652 } 4653 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4654 ps.readUserState(userId), userId); 4655 if (ai != null) { 4656 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4657 } 4658 return ai; 4659 } 4660 return null; 4661 } 4662 4663 @Override getApplicationInfo(String packageName, int flags, int userId)4664 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4665 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4666 } 4667 4668 /** 4669 * Important: The provided filterCallingUid is used exclusively to filter out applications 4670 * that can be seen based on user state. It's typically the original caller uid prior 4671 * to clearing. Because it can only be provided by trusted code, it's value can be 4672 * trusted and will be used as-is; unlike userId which will be validated by this method. 4673 */ getApplicationInfoInternal(String packageName, int flags, int filterCallingUid, int userId)4674 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4675 int filterCallingUid, int userId) { 4676 if (!sUserManager.exists(userId)) return null; 4677 flags = updateFlagsForApplication(flags, userId, packageName); 4678 4679 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4680 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4681 false /* requireFullPermission */, false /* checkShell */, 4682 "get application info"); 4683 } 4684 4685 // writer 4686 synchronized (mPackages) { 4687 // Normalize package name to handle renamed packages and static libs 4688 packageName = resolveInternalPackageNameLPr(packageName, 4689 PackageManager.VERSION_CODE_HIGHEST); 4690 4691 PackageParser.Package p = mPackages.get(packageName); 4692 if (DEBUG_PACKAGE_INFO) Log.v( 4693 TAG, "getApplicationInfo " + packageName 4694 + ": " + p); 4695 if (p != null) { 4696 PackageSetting ps = mSettings.mPackages.get(packageName); 4697 if (ps == null) return null; 4698 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4699 return null; 4700 } 4701 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4702 return null; 4703 } 4704 // Note: isEnabledLP() does not apply here - always return info 4705 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4706 p, flags, ps.readUserState(userId), userId); 4707 if (ai != null) { 4708 ai.packageName = resolveExternalPackageNameLPr(p); 4709 } 4710 return ai; 4711 } 4712 if ("android".equals(packageName)||"system".equals(packageName)) { 4713 return mAndroidApplication; 4714 } 4715 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4716 // Already generates the external package name 4717 return generateApplicationInfoFromSettingsLPw(packageName, 4718 flags, filterCallingUid, userId); 4719 } 4720 } 4721 return null; 4722 } 4723 4724 @GuardedBy("mPackages") normalizePackageNameLPr(String packageName)4725 private String normalizePackageNameLPr(String packageName) { 4726 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4727 return normalizedPackageName != null ? normalizedPackageName : packageName; 4728 } 4729 4730 @Override deletePreloadsFileCache()4731 public void deletePreloadsFileCache() { 4732 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CLEAR_APP_CACHE, 4733 "deletePreloadsFileCache"); 4734 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4735 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4736 FileUtils.deleteContents(dir); 4737 } 4738 4739 @Override freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, final int storageFlags, final IPackageDataObserver observer)4740 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4741 final int storageFlags, final IPackageDataObserver observer) { 4742 mContext.enforceCallingOrSelfPermission( 4743 android.Manifest.permission.CLEAR_APP_CACHE, null); 4744 mHandler.post(() -> { 4745 boolean success = false; 4746 try { 4747 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4748 success = true; 4749 } catch (IOException e) { 4750 Slog.w(TAG, e); 4751 } 4752 if (observer != null) { 4753 try { 4754 observer.onRemoveCompleted(null, success); 4755 } catch (RemoteException e) { 4756 Slog.w(TAG, e); 4757 } 4758 } 4759 }); 4760 } 4761 4762 @Override freeStorage(final String volumeUuid, final long freeStorageSize, final int storageFlags, final IntentSender pi)4763 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4764 final int storageFlags, final IntentSender pi) { 4765 mContext.enforceCallingOrSelfPermission( 4766 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4767 mHandler.post(() -> { 4768 boolean success = false; 4769 try { 4770 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4771 success = true; 4772 } catch (IOException e) { 4773 Slog.w(TAG, e); 4774 } 4775 if (pi != null) { 4776 try { 4777 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4778 } catch (SendIntentException e) { 4779 Slog.w(TAG, e); 4780 } 4781 } 4782 }); 4783 } 4784 4785 /** 4786 * Blocking call to clear various types of cached data across the system 4787 * until the requested bytes are available. 4788 */ freeStorage(String volumeUuid, long bytes, int storageFlags)4789 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4790 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4791 final File file = storage.findPathForUuid(volumeUuid); 4792 if (file.getUsableSpace() >= bytes) return; 4793 4794 if (ENABLE_FREE_CACHE_V2) { 4795 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4796 volumeUuid); 4797 final boolean aggressive = (storageFlags 4798 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4799 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4800 4801 // 1. Pre-flight to determine if we have any chance to succeed 4802 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4803 if (internalVolume && (aggressive || SystemProperties 4804 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4805 deletePreloadsFileCache(); 4806 if (file.getUsableSpace() >= bytes) return; 4807 } 4808 4809 // 3. Consider parsed APK data (aggressive only) 4810 if (internalVolume && aggressive) { 4811 FileUtils.deleteContents(mCacheDir); 4812 if (file.getUsableSpace() >= bytes) return; 4813 } 4814 4815 // 4. Consider cached app data (above quotas) 4816 try { 4817 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4818 Installer.FLAG_FREE_CACHE_V2); 4819 } catch (InstallerException ignored) { 4820 } 4821 if (file.getUsableSpace() >= bytes) return; 4822 4823 // 5. Consider shared libraries with refcount=0 and age>min cache period 4824 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4825 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4826 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4827 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4828 return; 4829 } 4830 4831 // 6. Consider dexopt output (aggressive only) 4832 // TODO: Implement 4833 4834 // 7. Consider installed instant apps unused longer than min cache period 4835 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4836 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4837 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4838 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4839 return; 4840 } 4841 4842 // 8. Consider cached app data (below quotas) 4843 try { 4844 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4845 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4846 } catch (InstallerException ignored) { 4847 } 4848 if (file.getUsableSpace() >= bytes) return; 4849 4850 // 9. Consider DropBox entries 4851 // TODO: Implement 4852 4853 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4854 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4855 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4856 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4857 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4858 return; 4859 } 4860 } else { 4861 try { 4862 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4863 } catch (InstallerException ignored) { 4864 } 4865 if (file.getUsableSpace() >= bytes) return; 4866 } 4867 4868 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4869 } 4870 pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod)4871 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4872 throws IOException { 4873 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4874 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4875 4876 List<VersionedPackage> packagesToDelete = null; 4877 final long now = System.currentTimeMillis(); 4878 4879 synchronized (mPackages) { 4880 final int[] allUsers = sUserManager.getUserIds(); 4881 final int libCount = mSharedLibraries.size(); 4882 for (int i = 0; i < libCount; i++) { 4883 final LongSparseArray<SharedLibraryInfo> versionedLib 4884 = mSharedLibraries.valueAt(i); 4885 if (versionedLib == null) { 4886 continue; 4887 } 4888 final int versionCount = versionedLib.size(); 4889 for (int j = 0; j < versionCount; j++) { 4890 SharedLibraryInfo libInfo = versionedLib.valueAt(j); 4891 // Skip packages that are not static shared libs. 4892 if (!libInfo.isStatic()) { 4893 break; 4894 } 4895 // Important: We skip static shared libs used for some user since 4896 // in such a case we need to keep the APK on the device. The check for 4897 // a lib being used for any user is performed by the uninstall call. 4898 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4899 // Resolve the package name - we use synthetic package names internally 4900 final String internalPackageName = resolveInternalPackageNameLPr( 4901 declaringPackage.getPackageName(), 4902 declaringPackage.getLongVersionCode()); 4903 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4904 // Skip unused static shared libs cached less than the min period 4905 // to prevent pruning a lib needed by a subsequently installed package. 4906 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4907 continue; 4908 } 4909 4910 if (ps.pkg.isSystem()) { 4911 continue; 4912 } 4913 4914 if (packagesToDelete == null) { 4915 packagesToDelete = new ArrayList<>(); 4916 } 4917 packagesToDelete.add(new VersionedPackage(internalPackageName, 4918 declaringPackage.getLongVersionCode())); 4919 } 4920 } 4921 } 4922 4923 if (packagesToDelete != null) { 4924 final int packageCount = packagesToDelete.size(); 4925 for (int i = 0; i < packageCount; i++) { 4926 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4927 // Delete the package synchronously (will fail of the lib used for any user). 4928 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4929 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4930 == PackageManager.DELETE_SUCCEEDED) { 4931 if (volume.getUsableSpace() >= neededSpace) { 4932 return true; 4933 } 4934 } 4935 } 4936 } 4937 4938 return false; 4939 } 4940 4941 /** 4942 * Update given flags based on encryption status of current user. 4943 */ updateFlags(int flags, int userId)4944 private int updateFlags(int flags, int userId) { 4945 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4946 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4947 // Caller expressed an explicit opinion about what encryption 4948 // aware/unaware components they want to see, so fall through and 4949 // give them what they want 4950 } else { 4951 // Caller expressed no opinion, so match based on user state 4952 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4953 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4954 } else { 4955 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4956 } 4957 } 4958 return flags; 4959 } 4960 getUserManagerInternal()4961 private UserManagerInternal getUserManagerInternal() { 4962 if (mUserManagerInternal == null) { 4963 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4964 } 4965 return mUserManagerInternal; 4966 } 4967 getActivityManagerInternal()4968 private ActivityManagerInternal getActivityManagerInternal() { 4969 if (mActivityManagerInternal == null) { 4970 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4971 } 4972 return mActivityManagerInternal; 4973 } 4974 getActivityTaskManagerInternal()4975 private ActivityTaskManagerInternal getActivityTaskManagerInternal() { 4976 if (mActivityTaskManagerInternal == null) { 4977 mActivityTaskManagerInternal = 4978 LocalServices.getService(ActivityTaskManagerInternal.class); 4979 } 4980 return mActivityTaskManagerInternal; 4981 } 4982 getDeviceIdleController()4983 private DeviceIdleController.LocalService getDeviceIdleController() { 4984 if (mDeviceIdleController == null) { 4985 mDeviceIdleController = 4986 LocalServices.getService(DeviceIdleController.LocalService.class); 4987 } 4988 return mDeviceIdleController; 4989 } 4990 getStorageManagerInternal()4991 private StorageManagerInternal getStorageManagerInternal() { 4992 if (mStorageManagerInternal == null) { 4993 mStorageManagerInternal = LocalServices.getService(StorageManagerInternal.class); 4994 } 4995 return mStorageManagerInternal; 4996 } 4997 4998 /** 4999 * Update given flags when being used to request {@link PackageInfo}. 5000 */ updateFlagsForPackage(int flags, int userId, Object cookie)5001 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 5002 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 5003 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 5004 // require the permission to be held; the calling uid and given user id referring 5005 // to the same user is not sufficient 5006 mPermissionManager.enforceCrossUserPermission( 5007 Binder.getCallingUid(), userId, false, false, 5008 !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId), 5009 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 5010 + Debug.getCallers(5)); 5011 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 5012 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 5013 // If the caller wants all packages and has a restricted profile associated with it, 5014 // then match all users. This is to make sure that launchers that need to access work 5015 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 5016 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 5017 flags |= PackageManager.MATCH_ANY_USER; 5018 } 5019 return updateFlags(flags, userId); 5020 } 5021 5022 /** 5023 * Update given flags when being used to request {@link ApplicationInfo}. 5024 */ updateFlagsForApplication(int flags, int userId, Object cookie)5025 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 5026 return updateFlagsForPackage(flags, userId, cookie); 5027 } 5028 5029 /** 5030 * Update given flags when being used to request {@link ComponentInfo}. 5031 */ updateFlagsForComponent(int flags, int userId, Object cookie)5032 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 5033 return updateFlags(flags, userId); 5034 } 5035 5036 /** 5037 * Update given intent when being used to request {@link ResolveInfo}. 5038 */ updateIntentForResolve(Intent intent)5039 private Intent updateIntentForResolve(Intent intent) { 5040 if (intent.getSelector() != null) { 5041 intent = intent.getSelector(); 5042 } 5043 if (DEBUG_PREFERRED) { 5044 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5045 } 5046 return intent; 5047 } 5048 5049 /** 5050 * Update given flags when being used to request {@link ResolveInfo}. 5051 * <p>Instant apps are resolved specially, depending upon context. Minimally, 5052 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 5053 * flag set. However, this flag is only honoured in three circumstances: 5054 * <ul> 5055 * <li>when called from a system process</li> 5056 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 5057 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 5058 * action and a {@code android.intent.category.BROWSABLE} category</li> 5059 * </ul> 5060 */ updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid)5061 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 5062 return updateFlagsForResolve(flags, userId, intent, callingUid, 5063 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 5064 } updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, boolean wantInstantApps)5065 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 5066 boolean wantInstantApps) { 5067 return updateFlagsForResolve(flags, userId, intent, callingUid, 5068 wantInstantApps, false /*onlyExposedExplicitly*/); 5069 } updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, boolean wantInstantApps, boolean onlyExposedExplicitly)5070 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 5071 boolean wantInstantApps, boolean onlyExposedExplicitly) { 5072 // Safe mode means we shouldn't match any third-party components 5073 if (mSafeMode) { 5074 flags |= PackageManager.MATCH_SYSTEM_ONLY; 5075 } 5076 if (getInstantAppPackageName(callingUid) != null) { 5077 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 5078 if (onlyExposedExplicitly) { 5079 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 5080 } 5081 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 5082 flags |= PackageManager.MATCH_INSTANT; 5083 } else { 5084 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 5085 final boolean allowMatchInstant = wantInstantApps 5086 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 5087 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 5088 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 5089 if (!allowMatchInstant) { 5090 flags &= ~PackageManager.MATCH_INSTANT; 5091 } 5092 } 5093 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 5094 } 5095 5096 @Override getActivityInfo(ComponentName component, int flags, int userId)5097 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 5098 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 5099 } 5100 5101 /** 5102 * Important: The provided filterCallingUid is used exclusively to filter out activities 5103 * that can be seen based on user state. It's typically the original caller uid prior 5104 * to clearing. Because it can only be provided by trusted code, it's value can be 5105 * trusted and will be used as-is; unlike userId which will be validated by this method. 5106 */ getActivityInfoInternal(ComponentName component, int flags, int filterCallingUid, int userId)5107 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 5108 int filterCallingUid, int userId) { 5109 if (!sUserManager.exists(userId)) return null; 5110 flags = updateFlagsForComponent(flags, userId, component); 5111 5112 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 5113 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5114 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 5115 } 5116 5117 synchronized (mPackages) { 5118 PackageParser.Activity a = mComponentResolver.getActivity(component); 5119 5120 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 5121 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 5122 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5123 if (ps == null) return null; 5124 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 5125 return null; 5126 } 5127 return PackageParser.generateActivityInfo( 5128 a, flags, ps.readUserState(userId), userId); 5129 } 5130 if (mResolveComponentName.equals(component)) { 5131 return PackageParser.generateActivityInfo( 5132 mResolveActivity, flags, new PackageUserState(), userId); 5133 } 5134 } 5135 return null; 5136 } 5137 isRecentsAccessingChildProfiles(int callingUid, int targetUserId)5138 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 5139 if (!getActivityTaskManagerInternal().isCallerRecents(callingUid)) { 5140 return false; 5141 } 5142 final long token = Binder.clearCallingIdentity(); 5143 try { 5144 final int callingUserId = UserHandle.getUserId(callingUid); 5145 if (ActivityManager.getCurrentUser() != callingUserId) { 5146 return false; 5147 } 5148 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 5149 } finally { 5150 Binder.restoreCallingIdentity(token); 5151 } 5152 } 5153 5154 @Override activitySupportsIntent(ComponentName component, Intent intent, String resolvedType)5155 public boolean activitySupportsIntent(ComponentName component, Intent intent, 5156 String resolvedType) { 5157 synchronized (mPackages) { 5158 if (component.equals(mResolveComponentName)) { 5159 // The resolver supports EVERYTHING! 5160 return true; 5161 } 5162 final int callingUid = Binder.getCallingUid(); 5163 final int callingUserId = UserHandle.getUserId(callingUid); 5164 PackageParser.Activity a = mComponentResolver.getActivity(component); 5165 if (a == null) { 5166 return false; 5167 } 5168 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5169 if (ps == null) { 5170 return false; 5171 } 5172 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 5173 return false; 5174 } 5175 for (int i=0; i<a.intents.size(); i++) { 5176 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 5177 intent.getData(), intent.getCategories(), TAG) >= 0) { 5178 return true; 5179 } 5180 } 5181 return false; 5182 } 5183 } 5184 5185 @Override getReceiverInfo(ComponentName component, int flags, int userId)5186 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 5187 if (!sUserManager.exists(userId)) return null; 5188 final int callingUid = Binder.getCallingUid(); 5189 flags = updateFlagsForComponent(flags, userId, component); 5190 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5191 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 5192 synchronized (mPackages) { 5193 PackageParser.Activity a = mComponentResolver.getReceiver(component); 5194 if (DEBUG_PACKAGE_INFO) Log.v( 5195 TAG, "getReceiverInfo " + component + ": " + a); 5196 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 5197 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5198 if (ps == null) return null; 5199 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 5200 return null; 5201 } 5202 return PackageParser.generateActivityInfo( 5203 a, flags, ps.readUserState(userId), userId); 5204 } 5205 } 5206 return null; 5207 } 5208 5209 @Override getSharedLibraries(String packageName, int flags, int userId)5210 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 5211 int flags, int userId) { 5212 if (!sUserManager.exists(userId)) return null; 5213 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 5214 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5215 return null; 5216 } 5217 5218 flags = updateFlagsForPackage(flags, userId, null); 5219 5220 final boolean canSeeStaticLibraries = 5221 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 5222 == PERMISSION_GRANTED 5223 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 5224 == PERMISSION_GRANTED 5225 || canRequestPackageInstallsInternal(packageName, 5226 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 5227 false /* throwIfPermNotDeclared*/) 5228 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 5229 == PERMISSION_GRANTED 5230 || mContext.checkCallingOrSelfPermission( 5231 Manifest.permission.ACCESS_SHARED_LIBRARIES) == PERMISSION_GRANTED; 5232 5233 synchronized (mPackages) { 5234 List<SharedLibraryInfo> result = null; 5235 5236 final int libCount = mSharedLibraries.size(); 5237 for (int i = 0; i < libCount; i++) { 5238 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i); 5239 if (versionedLib == null) { 5240 continue; 5241 } 5242 5243 final int versionCount = versionedLib.size(); 5244 for (int j = 0; j < versionCount; j++) { 5245 SharedLibraryInfo libInfo = versionedLib.valueAt(j); 5246 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5247 break; 5248 } 5249 final long identity = Binder.clearCallingIdentity(); 5250 try { 5251 PackageInfo packageInfo = getPackageInfoVersioned( 5252 libInfo.getDeclaringPackage(), flags 5253 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5254 if (packageInfo == null) { 5255 continue; 5256 } 5257 } finally { 5258 Binder.restoreCallingIdentity(identity); 5259 } 5260 5261 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getPath(), 5262 libInfo.getPackageName(), libInfo.getAllCodePaths(), 5263 libInfo.getName(), libInfo.getLongVersion(), 5264 libInfo.getType(), libInfo.getDeclaringPackage(), 5265 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId), 5266 (libInfo.getDependencies() == null 5267 ? null 5268 : new ArrayList<>(libInfo.getDependencies()))); 5269 5270 if (result == null) { 5271 result = new ArrayList<>(); 5272 } 5273 result.add(resLibInfo); 5274 } 5275 } 5276 5277 return result != null ? new ParceledListSlice<>(result) : null; 5278 } 5279 } 5280 5281 @Nullable 5282 @Override getDeclaredSharedLibraries( @onNull String packageName, int flags, @NonNull int userId)5283 public ParceledListSlice<SharedLibraryInfo> getDeclaredSharedLibraries( 5284 @NonNull String packageName, int flags, @NonNull int userId) { 5285 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES, 5286 "getDeclaredSharedLibraries"); 5287 int callingUid = Binder.getCallingUid(); 5288 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5289 true /* requireFullPermission */, false /* checkShell */, 5290 "getDeclaredSharedLibraries"); 5291 5292 Preconditions.checkNotNull(packageName, "packageName cannot be null"); 5293 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 5294 if (!sUserManager.exists(userId)) { 5295 return null; 5296 } 5297 5298 if (getInstantAppPackageName(callingUid) != null) { 5299 return null; 5300 } 5301 5302 synchronized (mPackages) { 5303 List<SharedLibraryInfo> result = null; 5304 5305 int libraryCount = mSharedLibraries.size(); 5306 for (int i = 0; i < libraryCount; i++) { 5307 LongSparseArray<SharedLibraryInfo> versionedLibrary = mSharedLibraries.valueAt(i); 5308 if (versionedLibrary == null) { 5309 continue; 5310 } 5311 5312 int versionCount = versionedLibrary.size(); 5313 for (int j = 0; j < versionCount; j++) { 5314 SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j); 5315 5316 VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage(); 5317 if (!Objects.equals(declaringPackage.getPackageName(), packageName)) { 5318 continue; 5319 } 5320 5321 long identity = Binder.clearCallingIdentity(); 5322 try { 5323 PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags 5324 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5325 if (packageInfo == null) { 5326 continue; 5327 } 5328 } finally { 5329 Binder.restoreCallingIdentity(identity); 5330 } 5331 5332 SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo( 5333 libraryInfo.getPath(), libraryInfo.getPackageName(), 5334 libraryInfo.getAllCodePaths(), libraryInfo.getName(), 5335 libraryInfo.getLongVersion(), libraryInfo.getType(), 5336 libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr( 5337 libraryInfo, flags, userId), libraryInfo.getDependencies() == null 5338 ? null : new ArrayList<>(libraryInfo.getDependencies())); 5339 5340 if (result == null) { 5341 result = new ArrayList<>(); 5342 } 5343 result.add(resultLibraryInfo); 5344 } 5345 } 5346 5347 return result != null ? new ParceledListSlice<>(result) : null; 5348 } 5349 } 5350 5351 @GuardedBy("mPackages") getPackagesUsingSharedLibraryLPr( SharedLibraryInfo libInfo, int flags, int userId)5352 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5353 SharedLibraryInfo libInfo, int flags, int userId) { 5354 List<VersionedPackage> versionedPackages = null; 5355 final int packageCount = mSettings.mPackages.size(); 5356 for (int i = 0; i < packageCount; i++) { 5357 PackageSetting ps = mSettings.mPackages.valueAt(i); 5358 5359 if (ps == null) { 5360 continue; 5361 } 5362 5363 if (!ps.readUserState(userId).isAvailable(flags)) { 5364 continue; 5365 } 5366 5367 final String libName = libInfo.getName(); 5368 if (libInfo.isStatic()) { 5369 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5370 if (libIdx < 0) { 5371 continue; 5372 } 5373 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5374 continue; 5375 } 5376 if (versionedPackages == null) { 5377 versionedPackages = new ArrayList<>(); 5378 } 5379 // If the dependent is a static shared lib, use the public package name 5380 String dependentPackageName = ps.name; 5381 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5382 dependentPackageName = ps.pkg.manifestPackageName; 5383 } 5384 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5385 } else if (ps.pkg != null) { 5386 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5387 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5388 if (versionedPackages == null) { 5389 versionedPackages = new ArrayList<>(); 5390 } 5391 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5392 } 5393 } 5394 } 5395 5396 return versionedPackages; 5397 } 5398 5399 @Override getServiceInfo(ComponentName component, int flags, int userId)5400 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5401 if (!sUserManager.exists(userId)) return null; 5402 final int callingUid = Binder.getCallingUid(); 5403 flags = updateFlagsForComponent(flags, userId, component); 5404 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5405 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5406 synchronized (mPackages) { 5407 PackageParser.Service s = mComponentResolver.getService(component); 5408 if (DEBUG_PACKAGE_INFO) Log.v( 5409 TAG, "getServiceInfo " + component + ": " + s); 5410 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5411 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5412 if (ps == null) return null; 5413 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5414 return null; 5415 } 5416 return PackageParser.generateServiceInfo( 5417 s, flags, ps.readUserState(userId), userId); 5418 } 5419 } 5420 return null; 5421 } 5422 5423 @Override getProviderInfo(ComponentName component, int flags, int userId)5424 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5425 if (!sUserManager.exists(userId)) return null; 5426 final int callingUid = Binder.getCallingUid(); 5427 flags = updateFlagsForComponent(flags, userId, component); 5428 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5429 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5430 synchronized (mPackages) { 5431 PackageParser.Provider p = mComponentResolver.getProvider(component); 5432 if (DEBUG_PACKAGE_INFO) Log.v( 5433 TAG, "getProviderInfo " + component + ": " + p); 5434 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5435 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5436 if (ps == null) return null; 5437 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5438 return null; 5439 } 5440 return PackageParser.generateProviderInfo( 5441 p, flags, ps.readUserState(userId), userId); 5442 } 5443 } 5444 return null; 5445 } 5446 5447 @Override getModuleInfo(String packageName, @ModuleInfoFlags int flags)5448 public ModuleInfo getModuleInfo(String packageName, @ModuleInfoFlags int flags) { 5449 return mModuleInfoProvider.getModuleInfo(packageName, flags); 5450 } 5451 5452 @Override getInstalledModules(int flags)5453 public List<ModuleInfo> getInstalledModules(int flags) { 5454 return mModuleInfoProvider.getInstalledModules(flags); 5455 } 5456 5457 @Override getSystemSharedLibraryNames()5458 public String[] getSystemSharedLibraryNames() { 5459 // allow instant applications 5460 synchronized (mPackages) { 5461 Set<String> libs = null; 5462 final int libCount = mSharedLibraries.size(); 5463 for (int i = 0; i < libCount; i++) { 5464 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i); 5465 if (versionedLib == null) { 5466 continue; 5467 } 5468 final int versionCount = versionedLib.size(); 5469 for (int j = 0; j < versionCount; j++) { 5470 SharedLibraryInfo libraryInfo = versionedLib.valueAt(j); 5471 if (!libraryInfo.isStatic()) { 5472 if (libs == null) { 5473 libs = new ArraySet<>(); 5474 } 5475 libs.add(libraryInfo.getName()); 5476 break; 5477 } 5478 PackageSetting ps = mSettings.getPackageLPr(libraryInfo.getPackageName()); 5479 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5480 UserHandle.getUserId(Binder.getCallingUid()), 5481 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5482 if (libs == null) { 5483 libs = new ArraySet<>(); 5484 } 5485 libs.add(libraryInfo.getName()); 5486 break; 5487 } 5488 } 5489 } 5490 5491 if (libs != null) { 5492 String[] libsArray = new String[libs.size()]; 5493 libs.toArray(libsArray); 5494 return libsArray; 5495 } 5496 5497 return null; 5498 } 5499 } 5500 5501 @Override getServicesSystemSharedLibraryPackageName()5502 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5503 // allow instant applications 5504 synchronized (mPackages) { 5505 return mServicesSystemSharedLibraryPackageName; 5506 } 5507 } 5508 5509 @Override getSharedSystemSharedLibraryPackageName()5510 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5511 // allow instant applications 5512 synchronized (mPackages) { 5513 return mSharedSystemSharedLibraryPackageName; 5514 } 5515 } 5516 5517 @GuardedBy("mPackages") updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList)5518 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5519 for (int i = userList.length - 1; i >= 0; --i) { 5520 final int userId = userList[i]; 5521 // don't add instant app to the list of updates 5522 if (pkgSetting.getInstantApp(userId)) { 5523 continue; 5524 } 5525 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5526 if (changedPackages == null) { 5527 changedPackages = new SparseArray<>(); 5528 mChangedPackages.put(userId, changedPackages); 5529 } 5530 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5531 if (sequenceNumbers == null) { 5532 sequenceNumbers = new HashMap<>(); 5533 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5534 } 5535 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5536 if (sequenceNumber != null) { 5537 changedPackages.remove(sequenceNumber); 5538 } 5539 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5540 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5541 } 5542 mChangedPackagesSequenceNumber++; 5543 } 5544 5545 @Override getChangedPackages(int sequenceNumber, int userId)5546 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5547 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5548 return null; 5549 } 5550 synchronized (mPackages) { 5551 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5552 return null; 5553 } 5554 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5555 if (changedPackages == null) { 5556 return null; 5557 } 5558 final List<String> packageNames = 5559 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5560 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5561 final String packageName = changedPackages.get(i); 5562 if (packageName != null) { 5563 packageNames.add(packageName); 5564 } 5565 } 5566 return packageNames.isEmpty() 5567 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5568 } 5569 } 5570 5571 @Override getSystemAvailableFeatures()5572 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5573 // allow instant applications 5574 ArrayList<FeatureInfo> res; 5575 synchronized (mAvailableFeatures) { 5576 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5577 res.addAll(mAvailableFeatures.values()); 5578 } 5579 final FeatureInfo fi = new FeatureInfo(); 5580 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5581 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5582 res.add(fi); 5583 5584 return new ParceledListSlice<>(res); 5585 } 5586 5587 @Override hasSystemFeature(String name, int version)5588 public boolean hasSystemFeature(String name, int version) { 5589 // allow instant applications 5590 synchronized (mAvailableFeatures) { 5591 final FeatureInfo feat = mAvailableFeatures.get(name); 5592 if (feat == null) { 5593 return false; 5594 } else { 5595 return feat.version >= version; 5596 } 5597 } 5598 } 5599 5600 @Override checkPermission(String permName, String pkgName, int userId)5601 public int checkPermission(String permName, String pkgName, int userId) { 5602 final CheckPermissionDelegate checkPermissionDelegate; 5603 synchronized (mPackages) { 5604 if (mCheckPermissionDelegate == null) { 5605 return checkPermissionImpl(permName, pkgName, userId); 5606 } 5607 checkPermissionDelegate = mCheckPermissionDelegate; 5608 } 5609 return checkPermissionDelegate.checkPermission(permName, pkgName, userId, 5610 PackageManagerService.this::checkPermissionImpl); 5611 } 5612 checkPermissionImpl(String permName, String pkgName, int userId)5613 private int checkPermissionImpl(String permName, String pkgName, int userId) { 5614 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5615 } 5616 5617 @Override checkUidPermission(String permName, int uid)5618 public int checkUidPermission(String permName, int uid) { 5619 final CheckPermissionDelegate checkPermissionDelegate; 5620 synchronized (mPackages) { 5621 if (mCheckPermissionDelegate == null) { 5622 return checkUidPermissionImpl(permName, uid); 5623 } 5624 checkPermissionDelegate = mCheckPermissionDelegate; 5625 } 5626 return checkPermissionDelegate.checkUidPermission(permName, uid, 5627 PackageManagerService.this::checkUidPermissionImpl); 5628 } 5629 checkUidPermissionImpl(String permName, int uid)5630 private int checkUidPermissionImpl(String permName, int uid) { 5631 synchronized (mPackages) { 5632 final String[] packageNames = getPackagesForUid(uid); 5633 PackageParser.Package pkg = null; 5634 final int N = packageNames == null ? 0 : packageNames.length; 5635 for (int i = 0; pkg == null && i < N; i++) { 5636 pkg = mPackages.get(packageNames[i]); 5637 } 5638 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5639 } 5640 } 5641 5642 @Override isPermissionRevokedByPolicy(String permission, String packageName, int userId)5643 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5644 if (UserHandle.getCallingUserId() != userId) { 5645 mContext.enforceCallingPermission( 5646 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5647 "isPermissionRevokedByPolicy for user " + userId); 5648 } 5649 5650 if (checkPermission(permission, packageName, userId) 5651 == PackageManager.PERMISSION_GRANTED) { 5652 return false; 5653 } 5654 5655 final int callingUid = Binder.getCallingUid(); 5656 if (getInstantAppPackageName(callingUid) != null) { 5657 if (!isCallerSameApp(packageName, callingUid)) { 5658 return false; 5659 } 5660 } else { 5661 if (isInstantApp(packageName, userId)) { 5662 return false; 5663 } 5664 } 5665 5666 final long identity = Binder.clearCallingIdentity(); 5667 try { 5668 final int flags = getPermissionFlags(permission, packageName, userId); 5669 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5670 } finally { 5671 Binder.restoreCallingIdentity(identity); 5672 } 5673 } 5674 5675 @Override getPermissionControllerPackageName()5676 public String getPermissionControllerPackageName() { 5677 synchronized (mPackages) { 5678 return mRequiredPermissionControllerPackage; 5679 } 5680 } 5681 getPackageInstallerPackageName()5682 String getPackageInstallerPackageName() { 5683 synchronized (mPackages) { 5684 return mRequiredInstallerPackage; 5685 } 5686 } 5687 addDynamicPermission(PermissionInfo info, final boolean async)5688 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5689 return mPermissionManager.addDynamicPermission( 5690 info, async, getCallingUid(), new PermissionCallback() { 5691 @Override 5692 public void onPermissionChanged() { 5693 if (!async) { 5694 mSettings.writeLPr(); 5695 } else { 5696 scheduleWriteSettingsLocked(); 5697 } 5698 } 5699 }); 5700 } 5701 5702 @Override 5703 public boolean addPermission(PermissionInfo info) { 5704 synchronized (mPackages) { 5705 return addDynamicPermission(info, false); 5706 } 5707 } 5708 5709 @Override 5710 public boolean addPermissionAsync(PermissionInfo info) { 5711 synchronized (mPackages) { 5712 return addDynamicPermission(info, true); 5713 } 5714 } 5715 5716 @Override 5717 public void removePermission(String permName) { 5718 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5719 } 5720 5721 @Override 5722 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5723 boolean overridePolicy = (checkUidPermission( 5724 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid()) 5725 == PackageManager.PERMISSION_GRANTED); 5726 5727 mPermissionManager.grantRuntimePermission(permName, packageName, overridePolicy, 5728 getCallingUid(), userId, mPermissionCallback); 5729 } 5730 5731 @Override 5732 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5733 boolean overridePolicy = (checkUidPermission( 5734 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid()) 5735 == PackageManager.PERMISSION_GRANTED); 5736 5737 mPermissionManager.revokeRuntimePermission(permName, packageName, overridePolicy, 5738 userId, mPermissionCallback); 5739 } 5740 5741 @Override 5742 public void resetRuntimePermissions() { 5743 mContext.enforceCallingOrSelfPermission( 5744 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5745 "revokeRuntimePermission"); 5746 5747 int callingUid = Binder.getCallingUid(); 5748 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5749 mContext.enforceCallingOrSelfPermission( 5750 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5751 "resetRuntimePermissions"); 5752 } 5753 5754 synchronized (mPackages) { 5755 mPermissionManager.updateAllPermissions( 5756 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5757 mPermissionCallback); 5758 for (int userId : UserManagerService.getInstance().getUserIds()) { 5759 final int packageCount = mPackages.size(); 5760 for (int i = 0; i < packageCount; i++) { 5761 PackageParser.Package pkg = mPackages.valueAt(i); 5762 if (!(pkg.mExtras instanceof PackageSetting)) { 5763 continue; 5764 } 5765 PackageSetting ps = (PackageSetting) pkg.mExtras; 5766 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5767 } 5768 } 5769 } 5770 } 5771 5772 @Override 5773 public int getPermissionFlags(String permName, String packageName, int userId) { 5774 return mPermissionManager.getPermissionFlags( 5775 permName, packageName, getCallingUid(), userId); 5776 } 5777 5778 @Override 5779 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5780 int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) { 5781 int callingUid = getCallingUid(); 5782 boolean overridePolicy = false; 5783 5784 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 5785 long callingIdentity = Binder.clearCallingIdentity(); 5786 try { 5787 if ((flagMask & FLAG_PERMISSION_POLICY_FIXED) != 0) { 5788 if (checkAdjustPolicyFlagPermission) { 5789 mContext.enforceCallingOrSelfPermission( 5790 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 5791 "Need " + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY 5792 + " to change policy flags"); 5793 } else if (!hasTargetSdkInUidLowerThan(callingUid, Build.VERSION_CODES.Q)) { 5794 throw new IllegalArgumentException( 5795 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY + " needs " 5796 + " to be checked for packages targeting " 5797 + Build.VERSION_CODES.Q + " or later when changing policy " 5798 + "flags"); 5799 } 5800 5801 overridePolicy = true; 5802 } 5803 } finally { 5804 Binder.restoreCallingIdentity(callingIdentity); 5805 } 5806 } 5807 5808 mPermissionManager.updatePermissionFlags( 5809 permName, packageName, flagMask, flagValues, callingUid, userId, 5810 overridePolicy, mPermissionCallback); 5811 } 5812 5813 /** 5814 * Update the permission flags for all packages and runtime permissions of a user in order 5815 * to allow device or profile owner to remove POLICY_FIXED. 5816 */ 5817 @Override 5818 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5819 synchronized (mPackages) { 5820 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5821 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5822 mPermissionCallback); 5823 if (changed) { 5824 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5825 } 5826 } 5827 } 5828 5829 @Override 5830 public @Nullable List<String> getWhitelistedRestrictedPermissions(@NonNull String packageName, 5831 @PermissionWhitelistFlags int whitelistFlags, @UserIdInt int userId) { 5832 Preconditions.checkNotNull(packageName); 5833 Preconditions.checkFlagsArgument(whitelistFlags, 5834 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5835 | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM 5836 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER); 5837 Preconditions.checkArgumentNonNegative(userId, null); 5838 5839 if (UserHandle.getCallingUserId() != userId) { 5840 mContext.enforceCallingOrSelfPermission( 5841 android.Manifest.permission.INTERACT_ACROSS_USERS, 5842 "getWhitelistedRestrictedPermissions for user " + userId); 5843 } 5844 5845 final PackageParser.Package pkg; 5846 5847 synchronized (mPackages) { 5848 final PackageSetting packageSetting = mSettings.mPackages.get(packageName); 5849 if (packageSetting == null) { 5850 Slog.w(TAG, "Unknown package: " + packageName); 5851 return null; 5852 } 5853 5854 pkg = packageSetting.pkg; 5855 5856 final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission( 5857 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5858 == PackageManager.PERMISSION_GRANTED; 5859 final PackageSetting installerPackageSetting = mSettings.mPackages.get( 5860 packageSetting.installerPackageName); 5861 final boolean isCallerInstallerOnRecord = installerPackageSetting != null 5862 && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid()); 5863 5864 if ((whitelistFlags & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0 5865 && !isCallerPrivileged) { 5866 throw new SecurityException("Querying system whitelist requires " 5867 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5868 } 5869 5870 if ((whitelistFlags & (PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5871 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER)) != 0) { 5872 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 5873 throw new SecurityException("Querying upgrade or installer whitelist" 5874 + " requires being installer on record or " 5875 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5876 } 5877 } 5878 5879 if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(), 5880 UserHandle.getCallingUserId())) { 5881 return null; 5882 } 5883 } 5884 5885 final long identity = Binder.clearCallingIdentity(); 5886 try { 5887 return mPermissionManager.getWhitelistedRestrictedPermissions( 5888 pkg, whitelistFlags, userId); 5889 } finally { 5890 Binder.restoreCallingIdentity(identity); 5891 } 5892 } 5893 5894 @Override 5895 public boolean addWhitelistedRestrictedPermission(@NonNull String packageName, 5896 @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags, 5897 @UserIdInt int userId) { 5898 // Other argument checks are done in get/setWhitelistedRestrictedPermissions 5899 Preconditions.checkNotNull(permission); 5900 5901 if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) { 5902 return false; 5903 } 5904 5905 List<String> permissions = getWhitelistedRestrictedPermissions(packageName, 5906 whitelistFlags, userId); 5907 if (permissions == null) { 5908 permissions = new ArrayList<>(1); 5909 } 5910 if (permissions.indexOf(permission) < 0) { 5911 permissions.add(permission); 5912 return setWhitelistedRestrictedPermissions(packageName, permissions, 5913 whitelistFlags, userId); 5914 } 5915 return false; 5916 } 5917 5918 private boolean checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission( 5919 @NonNull String permission) { 5920 synchronized (mPackages) { 5921 final BasePermission bp = mPermissionManager.getPermissionTEMP(permission); 5922 if (bp == null) { 5923 Slog.w(TAG, "No such permissions: " + permission); 5924 return false; 5925 } 5926 if (bp.isHardOrSoftRestricted() && bp.isImmutablyRestricted() 5927 && mContext.checkCallingOrSelfPermission( 5928 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5929 != PackageManager.PERMISSION_GRANTED) { 5930 throw new SecurityException("Cannot modify whitelisting of an immutably " 5931 + "restricted permission: " + permission); 5932 } 5933 return true; 5934 } 5935 } 5936 5937 @Override 5938 public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName, 5939 @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags, 5940 @UserIdInt int userId) { 5941 // Other argument checks are done in get/setWhitelistedRestrictedPermissions 5942 Preconditions.checkNotNull(permission); 5943 5944 if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) { 5945 return false; 5946 } 5947 5948 final List<String> permissions = getWhitelistedRestrictedPermissions(packageName, 5949 whitelistFlags, userId); 5950 if (permissions != null && permissions.remove(permission)) { 5951 return setWhitelistedRestrictedPermissions(packageName, permissions, 5952 whitelistFlags, userId); 5953 } 5954 return false; 5955 } 5956 5957 private boolean setWhitelistedRestrictedPermissions(@NonNull String packageName, 5958 @Nullable List<String> permissions, @PermissionWhitelistFlags int whitelistFlag, 5959 @UserIdInt int userId) { 5960 Preconditions.checkNotNull(packageName); 5961 Preconditions.checkFlagsArgument(whitelistFlag, 5962 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5963 | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM 5964 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER); 5965 Preconditions.checkArgument(Integer.bitCount(whitelistFlag) == 1); 5966 Preconditions.checkArgumentNonNegative(userId, null); 5967 5968 if (UserHandle.getCallingUserId() != userId) { 5969 mContext.enforceCallingOrSelfPermission( 5970 Manifest.permission.INTERACT_ACROSS_USERS, 5971 "setWhitelistedRestrictedPermissions for user " + userId); 5972 } 5973 5974 final PackageParser.Package pkg; 5975 5976 synchronized (mPackages) { 5977 final PackageSetting packageSetting = mSettings.mPackages.get(packageName); 5978 if (packageSetting == null) { 5979 Slog.w(TAG, "Unknown package: " + packageName); 5980 return false; 5981 } 5982 5983 pkg = packageSetting.pkg; 5984 5985 final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission( 5986 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5987 == PackageManager.PERMISSION_GRANTED; 5988 final PackageSetting installerPackageSetting = mSettings.mPackages.get( 5989 packageSetting.installerPackageName); 5990 final boolean isCallerInstallerOnRecord = installerPackageSetting != null 5991 && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid()); 5992 5993 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0 5994 && !isCallerPrivileged) { 5995 throw new SecurityException("Modifying system whitelist requires " 5996 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5997 } 5998 5999 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE) != 0) { 6000 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 6001 throw new SecurityException("Modifying upgrade whitelist requires" 6002 + " being installer on record or " 6003 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 6004 } 6005 final List<String> whitelistedPermissions = getWhitelistedRestrictedPermissions( 6006 packageName, whitelistFlag, userId); 6007 if (permissions == null || permissions.isEmpty()) { 6008 if (whitelistedPermissions == null || whitelistedPermissions.isEmpty()) { 6009 return true; 6010 } 6011 } else { 6012 // Only the system can add and remove while the installer can only remove. 6013 final int permissionCount = permissions.size(); 6014 for (int i = 0; i < permissionCount; i++) { 6015 if ((whitelistedPermissions == null 6016 || !whitelistedPermissions.contains(permissions.get(i))) 6017 && !isCallerPrivileged) { 6018 throw new SecurityException("Adding to upgrade whitelist requires" 6019 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 6020 } 6021 } 6022 } 6023 } 6024 6025 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER) != 0) { 6026 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 6027 throw new SecurityException("Modifying installer whitelist requires" 6028 + " being installer on record or " 6029 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 6030 } 6031 } 6032 6033 if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(), 6034 UserHandle.getCallingUserId())) { 6035 return false; 6036 } 6037 } 6038 6039 final long identity = Binder.clearCallingIdentity(); 6040 try { 6041 mPermissionManager.setWhitelistedRestrictedPermissions(pkg, 6042 new int[]{userId}, permissions, Process.myUid(), whitelistFlag, 6043 mPermissionCallback); 6044 } finally { 6045 Binder.restoreCallingIdentity(identity); 6046 } 6047 6048 return true; 6049 } 6050 6051 @Override 6052 public boolean shouldShowRequestPermissionRationale(String permissionName, 6053 String packageName, int userId) { 6054 if (UserHandle.getCallingUserId() != userId) { 6055 mContext.enforceCallingPermission( 6056 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 6057 "canShowRequestPermissionRationale for user " + userId); 6058 } 6059 6060 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 6061 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 6062 return false; 6063 } 6064 6065 if (checkPermission(permissionName, packageName, userId) 6066 == PackageManager.PERMISSION_GRANTED) { 6067 return false; 6068 } 6069 6070 final int flags; 6071 6072 final long identity = Binder.clearCallingIdentity(); 6073 try { 6074 flags = getPermissionFlags(permissionName, 6075 packageName, userId); 6076 } finally { 6077 Binder.restoreCallingIdentity(identity); 6078 } 6079 6080 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 6081 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 6082 | PackageManager.FLAG_PERMISSION_USER_FIXED; 6083 6084 if ((flags & fixedFlags) != 0) { 6085 return false; 6086 } 6087 6088 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 6089 } 6090 6091 @Override 6092 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6093 mContext.enforceCallingOrSelfPermission( 6094 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 6095 "addOnPermissionsChangeListener"); 6096 6097 synchronized (mPackages) { 6098 mOnPermissionChangeListeners.addListenerLocked(listener); 6099 } 6100 } 6101 6102 @Override 6103 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6104 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6105 throw new SecurityException("Instant applications don't have access to this method"); 6106 } 6107 synchronized (mPackages) { 6108 mOnPermissionChangeListeners.removeListenerLocked(listener); 6109 } 6110 } 6111 6112 @Override 6113 public boolean isProtectedBroadcast(String actionName) { 6114 // allow instant applications 6115 synchronized (mProtectedBroadcasts) { 6116 if (mProtectedBroadcasts.contains(actionName)) { 6117 return true; 6118 } else if (actionName != null) { 6119 // TODO: remove these terrible hacks 6120 if (actionName.startsWith("android.net.netmon.lingerExpired") 6121 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 6122 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 6123 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 6124 return true; 6125 } 6126 } 6127 } 6128 return false; 6129 } 6130 6131 @Override 6132 public int checkSignatures(String pkg1, String pkg2) { 6133 synchronized (mPackages) { 6134 final PackageParser.Package p1 = mPackages.get(pkg1); 6135 final PackageParser.Package p2 = mPackages.get(pkg2); 6136 if (p1 == null || p1.mExtras == null 6137 || p2 == null || p2.mExtras == null) { 6138 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6139 } 6140 final int callingUid = Binder.getCallingUid(); 6141 final int callingUserId = UserHandle.getUserId(callingUid); 6142 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 6143 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 6144 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 6145 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 6146 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6147 } 6148 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 6149 } 6150 } 6151 6152 @Override 6153 public int checkUidSignatures(int uid1, int uid2) { 6154 final int callingUid = Binder.getCallingUid(); 6155 final int callingUserId = UserHandle.getUserId(callingUid); 6156 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6157 // Map to base uids. 6158 final int appId1 = UserHandle.getAppId(uid1); 6159 final int appId2 = UserHandle.getAppId(uid2); 6160 // reader 6161 synchronized (mPackages) { 6162 Signature[] s1; 6163 Signature[] s2; 6164 Object obj = mSettings.getSettingLPr(appId1); 6165 if (obj != null) { 6166 if (obj instanceof SharedUserSetting) { 6167 if (isCallerInstantApp) { 6168 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6169 } 6170 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 6171 } else if (obj instanceof PackageSetting) { 6172 final PackageSetting ps = (PackageSetting) obj; 6173 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6174 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6175 } 6176 s1 = ps.signatures.mSigningDetails.signatures; 6177 } else { 6178 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6179 } 6180 } else { 6181 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6182 } 6183 obj = mSettings.getSettingLPr(appId2); 6184 if (obj != null) { 6185 if (obj instanceof SharedUserSetting) { 6186 if (isCallerInstantApp) { 6187 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6188 } 6189 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 6190 } else if (obj instanceof PackageSetting) { 6191 final PackageSetting ps = (PackageSetting) obj; 6192 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6193 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6194 } 6195 s2 = ps.signatures.mSigningDetails.signatures; 6196 } else { 6197 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6198 } 6199 } else { 6200 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6201 } 6202 return compareSignatures(s1, s2); 6203 } 6204 } 6205 6206 @Override 6207 public boolean hasSigningCertificate( 6208 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 6209 6210 synchronized (mPackages) { 6211 final PackageParser.Package p = mPackages.get(packageName); 6212 if (p == null || p.mExtras == null) { 6213 return false; 6214 } 6215 final int callingUid = Binder.getCallingUid(); 6216 final int callingUserId = UserHandle.getUserId(callingUid); 6217 final PackageSetting ps = (PackageSetting) p.mExtras; 6218 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6219 return false; 6220 } 6221 switch (type) { 6222 case CERT_INPUT_RAW_X509: 6223 return p.mSigningDetails.hasCertificate(certificate); 6224 case CERT_INPUT_SHA256: 6225 return p.mSigningDetails.hasSha256Certificate(certificate); 6226 default: 6227 return false; 6228 } 6229 } 6230 } 6231 6232 @Override 6233 public boolean hasUidSigningCertificate( 6234 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 6235 final int callingUid = Binder.getCallingUid(); 6236 final int callingUserId = UserHandle.getUserId(callingUid); 6237 // Map to base uids. 6238 final int appId = UserHandle.getAppId(uid); 6239 // reader 6240 synchronized (mPackages) { 6241 final PackageParser.SigningDetails signingDetails; 6242 final Object obj = mSettings.getSettingLPr(appId); 6243 if (obj != null) { 6244 if (obj instanceof SharedUserSetting) { 6245 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6246 if (isCallerInstantApp) { 6247 return false; 6248 } 6249 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 6250 } else if (obj instanceof PackageSetting) { 6251 final PackageSetting ps = (PackageSetting) obj; 6252 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6253 return false; 6254 } 6255 signingDetails = ps.signatures.mSigningDetails; 6256 } else { 6257 return false; 6258 } 6259 } else { 6260 return false; 6261 } 6262 switch (type) { 6263 case CERT_INPUT_RAW_X509: 6264 return signingDetails.hasCertificate(certificate); 6265 case CERT_INPUT_SHA256: 6266 return signingDetails.hasSha256Certificate(certificate); 6267 default: 6268 return false; 6269 } 6270 } 6271 } 6272 6273 /** 6274 * This method should typically only be used when granting or revoking 6275 * permissions, since the app may immediately restart after this call. 6276 * <p> 6277 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 6278 * guard your work against the app being relaunched. 6279 */ 6280 private void killUid(int appId, int userId, String reason) { 6281 final long identity = Binder.clearCallingIdentity(); 6282 try { 6283 IActivityManager am = ActivityManager.getService(); 6284 if (am != null) { 6285 try { 6286 am.killUid(appId, userId, reason); 6287 } catch (RemoteException e) { 6288 /* ignore - same process */ 6289 } 6290 } 6291 } finally { 6292 Binder.restoreCallingIdentity(identity); 6293 } 6294 } 6295 6296 /** 6297 * If the database version for this type of package (internal storage or 6298 * external storage) is less than the version where package signatures 6299 * were updated, return true. 6300 */ 6301 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6302 return isCompatSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg)); 6303 } 6304 6305 private static boolean isCompatSignatureUpdateNeeded(VersionInfo ver) { 6306 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 6307 } 6308 6309 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6310 return isRecoverSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg)); 6311 } 6312 6313 private static boolean isRecoverSignatureUpdateNeeded(VersionInfo ver) { 6314 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 6315 } 6316 6317 @Override 6318 public List<String> getAllPackages() { 6319 final int callingUid = Binder.getCallingUid(); 6320 final int callingUserId = UserHandle.getUserId(callingUid); 6321 synchronized (mPackages) { 6322 if (canViewInstantApps(callingUid, callingUserId)) { 6323 return new ArrayList<>(mPackages.keySet()); 6324 } 6325 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6326 final List<String> result = new ArrayList<>(); 6327 if (instantAppPkgName != null) { 6328 // caller is an instant application; filter unexposed applications 6329 for (PackageParser.Package pkg : mPackages.values()) { 6330 if (!pkg.visibleToInstantApps) { 6331 continue; 6332 } 6333 result.add(pkg.packageName); 6334 } 6335 } else { 6336 // caller is a normal application; filter instant applications 6337 for (PackageParser.Package pkg : mPackages.values()) { 6338 final PackageSetting ps = 6339 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 6340 if (ps != null 6341 && ps.getInstantApp(callingUserId) 6342 && !mInstantAppRegistry.isInstantAccessGranted( 6343 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 6344 continue; 6345 } 6346 result.add(pkg.packageName); 6347 } 6348 } 6349 return result; 6350 } 6351 } 6352 6353 /** 6354 * <em>IMPORTANT:</em> Not all packages returned by this method may be known 6355 * to the system. There are two conditions in which this may occur: 6356 * <ol> 6357 * <li>The package is on adoptable storage and the device has been removed</li> 6358 * <li>The package is being removed and the internal structures are partially updated</li> 6359 * </ol> 6360 * The second is an artifact of the current data structures and should be fixed. See 6361 * b/111075456 for one such instance. 6362 */ 6363 @Override 6364 public String[] getPackagesForUid(int uid) { 6365 final int callingUid = Binder.getCallingUid(); 6366 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6367 final int userId = UserHandle.getUserId(uid); 6368 final int appId = UserHandle.getAppId(uid); 6369 // reader 6370 synchronized (mPackages) { 6371 final Object obj = mSettings.getSettingLPr(appId); 6372 if (obj instanceof SharedUserSetting) { 6373 if (isCallerInstantApp) { 6374 return null; 6375 } 6376 final SharedUserSetting sus = (SharedUserSetting) obj; 6377 final int N = sus.packages.size(); 6378 String[] res = new String[N]; 6379 final Iterator<PackageSetting> it = sus.packages.iterator(); 6380 int i = 0; 6381 while (it.hasNext()) { 6382 PackageSetting ps = it.next(); 6383 if (ps.getInstalled(userId)) { 6384 res[i++] = ps.name; 6385 } else { 6386 res = ArrayUtils.removeElement(String.class, res, res[i]); 6387 } 6388 } 6389 return res; 6390 } else if (obj instanceof PackageSetting) { 6391 final PackageSetting ps = (PackageSetting) obj; 6392 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6393 return new String[]{ps.name}; 6394 } 6395 } 6396 } 6397 return null; 6398 } 6399 6400 @Override 6401 public String getNameForUid(int uid) { 6402 final int callingUid = Binder.getCallingUid(); 6403 if (getInstantAppPackageName(callingUid) != null) { 6404 return null; 6405 } 6406 final int appId = UserHandle.getAppId(uid); 6407 synchronized (mPackages) { 6408 final Object obj = mSettings.getSettingLPr(appId); 6409 if (obj instanceof SharedUserSetting) { 6410 final SharedUserSetting sus = (SharedUserSetting) obj; 6411 return sus.name + ":" + sus.userId; 6412 } else if (obj instanceof PackageSetting) { 6413 final PackageSetting ps = (PackageSetting) obj; 6414 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6415 return null; 6416 } 6417 return ps.name; 6418 } 6419 return null; 6420 } 6421 } 6422 6423 @Override 6424 public String[] getNamesForUids(int[] uids) { 6425 if (uids == null || uids.length == 0) { 6426 return null; 6427 } 6428 final int callingUid = Binder.getCallingUid(); 6429 if (getInstantAppPackageName(callingUid) != null) { 6430 return null; 6431 } 6432 final String[] names = new String[uids.length]; 6433 synchronized (mPackages) { 6434 for (int i = uids.length - 1; i >= 0; i--) { 6435 final int appId = UserHandle.getAppId(uids[i]); 6436 final Object obj = mSettings.getSettingLPr(appId); 6437 if (obj instanceof SharedUserSetting) { 6438 final SharedUserSetting sus = (SharedUserSetting) obj; 6439 names[i] = "shared:" + sus.name; 6440 } else if (obj instanceof PackageSetting) { 6441 final PackageSetting ps = (PackageSetting) obj; 6442 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6443 names[i] = null; 6444 } else { 6445 names[i] = ps.name; 6446 } 6447 } else { 6448 names[i] = null; 6449 } 6450 } 6451 } 6452 return names; 6453 } 6454 6455 @Override 6456 public int getUidForSharedUser(String sharedUserName) { 6457 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6458 return -1; 6459 } 6460 if (sharedUserName == null) { 6461 return -1; 6462 } 6463 // reader 6464 synchronized (mPackages) { 6465 SharedUserSetting suid; 6466 try { 6467 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6468 if (suid != null) { 6469 return suid.userId; 6470 } 6471 } catch (PackageManagerException ignore) { 6472 // can't happen, but, still need to catch it 6473 } 6474 return -1; 6475 } 6476 } 6477 6478 @Override 6479 public int getFlagsForUid(int uid) { 6480 final int callingUid = Binder.getCallingUid(); 6481 if (getInstantAppPackageName(callingUid) != null) { 6482 return 0; 6483 } 6484 final int appId = UserHandle.getAppId(uid); 6485 synchronized (mPackages) { 6486 final Object obj = mSettings.getSettingLPr(appId); 6487 if (obj instanceof SharedUserSetting) { 6488 final SharedUserSetting sus = (SharedUserSetting) obj; 6489 return sus.pkgFlags; 6490 } else if (obj instanceof PackageSetting) { 6491 final PackageSetting ps = (PackageSetting) obj; 6492 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6493 return 0; 6494 } 6495 return ps.pkgFlags; 6496 } 6497 } 6498 return 0; 6499 } 6500 6501 @Override 6502 public int getPrivateFlagsForUid(int uid) { 6503 final int callingUid = Binder.getCallingUid(); 6504 if (getInstantAppPackageName(callingUid) != null) { 6505 return 0; 6506 } 6507 final int appId = UserHandle.getAppId(uid); 6508 synchronized (mPackages) { 6509 final Object obj = mSettings.getSettingLPr(appId); 6510 if (obj instanceof SharedUserSetting) { 6511 final SharedUserSetting sus = (SharedUserSetting) obj; 6512 return sus.pkgPrivateFlags; 6513 } else if (obj instanceof PackageSetting) { 6514 final PackageSetting ps = (PackageSetting) obj; 6515 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6516 return 0; 6517 } 6518 return ps.pkgPrivateFlags; 6519 } 6520 } 6521 return 0; 6522 } 6523 6524 @Override 6525 public boolean isUidPrivileged(int uid) { 6526 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6527 return false; 6528 } 6529 final int appId = UserHandle.getAppId(uid); 6530 // reader 6531 synchronized (mPackages) { 6532 final Object obj = mSettings.getSettingLPr(appId); 6533 if (obj instanceof SharedUserSetting) { 6534 final SharedUserSetting sus = (SharedUserSetting) obj; 6535 final Iterator<PackageSetting> it = sus.packages.iterator(); 6536 while (it.hasNext()) { 6537 if (it.next().isPrivileged()) { 6538 return true; 6539 } 6540 } 6541 } else if (obj instanceof PackageSetting) { 6542 final PackageSetting ps = (PackageSetting) obj; 6543 return ps.isPrivileged(); 6544 } 6545 } 6546 return false; 6547 } 6548 6549 @Override 6550 public String[] getAppOpPermissionPackages(String permName) { 6551 return mPermissionManager.getAppOpPermissionPackages(permName); 6552 } 6553 6554 @Override 6555 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6556 int flags, int userId) { 6557 return resolveIntentInternal(intent, resolvedType, flags, userId, false, 6558 Binder.getCallingUid()); 6559 } 6560 6561 /** 6562 * Normally instant apps can only be resolved when they're visible to the caller. 6563 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 6564 * since we need to allow the system to start any installed application. 6565 */ 6566 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6567 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 6568 try { 6569 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6570 6571 if (!sUserManager.exists(userId)) return null; 6572 final int callingUid = Binder.getCallingUid(); 6573 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart); 6574 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 6575 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6576 6577 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6578 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6579 flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 6580 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6581 6582 final ResolveInfo bestChoice = 6583 chooseBestActivity(intent, resolvedType, flags, query, userId); 6584 return bestChoice; 6585 } finally { 6586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6587 } 6588 } 6589 6590 @Override 6591 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6592 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6593 throw new SecurityException( 6594 "findPersistentPreferredActivity can only be run by the system"); 6595 } 6596 if (!sUserManager.exists(userId)) { 6597 return null; 6598 } 6599 final int callingUid = Binder.getCallingUid(); 6600 intent = updateIntentForResolve(intent); 6601 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6602 final int flags = updateFlagsForResolve( 6603 0, userId, intent, callingUid, false /*includeInstantApps*/); 6604 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6605 userId); 6606 synchronized (mPackages) { 6607 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6608 userId); 6609 } 6610 } 6611 6612 @Override 6613 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6614 IntentFilter filter, int match, ComponentName activity) { 6615 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6616 return; 6617 } 6618 final int userId = UserHandle.getCallingUserId(); 6619 if (DEBUG_PREFERRED) { 6620 Log.v(TAG, "setLastChosenActivity intent=" + intent 6621 + " resolvedType=" + resolvedType 6622 + " flags=" + flags 6623 + " filter=" + filter 6624 + " match=" + match 6625 + " activity=" + activity); 6626 filter.dump(new PrintStreamPrinter(System.out), " "); 6627 } 6628 intent.setComponent(null); 6629 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6630 userId); 6631 // Find any earlier preferred or last chosen entries and nuke them 6632 findPreferredActivityNotLocked( 6633 intent, resolvedType, flags, query, 0, false, true, false, userId); 6634 // Add the new activity as the last chosen for this filter 6635 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6636 "Setting last chosen"); 6637 } 6638 6639 @Override 6640 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6641 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6642 return null; 6643 } 6644 final int userId = UserHandle.getCallingUserId(); 6645 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6646 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6647 userId); 6648 return findPreferredActivityNotLocked( 6649 intent, resolvedType, flags, query, 0, false, false, false, userId); 6650 } 6651 6652 /** 6653 * Returns whether or not instant apps have been disabled remotely. 6654 */ 6655 private boolean areWebInstantAppsDisabled(int userId) { 6656 return mWebInstantAppsDisabled.get(userId); 6657 } 6658 6659 private boolean isInstantAppResolutionAllowed( 6660 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6661 boolean skipPackageCheck) { 6662 if (mInstantAppResolverConnection == null) { 6663 return false; 6664 } 6665 if (mInstantAppInstallerActivity == null) { 6666 return false; 6667 } 6668 if (intent.getComponent() != null) { 6669 return false; 6670 } 6671 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6672 return false; 6673 } 6674 if (!skipPackageCheck && intent.getPackage() != null) { 6675 return false; 6676 } 6677 if (!intent.isWebIntent()) { 6678 // for non web intents, we should not resolve externally if an app already exists to 6679 // handle it or if the caller didn't explicitly request it. 6680 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6681 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6682 return false; 6683 } 6684 } else { 6685 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6686 return false; 6687 } else if (areWebInstantAppsDisabled(userId)) { 6688 return false; 6689 } 6690 } 6691 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6692 // Or if there's already an ephemeral app installed that handles the action 6693 synchronized (mPackages) { 6694 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6695 for (int n = 0; n < count; n++) { 6696 final ResolveInfo info = resolvedActivities.get(n); 6697 final String packageName = info.activityInfo.packageName; 6698 final PackageSetting ps = mSettings.mPackages.get(packageName); 6699 if (ps != null) { 6700 // only check domain verification status if the app is not a browser 6701 if (!info.handleAllWebDataURI) { 6702 // Try to get the status from User settings first 6703 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6704 final int status = (int) (packedStatus >> 32); 6705 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6706 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6707 if (DEBUG_INSTANT) { 6708 Slog.v(TAG, "DENY instant app;" 6709 + " pkg: " + packageName + ", status: " + status); 6710 } 6711 return false; 6712 } 6713 } 6714 if (ps.getInstantApp(userId)) { 6715 if (DEBUG_INSTANT) { 6716 Slog.v(TAG, "DENY instant app installed;" 6717 + " pkg: " + packageName); 6718 } 6719 return false; 6720 } 6721 } 6722 } 6723 } 6724 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6725 return true; 6726 } 6727 6728 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6729 Intent origIntent, String resolvedType, String callingPackage, 6730 Bundle verificationBundle, int userId) { 6731 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6732 new InstantAppRequest(responseObj, origIntent, resolvedType, 6733 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6734 mHandler.sendMessage(msg); 6735 } 6736 6737 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6738 int flags, List<ResolveInfo> query, int userId) { 6739 if (query != null) { 6740 final int N = query.size(); 6741 if (N == 1) { 6742 return query.get(0); 6743 } else if (N > 1) { 6744 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6745 // If there is more than one activity with the same priority, 6746 // then let the user decide between them. 6747 ResolveInfo r0 = query.get(0); 6748 ResolveInfo r1 = query.get(1); 6749 if (DEBUG_INTENT_MATCHING || debug) { 6750 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6751 + r1.activityInfo.name + "=" + r1.priority); 6752 } 6753 // If the first activity has a higher priority, or a different 6754 // default, then it is always desirable to pick it. 6755 if (r0.priority != r1.priority 6756 || r0.preferredOrder != r1.preferredOrder 6757 || r0.isDefault != r1.isDefault) { 6758 return query.get(0); 6759 } 6760 // If we have saved a preference for a preferred activity for 6761 // this Intent, use that. 6762 ResolveInfo ri = findPreferredActivityNotLocked(intent, resolvedType, 6763 flags, query, r0.priority, true, false, debug, userId); 6764 if (ri != null) { 6765 return ri; 6766 } 6767 // If we have an ephemeral app, use it 6768 for (int i = 0; i < N; i++) { 6769 ri = query.get(i); 6770 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6771 final String packageName = ri.activityInfo.packageName; 6772 final PackageSetting ps = mSettings.mPackages.get(packageName); 6773 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6774 final int status = (int)(packedStatus >> 32); 6775 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6776 return ri; 6777 } 6778 } 6779 } 6780 ri = new ResolveInfo(mResolveInfo); 6781 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6782 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6783 // If all of the options come from the same package, show the application's 6784 // label and icon instead of the generic resolver's. 6785 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6786 // and then throw away the ResolveInfo itself, meaning that the caller loses 6787 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6788 // a fallback for this case; we only set the target package's resources on 6789 // the ResolveInfo, not the ActivityInfo. 6790 final String intentPackage = intent.getPackage(); 6791 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6792 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6793 ri.resolvePackageName = intentPackage; 6794 if (userNeedsBadging(userId)) { 6795 ri.noResourceId = true; 6796 } else { 6797 ri.icon = appi.icon; 6798 } 6799 ri.iconResourceId = appi.icon; 6800 ri.labelRes = appi.labelRes; 6801 } 6802 ri.activityInfo.applicationInfo = new ApplicationInfo( 6803 ri.activityInfo.applicationInfo); 6804 if (userId != 0) { 6805 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6806 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6807 } 6808 // Make sure that the resolver is displayable in car mode 6809 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6810 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6811 return ri; 6812 } 6813 } 6814 return null; 6815 } 6816 6817 /** 6818 * Return true if the given list is not empty and all of its contents have 6819 * an activityInfo with the given package name. 6820 */ 6821 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6822 if (ArrayUtils.isEmpty(list)) { 6823 return false; 6824 } 6825 for (int i = 0, N = list.size(); i < N; i++) { 6826 final ResolveInfo ri = list.get(i); 6827 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6828 if (ai == null || !packageName.equals(ai.packageName)) { 6829 return false; 6830 } 6831 } 6832 return true; 6833 } 6834 6835 @GuardedBy("mPackages") 6836 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6837 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6838 final int N = query.size(); 6839 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6840 .get(userId); 6841 // Get the list of persistent preferred activities that handle the intent 6842 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6843 List<PersistentPreferredActivity> pprefs = ppir != null 6844 ? ppir.queryIntent(intent, resolvedType, 6845 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6846 userId) 6847 : null; 6848 if (pprefs != null && pprefs.size() > 0) { 6849 final int M = pprefs.size(); 6850 for (int i=0; i<M; i++) { 6851 final PersistentPreferredActivity ppa = pprefs.get(i); 6852 if (DEBUG_PREFERRED || debug) { 6853 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6854 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6855 + "\n component=" + ppa.mComponent); 6856 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6857 } 6858 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6859 flags | MATCH_DISABLED_COMPONENTS, userId); 6860 if (DEBUG_PREFERRED || debug) { 6861 Slog.v(TAG, "Found persistent preferred activity:"); 6862 if (ai != null) { 6863 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6864 } else { 6865 Slog.v(TAG, " null"); 6866 } 6867 } 6868 if (ai == null) { 6869 // This previously registered persistent preferred activity 6870 // component is no longer known. Ignore it and do NOT remove it. 6871 continue; 6872 } 6873 for (int j=0; j<N; j++) { 6874 final ResolveInfo ri = query.get(j); 6875 if (!ri.activityInfo.applicationInfo.packageName 6876 .equals(ai.applicationInfo.packageName)) { 6877 continue; 6878 } 6879 if (!ri.activityInfo.name.equals(ai.name)) { 6880 continue; 6881 } 6882 // Found a persistent preference that can handle the intent. 6883 if (DEBUG_PREFERRED || debug) { 6884 Slog.v(TAG, "Returning persistent preferred activity: " + 6885 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6886 } 6887 return ri; 6888 } 6889 } 6890 } 6891 return null; 6892 } 6893 6894 private boolean isHomeIntent(Intent intent) { 6895 return ACTION_MAIN.equals(intent.getAction()) 6896 && intent.hasCategory(CATEGORY_HOME) 6897 && intent.hasCategory(CATEGORY_DEFAULT); 6898 } 6899 6900 // TODO: handle preferred activities missing while user has amnesia 6901 /** <b>must not hold {@link #mPackages}</b> */ 6902 ResolveInfo findPreferredActivityNotLocked(Intent intent, String resolvedType, int flags, 6903 List<ResolveInfo> query, int priority, boolean always, 6904 boolean removeMatches, boolean debug, int userId) { 6905 if (Thread.holdsLock(mPackages)) { 6906 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 6907 + " is holding mPackages", new Throwable()); 6908 } 6909 if (!sUserManager.exists(userId)) return null; 6910 final int callingUid = Binder.getCallingUid(); 6911 // Do NOT hold the packages lock; this calls up into the settings provider which 6912 // could cause a deadlock. 6913 final boolean isDeviceProvisioned = 6914 android.provider.Settings.Global.getInt(mContext.getContentResolver(), 6915 android.provider.Settings.Global.DEVICE_PROVISIONED, 0) == 1; 6916 flags = updateFlagsForResolve( 6917 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6918 intent = updateIntentForResolve(intent); 6919 // writer 6920 synchronized (mPackages) { 6921 // Try to find a matching persistent preferred activity. 6922 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6923 debug, userId); 6924 6925 // If a persistent preferred activity matched, use it. 6926 if (pri != null) { 6927 return pri; 6928 } 6929 6930 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6931 // Get the list of preferred activities that handle the intent 6932 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6933 List<PreferredActivity> prefs = pir != null 6934 ? pir.queryIntent(intent, resolvedType, 6935 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6936 userId) 6937 : null; 6938 if (prefs != null && prefs.size() > 0) { 6939 boolean changed = false; 6940 try { 6941 // First figure out how good the original match set is. 6942 // We will only allow preferred activities that came 6943 // from the same match quality. 6944 int match = 0; 6945 6946 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6947 6948 final int N = query.size(); 6949 for (int j=0; j<N; j++) { 6950 final ResolveInfo ri = query.get(j); 6951 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6952 + ": 0x" + Integer.toHexString(match)); 6953 if (ri.match > match) { 6954 match = ri.match; 6955 } 6956 } 6957 6958 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6959 + Integer.toHexString(match)); 6960 6961 match &= IntentFilter.MATCH_CATEGORY_MASK; 6962 final int M = prefs.size(); 6963 for (int i=0; i<M; i++) { 6964 final PreferredActivity pa = prefs.get(i); 6965 if (DEBUG_PREFERRED || debug) { 6966 Slog.v(TAG, "Checking PreferredActivity ds=" 6967 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6968 + "\n component=" + pa.mPref.mComponent); 6969 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6970 } 6971 if (pa.mPref.mMatch != match) { 6972 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6973 + Integer.toHexString(pa.mPref.mMatch)); 6974 continue; 6975 } 6976 // If it's not an "always" type preferred activity and that's what we're 6977 // looking for, skip it. 6978 if (always && !pa.mPref.mAlways) { 6979 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6980 continue; 6981 } 6982 final ActivityInfo ai = getActivityInfo( 6983 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6984 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6985 userId); 6986 if (DEBUG_PREFERRED || debug) { 6987 Slog.v(TAG, "Found preferred activity:"); 6988 if (ai != null) { 6989 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6990 } else { 6991 Slog.v(TAG, " null"); 6992 } 6993 } 6994 final boolean excludeSetupWizardHomeActivity = isHomeIntent(intent) 6995 && !isDeviceProvisioned; 6996 if (ai == null) { 6997 // Do not remove launcher's preferred activity during SetupWizard 6998 // due to it may not install yet 6999 if (excludeSetupWizardHomeActivity) { 7000 continue; 7001 } 7002 7003 // This previously registered preferred activity 7004 // component is no longer known. Most likely an update 7005 // to the app was installed and in the new version this 7006 // component no longer exists. Clean it up by removing 7007 // it from the preferred activities list, and skip it. 7008 Slog.w(TAG, "Removing dangling preferred activity: " 7009 + pa.mPref.mComponent); 7010 pir.removeFilter(pa); 7011 changed = true; 7012 continue; 7013 } 7014 for (int j=0; j<N; j++) { 7015 final ResolveInfo ri = query.get(j); 7016 if (!ri.activityInfo.applicationInfo.packageName 7017 .equals(ai.applicationInfo.packageName)) { 7018 continue; 7019 } 7020 if (!ri.activityInfo.name.equals(ai.name)) { 7021 continue; 7022 } 7023 7024 if (removeMatches) { 7025 pir.removeFilter(pa); 7026 changed = true; 7027 if (DEBUG_PREFERRED) { 7028 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 7029 } 7030 break; 7031 } 7032 7033 // Okay we found a previously set preferred or last chosen app. 7034 // If the result set is different from when this 7035 // was created, and is not a subset of the preferred set, we need to 7036 // clear it and re-ask the user their preference, if we're looking for 7037 // an "always" type entry. 7038 7039 if (always && !pa.mPref.sameSet(query, excludeSetupWizardHomeActivity)) { 7040 if (pa.mPref.isSuperset(query, excludeSetupWizardHomeActivity)) { 7041 if (!excludeSetupWizardHomeActivity) { 7042 // some components of the set are no longer present in 7043 // the query, but the preferred activity can still be reused 7044 if (DEBUG_PREFERRED) { 7045 Slog.i(TAG, "Result set changed, but PreferredActivity" 7046 + " is still valid as only non-preferred" 7047 + " components were removed for " + intent 7048 + " type " + resolvedType); 7049 } 7050 // remove obsolete components and re-add the up-to-date 7051 // filter 7052 PreferredActivity freshPa = new PreferredActivity(pa, 7053 pa.mPref.mMatch, 7054 pa.mPref.discardObsoleteComponents(query), 7055 pa.mPref.mComponent, 7056 pa.mPref.mAlways); 7057 pir.removeFilter(pa); 7058 pir.addFilter(freshPa); 7059 changed = true; 7060 } else { 7061 if (DEBUG_PREFERRED) { 7062 Slog.i(TAG, "Do not remove preferred activity for launcher" 7063 + " during SetupWizard"); 7064 } 7065 } 7066 } else { 7067 Slog.i(TAG, 7068 "Result set changed, dropping preferred activity for " 7069 + intent + " type " + resolvedType); 7070 if (DEBUG_PREFERRED) { 7071 Slog.v(TAG, "Removing preferred activity since set changed " 7072 + pa.mPref.mComponent); 7073 } 7074 pir.removeFilter(pa); 7075 // Re-add the filter as a "last chosen" entry (!always) 7076 PreferredActivity lastChosen = new PreferredActivity( 7077 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 7078 pir.addFilter(lastChosen); 7079 changed = true; 7080 return null; 7081 } 7082 } 7083 7084 // Yay! Either the set matched or we're looking for the last chosen 7085 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 7086 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 7087 return ri; 7088 } 7089 } 7090 } finally { 7091 if (changed) { 7092 if (DEBUG_PREFERRED) { 7093 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 7094 } 7095 scheduleWritePackageRestrictionsLocked(userId); 7096 } 7097 } 7098 } 7099 } 7100 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 7101 return null; 7102 } 7103 7104 /* 7105 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 7106 */ 7107 @Override 7108 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 7109 int targetUserId) { 7110 mContext.enforceCallingOrSelfPermission( 7111 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 7112 List<CrossProfileIntentFilter> matches = 7113 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 7114 if (matches != null) { 7115 int size = matches.size(); 7116 for (int i = 0; i < size; i++) { 7117 if (matches.get(i).getTargetUserId() == targetUserId) return true; 7118 } 7119 } 7120 if (intent.hasWebURI()) { 7121 // cross-profile app linking works only towards the parent. 7122 final int callingUid = Binder.getCallingUid(); 7123 final UserInfo parent = getProfileParent(sourceUserId); 7124 synchronized(mPackages) { 7125 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 7126 false /*includeInstantApps*/); 7127 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 7128 intent, resolvedType, flags, sourceUserId, parent.id); 7129 return xpDomainInfo != null; 7130 } 7131 } 7132 return false; 7133 } 7134 7135 private UserInfo getProfileParent(int userId) { 7136 final long identity = Binder.clearCallingIdentity(); 7137 try { 7138 return sUserManager.getProfileParent(userId); 7139 } finally { 7140 Binder.restoreCallingIdentity(identity); 7141 } 7142 } 7143 7144 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 7145 String resolvedType, int userId) { 7146 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 7147 if (resolver != null) { 7148 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 7149 } 7150 return null; 7151 } 7152 7153 @Override 7154 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 7155 String resolvedType, int flags, int userId) { 7156 try { 7157 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 7158 7159 return new ParceledListSlice<>( 7160 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 7161 } finally { 7162 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7163 } 7164 } 7165 7166 /** 7167 * Returns the package name of the calling Uid if it's an instant app. If it isn't 7168 * instant, returns {@code null}. 7169 */ 7170 private String getInstantAppPackageName(int callingUid) { 7171 synchronized (mPackages) { 7172 // If the caller is an isolated app use the owner's uid for the lookup. 7173 if (Process.isIsolated(callingUid)) { 7174 callingUid = mIsolatedOwners.get(callingUid); 7175 } 7176 final int appId = UserHandle.getAppId(callingUid); 7177 final Object obj = mSettings.getSettingLPr(appId); 7178 if (obj instanceof PackageSetting) { 7179 final PackageSetting ps = (PackageSetting) obj; 7180 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 7181 return isInstantApp ? ps.pkg.packageName : null; 7182 } 7183 } 7184 return null; 7185 } 7186 7187 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7188 String resolvedType, int flags, int userId) { 7189 return queryIntentActivitiesInternal( 7190 intent, resolvedType, flags, Binder.getCallingUid(), userId, 7191 false /*resolveForStart*/, true /*allowDynamicSplits*/); 7192 } 7193 7194 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7195 String resolvedType, int flags, int filterCallingUid, int userId, 7196 boolean resolveForStart, boolean allowDynamicSplits) { 7197 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7198 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 7199 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7200 false /* requireFullPermission */, false /* checkShell */, 7201 "query intent activities"); 7202 final String pkgName = intent.getPackage(); 7203 ComponentName comp = intent.getComponent(); 7204 if (comp == null) { 7205 if (intent.getSelector() != null) { 7206 intent = intent.getSelector(); 7207 comp = intent.getComponent(); 7208 } 7209 } 7210 7211 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 7212 comp != null || pkgName != null /*onlyExposedExplicitly*/); 7213 if (comp != null) { 7214 final List<ResolveInfo> list = new ArrayList<>(1); 7215 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 7216 if (ai != null) { 7217 // When specifying an explicit component, we prevent the activity from being 7218 // used when either 1) the calling package is normal and the activity is within 7219 // an ephemeral application or 2) the calling package is ephemeral and the 7220 // activity is not visible to ephemeral applications. 7221 final boolean matchInstantApp = 7222 (flags & PackageManager.MATCH_INSTANT) != 0; 7223 final boolean matchVisibleToInstantAppOnly = 7224 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7225 final boolean matchExplicitlyVisibleOnly = 7226 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7227 final boolean isCallerInstantApp = 7228 instantAppPkgName != null; 7229 final boolean isTargetSameInstantApp = 7230 comp.getPackageName().equals(instantAppPkgName); 7231 final boolean isTargetInstantApp = 7232 (ai.applicationInfo.privateFlags 7233 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7234 final boolean isTargetVisibleToInstantApp = 7235 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7236 final boolean isTargetExplicitlyVisibleToInstantApp = 7237 isTargetVisibleToInstantApp 7238 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7239 final boolean isTargetHiddenFromInstantApp = 7240 !isTargetVisibleToInstantApp 7241 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7242 final boolean blockResolution = 7243 !isTargetSameInstantApp 7244 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7245 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7246 && isTargetHiddenFromInstantApp)); 7247 if (!blockResolution) { 7248 final ResolveInfo ri = new ResolveInfo(); 7249 ri.activityInfo = ai; 7250 list.add(ri); 7251 } 7252 } 7253 return applyPostResolutionFilter( 7254 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart, 7255 userId, intent); 7256 } 7257 7258 // reader 7259 boolean sortResult = false; 7260 boolean addInstant = false; 7261 List<ResolveInfo> result; 7262 synchronized (mPackages) { 7263 if (pkgName == null) { 7264 List<CrossProfileIntentFilter> matchingFilters = 7265 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 7266 // Check for results that need to skip the current profile. 7267 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 7268 resolvedType, flags, userId); 7269 if (xpResolveInfo != null) { 7270 List<ResolveInfo> xpResult = new ArrayList<>(1); 7271 xpResult.add(xpResolveInfo); 7272 return applyPostResolutionFilter( 7273 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 7274 allowDynamicSplits, filterCallingUid, resolveForStart, userId, intent); 7275 } 7276 7277 // Check for results in the current profile. 7278 result = filterIfNotSystemUser(mComponentResolver.queryActivities( 7279 intent, resolvedType, flags, userId), userId); 7280 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 7281 false /*skipPackageCheck*/); 7282 // Check for cross profile results. 7283 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 7284 xpResolveInfo = queryCrossProfileIntents( 7285 matchingFilters, intent, resolvedType, flags, userId, 7286 hasNonNegativePriorityResult); 7287 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 7288 boolean isVisibleToUser = filterIfNotSystemUser( 7289 Collections.singletonList(xpResolveInfo), userId).size() > 0; 7290 if (isVisibleToUser) { 7291 result.add(xpResolveInfo); 7292 sortResult = true; 7293 } 7294 } 7295 if (intent.hasWebURI()) { 7296 CrossProfileDomainInfo xpDomainInfo = null; 7297 final UserInfo parent = getProfileParent(userId); 7298 if (parent != null) { 7299 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 7300 flags, userId, parent.id); 7301 } 7302 if (xpDomainInfo != null) { 7303 if (xpResolveInfo != null) { 7304 // If we didn't remove it, the cross-profile ResolveInfo would be twice 7305 // in the result. 7306 result.remove(xpResolveInfo); 7307 } 7308 if (result.size() == 0 && !addInstant) { 7309 // No result in current profile, but found candidate in parent user. 7310 // And we are not going to add emphemeral app, so we can return the 7311 // result straight away. 7312 result.add(xpDomainInfo.resolveInfo); 7313 return applyPostResolutionFilter(result, instantAppPkgName, 7314 allowDynamicSplits, filterCallingUid, resolveForStart, userId, 7315 intent); 7316 } 7317 } else if (result.size() <= 1 && !addInstant) { 7318 // No result in parent user and <= 1 result in current profile, and we 7319 // are not going to add emphemeral app, so we can return the result without 7320 // further processing. 7321 return applyPostResolutionFilter(result, instantAppPkgName, 7322 allowDynamicSplits, filterCallingUid, resolveForStart, userId, 7323 intent); 7324 } 7325 // We have more than one candidate (combining results from current and parent 7326 // profile), so we need filtering and sorting. 7327 result = filterCandidatesWithDomainPreferredActivitiesLPr( 7328 intent, flags, result, xpDomainInfo, userId); 7329 sortResult = true; 7330 } 7331 } else { 7332 final PackageParser.Package pkg = mPackages.get(pkgName); 7333 result = null; 7334 if (pkg != null) { 7335 result = filterIfNotSystemUser(mComponentResolver.queryActivities( 7336 intent, resolvedType, flags, pkg.activities, userId), userId); 7337 } 7338 if (result == null || result.size() == 0) { 7339 // the caller wants to resolve for a particular package; however, there 7340 // were no installed results, so, try to find an ephemeral result 7341 addInstant = isInstantAppResolutionAllowed( 7342 intent, null /*result*/, userId, true /*skipPackageCheck*/); 7343 if (result == null) { 7344 result = new ArrayList<>(); 7345 } 7346 } 7347 } 7348 } 7349 if (addInstant) { 7350 result = maybeAddInstantAppInstaller( 7351 result, intent, resolvedType, flags, userId, resolveForStart); 7352 } 7353 if (sortResult) { 7354 Collections.sort(result, RESOLVE_PRIORITY_SORTER); 7355 } 7356 return applyPostResolutionFilter( 7357 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart, 7358 userId, intent); 7359 } 7360 7361 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 7362 String resolvedType, int flags, int userId, boolean resolveForStart) { 7363 // first, check to see if we've got an instant app already installed 7364 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 7365 ResolveInfo localInstantApp = null; 7366 boolean blockResolution = false; 7367 if (!alreadyResolvedLocally) { 7368 final List<ResolveInfo> instantApps = mComponentResolver.queryActivities( 7369 intent, 7370 resolvedType, 7371 flags 7372 | PackageManager.GET_RESOLVED_FILTER 7373 | PackageManager.MATCH_INSTANT 7374 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 7375 userId); 7376 for (int i = instantApps.size() - 1; i >= 0; --i) { 7377 final ResolveInfo info = instantApps.get(i); 7378 final String packageName = info.activityInfo.packageName; 7379 final PackageSetting ps = mSettings.mPackages.get(packageName); 7380 if (ps.getInstantApp(userId)) { 7381 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7382 final int status = (int)(packedStatus >> 32); 7383 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7384 // there's a local instant application installed, but, the user has 7385 // chosen to never use it; skip resolution and don't acknowledge 7386 // an instant application is even available 7387 if (DEBUG_INSTANT) { 7388 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 7389 } 7390 blockResolution = true; 7391 break; 7392 } else { 7393 // we have a locally installed instant application; skip resolution 7394 // but acknowledge there's an instant application available 7395 if (DEBUG_INSTANT) { 7396 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 7397 } 7398 localInstantApp = info; 7399 break; 7400 } 7401 } 7402 } 7403 } 7404 // no app installed, let's see if one's available 7405 AuxiliaryResolveInfo auxiliaryResponse = null; 7406 if (!blockResolution) { 7407 if (localInstantApp == null) { 7408 // we don't have an instant app locally, resolve externally 7409 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 7410 final InstantAppRequest requestObject = new InstantAppRequest( 7411 null /*responseObj*/, intent /*origIntent*/, resolvedType, 7412 null /*callingPackage*/, userId, null /*verificationBundle*/, 7413 resolveForStart); 7414 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 7415 mInstantAppResolverConnection, requestObject); 7416 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7417 } else { 7418 // we have an instant application locally, but, we can't admit that since 7419 // callers shouldn't be able to determine prior browsing. create a dummy 7420 // auxiliary response so the downstream code behaves as if there's an 7421 // instant application available externally. when it comes time to start 7422 // the instant application, we'll do the right thing. 7423 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 7424 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 7425 ai.packageName, ai.longVersionCode, null /* splitName */); 7426 } 7427 } 7428 if (intent.isWebIntent() && auxiliaryResponse == null) { 7429 return result; 7430 } 7431 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 7432 if (ps == null 7433 || !ps.readUserState(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 7434 return result; 7435 } 7436 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 7437 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 7438 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 7439 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7440 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7441 // add a non-generic filter 7442 ephemeralInstaller.filter = new IntentFilter(); 7443 if (intent.getAction() != null) { 7444 ephemeralInstaller.filter.addAction(intent.getAction()); 7445 } 7446 if (intent.getData() != null && intent.getData().getPath() != null) { 7447 ephemeralInstaller.filter.addDataPath( 7448 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 7449 } 7450 ephemeralInstaller.isInstantAppAvailable = true; 7451 // make sure this resolver is the default 7452 ephemeralInstaller.isDefault = true; 7453 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 7454 if (DEBUG_INSTANT) { 7455 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7456 } 7457 7458 result.add(ephemeralInstaller); 7459 return result; 7460 } 7461 7462 private static class CrossProfileDomainInfo { 7463 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 7464 ResolveInfo resolveInfo; 7465 /* Best domain verification status of the activities found in the other profile */ 7466 int bestDomainVerificationStatus; 7467 } 7468 7469 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 7470 String resolvedType, int flags, int sourceUserId, int parentUserId) { 7471 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 7472 sourceUserId)) { 7473 return null; 7474 } 7475 List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent, 7476 resolvedType, flags, parentUserId); 7477 7478 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 7479 return null; 7480 } 7481 CrossProfileDomainInfo result = null; 7482 int size = resultTargetUser.size(); 7483 for (int i = 0; i < size; i++) { 7484 ResolveInfo riTargetUser = resultTargetUser.get(i); 7485 // Intent filter verification is only for filters that specify a host. So don't return 7486 // those that handle all web uris. 7487 if (riTargetUser.handleAllWebDataURI) { 7488 continue; 7489 } 7490 String packageName = riTargetUser.activityInfo.packageName; 7491 PackageSetting ps = mSettings.mPackages.get(packageName); 7492 if (ps == null) { 7493 continue; 7494 } 7495 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 7496 int status = (int)(verificationState >> 32); 7497 if (result == null) { 7498 result = new CrossProfileDomainInfo(); 7499 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 7500 sourceUserId, parentUserId); 7501 result.bestDomainVerificationStatus = status; 7502 } else { 7503 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 7504 result.bestDomainVerificationStatus); 7505 } 7506 } 7507 // Don't consider matches with status NEVER across profiles. 7508 if (result != null && result.bestDomainVerificationStatus 7509 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7510 return null; 7511 } 7512 return result; 7513 } 7514 7515 /** 7516 * Verification statuses are ordered from the worse to the best, except for 7517 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7518 */ 7519 private int bestDomainVerificationStatus(int status1, int status2) { 7520 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7521 return status2; 7522 } 7523 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7524 return status1; 7525 } 7526 return (int) MathUtils.max(status1, status2); 7527 } 7528 7529 private boolean isUserEnabled(int userId) { 7530 long callingId = Binder.clearCallingIdentity(); 7531 try { 7532 UserInfo userInfo = sUserManager.getUserInfo(userId); 7533 return userInfo != null && userInfo.isEnabled(); 7534 } finally { 7535 Binder.restoreCallingIdentity(callingId); 7536 } 7537 } 7538 7539 /** 7540 * Filter out activities with systemUserOnly flag set, when current user is not System. 7541 * 7542 * @return filtered list 7543 */ 7544 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7545 if (userId == UserHandle.USER_SYSTEM) { 7546 return resolveInfos; 7547 } 7548 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7549 ResolveInfo info = resolveInfos.get(i); 7550 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7551 resolveInfos.remove(i); 7552 } 7553 } 7554 return resolveInfos; 7555 } 7556 7557 /** 7558 * Filters out ephemeral activities. 7559 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7560 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7561 * 7562 * @param resolveInfos The pre-filtered list of resolved activities 7563 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7564 * is performed. 7565 * @param intent 7566 * @return A filtered list of resolved activities. 7567 */ 7568 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7569 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, 7570 boolean resolveForStart, int userId, Intent intent) { 7571 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(userId); 7572 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7573 final ResolveInfo info = resolveInfos.get(i); 7574 // remove locally resolved instant app web results when disabled 7575 if (info.isInstantAppAvailable && blockInstant) { 7576 resolveInfos.remove(i); 7577 continue; 7578 } 7579 // allow activities that are defined in the provided package 7580 if (allowDynamicSplits 7581 && info.activityInfo != null 7582 && info.activityInfo.splitName != null 7583 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7584 info.activityInfo.splitName)) { 7585 if (mInstantAppInstallerActivity == null) { 7586 if (DEBUG_INSTALL) { 7587 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 7588 } 7589 resolveInfos.remove(i); 7590 continue; 7591 } 7592 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 7593 resolveInfos.remove(i); 7594 continue; 7595 } 7596 // requested activity is defined in a split that hasn't been installed yet. 7597 // add the installer to the resolve list 7598 if (DEBUG_INSTALL) { 7599 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 7600 } 7601 final ResolveInfo installerInfo = new ResolveInfo( 7602 mInstantAppInstallerInfo); 7603 final ComponentName installFailureActivity = findInstallFailureActivity( 7604 info.activityInfo.packageName, filterCallingUid, userId); 7605 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7606 installFailureActivity, 7607 info.activityInfo.packageName, 7608 info.activityInfo.applicationInfo.longVersionCode, 7609 info.activityInfo.splitName); 7610 // add a non-generic filter 7611 installerInfo.filter = new IntentFilter(); 7612 7613 // This resolve info may appear in the chooser UI, so let us make it 7614 // look as the one it replaces as far as the user is concerned which 7615 // requires loading the correct label and icon for the resolve info. 7616 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7617 installerInfo.labelRes = info.resolveLabelResId(); 7618 installerInfo.icon = info.resolveIconResId(); 7619 installerInfo.isInstantAppAvailable = true; 7620 resolveInfos.set(i, installerInfo); 7621 continue; 7622 } 7623 // caller is a full app, don't need to apply any other filtering 7624 if (ephemeralPkgName == null) { 7625 continue; 7626 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 7627 // caller is same app; don't need to apply any other filtering 7628 continue; 7629 } else if (resolveForStart 7630 && (intent.isWebIntent() 7631 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) 7632 && intent.getPackage() == null 7633 && intent.getComponent() == null) { 7634 // ephemeral apps can launch other ephemeral apps indirectly 7635 continue; 7636 } 7637 // allow activities that have been explicitly exposed to ephemeral apps 7638 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7639 if (!isEphemeralApp 7640 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7641 continue; 7642 } 7643 resolveInfos.remove(i); 7644 } 7645 return resolveInfos; 7646 } 7647 7648 /** 7649 * Returns the activity component that can handle install failures. 7650 * <p>By default, the instant application installer handles failures. However, an 7651 * application may want to handle failures on its own. Applications do this by 7652 * creating an activity with an intent filter that handles the action 7653 * {@link Intent#ACTION_INSTALL_FAILURE}. 7654 */ 7655 private @Nullable ComponentName findInstallFailureActivity( 7656 String packageName, int filterCallingUid, int userId) { 7657 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 7658 failureActivityIntent.setPackage(packageName); 7659 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 7660 final List<ResolveInfo> result = queryIntentActivitiesInternal( 7661 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 7662 false /*resolveForStart*/, false /*allowDynamicSplits*/); 7663 final int NR = result.size(); 7664 if (NR > 0) { 7665 for (int i = 0; i < NR; i++) { 7666 final ResolveInfo info = result.get(i); 7667 if (info.activityInfo.splitName != null) { 7668 continue; 7669 } 7670 return new ComponentName(packageName, info.activityInfo.name); 7671 } 7672 } 7673 return null; 7674 } 7675 7676 /** 7677 * @param resolveInfos list of resolve infos in descending priority order 7678 * @return if the list contains a resolve info with non-negative priority 7679 */ 7680 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7681 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7682 } 7683 7684 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7685 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7686 int userId) { 7687 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7688 7689 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7690 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7691 candidates.size()); 7692 } 7693 7694 final ArrayList<ResolveInfo> result = new ArrayList<>(); 7695 final ArrayList<ResolveInfo> alwaysList = new ArrayList<>(); 7696 final ArrayList<ResolveInfo> undefinedList = new ArrayList<>(); 7697 final ArrayList<ResolveInfo> alwaysAskList = new ArrayList<>(); 7698 final ArrayList<ResolveInfo> neverList = new ArrayList<>(); 7699 final ArrayList<ResolveInfo> matchAllList = new ArrayList<>(); 7700 7701 synchronized (mPackages) { 7702 final int count = candidates.size(); 7703 // First, try to use linked apps. Partition the candidates into four lists: 7704 // one for the final results, one for the "do not use ever", one for "undefined status" 7705 // and finally one for "browser app type". 7706 for (int n=0; n<count; n++) { 7707 ResolveInfo info = candidates.get(n); 7708 String packageName = info.activityInfo.packageName; 7709 PackageSetting ps = mSettings.mPackages.get(packageName); 7710 if (ps != null) { 7711 // Add to the special match all list (Browser use case) 7712 if (info.handleAllWebDataURI) { 7713 matchAllList.add(info); 7714 continue; 7715 } 7716 // Try to get the status from User settings first 7717 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7718 int status = (int)(packedStatus >> 32); 7719 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7720 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7721 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7722 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7723 + " : linkgen=" + linkGeneration); 7724 } 7725 // Use link-enabled generation as preferredOrder, i.e. 7726 // prefer newly-enabled over earlier-enabled. 7727 info.preferredOrder = linkGeneration; 7728 alwaysList.add(info); 7729 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7730 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7731 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7732 } 7733 neverList.add(info); 7734 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7735 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7736 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7737 } 7738 alwaysAskList.add(info); 7739 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7740 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7741 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7742 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7743 } 7744 undefinedList.add(info); 7745 } 7746 } 7747 } 7748 7749 // We'll want to include browser possibilities in a few cases 7750 boolean includeBrowser = false; 7751 7752 // First try to add the "always" resolution(s) for the current user, if any 7753 if (alwaysList.size() > 0) { 7754 result.addAll(alwaysList); 7755 } else { 7756 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7757 result.addAll(undefinedList); 7758 // Maybe add one for the other profile. 7759 if (xpDomainInfo != null && ( 7760 xpDomainInfo.bestDomainVerificationStatus 7761 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7762 result.add(xpDomainInfo.resolveInfo); 7763 } 7764 includeBrowser = true; 7765 } 7766 7767 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7768 // If there were 'always' entries their preferred order has been set, so we also 7769 // back that off to make the alternatives equivalent 7770 if (alwaysAskList.size() > 0) { 7771 for (ResolveInfo i : result) { 7772 i.preferredOrder = 0; 7773 } 7774 result.addAll(alwaysAskList); 7775 includeBrowser = true; 7776 } 7777 7778 if (includeBrowser) { 7779 // Also add browsers (all of them or only the default one) 7780 if (DEBUG_DOMAIN_VERIFICATION) { 7781 Slog.v(TAG, " ...including browsers in candidate set"); 7782 } 7783 if ((matchFlags & MATCH_ALL) != 0) { 7784 result.addAll(matchAllList); 7785 } else { 7786 // Browser/generic handling case. If there's a default browser, go straight 7787 // to that (but only if there is no other higher-priority match). 7788 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7789 int maxMatchPrio = 0; 7790 ResolveInfo defaultBrowserMatch = null; 7791 final int numCandidates = matchAllList.size(); 7792 for (int n = 0; n < numCandidates; n++) { 7793 ResolveInfo info = matchAllList.get(n); 7794 // track the highest overall match priority... 7795 if (info.priority > maxMatchPrio) { 7796 maxMatchPrio = info.priority; 7797 } 7798 // ...and the highest-priority default browser match 7799 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7800 if (defaultBrowserMatch == null 7801 || (defaultBrowserMatch.priority < info.priority)) { 7802 if (debug) { 7803 Slog.v(TAG, "Considering default browser match " + info); 7804 } 7805 defaultBrowserMatch = info; 7806 } 7807 } 7808 } 7809 if (defaultBrowserMatch != null 7810 && defaultBrowserMatch.priority >= maxMatchPrio 7811 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7812 { 7813 if (debug) { 7814 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7815 } 7816 result.add(defaultBrowserMatch); 7817 } else { 7818 result.addAll(matchAllList); 7819 } 7820 } 7821 7822 // If there is nothing selected, add all candidates and remove the ones that the user 7823 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7824 if (result.size() == 0) { 7825 result.addAll(candidates); 7826 result.removeAll(neverList); 7827 } 7828 } 7829 } 7830 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7831 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7832 result.size()); 7833 for (ResolveInfo info : result) { 7834 Slog.v(TAG, " + " + info.activityInfo); 7835 } 7836 } 7837 return result; 7838 } 7839 7840 // Returns a packed value as a long: 7841 // 7842 // high 'int'-sized word: link status: undefined/ask/never/always. 7843 // low 'int'-sized word: relative priority among 'always' results. 7844 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7845 long result = ps.getDomainVerificationStatusForUser(userId); 7846 // if none available, get the master status 7847 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7848 if (ps.getIntentFilterVerificationInfo() != null) { 7849 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7850 } 7851 } 7852 return result; 7853 } 7854 7855 private ResolveInfo querySkipCurrentProfileIntents( 7856 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7857 int flags, int sourceUserId) { 7858 if (matchingFilters != null) { 7859 int size = matchingFilters.size(); 7860 for (int i = 0; i < size; i ++) { 7861 CrossProfileIntentFilter filter = matchingFilters.get(i); 7862 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7863 // Checking if there are activities in the target user that can handle the 7864 // intent. 7865 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7866 resolvedType, flags, sourceUserId); 7867 if (resolveInfo != null) { 7868 return resolveInfo; 7869 } 7870 } 7871 } 7872 } 7873 return null; 7874 } 7875 7876 // Return matching ResolveInfo in target user if any. 7877 private ResolveInfo queryCrossProfileIntents( 7878 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7879 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7880 if (matchingFilters != null) { 7881 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7882 // match the same intent. For performance reasons, it is better not to 7883 // run queryIntent twice for the same userId 7884 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7885 int size = matchingFilters.size(); 7886 for (int i = 0; i < size; i++) { 7887 CrossProfileIntentFilter filter = matchingFilters.get(i); 7888 int targetUserId = filter.getTargetUserId(); 7889 boolean skipCurrentProfile = 7890 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7891 boolean skipCurrentProfileIfNoMatchFound = 7892 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7893 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7894 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7895 // Checking if there are activities in the target user that can handle the 7896 // intent. 7897 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7898 resolvedType, flags, sourceUserId); 7899 if (resolveInfo != null) return resolveInfo; 7900 alreadyTriedUserIds.put(targetUserId, true); 7901 } 7902 } 7903 } 7904 return null; 7905 } 7906 7907 /** 7908 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7909 * will forward the intent to the filter's target user. 7910 * Otherwise, returns null. 7911 */ 7912 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7913 String resolvedType, int flags, int sourceUserId) { 7914 int targetUserId = filter.getTargetUserId(); 7915 List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent, 7916 resolvedType, flags, targetUserId); 7917 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7918 // If all the matches in the target profile are suspended, return null. 7919 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7920 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7921 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7922 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7923 targetUserId); 7924 } 7925 } 7926 } 7927 return null; 7928 } 7929 7930 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7931 int sourceUserId, int targetUserId) { 7932 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7933 long ident = Binder.clearCallingIdentity(); 7934 boolean targetIsProfile; 7935 try { 7936 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7937 } finally { 7938 Binder.restoreCallingIdentity(ident); 7939 } 7940 String className; 7941 if (targetIsProfile) { 7942 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7943 } else { 7944 className = FORWARD_INTENT_TO_PARENT; 7945 } 7946 ComponentName forwardingActivityComponentName = new ComponentName( 7947 mAndroidApplication.packageName, className); 7948 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7949 sourceUserId); 7950 if (!targetIsProfile) { 7951 forwardingActivityInfo.showUserIcon = targetUserId; 7952 forwardingResolveInfo.noResourceId = true; 7953 } 7954 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7955 forwardingResolveInfo.priority = 0; 7956 forwardingResolveInfo.preferredOrder = 0; 7957 forwardingResolveInfo.match = 0; 7958 forwardingResolveInfo.isDefault = true; 7959 forwardingResolveInfo.filter = filter; 7960 forwardingResolveInfo.targetUserId = targetUserId; 7961 return forwardingResolveInfo; 7962 } 7963 7964 @Override 7965 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7966 Intent[] specifics, String[] specificTypes, Intent intent, 7967 String resolvedType, int flags, int userId) { 7968 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7969 specificTypes, intent, resolvedType, flags, userId)); 7970 } 7971 7972 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7973 Intent[] specifics, String[] specificTypes, Intent intent, 7974 String resolvedType, int flags, int userId) { 7975 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7976 final int callingUid = Binder.getCallingUid(); 7977 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7978 false /*includeInstantApps*/); 7979 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7980 false /*requireFullPermission*/, false /*checkShell*/, 7981 "query intent activity options"); 7982 final String resultsAction = intent.getAction(); 7983 7984 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7985 | PackageManager.GET_RESOLVED_FILTER, userId); 7986 7987 if (DEBUG_INTENT_MATCHING) { 7988 Log.v(TAG, "Query " + intent + ": " + results); 7989 } 7990 7991 int specificsPos = 0; 7992 int N; 7993 7994 // todo: note that the algorithm used here is O(N^2). This 7995 // isn't a problem in our current environment, but if we start running 7996 // into situations where we have more than 5 or 10 matches then this 7997 // should probably be changed to something smarter... 7998 7999 // First we go through and resolve each of the specific items 8000 // that were supplied, taking care of removing any corresponding 8001 // duplicate items in the generic resolve list. 8002 if (specifics != null) { 8003 for (int i=0; i<specifics.length; i++) { 8004 final Intent sintent = specifics[i]; 8005 if (sintent == null) { 8006 continue; 8007 } 8008 8009 if (DEBUG_INTENT_MATCHING) { 8010 Log.v(TAG, "Specific #" + i + ": " + sintent); 8011 } 8012 8013 String action = sintent.getAction(); 8014 if (resultsAction != null && resultsAction.equals(action)) { 8015 // If this action was explicitly requested, then don't 8016 // remove things that have it. 8017 action = null; 8018 } 8019 8020 ResolveInfo ri = null; 8021 ActivityInfo ai = null; 8022 8023 ComponentName comp = sintent.getComponent(); 8024 if (comp == null) { 8025 ri = resolveIntent( 8026 sintent, 8027 specificTypes != null ? specificTypes[i] : null, 8028 flags, userId); 8029 if (ri == null) { 8030 continue; 8031 } 8032 if (ri == mResolveInfo) { 8033 // ACK! Must do something better with this. 8034 } 8035 ai = ri.activityInfo; 8036 comp = new ComponentName(ai.applicationInfo.packageName, 8037 ai.name); 8038 } else { 8039 ai = getActivityInfo(comp, flags, userId); 8040 if (ai == null) { 8041 continue; 8042 } 8043 } 8044 8045 // Look for any generic query activities that are duplicates 8046 // of this specific one, and remove them from the results. 8047 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 8048 N = results.size(); 8049 int j; 8050 for (j=specificsPos; j<N; j++) { 8051 ResolveInfo sri = results.get(j); 8052 if ((sri.activityInfo.name.equals(comp.getClassName()) 8053 && sri.activityInfo.applicationInfo.packageName.equals( 8054 comp.getPackageName())) 8055 || (action != null && sri.filter.matchAction(action))) { 8056 results.remove(j); 8057 if (DEBUG_INTENT_MATCHING) Log.v( 8058 TAG, "Removing duplicate item from " + j 8059 + " due to specific " + specificsPos); 8060 if (ri == null) { 8061 ri = sri; 8062 } 8063 j--; 8064 N--; 8065 } 8066 } 8067 8068 // Add this specific item to its proper place. 8069 if (ri == null) { 8070 ri = new ResolveInfo(); 8071 ri.activityInfo = ai; 8072 } 8073 results.add(specificsPos, ri); 8074 ri.specificIndex = i; 8075 specificsPos++; 8076 } 8077 } 8078 8079 // Now we go through the remaining generic results and remove any 8080 // duplicate actions that are found here. 8081 N = results.size(); 8082 for (int i=specificsPos; i<N-1; i++) { 8083 final ResolveInfo rii = results.get(i); 8084 if (rii.filter == null) { 8085 continue; 8086 } 8087 8088 // Iterate over all of the actions of this result's intent 8089 // filter... typically this should be just one. 8090 final Iterator<String> it = rii.filter.actionsIterator(); 8091 if (it == null) { 8092 continue; 8093 } 8094 while (it.hasNext()) { 8095 final String action = it.next(); 8096 if (resultsAction != null && resultsAction.equals(action)) { 8097 // If this action was explicitly requested, then don't 8098 // remove things that have it. 8099 continue; 8100 } 8101 for (int j=i+1; j<N; j++) { 8102 final ResolveInfo rij = results.get(j); 8103 if (rij.filter != null && rij.filter.hasAction(action)) { 8104 results.remove(j); 8105 if (DEBUG_INTENT_MATCHING) Log.v( 8106 TAG, "Removing duplicate item from " + j 8107 + " due to action " + action + " at " + i); 8108 j--; 8109 N--; 8110 } 8111 } 8112 } 8113 8114 // If the caller didn't request filter information, drop it now 8115 // so we don't have to marshall/unmarshall it. 8116 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8117 rii.filter = null; 8118 } 8119 } 8120 8121 // Filter out the caller activity if so requested. 8122 if (caller != null) { 8123 N = results.size(); 8124 for (int i=0; i<N; i++) { 8125 ActivityInfo ainfo = results.get(i).activityInfo; 8126 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 8127 && caller.getClassName().equals(ainfo.name)) { 8128 results.remove(i); 8129 break; 8130 } 8131 } 8132 } 8133 8134 // If the caller didn't request filter information, 8135 // drop them now so we don't have to 8136 // marshall/unmarshall it. 8137 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8138 N = results.size(); 8139 for (int i=0; i<N; i++) { 8140 results.get(i).filter = null; 8141 } 8142 } 8143 8144 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 8145 return results; 8146 } 8147 8148 @Override 8149 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 8150 String resolvedType, int flags, int userId) { 8151 return new ParceledListSlice<>( 8152 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 8153 false /*allowDynamicSplits*/)); 8154 } 8155 8156 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 8157 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 8158 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8159 final int callingUid = Binder.getCallingUid(); 8160 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8161 false /*requireFullPermission*/, false /*checkShell*/, 8162 "query intent receivers"); 8163 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8164 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8165 false /*includeInstantApps*/); 8166 ComponentName comp = intent.getComponent(); 8167 if (comp == null) { 8168 if (intent.getSelector() != null) { 8169 intent = intent.getSelector(); 8170 comp = intent.getComponent(); 8171 } 8172 } 8173 if (comp != null) { 8174 final List<ResolveInfo> list = new ArrayList<>(1); 8175 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 8176 if (ai != null) { 8177 // When specifying an explicit component, we prevent the activity from being 8178 // used when either 1) the calling package is normal and the activity is within 8179 // an instant application or 2) the calling package is ephemeral and the 8180 // activity is not visible to instant applications. 8181 final boolean matchInstantApp = 8182 (flags & PackageManager.MATCH_INSTANT) != 0; 8183 final boolean matchVisibleToInstantAppOnly = 8184 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8185 final boolean matchExplicitlyVisibleOnly = 8186 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 8187 final boolean isCallerInstantApp = 8188 instantAppPkgName != null; 8189 final boolean isTargetSameInstantApp = 8190 comp.getPackageName().equals(instantAppPkgName); 8191 final boolean isTargetInstantApp = 8192 (ai.applicationInfo.privateFlags 8193 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8194 final boolean isTargetVisibleToInstantApp = 8195 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 8196 final boolean isTargetExplicitlyVisibleToInstantApp = 8197 isTargetVisibleToInstantApp 8198 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 8199 final boolean isTargetHiddenFromInstantApp = 8200 !isTargetVisibleToInstantApp 8201 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 8202 final boolean blockResolution = 8203 !isTargetSameInstantApp 8204 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8205 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8206 && isTargetHiddenFromInstantApp)); 8207 if (!blockResolution) { 8208 ResolveInfo ri = new ResolveInfo(); 8209 ri.activityInfo = ai; 8210 list.add(ri); 8211 } 8212 } 8213 return applyPostResolutionFilter( 8214 list, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8215 intent); 8216 } 8217 8218 // reader 8219 synchronized (mPackages) { 8220 String pkgName = intent.getPackage(); 8221 if (pkgName == null) { 8222 final List<ResolveInfo> result = 8223 mComponentResolver.queryReceivers(intent, resolvedType, flags, userId); 8224 return applyPostResolutionFilter( 8225 result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8226 intent); 8227 } 8228 final PackageParser.Package pkg = mPackages.get(pkgName); 8229 if (pkg != null) { 8230 final List<ResolveInfo> result = mComponentResolver.queryReceivers( 8231 intent, resolvedType, flags, pkg.receivers, userId); 8232 return applyPostResolutionFilter( 8233 result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8234 intent); 8235 } 8236 return Collections.emptyList(); 8237 } 8238 } 8239 8240 @Override 8241 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 8242 final int callingUid = Binder.getCallingUid(); 8243 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 8244 } 8245 8246 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 8247 int userId, int callingUid) { 8248 if (!sUserManager.exists(userId)) return null; 8249 flags = updateFlagsForResolve( 8250 flags, userId, intent, callingUid, false /*includeInstantApps*/); 8251 List<ResolveInfo> query = queryIntentServicesInternal( 8252 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 8253 if (query != null) { 8254 if (query.size() >= 1) { 8255 // If there is more than one service with the same priority, 8256 // just arbitrarily pick the first one. 8257 return query.get(0); 8258 } 8259 } 8260 return null; 8261 } 8262 8263 @Override 8264 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 8265 String resolvedType, int flags, int userId) { 8266 final int callingUid = Binder.getCallingUid(); 8267 return new ParceledListSlice<>(queryIntentServicesInternal( 8268 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 8269 } 8270 8271 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 8272 String resolvedType, int flags, int userId, int callingUid, 8273 boolean includeInstantApps) { 8274 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8275 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8276 false /*requireFullPermission*/, false /*checkShell*/, 8277 "query intent receivers"); 8278 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8279 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 8280 ComponentName comp = intent.getComponent(); 8281 if (comp == null) { 8282 if (intent.getSelector() != null) { 8283 intent = intent.getSelector(); 8284 comp = intent.getComponent(); 8285 } 8286 } 8287 if (comp != null) { 8288 final List<ResolveInfo> list = new ArrayList<>(1); 8289 final ServiceInfo si = getServiceInfo(comp, flags, userId); 8290 if (si != null) { 8291 // When specifying an explicit component, we prevent the service from being 8292 // used when either 1) the service is in an instant application and the 8293 // caller is not the same instant application or 2) the calling package is 8294 // ephemeral and the activity is not visible to ephemeral applications. 8295 final boolean matchInstantApp = 8296 (flags & PackageManager.MATCH_INSTANT) != 0; 8297 final boolean matchVisibleToInstantAppOnly = 8298 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8299 final boolean isCallerInstantApp = 8300 instantAppPkgName != null; 8301 final boolean isTargetSameInstantApp = 8302 comp.getPackageName().equals(instantAppPkgName); 8303 final boolean isTargetInstantApp = 8304 (si.applicationInfo.privateFlags 8305 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8306 final boolean isTargetHiddenFromInstantApp = 8307 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8308 final boolean blockResolution = 8309 !isTargetSameInstantApp 8310 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8311 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8312 && isTargetHiddenFromInstantApp)); 8313 if (!blockResolution) { 8314 final ResolveInfo ri = new ResolveInfo(); 8315 ri.serviceInfo = si; 8316 list.add(ri); 8317 } 8318 } 8319 return list; 8320 } 8321 8322 // reader 8323 synchronized (mPackages) { 8324 String pkgName = intent.getPackage(); 8325 if (pkgName == null) { 8326 return applyPostServiceResolutionFilter( 8327 mComponentResolver.queryServices(intent, resolvedType, flags, userId), 8328 instantAppPkgName); 8329 } 8330 final PackageParser.Package pkg = mPackages.get(pkgName); 8331 if (pkg != null) { 8332 return applyPostServiceResolutionFilter( 8333 mComponentResolver.queryServices(intent, resolvedType, flags, pkg.services, 8334 userId), 8335 instantAppPkgName); 8336 } 8337 return Collections.emptyList(); 8338 } 8339 } 8340 8341 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 8342 String instantAppPkgName) { 8343 if (instantAppPkgName == null) { 8344 return resolveInfos; 8345 } 8346 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8347 final ResolveInfo info = resolveInfos.get(i); 8348 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 8349 // allow services that are defined in the provided package 8350 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 8351 if (info.serviceInfo.splitName != null 8352 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 8353 info.serviceInfo.splitName)) { 8354 // requested service is defined in a split that hasn't been installed yet. 8355 // add the installer to the resolve list 8356 if (DEBUG_INSTANT) { 8357 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8358 } 8359 final ResolveInfo installerInfo = new ResolveInfo( 8360 mInstantAppInstallerInfo); 8361 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8362 null /* installFailureActivity */, 8363 info.serviceInfo.packageName, 8364 info.serviceInfo.applicationInfo.longVersionCode, 8365 info.serviceInfo.splitName); 8366 // add a non-generic filter 8367 installerInfo.filter = new IntentFilter(); 8368 // load resources from the correct package 8369 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8370 resolveInfos.set(i, installerInfo); 8371 } 8372 continue; 8373 } 8374 // allow services that have been explicitly exposed to ephemeral apps 8375 if (!isEphemeralApp 8376 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8377 continue; 8378 } 8379 resolveInfos.remove(i); 8380 } 8381 return resolveInfos; 8382 } 8383 8384 @Override 8385 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 8386 String resolvedType, int flags, int userId) { 8387 return new ParceledListSlice<>( 8388 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 8389 } 8390 8391 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 8392 Intent intent, String resolvedType, int flags, int userId) { 8393 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8394 final int callingUid = Binder.getCallingUid(); 8395 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8396 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8397 false /*includeInstantApps*/); 8398 ComponentName comp = intent.getComponent(); 8399 if (comp == null) { 8400 if (intent.getSelector() != null) { 8401 intent = intent.getSelector(); 8402 comp = intent.getComponent(); 8403 } 8404 } 8405 if (comp != null) { 8406 final List<ResolveInfo> list = new ArrayList<>(1); 8407 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 8408 if (pi != null) { 8409 // When specifying an explicit component, we prevent the provider from being 8410 // used when either 1) the provider is in an instant application and the 8411 // caller is not the same instant application or 2) the calling package is an 8412 // instant application and the provider is not visible to instant applications. 8413 final boolean matchInstantApp = 8414 (flags & PackageManager.MATCH_INSTANT) != 0; 8415 final boolean matchVisibleToInstantAppOnly = 8416 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8417 final boolean isCallerInstantApp = 8418 instantAppPkgName != null; 8419 final boolean isTargetSameInstantApp = 8420 comp.getPackageName().equals(instantAppPkgName); 8421 final boolean isTargetInstantApp = 8422 (pi.applicationInfo.privateFlags 8423 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8424 final boolean isTargetHiddenFromInstantApp = 8425 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8426 final boolean blockResolution = 8427 !isTargetSameInstantApp 8428 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8429 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8430 && isTargetHiddenFromInstantApp)); 8431 if (!blockResolution) { 8432 final ResolveInfo ri = new ResolveInfo(); 8433 ri.providerInfo = pi; 8434 list.add(ri); 8435 } 8436 } 8437 return list; 8438 } 8439 8440 // reader 8441 synchronized (mPackages) { 8442 String pkgName = intent.getPackage(); 8443 if (pkgName == null) { 8444 return applyPostContentProviderResolutionFilter( 8445 mComponentResolver.queryProviders(intent, resolvedType, flags, userId), 8446 instantAppPkgName); 8447 } 8448 final PackageParser.Package pkg = mPackages.get(pkgName); 8449 if (pkg != null) { 8450 return applyPostContentProviderResolutionFilter( 8451 mComponentResolver.queryProviders(intent, resolvedType, flags, 8452 pkg.providers, userId), 8453 instantAppPkgName); 8454 } 8455 return Collections.emptyList(); 8456 } 8457 } 8458 8459 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 8460 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 8461 if (instantAppPkgName == null) { 8462 return resolveInfos; 8463 } 8464 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8465 final ResolveInfo info = resolveInfos.get(i); 8466 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 8467 // allow providers that are defined in the provided package 8468 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 8469 if (info.providerInfo.splitName != null 8470 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 8471 info.providerInfo.splitName)) { 8472 // requested provider is defined in a split that hasn't been installed yet. 8473 // add the installer to the resolve list 8474 if (DEBUG_INSTANT) { 8475 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8476 } 8477 final ResolveInfo installerInfo = new ResolveInfo( 8478 mInstantAppInstallerInfo); 8479 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8480 null /*failureActivity*/, 8481 info.providerInfo.packageName, 8482 info.providerInfo.applicationInfo.longVersionCode, 8483 info.providerInfo.splitName); 8484 // add a non-generic filter 8485 installerInfo.filter = new IntentFilter(); 8486 // load resources from the correct package 8487 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8488 resolveInfos.set(i, installerInfo); 8489 } 8490 continue; 8491 } 8492 // allow providers that have been explicitly exposed to instant applications 8493 if (!isEphemeralApp 8494 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8495 continue; 8496 } 8497 resolveInfos.remove(i); 8498 } 8499 return resolveInfos; 8500 } 8501 8502 @Override 8503 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 8504 final int callingUid = Binder.getCallingUid(); 8505 if (getInstantAppPackageName(callingUid) != null) { 8506 return ParceledListSlice.emptyList(); 8507 } 8508 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8509 flags = updateFlagsForPackage(flags, userId, null); 8510 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8511 final boolean listApex = (flags & MATCH_APEX) != 0; 8512 final boolean listFactory = (flags & MATCH_FACTORY_ONLY) != 0; 8513 8514 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8515 false /* requireFullPermission */, false /* checkShell */, 8516 "get installed packages"); 8517 8518 // writer 8519 synchronized (mPackages) { 8520 ArrayList<PackageInfo> list; 8521 if (listUninstalled) { 8522 list = new ArrayList<>(mSettings.mPackages.size()); 8523 for (PackageSetting ps : mSettings.mPackages.values()) { 8524 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8525 continue; 8526 } 8527 if (filterAppAccessLPr(ps, callingUid, userId)) { 8528 continue; 8529 } 8530 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8531 if (pi != null) { 8532 list.add(pi); 8533 } 8534 } 8535 } else { 8536 list = new ArrayList<>(mPackages.size()); 8537 for (PackageParser.Package p : mPackages.values()) { 8538 final PackageSetting ps = (PackageSetting) p.mExtras; 8539 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8540 continue; 8541 } 8542 if (filterAppAccessLPr(ps, callingUid, userId)) { 8543 continue; 8544 } 8545 final PackageInfo pi = generatePackageInfo((PackageSetting) 8546 p.mExtras, flags, userId); 8547 if (pi != null) { 8548 list.add(pi); 8549 } 8550 } 8551 } 8552 if (listApex) { 8553 if (listFactory) { 8554 list.addAll(mApexManager.getFactoryPackages()); 8555 } else { 8556 list.addAll(mApexManager.getActivePackages()); 8557 } 8558 if (listUninstalled) { 8559 list.addAll(mApexManager.getInactivePackages()); 8560 } 8561 } 8562 return new ParceledListSlice<>(list); 8563 } 8564 } 8565 8566 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 8567 String[] permissions, boolean[] tmp, int flags, int userId) { 8568 int numMatch = 0; 8569 final PermissionsState permissionsState = ps.getPermissionsState(); 8570 for (int i=0; i<permissions.length; i++) { 8571 final String permission = permissions[i]; 8572 if (permissionsState.hasPermission(permission, userId)) { 8573 tmp[i] = true; 8574 numMatch++; 8575 } else { 8576 tmp[i] = false; 8577 } 8578 } 8579 if (numMatch == 0) { 8580 return; 8581 } 8582 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8583 8584 // The above might return null in cases of uninstalled apps or install-state 8585 // skew across users/profiles. 8586 if (pi != null) { 8587 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 8588 if (numMatch == permissions.length) { 8589 pi.requestedPermissions = permissions; 8590 } else { 8591 pi.requestedPermissions = new String[numMatch]; 8592 numMatch = 0; 8593 for (int i=0; i<permissions.length; i++) { 8594 if (tmp[i]) { 8595 pi.requestedPermissions[numMatch] = permissions[i]; 8596 numMatch++; 8597 } 8598 } 8599 } 8600 } 8601 list.add(pi); 8602 } 8603 } 8604 8605 @Override 8606 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8607 String[] permissions, int flags, int userId) { 8608 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8609 flags = updateFlagsForPackage(flags, userId, permissions); 8610 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8611 true /* requireFullPermission */, false /* checkShell */, 8612 "get packages holding permissions"); 8613 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8614 8615 // writer 8616 synchronized (mPackages) { 8617 ArrayList<PackageInfo> list = new ArrayList<>(); 8618 boolean[] tmpBools = new boolean[permissions.length]; 8619 if (listUninstalled) { 8620 for (PackageSetting ps : mSettings.mPackages.values()) { 8621 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8622 userId); 8623 } 8624 } else { 8625 for (PackageParser.Package pkg : mPackages.values()) { 8626 PackageSetting ps = (PackageSetting)pkg.mExtras; 8627 if (ps != null) { 8628 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8629 userId); 8630 } 8631 } 8632 } 8633 8634 return new ParceledListSlice<>(list); 8635 } 8636 } 8637 8638 @Override 8639 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8640 final int callingUid = Binder.getCallingUid(); 8641 return new ParceledListSlice<>( 8642 getInstalledApplicationsListInternal(flags, userId, callingUid)); 8643 } 8644 8645 private List<ApplicationInfo> getInstalledApplicationsListInternal(int flags, int userId, 8646 int callingUid) { 8647 if (getInstantAppPackageName(callingUid) != null) { 8648 return Collections.emptyList(); 8649 } 8650 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8651 flags = updateFlagsForApplication(flags, userId, null); 8652 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8653 8654 mPermissionManager.enforceCrossUserPermission( 8655 callingUid, 8656 userId, 8657 false /* requireFullPermission */, 8658 false /* checkShell */, 8659 "get installed application info"); 8660 8661 // writer 8662 synchronized (mPackages) { 8663 ArrayList<ApplicationInfo> list; 8664 if (listUninstalled) { 8665 list = new ArrayList<>(mSettings.mPackages.size()); 8666 for (PackageSetting ps : mSettings.mPackages.values()) { 8667 ApplicationInfo ai; 8668 int effectiveFlags = flags; 8669 if (ps.isSystem()) { 8670 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8671 } 8672 if (ps.pkg != null) { 8673 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8674 continue; 8675 } 8676 if (filterAppAccessLPr(ps, callingUid, userId)) { 8677 continue; 8678 } 8679 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8680 ps.readUserState(userId), userId); 8681 if (ai != null) { 8682 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8683 } 8684 } else { 8685 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8686 // and already converts to externally visible package name 8687 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8688 callingUid, effectiveFlags, userId); 8689 } 8690 if (ai != null) { 8691 list.add(ai); 8692 } 8693 } 8694 } else { 8695 list = new ArrayList<>(mPackages.size()); 8696 for (PackageParser.Package p : mPackages.values()) { 8697 if (p.mExtras != null) { 8698 PackageSetting ps = (PackageSetting) p.mExtras; 8699 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8700 continue; 8701 } 8702 if (filterAppAccessLPr(ps, callingUid, userId)) { 8703 continue; 8704 } 8705 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8706 ps.readUserState(userId), userId); 8707 if (ai != null) { 8708 ai.packageName = resolveExternalPackageNameLPr(p); 8709 list.add(ai); 8710 } 8711 } 8712 } 8713 } 8714 8715 return list; 8716 } 8717 } 8718 8719 @Override 8720 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8721 if (HIDE_EPHEMERAL_APIS) { 8722 return null; 8723 } 8724 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8725 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8726 "getEphemeralApplications"); 8727 } 8728 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8729 true /* requireFullPermission */, false /* checkShell */, 8730 "getEphemeralApplications"); 8731 synchronized (mPackages) { 8732 List<InstantAppInfo> instantApps = mInstantAppRegistry 8733 .getInstantAppsLPr(userId); 8734 if (instantApps != null) { 8735 return new ParceledListSlice<>(instantApps); 8736 } 8737 } 8738 return null; 8739 } 8740 8741 @Override 8742 public boolean isInstantApp(String packageName, int userId) { 8743 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8744 true /* requireFullPermission */, false /* checkShell */, 8745 "isInstantApp"); 8746 if (HIDE_EPHEMERAL_APIS) { 8747 return false; 8748 } 8749 8750 synchronized (mPackages) { 8751 int callingUid = Binder.getCallingUid(); 8752 if (Process.isIsolated(callingUid)) { 8753 callingUid = mIsolatedOwners.get(callingUid); 8754 } 8755 final PackageSetting ps = mSettings.mPackages.get(packageName); 8756 PackageParser.Package pkg = mPackages.get(packageName); 8757 final boolean returnAllowed = 8758 ps != null 8759 && (isCallerSameApp(packageName, callingUid) 8760 || canViewInstantApps(callingUid, userId) 8761 || mInstantAppRegistry.isInstantAccessGranted( 8762 userId, UserHandle.getAppId(callingUid), ps.appId)); 8763 if (returnAllowed) { 8764 return ps.getInstantApp(userId); 8765 } 8766 } 8767 return false; 8768 } 8769 8770 @Override 8771 public byte[] getInstantAppCookie(String packageName, int userId) { 8772 if (HIDE_EPHEMERAL_APIS) { 8773 return null; 8774 } 8775 8776 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8777 true /* requireFullPermission */, false /* checkShell */, 8778 "getInstantAppCookie"); 8779 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8780 return null; 8781 } 8782 synchronized (mPackages) { 8783 return mInstantAppRegistry.getInstantAppCookieLPw( 8784 packageName, userId); 8785 } 8786 } 8787 8788 @Override 8789 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8790 if (HIDE_EPHEMERAL_APIS) { 8791 return true; 8792 } 8793 8794 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8795 true /* requireFullPermission */, true /* checkShell */, 8796 "setInstantAppCookie"); 8797 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8798 return false; 8799 } 8800 synchronized (mPackages) { 8801 return mInstantAppRegistry.setInstantAppCookieLPw( 8802 packageName, cookie, userId); 8803 } 8804 } 8805 8806 @Override 8807 public Bitmap getInstantAppIcon(String packageName, int userId) { 8808 if (HIDE_EPHEMERAL_APIS) { 8809 return null; 8810 } 8811 8812 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8813 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8814 "getInstantAppIcon"); 8815 } 8816 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8817 true /* requireFullPermission */, false /* checkShell */, 8818 "getInstantAppIcon"); 8819 8820 synchronized (mPackages) { 8821 return mInstantAppRegistry.getInstantAppIconLPw( 8822 packageName, userId); 8823 } 8824 } 8825 8826 private boolean isCallerSameApp(String packageName, int uid) { 8827 PackageParser.Package pkg = mPackages.get(packageName); 8828 return pkg != null 8829 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8830 } 8831 8832 @Override 8833 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8834 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8835 return ParceledListSlice.emptyList(); 8836 } 8837 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8838 } 8839 8840 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8841 final ArrayList<ApplicationInfo> finalList = new ArrayList<>(); 8842 8843 // reader 8844 synchronized (mPackages) { 8845 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8846 final int userId = UserHandle.getCallingUserId(); 8847 while (i.hasNext()) { 8848 final PackageParser.Package p = i.next(); 8849 if (p.applicationInfo == null) continue; 8850 8851 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8852 && !p.applicationInfo.isDirectBootAware(); 8853 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8854 && p.applicationInfo.isDirectBootAware(); 8855 8856 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8857 && (!mSafeMode || isSystemApp(p)) 8858 && (matchesUnaware || matchesAware)) { 8859 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8860 if (ps != null) { 8861 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8862 ps.readUserState(userId), userId); 8863 if (ai != null) { 8864 finalList.add(ai); 8865 } 8866 } 8867 } 8868 } 8869 } 8870 8871 return finalList; 8872 } 8873 8874 @Override 8875 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8876 return resolveContentProviderInternal(name, flags, userId); 8877 } 8878 8879 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8880 if (!sUserManager.exists(userId)) return null; 8881 flags = updateFlagsForComponent(flags, userId, name); 8882 final int callingUid = Binder.getCallingUid(); 8883 final ProviderInfo providerInfo = mComponentResolver.queryProvider(name, flags, userId); 8884 if (providerInfo == null) { 8885 return null; 8886 } 8887 if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) { 8888 return null; 8889 } 8890 synchronized (mPackages) { 8891 final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName); 8892 final ComponentName component = 8893 new ComponentName(providerInfo.packageName, providerInfo.name); 8894 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8895 return null; 8896 } 8897 return providerInfo; 8898 } 8899 } 8900 8901 /** 8902 * @deprecated 8903 */ 8904 @Deprecated 8905 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8906 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8907 return; 8908 } 8909 mComponentResolver.querySyncProviders( 8910 outNames, outInfo, mSafeMode, UserHandle.getCallingUserId()); 8911 } 8912 8913 @Override 8914 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8915 int uid, int flags, String metaDataKey) { 8916 final int callingUid = Binder.getCallingUid(); 8917 final int userId = processName != null ? UserHandle.getUserId(uid) 8918 : UserHandle.getCallingUserId(); 8919 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8920 flags = updateFlagsForComponent(flags, userId, processName); 8921 ArrayList<ProviderInfo> finalList = null; 8922 final List<ProviderInfo> matchList = 8923 mComponentResolver.queryProviders(processName, metaDataKey, uid, flags, userId); 8924 final int listSize = (matchList == null ? 0 : matchList.size()); 8925 synchronized (mPackages) { 8926 for (int i = 0; i < listSize; i++) { 8927 final ProviderInfo providerInfo = matchList.get(i); 8928 if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) { 8929 continue; 8930 } 8931 final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName); 8932 final ComponentName component = 8933 new ComponentName(providerInfo.packageName, providerInfo.name); 8934 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8935 continue; 8936 } 8937 if (finalList == null) { 8938 finalList = new ArrayList<>(listSize - i); 8939 } 8940 finalList.add(providerInfo); 8941 } 8942 } 8943 8944 if (finalList != null) { 8945 finalList.sort(sProviderInitOrderSorter); 8946 return new ParceledListSlice<>(finalList); 8947 } 8948 8949 return ParceledListSlice.emptyList(); 8950 } 8951 8952 @Override 8953 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8954 // reader 8955 synchronized (mPackages) { 8956 final int callingUid = Binder.getCallingUid(); 8957 final int callingUserId = UserHandle.getUserId(callingUid); 8958 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8959 if (ps == null) return null; 8960 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8961 return null; 8962 } 8963 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8964 return PackageParser.generateInstrumentationInfo(i, flags); 8965 } 8966 } 8967 8968 @Override 8969 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8970 String targetPackage, int flags) { 8971 final int callingUid = Binder.getCallingUid(); 8972 final int callingUserId = UserHandle.getUserId(callingUid); 8973 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8974 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8975 return ParceledListSlice.emptyList(); 8976 } 8977 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8978 } 8979 8980 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8981 int flags) { 8982 ArrayList<InstrumentationInfo> finalList = new ArrayList<>(); 8983 8984 // reader 8985 synchronized (mPackages) { 8986 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8987 while (i.hasNext()) { 8988 final PackageParser.Instrumentation p = i.next(); 8989 if (targetPackage == null 8990 || targetPackage.equals(p.info.targetPackage)) { 8991 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8992 flags); 8993 if (ii != null) { 8994 finalList.add(ii); 8995 } 8996 } 8997 } 8998 } 8999 9000 return finalList; 9001 } 9002 9003 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 9004 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 9005 try { 9006 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 9007 } finally { 9008 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9009 } 9010 } 9011 9012 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 9013 final File[] files = scanDir.listFiles(); 9014 if (ArrayUtils.isEmpty(files)) { 9015 Log.d(TAG, "No files in app dir " + scanDir); 9016 return; 9017 } 9018 9019 if (DEBUG_PACKAGE_SCANNING) { 9020 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 9021 + " flags=0x" + Integer.toHexString(parseFlags)); 9022 } 9023 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 9024 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 9025 mParallelPackageParserCallback)) { 9026 // Submit files for parsing in parallel 9027 int fileCount = 0; 9028 for (File file : files) { 9029 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 9030 && !PackageInstallerService.isStageName(file.getName()); 9031 if (!isPackage) { 9032 // Ignore entries which are not packages 9033 continue; 9034 } 9035 parallelPackageParser.submit(file, parseFlags); 9036 fileCount++; 9037 } 9038 9039 // Process results one by one 9040 for (; fileCount > 0; fileCount--) { 9041 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 9042 Throwable throwable = parseResult.throwable; 9043 int errorCode = PackageManager.INSTALL_SUCCEEDED; 9044 9045 if (throwable == null) { 9046 // TODO(toddke): move lower in the scan chain 9047 // Static shared libraries have synthetic package names 9048 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 9049 renameStaticSharedLibraryPackage(parseResult.pkg); 9050 } 9051 try { 9052 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 9053 currentTime, null); 9054 } catch (PackageManagerException e) { 9055 errorCode = e.error; 9056 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 9057 } 9058 } else if (throwable instanceof PackageParser.PackageParserException) { 9059 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 9060 throwable; 9061 errorCode = e.error; 9062 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 9063 } else { 9064 throw new IllegalStateException("Unexpected exception occurred while parsing " 9065 + parseResult.scanFile, throwable); 9066 } 9067 9068 // Delete invalid userdata apps 9069 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 9070 errorCode != PackageManager.INSTALL_SUCCEEDED) { 9071 logCriticalInfo(Log.WARN, 9072 "Deleting invalid package at " + parseResult.scanFile); 9073 removeCodePathLI(parseResult.scanFile); 9074 } 9075 } 9076 } 9077 } 9078 9079 public static void reportSettingsProblem(int priority, String msg) { 9080 logCriticalInfo(priority, msg); 9081 } 9082 9083 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 9084 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 9085 // When upgrading from pre-N MR1, verify the package time stamp using the package 9086 // directory and not the APK file. 9087 final long lastModifiedTime = mIsPreNMR1Upgrade 9088 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 9089 final VersionInfo settingsVersionForPackage = getSettingsVersionForPackage(pkg); 9090 if (ps != null && !forceCollect 9091 && ps.codePathString.equals(pkg.codePath) 9092 && ps.timeStamp == lastModifiedTime 9093 && !isCompatSignatureUpdateNeeded(settingsVersionForPackage) 9094 && !isRecoverSignatureUpdateNeeded(settingsVersionForPackage)) { 9095 if (ps.signatures.mSigningDetails.signatures != null 9096 && ps.signatures.mSigningDetails.signatures.length != 0 9097 && ps.signatures.mSigningDetails.signatureSchemeVersion 9098 != SignatureSchemeVersion.UNKNOWN) { 9099 // Optimization: reuse the existing cached signing data 9100 // if the package appears to be unchanged. 9101 pkg.mSigningDetails = 9102 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 9103 return; 9104 } 9105 9106 Slog.w(TAG, "PackageSetting for " + ps.name 9107 + " is missing signatures. Collecting certs again to recover them."); 9108 } else { 9109 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 9110 (forceCollect ? " (forced)" : "")); 9111 } 9112 9113 try { 9114 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 9115 PackageParser.collectCertificates(pkg, skipVerify); 9116 } catch (PackageParserException e) { 9117 throw PackageManagerException.from(e); 9118 } finally { 9119 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9120 } 9121 } 9122 9123 /** 9124 * Clear the package profile if this was an upgrade and the package 9125 * version was updated. 9126 */ 9127 private void maybeClearProfilesForUpgradesLI( 9128 @Nullable PackageSetting originalPkgSetting, 9129 @NonNull PackageParser.Package currentPkg) { 9130 if (originalPkgSetting == null || !isDeviceUpgrading()) { 9131 return; 9132 } 9133 if (originalPkgSetting.versionCode == currentPkg.mVersionCode) { 9134 return; 9135 } 9136 9137 clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL); 9138 if (DEBUG_INSTALL) { 9139 Slog.d(TAG, originalPkgSetting.name 9140 + " clear profile due to version change " 9141 + originalPkgSetting.versionCode + " != " 9142 + currentPkg.mVersionCode); 9143 } 9144 } 9145 9146 /** 9147 * Traces a package scan. 9148 * @see #scanPackageLI(File, int, int, long, UserHandle) 9149 */ 9150 @GuardedBy({"mInstallLock", "mPackages"}) 9151 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 9152 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 9153 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 9154 try { 9155 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 9156 } finally { 9157 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9158 } 9159 } 9160 9161 /** 9162 * Scans a package and returns the newly parsed package. 9163 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 9164 */ 9165 @GuardedBy({"mInstallLock", "mPackages"}) 9166 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 9167 long currentTime, UserHandle user) throws PackageManagerException { 9168 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 9169 PackageParser pp = new PackageParser(); 9170 pp.setSeparateProcesses(mSeparateProcesses); 9171 pp.setOnlyCoreApps(mOnlyCore); 9172 pp.setDisplayMetrics(mMetrics); 9173 pp.setCallback(mPackageParserCallback); 9174 9175 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 9176 final PackageParser.Package pkg; 9177 try { 9178 pkg = pp.parsePackage(scanFile, parseFlags); 9179 } catch (PackageParserException e) { 9180 throw PackageManagerException.from(e); 9181 } finally { 9182 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9183 } 9184 9185 // Static shared libraries have synthetic package names 9186 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9187 renameStaticSharedLibraryPackage(pkg); 9188 } 9189 9190 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 9191 } 9192 9193 /** 9194 * Scans a package and returns the newly parsed package. 9195 * @throws PackageManagerException on a parse error. 9196 */ 9197 @GuardedBy({"mInstallLock", "mPackages"}) 9198 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 9199 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9200 @Nullable UserHandle user) 9201 throws PackageManagerException { 9202 // If the package has children and this is the first dive in the function 9203 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 9204 // packages (parent and children) would be successfully scanned before the 9205 // actual scan since scanning mutates internal state and we want to atomically 9206 // install the package and its children. 9207 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9208 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9209 scanFlags |= SCAN_CHECK_ONLY; 9210 } 9211 } else { 9212 scanFlags &= ~SCAN_CHECK_ONLY; 9213 } 9214 9215 // Scan the parent 9216 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 9217 scanFlags, currentTime, user); 9218 9219 // Scan the children 9220 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9221 for (int i = 0; i < childCount; i++) { 9222 PackageParser.Package childPackage = pkg.childPackages.get(i); 9223 addForInitLI(childPackage, parseFlags, scanFlags, 9224 currentTime, user); 9225 } 9226 9227 9228 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9229 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 9230 } 9231 9232 return scannedPkg; 9233 } 9234 9235 /** 9236 * Returns if forced apk verification can be skipped for the whole package, including splits. 9237 */ 9238 private boolean canSkipForcedPackageVerification(PackageParser.Package pkg) { 9239 if (!canSkipForcedApkVerification(pkg.baseCodePath)) { 9240 return false; 9241 } 9242 // TODO: Allow base and splits to be verified individually. 9243 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9244 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9245 if (!canSkipForcedApkVerification(pkg.splitCodePaths[i])) { 9246 return false; 9247 } 9248 } 9249 } 9250 return true; 9251 } 9252 9253 /** 9254 * Returns if forced apk verification can be skipped, depending on current FSVerity setup and 9255 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 9256 * match one in a trusted source, and should be done separately. 9257 */ 9258 private boolean canSkipForcedApkVerification(String apkPath) { 9259 if (!PackageManagerServiceUtils.isLegacyApkVerityEnabled()) { 9260 return VerityUtils.hasFsverity(apkPath); 9261 } 9262 9263 try { 9264 final byte[] rootHashObserved = VerityUtils.generateApkVerityRootHash(apkPath); 9265 if (rootHashObserved == null) { 9266 return false; // APK does not contain Merkle tree root hash. 9267 } 9268 synchronized (mInstallLock) { 9269 // Returns whether the observed root hash matches what kernel has. 9270 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 9271 return true; 9272 } 9273 } catch (InstallerException | IOException | DigestException | 9274 NoSuchAlgorithmException e) { 9275 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 9276 } 9277 return false; 9278 } 9279 9280 /** 9281 * Adds a new package to the internal data structures during platform initialization. 9282 * <p>After adding, the package is known to the system and available for querying. 9283 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 9284 * etc...], additional checks are performed. Basic verification [such as ensuring 9285 * matching signatures, checking version codes, etc...] occurs if the package is 9286 * identical to a previously known package. If the package fails a signature check, 9287 * the version installed on /data will be removed. If the version of the new package 9288 * is less than or equal than the version on /data, it will be ignored. 9289 * <p>Regardless of the package location, the results are applied to the internal 9290 * structures and the package is made available to the rest of the system. 9291 * <p>NOTE: The return value should be removed. It's the passed in package object. 9292 */ 9293 @GuardedBy({"mInstallLock", "mPackages"}) 9294 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 9295 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9296 @Nullable UserHandle user) 9297 throws PackageManagerException { 9298 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 9299 final String renamedPkgName; 9300 final PackageSetting disabledPkgSetting; 9301 final boolean isSystemPkgUpdated; 9302 final boolean pkgAlreadyExists; 9303 PackageSetting pkgSetting; 9304 9305 // NOTE: installPackageLI() has the same code to setup the package's 9306 // application info. This probably should be done lower in the call 9307 // stack [such as scanPackageOnly()]. However, we verify the application 9308 // info prior to that [in scanPackageNew()] and thus have to setup 9309 // the application info early. 9310 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 9311 pkg.setApplicationInfoCodePath(pkg.codePath); 9312 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 9313 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 9314 pkg.setApplicationInfoResourcePath(pkg.codePath); 9315 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 9316 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 9317 9318 synchronized (mPackages) { 9319 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9320 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9321 if (realPkgName != null) { 9322 ensurePackageRenamed(pkg, renamedPkgName); 9323 } 9324 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9325 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 9326 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 9327 pkgAlreadyExists = pkgSetting != null; 9328 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 9329 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 9330 isSystemPkgUpdated = disabledPkgSetting != null; 9331 9332 if (DEBUG_INSTALL && isSystemPkgUpdated) { 9333 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 9334 } 9335 9336 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 9337 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 9338 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 9339 : null; 9340 if (DEBUG_PACKAGE_SCANNING 9341 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 9342 && sharedUserSetting != null) { 9343 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9344 + " (uid=" + sharedUserSetting.userId + "):" 9345 + " packages=" + sharedUserSetting.packages); 9346 } 9347 9348 if (scanSystemPartition) { 9349 // Potentially prune child packages. If the application on the /system 9350 // partition has been updated via OTA, but, is still disabled by a 9351 // version on /data, cycle through all of its children packages and 9352 // remove children that are no longer defined. 9353 if (isSystemPkgUpdated) { 9354 final int scannedChildCount = (pkg.childPackages != null) 9355 ? pkg.childPackages.size() : 0; 9356 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 9357 ? disabledPkgSetting.childPackageNames.size() : 0; 9358 for (int i = 0; i < disabledChildCount; i++) { 9359 String disabledChildPackageName = 9360 disabledPkgSetting.childPackageNames.get(i); 9361 boolean disabledPackageAvailable = false; 9362 for (int j = 0; j < scannedChildCount; j++) { 9363 PackageParser.Package childPkg = pkg.childPackages.get(j); 9364 if (childPkg.packageName.equals(disabledChildPackageName)) { 9365 disabledPackageAvailable = true; 9366 break; 9367 } 9368 } 9369 if (!disabledPackageAvailable) { 9370 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 9371 } 9372 } 9373 // we're updating the disabled package, so, scan it as the package setting 9374 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null, 9375 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 9376 null /* originalPkgSetting */, null, parseFlags, scanFlags, 9377 (pkg == mPlatformPackage), user); 9378 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 9379 final ScanResult scanResult = scanPackageOnlyLI(request, mFactoryTest, -1L); 9380 if (scanResult.existingSettingCopied && scanResult.request.pkgSetting != null) { 9381 scanResult.request.pkgSetting.updateFrom(scanResult.pkgSetting); 9382 } 9383 } 9384 } 9385 } 9386 9387 final boolean newPkgChangedPaths = 9388 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 9389 final boolean newPkgVersionGreater = 9390 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 9391 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 9392 && newPkgChangedPaths && newPkgVersionGreater; 9393 if (isSystemPkgBetter) { 9394 // The version of the application on /system is greater than the version on 9395 // /data. Switch back to the application on /system. 9396 // It's safe to assume the application on /system will correctly scan. If not, 9397 // there won't be a working copy of the application. 9398 synchronized (mPackages) { 9399 // just remove the loaded entries from package lists 9400 mPackages.remove(pkgSetting.name); 9401 } 9402 9403 logCriticalInfo(Log.WARN, 9404 "System package updated;" 9405 + " name: " + pkgSetting.name 9406 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 9407 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 9408 9409 final InstallArgs args = createInstallArgsForExisting( 9410 pkgSetting.codePathString, 9411 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 9412 args.cleanUpResourcesLI(); 9413 synchronized (mPackages) { 9414 mSettings.enableSystemPackageLPw(pkgSetting.name); 9415 } 9416 } 9417 9418 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 9419 // The version of the application on the /system partition is less than or 9420 // equal to the version on the /data partition. Throw an exception and use 9421 // the application already installed on the /data partition. 9422 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 9423 + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode 9424 + " better than this " + pkg.getLongVersionCode()); 9425 } 9426 9427 // Verify certificates against what was last scanned. If there was an upgrade and this is an 9428 // app in a system partition, or if this is an updated priv app, we will force re-collecting 9429 // certificate. 9430 final boolean forceCollect = (mIsUpgrade && scanSystemPartition) 9431 || PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting); 9432 // Full APK verification can be skipped during certificate collection, only if the file is 9433 // in verified partition, or can be verified on access (when apk verity is enabled). In both 9434 // cases, only data in Signing Block is verified instead of the whole file. 9435 final boolean skipVerify = scanSystemPartition 9436 || (forceCollect && canSkipForcedPackageVerification(pkg)); 9437 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 9438 9439 // Reset profile if the application version is changed 9440 maybeClearProfilesForUpgradesLI(pkgSetting, pkg); 9441 9442 /* 9443 * A new system app appeared, but we already had a non-system one of the 9444 * same name installed earlier. 9445 */ 9446 boolean shouldHideSystemApp = false; 9447 // A new application appeared on /system, but, we already have a copy of 9448 // the application installed on /data. 9449 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 9450 && !pkgSetting.isSystem()) { 9451 9452 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 9453 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA) 9454 && !pkgSetting.signatures.mSigningDetails.checkCapability( 9455 pkg.mSigningDetails, 9456 PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) { 9457 logCriticalInfo(Log.WARN, 9458 "System package signature mismatch;" 9459 + " name: " + pkgSetting.name); 9460 try (PackageFreezer freezer = freezePackage(pkg.packageName, 9461 "scanPackageInternalLI")) { 9462 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 9463 } 9464 pkgSetting = null; 9465 } else if (newPkgVersionGreater) { 9466 // The application on /system is newer than the application on /data. 9467 // Simply remove the application on /data [keeping application data] 9468 // and replace it with the version on /system. 9469 logCriticalInfo(Log.WARN, 9470 "System package enabled;" 9471 + " name: " + pkgSetting.name 9472 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 9473 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 9474 InstallArgs args = createInstallArgsForExisting( 9475 pkgSetting.codePathString, 9476 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 9477 synchronized (mInstallLock) { 9478 args.cleanUpResourcesLI(); 9479 } 9480 } else { 9481 // The application on /system is older than the application on /data. Hide 9482 // the application on /system and the version on /data will be scanned later 9483 // and re-added like an update. 9484 shouldHideSystemApp = true; 9485 logCriticalInfo(Log.INFO, 9486 "System package disabled;" 9487 + " name: " + pkgSetting.name 9488 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 9489 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 9490 } 9491 } 9492 9493 final ScanResult scanResult = scanPackageNewLI(pkg, parseFlags, scanFlags 9494 | SCAN_UPDATE_SIGNATURE, currentTime, user); 9495 if (scanResult.success) { 9496 synchronized (mPackages) { 9497 boolean appIdCreated = false; 9498 try { 9499 final String pkgName = scanResult.pkgSetting.name; 9500 final Map<String, ReconciledPackage> reconcileResult = reconcilePackagesLocked( 9501 new ReconcileRequest( 9502 Collections.singletonMap(pkgName, scanResult), 9503 mSharedLibraries, 9504 mPackages, 9505 Collections.singletonMap( 9506 pkgName, getSettingsVersionForPackage(pkg)), 9507 Collections.singletonMap(pkgName, 9508 getSharedLibLatestVersionSetting(scanResult))), 9509 mSettings.mKeySetManagerService); 9510 appIdCreated = optimisticallyRegisterAppId(scanResult); 9511 commitReconciledScanResultLocked(reconcileResult.get(pkgName)); 9512 } catch (PackageManagerException e) { 9513 if (appIdCreated) { 9514 cleanUpAppIdCreation(scanResult); 9515 } 9516 throw e; 9517 } 9518 } 9519 } 9520 9521 if (shouldHideSystemApp) { 9522 synchronized (mPackages) { 9523 mSettings.disableSystemPackageLPw(pkg.packageName, true); 9524 } 9525 } 9526 return scanResult.pkgSetting.pkg; 9527 } 9528 9529 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 9530 // Derive the new package synthetic package name 9531 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 9532 + pkg.staticSharedLibVersion); 9533 } 9534 9535 static String fixProcessName(String defProcessName, String processName) { 9536 if (processName == null) { 9537 return defProcessName; 9538 } 9539 return processName; 9540 } 9541 9542 /** 9543 * Enforces that only the system UID or root's UID can call a method exposed 9544 * via Binder. 9545 * 9546 * @param message used as message if SecurityException is thrown 9547 * @throws SecurityException if the caller is not system or root 9548 */ 9549 private static void enforceSystemOrRoot(String message) { 9550 final int uid = Binder.getCallingUid(); 9551 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9552 throw new SecurityException(message); 9553 } 9554 } 9555 9556 /** 9557 * Enforces that only the system UID or root's UID or shell's UID can call 9558 * a method exposed via Binder. 9559 * 9560 * @param message used as message if SecurityException is thrown 9561 * @throws SecurityException if the caller is not system or shell 9562 */ 9563 private static void enforceSystemOrRootOrShell(String message) { 9564 final int uid = Binder.getCallingUid(); 9565 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID && uid != Process.SHELL_UID) { 9566 throw new SecurityException(message); 9567 } 9568 } 9569 9570 @Override 9571 public void performFstrimIfNeeded() { 9572 enforceSystemOrRoot("Only the system can request fstrim"); 9573 9574 // Before everything else, see whether we need to fstrim. 9575 try { 9576 IStorageManager sm = PackageHelper.getStorageManager(); 9577 if (sm != null) { 9578 boolean doTrim = false; 9579 final long interval = android.provider.Settings.Global.getLong( 9580 mContext.getContentResolver(), 9581 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9582 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9583 if (interval > 0) { 9584 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9585 if (timeSinceLast > interval) { 9586 doTrim = true; 9587 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9588 + "; running immediately"); 9589 } 9590 } 9591 if (doTrim) { 9592 final boolean dexOptDialogShown; 9593 synchronized (mPackages) { 9594 dexOptDialogShown = mDexOptDialogShown; 9595 } 9596 if (!isFirstBoot() && dexOptDialogShown) { 9597 try { 9598 ActivityManager.getService().showBootMessage( 9599 mContext.getResources().getString( 9600 R.string.android_upgrading_fstrim), true); 9601 } catch (RemoteException e) { 9602 } 9603 } 9604 sm.runMaintenance(); 9605 } 9606 } else { 9607 Slog.e(TAG, "storageManager service unavailable!"); 9608 } 9609 } catch (RemoteException e) { 9610 // Can't happen; StorageManagerService is local 9611 } 9612 } 9613 9614 @Override 9615 public void updatePackagesIfNeeded() { 9616 enforceSystemOrRoot("Only the system can request package update"); 9617 9618 // We need to re-extract after an OTA. 9619 boolean causeUpgrade = isDeviceUpgrading(); 9620 9621 // First boot or factory reset. 9622 // Note: we also handle devices that are upgrading to N right now as if it is their 9623 // first boot, as they do not have profile data. 9624 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9625 9626 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9627 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9628 9629 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9630 return; 9631 } 9632 9633 List<PackageParser.Package> pkgs; 9634 synchronized (mPackages) { 9635 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9636 } 9637 9638 final long startTime = System.nanoTime(); 9639 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9640 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 9641 false /* bootComplete */); 9642 9643 final int elapsedTimeSeconds = 9644 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9645 9646 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9647 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9648 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9649 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9650 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9651 } 9652 9653 /* 9654 * Return the prebuilt profile path given a package base code path. 9655 */ 9656 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 9657 return pkg.baseCodePath + ".prof"; 9658 } 9659 9660 /** 9661 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9662 * containing statistics about the invocation. The array consists of three elements, 9663 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9664 * and {@code numberOfPackagesFailed}. 9665 */ 9666 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9667 final int compilationReason, boolean bootComplete) { 9668 9669 int numberOfPackagesVisited = 0; 9670 int numberOfPackagesOptimized = 0; 9671 int numberOfPackagesSkipped = 0; 9672 int numberOfPackagesFailed = 0; 9673 final int numberOfPackagesToDexopt = pkgs.size(); 9674 9675 for (PackageParser.Package pkg : pkgs) { 9676 numberOfPackagesVisited++; 9677 9678 boolean useProfileForDexopt = false; 9679 9680 if ((isFirstBoot() || isDeviceUpgrading()) && isSystemApp(pkg)) { 9681 // Copy over initial preopt profiles since we won't get any JIT samples for methods 9682 // that are already compiled. 9683 File profileFile = new File(getPrebuildProfilePath(pkg)); 9684 // Copy profile if it exists. 9685 if (profileFile.exists()) { 9686 try { 9687 // We could also do this lazily before calling dexopt in 9688 // PackageDexOptimizer to prevent this happening on first boot. The issue 9689 // is that we don't have a good way to say "do this only once". 9690 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9691 pkg.applicationInfo.uid, pkg.packageName, 9692 ArtManager.getProfileName(null))) { 9693 Log.e(TAG, "Installer failed to copy system profile!"); 9694 } else { 9695 // Disabled as this causes speed-profile compilation during first boot 9696 // even if things are already compiled. 9697 // useProfileForDexopt = true; 9698 } 9699 } catch (Exception e) { 9700 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 9701 e); 9702 } 9703 } else { 9704 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9705 // Handle compressed APKs in this path. Only do this for stubs with profiles to 9706 // minimize the number off apps being speed-profile compiled during first boot. 9707 // The other paths will not change the filter. 9708 if (disabledPs != null && disabledPs.pkg.isStub) { 9709 // The package is the stub one, remove the stub suffix to get the normal 9710 // package and APK names. 9711 String systemProfilePath = 9712 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9713 profileFile = new File(systemProfilePath); 9714 // If we have a profile for a compressed APK, copy it to the reference 9715 // location. 9716 // Note that copying the profile here will cause it to override the 9717 // reference profile every OTA even though the existing reference profile 9718 // may have more data. We can't copy during decompression since the 9719 // directories are not set up at that point. 9720 if (profileFile.exists()) { 9721 try { 9722 // We could also do this lazily before calling dexopt in 9723 // PackageDexOptimizer to prevent this happening on first boot. The 9724 // issue is that we don't have a good way to say "do this only 9725 // once". 9726 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9727 pkg.applicationInfo.uid, pkg.packageName, 9728 ArtManager.getProfileName(null))) { 9729 Log.e(TAG, "Failed to copy system profile for stub package!"); 9730 } else { 9731 useProfileForDexopt = true; 9732 } 9733 } catch (Exception e) { 9734 Log.e(TAG, "Failed to copy profile " + 9735 profileFile.getAbsolutePath() + " ", e); 9736 } 9737 } 9738 } 9739 } 9740 } 9741 9742 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9743 if (DEBUG_DEXOPT) { 9744 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9745 } 9746 numberOfPackagesSkipped++; 9747 continue; 9748 } 9749 9750 if (DEBUG_DEXOPT) { 9751 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9752 numberOfPackagesToDexopt + ": " + pkg.packageName); 9753 } 9754 9755 if (showDialog) { 9756 try { 9757 ActivityManager.getService().showBootMessage( 9758 mContext.getResources().getString(R.string.android_upgrading_apk, 9759 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9760 } catch (RemoteException e) { 9761 } 9762 synchronized (mPackages) { 9763 mDexOptDialogShown = true; 9764 } 9765 } 9766 9767 int pkgCompilationReason = compilationReason; 9768 if (useProfileForDexopt) { 9769 // Use background dexopt mode to try and use the profile. Note that this does not 9770 // guarantee usage of the profile. 9771 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9772 } 9773 9774 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) { 9775 mArtManagerService.compileLayouts(pkg); 9776 } 9777 9778 // checkProfiles is false to avoid merging profiles during boot which 9779 // might interfere with background compilation (b/28612421). 9780 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9781 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9782 // trade-off worth doing to save boot time work. 9783 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9784 if (compilationReason == REASON_FIRST_BOOT) { 9785 // TODO: This doesn't cover the upgrade case, we should check for this too. 9786 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9787 } 9788 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9789 pkg.packageName, 9790 pkgCompilationReason, 9791 dexoptFlags)); 9792 9793 switch (primaryDexOptStaus) { 9794 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9795 numberOfPackagesOptimized++; 9796 break; 9797 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9798 numberOfPackagesSkipped++; 9799 break; 9800 case PackageDexOptimizer.DEX_OPT_FAILED: 9801 numberOfPackagesFailed++; 9802 break; 9803 default: 9804 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9805 break; 9806 } 9807 } 9808 9809 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9810 numberOfPackagesFailed }; 9811 } 9812 9813 @Override 9814 public void notifyPackageUse(String packageName, int reason) { 9815 synchronized (mPackages) { 9816 final int callingUid = Binder.getCallingUid(); 9817 final int callingUserId = UserHandle.getUserId(callingUid); 9818 if (getInstantAppPackageName(callingUid) != null) { 9819 if (!isCallerSameApp(packageName, callingUid)) { 9820 return; 9821 } 9822 } else { 9823 if (isInstantApp(packageName, callingUserId)) { 9824 return; 9825 } 9826 } 9827 notifyPackageUseLocked(packageName, reason); 9828 } 9829 } 9830 9831 @GuardedBy("mPackages") 9832 public CheckPermissionDelegate getCheckPermissionDelegateLocked() { 9833 return mCheckPermissionDelegate; 9834 } 9835 9836 @GuardedBy("mPackages") 9837 public void setCheckPermissionDelegateLocked(CheckPermissionDelegate delegate) { 9838 mCheckPermissionDelegate = delegate; 9839 } 9840 9841 @GuardedBy("mPackages") 9842 private void notifyPackageUseLocked(String packageName, int reason) { 9843 final PackageParser.Package p = mPackages.get(packageName); 9844 if (p == null) { 9845 return; 9846 } 9847 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9848 } 9849 9850 @Override 9851 public void notifyDexLoad(String loadingPackageName, List<String> classLoaderNames, 9852 List<String> classPaths, String loaderIsa) { 9853 int userId = UserHandle.getCallingUserId(); 9854 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9855 if (ai == null) { 9856 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9857 + loadingPackageName + ", user=" + userId); 9858 return; 9859 } 9860 mDexManager.notifyDexLoad(ai, classLoaderNames, classPaths, loaderIsa, userId); 9861 } 9862 9863 @Override 9864 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9865 IDexModuleRegisterCallback callback) { 9866 int userId = UserHandle.getCallingUserId(); 9867 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9868 DexManager.RegisterDexModuleResult result; 9869 if (ai == null) { 9870 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9871 " calling user. package=" + packageName + ", user=" + userId); 9872 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9873 } else { 9874 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9875 } 9876 9877 if (callback != null) { 9878 mHandler.post(() -> { 9879 try { 9880 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9881 } catch (RemoteException e) { 9882 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9883 } 9884 }); 9885 } 9886 } 9887 9888 /** 9889 * Ask the package manager to perform a dex-opt with the given compiler filter. 9890 * 9891 * Note: exposed only for the shell command to allow moving packages explicitly to a 9892 * definite state. 9893 */ 9894 @Override 9895 public boolean performDexOptMode(String packageName, 9896 boolean checkProfiles, String targetCompilerFilter, boolean force, 9897 boolean bootComplete, String splitName) { 9898 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9899 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9900 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9901 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9902 targetCompilerFilter, splitName, flags)); 9903 } 9904 9905 /** 9906 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9907 * secondary dex files belonging to the given package. 9908 * 9909 * Note: exposed only for the shell command to allow moving packages explicitly to a 9910 * definite state. 9911 */ 9912 @Override 9913 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9914 boolean force) { 9915 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9916 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9917 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9918 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9919 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9920 } 9921 9922 /** 9923 * Ask the package manager to compile layouts in the given package. 9924 */ 9925 @Override 9926 public boolean compileLayouts(String packageName) { 9927 PackageParser.Package pkg; 9928 synchronized (mPackages) { 9929 pkg = mPackages.get(packageName); 9930 if (pkg == null) { 9931 return false; 9932 } 9933 } 9934 return mViewCompiler.compileLayouts(pkg); 9935 } 9936 9937 /*package*/ boolean performDexOpt(DexoptOptions options) { 9938 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9939 return false; 9940 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9941 return false; 9942 } 9943 9944 if (options.isDexoptOnlySecondaryDex()) { 9945 return mDexManager.dexoptSecondaryDex(options); 9946 } else { 9947 int dexoptStatus = performDexOptWithStatus(options); 9948 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9949 } 9950 } 9951 9952 /** 9953 * Perform dexopt on the given package and return one of following result: 9954 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9955 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9956 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9957 */ 9958 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9959 return performDexOptTraced(options); 9960 } 9961 9962 private int performDexOptTraced(DexoptOptions options) { 9963 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9964 try { 9965 return performDexOptInternal(options); 9966 } finally { 9967 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9968 } 9969 } 9970 9971 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9972 // if the package can now be considered up to date for the given filter. 9973 private int performDexOptInternal(DexoptOptions options) { 9974 PackageParser.Package p; 9975 synchronized (mPackages) { 9976 p = mPackages.get(options.getPackageName()); 9977 if (p == null) { 9978 // Package could not be found. Report failure. 9979 return PackageDexOptimizer.DEX_OPT_FAILED; 9980 } 9981 mPackageUsage.maybeWriteAsync(mPackages); 9982 mCompilerStats.maybeWriteAsync(); 9983 } 9984 long callingId = Binder.clearCallingIdentity(); 9985 try { 9986 synchronized (mInstallLock) { 9987 return performDexOptInternalWithDependenciesLI(p, options); 9988 } 9989 } finally { 9990 Binder.restoreCallingIdentity(callingId); 9991 } 9992 } 9993 9994 public ArraySet<String> getOptimizablePackages() { 9995 ArraySet<String> pkgs = new ArraySet<>(); 9996 synchronized (mPackages) { 9997 for (PackageParser.Package p : mPackages.values()) { 9998 if (PackageDexOptimizer.canOptimizePackage(p)) { 9999 pkgs.add(p.packageName); 10000 } 10001 } 10002 } 10003 return pkgs; 10004 } 10005 10006 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 10007 DexoptOptions options) { 10008 // Select the dex optimizer based on the force parameter. 10009 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 10010 // allocate an object here. 10011 PackageDexOptimizer pdo = options.isForce() 10012 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 10013 : mPackageDexOptimizer; 10014 10015 // Dexopt all dependencies first. Note: we ignore the return value and march on 10016 // on errors. 10017 // Note that we are going to call performDexOpt on those libraries as many times as 10018 // they are referenced in packages. When we do a batch of performDexOpt (for example 10019 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 10020 // and the first package that uses the library will dexopt it. The 10021 // others will see that the compiled code for the library is up to date. 10022 Collection<SharedLibraryInfo> deps = findSharedLibraries(p); 10023 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 10024 if (!deps.isEmpty()) { 10025 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 10026 options.getCompilationReason(), options.getCompilerFilter(), 10027 options.getSplitName(), 10028 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 10029 for (SharedLibraryInfo info : deps) { 10030 PackageParser.Package depPackage = null; 10031 synchronized (mPackages) { 10032 depPackage = mPackages.get(info.getPackageName()); 10033 } 10034 if (depPackage != null) { 10035 // TODO: Analyze and investigate if we (should) profile libraries. 10036 pdo.performDexOpt(depPackage, instructionSets, 10037 getOrCreateCompilerPackageStats(depPackage), 10038 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), 10039 libraryOptions); 10040 } else { 10041 // TODO(ngeoffray): Support dexopting system shared libraries. 10042 } 10043 } 10044 } 10045 return pdo.performDexOpt(p, instructionSets, 10046 getOrCreateCompilerPackageStats(p), 10047 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 10048 } 10049 10050 /** 10051 * Reconcile the information we have about the secondary dex files belonging to 10052 * {@code packageName} and the actual dex files. For all dex files that were 10053 * deleted, update the internal records and delete the generated oat files. 10054 */ 10055 @Override 10056 public void reconcileSecondaryDexFiles(String packageName) { 10057 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10058 return; 10059 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 10060 return; 10061 } 10062 mDexManager.reconcileSecondaryDexFiles(packageName); 10063 } 10064 10065 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 10066 // a reference there. 10067 /*package*/ DexManager getDexManager() { 10068 return mDexManager; 10069 } 10070 10071 /** 10072 * Execute the background dexopt job immediately. 10073 */ 10074 @Override 10075 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 10076 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10077 return false; 10078 } 10079 enforceSystemOrRootOrShell("runBackgroundDexoptJob"); 10080 final long identity = Binder.clearCallingIdentity(); 10081 try { 10082 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 10083 } finally { 10084 Binder.restoreCallingIdentity(identity); 10085 } 10086 } 10087 10088 private static List<SharedLibraryInfo> findSharedLibraries(PackageParser.Package p) { 10089 if (p.usesLibraryInfos != null) { 10090 ArrayList<SharedLibraryInfo> retValue = new ArrayList<>(); 10091 Set<String> collectedNames = new HashSet<>(); 10092 for (SharedLibraryInfo info : p.usesLibraryInfos) { 10093 findSharedLibrariesRecursive(info, retValue, collectedNames); 10094 } 10095 return retValue; 10096 } else { 10097 return Collections.emptyList(); 10098 } 10099 } 10100 10101 private static void findSharedLibrariesRecursive(SharedLibraryInfo info, 10102 ArrayList<SharedLibraryInfo> collected, Set<String> collectedNames) { 10103 if (!collectedNames.contains(info.getName())) { 10104 collectedNames.add(info.getName()); 10105 collected.add(info); 10106 10107 if (info.getDependencies() != null) { 10108 for (SharedLibraryInfo dep : info.getDependencies()) { 10109 findSharedLibrariesRecursive(dep, collected, collectedNames); 10110 } 10111 } 10112 } 10113 } 10114 10115 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package pkg) { 10116 List<SharedLibraryInfo> deps = findSharedLibraries(pkg); 10117 if (!deps.isEmpty()) { 10118 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 10119 synchronized (mPackages) { 10120 for (SharedLibraryInfo info : deps) { 10121 PackageParser.Package depPackage = mPackages.get(info.getPackageName()); 10122 if (depPackage != null) { 10123 retValue.add(depPackage); 10124 } 10125 } 10126 } 10127 return retValue; 10128 } else { 10129 return Collections.emptyList(); 10130 } 10131 } 10132 10133 @Nullable 10134 private SharedLibraryInfo getSharedLibraryInfoLPr(String name, long version) { 10135 return getSharedLibraryInfo(name, version, mSharedLibraries, null); 10136 } 10137 10138 @Nullable 10139 private static SharedLibraryInfo getSharedLibraryInfo(String name, long version, 10140 Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10141 @Nullable Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) { 10142 if (newLibraries != null) { 10143 final LongSparseArray<SharedLibraryInfo> versionedLib = newLibraries.get(name); 10144 SharedLibraryInfo info = null; 10145 if (versionedLib != null) { 10146 info = versionedLib.get(version); 10147 } 10148 if (info != null) { 10149 return info; 10150 } 10151 } 10152 final LongSparseArray<SharedLibraryInfo> versionedLib = existingLibraries.get(name); 10153 if (versionedLib == null) { 10154 return null; 10155 } 10156 return versionedLib.get(version); 10157 } 10158 10159 private SharedLibraryInfo getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 10160 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get( 10161 pkg.staticSharedLibName); 10162 if (versionedLib == null) { 10163 return null; 10164 } 10165 long previousLibVersion = -1; 10166 final int versionCount = versionedLib.size(); 10167 for (int i = 0; i < versionCount; i++) { 10168 final long libVersion = versionedLib.keyAt(i); 10169 if (libVersion < pkg.staticSharedLibVersion) { 10170 previousLibVersion = Math.max(previousLibVersion, libVersion); 10171 } 10172 } 10173 if (previousLibVersion >= 0) { 10174 return versionedLib.get(previousLibVersion); 10175 } 10176 return null; 10177 } 10178 10179 10180 @Nullable 10181 private PackageSetting getSharedLibLatestVersionSetting(@NonNull ScanResult scanResult) { 10182 PackageSetting sharedLibPackage = null; 10183 synchronized (mPackages) { 10184 final SharedLibraryInfo latestSharedLibraVersionLPr = 10185 getLatestSharedLibraVersionLPr(scanResult.pkgSetting.pkg); 10186 if (latestSharedLibraVersionLPr != null) { 10187 sharedLibPackage = mSettings.getPackageLPr( 10188 latestSharedLibraVersionLPr.getPackageName()); 10189 } 10190 } 10191 return sharedLibPackage; 10192 } 10193 10194 public void shutdown() { 10195 mPackageUsage.writeNow(mPackages); 10196 mCompilerStats.writeNow(); 10197 mDexManager.writePackageDexUsageNow(); 10198 PackageWatchdog.getInstance(mContext).writeNow(); 10199 10200 // This is the last chance to write out pending restriction settings 10201 synchronized (mPackages) { 10202 if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 10203 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 10204 for (int userId : mDirtyUsers) { 10205 mSettings.writePackageRestrictionsLPr(userId); 10206 } 10207 mDirtyUsers.clear(); 10208 } 10209 } 10210 } 10211 10212 @Override 10213 public void dumpProfiles(String packageName) { 10214 PackageParser.Package pkg; 10215 synchronized (mPackages) { 10216 pkg = mPackages.get(packageName); 10217 if (pkg == null) { 10218 throw new IllegalArgumentException("Unknown package: " + packageName); 10219 } 10220 } 10221 /* Only the shell, root, or the app user should be able to dump profiles. */ 10222 int callingUid = Binder.getCallingUid(); 10223 if (callingUid != Process.SHELL_UID && 10224 callingUid != Process.ROOT_UID && 10225 callingUid != pkg.applicationInfo.uid) { 10226 throw new SecurityException("dumpProfiles"); 10227 } 10228 10229 synchronized (mInstallLock) { 10230 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 10231 mArtManagerService.dumpProfiles(pkg); 10232 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10233 } 10234 } 10235 10236 @Override 10237 public void forceDexOpt(String packageName) { 10238 enforceSystemOrRoot("forceDexOpt"); 10239 10240 PackageParser.Package pkg; 10241 synchronized (mPackages) { 10242 pkg = mPackages.get(packageName); 10243 if (pkg == null) { 10244 throw new IllegalArgumentException("Unknown package: " + packageName); 10245 } 10246 } 10247 10248 synchronized (mInstallLock) { 10249 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 10250 10251 // Whoever is calling forceDexOpt wants a compiled package. 10252 // Don't use profiles since that may cause compilation to be skipped. 10253 final int res = performDexOptInternalWithDependenciesLI( 10254 pkg, 10255 new DexoptOptions(packageName, 10256 getDefaultCompilerFilter(), 10257 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 10258 10259 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10260 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 10261 throw new IllegalStateException("Failed to dexopt: " + res); 10262 } 10263 } 10264 } 10265 10266 @GuardedBy("mPackages") 10267 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 10268 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 10269 Slog.w(TAG, "Unable to update from " + oldPkg.name 10270 + " to " + newPkg.packageName 10271 + ": old package not in system partition"); 10272 return false; 10273 } else if (mPackages.get(oldPkg.name) != null) { 10274 Slog.w(TAG, "Unable to update from " + oldPkg.name 10275 + " to " + newPkg.packageName 10276 + ": old package still exists"); 10277 return false; 10278 } 10279 return true; 10280 } 10281 10282 @GuardedBy("mInstallLock") 10283 void removeCodePathLI(File codePath) { 10284 if (codePath.isDirectory()) { 10285 try { 10286 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 10287 } catch (InstallerException e) { 10288 Slog.w(TAG, "Failed to remove code path", e); 10289 } 10290 } else { 10291 codePath.delete(); 10292 } 10293 } 10294 10295 private int[] resolveUserIds(int userId) { 10296 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 10297 } 10298 10299 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10300 if (pkg == null) { 10301 Slog.wtf(TAG, "Package was null!", new Throwable()); 10302 return; 10303 } 10304 clearAppDataLeafLIF(pkg, userId, flags); 10305 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10306 for (int i = 0; i < childCount; i++) { 10307 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10308 } 10309 10310 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 10311 } 10312 10313 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10314 final PackageSetting ps; 10315 synchronized (mPackages) { 10316 ps = mSettings.mPackages.get(pkg.packageName); 10317 } 10318 for (int realUserId : resolveUserIds(userId)) { 10319 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10320 try { 10321 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10322 ceDataInode); 10323 } catch (InstallerException e) { 10324 Slog.w(TAG, String.valueOf(e)); 10325 } 10326 } 10327 } 10328 10329 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10330 if (pkg == null) { 10331 Slog.wtf(TAG, "Package was null!", new Throwable()); 10332 return; 10333 } 10334 destroyAppDataLeafLIF(pkg, userId, flags); 10335 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10336 for (int i = 0; i < childCount; i++) { 10337 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10338 } 10339 } 10340 10341 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10342 final PackageSetting ps; 10343 synchronized (mPackages) { 10344 ps = mSettings.mPackages.get(pkg.packageName); 10345 } 10346 for (int realUserId : resolveUserIds(userId)) { 10347 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10348 try { 10349 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10350 ceDataInode); 10351 } catch (InstallerException e) { 10352 Slog.w(TAG, String.valueOf(e)); 10353 } 10354 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 10355 } 10356 } 10357 10358 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 10359 if (pkg == null) { 10360 Slog.wtf(TAG, "Package was null!", new Throwable()); 10361 return; 10362 } 10363 destroyAppProfilesLeafLIF(pkg); 10364 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10365 for (int i = 0; i < childCount; i++) { 10366 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 10367 } 10368 } 10369 10370 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 10371 try { 10372 mInstaller.destroyAppProfiles(pkg.packageName); 10373 } catch (InstallerException e) { 10374 Slog.w(TAG, String.valueOf(e)); 10375 } 10376 } 10377 10378 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 10379 if (pkg == null) { 10380 Slog.wtf(TAG, "Package was null!", new Throwable()); 10381 return; 10382 } 10383 mArtManagerService.clearAppProfiles(pkg); 10384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10385 for (int i = 0; i < childCount; i++) { 10386 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 10387 } 10388 } 10389 10390 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 10391 long lastUpdateTime) { 10392 // Set parent install/update time 10393 PackageSetting ps = (PackageSetting) pkg.mExtras; 10394 if (ps != null) { 10395 ps.firstInstallTime = firstInstallTime; 10396 ps.lastUpdateTime = lastUpdateTime; 10397 } 10398 // Set children install/update time 10399 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10400 for (int i = 0; i < childCount; i++) { 10401 PackageParser.Package childPkg = pkg.childPackages.get(i); 10402 ps = (PackageSetting) childPkg.mExtras; 10403 if (ps != null) { 10404 ps.firstInstallTime = firstInstallTime; 10405 ps.lastUpdateTime = lastUpdateTime; 10406 } 10407 } 10408 } 10409 10410 @GuardedBy("mPackages") 10411 private void applyDefiningSharedLibraryUpdateLocked( 10412 PackageParser.Package pkg, SharedLibraryInfo libInfo, 10413 BiConsumer<SharedLibraryInfo, SharedLibraryInfo> action) { 10414 // Note that libraries defined by this package may be null if: 10415 // - Package manager was unable to create the shared library. The package still 10416 // gets installed, but the shared library does not get created. 10417 // Or: 10418 // - Package manager is in a state where package isn't scanned yet. This will 10419 // get called again after scanning to fix the dependencies. 10420 if (pkg.isLibrary()) { 10421 if (pkg.staticSharedLibName != null) { 10422 SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr( 10423 pkg.staticSharedLibName, pkg.staticSharedLibVersion); 10424 if (definedLibrary != null) { 10425 action.accept(definedLibrary, libInfo); 10426 } 10427 } else { 10428 for (String libraryName : pkg.libraryNames) { 10429 SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr( 10430 libraryName, SharedLibraryInfo.VERSION_UNDEFINED); 10431 if (definedLibrary != null) { 10432 action.accept(definedLibrary, libInfo); 10433 } 10434 } 10435 } 10436 } 10437 } 10438 10439 @GuardedBy("mPackages") 10440 private void addSharedLibraryLPr(PackageParser.Package pkg, Set<String> usesLibraryFiles, 10441 SharedLibraryInfo libInfo, PackageParser.Package changingLib) { 10442 if (libInfo.getPath() != null) { 10443 usesLibraryFiles.add(libInfo.getPath()); 10444 return; 10445 } 10446 PackageParser.Package p = mPackages.get(libInfo.getPackageName()); 10447 if (changingLib != null && changingLib.packageName.equals(libInfo.getPackageName())) { 10448 // If we are doing this while in the middle of updating a library apk, 10449 // then we need to make sure to use that new apk for determining the 10450 // dependencies here. (We haven't yet finished committing the new apk 10451 // to the package manager state.) 10452 if (p == null || p.packageName.equals(changingLib.packageName)) { 10453 p = changingLib; 10454 } 10455 } 10456 if (p != null) { 10457 usesLibraryFiles.addAll(p.getAllCodePaths()); 10458 // If the package provides libraries, add the dependency to them. 10459 applyDefiningSharedLibraryUpdateLocked(pkg, libInfo, (definingLibrary, dependency) -> { 10460 definingLibrary.addDependency(dependency); 10461 }); 10462 if (p.usesLibraryFiles != null) { 10463 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 10464 } 10465 } 10466 } 10467 10468 @GuardedBy("mPackages") 10469 private void updateSharedLibrariesLocked(PackageParser.Package pkg, 10470 PackageParser.Package changingLib, Map<String, PackageParser.Package> availablePackages) 10471 throws PackageManagerException { 10472 final ArrayList<SharedLibraryInfo> sharedLibraryInfos = 10473 collectSharedLibraryInfos(pkg, availablePackages, mSharedLibraries, null); 10474 executeSharedLibrariesUpdateLPr(pkg, changingLib, sharedLibraryInfos); 10475 } 10476 10477 private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos(PackageParser.Package pkg, 10478 Map<String, PackageParser.Package> availablePackages, 10479 @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10480 @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) 10481 throws PackageManagerException { 10482 if (pkg == null) { 10483 return null; 10484 } 10485 // The collection used here must maintain the order of addition (so 10486 // that libraries are searched in the correct order) and must have no 10487 // duplicates. 10488 ArrayList<SharedLibraryInfo> usesLibraryInfos = null; 10489 if (pkg.usesLibraries != null) { 10490 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesLibraries, null, null, 10491 pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, null, 10492 availablePackages, existingLibraries, newLibraries); 10493 } 10494 if (pkg.usesStaticLibraries != null) { 10495 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesStaticLibraries, 10496 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 10497 pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, usesLibraryInfos, 10498 availablePackages, existingLibraries, newLibraries); 10499 } 10500 if (pkg.usesOptionalLibraries != null) { 10501 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesOptionalLibraries, 10502 null, null, pkg.packageName, false, pkg.applicationInfo.targetSdkVersion, 10503 usesLibraryInfos, availablePackages, existingLibraries, newLibraries); 10504 } 10505 return usesLibraryInfos; 10506 } 10507 10508 private void executeSharedLibrariesUpdateLPr(PackageParser.Package pkg, 10509 PackageParser.Package changingLib, ArrayList<SharedLibraryInfo> usesLibraryInfos) { 10510 // If the package provides libraries, clear their old dependencies. 10511 // This method will set them up again. 10512 applyDefiningSharedLibraryUpdateLocked(pkg, null, (definingLibrary, dependency) -> { 10513 definingLibrary.clearDependencies(); 10514 }); 10515 if (usesLibraryInfos != null) { 10516 pkg.usesLibraryInfos = usesLibraryInfos; 10517 // Use LinkedHashSet to preserve the order of files added to 10518 // usesLibraryFiles while eliminating duplicates. 10519 Set<String> usesLibraryFiles = new LinkedHashSet<>(); 10520 for (SharedLibraryInfo libInfo : usesLibraryInfos) { 10521 addSharedLibraryLPr(pkg, usesLibraryFiles, libInfo, changingLib); 10522 } 10523 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 10524 } else { 10525 pkg.usesLibraryInfos = null; 10526 pkg.usesLibraryFiles = null; 10527 } 10528 } 10529 10530 @GuardedBy("mPackages") 10531 private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos( 10532 @NonNull List<String> requestedLibraries, 10533 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 10534 @NonNull String packageName, boolean required, int targetSdk, 10535 @Nullable ArrayList<SharedLibraryInfo> outUsedLibraries, 10536 @NonNull final Map<String, PackageParser.Package> availablePackages, 10537 @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10538 @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) 10539 throws PackageManagerException { 10540 final int libCount = requestedLibraries.size(); 10541 for (int i = 0; i < libCount; i++) { 10542 final String libName = requestedLibraries.get(i); 10543 final long libVersion = requiredVersions != null ? requiredVersions[i] 10544 : SharedLibraryInfo.VERSION_UNDEFINED; 10545 final SharedLibraryInfo libraryInfo = getSharedLibraryInfo(libName, libVersion, 10546 existingLibraries, newLibraries); 10547 if (libraryInfo == null) { 10548 if (required) { 10549 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10550 "Package " + packageName + " requires unavailable shared library " 10551 + libName + "; failing!"); 10552 } else if (DEBUG_SHARED_LIBRARIES) { 10553 Slog.i(TAG, "Package " + packageName 10554 + " desires unavailable shared library " 10555 + libName + "; ignoring!"); 10556 } 10557 } else { 10558 if (requiredVersions != null && requiredCertDigests != null) { 10559 if (libraryInfo.getLongVersion() != requiredVersions[i]) { 10560 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10561 "Package " + packageName + " requires unavailable static shared" 10562 + " library " + libName + " version " 10563 + libraryInfo.getLongVersion() + "; failing!"); 10564 } 10565 PackageParser.Package libPkg = 10566 availablePackages.get(libraryInfo.getPackageName()); 10567 if (libPkg == null) { 10568 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10569 "Package " + packageName + " requires unavailable static shared" 10570 + " library; failing!"); 10571 } 10572 final String[] expectedCertDigests = requiredCertDigests[i]; 10573 if (expectedCertDigests.length > 1) { 10574 // For apps targeting O MR1 we require explicit enumeration of all certs. 10575 final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1) 10576 ? PackageUtils.computeSignaturesSha256Digests( 10577 libPkg.mSigningDetails.signatures) 10578 : PackageUtils.computeSignaturesSha256Digests( 10579 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 10580 10581 // Take a shortcut if sizes don't match. Note that if an app doesn't 10582 // target O we don't parse the "additional-certificate" tags similarly 10583 // how we only consider all certs only for apps targeting O (see above). 10584 // Therefore, the size check is safe to make. 10585 if (expectedCertDigests.length != libCertDigests.length) { 10586 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10587 "Package " + packageName + " requires differently signed" + 10588 " static shared library; failing!"); 10589 } 10590 10591 // Use a predictable order as signature order may vary 10592 Arrays.sort(libCertDigests); 10593 Arrays.sort(expectedCertDigests); 10594 10595 final int certCount = libCertDigests.length; 10596 for (int j = 0; j < certCount; j++) { 10597 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 10598 throw new PackageManagerException( 10599 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10600 "Package " + packageName + " requires differently signed" + 10601 " static shared library; failing!"); 10602 } 10603 } 10604 } else { 10605 // lib signing cert could have rotated beyond the one expected, check to see 10606 // if the new one has been blessed by the old 10607 if (!libPkg.mSigningDetails.hasSha256Certificate( 10608 ByteStringUtils.fromHexToByteArray(expectedCertDigests[0]))) { 10609 throw new PackageManagerException( 10610 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10611 "Package " + packageName + " requires differently signed" + 10612 " static shared library; failing!"); 10613 } 10614 } 10615 } 10616 if (outUsedLibraries == null) { 10617 outUsedLibraries = new ArrayList<>(); 10618 } 10619 outUsedLibraries.add(libraryInfo); 10620 } 10621 } 10622 return outUsedLibraries; 10623 } 10624 10625 private static boolean hasString(List<String> list, List<String> which) { 10626 if (list == null || which == null) { 10627 return false; 10628 } 10629 for (int i=list.size()-1; i>=0; i--) { 10630 for (int j=which.size()-1; j>=0; j--) { 10631 if (which.get(j).equals(list.get(i))) { 10632 return true; 10633 } 10634 } 10635 } 10636 return false; 10637 } 10638 10639 @GuardedBy("mPackages") 10640 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLocked( 10641 PackageParser.Package updatedPkg, 10642 Map<String, PackageParser.Package> availablePackages) { 10643 ArrayList<PackageParser.Package> resultList = null; 10644 // Set of all descendants of a library; used to eliminate cycles 10645 ArraySet<String> descendants = null; 10646 // The current list of packages that need updating 10647 ArrayList<PackageParser.Package> needsUpdating = null; 10648 if (updatedPkg != null) { 10649 needsUpdating = new ArrayList<>(1); 10650 needsUpdating.add(updatedPkg); 10651 } 10652 do { 10653 final PackageParser.Package changingPkg = 10654 (needsUpdating == null) ? null : needsUpdating.remove(0); 10655 for (int i = mPackages.size() - 1; i >= 0; --i) { 10656 final PackageParser.Package pkg = mPackages.valueAt(i); 10657 if (changingPkg != null 10658 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 10659 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 10660 && !ArrayUtils.contains(pkg.usesStaticLibraries, 10661 changingPkg.staticSharedLibName)) { 10662 continue; 10663 } 10664 if (resultList == null) { 10665 resultList = new ArrayList<>(); 10666 } 10667 resultList.add(pkg); 10668 // if we're updating a shared library, all of its descendants must be updated 10669 if (changingPkg != null) { 10670 if (descendants == null) { 10671 descendants = new ArraySet<>(); 10672 } 10673 if (!descendants.contains(pkg.packageName)) { 10674 descendants.add(pkg.packageName); 10675 needsUpdating.add(pkg); 10676 } 10677 } 10678 try { 10679 updateSharedLibrariesLocked(pkg, changingPkg, availablePackages); 10680 } catch (PackageManagerException e) { 10681 // If a system app update or an app and a required lib missing we 10682 // delete the package and for updated system apps keep the data as 10683 // it is better for the user to reinstall than to be in an limbo 10684 // state. Also libs disappearing under an app should never happen 10685 // - just in case. 10686 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 10687 final int flags = pkg.isUpdatedSystemApp() 10688 ? PackageManager.DELETE_KEEP_DATA : 0; 10689 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 10690 flags , null, true, null); 10691 } 10692 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 10693 } 10694 } 10695 } while (needsUpdating != null && needsUpdating.size() > 0); 10696 return resultList; 10697 } 10698 10699 @GuardedBy({"mInstallLock", "mPackages"}) 10700 private List<ScanResult> scanPackageTracedLI(PackageParser.Package pkg, 10701 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10702 @Nullable UserHandle user) throws PackageManagerException { 10703 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 10704 // If the package has children and this is the first dive in the function 10705 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 10706 // whether all packages (parent and children) would be successfully scanned 10707 // before the actual scan since scanning mutates internal state and we want 10708 // to atomically install the package and its children. 10709 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10710 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 10711 scanFlags |= SCAN_CHECK_ONLY; 10712 } 10713 } else { 10714 scanFlags &= ~SCAN_CHECK_ONLY; 10715 } 10716 10717 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10718 final List<ScanResult> scanResults = new ArrayList<>(1 + childCount); 10719 try { 10720 // Scan the parent 10721 scanResults.add(scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user)); 10722 // Scan the children 10723 for (int i = 0; i < childCount; i++) { 10724 PackageParser.Package childPkg = pkg.childPackages.get(i); 10725 scanResults.add(scanPackageNewLI(childPkg, parseFlags, 10726 scanFlags, currentTime, user)); 10727 } 10728 } finally { 10729 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10730 } 10731 10732 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10733 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 10734 } 10735 10736 return scanResults; 10737 } 10738 10739 /** The result of a package scan. */ 10740 private static class ScanResult { 10741 /** The request that initiated the scan that produced this result. */ 10742 public final ScanRequest request; 10743 /** Whether or not the package scan was successful */ 10744 public final boolean success; 10745 /** 10746 * Whether or not the original PackageSetting needs to be updated with this result on 10747 * commit. 10748 */ 10749 public final boolean existingSettingCopied; 10750 /** 10751 * The final package settings. This may be the same object passed in 10752 * the {@link ScanRequest}, but, with modified values. 10753 */ 10754 @Nullable public final PackageSetting pkgSetting; 10755 /** ABI code paths that have changed in the package scan */ 10756 @Nullable public final List<String> changedAbiCodePath; 10757 10758 public final SharedLibraryInfo staticSharedLibraryInfo; 10759 10760 public final List<SharedLibraryInfo> dynamicSharedLibraryInfos; 10761 10762 public ScanResult( 10763 ScanRequest request, boolean success, 10764 @Nullable PackageSetting pkgSetting, 10765 @Nullable List<String> changedAbiCodePath, boolean existingSettingCopied, 10766 SharedLibraryInfo staticSharedLibraryInfo, 10767 List<SharedLibraryInfo> dynamicSharedLibraryInfos) { 10768 this.request = request; 10769 this.success = success; 10770 this.pkgSetting = pkgSetting; 10771 this.changedAbiCodePath = changedAbiCodePath; 10772 this.existingSettingCopied = existingSettingCopied; 10773 this.staticSharedLibraryInfo = staticSharedLibraryInfo; 10774 this.dynamicSharedLibraryInfos = dynamicSharedLibraryInfos; 10775 } 10776 } 10777 10778 /** A package to be scanned */ 10779 private static class ScanRequest { 10780 /** The parsed package */ 10781 @NonNull public final PackageParser.Package pkg; 10782 /** The package this package replaces */ 10783 @Nullable public final PackageParser.Package oldPkg; 10784 /** Shared user settings, if the package has a shared user */ 10785 @Nullable public final SharedUserSetting sharedUserSetting; 10786 /** 10787 * Package settings of the currently installed version. 10788 * <p><em>IMPORTANT:</em> The contents of this object may be modified 10789 * during scan. 10790 */ 10791 @Nullable public final PackageSetting pkgSetting; 10792 /** A copy of the settings for the currently installed version */ 10793 @Nullable public final PackageSetting oldPkgSetting; 10794 /** Package settings for the disabled version on the /system partition */ 10795 @Nullable public final PackageSetting disabledPkgSetting; 10796 /** Package settings for the installed version under its original package name */ 10797 @Nullable public final PackageSetting originalPkgSetting; 10798 /** The real package name of a renamed application */ 10799 @Nullable public final String realPkgName; 10800 public final @ParseFlags int parseFlags; 10801 public final @ScanFlags int scanFlags; 10802 /** The user for which the package is being scanned */ 10803 @Nullable public final UserHandle user; 10804 /** Whether or not the platform package is being scanned */ 10805 public final boolean isPlatformPackage; 10806 public ScanRequest( 10807 @NonNull PackageParser.Package pkg, 10808 @Nullable SharedUserSetting sharedUserSetting, 10809 @Nullable PackageParser.Package oldPkg, 10810 @Nullable PackageSetting pkgSetting, 10811 @Nullable PackageSetting disabledPkgSetting, 10812 @Nullable PackageSetting originalPkgSetting, 10813 @Nullable String realPkgName, 10814 @ParseFlags int parseFlags, 10815 @ScanFlags int scanFlags, 10816 boolean isPlatformPackage, 10817 @Nullable UserHandle user) { 10818 this.pkg = pkg; 10819 this.oldPkg = oldPkg; 10820 this.pkgSetting = pkgSetting; 10821 this.sharedUserSetting = sharedUserSetting; 10822 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 10823 this.disabledPkgSetting = disabledPkgSetting; 10824 this.originalPkgSetting = originalPkgSetting; 10825 this.realPkgName = realPkgName; 10826 this.parseFlags = parseFlags; 10827 this.scanFlags = scanFlags; 10828 this.isPlatformPackage = isPlatformPackage; 10829 this.user = user; 10830 } 10831 } 10832 10833 /** 10834 * Returns the actual scan flags depending upon the state of the other settings. 10835 * <p>Updated system applications will not have the following flags set 10836 * by default and need to be adjusted after the fact: 10837 * <ul> 10838 * <li>{@link #SCAN_AS_SYSTEM}</li> 10839 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 10840 * <li>{@link #SCAN_AS_OEM}</li> 10841 * <li>{@link #SCAN_AS_VENDOR}</li> 10842 * <li>{@link #SCAN_AS_PRODUCT}</li> 10843 * <li>{@link #SCAN_AS_PRODUCT_SERVICES}</li> 10844 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 10845 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 10846 * <li>{@link #SCAN_AS_ODM}</li> 10847 * </ul> 10848 */ 10849 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 10850 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 10851 PackageParser.Package pkg) { 10852 10853 // TODO(patb): Do away entirely with disabledPkgSetting here. PkgSetting will always contain 10854 // the correct isSystem value now that we don't disable system packages before scan. 10855 final PackageSetting systemPkgSetting = 10856 (scanFlags & SCAN_NEW_INSTALL) != 0 && disabledPkgSetting == null 10857 && pkgSetting != null && pkgSetting.isSystem() 10858 ? pkgSetting 10859 : disabledPkgSetting; 10860 if (systemPkgSetting != null) { 10861 // updated system application, must at least have SCAN_AS_SYSTEM 10862 scanFlags |= SCAN_AS_SYSTEM; 10863 if ((systemPkgSetting.pkgPrivateFlags 10864 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 10865 scanFlags |= SCAN_AS_PRIVILEGED; 10866 } 10867 if ((systemPkgSetting.pkgPrivateFlags 10868 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 10869 scanFlags |= SCAN_AS_OEM; 10870 } 10871 if ((systemPkgSetting.pkgPrivateFlags 10872 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 10873 scanFlags |= SCAN_AS_VENDOR; 10874 } 10875 if ((systemPkgSetting.pkgPrivateFlags 10876 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 10877 scanFlags |= SCAN_AS_PRODUCT; 10878 } 10879 if ((systemPkgSetting.pkgPrivateFlags 10880 & ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES) != 0) { 10881 scanFlags |= SCAN_AS_PRODUCT_SERVICES; 10882 } 10883 if ((systemPkgSetting.pkgPrivateFlags 10884 & ApplicationInfo.PRIVATE_FLAG_ODM) != 0) { 10885 scanFlags |= SCAN_AS_ODM; 10886 } 10887 } 10888 if (pkgSetting != null) { 10889 final int userId = ((user == null) ? 0 : user.getIdentifier()); 10890 if (pkgSetting.getInstantApp(userId)) { 10891 scanFlags |= SCAN_AS_INSTANT_APP; 10892 } 10893 if (pkgSetting.getVirtulalPreload(userId)) { 10894 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 10895 } 10896 } 10897 10898 // Scan as privileged apps that share a user with a priv-app. 10899 final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0) 10900 && SystemProperties.getInt("ro.vndk.version", 28) < 28; 10901 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) 10902 && !pkg.isPrivileged() 10903 && (pkg.mSharedUserId != null) 10904 && !skipVendorPrivilegeScan) { 10905 SharedUserSetting sharedUserSetting = null; 10906 try { 10907 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10908 } catch (PackageManagerException ignore) {} 10909 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10910 // Exempt SharedUsers signed with the platform key. 10911 // TODO(b/72378145) Fix this exemption. Force signature apps 10912 // to whitelist their privileged permissions just like other 10913 // priv-apps. 10914 synchronized (mPackages) { 10915 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10916 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 10917 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 10918 scanFlags |= SCAN_AS_PRIVILEGED; 10919 } 10920 } 10921 } 10922 } 10923 10924 return scanFlags; 10925 } 10926 10927 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 10928 // the results / removing app data needs to be moved up a level to the callers of this 10929 // method. Also, we need to solve the problem of potentially creating a new shared user 10930 // setting. That can probably be done later and patch things up after the fact. 10931 @GuardedBy({"mInstallLock", "mPackages"}) 10932 private ScanResult scanPackageNewLI(@NonNull PackageParser.Package pkg, 10933 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10934 @Nullable UserHandle user) throws PackageManagerException { 10935 10936 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10937 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 10938 if (realPkgName != null) { 10939 ensurePackageRenamed(pkg, renamedPkgName); 10940 } 10941 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10942 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10943 final PackageSetting disabledPkgSetting = 10944 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10945 10946 if (mTransferedPackages.contains(pkg.packageName)) { 10947 Slog.w(TAG, "Package " + pkg.packageName 10948 + " was transferred to another, but its .apk remains"); 10949 } 10950 10951 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10952 synchronized (mPackages) { 10953 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 10954 assertPackageIsValid(pkg, parseFlags, scanFlags); 10955 10956 SharedUserSetting sharedUserSetting = null; 10957 if (pkg.mSharedUserId != null) { 10958 // SIDE EFFECTS; may potentially allocate a new shared user 10959 sharedUserSetting = mSettings.getSharedUserLPw( 10960 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10961 if (DEBUG_PACKAGE_SCANNING) { 10962 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10963 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10964 + " (uid=" + sharedUserSetting.userId + "):" 10965 + " packages=" + sharedUserSetting.packages); 10966 } 10967 } 10968 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 10969 pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting, 10970 originalPkgSetting, realPkgName, parseFlags, scanFlags, 10971 (pkg == mPlatformPackage), user); 10972 return scanPackageOnlyLI(request, mFactoryTest, currentTime); 10973 } 10974 } 10975 10976 10977 /** 10978 * Prepares the system to commit a {@link ScanResult} in a way that will not fail by registering 10979 * the app ID required for reconcile. 10980 * @return {@code true} if a new app ID was registered and will need to be cleaned up on 10981 * failure. 10982 */ 10983 private boolean optimisticallyRegisterAppId(@NonNull ScanResult result) 10984 throws PackageManagerException { 10985 if (!result.existingSettingCopied) { 10986 // THROWS: when we can't allocate a user id. add call to check if there's 10987 // enough space to ensure we won't throw; otherwise, don't modify state 10988 return mSettings.registerAppIdLPw(result.pkgSetting); 10989 } 10990 return false; 10991 } 10992 10993 /** 10994 * Reverts any app ID creation that were made by 10995 * {@link #optimisticallyRegisterAppId(ScanResult)}. Note: this is only necessary if the 10996 * referenced method returned true. 10997 */ 10998 private void cleanUpAppIdCreation(@NonNull ScanResult result) { 10999 // iff we've acquired an app ID for a new package setting, remove it so that it can be 11000 // acquired by another request. 11001 if (result.pkgSetting.appId > 0) { 11002 mSettings.removeAppIdLPw(result.pkgSetting.appId); 11003 } 11004 } 11005 11006 /** 11007 * Commits the package scan and modifies system state. 11008 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 11009 * of committing the package, leaving the system in an inconsistent state. 11010 * This needs to be fixed so, once we get to this point, no errors are 11011 * possible and the system is not left in an inconsistent state. 11012 */ 11013 @GuardedBy({"mPackages", "mInstallLock"}) 11014 private void commitReconciledScanResultLocked(@NonNull ReconciledPackage reconciledPkg) { 11015 final ScanResult result = reconciledPkg.scanResult; 11016 final ScanRequest request = result.request; 11017 final PackageParser.Package pkg = request.pkg; 11018 final PackageParser.Package oldPkg = request.oldPkg; 11019 final @ParseFlags int parseFlags = request.parseFlags; 11020 final @ScanFlags int scanFlags = request.scanFlags; 11021 final PackageSetting oldPkgSetting = request.oldPkgSetting; 11022 final PackageSetting originalPkgSetting = request.originalPkgSetting; 11023 final UserHandle user = request.user; 11024 final String realPkgName = request.realPkgName; 11025 final List<String> changedAbiCodePath = result.changedAbiCodePath; 11026 final PackageSetting pkgSetting; 11027 if (request.pkgSetting != null && request.pkgSetting.sharedUser != null 11028 && request.pkgSetting.sharedUser != result.pkgSetting.sharedUser) { 11029 // shared user changed, remove from old shared user 11030 request.pkgSetting.sharedUser.removePackage(request.pkgSetting); 11031 } 11032 if (result.existingSettingCopied) { 11033 pkgSetting = request.pkgSetting; 11034 pkgSetting.updateFrom(result.pkgSetting); 11035 pkg.mExtras = pkgSetting; 11036 } else { 11037 pkgSetting = result.pkgSetting; 11038 if (originalPkgSetting != null) { 11039 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 11040 } 11041 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 11042 mTransferedPackages.add(originalPkgSetting.name); 11043 } 11044 } 11045 if (pkgSetting.sharedUser != null) { 11046 pkgSetting.sharedUser.addPackage(pkgSetting); 11047 } 11048 // TODO(toddke): Consider a method specifically for modifying the Package object 11049 // post scan; or, moving this stuff out of the Package object since it has nothing 11050 // to do with the package on disk. 11051 // We need to have this here because addUserToSettingLPw() is sometimes responsible 11052 // for creating the application ID. If we did this earlier, we would be saving the 11053 // correct ID. 11054 pkg.applicationInfo.uid = pkgSetting.appId; 11055 11056 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 11057 11058 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 11059 mTransferedPackages.add(pkg.packageName); 11060 } 11061 11062 if (reconciledPkg.collectedSharedLibraryInfos != null) { 11063 executeSharedLibrariesUpdateLPr(pkg, null, reconciledPkg.collectedSharedLibraryInfos); 11064 } 11065 11066 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 11067 if (reconciledPkg.removeAppKeySetData) { 11068 ksms.removeAppKeySetDataLPw(pkg.packageName); 11069 } 11070 if (reconciledPkg.sharedUserSignaturesChanged) { 11071 pkgSetting.sharedUser.signaturesChanged = Boolean.TRUE; 11072 pkgSetting.sharedUser.signatures.mSigningDetails = reconciledPkg.signingDetails; 11073 } 11074 pkgSetting.signatures.mSigningDetails = reconciledPkg.signingDetails; 11075 11076 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 11077 // This package wants to adopt ownership of permissions from 11078 // another package. 11079 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 11080 final String origName = pkg.mAdoptPermissions.get(i); 11081 final PackageSetting orig = mSettings.getPackageLPr(origName); 11082 if (orig != null) { 11083 if (verifyPackageUpdateLPr(orig, pkg)) { 11084 Slog.i(TAG, "Adopting permissions from " + origName + " to " 11085 + pkg.packageName); 11086 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 11087 } 11088 } 11089 } 11090 } 11091 11092 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 11093 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 11094 final String codePathString = changedAbiCodePath.get(i); 11095 try { 11096 mInstaller.rmdex(codePathString, 11097 getDexCodeInstructionSet(getPreferredInstructionSet())); 11098 } catch (InstallerException ignored) { 11099 } 11100 } 11101 } 11102 11103 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 11104 if (oldPkgSetting != null) { 11105 synchronized (mPackages) { 11106 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 11107 } 11108 } 11109 } else { 11110 final int userId = user == null ? 0 : user.getIdentifier(); 11111 // Modify state for the given package setting 11112 commitPackageSettings(pkg, oldPkg, pkgSetting, scanFlags, 11113 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/, reconciledPkg); 11114 if (pkgSetting.getInstantApp(userId)) { 11115 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 11116 } 11117 } 11118 } 11119 11120 /** 11121 * Returns the "real" name of the package. 11122 * <p>This may differ from the package's actual name if the application has already 11123 * been installed under one of this package's original names. 11124 */ 11125 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 11126 @Nullable String renamedPkgName) { 11127 if (isPackageRenamed(pkg, renamedPkgName)) { 11128 return pkg.mRealPackage; 11129 } 11130 return null; 11131 } 11132 11133 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 11134 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 11135 @Nullable String renamedPkgName) { 11136 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 11137 } 11138 11139 /** 11140 * Returns the original package setting. 11141 * <p>A package can migrate its name during an update. In this scenario, a package 11142 * designates a set of names that it considers as one of its original names. 11143 * <p>An original package must be signed identically and it must have the same 11144 * shared user [if any]. 11145 */ 11146 @GuardedBy("mPackages") 11147 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 11148 @Nullable String renamedPkgName) { 11149 if (!isPackageRenamed(pkg, renamedPkgName)) { 11150 return null; 11151 } 11152 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 11153 final PackageSetting originalPs = 11154 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 11155 if (originalPs != null) { 11156 // the package is already installed under its original name... 11157 // but, should we use it? 11158 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 11159 // the new package is incompatible with the original 11160 continue; 11161 } else if (originalPs.sharedUser != null) { 11162 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 11163 // the shared user id is incompatible with the original 11164 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 11165 + " to " + pkg.packageName + ": old uid " 11166 + originalPs.sharedUser.name 11167 + " differs from " + pkg.mSharedUserId); 11168 continue; 11169 } 11170 // TODO: Add case when shared user id is added [b/28144775] 11171 } else { 11172 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 11173 + pkg.packageName + " to old name " + originalPs.name); 11174 } 11175 return originalPs; 11176 } 11177 } 11178 return null; 11179 } 11180 11181 /** 11182 * Renames the package if it was installed under a different name. 11183 * <p>When we've already installed the package under an original name, update 11184 * the new package so we can continue to have the old name. 11185 */ 11186 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 11187 @NonNull String renamedPackageName) { 11188 if (pkg.mOriginalPackages == null 11189 || !pkg.mOriginalPackages.contains(renamedPackageName) 11190 || pkg.packageName.equals(renamedPackageName)) { 11191 return; 11192 } 11193 pkg.setPackageName(renamedPackageName); 11194 } 11195 11196 /** 11197 * Just scans the package without any side effects. 11198 * <p>Not entirely true at the moment. There is still one side effect -- this 11199 * method potentially modifies a live {@link PackageSetting} object representing 11200 * the package being scanned. This will be resolved in the future. 11201 * 11202 * @param request Information about the package to be scanned 11203 * @param isUnderFactoryTest Whether or not the device is under factory test 11204 * @param currentTime The current time, in millis 11205 * @return The results of the scan 11206 */ 11207 @GuardedBy("mInstallLock") 11208 private static @NonNull ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 11209 boolean isUnderFactoryTest, long currentTime) 11210 throws PackageManagerException { 11211 final PackageParser.Package pkg = request.pkg; 11212 PackageSetting pkgSetting = request.pkgSetting; 11213 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 11214 final PackageSetting originalPkgSetting = request.originalPkgSetting; 11215 final @ParseFlags int parseFlags = request.parseFlags; 11216 final @ScanFlags int scanFlags = request.scanFlags; 11217 final String realPkgName = request.realPkgName; 11218 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 11219 final UserHandle user = request.user; 11220 final boolean isPlatformPackage = request.isPlatformPackage; 11221 11222 List<String> changedAbiCodePath = null; 11223 11224 if (DEBUG_PACKAGE_SCANNING) { 11225 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 11226 Log.d(TAG, "Scanning package " + pkg.packageName); 11227 } 11228 11229 // Initialize package source and resource directories 11230 final File scanFile = new File(pkg.codePath); 11231 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 11232 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 11233 11234 // We keep references to the derived CPU Abis from settings in oder to reuse 11235 // them in the case where we're not upgrading or booting for the first time. 11236 String primaryCpuAbiFromSettings = null; 11237 String secondaryCpuAbiFromSettings = null; 11238 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 11239 if (!needToDeriveAbi) { 11240 if (pkgSetting != null) { 11241 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 11242 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 11243 } else { 11244 // Re-scanning a system package after uninstalling updates; need to derive ABI 11245 needToDeriveAbi = true; 11246 } 11247 } 11248 11249 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 11250 PackageManagerService.reportSettingsProblem(Log.WARN, 11251 "Package " + pkg.packageName + " shared user changed from " 11252 + (pkgSetting.sharedUser != null 11253 ? pkgSetting.sharedUser.name : "<nothing>") 11254 + " to " 11255 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 11256 + "; replacing with new"); 11257 pkgSetting = null; 11258 } 11259 11260 String[] usesStaticLibraries = null; 11261 if (pkg.usesStaticLibraries != null) { 11262 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 11263 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 11264 } 11265 final boolean createNewPackage = (pkgSetting == null); 11266 if (createNewPackage) { 11267 final String parentPackageName = (pkg.parentPackage != null) 11268 ? pkg.parentPackage.packageName : null; 11269 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 11270 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 11271 // REMOVE SharedUserSetting from method; update in a separate call 11272 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 11273 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 11274 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 11275 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 11276 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 11277 user, true /*allowInstall*/, instantApp, virtualPreload, 11278 parentPackageName, pkg.getChildPackageNames(), 11279 UserManagerService.getInstance(), usesStaticLibraries, 11280 pkg.usesStaticLibrariesVersions); 11281 } else { 11282 // make a deep copy to avoid modifying any existing system state. 11283 pkgSetting = new PackageSetting(pkgSetting); 11284 pkgSetting.pkg = pkg; 11285 11286 // REMOVE SharedUserSetting from method; update in a separate call. 11287 // 11288 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 11289 // secondaryCpuAbi are not known at this point so we always update them 11290 // to null here, only to reset them at a later point. 11291 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 11292 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 11293 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 11294 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 11295 pkg.getChildPackageNames(), UserManagerService.getInstance(), 11296 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 11297 } 11298 if (createNewPackage && originalPkgSetting != null) { 11299 // This is the initial transition from the original package, so, 11300 // fix up the new package's name now. We must do this after looking 11301 // up the package under its new name, so getPackageLP takes care of 11302 // fiddling things correctly. 11303 pkg.setPackageName(originalPkgSetting.name); 11304 11305 // File a report about this. 11306 String msg = "New package " + pkgSetting.realName 11307 + " renamed to replace old package " + pkgSetting.name; 11308 reportSettingsProblem(Log.WARN, msg); 11309 } 11310 11311 final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier()); 11312 // for existing packages, change the install state; but, only if it's explicitly specified 11313 if (!createNewPackage) { 11314 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 11315 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 11316 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 11317 } 11318 // TODO(patb): see if we can do away with disabled check here. 11319 if (disabledPkgSetting != null 11320 || (0 != (scanFlags & SCAN_NEW_INSTALL) 11321 && pkgSetting != null && pkgSetting.isSystem())) { 11322 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11323 } 11324 11325 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 11326 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 11327 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 11328 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 11329 // least restrictive selinux domain. 11330 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 11331 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 11332 // ensures that all packages continue to run in the same selinux domain. 11333 final int targetSdkVersion = 11334 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 11335 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 11336 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 11337 // They currently can be if the sharedUser apps are signed with the platform key. 11338 final boolean isPrivileged = (sharedUserSetting != null) ? 11339 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 11340 11341 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 11342 pkg.applicationInfo.targetSandboxVersion, targetSdkVersion); 11343 pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState( 11344 userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId)); 11345 11346 pkg.mExtras = pkgSetting; 11347 pkg.applicationInfo.processName = fixProcessName( 11348 pkg.applicationInfo.packageName, 11349 pkg.applicationInfo.processName); 11350 11351 if (!isPlatformPackage) { 11352 // Get all of our default paths setup 11353 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 11354 } 11355 11356 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 11357 11358 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 11359 if (needToDeriveAbi) { 11360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 11361 final boolean extractNativeLibs = !pkg.isLibrary(); 11362 derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 11363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11364 11365 // Some system apps still use directory structure for native libraries 11366 // in which case we might end up not detecting abi solely based on apk 11367 // structure. Try to detect abi based on directory structure. 11368 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 11369 pkg.applicationInfo.primaryCpuAbi == null) { 11370 setBundledAppAbisAndRoots(pkg, pkgSetting); 11371 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11372 } 11373 } else { 11374 // This is not a first boot or an upgrade, don't bother deriving the 11375 // ABI during the scan. Instead, trust the value that was stored in the 11376 // package setting. 11377 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 11378 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 11379 11380 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11381 11382 if (DEBUG_ABI_SELECTION) { 11383 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 11384 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 11385 pkg.applicationInfo.secondaryCpuAbi); 11386 } 11387 } 11388 } else { 11389 if ((scanFlags & SCAN_MOVE) != 0) { 11390 // We haven't run dex-opt for this move (since we've moved the compiled output too) 11391 // but we already have this packages package info in the PackageSetting. We just 11392 // use that and derive the native library path based on the new codepath. 11393 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 11394 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 11395 } 11396 11397 // Set native library paths again. For moves, the path will be updated based on the 11398 // ABIs we've determined above. For non-moves, the path will be updated based on the 11399 // ABIs we determined during compilation, but the path will depend on the final 11400 // package path (after the rename away from the stage path). 11401 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 11402 } 11403 11404 // This is a special case for the "system" package, where the ABI is 11405 // dictated by the zygote configuration (and init.rc). We should keep track 11406 // of this ABI so that we can deal with "normal" applications that run under 11407 // the same UID correctly. 11408 if (isPlatformPackage) { 11409 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 11410 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 11411 } 11412 11413 // If there's a mismatch between the abi-override in the package setting 11414 // and the abiOverride specified for the install. Warn about this because we 11415 // would've already compiled the app without taking the package setting into 11416 // account. 11417 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 11418 if (cpuAbiOverride == null && pkg.packageName != null) { 11419 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 11420 " for package " + pkg.packageName); 11421 } 11422 } 11423 11424 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11425 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11426 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 11427 11428 // Copy the derived override back to the parsed package, so that we can 11429 // update the package settings accordingly. 11430 pkg.cpuAbiOverride = cpuAbiOverride; 11431 11432 if (DEBUG_ABI_SELECTION) { 11433 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 11434 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 11435 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 11436 } 11437 11438 // Push the derived path down into PackageSettings so we know what to 11439 // clean up at uninstall time. 11440 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 11441 11442 if (DEBUG_ABI_SELECTION) { 11443 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 11444 " primary=" + pkg.applicationInfo.primaryCpuAbi + 11445 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 11446 } 11447 11448 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 11449 // We don't do this here during boot because we can do it all 11450 // at once after scanning all existing packages. 11451 // 11452 // We also do this *before* we perform dexopt on this package, so that 11453 // we can avoid redundant dexopts, and also to make sure we've got the 11454 // code and package path correct. 11455 changedAbiCodePath = 11456 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, pkg); 11457 } 11458 11459 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 11460 android.Manifest.permission.FACTORY_TEST)) { 11461 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 11462 } 11463 11464 if (isSystemApp(pkg)) { 11465 pkgSetting.isOrphaned = true; 11466 } 11467 11468 // Take care of first install / last update times. 11469 final long scanFileTime = getLastModifiedTime(pkg); 11470 if (currentTime != 0) { 11471 if (pkgSetting.firstInstallTime == 0) { 11472 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 11473 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 11474 pkgSetting.lastUpdateTime = currentTime; 11475 } 11476 } else if (pkgSetting.firstInstallTime == 0) { 11477 // We need *something*. Take time time stamp of the file. 11478 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 11479 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 11480 if (scanFileTime != pkgSetting.timeStamp) { 11481 // A package on the system image has changed; consider this 11482 // to be an update. 11483 pkgSetting.lastUpdateTime = scanFileTime; 11484 } 11485 } 11486 pkgSetting.setTimeStamp(scanFileTime); 11487 11488 pkgSetting.pkg = pkg; 11489 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 11490 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 11491 pkgSetting.versionCode = pkg.getLongVersionCode(); 11492 } 11493 // Update volume if needed 11494 final String volumeUuid = pkg.applicationInfo.volumeUuid; 11495 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 11496 Slog.i(PackageManagerService.TAG, 11497 "Update" + (pkgSetting.isSystem() ? " system" : "") 11498 + " package " + pkg.packageName 11499 + " volume from " + pkgSetting.volumeUuid 11500 + " to " + volumeUuid); 11501 pkgSetting.volumeUuid = volumeUuid; 11502 } 11503 11504 SharedLibraryInfo staticSharedLibraryInfo = null; 11505 if (!TextUtils.isEmpty(pkg.staticSharedLibName)) { 11506 staticSharedLibraryInfo = SharedLibraryInfo.createForStatic(pkg); 11507 } 11508 List<SharedLibraryInfo> dynamicSharedLibraryInfos = null; 11509 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 11510 dynamicSharedLibraryInfos = new ArrayList<>(pkg.libraryNames.size()); 11511 for (String name : pkg.libraryNames) { 11512 dynamicSharedLibraryInfos.add(SharedLibraryInfo.createForDynamic(pkg, name)); 11513 } 11514 } 11515 11516 return new ScanResult(request, true, pkgSetting, changedAbiCodePath, 11517 !createNewPackage /* existingSettingCopied */, staticSharedLibraryInfo, 11518 dynamicSharedLibraryInfos); 11519 } 11520 11521 /** 11522 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 11523 */ 11524 private static boolean apkHasCode(String fileName) { 11525 StrictJarFile jarFile = null; 11526 try { 11527 jarFile = new StrictJarFile(fileName, 11528 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 11529 return jarFile.findEntry("classes.dex") != null; 11530 } catch (IOException ignore) { 11531 } finally { 11532 try { 11533 if (jarFile != null) { 11534 jarFile.close(); 11535 } 11536 } catch (IOException ignore) {} 11537 } 11538 return false; 11539 } 11540 11541 /** 11542 * Enforces code policy for the package. This ensures that if an APK has 11543 * declared hasCode="true" in its manifest that the APK actually contains 11544 * code. 11545 * 11546 * @throws PackageManagerException If bytecode could not be found when it should exist 11547 */ 11548 private static void assertCodePolicy(PackageParser.Package pkg) 11549 throws PackageManagerException { 11550 final boolean shouldHaveCode = 11551 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 11552 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 11553 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11554 "Package " + pkg.baseCodePath + " code is missing"); 11555 } 11556 11557 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 11558 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 11559 final boolean splitShouldHaveCode = 11560 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 11561 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 11562 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11563 "Package " + pkg.splitCodePaths[i] + " code is missing"); 11564 } 11565 } 11566 } 11567 } 11568 11569 /** 11570 * Applies policy to the parsed package based upon the given policy flags. 11571 * Ensures the package is in a good state. 11572 * <p> 11573 * Implementation detail: This method must NOT have any side effect. It would 11574 * ideally be static, but, it requires locks to read system state. 11575 */ 11576 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 11577 final @ScanFlags int scanFlags, PackageParser.Package platformPkg) { 11578 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11579 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 11580 if (pkg.applicationInfo.isDirectBootAware()) { 11581 // we're direct boot aware; set for all components 11582 for (PackageParser.Service s : pkg.services) { 11583 s.info.encryptionAware = s.info.directBootAware = true; 11584 } 11585 for (PackageParser.Provider p : pkg.providers) { 11586 p.info.encryptionAware = p.info.directBootAware = true; 11587 } 11588 for (PackageParser.Activity a : pkg.activities) { 11589 a.info.encryptionAware = a.info.directBootAware = true; 11590 } 11591 for (PackageParser.Activity r : pkg.receivers) { 11592 r.info.encryptionAware = r.info.directBootAware = true; 11593 } 11594 } 11595 if (compressedFileExists(pkg.codePath)) { 11596 pkg.isStub = true; 11597 } 11598 } else { 11599 // non system apps can't be flagged as core 11600 pkg.coreApp = false; 11601 // clear flags not applicable to regular apps 11602 pkg.applicationInfo.flags &= 11603 ~ApplicationInfo.FLAG_PERSISTENT; 11604 pkg.applicationInfo.privateFlags &= 11605 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 11606 pkg.applicationInfo.privateFlags &= 11607 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 11608 // clear protected broadcasts 11609 pkg.protectedBroadcasts = null; 11610 // cap permission priorities 11611 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 11612 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 11613 pkg.permissionGroups.get(i).info.priority = 0; 11614 } 11615 } 11616 } 11617 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 11618 // ignore export request for single user receivers 11619 if (pkg.receivers != null) { 11620 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 11621 final PackageParser.Activity receiver = pkg.receivers.get(i); 11622 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 11623 receiver.info.exported = false; 11624 } 11625 } 11626 } 11627 // ignore export request for single user services 11628 if (pkg.services != null) { 11629 for (int i = pkg.services.size() - 1; i >= 0; --i) { 11630 final PackageParser.Service service = pkg.services.get(i); 11631 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 11632 service.info.exported = false; 11633 } 11634 } 11635 } 11636 // ignore export request for single user providers 11637 if (pkg.providers != null) { 11638 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 11639 final PackageParser.Provider provider = pkg.providers.get(i); 11640 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 11641 provider.info.exported = false; 11642 } 11643 } 11644 } 11645 } 11646 11647 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 11648 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 11649 } 11650 11651 if ((scanFlags & SCAN_AS_OEM) != 0) { 11652 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 11653 } 11654 11655 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 11656 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 11657 } 11658 11659 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 11660 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 11661 } 11662 11663 if ((scanFlags & SCAN_AS_PRODUCT_SERVICES) != 0) { 11664 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES; 11665 } 11666 11667 if ((scanFlags & SCAN_AS_ODM) != 0) { 11668 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ODM; 11669 } 11670 11671 // Check if the package is signed with the same key as the platform package. 11672 if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) || 11673 (platformPkg != null && compareSignatures( 11674 platformPkg.mSigningDetails.signatures, 11675 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) { 11676 pkg.applicationInfo.privateFlags |= 11677 ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY; 11678 } 11679 11680 if (!isSystemApp(pkg)) { 11681 // Only system apps can use these features. 11682 pkg.mOriginalPackages = null; 11683 pkg.mRealPackage = null; 11684 pkg.mAdoptPermissions = null; 11685 } 11686 11687 PackageBackwardCompatibility.modifySharedLibraries(pkg); 11688 } 11689 11690 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 11691 throws PackageManagerException { 11692 if (object == null) { 11693 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 11694 } 11695 return object; 11696 } 11697 11698 /** 11699 * Asserts the parsed package is valid according to the given policy. If the 11700 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 11701 * <p> 11702 * Implementation detail: This method must NOT have any side effects. It would 11703 * ideally be static, but, it requires locks to read system state. 11704 * 11705 * @throws PackageManagerException If the package fails any of the validation checks 11706 */ 11707 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 11708 final @ScanFlags int scanFlags) 11709 throws PackageManagerException { 11710 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 11711 assertCodePolicy(pkg); 11712 } 11713 11714 if (pkg.applicationInfo.getCodePath() == null || 11715 pkg.applicationInfo.getResourcePath() == null) { 11716 // Bail out. The resource and code paths haven't been set. 11717 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11718 "Code and resource paths haven't been set correctly"); 11719 } 11720 11721 // Check that there is an APEX package with the same name only during install/first boot 11722 // after OTA. 11723 final boolean isUserInstall = (scanFlags & SCAN_BOOTING) == 0; 11724 final boolean isFirstBootOrUpgrade = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 11725 if ((isUserInstall || isFirstBootOrUpgrade) 11726 && mApexManager.isApexPackage(pkg.packageName)) { 11727 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11728 pkg.packageName + " is an APEX package and can't be installed as an APK."); 11729 } 11730 11731 // Make sure we're not adding any bogus keyset info 11732 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 11733 ksms.assertScannedPackageValid(pkg); 11734 11735 synchronized (mPackages) { 11736 // The special "android" package can only be defined once 11737 if (pkg.packageName.equals("android")) { 11738 if (mAndroidApplication != null) { 11739 Slog.w(TAG, "*************************************************"); 11740 Slog.w(TAG, "Core android package being redefined. Skipping."); 11741 Slog.w(TAG, " codePath=" + pkg.codePath); 11742 Slog.w(TAG, "*************************************************"); 11743 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11744 "Core android package being redefined. Skipping."); 11745 } 11746 } 11747 11748 // A package name must be unique; don't allow duplicates 11749 if ((scanFlags & SCAN_NEW_INSTALL) == 0 && mPackages.containsKey(pkg.packageName)) { 11750 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11751 "Application package " + pkg.packageName 11752 + " already installed. Skipping duplicate."); 11753 } 11754 11755 if (pkg.applicationInfo.isStaticSharedLibrary()) { 11756 // Static libs have a synthetic package name containing the version 11757 // but we still want the base name to be unique. 11758 if ((scanFlags & SCAN_NEW_INSTALL) == 0 11759 && mPackages.containsKey(pkg.manifestPackageName)) { 11760 throw new PackageManagerException( 11761 "Duplicate static shared lib provider package"); 11762 } 11763 11764 // Static shared libraries should have at least O target SDK 11765 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 11766 throw new PackageManagerException( 11767 "Packages declaring static-shared libs must target O SDK or higher"); 11768 } 11769 11770 // Package declaring static a shared lib cannot be instant apps 11771 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11772 throw new PackageManagerException( 11773 "Packages declaring static-shared libs cannot be instant apps"); 11774 } 11775 11776 // Package declaring static a shared lib cannot be renamed since the package 11777 // name is synthetic and apps can't code around package manager internals. 11778 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 11779 throw new PackageManagerException( 11780 "Packages declaring static-shared libs cannot be renamed"); 11781 } 11782 11783 // Package declaring static a shared lib cannot declare child packages 11784 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 11785 throw new PackageManagerException( 11786 "Packages declaring static-shared libs cannot have child packages"); 11787 } 11788 11789 // Package declaring static a shared lib cannot declare dynamic libs 11790 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 11791 throw new PackageManagerException( 11792 "Packages declaring static-shared libs cannot declare dynamic libs"); 11793 } 11794 11795 // Package declaring static a shared lib cannot declare shared users 11796 if (pkg.mSharedUserId != null) { 11797 throw new PackageManagerException( 11798 "Packages declaring static-shared libs cannot declare shared users"); 11799 } 11800 11801 // Static shared libs cannot declare activities 11802 if (!pkg.activities.isEmpty()) { 11803 throw new PackageManagerException( 11804 "Static shared libs cannot declare activities"); 11805 } 11806 11807 // Static shared libs cannot declare services 11808 if (!pkg.services.isEmpty()) { 11809 throw new PackageManagerException( 11810 "Static shared libs cannot declare services"); 11811 } 11812 11813 // Static shared libs cannot declare providers 11814 if (!pkg.providers.isEmpty()) { 11815 throw new PackageManagerException( 11816 "Static shared libs cannot declare content providers"); 11817 } 11818 11819 // Static shared libs cannot declare receivers 11820 if (!pkg.receivers.isEmpty()) { 11821 throw new PackageManagerException( 11822 "Static shared libs cannot declare broadcast receivers"); 11823 } 11824 11825 // Static shared libs cannot declare permission groups 11826 if (!pkg.permissionGroups.isEmpty()) { 11827 throw new PackageManagerException( 11828 "Static shared libs cannot declare permission groups"); 11829 } 11830 11831 // Static shared libs cannot declare permissions 11832 if (!pkg.permissions.isEmpty()) { 11833 throw new PackageManagerException( 11834 "Static shared libs cannot declare permissions"); 11835 } 11836 11837 // Static shared libs cannot declare protected broadcasts 11838 if (pkg.protectedBroadcasts != null) { 11839 throw new PackageManagerException( 11840 "Static shared libs cannot declare protected broadcasts"); 11841 } 11842 11843 // Static shared libs cannot be overlay targets 11844 if (pkg.mOverlayTarget != null) { 11845 throw new PackageManagerException( 11846 "Static shared libs cannot be overlay targets"); 11847 } 11848 11849 // The version codes must be ordered as lib versions 11850 long minVersionCode = Long.MIN_VALUE; 11851 long maxVersionCode = Long.MAX_VALUE; 11852 11853 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get( 11854 pkg.staticSharedLibName); 11855 if (versionedLib != null) { 11856 final int versionCount = versionedLib.size(); 11857 for (int i = 0; i < versionCount; i++) { 11858 SharedLibraryInfo libInfo = versionedLib.valueAt(i); 11859 final long libVersionCode = libInfo.getDeclaringPackage() 11860 .getLongVersionCode(); 11861 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 11862 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 11863 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 11864 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 11865 } else { 11866 minVersionCode = maxVersionCode = libVersionCode; 11867 break; 11868 } 11869 } 11870 } 11871 if (pkg.getLongVersionCode() < minVersionCode 11872 || pkg.getLongVersionCode() > maxVersionCode) { 11873 throw new PackageManagerException("Static shared" 11874 + " lib version codes must be ordered as lib versions"); 11875 } 11876 } 11877 11878 // Only privileged apps and updated privileged apps can add child packages. 11879 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 11880 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 11881 throw new PackageManagerException("Only privileged apps can add child " 11882 + "packages. Ignoring package " + pkg.packageName); 11883 } 11884 final int childCount = pkg.childPackages.size(); 11885 for (int i = 0; i < childCount; i++) { 11886 PackageParser.Package childPkg = pkg.childPackages.get(i); 11887 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 11888 childPkg.packageName)) { 11889 throw new PackageManagerException("Can't override child of " 11890 + "another disabled app. Ignoring package " + pkg.packageName); 11891 } 11892 } 11893 } 11894 11895 // If we're only installing presumed-existing packages, require that the 11896 // scanned APK is both already known and at the path previously established 11897 // for it. Previously unknown packages we pick up normally, but if we have an 11898 // a priori expectation about this package's install presence, enforce it. 11899 // With a singular exception for new system packages. When an OTA contains 11900 // a new system package, we allow the codepath to change from a system location 11901 // to the user-installed location. If we don't allow this change, any newer, 11902 // user-installed version of the application will be ignored. 11903 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 11904 if (mExpectingBetter.containsKey(pkg.packageName)) { 11905 logCriticalInfo(Log.WARN, 11906 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 11907 } else { 11908 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 11909 if (known != null) { 11910 if (DEBUG_PACKAGE_SCANNING) { 11911 Log.d(TAG, "Examining " + pkg.codePath 11912 + " and requiring known paths " + known.codePathString 11913 + " & " + known.resourcePathString); 11914 } 11915 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 11916 || !pkg.applicationInfo.getResourcePath().equals( 11917 known.resourcePathString)) { 11918 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 11919 "Application package " + pkg.packageName 11920 + " found at " + pkg.applicationInfo.getCodePath() 11921 + " but expected at " + known.codePathString 11922 + "; ignoring."); 11923 } 11924 } else { 11925 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11926 "Application package " + pkg.packageName 11927 + " not found; ignoring."); 11928 } 11929 } 11930 } 11931 11932 // Verify that this new package doesn't have any content providers 11933 // that conflict with existing packages. Only do this if the 11934 // package isn't already installed, since we don't want to break 11935 // things that are installed. 11936 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11937 mComponentResolver.assertProvidersNotDefined(pkg); 11938 } 11939 11940 // Verify that packages sharing a user with a privileged app are marked as privileged. 11941 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11942 SharedUserSetting sharedUserSetting = null; 11943 try { 11944 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11945 } catch (PackageManagerException ignore) {} 11946 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11947 // Exempt SharedUsers signed with the platform key. 11948 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11949 if ((platformPkgSetting.signatures.mSigningDetails 11950 != PackageParser.SigningDetails.UNKNOWN) 11951 && (compareSignatures( 11952 platformPkgSetting.signatures.mSigningDetails.signatures, 11953 pkg.mSigningDetails.signatures) 11954 != PackageManager.SIGNATURE_MATCH)) { 11955 throw new PackageManagerException("Apps that share a user with a " + 11956 "privileged app must themselves be marked as privileged. " + 11957 pkg.packageName + " shares privileged user " + 11958 pkg.mSharedUserId + "."); 11959 } 11960 } 11961 } 11962 11963 // Apply policies specific for runtime resource overlays (RROs). 11964 if (pkg.mOverlayTarget != null) { 11965 // System overlays have some restrictions on their use of the 'static' state. 11966 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11967 // We are scanning a system overlay. This can be the first scan of the 11968 // system/vendor/oem partition, or an update to the system overlay. 11969 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11970 // This must be an update to a system overlay. 11971 final PackageSetting previousPkg = assertNotNull( 11972 mSettings.getPackageLPr(pkg.packageName), 11973 "previous package state not present"); 11974 11975 // previousPkg.pkg may be null: the package will be not be scanned if the 11976 // package manager knows there is a newer version on /data. 11977 // TODO[b/79435695]: Find a better way to keep track of the "static" 11978 // property for RROs instead of having to parse packages on /system 11979 PackageParser.Package ppkg = previousPkg.pkg; 11980 if (ppkg == null) { 11981 try { 11982 final PackageParser pp = new PackageParser(); 11983 ppkg = pp.parsePackage(previousPkg.codePath, 11984 parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR); 11985 } catch (PackageParserException e) { 11986 Slog.w(TAG, "failed to parse " + previousPkg.codePath, e); 11987 } 11988 } 11989 11990 // Static overlays cannot be updated. 11991 if (ppkg != null && ppkg.mOverlayIsStatic) { 11992 throw new PackageManagerException("Overlay " + pkg.packageName + 11993 " is static and cannot be upgraded."); 11994 // Non-static overlays cannot be converted to static overlays. 11995 } else if (pkg.mOverlayIsStatic) { 11996 throw new PackageManagerException("Overlay " + pkg.packageName + 11997 " cannot be upgraded into a static overlay."); 11998 } 11999 } 12000 } else { 12001 // The overlay is a non-system overlay. Non-system overlays cannot be static. 12002 if (pkg.mOverlayIsStatic) { 12003 throw new PackageManagerException("Overlay " + pkg.packageName + 12004 " is static but not pre-installed."); 12005 } 12006 12007 // A non-preloaded overlay packages must have targetSdkVersion >= Q, or be 12008 // signed with the platform certificate. Check this in increasing order of 12009 // computational cost. 12010 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.Q) { 12011 final PackageSetting platformPkgSetting = 12012 mSettings.getPackageLPr("android"); 12013 if ((platformPkgSetting.signatures.mSigningDetails 12014 != PackageParser.SigningDetails.UNKNOWN) 12015 && (compareSignatures( 12016 platformPkgSetting.signatures.mSigningDetails.signatures, 12017 pkg.mSigningDetails.signatures) 12018 != PackageManager.SIGNATURE_MATCH)) { 12019 throw new PackageManagerException("Overlay " + pkg.packageName 12020 + " must target Q or later, " 12021 + "or be signed with the platform certificate"); 12022 } 12023 } 12024 12025 // A non-preloaded overlay package, without <overlay android:targetName>, will 12026 // only be used if it is signed with the same certificate as its target. If the 12027 // target is already installed, check this here to augment the last line of 12028 // defence which is OMS. 12029 if (pkg.mOverlayTargetName == null) { 12030 final PackageSetting targetPkgSetting = 12031 mSettings.getPackageLPr(pkg.mOverlayTarget); 12032 if (targetPkgSetting != null) { 12033 if ((targetPkgSetting.signatures.mSigningDetails 12034 != PackageParser.SigningDetails.UNKNOWN) 12035 && (compareSignatures( 12036 targetPkgSetting.signatures.mSigningDetails.signatures, 12037 pkg.mSigningDetails.signatures) 12038 != PackageManager.SIGNATURE_MATCH)) { 12039 throw new PackageManagerException("Overlay " + pkg.packageName 12040 + " and target " + pkg.mOverlayTarget + " signed with" 12041 + " different certificates, and the overlay lacks" 12042 + " <overlay android:targetName>"); 12043 } 12044 } 12045 } 12046 } 12047 } 12048 } 12049 } 12050 12051 @GuardedBy("mPackages") 12052 private boolean addBuiltInSharedLibraryLocked(String path, String name) { 12053 if (nonStaticSharedLibExistsLocked(name)) { 12054 return false; 12055 } 12056 12057 SharedLibraryInfo libraryInfo = new SharedLibraryInfo(path, null, null, name, 12058 (long) SharedLibraryInfo.VERSION_UNDEFINED, SharedLibraryInfo.TYPE_BUILTIN, 12059 new VersionedPackage(PLATFORM_PACKAGE_NAME, (long) 0), 12060 null, null); 12061 12062 commitSharedLibraryInfoLocked(libraryInfo); 12063 return true; 12064 } 12065 12066 @GuardedBy("mPackages") 12067 private boolean nonStaticSharedLibExistsLocked(String name) { 12068 return sharedLibExists(name, SharedLibraryInfo.VERSION_UNDEFINED, mSharedLibraries); 12069 } 12070 12071 private static boolean sharedLibExists(final String name, final long version, 12072 Map<String, LongSparseArray<SharedLibraryInfo>> librarySource) { 12073 LongSparseArray<SharedLibraryInfo> versionedLib = librarySource.get(name); 12074 if (versionedLib != null && versionedLib.indexOfKey(version) >= 0) { 12075 return true; 12076 } 12077 return false; 12078 } 12079 12080 @GuardedBy("mPackages") 12081 private void commitSharedLibraryInfoLocked(SharedLibraryInfo libraryInfo) { 12082 final String name = libraryInfo.getName(); 12083 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name); 12084 if (versionedLib == null) { 12085 versionedLib = new LongSparseArray<>(); 12086 mSharedLibraries.put(name, versionedLib); 12087 } 12088 final String declaringPackageName = libraryInfo.getDeclaringPackage().getPackageName(); 12089 if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) { 12090 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 12091 } 12092 versionedLib.put(libraryInfo.getLongVersion(), libraryInfo); 12093 } 12094 12095 private boolean removeSharedLibraryLPw(String name, long version) { 12096 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name); 12097 if (versionedLib == null) { 12098 return false; 12099 } 12100 final int libIdx = versionedLib.indexOfKey(version); 12101 if (libIdx < 0) { 12102 return false; 12103 } 12104 SharedLibraryInfo libraryInfo = versionedLib.valueAt(libIdx); 12105 versionedLib.remove(version); 12106 if (versionedLib.size() <= 0) { 12107 mSharedLibraries.remove(name); 12108 if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) { 12109 mStaticLibsByDeclaringPackage.remove(libraryInfo.getDeclaringPackage() 12110 .getPackageName()); 12111 } 12112 } 12113 return true; 12114 } 12115 12116 /** 12117 * Adds a scanned package to the system. When this method is finished, the package will 12118 * be available for query, resolution, etc... 12119 */ 12120 private void commitPackageSettings(PackageParser.Package pkg, 12121 @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, 12122 final @ScanFlags int scanFlags, boolean chatty, ReconciledPackage reconciledPkg) { 12123 final String pkgName = pkg.packageName; 12124 if (mCustomResolverComponentName != null && 12125 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 12126 setUpCustomResolverActivity(pkg); 12127 } 12128 12129 if (pkg.packageName.equals("android")) { 12130 synchronized (mPackages) { 12131 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 12132 // Set up information for our fall-back user intent resolution activity. 12133 mPlatformPackage = pkg; 12134 pkg.mVersionCode = mSdkVersion; 12135 pkg.mVersionCodeMajor = 0; 12136 mAndroidApplication = pkg.applicationInfo; 12137 if (!mResolverReplaced) { 12138 mResolveActivity.applicationInfo = mAndroidApplication; 12139 mResolveActivity.name = ResolverActivity.class.getName(); 12140 mResolveActivity.packageName = mAndroidApplication.packageName; 12141 mResolveActivity.processName = "system:ui"; 12142 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 12143 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 12144 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 12145 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 12146 mResolveActivity.exported = true; 12147 mResolveActivity.enabled = true; 12148 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 12149 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 12150 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 12151 | ActivityInfo.CONFIG_SCREEN_LAYOUT 12152 | ActivityInfo.CONFIG_ORIENTATION 12153 | ActivityInfo.CONFIG_KEYBOARD 12154 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 12155 mResolveInfo.activityInfo = mResolveActivity; 12156 mResolveInfo.priority = 0; 12157 mResolveInfo.preferredOrder = 0; 12158 mResolveInfo.match = 0; 12159 mResolveComponentName = new ComponentName( 12160 mAndroidApplication.packageName, mResolveActivity.name); 12161 } 12162 } 12163 } 12164 } 12165 12166 ArrayList<PackageParser.Package> clientLibPkgs = null; 12167 // writer 12168 synchronized (mPackages) { 12169 if (!ArrayUtils.isEmpty(reconciledPkg.allowedSharedLibraryInfos)) { 12170 for (SharedLibraryInfo info : reconciledPkg.allowedSharedLibraryInfos) { 12171 commitSharedLibraryInfoLocked(info); 12172 } 12173 final Map<String, PackageParser.Package> combinedPackages = 12174 reconciledPkg.getCombinedPackages(); 12175 try { 12176 // Shared libraries for the package need to be updated. 12177 updateSharedLibrariesLocked(pkg, null, combinedPackages); 12178 } catch (PackageManagerException e) { 12179 Slog.e(TAG, "updateSharedLibrariesLPr failed: ", e); 12180 } 12181 // Update all applications that use this library. Skip when booting 12182 // since this will be done after all packages are scaned. 12183 if ((scanFlags & SCAN_BOOTING) == 0) { 12184 clientLibPkgs = updateAllSharedLibrariesLocked(pkg, combinedPackages); 12185 } 12186 } 12187 } 12188 12189 if ((scanFlags & SCAN_BOOTING) != 0) { 12190 // No apps can run during boot scan, so they don't need to be frozen 12191 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 12192 // Caller asked to not kill app, so it's probably not frozen 12193 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 12194 // Caller asked us to ignore frozen check for some reason; they 12195 // probably didn't know the package name 12196 } else { 12197 // We're doing major surgery on this package, so it better be frozen 12198 // right now to keep it from launching 12199 checkPackageFrozen(pkgName); 12200 } 12201 12202 // Also need to kill any apps that are dependent on the library. 12203 if (clientLibPkgs != null) { 12204 for (int i=0; i<clientLibPkgs.size(); i++) { 12205 PackageParser.Package clientPkg = clientLibPkgs.get(i); 12206 killApplication(clientPkg.applicationInfo.packageName, 12207 clientPkg.applicationInfo.uid, "update lib"); 12208 } 12209 } 12210 12211 // writer 12212 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12213 12214 synchronized (mPackages) { 12215 // We don't expect installation to fail beyond this point 12216 12217 // Add the new setting to mSettings 12218 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 12219 // Add the new setting to mPackages 12220 mPackages.put(pkg.applicationInfo.packageName, pkg); 12221 12222 // Add the package's KeySets to the global KeySetManagerService 12223 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12224 ksms.addScannedPackageLPw(pkg); 12225 12226 mComponentResolver.addAllComponents(pkg, chatty); 12227 12228 // Don't allow ephemeral applications to define new permissions groups. 12229 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 12230 Slog.w(TAG, "Permission groups from package " + pkg.packageName 12231 + " ignored: instant apps cannot define new permission groups."); 12232 } else { 12233 mPermissionManager.addAllPermissionGroups(pkg, chatty); 12234 } 12235 12236 // Don't allow ephemeral applications to define new permissions. 12237 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 12238 Slog.w(TAG, "Permissions from package " + pkg.packageName 12239 + " ignored: instant apps cannot define new permissions."); 12240 } else { 12241 mPermissionManager.addAllPermissions(pkg, chatty); 12242 } 12243 12244 int collectionSize = pkg.instrumentation.size(); 12245 StringBuilder r = null; 12246 int i; 12247 for (i = 0; i < collectionSize; i++) { 12248 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12249 a.info.packageName = pkg.applicationInfo.packageName; 12250 a.info.sourceDir = pkg.applicationInfo.sourceDir; 12251 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 12252 a.info.splitNames = pkg.splitNames; 12253 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 12254 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 12255 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 12256 a.info.dataDir = pkg.applicationInfo.dataDir; 12257 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 12258 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 12259 a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 12260 a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi; 12261 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 12262 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 12263 mInstrumentation.put(a.getComponentName(), a); 12264 if (chatty) { 12265 if (r == null) { 12266 r = new StringBuilder(256); 12267 } else { 12268 r.append(' '); 12269 } 12270 r.append(a.info.name); 12271 } 12272 } 12273 if (r != null) { 12274 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 12275 } 12276 12277 if (pkg.protectedBroadcasts != null) { 12278 collectionSize = pkg.protectedBroadcasts.size(); 12279 synchronized (mProtectedBroadcasts) { 12280 for (i = 0; i < collectionSize; i++) { 12281 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 12282 } 12283 } 12284 } 12285 12286 if (oldPkg != null) { 12287 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission 12288 // revoke callbacks from this method might need to kill apps which need the 12289 // mPackages lock on a different thread. This would dead lock. 12290 // 12291 // Hence create a copy of all package names and pass it into 12292 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get 12293 // revoked. If a new package is added before the async code runs the permission 12294 // won't be granted yet, hence new packages are no problem. 12295 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet()); 12296 12297 AsyncTask.execute(() -> 12298 mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, 12299 allPackageNames, mPermissionCallback)); 12300 } 12301 } 12302 12303 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12304 } 12305 12306 /** 12307 * Derive the ABI of a non-system package located at {@code scanFile}. This information 12308 * is derived purely on the basis of the contents of {@code scanFile} and 12309 * {@code cpuAbiOverride}. 12310 * 12311 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 12312 */ 12313 private static void derivePackageAbi(PackageParser.Package pkg, String cpuAbiOverride, 12314 boolean extractLibs) 12315 throws PackageManagerException { 12316 // Give ourselves some initial paths; we'll come back for another 12317 // pass once we've determined ABI below. 12318 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 12319 12320 // We shouldn't attempt to extract libs from system app when it was not updated. 12321 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp()) { 12322 extractLibs = false; 12323 } 12324 12325 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 12326 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 12327 12328 NativeLibraryHelper.Handle handle = null; 12329 try { 12330 handle = NativeLibraryHelper.Handle.create(pkg); 12331 // TODO(multiArch): This can be null for apps that didn't go through the 12332 // usual installation process. We can calculate it again, like we 12333 // do during install time. 12334 // 12335 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 12336 // unnecessary. 12337 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 12338 12339 // Null out the abis so that they can be recalculated. 12340 pkg.applicationInfo.primaryCpuAbi = null; 12341 pkg.applicationInfo.secondaryCpuAbi = null; 12342 if (isMultiArch(pkg.applicationInfo)) { 12343 // Warn if we've set an abiOverride for multi-lib packages.. 12344 // By definition, we need to copy both 32 and 64 bit libraries for 12345 // such packages. 12346 if (pkg.cpuAbiOverride != null 12347 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 12348 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 12349 } 12350 12351 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 12352 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 12353 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 12354 if (extractLibs) { 12355 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12356 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12357 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 12358 useIsaSpecificSubdirs); 12359 } else { 12360 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12361 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 12362 } 12363 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12364 } 12365 12366 // Shared library native code should be in the APK zip aligned 12367 if (abi32 >= 0 && pkg.isLibrary() && extractLibs) { 12368 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12369 "Shared library native lib extraction not supported"); 12370 } 12371 12372 maybeThrowExceptionForMultiArchCopy( 12373 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 12374 12375 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 12376 if (extractLibs) { 12377 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12378 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12379 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 12380 useIsaSpecificSubdirs); 12381 } else { 12382 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12383 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 12384 } 12385 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12386 } 12387 12388 maybeThrowExceptionForMultiArchCopy( 12389 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 12390 12391 if (abi64 >= 0) { 12392 // Shared library native libs should be in the APK zip aligned 12393 if (extractLibs && pkg.isLibrary()) { 12394 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12395 "Shared library native lib extraction not supported"); 12396 } 12397 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 12398 } 12399 12400 if (abi32 >= 0) { 12401 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 12402 if (abi64 >= 0) { 12403 if (pkg.use32bitAbi) { 12404 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 12405 pkg.applicationInfo.primaryCpuAbi = abi; 12406 } else { 12407 pkg.applicationInfo.secondaryCpuAbi = abi; 12408 } 12409 } else { 12410 pkg.applicationInfo.primaryCpuAbi = abi; 12411 } 12412 } 12413 } else { 12414 String[] abiList = (cpuAbiOverride != null) ? 12415 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 12416 12417 // Enable gross and lame hacks for apps that are built with old 12418 // SDK tools. We must scan their APKs for renderscript bitcode and 12419 // not launch them if it's present. Don't bother checking on devices 12420 // that don't have 64 bit support. 12421 boolean needsRenderScriptOverride = false; 12422 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 12423 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 12424 abiList = Build.SUPPORTED_32_BIT_ABIS; 12425 needsRenderScriptOverride = true; 12426 } 12427 12428 final int copyRet; 12429 if (extractLibs) { 12430 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyNativeBinaries"); 12431 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 12432 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 12433 } else { 12434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "findSupportedAbi"); 12435 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 12436 } 12437 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12438 12439 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 12440 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12441 "Error unpackaging native libs for app, errorCode=" + copyRet); 12442 } 12443 12444 if (copyRet >= 0) { 12445 // Shared libraries that have native libs must be multi-architecture 12446 if (pkg.isLibrary()) { 12447 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 12448 "Shared library with native libs must be multiarch"); 12449 } 12450 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 12451 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 12452 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 12453 } else if (needsRenderScriptOverride) { 12454 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 12455 } 12456 } 12457 } catch (IOException ioe) { 12458 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 12459 } finally { 12460 IoUtils.closeQuietly(handle); 12461 } 12462 12463 // Now that we've calculated the ABIs and determined if it's an internal app, 12464 // we will go ahead and populate the nativeLibraryPath. 12465 setNativeLibraryPaths(pkg, sAppLib32InstallDir); 12466 } 12467 12468 /** 12469 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 12470 * i.e, so that all packages can be run inside a single process if required. 12471 * 12472 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 12473 * this function will either try and make the ABI for all packages in {@code packagesForUser} 12474 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 12475 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 12476 * updating a package that belongs to a shared user. 12477 * 12478 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 12479 * adds unnecessary complexity. 12480 */ 12481 private static @Nullable List<String> adjustCpuAbisForSharedUserLPw( 12482 Set<PackageSetting> packagesForUser, PackageParser.Package scannedPackage) { 12483 List<String> changedAbiCodePath = null; 12484 String requiredInstructionSet = null; 12485 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 12486 requiredInstructionSet = VMRuntime.getInstructionSet( 12487 scannedPackage.applicationInfo.primaryCpuAbi); 12488 } 12489 12490 PackageSetting requirer = null; 12491 for (PackageSetting ps : packagesForUser) { 12492 // If packagesForUser contains scannedPackage, we skip it. This will happen 12493 // when scannedPackage is an update of an existing package. Without this check, 12494 // we will never be able to change the ABI of any package belonging to a shared 12495 // user, even if it's compatible with other packages. 12496 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 12497 if (ps.primaryCpuAbiString == null) { 12498 continue; 12499 } 12500 12501 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 12502 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 12503 // We have a mismatch between instruction sets (say arm vs arm64) warn about 12504 // this but there's not much we can do. 12505 String errorMessage = "Instruction set mismatch, " 12506 + ((requirer == null) ? "[caller]" : requirer) 12507 + " requires " + requiredInstructionSet + " whereas " + ps 12508 + " requires " + instructionSet; 12509 Slog.w(TAG, errorMessage); 12510 } 12511 12512 if (requiredInstructionSet == null) { 12513 requiredInstructionSet = instructionSet; 12514 requirer = ps; 12515 } 12516 } 12517 } 12518 12519 if (requiredInstructionSet != null) { 12520 String adjustedAbi; 12521 if (requirer != null) { 12522 // requirer != null implies that either scannedPackage was null or that scannedPackage 12523 // did not require an ABI, in which case we have to adjust scannedPackage to match 12524 // the ABI of the set (which is the same as requirer's ABI) 12525 adjustedAbi = requirer.primaryCpuAbiString; 12526 if (scannedPackage != null) { 12527 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 12528 } 12529 } else { 12530 // requirer == null implies that we're updating all ABIs in the set to 12531 // match scannedPackage. 12532 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 12533 } 12534 12535 for (PackageSetting ps : packagesForUser) { 12536 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 12537 if (ps.primaryCpuAbiString != null) { 12538 continue; 12539 } 12540 12541 ps.primaryCpuAbiString = adjustedAbi; 12542 if (ps.pkg != null && ps.pkg.applicationInfo != null && 12543 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 12544 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 12545 if (DEBUG_ABI_SELECTION) { 12546 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 12547 + " (requirer=" 12548 + (requirer != null ? requirer.pkg : "null") 12549 + ", scannedPackage=" 12550 + (scannedPackage != null ? scannedPackage : "null") 12551 + ")"); 12552 } 12553 if (changedAbiCodePath == null) { 12554 changedAbiCodePath = new ArrayList<>(); 12555 } 12556 changedAbiCodePath.add(ps.codePathString); 12557 } 12558 } 12559 } 12560 } 12561 return changedAbiCodePath; 12562 } 12563 12564 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 12565 synchronized (mPackages) { 12566 mResolverReplaced = true; 12567 // Set up information for custom user intent resolution activity. 12568 mResolveActivity.applicationInfo = pkg.applicationInfo; 12569 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 12570 mResolveActivity.packageName = pkg.applicationInfo.packageName; 12571 mResolveActivity.processName = pkg.applicationInfo.packageName; 12572 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 12573 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 12574 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12575 mResolveActivity.theme = 0; 12576 mResolveActivity.exported = true; 12577 mResolveActivity.enabled = true; 12578 mResolveInfo.activityInfo = mResolveActivity; 12579 mResolveInfo.priority = 0; 12580 mResolveInfo.preferredOrder = 0; 12581 mResolveInfo.match = 0; 12582 mResolveComponentName = mCustomResolverComponentName; 12583 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 12584 mResolveComponentName); 12585 } 12586 } 12587 12588 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 12589 if (installerActivity == null) { 12590 if (DEBUG_INSTANT) { 12591 Slog.d(TAG, "Clear ephemeral installer activity"); 12592 } 12593 mInstantAppInstallerActivity = null; 12594 return; 12595 } 12596 12597 if (DEBUG_INSTANT) { 12598 Slog.d(TAG, "Set ephemeral installer activity: " 12599 + installerActivity.getComponentName()); 12600 } 12601 // Set up information for ephemeral installer activity 12602 mInstantAppInstallerActivity = installerActivity; 12603 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 12604 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12605 mInstantAppInstallerActivity.exported = true; 12606 mInstantAppInstallerActivity.enabled = true; 12607 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 12608 mInstantAppInstallerInfo.priority = 1; 12609 mInstantAppInstallerInfo.preferredOrder = 1; 12610 mInstantAppInstallerInfo.isDefault = true; 12611 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 12612 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 12613 } 12614 12615 private static String calculateBundledApkRoot(final String codePathString) { 12616 final File codePath = new File(codePathString); 12617 final File codeRoot; 12618 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 12619 codeRoot = Environment.getRootDirectory(); 12620 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 12621 codeRoot = Environment.getOemDirectory(); 12622 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 12623 codeRoot = Environment.getVendorDirectory(); 12624 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 12625 codeRoot = Environment.getOdmDirectory(); 12626 } else if (FileUtils.contains(Environment.getProductDirectory(), codePath)) { 12627 codeRoot = Environment.getProductDirectory(); 12628 } else if (FileUtils.contains(Environment.getProductServicesDirectory(), codePath)) { 12629 codeRoot = Environment.getProductServicesDirectory(); 12630 } else if (FileUtils.contains(Environment.getOdmDirectory(), codePath)) { 12631 codeRoot = Environment.getOdmDirectory(); 12632 } else { 12633 // Unrecognized code path; take its top real segment as the apk root: 12634 // e.g. /something/app/blah.apk => /something 12635 try { 12636 File f = codePath.getCanonicalFile(); 12637 File parent = f.getParentFile(); // non-null because codePath is a file 12638 File tmp; 12639 while ((tmp = parent.getParentFile()) != null) { 12640 f = parent; 12641 parent = tmp; 12642 } 12643 codeRoot = f; 12644 Slog.w(TAG, "Unrecognized code path " 12645 + codePath + " - using " + codeRoot); 12646 } catch (IOException e) { 12647 // Can't canonicalize the code path -- shenanigans? 12648 Slog.w(TAG, "Can't canonicalize code path " + codePath); 12649 return Environment.getRootDirectory().getPath(); 12650 } 12651 } 12652 return codeRoot.getPath(); 12653 } 12654 12655 /** 12656 * Derive and set the location of native libraries for the given package, 12657 * which varies depending on where and how the package was installed. 12658 */ 12659 private static void setNativeLibraryPaths(PackageParser.Package pkg, File appLib32InstallDir) { 12660 final ApplicationInfo info = pkg.applicationInfo; 12661 final String codePath = pkg.codePath; 12662 final File codeFile = new File(codePath); 12663 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 12664 12665 info.nativeLibraryRootDir = null; 12666 info.nativeLibraryRootRequiresIsa = false; 12667 info.nativeLibraryDir = null; 12668 info.secondaryNativeLibraryDir = null; 12669 12670 if (isApkFile(codeFile)) { 12671 // Monolithic install 12672 if (bundledApp) { 12673 // If "/system/lib64/apkname" exists, assume that is the per-package 12674 // native library directory to use; otherwise use "/system/lib/apkname". 12675 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 12676 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 12677 getPrimaryInstructionSet(info)); 12678 12679 // This is a bundled system app so choose the path based on the ABI. 12680 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 12681 // is just the default path. 12682 final String apkName = deriveCodePathName(codePath); 12683 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 12684 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 12685 apkName).getAbsolutePath(); 12686 12687 if (info.secondaryCpuAbi != null) { 12688 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 12689 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 12690 secondaryLibDir, apkName).getAbsolutePath(); 12691 } 12692 } else { 12693 final String apkName = deriveCodePathName(codePath); 12694 info.nativeLibraryRootDir = new File(appLib32InstallDir, apkName) 12695 .getAbsolutePath(); 12696 } 12697 12698 info.nativeLibraryRootRequiresIsa = false; 12699 info.nativeLibraryDir = info.nativeLibraryRootDir; 12700 } else { 12701 // Cluster install 12702 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 12703 info.nativeLibraryRootRequiresIsa = true; 12704 12705 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 12706 getPrimaryInstructionSet(info)).getAbsolutePath(); 12707 12708 if (info.secondaryCpuAbi != null) { 12709 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 12710 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 12711 } 12712 } 12713 } 12714 12715 /** 12716 * Calculate the abis and roots for a bundled app. These can uniquely 12717 * be determined from the contents of the system partition, i.e whether 12718 * it contains 64 or 32 bit shared libraries etc. We do not validate any 12719 * of this information, and instead assume that the system was built 12720 * sensibly. 12721 */ 12722 private static void setBundledAppAbisAndRoots(PackageParser.Package pkg, 12723 PackageSetting pkgSetting) { 12724 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 12725 12726 // If "/system/lib64/apkname" exists, assume that is the per-package 12727 // native library directory to use; otherwise use "/system/lib/apkname". 12728 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 12729 setBundledAppAbi(pkg, apkRoot, apkName); 12730 // pkgSetting might be null during rescan following uninstall of updates 12731 // to a bundled app, so accommodate that possibility. The settings in 12732 // that case will be established later from the parsed package. 12733 // 12734 // If the settings aren't null, sync them up with what we've just derived. 12735 // note that apkRoot isn't stored in the package settings. 12736 if (pkgSetting != null) { 12737 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 12738 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 12739 } 12740 } 12741 12742 /** 12743 * Deduces the ABI of a bundled app and sets the relevant fields on the 12744 * parsed pkg object. 12745 * 12746 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 12747 * under which system libraries are installed. 12748 * @param apkName the name of the installed package. 12749 */ 12750 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 12751 final File codeFile = new File(pkg.codePath); 12752 12753 final boolean has64BitLibs; 12754 final boolean has32BitLibs; 12755 if (isApkFile(codeFile)) { 12756 // Monolithic install 12757 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 12758 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 12759 } else { 12760 // Cluster install 12761 final File rootDir = new File(codeFile, LIB_DIR_NAME); 12762 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 12763 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 12764 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 12765 has64BitLibs = (new File(rootDir, isa)).exists(); 12766 } else { 12767 has64BitLibs = false; 12768 } 12769 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 12770 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 12771 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 12772 has32BitLibs = (new File(rootDir, isa)).exists(); 12773 } else { 12774 has32BitLibs = false; 12775 } 12776 } 12777 12778 if (has64BitLibs && !has32BitLibs) { 12779 // The package has 64 bit libs, but not 32 bit libs. Its primary 12780 // ABI should be 64 bit. We can safely assume here that the bundled 12781 // native libraries correspond to the most preferred ABI in the list. 12782 12783 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12784 pkg.applicationInfo.secondaryCpuAbi = null; 12785 } else if (has32BitLibs && !has64BitLibs) { 12786 // The package has 32 bit libs but not 64 bit libs. Its primary 12787 // ABI should be 32 bit. 12788 12789 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12790 pkg.applicationInfo.secondaryCpuAbi = null; 12791 } else if (has32BitLibs && has64BitLibs) { 12792 // The application has both 64 and 32 bit bundled libraries. We check 12793 // here that the app declares multiArch support, and warn if it doesn't. 12794 // 12795 // We will be lenient here and record both ABIs. The primary will be the 12796 // ABI that's higher on the list, i.e, a device that's configured to prefer 12797 // 64 bit apps will see a 64 bit primary ABI, 12798 12799 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 12800 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 12801 } 12802 12803 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 12804 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12805 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12806 } else { 12807 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 12808 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 12809 } 12810 } else { 12811 pkg.applicationInfo.primaryCpuAbi = null; 12812 pkg.applicationInfo.secondaryCpuAbi = null; 12813 } 12814 } 12815 12816 private void killApplication(String pkgName, int appId, String reason) { 12817 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12818 } 12819 12820 private void killApplication(String pkgName, int appId, int userId, String reason) { 12821 // Request the ActivityManager to kill the process(only for existing packages) 12822 // so that we do not end up in a confused state while the user is still using the older 12823 // version of the application while the new one gets installed. 12824 final long token = Binder.clearCallingIdentity(); 12825 try { 12826 IActivityManager am = ActivityManager.getService(); 12827 if (am != null) { 12828 try { 12829 am.killApplication(pkgName, appId, userId, reason); 12830 } catch (RemoteException e) { 12831 } 12832 } 12833 } finally { 12834 Binder.restoreCallingIdentity(token); 12835 } 12836 } 12837 12838 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12839 // Remove the parent package setting 12840 PackageSetting ps = (PackageSetting) pkg.mExtras; 12841 if (ps != null) { 12842 removePackageLI(ps.name, chatty); 12843 } else if (DEBUG_REMOVE && chatty) { 12844 Log.d(TAG, "Not removing package " + pkg.packageName + "; mExtras == null"); 12845 } 12846 // Remove the child package setting 12847 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12848 for (int i = 0; i < childCount; i++) { 12849 PackageParser.Package childPkg = pkg.childPackages.get(i); 12850 ps = (PackageSetting) childPkg.mExtras; 12851 if (ps != null) { 12852 removePackageLI(ps.name, chatty); 12853 } 12854 } 12855 } 12856 12857 void removePackageLI(String packageName, boolean chatty) { 12858 if (DEBUG_INSTALL) { 12859 if (chatty) 12860 Log.d(TAG, "Removing package " + packageName); 12861 } 12862 12863 // writer 12864 synchronized (mPackages) { 12865 final PackageParser.Package removedPackage = mPackages.remove(packageName); 12866 if (removedPackage != null) { 12867 cleanPackageDataStructuresLILPw(removedPackage, chatty); 12868 } 12869 } 12870 } 12871 12872 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12873 if (DEBUG_INSTALL) { 12874 if (chatty) 12875 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12876 } 12877 12878 // writer 12879 synchronized (mPackages) { 12880 // Remove the parent package 12881 mPackages.remove(pkg.applicationInfo.packageName); 12882 cleanPackageDataStructuresLILPw(pkg, chatty); 12883 12884 // Remove the child packages 12885 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12886 for (int i = 0; i < childCount; i++) { 12887 PackageParser.Package childPkg = pkg.childPackages.get(i); 12888 mPackages.remove(childPkg.applicationInfo.packageName); 12889 cleanPackageDataStructuresLILPw(childPkg, chatty); 12890 } 12891 } 12892 } 12893 12894 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12895 mComponentResolver.removeAllComponents(pkg, chatty); 12896 12897 mPermissionManager.removeAllPermissions(pkg, chatty); 12898 12899 final int instrumentationSize = pkg.instrumentation.size(); 12900 StringBuilder r = null; 12901 int i; 12902 for (i = 0; i < instrumentationSize; i++) { 12903 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12904 mInstrumentation.remove(a.getComponentName()); 12905 if (DEBUG_REMOVE && chatty) { 12906 if (r == null) { 12907 r = new StringBuilder(256); 12908 } else { 12909 r.append(' '); 12910 } 12911 r.append(a.info.name); 12912 } 12913 } 12914 if (r != null) { 12915 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12916 } 12917 12918 r = null; 12919 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12920 // Only system apps can hold shared libraries. 12921 if (pkg.libraryNames != null) { 12922 final int libraryNamesSize = pkg.libraryNames.size(); 12923 for (i = 0; i < libraryNamesSize; i++) { 12924 String name = pkg.libraryNames.get(i); 12925 if (removeSharedLibraryLPw(name, 0)) { 12926 if (DEBUG_REMOVE && chatty) { 12927 if (r == null) { 12928 r = new StringBuilder(256); 12929 } else { 12930 r.append(' '); 12931 } 12932 r.append(name); 12933 } 12934 } 12935 } 12936 } 12937 } 12938 12939 r = null; 12940 12941 // Any package can hold static shared libraries. 12942 if (pkg.staticSharedLibName != null) { 12943 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12944 if (DEBUG_REMOVE && chatty) { 12945 if (r == null) { 12946 r = new StringBuilder(256); 12947 } else { 12948 r.append(' '); 12949 } 12950 r.append(pkg.staticSharedLibName); 12951 } 12952 } 12953 } 12954 12955 if (r != null) { 12956 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12957 } 12958 } 12959 12960 @Override 12961 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12962 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12963 final int[] userIds, int[] instantUserIds) { 12964 mHandler.post(() -> { 12965 try { 12966 final IActivityManager am = ActivityManager.getService(); 12967 if (am == null) return; 12968 final int[] resolvedUserIds; 12969 if (userIds == null) { 12970 resolvedUserIds = am.getRunningUserIds(); 12971 } else { 12972 resolvedUserIds = userIds; 12973 } 12974 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12975 resolvedUserIds, false); 12976 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 12977 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12978 instantUserIds, true); 12979 } 12980 } catch (RemoteException ex) { 12981 } 12982 }); 12983 } 12984 12985 @Override 12986 public void notifyPackageAdded(String packageName, int uid) { 12987 final PackageListObserver[] observers; 12988 synchronized (mPackages) { 12989 if (mPackageListObservers.size() == 0) { 12990 return; 12991 } 12992 final PackageListObserver[] observerArray = 12993 new PackageListObserver[mPackageListObservers.size()]; 12994 observers = mPackageListObservers.toArray(observerArray); 12995 } 12996 for (int i = observers.length - 1; i >= 0; --i) { 12997 observers[i].onPackageAdded(packageName, uid); 12998 } 12999 } 13000 13001 @Override 13002 public void notifyPackageChanged(String packageName, int uid) { 13003 final PackageListObserver[] observers; 13004 synchronized (mPackages) { 13005 if (mPackageListObservers.size() == 0) { 13006 return; 13007 } 13008 final PackageListObserver[] observerArray = 13009 new PackageListObserver[mPackageListObservers.size()]; 13010 observers = mPackageListObservers.toArray(observerArray); 13011 } 13012 for (int i = observers.length - 1; i >= 0; --i) { 13013 observers[i].onPackageChanged(packageName, uid); 13014 } 13015 } 13016 13017 private static final Comparator<ProviderInfo> sProviderInitOrderSorter = (p1, p2) -> { 13018 final int v1 = p1.initOrder; 13019 final int v2 = p2.initOrder; 13020 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 13021 }; 13022 13023 @Override 13024 public void notifyPackageRemoved(String packageName, int uid) { 13025 final PackageListObserver[] observers; 13026 synchronized (mPackages) { 13027 if (mPackageListObservers.size() == 0) { 13028 return; 13029 } 13030 final PackageListObserver[] observerArray = 13031 new PackageListObserver[mPackageListObservers.size()]; 13032 observers = mPackageListObservers.toArray(observerArray); 13033 } 13034 for (int i = observers.length - 1; i >= 0; --i) { 13035 observers[i].onPackageRemoved(packageName, uid); 13036 } 13037 } 13038 13039 /** 13040 * Sends a broadcast for the given action. 13041 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 13042 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 13043 * the system and applications allowed to see instant applications to receive package 13044 * lifecycle events for instant applications. 13045 */ 13046 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 13047 int flags, String targetPkg, IIntentReceiver finishedReceiver, 13048 int[] userIds, boolean isInstantApp) 13049 throws RemoteException { 13050 for (int id : userIds) { 13051 final Intent intent = new Intent(action, 13052 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 13053 final String[] requiredPermissions = 13054 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 13055 if (extras != null) { 13056 intent.putExtras(extras); 13057 } 13058 if (targetPkg != null) { 13059 intent.setPackage(targetPkg); 13060 } 13061 // Modify the UID when posting to other users 13062 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 13063 if (uid > 0 && UserHandle.getUserId(uid) != id) { 13064 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 13065 intent.putExtra(Intent.EXTRA_UID, uid); 13066 } 13067 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 13068 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 13069 if (DEBUG_BROADCASTS) { 13070 RuntimeException here = new RuntimeException("here"); 13071 here.fillInStackTrace(); 13072 Slog.d(TAG, "Sending to user " + id + ": " 13073 + intent.toShortString(false, true, false, false) 13074 + " " + intent.getExtras(), here); 13075 } 13076 am.broadcastIntent(null, intent, null, finishedReceiver, 13077 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 13078 null, finishedReceiver != null, false, id); 13079 } 13080 } 13081 13082 /** 13083 * Check if the external storage media is available. This is true if there 13084 * is a mounted external storage medium or if the external storage is 13085 * emulated. 13086 */ 13087 private boolean isExternalMediaAvailable() { 13088 return mMediaMounted || Environment.isExternalStorageEmulated(); 13089 } 13090 13091 /** 13092 * Ensure that the install reason matches what we know about the package installer (e.g. whether 13093 * it is acting on behalf on an enterprise or the user). 13094 * 13095 * Note that the ordering of the conditionals in this method is important. The checks we perform 13096 * are as follows, in this order: 13097 * 13098 * 1) If the install is being performed by a system app, we can trust the app to have set the 13099 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 13100 * what it is. 13101 * 2) If the install is being performed by a device or profile owner app, the install reason 13102 * should be enterprise policy. However, we cannot be sure that the device or profile owner 13103 * set the install reason correctly. If the app targets an older SDK version where install 13104 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 13105 * unset or wrong. Thus, we force the install reason to be enterprise policy. 13106 * 3) In all other cases, the install is being performed by a regular app that is neither part 13107 * of the system nor a device or profile owner. We have no reason to believe that this app is 13108 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 13109 * set to enterprise policy and if so, change it to unknown instead. 13110 */ 13111 private int fixUpInstallReason(String installerPackageName, int installerUid, 13112 int installReason) { 13113 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 13114 == PERMISSION_GRANTED) { 13115 // If the install is being performed by a system app, we trust that app to have set the 13116 // install reason correctly. 13117 return installReason; 13118 } 13119 final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage( 13120 UserHandle.getUserId(installerUid)); 13121 if (ownerPackage != null && ownerPackage.equals(installerPackageName)) { 13122 // If the install is being performed by a device or profile owner, the install 13123 // reason should be enterprise policy. 13124 return PackageManager.INSTALL_REASON_POLICY; 13125 } 13126 13127 13128 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 13129 // If the install is being performed by a regular app (i.e. neither system app nor 13130 // device or profile owner), we have no reason to believe that the app is acting on 13131 // behalf of an enterprise. If the app set the install reason to enterprise policy, 13132 // change it to unknown instead. 13133 return PackageManager.INSTALL_REASON_UNKNOWN; 13134 } 13135 13136 // If the install is being performed by a regular app and the install reason was set to any 13137 // value but enterprise policy, leave the install reason unchanged. 13138 return installReason; 13139 } 13140 13141 void installStage(ActiveInstallSession activeInstallSession) { 13142 if (DEBUG_INSTANT) { 13143 if ((activeInstallSession.getSessionParams().installFlags 13144 & PackageManager.INSTALL_INSTANT_APP) != 0) { 13145 Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName()); 13146 } 13147 } 13148 final Message msg = mHandler.obtainMessage(INIT_COPY); 13149 final InstallParams params = new InstallParams(activeInstallSession); 13150 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 13151 msg.obj = params; 13152 13153 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 13154 System.identityHashCode(msg.obj)); 13155 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13156 System.identityHashCode(msg.obj)); 13157 13158 mHandler.sendMessage(msg); 13159 } 13160 13161 void installStage(List<ActiveInstallSession> children) 13162 throws PackageManagerException { 13163 final Message msg = mHandler.obtainMessage(INIT_COPY); 13164 final MultiPackageInstallParams params = 13165 new MultiPackageInstallParams(UserHandle.ALL, children); 13166 params.setTraceMethod("installStageMultiPackage") 13167 .setTraceCookie(System.identityHashCode(params)); 13168 msg.obj = params; 13169 13170 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStageMultiPackage", 13171 System.identityHashCode(msg.obj)); 13172 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 13173 System.identityHashCode(msg.obj)); 13174 mHandler.sendMessage(msg); 13175 } 13176 13177 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 13178 int userId) { 13179 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 13180 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 13181 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 13182 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 13183 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 13184 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 13185 13186 // Send a session commit broadcast 13187 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 13188 info.installReason = pkgSetting.getInstallReason(userId); 13189 info.appPackageName = packageName; 13190 sendSessionCommitBroadcast(info, userId); 13191 } 13192 13193 @Override 13194 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 13195 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 13196 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 13197 return; 13198 } 13199 Bundle extras = new Bundle(1); 13200 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 13201 final int uid = UserHandle.getUid( 13202 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 13203 extras.putInt(Intent.EXTRA_UID, uid); 13204 13205 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 13206 packageName, extras, 0, null, null, userIds, instantUserIds); 13207 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 13208 mHandler.post(() -> { 13209 for (int userId : userIds) { 13210 sendBootCompletedBroadcastToSystemApp( 13211 packageName, includeStopped, userId); 13212 } 13213 } 13214 ); 13215 } 13216 } 13217 13218 /** 13219 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 13220 * automatically without needing an explicit launch. 13221 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 13222 */ 13223 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 13224 int userId) { 13225 // If user is not running, the app didn't miss any broadcast 13226 if (!mUserManagerInternal.isUserRunning(userId)) { 13227 return; 13228 } 13229 final IActivityManager am = ActivityManager.getService(); 13230 try { 13231 // Deliver LOCKED_BOOT_COMPLETED first 13232 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 13233 .setPackage(packageName); 13234 if (includeStopped) { 13235 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13236 } 13237 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 13238 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 13239 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13240 13241 // Deliver BOOT_COMPLETED only if user is unlocked 13242 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 13243 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 13244 if (includeStopped) { 13245 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 13246 } 13247 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 13248 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 13249 } 13250 } catch (RemoteException e) { 13251 throw e.rethrowFromSystemServer(); 13252 } 13253 } 13254 13255 @Override 13256 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 13257 int userId) { 13258 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13259 PackageSetting pkgSetting; 13260 final int callingUid = Binder.getCallingUid(); 13261 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13262 true /* requireFullPermission */, true /* checkShell */, 13263 "setApplicationHiddenSetting for user " + userId); 13264 13265 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 13266 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 13267 return false; 13268 } 13269 13270 long callingId = Binder.clearCallingIdentity(); 13271 try { 13272 boolean sendAdded = false; 13273 boolean sendRemoved = false; 13274 // writer 13275 synchronized (mPackages) { 13276 pkgSetting = mSettings.mPackages.get(packageName); 13277 if (pkgSetting == null) { 13278 return false; 13279 } 13280 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13281 return false; 13282 } 13283 // Do not allow "android" is being disabled 13284 if ("android".equals(packageName)) { 13285 Slog.w(TAG, "Cannot hide package: android"); 13286 return false; 13287 } 13288 // Cannot hide static shared libs as they are considered 13289 // a part of the using app (emulating static linking). Also 13290 // static libs are installed always on internal storage. 13291 PackageParser.Package pkg = mPackages.get(packageName); 13292 if (pkg != null && pkg.staticSharedLibName != null) { 13293 Slog.w(TAG, "Cannot hide package: " + packageName 13294 + " providing static shared library: " 13295 + pkg.staticSharedLibName); 13296 return false; 13297 } 13298 // Only allow protected packages to hide themselves. 13299 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 13300 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13301 Slog.w(TAG, "Not hiding protected package: " + packageName); 13302 return false; 13303 } 13304 13305 if (pkgSetting.getHidden(userId) != hidden) { 13306 pkgSetting.setHidden(hidden, userId); 13307 mSettings.writePackageRestrictionsLPr(userId); 13308 if (hidden) { 13309 sendRemoved = true; 13310 } else { 13311 sendAdded = true; 13312 } 13313 } 13314 } 13315 if (sendAdded) { 13316 sendPackageAddedForUser(packageName, pkgSetting, userId); 13317 return true; 13318 } 13319 if (sendRemoved) { 13320 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 13321 "hiding pkg"); 13322 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 13323 return true; 13324 } 13325 } finally { 13326 Binder.restoreCallingIdentity(callingId); 13327 } 13328 return false; 13329 } 13330 13331 @Override 13332 public void setSystemAppHiddenUntilInstalled(String packageName, boolean hidden) { 13333 enforceSystemOrPhoneCaller("setSystemAppHiddenUntilInstalled"); 13334 synchronized (mPackages) { 13335 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13336 if (pkgSetting == null || !pkgSetting.isSystem()) { 13337 return; 13338 } 13339 PackageParser.Package pkg = pkgSetting.pkg; 13340 if (pkg != null && pkg.applicationInfo != null) { 13341 pkg.applicationInfo.hiddenUntilInstalled = hidden; 13342 } 13343 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(packageName); 13344 if (disabledPs == null) { 13345 return; 13346 } 13347 pkg = disabledPs.pkg; 13348 if (pkg != null && pkg.applicationInfo != null) { 13349 pkg.applicationInfo.hiddenUntilInstalled = hidden; 13350 } 13351 } 13352 } 13353 13354 @Override 13355 public boolean setSystemAppInstallState(String packageName, boolean installed, int userId) { 13356 enforceSystemOrPhoneCaller("setSystemAppInstallState"); 13357 synchronized (mPackages) { 13358 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 13359 // The target app should always be in system 13360 if (pkgSetting == null || !pkgSetting.isSystem()) { 13361 return false; 13362 } 13363 // Check if the install state is the same 13364 if (pkgSetting.getInstalled(userId) == installed) { 13365 return false; 13366 } 13367 } 13368 13369 final long callingId = Binder.clearCallingIdentity(); 13370 try { 13371 if (installed) { 13372 // install the app from uninstalled state 13373 installExistingPackageAsUser( 13374 packageName, 13375 userId, 13376 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 13377 PackageManager.INSTALL_REASON_DEVICE_SETUP, 13378 null); 13379 return true; 13380 } 13381 13382 // uninstall the app from installed state 13383 deletePackageVersioned( 13384 new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST), 13385 new LegacyPackageDeleteObserver(null).getBinder(), 13386 userId, 13387 PackageManager.DELETE_SYSTEM_APP); 13388 return true; 13389 } finally { 13390 Binder.restoreCallingIdentity(callingId); 13391 } 13392 } 13393 13394 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 13395 int userId) { 13396 final PackageRemovedInfo info = new PackageRemovedInfo(this); 13397 info.removedPackage = packageName; 13398 info.installerPackageName = pkgSetting.installerPackageName; 13399 info.removedUsers = new int[] {userId}; 13400 info.broadcastUsers = new int[] {userId}; 13401 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 13402 info.sendPackageRemovedBroadcasts(true /*killApp*/); 13403 } 13404 13405 private void sendDistractingPackagesChanged(String[] pkgList, int[] uidList, int userId, 13406 int distractionFlags) { 13407 final Bundle extras = new Bundle(3); 13408 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13409 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList); 13410 extras.putInt(Intent.EXTRA_DISTRACTION_RESTRICTIONS, distractionFlags); 13411 sendPackageBroadcast(Intent.ACTION_DISTRACTING_PACKAGES_CHANGED, null, extras, 13412 Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, new int[]{userId}, null); 13413 } 13414 13415 private void sendPackagesSuspendedForUser(String[] pkgList, int[] uidList, int userId, 13416 boolean suspended, PersistableBundle launcherExtras) { 13417 final Bundle extras = new Bundle(3); 13418 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 13419 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList); 13420 if (launcherExtras != null) { 13421 extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS, 13422 new Bundle(launcherExtras.deepCopy())); 13423 } 13424 sendPackageBroadcast( 13425 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 13426 : Intent.ACTION_PACKAGES_UNSUSPENDED, 13427 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 13428 new int[] {userId}, null); 13429 } 13430 13431 /** 13432 * Returns true if application is not found or there was an error. Otherwise it returns 13433 * the hidden state of the package for the given user. 13434 */ 13435 @Override 13436 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 13437 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 13438 final int callingUid = Binder.getCallingUid(); 13439 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13440 true /* requireFullPermission */, false /* checkShell */, 13441 "getApplicationHidden for user " + userId); 13442 PackageSetting ps; 13443 long callingId = Binder.clearCallingIdentity(); 13444 try { 13445 // writer 13446 synchronized (mPackages) { 13447 ps = mSettings.mPackages.get(packageName); 13448 if (ps == null) { 13449 return true; 13450 } 13451 if (filterAppAccessLPr(ps, callingUid, userId)) { 13452 return true; 13453 } 13454 return ps.getHidden(userId); 13455 } 13456 } finally { 13457 Binder.restoreCallingIdentity(callingId); 13458 } 13459 } 13460 13461 /** 13462 * @hide 13463 */ 13464 @Override 13465 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13466 int installReason, List<String> whiteListedPermissions) { 13467 return installExistingPackageAsUser(packageName, userId, installFlags, installReason, 13468 whiteListedPermissions, null); 13469 } 13470 13471 int installExistingPackageAsUser(@Nullable String packageName, @UserIdInt int userId, 13472 @PackageManager.InstallFlags int installFlags, 13473 @PackageManager.InstallReason int installReason, 13474 @Nullable List<String> whiteListedPermissions, @Nullable IntentSender intentSender) { 13475 if (DEBUG_INSTALL) { 13476 Log.v(TAG, "installExistingPackageAsUser package=" + packageName + " userId=" + userId 13477 + " installFlags=" + installFlags + " installReason=" + installReason 13478 + " whiteListedPermissions=" + whiteListedPermissions); 13479 } 13480 13481 final int callingUid = Binder.getCallingUid(); 13482 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES) 13483 != PackageManager.PERMISSION_GRANTED 13484 && mContext.checkCallingOrSelfPermission( 13485 android.Manifest.permission.INSTALL_EXISTING_PACKAGES) 13486 != PackageManager.PERMISSION_GRANTED) { 13487 throw new SecurityException("Neither user " + callingUid + " nor current process has " 13488 + android.Manifest.permission.INSTALL_PACKAGES + "."); 13489 } 13490 PackageSetting pkgSetting; 13491 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13492 true /* requireFullPermission */, true /* checkShell */, 13493 "installExistingPackage for user " + userId); 13494 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13495 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13496 } 13497 13498 long callingId = Binder.clearCallingIdentity(); 13499 try { 13500 boolean installed = false; 13501 final boolean instantApp = 13502 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13503 final boolean fullApp = 13504 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13505 13506 // writer 13507 synchronized (mPackages) { 13508 pkgSetting = mSettings.mPackages.get(packageName); 13509 if (pkgSetting == null) { 13510 return PackageManager.INSTALL_FAILED_INVALID_URI; 13511 } 13512 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13513 // only allow the existing package to be used if it's installed as a full 13514 // application for at least one user 13515 boolean installAllowed = false; 13516 for (int checkUserId : sUserManager.getUserIds()) { 13517 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13518 if (installAllowed) { 13519 break; 13520 } 13521 } 13522 if (!installAllowed) { 13523 return PackageManager.INSTALL_FAILED_INVALID_URI; 13524 } 13525 } 13526 if (!pkgSetting.getInstalled(userId)) { 13527 pkgSetting.setInstalled(true, userId); 13528 pkgSetting.setHidden(false, userId); 13529 pkgSetting.setInstallReason(installReason, userId); 13530 mSettings.writePackageRestrictionsLPr(userId); 13531 mSettings.writeKernelMappingLPr(pkgSetting); 13532 installed = true; 13533 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13534 // upgrade app from instant to full; we don't allow app downgrade 13535 installed = true; 13536 } 13537 setInstantAppForUser(pkgSetting, userId, instantApp, fullApp); 13538 } 13539 13540 if (installed) { 13541 if ((installFlags & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) 13542 != 0 && pkgSetting.pkg != null) { 13543 whiteListedPermissions = pkgSetting.pkg.requestedPermissions; 13544 } 13545 setWhitelistedRestrictedPermissions(packageName, whiteListedPermissions, 13546 PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER, userId); 13547 13548 if (pkgSetting.pkg != null) { 13549 synchronized (mInstallLock) { 13550 // We don't need to freeze for a brand new install 13551 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13552 } 13553 } 13554 sendPackageAddedForUser(packageName, pkgSetting, userId); 13555 synchronized (mPackages) { 13556 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13557 } 13558 // start async restore with no post-install since we finish install here 13559 PackageInstalledInfo res = 13560 createPackageInstalledInfo(PackageManager.INSTALL_SUCCEEDED); 13561 res.pkg = pkgSetting.pkg; 13562 res.newUsers = new int[]{ userId }; 13563 PostInstallData postInstallData = intentSender == null ? null : 13564 new PostInstallData(null, res, () -> onRestoreComplete(res.returnCode, 13565 mContext, intentSender)); 13566 restoreAndPostInstall(userId, res, postInstallData); 13567 } 13568 } finally { 13569 Binder.restoreCallingIdentity(callingId); 13570 } 13571 13572 return PackageManager.INSTALL_SUCCEEDED; 13573 } 13574 13575 static void onRestoreComplete(int returnCode, Context context, IntentSender target) { 13576 Intent fillIn = new Intent(); 13577 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 13578 PackageManager.installStatusToPublicStatus(returnCode)); 13579 try { 13580 target.sendIntent(context, 0, fillIn, null, null); 13581 } catch (SendIntentException ignored) { 13582 } 13583 } 13584 13585 static void setInstantAppForUser(PackageSetting pkgSetting, int userId, 13586 boolean instantApp, boolean fullApp) { 13587 // no state specified; do nothing 13588 if (!instantApp && !fullApp) { 13589 return; 13590 } 13591 if (userId != UserHandle.USER_ALL) { 13592 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13593 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13594 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13595 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13596 } 13597 } else { 13598 for (int currentUserId : sUserManager.getUserIds()) { 13599 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13600 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13601 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13602 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13603 } 13604 } 13605 } 13606 } 13607 13608 boolean isUserRestricted(int userId, String restrictionKey) { 13609 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13610 if (restrictions.getBoolean(restrictionKey, false)) { 13611 Log.w(TAG, "User is restricted: " + restrictionKey); 13612 return true; 13613 } 13614 return false; 13615 } 13616 13617 @Override 13618 public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames, 13619 int restrictionFlags, int userId) { 13620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, 13621 "setDistractingPackageRestrictionsAsUser"); 13622 13623 final int callingUid = Binder.getCallingUid(); 13624 if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID 13625 && UserHandle.getUserId(callingUid) != userId) { 13626 throw new SecurityException("Calling uid " + callingUid + " cannot call for user " 13627 + userId); 13628 } 13629 Preconditions.checkNotNull(packageNames, "packageNames cannot be null"); 13630 13631 final List<String> changedPackagesList = new ArrayList<>(packageNames.length); 13632 final IntArray changedUids = new IntArray(packageNames.length); 13633 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13634 final boolean[] canRestrict = (restrictionFlags != 0) ? canSuspendPackageForUserInternal( 13635 packageNames, userId) : null; 13636 13637 for (int i = 0; i < packageNames.length; i++) { 13638 final String packageName = packageNames[i]; 13639 final PackageSetting pkgSetting; 13640 synchronized (mPackages) { 13641 pkgSetting = mSettings.mPackages.get(packageName); 13642 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13643 Slog.w(TAG, "Could not find package setting for package: " + packageName 13644 + ". Skipping..."); 13645 unactionedPackages.add(packageName); 13646 continue; 13647 } 13648 } 13649 if (canRestrict != null && !canRestrict[i]) { 13650 unactionedPackages.add(packageName); 13651 continue; 13652 } 13653 synchronized (mPackages) { 13654 final int oldDistractionFlags = pkgSetting.getDistractionFlags(userId); 13655 if (restrictionFlags != oldDistractionFlags) { 13656 pkgSetting.setDistractionFlags(restrictionFlags, userId); 13657 changedPackagesList.add(packageName); 13658 changedUids.add(UserHandle.getUid(userId, pkgSetting.appId)); 13659 } 13660 } 13661 } 13662 13663 if (!changedPackagesList.isEmpty()) { 13664 final String[] changedPackages = changedPackagesList.toArray( 13665 new String[changedPackagesList.size()]); 13666 sendDistractingPackagesChanged(changedPackages, changedUids.toArray(), userId, 13667 restrictionFlags); 13668 synchronized (mPackages) { 13669 scheduleWritePackageRestrictionsLocked(userId); 13670 } 13671 } 13672 return unactionedPackages.toArray(new String[0]); 13673 } 13674 13675 private void enforceCanSetPackagesSuspendedAsUser(String callingPackage, int callingUid, 13676 int userId, String callingMethod) { 13677 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID) { 13678 return; 13679 } 13680 13681 final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId); 13682 if (ownerPackage != null) { 13683 final int ownerUid = getPackageUid(ownerPackage, 0, userId); 13684 if (ownerUid == callingUid) { 13685 return; 13686 } 13687 throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User " 13688 + userId + " has an active DO or PO"); 13689 } 13690 13691 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, 13692 callingMethod); 13693 13694 final int packageUid = getPackageUid(callingPackage, 0, userId); 13695 final boolean allowedPackageUid = packageUid == callingUid; 13696 final boolean allowedShell = callingUid == SHELL_UID 13697 && UserHandle.isSameApp(packageUid, callingUid); 13698 13699 if (!allowedShell && !allowedPackageUid) { 13700 throw new SecurityException("Calling package " + callingPackage + " in user " 13701 + userId + " does not belong to calling uid " + callingUid); 13702 } 13703 } 13704 13705 @Override 13706 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13707 PersistableBundle appExtras, PersistableBundle launcherExtras, 13708 SuspendDialogInfo dialogInfo, String callingPackage, int userId) { 13709 final int callingUid = Binder.getCallingUid(); 13710 enforceCanSetPackagesSuspendedAsUser(callingPackage, callingUid, userId, 13711 "setPackagesSuspendedAsUser"); 13712 13713 if (ArrayUtils.isEmpty(packageNames)) { 13714 return packageNames; 13715 } 13716 13717 final List<String> changedPackagesList = new ArrayList<>(packageNames.length); 13718 final IntArray changedUids = new IntArray(packageNames.length); 13719 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13720 final boolean[] canSuspend = suspended ? canSuspendPackageForUserInternal(packageNames, 13721 userId) : null; 13722 13723 for (int i = 0; i < packageNames.length; i++) { 13724 final String packageName = packageNames[i]; 13725 if (callingPackage.equals(packageName)) { 13726 Slog.w(TAG, "Calling package: " + callingPackage + " trying to " 13727 + (suspended ? "" : "un") + "suspend itself. Ignoring"); 13728 unactionedPackages.add(packageName); 13729 continue; 13730 } 13731 final PackageSetting pkgSetting; 13732 synchronized (mPackages) { 13733 pkgSetting = mSettings.mPackages.get(packageName); 13734 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13735 Slog.w(TAG, "Could not find package setting for package: " + packageName 13736 + ". Skipping suspending/un-suspending."); 13737 unactionedPackages.add(packageName); 13738 continue; 13739 } 13740 } 13741 if (canSuspend != null && !canSuspend[i]) { 13742 unactionedPackages.add(packageName); 13743 continue; 13744 } 13745 synchronized (mPackages) { 13746 pkgSetting.setSuspended(suspended, callingPackage, dialogInfo, appExtras, 13747 launcherExtras, userId); 13748 } 13749 changedPackagesList.add(packageName); 13750 changedUids.add(UserHandle.getUid(userId, pkgSetting.appId)); 13751 } 13752 13753 if (!changedPackagesList.isEmpty()) { 13754 final String[] changedPackages = changedPackagesList.toArray( 13755 new String[changedPackagesList.size()]); 13756 sendPackagesSuspendedForUser( 13757 changedPackages, changedUids.toArray(), userId, suspended, launcherExtras); 13758 sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId); 13759 synchronized (mPackages) { 13760 scheduleWritePackageRestrictionsLocked(userId); 13761 } 13762 } 13763 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13764 } 13765 13766 @Override 13767 public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) { 13768 final int callingUid = Binder.getCallingUid(); 13769 if (getPackageUid(packageName, 0, userId) != callingUid) { 13770 throw new SecurityException("Calling package " + packageName 13771 + " does not belong to calling uid " + callingUid); 13772 } 13773 synchronized (mPackages) { 13774 final PackageSetting ps = mSettings.mPackages.get(packageName); 13775 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13776 throw new IllegalArgumentException("Unknown target package: " + packageName); 13777 } 13778 final PackageUserState packageUserState = ps.readUserState(userId); 13779 if (packageUserState.suspended) { 13780 return packageUserState.suspendedAppExtras; 13781 } 13782 return null; 13783 } 13784 } 13785 13786 private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended, 13787 PersistableBundle appExtras, int userId) { 13788 final String action; 13789 final Bundle intentExtras = new Bundle(); 13790 if (suspended) { 13791 action = Intent.ACTION_MY_PACKAGE_SUSPENDED; 13792 if (appExtras != null) { 13793 final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy()); 13794 intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras); 13795 } 13796 } else { 13797 action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED; 13798 } 13799 mHandler.post(() -> { 13800 try { 13801 final IActivityManager am = ActivityManager.getService(); 13802 if (am == null) { 13803 Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ " 13804 + (suspended ? "" : "UN") + "SUSPENDED broadcasts"); 13805 return; 13806 } 13807 final int[] targetUserIds = new int[] {userId}; 13808 for (String packageName : affectedPackages) { 13809 doSendBroadcast(am, action, null, intentExtras, 13810 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null, 13811 targetUserIds, false); 13812 } 13813 } catch (RemoteException ex) { 13814 // Shouldn't happen as AMS is in the same process. 13815 } 13816 }); 13817 } 13818 13819 @Override 13820 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13821 final int callingUid = Binder.getCallingUid(); 13822 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13823 true /* requireFullPermission */, false /* checkShell */, 13824 "isPackageSuspendedForUser for user " + userId); 13825 synchronized (mPackages) { 13826 final PackageSetting ps = mSettings.mPackages.get(packageName); 13827 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13828 throw new IllegalArgumentException("Unknown target package: " + packageName); 13829 } 13830 return ps.getSuspended(userId); 13831 } 13832 } 13833 13834 /** 13835 * Immediately unsuspends any packages suspended by the given package. To be called 13836 * when such a package's data is cleared or it is removed from the device. 13837 * 13838 * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk 13839 * synchronously 13840 * 13841 * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission 13842 * @param affectedUser The user for which the changes are taking place. 13843 */ 13844 void unsuspendForSuspendingPackage(final String packageName, int affectedUser) { 13845 final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds() 13846 : new int[] {affectedUser}; 13847 for (int userId : userIds) { 13848 unsuspendForSuspendingPackages(packageName::equals, userId); 13849 } 13850 } 13851 13852 /** 13853 * Immediately unsuspends any packages in the given users not suspended by the platform or root. 13854 * To be called when a profile owner or a device owner is added. 13855 * 13856 * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk 13857 * synchronously 13858 * 13859 * @param userIds The users for which to unsuspend packages 13860 */ 13861 void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) { 13862 final int sz = userIds.size(); 13863 for (int i = 0; i < sz; i++) { 13864 unsuspendForSuspendingPackages( 13865 (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage), 13866 userIds.valueAt(i)); 13867 } 13868 } 13869 13870 private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) { 13871 final List<String> affectedPackages = new ArrayList<>(); 13872 final IntArray affectedUids = new IntArray(); 13873 synchronized (mPackages) { 13874 for (PackageSetting ps : mSettings.mPackages.values()) { 13875 final PackageUserState pus = ps.readUserState(userId); 13876 if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) { 13877 ps.setSuspended(false, null, null, null, null, userId); 13878 affectedPackages.add(ps.name); 13879 affectedUids.add(UserHandle.getUid(userId, ps.getAppId())); 13880 } 13881 } 13882 } 13883 if (!affectedPackages.isEmpty()) { 13884 final String[] packageArray = affectedPackages.toArray( 13885 new String[affectedPackages.size()]); 13886 sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId); 13887 sendPackagesSuspendedForUser( 13888 packageArray, affectedUids.toArray(), userId, false, null); 13889 // Write package restrictions immediately to avoid an inconsistent state. 13890 mSettings.writePackageRestrictionsLPr(userId); 13891 } 13892 } 13893 13894 @Override 13895 public String[] getUnsuspendablePackagesForUser(String[] packageNames, int userId) { 13896 Preconditions.checkNotNull("packageNames cannot be null", packageNames); 13897 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 13898 "getUnsuspendablePackagesForUser"); 13899 final int callingUid = Binder.getCallingUid(); 13900 if (UserHandle.getUserId(callingUid) != userId) { 13901 throw new SecurityException("Calling uid " + callingUid 13902 + " cannot query getUnsuspendablePackagesForUser for user " + userId); 13903 } 13904 final ArraySet<String> unactionablePackages = new ArraySet<>(); 13905 final boolean[] canSuspend = canSuspendPackageForUserInternal(packageNames, userId); 13906 for (int i = 0; i < packageNames.length; i++) { 13907 if (!canSuspend[i]) { 13908 unactionablePackages.add(packageNames[i]); 13909 } 13910 } 13911 return unactionablePackages.toArray(new String[unactionablePackages.size()]); 13912 } 13913 13914 /** 13915 * Returns an array of booleans, such that the ith boolean denotes whether the ith package can 13916 * be suspended or not. 13917 * 13918 * @param packageNames The package names to check suspendability for. 13919 * @param userId The user to check in 13920 * @return An array containing results of the checks 13921 */ 13922 @NonNull 13923 private boolean[] canSuspendPackageForUserInternal(@NonNull String[] packageNames, int userId) { 13924 final boolean[] canSuspend = new boolean[packageNames.length]; 13925 final long callingId = Binder.clearCallingIdentity(); 13926 try { 13927 final String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13928 final String dialerPackageName = getDefaultDialerPackageName(userId); 13929 for (int i = 0; i < packageNames.length; i++) { 13930 canSuspend[i] = false; 13931 final String packageName = packageNames[i]; 13932 13933 if (isPackageDeviceAdmin(packageName, userId)) { 13934 Slog.w(TAG, "Cannot suspend package \"" + packageName 13935 + "\": has an active device admin"); 13936 continue; 13937 } 13938 if (packageName.equals(activeLauncherPackageName)) { 13939 Slog.w(TAG, "Cannot suspend package \"" + packageName 13940 + "\": contains the active launcher"); 13941 continue; 13942 } 13943 if (packageName.equals(mRequiredInstallerPackage)) { 13944 Slog.w(TAG, "Cannot suspend package \"" + packageName 13945 + "\": required for package installation"); 13946 continue; 13947 } 13948 if (packageName.equals(mRequiredUninstallerPackage)) { 13949 Slog.w(TAG, "Cannot suspend package \"" + packageName 13950 + "\": required for package uninstallation"); 13951 continue; 13952 } 13953 if (packageName.equals(mRequiredVerifierPackage)) { 13954 Slog.w(TAG, "Cannot suspend package \"" + packageName 13955 + "\": required for package verification"); 13956 continue; 13957 } 13958 if (packageName.equals(dialerPackageName)) { 13959 Slog.w(TAG, "Cannot suspend package \"" + packageName 13960 + "\": is the default dialer"); 13961 continue; 13962 } 13963 if (packageName.equals(mRequiredPermissionControllerPackage)) { 13964 Slog.w(TAG, "Cannot suspend package \"" + packageName 13965 + "\": required for permissions management"); 13966 continue; 13967 } 13968 synchronized (mPackages) { 13969 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13970 Slog.w(TAG, "Cannot suspend package \"" + packageName 13971 + "\": protected package"); 13972 continue; 13973 } 13974 13975 // Cannot suspend static shared libs as they are considered 13976 // a part of the using app (emulating static linking). Also 13977 // static libs are installed always on internal storage. 13978 PackageParser.Package pkg = mPackages.get(packageName); 13979 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13980 Slog.w(TAG, "Cannot suspend package: " + packageName 13981 + " providing static shared library: " 13982 + pkg.staticSharedLibName); 13983 continue; 13984 } 13985 } 13986 if (PLATFORM_PACKAGE_NAME.equals(packageName)) { 13987 Slog.w(TAG, "Cannot suspend the platform package: " + packageName); 13988 continue; 13989 } 13990 canSuspend[i] = true; 13991 } 13992 } finally { 13993 Binder.restoreCallingIdentity(callingId); 13994 } 13995 return canSuspend; 13996 } 13997 13998 private String getActiveLauncherPackageName(int userId) { 13999 Intent intent = new Intent(Intent.ACTION_MAIN); 14000 intent.addCategory(Intent.CATEGORY_HOME); 14001 ResolveInfo resolveInfo = resolveIntent( 14002 intent, 14003 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 14004 PackageManager.MATCH_DEFAULT_ONLY, 14005 userId); 14006 14007 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 14008 } 14009 14010 @Nullable 14011 private String getDefaultDialerPackageName(@UserIdInt int userId) { 14012 PackageManagerInternal.DefaultDialerProvider provider; 14013 synchronized (mPackages) { 14014 provider = mDefaultDialerProvider; 14015 } 14016 if (provider == null) { 14017 Slog.e(TAG, "mDefaultDialerProvider is null"); 14018 return null; 14019 } 14020 return provider.getDefaultDialer(userId); 14021 } 14022 14023 @Override 14024 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 14025 mContext.enforceCallingOrSelfPermission( 14026 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14027 "Only package verification agents can verify applications"); 14028 14029 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14030 final PackageVerificationResponse response = new PackageVerificationResponse( 14031 verificationCode, Binder.getCallingUid()); 14032 msg.arg1 = id; 14033 msg.obj = response; 14034 mHandler.sendMessage(msg); 14035 } 14036 14037 @Override 14038 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 14039 long millisecondsToDelay) { 14040 mContext.enforceCallingOrSelfPermission( 14041 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14042 "Only package verification agents can extend verification timeouts"); 14043 14044 final PackageVerificationState state = mPendingVerification.get(id); 14045 final PackageVerificationResponse response = new PackageVerificationResponse( 14046 verificationCodeAtTimeout, Binder.getCallingUid()); 14047 14048 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 14049 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 14050 } 14051 if (millisecondsToDelay < 0) { 14052 millisecondsToDelay = 0; 14053 } 14054 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 14055 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 14056 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 14057 } 14058 14059 if ((state != null) && !state.timeoutExtended()) { 14060 state.extendTimeout(); 14061 14062 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 14063 msg.arg1 = id; 14064 msg.obj = response; 14065 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 14066 } 14067 } 14068 14069 private void broadcastPackageVerified(int verificationId, Uri packageUri, 14070 int verificationCode, UserHandle user) { 14071 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 14072 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 14073 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14074 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14075 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 14076 14077 mContext.sendBroadcastAsUser(intent, user, 14078 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 14079 } 14080 14081 private ComponentName matchComponentForVerifier(String packageName, 14082 List<ResolveInfo> receivers) { 14083 ActivityInfo targetReceiver = null; 14084 14085 final int NR = receivers.size(); 14086 for (int i = 0; i < NR; i++) { 14087 final ResolveInfo info = receivers.get(i); 14088 if (info.activityInfo == null) { 14089 continue; 14090 } 14091 14092 if (packageName.equals(info.activityInfo.packageName)) { 14093 targetReceiver = info.activityInfo; 14094 break; 14095 } 14096 } 14097 14098 if (targetReceiver == null) { 14099 return null; 14100 } 14101 14102 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 14103 } 14104 14105 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 14106 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 14107 if (pkgInfo.verifiers.length == 0) { 14108 return null; 14109 } 14110 14111 final int N = pkgInfo.verifiers.length; 14112 final List<ComponentName> sufficientVerifiers = new ArrayList<>(N + 1); 14113 for (int i = 0; i < N; i++) { 14114 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 14115 14116 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 14117 receivers); 14118 if (comp == null) { 14119 continue; 14120 } 14121 14122 final int verifierUid = getUidForVerifier(verifierInfo); 14123 if (verifierUid == -1) { 14124 continue; 14125 } 14126 14127 if (DEBUG_VERIFY) { 14128 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 14129 + " with the correct signature"); 14130 } 14131 sufficientVerifiers.add(comp); 14132 verificationState.addSufficientVerifier(verifierUid); 14133 } 14134 14135 return sufficientVerifiers; 14136 } 14137 14138 private int getUidForVerifier(VerifierInfo verifierInfo) { 14139 synchronized (mPackages) { 14140 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 14141 if (pkg == null) { 14142 return -1; 14143 } else if (pkg.mSigningDetails.signatures.length != 1) { 14144 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14145 + " has more than one signature; ignoring"); 14146 return -1; 14147 } 14148 14149 /* 14150 * If the public key of the package's signature does not match 14151 * our expected public key, then this is a different package and 14152 * we should skip. 14153 */ 14154 14155 final byte[] expectedPublicKey; 14156 try { 14157 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 14158 final PublicKey publicKey = verifierSig.getPublicKey(); 14159 expectedPublicKey = publicKey.getEncoded(); 14160 } catch (CertificateException e) { 14161 return -1; 14162 } 14163 14164 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 14165 14166 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 14167 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 14168 + " does not have the expected public key; ignoring"); 14169 return -1; 14170 } 14171 14172 return pkg.applicationInfo.uid; 14173 } 14174 } 14175 14176 private void setEnableRollbackCode(int token, int enableRollbackCode) { 14177 final Message msg = mHandler.obtainMessage(ENABLE_ROLLBACK_STATUS); 14178 msg.arg1 = token; 14179 msg.arg2 = enableRollbackCode; 14180 mHandler.sendMessage(msg); 14181 } 14182 14183 @Override 14184 public void finishPackageInstall(int token, boolean didLaunch) { 14185 enforceSystemOrRoot("Only the system is allowed to finish installs"); 14186 14187 if (DEBUG_INSTALL) { 14188 Slog.v(TAG, "BM finishing package install for " + token); 14189 } 14190 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14191 14192 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 14193 mHandler.sendMessage(msg); 14194 } 14195 14196 /** 14197 * Get the verification agent timeout. Used for both the APK verifier and the 14198 * intent filter verifier. 14199 * 14200 * @return verification timeout in milliseconds 14201 */ 14202 private long getVerificationTimeout() { 14203 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 14204 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 14205 DEFAULT_VERIFICATION_TIMEOUT); 14206 } 14207 14208 /** 14209 * Get the default verification agent response code. 14210 * 14211 * @return default verification response code 14212 */ 14213 private int getDefaultVerificationResponse(UserHandle user) { 14214 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 14215 return PackageManager.VERIFICATION_REJECT; 14216 } 14217 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14218 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 14219 DEFAULT_VERIFICATION_RESPONSE); 14220 } 14221 14222 /** 14223 * Check whether or not package verification has been enabled. 14224 * 14225 * @return true if verification should be performed 14226 */ 14227 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 14228 if (!DEFAULT_VERIFY_ENABLE) { 14229 return false; 14230 } 14231 14232 if ((installFlags & PackageManager.INSTALL_DISABLE_VERIFICATION) != 0) { 14233 return false; 14234 } 14235 14236 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 14237 14238 // Check if installing from ADB 14239 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 14240 // Do not run verification in a test harness environment 14241 if (ActivityManager.isRunningInTestHarness()) { 14242 return false; 14243 } 14244 if (ensureVerifyAppsEnabled) { 14245 return true; 14246 } 14247 // Check if the developer does not want package verification for ADB installs 14248 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14249 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 14250 return false; 14251 } 14252 } else { 14253 // only when not installed from ADB, skip verification for instant apps when 14254 // the installer and verifier are the same. 14255 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 14256 if (mInstantAppInstallerActivity != null 14257 && mInstantAppInstallerActivity.packageName.equals( 14258 mRequiredVerifierPackage)) { 14259 try { 14260 mContext.getSystemService(AppOpsManager.class) 14261 .checkPackage(installerUid, mRequiredVerifierPackage); 14262 if (DEBUG_VERIFY) { 14263 Slog.i(TAG, "disable verification for instant app"); 14264 } 14265 return false; 14266 } catch (SecurityException ignore) { } 14267 } 14268 } 14269 } 14270 14271 if (ensureVerifyAppsEnabled) { 14272 return true; 14273 } 14274 14275 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 14276 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 14277 } 14278 14279 @Override 14280 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 14281 throws RemoteException { 14282 mContext.enforceCallingOrSelfPermission( 14283 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 14284 "Only intentfilter verification agents can verify applications"); 14285 14286 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 14287 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 14288 Binder.getCallingUid(), verificationCode, failedDomains); 14289 msg.arg1 = id; 14290 msg.obj = response; 14291 mHandler.sendMessage(msg); 14292 } 14293 14294 @Override 14295 public int getIntentVerificationStatus(String packageName, int userId) { 14296 final int callingUid = Binder.getCallingUid(); 14297 if (UserHandle.getUserId(callingUid) != userId) { 14298 mContext.enforceCallingOrSelfPermission( 14299 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14300 "getIntentVerificationStatus" + userId); 14301 } 14302 if (getInstantAppPackageName(callingUid) != null) { 14303 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14304 } 14305 synchronized (mPackages) { 14306 final PackageSetting ps = mSettings.mPackages.get(packageName); 14307 if (ps == null 14308 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14309 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 14310 } 14311 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 14312 } 14313 } 14314 14315 @Override 14316 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 14317 mContext.enforceCallingOrSelfPermission( 14318 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14319 14320 boolean result = false; 14321 synchronized (mPackages) { 14322 final PackageSetting ps = mSettings.mPackages.get(packageName); 14323 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14324 return false; 14325 } 14326 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 14327 } 14328 if (result) { 14329 scheduleWritePackageRestrictionsLocked(userId); 14330 } 14331 return result; 14332 } 14333 14334 @Override 14335 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 14336 String packageName) { 14337 final int callingUid = Binder.getCallingUid(); 14338 if (getInstantAppPackageName(callingUid) != null) { 14339 return ParceledListSlice.emptyList(); 14340 } 14341 synchronized (mPackages) { 14342 final PackageSetting ps = mSettings.mPackages.get(packageName); 14343 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 14344 return ParceledListSlice.emptyList(); 14345 } 14346 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 14347 } 14348 } 14349 14350 @Override 14351 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 14352 if (TextUtils.isEmpty(packageName)) { 14353 return ParceledListSlice.emptyList(); 14354 } 14355 final int callingUid = Binder.getCallingUid(); 14356 final int callingUserId = UserHandle.getUserId(callingUid); 14357 synchronized (mPackages) { 14358 PackageParser.Package pkg = mPackages.get(packageName); 14359 if (pkg == null || pkg.activities == null) { 14360 return ParceledListSlice.emptyList(); 14361 } 14362 if (pkg.mExtras == null) { 14363 return ParceledListSlice.emptyList(); 14364 } 14365 final PackageSetting ps = (PackageSetting) pkg.mExtras; 14366 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 14367 return ParceledListSlice.emptyList(); 14368 } 14369 final int count = pkg.activities.size(); 14370 ArrayList<IntentFilter> result = new ArrayList<>(); 14371 for (int n=0; n<count; n++) { 14372 PackageParser.Activity activity = pkg.activities.get(n); 14373 if (activity.intents != null && activity.intents.size() > 0) { 14374 result.addAll(activity.intents); 14375 } 14376 } 14377 return new ParceledListSlice<>(result); 14378 } 14379 } 14380 14381 @Override 14382 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 14383 mContext.enforceCallingOrSelfPermission( 14384 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 14385 if (UserHandle.getCallingUserId() != userId) { 14386 mContext.enforceCallingOrSelfPermission( 14387 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14388 } 14389 if (userId == UserHandle.USER_ALL) { 14390 return false; 14391 } 14392 PackageManagerInternal.DefaultBrowserProvider provider; 14393 synchronized (mPackages) { 14394 provider = mDefaultBrowserProvider; 14395 } 14396 if (provider == null) { 14397 Slog.e(TAG, "mDefaultBrowserProvider is null"); 14398 return false; 14399 } 14400 boolean successful = provider.setDefaultBrowser(packageName, userId); 14401 if (!successful) { 14402 return false; 14403 } 14404 if (packageName != null) { 14405 synchronized (mPackages) { 14406 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName, 14407 userId); 14408 } 14409 } 14410 return true; 14411 } 14412 14413 private void setDefaultBrowserAsyncLPw(@Nullable String packageName, @UserIdInt int userId) { 14414 if (userId == UserHandle.USER_ALL) { 14415 return; 14416 } 14417 if (mDefaultBrowserProvider == null) { 14418 Slog.e(TAG, "mDefaultBrowserProvider is null"); 14419 return; 14420 } 14421 mDefaultBrowserProvider.setDefaultBrowserAsync(packageName, userId); 14422 if (packageName != null) { 14423 synchronized (mPackages) { 14424 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName, 14425 userId); 14426 } 14427 } 14428 } 14429 14430 @Override 14431 public String getDefaultBrowserPackageName(int userId) { 14432 if (UserHandle.getCallingUserId() != userId) { 14433 mContext.enforceCallingOrSelfPermission( 14434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 14435 } 14436 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14437 return null; 14438 } 14439 PackageManagerInternal.DefaultBrowserProvider provider; 14440 synchronized (mPackages) { 14441 provider = mDefaultBrowserProvider; 14442 } 14443 if (provider == null) { 14444 Slog.e(TAG, "mDefaultBrowserProvider is null"); 14445 return null; 14446 } 14447 return provider.getDefaultBrowser(userId); 14448 } 14449 14450 /** 14451 * Get the "allow unknown sources" setting. 14452 * 14453 * @return the current "allow unknown sources" setting 14454 */ 14455 private int getUnknownSourcesSettings() { 14456 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14457 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14458 -1); 14459 } 14460 14461 @Override 14462 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14463 final int callingUid = Binder.getCallingUid(); 14464 if (getInstantAppPackageName(callingUid) != null) { 14465 return; 14466 } 14467 // writer 14468 synchronized (mPackages) { 14469 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14470 if (targetPackageSetting == null 14471 || filterAppAccessLPr( 14472 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14473 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14474 } 14475 14476 PackageSetting installerPackageSetting; 14477 if (installerPackageName != null) { 14478 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14479 if (installerPackageSetting == null) { 14480 throw new IllegalArgumentException("Unknown installer package: " 14481 + installerPackageName); 14482 } 14483 } else { 14484 installerPackageSetting = null; 14485 } 14486 14487 Signature[] callerSignature; 14488 final int appId = UserHandle.getAppId(callingUid); 14489 final Object obj = mSettings.getSettingLPr(appId); 14490 if (obj != null) { 14491 if (obj instanceof SharedUserSetting) { 14492 callerSignature = 14493 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14494 } else if (obj instanceof PackageSetting) { 14495 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14496 } else { 14497 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14498 } 14499 } else { 14500 throw new SecurityException("Unknown calling UID: " + callingUid); 14501 } 14502 14503 // Verify: can't set installerPackageName to a package that is 14504 // not signed with the same cert as the caller. 14505 if (installerPackageSetting != null) { 14506 if (compareSignatures(callerSignature, 14507 installerPackageSetting.signatures.mSigningDetails.signatures) 14508 != PackageManager.SIGNATURE_MATCH) { 14509 throw new SecurityException( 14510 "Caller does not have same cert as new installer package " 14511 + installerPackageName); 14512 } 14513 } 14514 14515 // Verify: if target already has an installer package, it must 14516 // be signed with the same cert as the caller. 14517 String targetInstallerPackageName = 14518 targetPackageSetting.installerPackageName; 14519 PackageSetting targetInstallerPkgSetting = targetInstallerPackageName == null ? null : 14520 mSettings.mPackages.get(targetInstallerPackageName); 14521 14522 if (targetInstallerPkgSetting != null) { 14523 if (compareSignatures(callerSignature, 14524 targetInstallerPkgSetting.signatures.mSigningDetails.signatures) 14525 != PackageManager.SIGNATURE_MATCH) { 14526 throw new SecurityException( 14527 "Caller does not have same cert as old installer package " 14528 + targetInstallerPackageName); 14529 } 14530 } else if (mContext.checkCallingOrSelfPermission(Manifest.permission.INSTALL_PACKAGES) 14531 != PackageManager.PERMISSION_GRANTED) { 14532 // This is probably an attempt to exploit vulnerability b/150857253 of taking 14533 // privileged installer permissions when the installer has been uninstalled or 14534 // was never set. 14535 EventLog.writeEvent(0x534e4554, "150857253", callingUid, ""); 14536 14537 if (getUidTargetSdkVersionLockedLPr(callingUid) > Build.VERSION_CODES.Q) { 14538 throw new SecurityException("Neither user " + callingUid 14539 + " nor current process has " + Manifest.permission.INSTALL_PACKAGES); 14540 } else { 14541 // If not targeting >Q, fail silently for backwards compatibility 14542 return; 14543 } 14544 } 14545 14546 // Okay! 14547 targetPackageSetting.installerPackageName = installerPackageName; 14548 if (installerPackageName != null) { 14549 mSettings.mInstallerPackages.add(installerPackageName); 14550 } 14551 scheduleWriteSettingsLocked(); 14552 } 14553 } 14554 14555 @Override 14556 public void setApplicationCategoryHint(String packageName, int categoryHint, 14557 String callerPackageName) { 14558 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14559 throw new SecurityException("Instant applications don't have access to this method"); 14560 } 14561 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14562 callerPackageName); 14563 synchronized (mPackages) { 14564 PackageSetting ps = mSettings.mPackages.get(packageName); 14565 if (ps == null) { 14566 throw new IllegalArgumentException("Unknown target package " + packageName); 14567 } 14568 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14569 throw new IllegalArgumentException("Unknown target package " + packageName); 14570 } 14571 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14572 throw new IllegalArgumentException("Calling package " + callerPackageName 14573 + " is not installer for " + packageName); 14574 } 14575 14576 if (ps.categoryHint != categoryHint) { 14577 ps.categoryHint = categoryHint; 14578 scheduleWriteSettingsLocked(); 14579 } 14580 } 14581 } 14582 14583 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14584 if (args.mMultiPackageInstallParams != null) { 14585 args.mMultiPackageInstallParams.tryProcessInstallRequest(args, currentStatus); 14586 } else { 14587 PackageInstalledInfo res = createPackageInstalledInfo(currentStatus); 14588 processInstallRequestsAsync( 14589 res.returnCode == PackageManager.INSTALL_SUCCEEDED, 14590 Collections.singletonList(new InstallRequest(args, res))); 14591 } 14592 } 14593 14594 // Queue up an async operation since the package installation may take a little while. 14595 private void processInstallRequestsAsync(boolean success, 14596 List<InstallRequest> installRequests) { 14597 mHandler.post(() -> { 14598 if (success) { 14599 for (InstallRequest request : installRequests) { 14600 request.args.doPreInstall(request.installResult.returnCode); 14601 } 14602 synchronized (mInstallLock) { 14603 installPackagesTracedLI(installRequests); 14604 } 14605 for (InstallRequest request : installRequests) { 14606 request.args.doPostInstall( 14607 request.installResult.returnCode, request.installResult.uid); 14608 } 14609 } 14610 for (InstallRequest request : installRequests) { 14611 restoreAndPostInstall(request.args.user.getIdentifier(), request.installResult, 14612 new PostInstallData(request.args, request.installResult, null)); 14613 } 14614 }); 14615 } 14616 14617 private PackageInstalledInfo createPackageInstalledInfo( 14618 int currentStatus) { 14619 PackageInstalledInfo res = new PackageInstalledInfo(); 14620 res.setReturnCode(currentStatus); 14621 res.uid = -1; 14622 res.pkg = null; 14623 res.removedInfo = null; 14624 return res; 14625 } 14626 14627 /** @param data Post-install is performed only if this is non-null. */ 14628 private void restoreAndPostInstall( 14629 int userId, PackageInstalledInfo res, @Nullable PostInstallData data) { 14630 if (DEBUG_INSTALL) { 14631 Log.v(TAG, "restoreAndPostInstall userId=" + userId + " package=" 14632 + res.pkg.packageName); 14633 } 14634 14635 // A restore should be performed at this point if (a) the install 14636 // succeeded, (b) the operation is not an update, and (c) the new 14637 // package has not opted out of backup participation. 14638 final boolean update = res.removedInfo != null 14639 && res.removedInfo.removedPackage != null; 14640 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14641 boolean doRestore = !update 14642 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14643 14644 // Set up the post-install work request bookkeeping. This will be used 14645 // and cleaned up by the post-install event handling regardless of whether 14646 // there's a restore pass performed. Token values are >= 1. 14647 int token; 14648 if (mNextInstallToken < 0) mNextInstallToken = 1; 14649 token = mNextInstallToken++; 14650 if (data != null) { 14651 mRunningInstalls.put(token, data); 14652 } else if (DEBUG_INSTALL) { 14653 Log.v(TAG, "No post-install required for " + token); 14654 } 14655 14656 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14657 14658 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14659 // Pass responsibility to the Backup Manager. It will perform a 14660 // restore if appropriate, then pass responsibility back to the 14661 // Package Manager to run the post-install observer callbacks 14662 // and broadcasts. 14663 IBackupManager bm = IBackupManager.Stub.asInterface( 14664 ServiceManager.getService(Context.BACKUP_SERVICE)); 14665 if (bm != null) { 14666 // For backwards compatibility as USER_ALL previously routed directly to USER_SYSTEM 14667 // in the BackupManager. USER_ALL is used in compatibility tests. 14668 if (userId == UserHandle.USER_ALL) { 14669 userId = UserHandle.USER_SYSTEM; 14670 } 14671 if (DEBUG_INSTALL) { 14672 Log.v(TAG, "token " + token + " to BM for possible restore for user " + userId); 14673 } 14674 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14675 try { 14676 if (bm.isBackupServiceActive(userId)) { 14677 bm.restoreAtInstallForUser( 14678 userId, res.pkg.applicationInfo.packageName, token); 14679 } else { 14680 doRestore = false; 14681 } 14682 } catch (RemoteException e) { 14683 // can't happen; the backup manager is local 14684 } catch (Exception e) { 14685 Slog.e(TAG, "Exception trying to enqueue restore", e); 14686 doRestore = false; 14687 } 14688 } else { 14689 Slog.e(TAG, "Backup Manager not found!"); 14690 doRestore = false; 14691 } 14692 } 14693 14694 // If this is an update to a package that might be potentially downgraded, then we 14695 // need to check with the rollback manager whether there's any userdata that might 14696 // need to be restored for the package. 14697 // 14698 // TODO(narayan): Get this working for cases where userId == UserHandle.USER_ALL. 14699 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && !doRestore && update) { 14700 IRollbackManager rm = IRollbackManager.Stub.asInterface( 14701 ServiceManager.getService(Context.ROLLBACK_SERVICE)); 14702 14703 final String packageName = res.pkg.applicationInfo.packageName; 14704 final String seInfo = res.pkg.applicationInfo.seInfo; 14705 final int[] allUsers = sUserManager.getUserIds(); 14706 final int[] installedUsers; 14707 14708 final PackageSetting ps; 14709 int appId = -1; 14710 long ceDataInode = -1; 14711 synchronized (mSettings) { 14712 ps = mSettings.getPackageLPr(packageName); 14713 if (ps != null) { 14714 appId = ps.appId; 14715 ceDataInode = ps.getCeDataInode(userId); 14716 } 14717 14718 // NOTE: We ignore the user specified in the InstallParam because we know this is 14719 // an update, and hence need to restore data for all installed users. 14720 installedUsers = ps.queryInstalledUsers(allUsers, true); 14721 } 14722 14723 if (ps != null) { 14724 try { 14725 rm.snapshotAndRestoreUserData(packageName, installedUsers, appId, ceDataInode, 14726 seInfo, token); 14727 } catch (RemoteException re) { 14728 // Cannot happen, the RollbackManager is hosted in the same process. 14729 } 14730 doRestore = true; 14731 } 14732 } 14733 14734 if (!doRestore) { 14735 // No restore possible, or the Backup Manager was mysteriously not 14736 // available -- just fire the post-install work request directly. 14737 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14738 14739 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14740 14741 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14742 mHandler.sendMessage(msg); 14743 } 14744 } 14745 14746 /** 14747 * Callback from PackageSettings whenever an app is first transitioned out of the 14748 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14749 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14750 * here whether the app is the target of an ongoing install, and only send the 14751 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14752 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14753 * handling. 14754 */ 14755 void notifyFirstLaunch(final String packageName, final String installerPackage, 14756 final int userId) { 14757 // Serialize this with the rest of the install-process message chain. In the 14758 // restore-at-install case, this Runnable will necessarily run before the 14759 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14760 // are coherent. In the non-restore case, the app has already completed install 14761 // and been launched through some other means, so it is not in a problematic 14762 // state for observers to see the FIRST_LAUNCH signal. 14763 mHandler.post(() -> { 14764 for (int i = 0; i < mRunningInstalls.size(); i++) { 14765 final PostInstallData data = mRunningInstalls.valueAt(i); 14766 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14767 continue; 14768 } 14769 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14770 // right package; but is it for the right user? 14771 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14772 if (userId == data.res.newUsers[uIndex]) { 14773 if (DEBUG_BACKUP) { 14774 Slog.i(TAG, "Package " + packageName 14775 + " being restored so deferring FIRST_LAUNCH"); 14776 } 14777 return; 14778 } 14779 } 14780 } 14781 } 14782 // didn't find it, so not being restored 14783 if (DEBUG_BACKUP) { 14784 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14785 } 14786 final boolean isInstantApp = isInstantApp(packageName, userId); 14787 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14788 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14789 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14790 }); 14791 } 14792 14793 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14794 int[] userIds, int[] instantUserIds) { 14795 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14796 installerPkg, null, userIds, instantUserIds); 14797 } 14798 14799 private abstract class HandlerParams { 14800 /** User handle for the user requesting the information or installation. */ 14801 private final UserHandle mUser; 14802 String traceMethod; 14803 int traceCookie; 14804 14805 HandlerParams(UserHandle user) { 14806 mUser = user; 14807 } 14808 14809 UserHandle getUser() { 14810 return mUser; 14811 } 14812 14813 /** 14814 * Gets the user handle for the user that the rollback agent should 14815 * use to look up information about this installation when enabling 14816 * rollback. 14817 */ 14818 UserHandle getRollbackUser() { 14819 // The session for packages installed for "all" users is 14820 // associated with the "system" user. 14821 if (mUser == UserHandle.ALL) { 14822 return UserHandle.SYSTEM; 14823 } 14824 return mUser; 14825 } 14826 14827 HandlerParams setTraceMethod(String traceMethod) { 14828 this.traceMethod = traceMethod; 14829 return this; 14830 } 14831 14832 HandlerParams setTraceCookie(int traceCookie) { 14833 this.traceCookie = traceCookie; 14834 return this; 14835 } 14836 14837 final void startCopy() { 14838 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14839 handleStartCopy(); 14840 handleReturnCode(); 14841 } 14842 14843 abstract void handleStartCopy(); 14844 abstract void handleReturnCode(); 14845 } 14846 14847 static class OriginInfo { 14848 /** 14849 * Location where install is coming from, before it has been 14850 * copied/renamed into place. This could be a single monolithic APK 14851 * file, or a cluster directory. This location may be untrusted. 14852 */ 14853 final File file; 14854 14855 /** 14856 * Flag indicating that {@link #file} has already been staged, meaning downstream users 14857 * don't need to defensively copy the contents. 14858 */ 14859 final boolean staged; 14860 14861 /** 14862 * Flag indicating that {@link #file} is an already installed app that is being moved. 14863 */ 14864 final boolean existing; 14865 14866 final String resolvedPath; 14867 final File resolvedFile; 14868 14869 static OriginInfo fromNothing() { 14870 return new OriginInfo(null, false, false); 14871 } 14872 14873 static OriginInfo fromUntrustedFile(File file) { 14874 return new OriginInfo(file, false, false); 14875 } 14876 14877 static OriginInfo fromExistingFile(File file) { 14878 return new OriginInfo(file, false, true); 14879 } 14880 14881 static OriginInfo fromStagedFile(File file) { 14882 return new OriginInfo(file, true, false); 14883 } 14884 14885 private OriginInfo(File file, boolean staged, boolean existing) { 14886 this.file = file; 14887 this.staged = staged; 14888 this.existing = existing; 14889 14890 if (file != null) { 14891 resolvedPath = file.getAbsolutePath(); 14892 resolvedFile = file; 14893 } else { 14894 resolvedPath = null; 14895 resolvedFile = null; 14896 } 14897 } 14898 } 14899 14900 static class MoveInfo { 14901 final int moveId; 14902 final String fromUuid; 14903 final String toUuid; 14904 final String packageName; 14905 final String dataAppName; 14906 final int appId; 14907 final String seinfo; 14908 final int targetSdkVersion; 14909 14910 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14911 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14912 this.moveId = moveId; 14913 this.fromUuid = fromUuid; 14914 this.toUuid = toUuid; 14915 this.packageName = packageName; 14916 this.dataAppName = dataAppName; 14917 this.appId = appId; 14918 this.seinfo = seinfo; 14919 this.targetSdkVersion = targetSdkVersion; 14920 } 14921 } 14922 14923 static class VerificationInfo { 14924 /** A constant used to indicate that a uid value is not present. */ 14925 public static final int NO_UID = -1; 14926 14927 /** URI referencing where the package was downloaded from. */ 14928 final Uri originatingUri; 14929 14930 /** HTTP referrer URI associated with the originatingURI. */ 14931 final Uri referrer; 14932 14933 /** UID of the application that the install request originated from. */ 14934 final int originatingUid; 14935 14936 /** UID of application requesting the install */ 14937 final int installerUid; 14938 14939 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14940 this.originatingUri = originatingUri; 14941 this.referrer = referrer; 14942 this.originatingUid = originatingUid; 14943 this.installerUid = installerUid; 14944 } 14945 } 14946 14947 /** 14948 * Container for a multi-package install which refers to all install sessions and args being 14949 * committed together. 14950 */ 14951 class MultiPackageInstallParams extends HandlerParams { 14952 14953 private int mRet = INSTALL_SUCCEEDED; 14954 @NonNull 14955 private final ArrayList<InstallParams> mChildParams; 14956 @NonNull 14957 private final Map<InstallArgs, Integer> mCurrentState; 14958 14959 MultiPackageInstallParams( 14960 @NonNull UserHandle user, 14961 @NonNull List<ActiveInstallSession> activeInstallSessions) 14962 throws PackageManagerException { 14963 super(user); 14964 if (activeInstallSessions.size() == 0) { 14965 throw new PackageManagerException("No child sessions found!"); 14966 } 14967 mChildParams = new ArrayList<>(activeInstallSessions.size()); 14968 for (int i = 0; i < activeInstallSessions.size(); i++) { 14969 final InstallParams childParams = new InstallParams(activeInstallSessions.get(i)); 14970 childParams.mParentInstallParams = this; 14971 this.mChildParams.add(childParams); 14972 } 14973 this.mCurrentState = new ArrayMap<>(mChildParams.size()); 14974 } 14975 14976 @Override 14977 void handleStartCopy() { 14978 for (InstallParams params : mChildParams) { 14979 params.handleStartCopy(); 14980 if (params.mRet != INSTALL_SUCCEEDED) { 14981 mRet = params.mRet; 14982 } 14983 } 14984 } 14985 14986 @Override 14987 void handleReturnCode() { 14988 for (InstallParams params : mChildParams) { 14989 params.handleReturnCode(); 14990 if (params.mRet != INSTALL_SUCCEEDED) { 14991 mRet = params.mRet; 14992 } 14993 } 14994 } 14995 14996 void tryProcessInstallRequest(InstallArgs args, int currentStatus) { 14997 mCurrentState.put(args, currentStatus); 14998 if (mCurrentState.size() != mChildParams.size()) { 14999 return; 15000 } 15001 int completeStatus = PackageManager.INSTALL_SUCCEEDED; 15002 for (Integer status : mCurrentState.values()) { 15003 if (status == PackageManager.INSTALL_UNKNOWN) { 15004 return; 15005 } else if (status != PackageManager.INSTALL_SUCCEEDED) { 15006 completeStatus = status; 15007 break; 15008 } 15009 } 15010 final List<InstallRequest> installRequests = new ArrayList<>(mCurrentState.size()); 15011 for (Map.Entry<InstallArgs, Integer> entry : mCurrentState.entrySet()) { 15012 installRequests.add(new InstallRequest(entry.getKey(), 15013 createPackageInstalledInfo(completeStatus))); 15014 } 15015 processInstallRequestsAsync( 15016 completeStatus == PackageManager.INSTALL_SUCCEEDED, 15017 installRequests); 15018 } 15019 } 15020 15021 class InstallParams extends HandlerParams { 15022 // TODO: see if we can collapse this into ActiveInstallSession 15023 15024 final OriginInfo origin; 15025 final MoveInfo move; 15026 final IPackageInstallObserver2 observer; 15027 int installFlags; 15028 final String installerPackageName; 15029 final String volumeUuid; 15030 private boolean mVerificationCompleted; 15031 private boolean mEnableRollbackCompleted; 15032 private InstallArgs mArgs; 15033 int mRet; 15034 final String packageAbiOverride; 15035 final String[] grantedRuntimePermissions; 15036 final List<String> whitelistedRestrictedPermissions; 15037 final VerificationInfo verificationInfo; 15038 final PackageParser.SigningDetails signingDetails; 15039 final int installReason; 15040 @Nullable 15041 MultiPackageInstallParams mParentInstallParams; 15042 final long requiredInstalledVersionCode; 15043 15044 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15045 int installFlags, String installerPackageName, String volumeUuid, 15046 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 15047 String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, 15048 PackageParser.SigningDetails signingDetails, int installReason, 15049 long requiredInstalledVersionCode) { 15050 super(user); 15051 this.origin = origin; 15052 this.move = move; 15053 this.observer = observer; 15054 this.installFlags = installFlags; 15055 this.installerPackageName = installerPackageName; 15056 this.volumeUuid = volumeUuid; 15057 this.verificationInfo = verificationInfo; 15058 this.packageAbiOverride = packageAbiOverride; 15059 this.grantedRuntimePermissions = grantedPermissions; 15060 this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions; 15061 this.signingDetails = signingDetails; 15062 this.installReason = installReason; 15063 this.requiredInstalledVersionCode = requiredInstalledVersionCode; 15064 } 15065 15066 InstallParams(ActiveInstallSession activeInstallSession) { 15067 super(activeInstallSession.getUser()); 15068 if (DEBUG_INSTANT) { 15069 if ((activeInstallSession.getSessionParams().installFlags 15070 & PackageManager.INSTALL_INSTANT_APP) != 0) { 15071 Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName()); 15072 } 15073 } 15074 verificationInfo = new VerificationInfo( 15075 activeInstallSession.getSessionParams().originatingUri, 15076 activeInstallSession.getSessionParams().referrerUri, 15077 activeInstallSession.getSessionParams().originatingUid, 15078 activeInstallSession.getInstallerUid()); 15079 origin = OriginInfo.fromStagedFile(activeInstallSession.getStagedDir()); 15080 move = null; 15081 installReason = fixUpInstallReason(activeInstallSession.getInstallerPackageName(), 15082 activeInstallSession.getInstallerUid(), 15083 activeInstallSession.getSessionParams().installReason); 15084 observer = activeInstallSession.getObserver(); 15085 installFlags = activeInstallSession.getSessionParams().installFlags; 15086 installerPackageName = activeInstallSession.getInstallerPackageName(); 15087 volumeUuid = activeInstallSession.getSessionParams().volumeUuid; 15088 packageAbiOverride = activeInstallSession.getSessionParams().abiOverride; 15089 grantedRuntimePermissions = activeInstallSession.getSessionParams() 15090 .grantedRuntimePermissions; 15091 whitelistedRestrictedPermissions = activeInstallSession.getSessionParams() 15092 .whitelistedRestrictedPermissions; 15093 signingDetails = activeInstallSession.getSigningDetails(); 15094 requiredInstalledVersionCode = activeInstallSession.getSessionParams() 15095 .requiredInstalledVersionCode; 15096 } 15097 15098 @Override 15099 public String toString() { 15100 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 15101 + " file=" + origin.file + "}"; 15102 } 15103 15104 private int installLocationPolicy(PackageInfoLite pkgLite) { 15105 String packageName = pkgLite.packageName; 15106 int installLocation = pkgLite.installLocation; 15107 // reader 15108 synchronized (mPackages) { 15109 // Currently installed package which the new package is attempting to replace or 15110 // null if no such package is installed. 15111 PackageParser.Package installedPkg = mPackages.get(packageName); 15112 // Package which currently owns the data which the new package will own if installed. 15113 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 15114 // will be null whereas dataOwnerPkg will contain information about the package 15115 // which was uninstalled while keeping its data. 15116 PackageParser.Package dataOwnerPkg = installedPkg; 15117 if (dataOwnerPkg == null) { 15118 PackageSetting ps = mSettings.mPackages.get(packageName); 15119 if (ps != null) { 15120 dataOwnerPkg = ps.pkg; 15121 } 15122 } 15123 15124 if (requiredInstalledVersionCode != PackageManager.VERSION_CODE_HIGHEST) { 15125 if (dataOwnerPkg == null) { 15126 Slog.w(TAG, "Required installed version code was " 15127 + requiredInstalledVersionCode 15128 + " but package is not installed"); 15129 return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION; 15130 } 15131 15132 if (dataOwnerPkg.getLongVersionCode() != requiredInstalledVersionCode) { 15133 Slog.w(TAG, "Required installed version code was " 15134 + requiredInstalledVersionCode 15135 + " but actual installed version is " 15136 + dataOwnerPkg.getLongVersionCode()); 15137 return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION; 15138 } 15139 } 15140 15141 if (dataOwnerPkg != null) { 15142 if (!PackageManagerServiceUtils.isDowngradePermitted(installFlags, 15143 dataOwnerPkg.applicationInfo.flags)) { 15144 try { 15145 checkDowngrade(dataOwnerPkg, pkgLite); 15146 } catch (PackageManagerException e) { 15147 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 15148 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 15149 } 15150 } 15151 } 15152 15153 if (installedPkg != null) { 15154 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15155 // Check for updated system application. 15156 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 15157 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15158 } else { 15159 // If current upgrade specifies particular preference 15160 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 15161 // Application explicitly specified internal. 15162 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15163 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 15164 // App explictly prefers external. Let policy decide 15165 } else { 15166 // Prefer previous location 15167 if (isExternal(installedPkg)) { 15168 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 15169 } 15170 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 15171 } 15172 } 15173 } else { 15174 // Invalid install. Return error code 15175 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 15176 } 15177 } 15178 } 15179 return pkgLite.recommendedInstallLocation; 15180 } 15181 15182 /* 15183 * Invoke remote method to get package information and install 15184 * location values. Override install location based on default 15185 * policy if needed and then create install arguments based 15186 * on the install location. 15187 */ 15188 public void handleStartCopy() { 15189 int ret = PackageManager.INSTALL_SUCCEEDED; 15190 15191 // If we're already staged, we've firmly committed to an install location 15192 if (origin.staged) { 15193 if (origin.file != null) { 15194 installFlags |= PackageManager.INSTALL_INTERNAL; 15195 } else { 15196 throw new IllegalStateException("Invalid stage location"); 15197 } 15198 } 15199 15200 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 15201 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15202 PackageInfoLite pkgLite = null; 15203 15204 15205 pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext, 15206 origin.resolvedPath, installFlags, packageAbiOverride); 15207 15208 if (DEBUG_INSTANT && ephemeral) { 15209 Slog.v(TAG, "pkgLite for install: " + pkgLite); 15210 } 15211 15212 /* 15213 * If we have too little free space, try to free cache 15214 * before giving up. 15215 */ 15216 if (!origin.staged && pkgLite.recommendedInstallLocation 15217 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15218 // TODO: focus freeing disk space on the target device 15219 final StorageManager storage = StorageManager.from(mContext); 15220 final long lowThreshold = storage.getStorageLowBytes( 15221 Environment.getDataDirectory()); 15222 15223 final long sizeBytes = PackageManagerServiceUtils.calculateInstalledSize( 15224 origin.resolvedPath, packageAbiOverride); 15225 if (sizeBytes >= 0) { 15226 try { 15227 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 15228 pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext, 15229 origin.resolvedPath, installFlags, packageAbiOverride); 15230 } catch (InstallerException e) { 15231 Slog.w(TAG, "Failed to free cache", e); 15232 } 15233 } 15234 15235 /* 15236 * The cache free must have deleted the file we downloaded to install. 15237 * 15238 * TODO: fix the "freeCache" call to not delete the file we care about. 15239 */ 15240 if (pkgLite.recommendedInstallLocation 15241 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15242 pkgLite.recommendedInstallLocation 15243 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 15244 } 15245 } 15246 15247 15248 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15249 int loc = pkgLite.recommendedInstallLocation; 15250 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 15251 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 15252 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 15253 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 15254 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 15255 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15256 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 15257 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 15258 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 15259 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 15260 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 15261 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 15262 } else { 15263 // Override with defaults if needed. 15264 loc = installLocationPolicy(pkgLite); 15265 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 15266 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 15267 } else if (loc == PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION) { 15268 ret = PackageManager.INSTALL_FAILED_WRONG_INSTALLED_VERSION; 15269 } else if (!onInt) { 15270 // Override install location with flags 15271 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 15272 // Set the flag to install on external media. 15273 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15274 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 15275 if (DEBUG_INSTANT) { 15276 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 15277 } 15278 installFlags |= PackageManager.INSTALL_INSTANT_APP; 15279 installFlags &= ~PackageManager.INSTALL_INTERNAL; 15280 } else { 15281 // Make sure the flag for installing on external 15282 // media is unset 15283 installFlags |= PackageManager.INSTALL_INTERNAL; 15284 } 15285 } 15286 } 15287 } 15288 15289 final InstallArgs args = createInstallArgs(this); 15290 mVerificationCompleted = true; 15291 mEnableRollbackCompleted = true; 15292 mArgs = args; 15293 15294 if (ret == PackageManager.INSTALL_SUCCEEDED) { 15295 // TODO: http://b/22976637 15296 // Apps installed for "all" users use the device owner to verify the app 15297 UserHandle verifierUser = getUser(); 15298 if (verifierUser == UserHandle.ALL) { 15299 verifierUser = UserHandle.SYSTEM; 15300 } 15301 15302 /* 15303 * Determine if we have any installed package verifiers. If we 15304 * do, then we'll defer to them to verify the packages. 15305 */ 15306 final int requiredUid = mRequiredVerifierPackage == null ? -1 15307 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 15308 verifierUser.getIdentifier()); 15309 final int installerUid = 15310 verificationInfo == null ? -1 : verificationInfo.installerUid; 15311 if (!origin.existing && requiredUid != -1 15312 && isVerificationEnabled( 15313 verifierUser.getIdentifier(), installFlags, installerUid)) { 15314 final Intent verification = new Intent( 15315 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 15316 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 15317 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15318 PACKAGE_MIME_TYPE); 15319 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15320 15321 // Query all live verifiers based on current user state 15322 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 15323 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 15324 false /*allowDynamicSplits*/); 15325 15326 if (DEBUG_VERIFY) { 15327 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 15328 + verification.toString() + " with " + pkgLite.verifiers.length 15329 + " optional verifiers"); 15330 } 15331 15332 final int verificationId = mPendingVerificationToken++; 15333 15334 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 15335 15336 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 15337 installerPackageName); 15338 15339 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 15340 installFlags); 15341 15342 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 15343 pkgLite.packageName); 15344 15345 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 15346 pkgLite.versionCode); 15347 15348 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 15349 pkgLite.getLongVersionCode()); 15350 15351 if (verificationInfo != null) { 15352 if (verificationInfo.originatingUri != null) { 15353 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 15354 verificationInfo.originatingUri); 15355 } 15356 if (verificationInfo.referrer != null) { 15357 verification.putExtra(Intent.EXTRA_REFERRER, 15358 verificationInfo.referrer); 15359 } 15360 if (verificationInfo.originatingUid >= 0) { 15361 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 15362 verificationInfo.originatingUid); 15363 } 15364 if (verificationInfo.installerUid >= 0) { 15365 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 15366 verificationInfo.installerUid); 15367 } 15368 } 15369 15370 final PackageVerificationState verificationState = new PackageVerificationState( 15371 requiredUid, this); 15372 15373 mPendingVerification.append(verificationId, verificationState); 15374 15375 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 15376 receivers, verificationState); 15377 15378 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 15379 final long idleDuration = getVerificationTimeout(); 15380 15381 /* 15382 * If any sufficient verifiers were listed in the package 15383 * manifest, attempt to ask them. 15384 */ 15385 if (sufficientVerifiers != null) { 15386 final int N = sufficientVerifiers.size(); 15387 if (N == 0) { 15388 Slog.i(TAG, "Additional verifiers required, but none installed."); 15389 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 15390 } else { 15391 for (int i = 0; i < N; i++) { 15392 final ComponentName verifierComponent = sufficientVerifiers.get(i); 15393 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15394 verifierComponent.getPackageName(), idleDuration, 15395 verifierUser.getIdentifier(), false, "package verifier"); 15396 15397 final Intent sufficientIntent = new Intent(verification); 15398 sufficientIntent.setComponent(verifierComponent); 15399 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 15400 } 15401 } 15402 } 15403 15404 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 15405 mRequiredVerifierPackage, receivers); 15406 if (ret == PackageManager.INSTALL_SUCCEEDED 15407 && mRequiredVerifierPackage != null) { 15408 Trace.asyncTraceBegin( 15409 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 15410 /* 15411 * Send the intent to the required verification agent, 15412 * but only start the verification timeout after the 15413 * target BroadcastReceivers have run. 15414 */ 15415 verification.setComponent(requiredVerifierComponent); 15416 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 15417 mRequiredVerifierPackage, idleDuration, 15418 verifierUser.getIdentifier(), false, "package verifier"); 15419 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 15420 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 15421 new BroadcastReceiver() { 15422 @Override 15423 public void onReceive(Context context, Intent intent) { 15424 final Message msg = mHandler 15425 .obtainMessage(CHECK_PENDING_VERIFICATION); 15426 msg.arg1 = verificationId; 15427 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 15428 } 15429 }, null, 0, null, null); 15430 15431 /* 15432 * We don't want the copy to proceed until verification 15433 * succeeds. 15434 */ 15435 mVerificationCompleted = false; 15436 } 15437 } 15438 15439 if ((installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) { 15440 // TODO(ruhler) b/112431924: Don't do this in case of 'move'? 15441 final int enableRollbackToken = mPendingEnableRollbackToken++; 15442 Trace.asyncTraceBegin( 15443 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 15444 mPendingEnableRollback.append(enableRollbackToken, this); 15445 15446 final int[] installedUsers; 15447 synchronized (mPackages) { 15448 PackageSetting ps = mSettings.getPackageLPr(pkgLite.packageName); 15449 if (ps != null) { 15450 installedUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), 15451 true); 15452 } else { 15453 installedUsers = new int[0]; 15454 } 15455 } 15456 15457 Intent enableRollbackIntent = new Intent(Intent.ACTION_PACKAGE_ENABLE_ROLLBACK); 15458 enableRollbackIntent.putExtra( 15459 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN, 15460 enableRollbackToken); 15461 enableRollbackIntent.putExtra( 15462 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_INSTALL_FLAGS, 15463 installFlags); 15464 enableRollbackIntent.putExtra( 15465 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_INSTALLED_USERS, 15466 installedUsers); 15467 enableRollbackIntent.putExtra( 15468 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_USER, 15469 getRollbackUser().getIdentifier()); 15470 enableRollbackIntent.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15471 PACKAGE_MIME_TYPE); 15472 enableRollbackIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15473 15474 // Allow the broadcast to be sent before boot complete. 15475 // This is needed when committing the apk part of a staged 15476 // session in early boot. The rollback manager registers 15477 // its receiver early enough during the boot process that 15478 // it will not miss the broadcast. 15479 enableRollbackIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 15480 15481 mContext.sendOrderedBroadcastAsUser(enableRollbackIntent, UserHandle.SYSTEM, 15482 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT, 15483 new BroadcastReceiver() { 15484 @Override 15485 public void onReceive(Context context, Intent intent) { 15486 // the duration to wait for rollback to be enabled, in millis 15487 long rollbackTimeout = DeviceConfig.getLong( 15488 DeviceConfig.NAMESPACE_ROLLBACK, 15489 PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS, 15490 DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS); 15491 if (rollbackTimeout < 0) { 15492 rollbackTimeout = DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS; 15493 } 15494 final Message msg = mHandler.obtainMessage( 15495 ENABLE_ROLLBACK_TIMEOUT); 15496 msg.arg1 = enableRollbackToken; 15497 mHandler.sendMessageDelayed(msg, rollbackTimeout); 15498 } 15499 }, null, 0, null, null); 15500 15501 mEnableRollbackCompleted = false; 15502 } 15503 } 15504 15505 mRet = ret; 15506 } 15507 15508 void setReturnCode(int ret) { 15509 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 15510 // Only update mRet if it was previously INSTALL_SUCCEEDED to 15511 // ensure we do not overwrite any previous failure results. 15512 mRet = ret; 15513 } 15514 } 15515 15516 void handleVerificationFinished() { 15517 mVerificationCompleted = true; 15518 handleReturnCode(); 15519 } 15520 15521 void handleRollbackEnabled() { 15522 // TODO(ruhler) b/112431924: Consider halting the install if we 15523 // couldn't enable rollback. 15524 mEnableRollbackCompleted = true; 15525 handleReturnCode(); 15526 } 15527 15528 @Override 15529 void handleReturnCode() { 15530 if (mVerificationCompleted && mEnableRollbackCompleted) { 15531 if ((installFlags & PackageManager.INSTALL_DRY_RUN) != 0) { 15532 String packageName = ""; 15533 try { 15534 PackageLite packageInfo = 15535 new PackageParser().parsePackageLite(origin.file, 0); 15536 packageName = packageInfo.packageName; 15537 } catch (PackageParserException e) { 15538 Slog.e(TAG, "Can't parse package at " + origin.file.getAbsolutePath(), e); 15539 } 15540 try { 15541 observer.onPackageInstalled(packageName, mRet, "Dry run", new Bundle()); 15542 } catch (RemoteException e) { 15543 Slog.i(TAG, "Observer no longer exists."); 15544 } 15545 return; 15546 } 15547 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 15548 mRet = mArgs.copyApk(); 15549 } 15550 processPendingInstall(mArgs, mRet); 15551 } 15552 } 15553 } 15554 15555 private InstallArgs createInstallArgs(InstallParams params) { 15556 if (params.move != null) { 15557 return new MoveInstallArgs(params); 15558 } else { 15559 return new FileInstallArgs(params); 15560 } 15561 } 15562 15563 /** 15564 * Create args that describe an existing installed package. Typically used 15565 * when cleaning up old installs, or used as a move source. 15566 */ 15567 private InstallArgs createInstallArgsForExisting(String codePath, 15568 String resourcePath, String[] instructionSets) { 15569 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15570 } 15571 15572 static abstract class InstallArgs { 15573 /** @see InstallParams#origin */ 15574 final OriginInfo origin; 15575 /** @see InstallParams#move */ 15576 final MoveInfo move; 15577 15578 final IPackageInstallObserver2 observer; 15579 // Always refers to PackageManager flags only 15580 final int installFlags; 15581 final String installerPackageName; 15582 final String volumeUuid; 15583 final UserHandle user; 15584 final String abiOverride; 15585 final String[] installGrantPermissions; 15586 final List<String> whitelistedRestrictedPermissions; 15587 /** If non-null, drop an async trace when the install completes */ 15588 final String traceMethod; 15589 final int traceCookie; 15590 final PackageParser.SigningDetails signingDetails; 15591 final int installReason; 15592 @Nullable final MultiPackageInstallParams mMultiPackageInstallParams; 15593 15594 // The list of instruction sets supported by this app. This is currently 15595 // only used during the rmdex() phase to clean up resources. We can get rid of this 15596 // if we move dex files under the common app path. 15597 /* nullable */ String[] instructionSets; 15598 15599 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15600 int installFlags, String installerPackageName, String volumeUuid, 15601 UserHandle user, String[] instructionSets, 15602 String abiOverride, String[] installGrantPermissions, 15603 List<String> whitelistedRestrictedPermissions, 15604 String traceMethod, int traceCookie, SigningDetails signingDetails, 15605 int installReason, 15606 MultiPackageInstallParams multiPackageInstallParams) { 15607 this.origin = origin; 15608 this.move = move; 15609 this.installFlags = installFlags; 15610 this.observer = observer; 15611 this.installerPackageName = installerPackageName; 15612 this.volumeUuid = volumeUuid; 15613 this.user = user; 15614 this.instructionSets = instructionSets; 15615 this.abiOverride = abiOverride; 15616 this.installGrantPermissions = installGrantPermissions; 15617 this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions; 15618 this.traceMethod = traceMethod; 15619 this.traceCookie = traceCookie; 15620 this.signingDetails = signingDetails; 15621 this.installReason = installReason; 15622 this.mMultiPackageInstallParams = multiPackageInstallParams; 15623 } 15624 15625 abstract int copyApk(); 15626 abstract int doPreInstall(int status); 15627 15628 /** 15629 * Rename package into final resting place. All paths on the given 15630 * scanned package should be updated to reflect the rename. 15631 */ 15632 abstract boolean doRename(int status, PackageParser.Package pkg); 15633 abstract int doPostInstall(int status, int uid); 15634 15635 /** @see PackageSettingBase#codePathString */ 15636 abstract String getCodePath(); 15637 /** @see PackageSettingBase#resourcePathString */ 15638 abstract String getResourcePath(); 15639 15640 // Need installer lock especially for dex file removal. 15641 abstract void cleanUpResourcesLI(); 15642 abstract boolean doPostDeleteLI(boolean delete); 15643 15644 /** 15645 * Called before the source arguments are copied. This is used mostly 15646 * for MoveParams when it needs to read the source file to put it in the 15647 * destination. 15648 */ 15649 int doPreCopy() { 15650 return PackageManager.INSTALL_SUCCEEDED; 15651 } 15652 15653 /** 15654 * Called after the source arguments are copied. This is used mostly for 15655 * MoveParams when it needs to read the source file to put it in the 15656 * destination. 15657 */ 15658 int doPostCopy(int uid) { 15659 return PackageManager.INSTALL_SUCCEEDED; 15660 } 15661 15662 protected boolean isEphemeral() { 15663 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15664 } 15665 15666 UserHandle getUser() { 15667 return user; 15668 } 15669 } 15670 15671 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15672 if (!allCodePaths.isEmpty()) { 15673 if (instructionSets == null) { 15674 throw new IllegalStateException("instructionSet == null"); 15675 } 15676 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15677 for (String codePath : allCodePaths) { 15678 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15679 try { 15680 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15681 } catch (InstallerException ignored) { 15682 } 15683 } 15684 } 15685 } 15686 } 15687 15688 /** 15689 * Logic to handle installation of new applications, including copying 15690 * and renaming logic. 15691 */ 15692 class FileInstallArgs extends InstallArgs { 15693 private File codeFile; 15694 private File resourceFile; 15695 15696 // Example topology: 15697 // /data/app/com.example/base.apk 15698 // /data/app/com.example/split_foo.apk 15699 // /data/app/com.example/lib/arm/libfoo.so 15700 // /data/app/com.example/lib/arm64/libfoo.so 15701 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15702 15703 /** New install */ 15704 FileInstallArgs(InstallParams params) { 15705 super(params.origin, params.move, params.observer, params.installFlags, 15706 params.installerPackageName, params.volumeUuid, 15707 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15708 params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions, 15709 params.traceMethod, params.traceCookie, params.signingDetails, 15710 params.installReason, params.mParentInstallParams); 15711 } 15712 15713 /** Existing install */ 15714 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15715 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15716 null, null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15717 PackageManager.INSTALL_REASON_UNKNOWN, null /* parent */); 15718 this.codeFile = (codePath != null) ? new File(codePath) : null; 15719 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15720 } 15721 15722 int copyApk() { 15723 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15724 try { 15725 return doCopyApk(); 15726 } finally { 15727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15728 } 15729 } 15730 15731 private int doCopyApk() { 15732 if (origin.staged) { 15733 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15734 codeFile = origin.file; 15735 resourceFile = origin.file; 15736 return PackageManager.INSTALL_SUCCEEDED; 15737 } 15738 15739 try { 15740 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15741 final File tempDir = 15742 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15743 codeFile = tempDir; 15744 resourceFile = tempDir; 15745 } catch (IOException e) { 15746 Slog.w(TAG, "Failed to create copy file: " + e); 15747 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15748 } 15749 15750 int ret = PackageManagerServiceUtils.copyPackage( 15751 origin.file.getAbsolutePath(), codeFile); 15752 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15753 Slog.e(TAG, "Failed to copy package"); 15754 return ret; 15755 } 15756 15757 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15758 NativeLibraryHelper.Handle handle = null; 15759 try { 15760 handle = NativeLibraryHelper.Handle.create(codeFile); 15761 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15762 abiOverride); 15763 } catch (IOException e) { 15764 Slog.e(TAG, "Copying native libraries failed", e); 15765 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15766 } finally { 15767 IoUtils.closeQuietly(handle); 15768 } 15769 15770 return ret; 15771 } 15772 15773 int doPreInstall(int status) { 15774 if (status != PackageManager.INSTALL_SUCCEEDED) { 15775 cleanUp(); 15776 } 15777 return status; 15778 } 15779 15780 boolean doRename(int status, PackageParser.Package pkg) { 15781 if (status != PackageManager.INSTALL_SUCCEEDED) { 15782 cleanUp(); 15783 return false; 15784 } 15785 15786 final File targetDir = codeFile.getParentFile(); 15787 final File beforeCodeFile = codeFile; 15788 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15789 15790 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15791 try { 15792 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15793 } catch (ErrnoException e) { 15794 Slog.w(TAG, "Failed to rename", e); 15795 return false; 15796 } 15797 15798 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15799 Slog.w(TAG, "Failed to restorecon"); 15800 return false; 15801 } 15802 15803 // Reflect the rename internally 15804 codeFile = afterCodeFile; 15805 resourceFile = afterCodeFile; 15806 15807 // Reflect the rename in scanned details 15808 try { 15809 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15810 } catch (IOException e) { 15811 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15812 return false; 15813 } 15814 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15815 afterCodeFile, pkg.baseCodePath)); 15816 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15817 afterCodeFile, pkg.splitCodePaths)); 15818 15819 // Reflect the rename in app info 15820 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15821 pkg.setApplicationInfoCodePath(pkg.codePath); 15822 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15823 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15824 pkg.setApplicationInfoResourcePath(pkg.codePath); 15825 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15826 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15827 15828 return true; 15829 } 15830 15831 int doPostInstall(int status, int uid) { 15832 if (status != PackageManager.INSTALL_SUCCEEDED) { 15833 cleanUp(); 15834 } 15835 return status; 15836 } 15837 15838 @Override 15839 String getCodePath() { 15840 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15841 } 15842 15843 @Override 15844 String getResourcePath() { 15845 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15846 } 15847 15848 private boolean cleanUp() { 15849 if (codeFile == null || !codeFile.exists()) { 15850 return false; 15851 } 15852 15853 removeCodePathLI(codeFile); 15854 15855 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15856 resourceFile.delete(); 15857 } 15858 15859 return true; 15860 } 15861 15862 void cleanUpResourcesLI() { 15863 // Try enumerating all code paths before deleting 15864 List<String> allCodePaths = Collections.EMPTY_LIST; 15865 if (codeFile != null && codeFile.exists()) { 15866 try { 15867 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15868 allCodePaths = pkg.getAllCodePaths(); 15869 } catch (PackageParserException e) { 15870 // Ignored; we tried our best 15871 } 15872 } 15873 15874 cleanUp(); 15875 removeDexFiles(allCodePaths, instructionSets); 15876 } 15877 15878 boolean doPostDeleteLI(boolean delete) { 15879 // XXX err, shouldn't we respect the delete flag? 15880 cleanUpResourcesLI(); 15881 return true; 15882 } 15883 } 15884 15885 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 15886 PackageManagerException { 15887 if (copyRet < 0) { 15888 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 15889 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 15890 throw new PackageManagerException(copyRet, message); 15891 } 15892 } 15893 } 15894 15895 /** 15896 * Logic to handle movement of existing installed applications. 15897 */ 15898 class MoveInstallArgs extends InstallArgs { 15899 private File codeFile; 15900 private File resourceFile; 15901 15902 /** New install */ 15903 MoveInstallArgs(InstallParams params) { 15904 super(params.origin, params.move, params.observer, params.installFlags, 15905 params.installerPackageName, params.volumeUuid, 15906 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15907 params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions, 15908 params.traceMethod, params.traceCookie, params.signingDetails, 15909 params.installReason, params.mParentInstallParams); 15910 } 15911 15912 int copyApk() { 15913 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15914 + move.fromUuid + " to " + move.toUuid); 15915 synchronized (mInstaller) { 15916 try { 15917 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15918 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15919 } catch (InstallerException e) { 15920 Slog.w(TAG, "Failed to move app", e); 15921 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15922 } 15923 } 15924 15925 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15926 resourceFile = codeFile; 15927 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15928 15929 return PackageManager.INSTALL_SUCCEEDED; 15930 } 15931 15932 int doPreInstall(int status) { 15933 if (status != PackageManager.INSTALL_SUCCEEDED) { 15934 cleanUp(move.toUuid); 15935 } 15936 return status; 15937 } 15938 15939 boolean doRename(int status, PackageParser.Package pkg) { 15940 if (status != PackageManager.INSTALL_SUCCEEDED) { 15941 cleanUp(move.toUuid); 15942 return false; 15943 } 15944 15945 // Reflect the move in app info 15946 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15947 pkg.setApplicationInfoCodePath(pkg.codePath); 15948 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15949 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15950 pkg.setApplicationInfoResourcePath(pkg.codePath); 15951 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15952 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15953 15954 return true; 15955 } 15956 15957 int doPostInstall(int status, int uid) { 15958 if (status == PackageManager.INSTALL_SUCCEEDED) { 15959 cleanUp(move.fromUuid); 15960 } else { 15961 cleanUp(move.toUuid); 15962 } 15963 return status; 15964 } 15965 15966 @Override 15967 String getCodePath() { 15968 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15969 } 15970 15971 @Override 15972 String getResourcePath() { 15973 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15974 } 15975 15976 private boolean cleanUp(String volumeUuid) { 15977 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15978 move.dataAppName); 15979 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15980 final int[] userIds = sUserManager.getUserIds(); 15981 synchronized (mInstallLock) { 15982 // Clean up both app data and code 15983 // All package moves are frozen until finished 15984 15985 // We purposefully exclude FLAG_STORAGE_EXTERNAL here, since 15986 // this task was only focused on moving data on internal storage. 15987 for (int userId : userIds) { 15988 try { 15989 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15990 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15991 } catch (InstallerException e) { 15992 Slog.w(TAG, String.valueOf(e)); 15993 } 15994 } 15995 removeCodePathLI(codeFile); 15996 } 15997 return true; 15998 } 15999 16000 void cleanUpResourcesLI() { 16001 throw new UnsupportedOperationException(); 16002 } 16003 16004 boolean doPostDeleteLI(boolean delete) { 16005 throw new UnsupportedOperationException(); 16006 } 16007 } 16008 16009 private File getNextCodePath(File targetDir, String packageName) { 16010 File result; 16011 SecureRandom random = new SecureRandom(); 16012 byte[] bytes = new byte[16]; 16013 do { 16014 random.nextBytes(bytes); 16015 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 16016 result = new File(targetDir, packageName + "-" + suffix); 16017 } while (result.exists()); 16018 return result; 16019 } 16020 16021 // Utility method that returns the relative package path with respect 16022 // to the installation directory. Like say for /data/data/com.test-1.apk 16023 // string com.test-1 is returned. 16024 static String deriveCodePathName(String codePath) { 16025 if (codePath == null) { 16026 return null; 16027 } 16028 final File codeFile = new File(codePath); 16029 final String name = codeFile.getName(); 16030 if (codeFile.isDirectory()) { 16031 return name; 16032 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 16033 final int lastDot = name.lastIndexOf('.'); 16034 return name.substring(0, lastDot); 16035 } else { 16036 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 16037 return null; 16038 } 16039 } 16040 16041 static class PackageInstalledInfo { 16042 String name; 16043 int uid; 16044 // The set of users that originally had this package installed. 16045 int[] origUsers; 16046 // The set of users that now have this package installed. 16047 int[] newUsers; 16048 PackageParser.Package pkg; 16049 int returnCode; 16050 String returnMsg; 16051 String installerPackageName; 16052 PackageRemovedInfo removedInfo; 16053 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 16054 16055 public void setError(int code, String msg) { 16056 setReturnCode(code); 16057 setReturnMessage(msg); 16058 Slog.w(TAG, msg); 16059 } 16060 16061 public void setError(String msg, PackageParserException e) { 16062 setReturnCode(e.error); 16063 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16064 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16065 for (int i = 0; i < childCount; i++) { 16066 addedChildPackages.valueAt(i).setError(msg, e); 16067 } 16068 Slog.w(TAG, msg, e); 16069 } 16070 16071 public void setError(String msg, PackageManagerException e) { 16072 returnCode = e.error; 16073 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 16074 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16075 for (int i = 0; i < childCount; i++) { 16076 addedChildPackages.valueAt(i).setError(msg, e); 16077 } 16078 Slog.w(TAG, msg, e); 16079 } 16080 16081 public void setReturnCode(int returnCode) { 16082 this.returnCode = returnCode; 16083 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16084 for (int i = 0; i < childCount; i++) { 16085 addedChildPackages.valueAt(i).returnCode = returnCode; 16086 } 16087 } 16088 16089 private void setReturnMessage(String returnMsg) { 16090 this.returnMsg = returnMsg; 16091 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 16092 for (int i = 0; i < childCount; i++) { 16093 addedChildPackages.valueAt(i).returnMsg = returnMsg; 16094 } 16095 } 16096 16097 // In some error cases we want to convey more info back to the observer 16098 String origPackage; 16099 String origPermission; 16100 } 16101 16102 private static void updateDigest(MessageDigest digest, File file) throws IOException { 16103 try (DigestInputStream digestStream = 16104 new DigestInputStream(new FileInputStream(file), digest)) { 16105 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 16106 } 16107 } 16108 16109 /** 16110 * Checks whether the parent or any of the child packages have a change shared 16111 * user. For a package to be a valid update the shred users of the parent and 16112 * the children should match. We may later support changing child shared users. 16113 * @param oldPkg The updated package. 16114 * @param newPkg The update package. 16115 * @return The shared user that change between the versions. 16116 */ 16117 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 16118 PackageParser.Package newPkg) { 16119 // Check parent shared user 16120 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 16121 return newPkg.packageName; 16122 } 16123 // Check child shared users 16124 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16125 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 16126 for (int i = 0; i < newChildCount; i++) { 16127 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 16128 // If this child was present, did it have the same shared user? 16129 for (int j = 0; j < oldChildCount; j++) { 16130 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 16131 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 16132 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 16133 return newChildPkg.packageName; 16134 } 16135 } 16136 } 16137 return null; 16138 } 16139 16140 private void removeNativeBinariesLI(PackageSetting ps) { 16141 // Remove the lib path for the parent package 16142 if (ps != null) { 16143 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 16144 // Remove the lib path for the child packages 16145 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16146 for (int i = 0; i < childCount; i++) { 16147 PackageSetting childPs = null; 16148 synchronized (mPackages) { 16149 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 16150 } 16151 if (childPs != null) { 16152 NativeLibraryHelper.removeNativeBinariesLI(childPs 16153 .legacyNativeLibraryPathString); 16154 } 16155 } 16156 } 16157 } 16158 16159 @GuardedBy("mPackages") 16160 private void enableSystemPackageLPw(PackageParser.Package pkg) { 16161 // Enable the parent package 16162 mSettings.enableSystemPackageLPw(pkg.packageName); 16163 // Enable the child packages 16164 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16165 for (int i = 0; i < childCount; i++) { 16166 PackageParser.Package childPkg = pkg.childPackages.get(i); 16167 mSettings.enableSystemPackageLPw(childPkg.packageName); 16168 } 16169 } 16170 16171 @GuardedBy("mPackages") 16172 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 16173 PackageParser.Package newPkg) { 16174 // Disable the parent package (parent always replaced) 16175 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 16176 // Disable the child packages 16177 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 16178 for (int i = 0; i < childCount; i++) { 16179 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 16180 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 16181 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 16182 } 16183 return disabled; 16184 } 16185 16186 @GuardedBy("mPackages") 16187 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 16188 String installerPackageName) { 16189 // Enable the parent package 16190 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 16191 // Enable the child packages 16192 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16193 for (int i = 0; i < childCount; i++) { 16194 PackageParser.Package childPkg = pkg.childPackages.get(i); 16195 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 16196 } 16197 } 16198 16199 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 16200 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 16201 // Update the parent package setting 16202 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 16203 res, user, installReason); 16204 // Update the child packages setting 16205 final int childCount = (newPackage.childPackages != null) 16206 ? newPackage.childPackages.size() : 0; 16207 for (int i = 0; i < childCount; i++) { 16208 PackageParser.Package childPackage = newPackage.childPackages.get(i); 16209 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 16210 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 16211 childRes.origUsers, childRes, user, installReason); 16212 } 16213 } 16214 16215 private void updateSettingsInternalLI(PackageParser.Package pkg, 16216 String installerPackageName, int[] allUsers, int[] installedForUsers, 16217 PackageInstalledInfo res, UserHandle user, int installReason) { 16218 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 16219 16220 final String pkgName = pkg.packageName; 16221 16222 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 16223 synchronized (mPackages) { 16224 // NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 16225 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 16226 mPermissionCallback); 16227 // For system-bundled packages, we assume that installing an upgraded version 16228 // of the package implies that the user actually wants to run that new code, 16229 // so we enable the package. 16230 PackageSetting ps = mSettings.mPackages.get(pkgName); 16231 final int userId = user.getIdentifier(); 16232 if (ps != null) { 16233 if (isSystemApp(pkg)) { 16234 if (DEBUG_INSTALL) { 16235 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 16236 } 16237 // Enable system package for requested users 16238 if (res.origUsers != null) { 16239 for (int origUserId : res.origUsers) { 16240 if (userId == UserHandle.USER_ALL || userId == origUserId) { 16241 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 16242 origUserId, installerPackageName); 16243 } 16244 } 16245 } 16246 // Also convey the prior install/uninstall state 16247 if (allUsers != null && installedForUsers != null) { 16248 for (int currentUserId : allUsers) { 16249 final boolean installed = ArrayUtils.contains( 16250 installedForUsers, currentUserId); 16251 if (DEBUG_INSTALL) { 16252 Slog.d(TAG, " user " + currentUserId + " => " + installed); 16253 } 16254 ps.setInstalled(installed, currentUserId); 16255 } 16256 // these install state changes will be persisted in the 16257 // upcoming call to mSettings.writeLPr(). 16258 } 16259 } 16260 // It's implied that when a user requests installation, they want the app to be 16261 // installed and enabled. 16262 if (userId != UserHandle.USER_ALL) { 16263 ps.setInstalled(true, userId); 16264 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 16265 } 16266 16267 // When replacing an existing package, preserve the original install reason for all 16268 // users that had the package installed before. 16269 final Set<Integer> previousUserIds = new ArraySet<>(); 16270 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 16271 final int installReasonCount = res.removedInfo.installReasons.size(); 16272 for (int i = 0; i < installReasonCount; i++) { 16273 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 16274 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 16275 ps.setInstallReason(previousInstallReason, previousUserId); 16276 previousUserIds.add(previousUserId); 16277 } 16278 } 16279 16280 // Set install reason for users that are having the package newly installed. 16281 if (userId == UserHandle.USER_ALL) { 16282 for (int currentUserId : sUserManager.getUserIds()) { 16283 if (!previousUserIds.contains(currentUserId)) { 16284 ps.setInstallReason(installReason, currentUserId); 16285 } 16286 } 16287 } else if (!previousUserIds.contains(userId)) { 16288 ps.setInstallReason(installReason, userId); 16289 } 16290 mSettings.writeKernelMappingLPr(ps); 16291 } 16292 res.name = pkgName; 16293 res.uid = pkg.applicationInfo.uid; 16294 res.pkg = pkg; 16295 mSettings.setInstallerPackageName(pkgName, installerPackageName); 16296 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16297 //to update install status 16298 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 16299 mSettings.writeLPr(); 16300 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16301 } 16302 16303 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16304 } 16305 16306 private static class InstallRequest { 16307 public final InstallArgs args; 16308 public final PackageInstalledInfo installResult; 16309 16310 private InstallRequest(InstallArgs args, PackageInstalledInfo res) { 16311 this.args = args; 16312 this.installResult = res; 16313 } 16314 } 16315 16316 @GuardedBy({"mInstallLock", "mPackages"}) 16317 private void installPackagesTracedLI(List<InstallRequest> requests) { 16318 try { 16319 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackages"); 16320 installPackagesLI(requests); 16321 } finally { 16322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16323 } 16324 } 16325 16326 /** 16327 * Package state to commit to memory and disk after reconciliation has completed. 16328 */ 16329 private static class CommitRequest { 16330 final Map<String, ReconciledPackage> reconciledPackages; 16331 final int[] mAllUsers; 16332 16333 private CommitRequest(Map<String, ReconciledPackage> reconciledPackages, int[] allUsers) { 16334 this.reconciledPackages = reconciledPackages; 16335 this.mAllUsers = allUsers; 16336 } 16337 } 16338 16339 /** 16340 * Package scan results and related request details used to reconcile the potential addition of 16341 * one or more packages to the system. 16342 * 16343 * Reconcile will take a set of package details that need to be committed to the system and make 16344 * sure that they are valid in the context of the system and the other installing apps. Any 16345 * invalid state or app will result in a failed reconciliation and thus whatever operation (such 16346 * as install) led to the request. 16347 */ 16348 private static class ReconcileRequest { 16349 public final Map<String, ScanResult> scannedPackages; 16350 16351 public final Map<String, PackageParser.Package> allPackages; 16352 public final Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource; 16353 public final Map<String, InstallArgs> installArgs; 16354 public final Map<String, PackageInstalledInfo> installResults; 16355 public final Map<String, PrepareResult> preparedPackages; 16356 public final Map<String, VersionInfo> versionInfos; 16357 public final Map<String, PackageSetting> lastStaticSharedLibSettings; 16358 16359 private ReconcileRequest(Map<String, ScanResult> scannedPackages, 16360 Map<String, InstallArgs> installArgs, 16361 Map<String, PackageInstalledInfo> installResults, 16362 Map<String, PrepareResult> preparedPackages, 16363 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource, 16364 Map<String, PackageParser.Package> allPackages, 16365 Map<String, VersionInfo> versionInfos, 16366 Map<String, PackageSetting> lastStaticSharedLibSettings) { 16367 this.scannedPackages = scannedPackages; 16368 this.installArgs = installArgs; 16369 this.installResults = installResults; 16370 this.preparedPackages = preparedPackages; 16371 this.sharedLibrarySource = sharedLibrarySource; 16372 this.allPackages = allPackages; 16373 this.versionInfos = versionInfos; 16374 this.lastStaticSharedLibSettings = lastStaticSharedLibSettings; 16375 } 16376 16377 private ReconcileRequest(Map<String, ScanResult> scannedPackages, 16378 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource, 16379 Map<String, PackageParser.Package> allPackages, 16380 Map<String, VersionInfo> versionInfos, 16381 Map<String, PackageSetting> lastStaticSharedLibSettings) { 16382 this(scannedPackages, Collections.emptyMap(), Collections.emptyMap(), 16383 Collections.emptyMap(), sharedLibrarySource, allPackages, versionInfos, 16384 lastStaticSharedLibSettings); 16385 } 16386 } 16387 private static class ReconcileFailure extends PackageManagerException { 16388 ReconcileFailure(String message) { 16389 super("Reconcile failed: " + message); 16390 } 16391 ReconcileFailure(int reason, String message) { 16392 super(reason, "Reconcile failed: " + message); 16393 } 16394 ReconcileFailure(PackageManagerException e) { 16395 this(e.error, e.getMessage()); 16396 } 16397 } 16398 16399 /** 16400 * A container of all data needed to commit a package to in-memory data structures and to disk. 16401 * TODO: move most of the data contained her into a PackageSetting for commit. 16402 */ 16403 private static class ReconciledPackage { 16404 public final ReconcileRequest request; 16405 public final PackageSetting pkgSetting; 16406 public final ScanResult scanResult; 16407 // TODO: Remove install-specific details from the reconcile result 16408 public final PackageInstalledInfo installResult; 16409 @Nullable public final PrepareResult prepareResult; 16410 @Nullable public final InstallArgs installArgs; 16411 public final DeletePackageAction deletePackageAction; 16412 public final List<SharedLibraryInfo> allowedSharedLibraryInfos; 16413 public final SigningDetails signingDetails; 16414 public final boolean sharedUserSignaturesChanged; 16415 public ArrayList<SharedLibraryInfo> collectedSharedLibraryInfos; 16416 public final boolean removeAppKeySetData; 16417 16418 private ReconciledPackage(ReconcileRequest request, 16419 InstallArgs installArgs, 16420 PackageSetting pkgSetting, 16421 PackageInstalledInfo installResult, 16422 PrepareResult prepareResult, 16423 ScanResult scanResult, 16424 DeletePackageAction deletePackageAction, 16425 List<SharedLibraryInfo> allowedSharedLibraryInfos, 16426 SigningDetails signingDetails, 16427 boolean sharedUserSignaturesChanged, 16428 boolean removeAppKeySetData) { 16429 this.request = request; 16430 this.installArgs = installArgs; 16431 this.pkgSetting = pkgSetting; 16432 this.installResult = installResult; 16433 this.prepareResult = prepareResult; 16434 this.scanResult = scanResult; 16435 this.deletePackageAction = deletePackageAction; 16436 this.allowedSharedLibraryInfos = allowedSharedLibraryInfos; 16437 this.signingDetails = signingDetails; 16438 this.sharedUserSignaturesChanged = sharedUserSignaturesChanged; 16439 this.removeAppKeySetData = removeAppKeySetData; 16440 } 16441 16442 /** 16443 * Returns a combined set of packages containing the packages already installed combined 16444 * with the package(s) currently being installed. The to-be installed packages take 16445 * precedence and may shadow already installed packages. 16446 */ 16447 private Map<String, PackageParser.Package> getCombinedPackages() { 16448 final ArrayMap<String, PackageParser.Package> combinedPackages = 16449 new ArrayMap<>(request.allPackages.size() + request.scannedPackages.size()); 16450 16451 combinedPackages.putAll(request.allPackages); 16452 for (ScanResult scanResult : request.scannedPackages.values()) { 16453 combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg); 16454 } 16455 return combinedPackages; 16456 } 16457 } 16458 16459 @GuardedBy("mPackages") 16460 private static Map<String, ReconciledPackage> reconcilePackagesLocked( 16461 final ReconcileRequest request, KeySetManagerService ksms) 16462 throws ReconcileFailure { 16463 final Map<String, ScanResult> scannedPackages = request.scannedPackages; 16464 16465 final Map<String, ReconciledPackage> result = new ArrayMap<>(scannedPackages.size()); 16466 16467 // make a copy of the existing set of packages so we can combine them with incoming packages 16468 final ArrayMap<String, PackageParser.Package> combinedPackages = 16469 new ArrayMap<>(request.allPackages.size() + scannedPackages.size()); 16470 combinedPackages.putAll(request.allPackages); 16471 16472 final Map<String, LongSparseArray<SharedLibraryInfo>> incomingSharedLibraries = 16473 new ArrayMap<>(); 16474 16475 for (String installPackageName : scannedPackages.keySet()) { 16476 final ScanResult scanResult = scannedPackages.get(installPackageName); 16477 16478 // add / replace existing with incoming packages 16479 combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg); 16480 16481 // in the first pass, we'll build up the set of incoming shared libraries 16482 final List<SharedLibraryInfo> allowedSharedLibInfos = 16483 getAllowedSharedLibInfos(scanResult, request.sharedLibrarySource); 16484 final SharedLibraryInfo staticLib = scanResult.staticSharedLibraryInfo; 16485 if (allowedSharedLibInfos != null) { 16486 for (SharedLibraryInfo info : allowedSharedLibInfos) { 16487 if (!addSharedLibraryToPackageVersionMap(incomingSharedLibraries, info)) { 16488 throw new ReconcileFailure("Static Shared Library " + staticLib.getName() 16489 + " is being installed twice in this set!"); 16490 } 16491 } 16492 } 16493 16494 // the following may be null if we're just reconciling on boot (and not during install) 16495 final InstallArgs installArgs = request.installArgs.get(installPackageName); 16496 final PackageInstalledInfo res = request.installResults.get(installPackageName); 16497 final PrepareResult prepareResult = request.preparedPackages.get(installPackageName); 16498 final boolean isInstall = installArgs != null; 16499 if (isInstall && (res == null || prepareResult == null)) { 16500 throw new ReconcileFailure("Reconcile arguments are not balanced for " 16501 + installPackageName + "!"); 16502 } 16503 16504 final DeletePackageAction deletePackageAction; 16505 // we only want to try to delete for non system apps 16506 if (isInstall && prepareResult.replace && !prepareResult.system) { 16507 final boolean killApp = (scanResult.request.scanFlags & SCAN_DONT_KILL_APP) == 0; 16508 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16509 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16510 deletePackageAction = mayDeletePackageLocked(res.removedInfo, 16511 prepareResult.originalPs, prepareResult.disabledPs, 16512 prepareResult.childPackageSettings, deleteFlags, null /* all users */); 16513 if (deletePackageAction == null) { 16514 throw new ReconcileFailure( 16515 PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE, 16516 "May not delete " + installPackageName + " to replace"); 16517 } 16518 } else { 16519 deletePackageAction = null; 16520 } 16521 16522 final int scanFlags = scanResult.request.scanFlags; 16523 final int parseFlags = scanResult.request.parseFlags; 16524 final PackageParser.Package pkg = scanResult.request.pkg; 16525 16526 final PackageSetting disabledPkgSetting = scanResult.request.disabledPkgSetting; 16527 final PackageSetting lastStaticSharedLibSetting = 16528 request.lastStaticSharedLibSettings.get(installPackageName); 16529 final PackageSetting signatureCheckPs = 16530 (prepareResult != null && lastStaticSharedLibSetting != null) 16531 ? lastStaticSharedLibSetting 16532 : scanResult.pkgSetting; 16533 boolean removeAppKeySetData = false; 16534 boolean sharedUserSignaturesChanged = false; 16535 SigningDetails signingDetails = null; 16536 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16537 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16538 // We just determined the app is signed correctly, so bring 16539 // over the latest parsed certs. 16540 } else { 16541 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 16542 throw new ReconcileFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16543 "Package " + pkg.packageName + " upgrade keys do not match the " 16544 + "previously installed version"); 16545 } else { 16546 String msg = "System package " + pkg.packageName 16547 + " signature changed; retaining data."; 16548 reportSettingsProblem(Log.WARN, msg); 16549 } 16550 } 16551 signingDetails = pkg.mSigningDetails; 16552 } else { 16553 try { 16554 final VersionInfo versionInfo = request.versionInfos.get(installPackageName); 16555 final boolean compareCompat = isCompatSignatureUpdateNeeded(versionInfo); 16556 final boolean compareRecover = isRecoverSignatureUpdateNeeded(versionInfo); 16557 final boolean compatMatch = verifySignatures(signatureCheckPs, 16558 disabledPkgSetting, pkg.mSigningDetails, compareCompat, compareRecover); 16559 // The new KeySets will be re-added later in the scanning process. 16560 if (compatMatch) { 16561 removeAppKeySetData = true; 16562 } 16563 // We just determined the app is signed correctly, so bring 16564 // over the latest parsed certs. 16565 signingDetails = pkg.mSigningDetails; 16566 16567 16568 // if this is is a sharedUser, check to see if the new package is signed by a 16569 // newer 16570 // signing certificate than the existing one, and if so, copy over the new 16571 // details 16572 if (signatureCheckPs.sharedUser != null) { 16573 if (pkg.mSigningDetails.hasAncestor( 16574 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 16575 signatureCheckPs.sharedUser.signatures.mSigningDetails = 16576 pkg.mSigningDetails; 16577 } 16578 if (signatureCheckPs.sharedUser.signaturesChanged == null) { 16579 signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE; 16580 } 16581 } 16582 } catch (PackageManagerException e) { 16583 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 16584 throw new ReconcileFailure(e); 16585 } 16586 signingDetails = pkg.mSigningDetails; 16587 16588 // If the system app is part of a shared user we allow that shared user to 16589 // change 16590 // signatures as well as part of an OTA. We still need to verify that the 16591 // signatures 16592 // are consistent within the shared user for a given boot, so only allow 16593 // updating 16594 // the signatures on the first package scanned for the shared user (i.e. if the 16595 // signaturesChanged state hasn't been initialized yet in SharedUserSetting). 16596 if (signatureCheckPs.sharedUser != null) { 16597 final Signature[] sharedUserSignatures = 16598 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures; 16599 if (signatureCheckPs.sharedUser.signaturesChanged != null 16600 && compareSignatures(sharedUserSignatures, 16601 pkg.mSigningDetails.signatures) 16602 != PackageManager.SIGNATURE_MATCH) { 16603 if (SystemProperties.getInt("ro.product.first_api_level", 0) <= 29) { 16604 // Mismatched signatures is an error and silently skipping system 16605 // packages will likely break the device in unforeseen ways. 16606 // However, we allow the device to boot anyway because, prior to Q, 16607 // vendors were not expecting the platform to crash in this 16608 // situation. 16609 // This WILL be a hard failure on any new API levels after Q. 16610 throw new ReconcileFailure( 16611 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 16612 "Signature mismatch for shared user: " 16613 + scanResult.pkgSetting.sharedUser); 16614 } else { 16615 // Treat mismatched signatures on system packages using a shared 16616 // UID as 16617 // fatal for the system overall, rather than just failing to install 16618 // whichever package happened to be scanned later. 16619 throw new IllegalStateException( 16620 "Signature mismatch on system package " 16621 + pkg.packageName + " for shared user " 16622 + scanResult.pkgSetting.sharedUser); 16623 } 16624 } 16625 16626 sharedUserSignaturesChanged = true; 16627 signatureCheckPs.sharedUser.signatures.mSigningDetails = 16628 pkg.mSigningDetails; 16629 signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE; 16630 } 16631 // File a report about this. 16632 String msg = "System package " + pkg.packageName 16633 + " signature changed; retaining data."; 16634 reportSettingsProblem(Log.WARN, msg); 16635 } catch (IllegalArgumentException e) { 16636 // should never happen: certs matched when checking, but not when comparing 16637 // old to new for sharedUser 16638 throw new RuntimeException( 16639 "Signing certificates comparison made on incomparable signing details" 16640 + " but somehow passed verifySignatures!", e); 16641 } 16642 } 16643 16644 result.put(installPackageName, 16645 new ReconciledPackage(request, installArgs, scanResult.pkgSetting, 16646 res, request.preparedPackages.get(installPackageName), scanResult, 16647 deletePackageAction, allowedSharedLibInfos, signingDetails, 16648 sharedUserSignaturesChanged, removeAppKeySetData)); 16649 } 16650 16651 for (String installPackageName : scannedPackages.keySet()) { 16652 // Check all shared libraries and map to their actual file path. 16653 // We only do this here for apps not on a system dir, because those 16654 // are the only ones that can fail an install due to this. We 16655 // will take care of the system apps by updating all of their 16656 // library paths after the scan is done. Also during the initial 16657 // scan don't update any libs as we do this wholesale after all 16658 // apps are scanned to avoid dependency based scanning. 16659 final ScanResult scanResult = scannedPackages.get(installPackageName); 16660 if ((scanResult.request.scanFlags & SCAN_BOOTING) != 0 16661 || (scanResult.request.parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 16662 continue; 16663 } 16664 try { 16665 result.get(installPackageName).collectedSharedLibraryInfos = 16666 collectSharedLibraryInfos(scanResult.request.pkg, combinedPackages, 16667 request.sharedLibrarySource, incomingSharedLibraries); 16668 16669 } catch (PackageManagerException e) { 16670 throw new ReconcileFailure(e.error, e.getMessage()); 16671 } 16672 } 16673 16674 return result; 16675 } 16676 16677 /** 16678 * Compare the newly scanned package with current system state to see which of its declared 16679 * shared libraries should be allowed to be added to the system. 16680 */ 16681 private static List<SharedLibraryInfo> getAllowedSharedLibInfos( 16682 ScanResult scanResult, 16683 Map<String, LongSparseArray<SharedLibraryInfo>> existingSharedLibraries) { 16684 // Let's used the parsed package as scanResult.pkgSetting may be null 16685 final PackageParser.Package pkg = scanResult.request.pkg; 16686 if (scanResult.staticSharedLibraryInfo == null 16687 && scanResult.dynamicSharedLibraryInfos == null) { 16688 return null; 16689 } 16690 16691 // Any app can add new static shared libraries 16692 if (scanResult.staticSharedLibraryInfo != null) { 16693 return Collections.singletonList(scanResult.staticSharedLibraryInfo); 16694 } 16695 final boolean hasDynamicLibraries = 16696 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 16697 && scanResult.dynamicSharedLibraryInfos != null; 16698 if (!hasDynamicLibraries) { 16699 return null; 16700 } 16701 final boolean isUpdatedSystemApp = pkg.isUpdatedSystemApp(); 16702 // We may not yet have disabled the updated package yet, so be sure to grab the 16703 // current setting if that's the case. 16704 final PackageSetting updatedSystemPs = isUpdatedSystemApp 16705 ? scanResult.request.disabledPkgSetting == null 16706 ? scanResult.request.oldPkgSetting 16707 : scanResult.request.disabledPkgSetting 16708 : null; 16709 if (isUpdatedSystemApp && (updatedSystemPs.pkg == null 16710 || updatedSystemPs.pkg.libraryNames == null)) { 16711 Slog.w(TAG, "Package " + pkg.packageName + " declares libraries that are not " 16712 + "declared on the system image; skipping"); 16713 return null; 16714 } 16715 final ArrayList<SharedLibraryInfo> infos = 16716 new ArrayList<>(scanResult.dynamicSharedLibraryInfos.size()); 16717 for (SharedLibraryInfo info : scanResult.dynamicSharedLibraryInfos) { 16718 final String name = info.getName(); 16719 if (isUpdatedSystemApp) { 16720 // New library entries can only be added through the 16721 // system image. This is important to get rid of a lot 16722 // of nasty edge cases: for example if we allowed a non- 16723 // system update of the app to add a library, then uninstalling 16724 // the update would make the library go away, and assumptions 16725 // we made such as through app install filtering would now 16726 // have allowed apps on the device which aren't compatible 16727 // with it. Better to just have the restriction here, be 16728 // conservative, and create many fewer cases that can negatively 16729 // impact the user experience. 16730 if (!updatedSystemPs.pkg.libraryNames.contains(name)) { 16731 Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name 16732 + " that is not declared on system image; skipping"); 16733 continue; 16734 } 16735 } 16736 if (sharedLibExists( 16737 name, SharedLibraryInfo.VERSION_UNDEFINED, existingSharedLibraries)) { 16738 Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name 16739 + " that already exists; skipping"); 16740 continue; 16741 } 16742 infos.add(info); 16743 } 16744 return infos; 16745 } 16746 16747 /** 16748 * Returns false if the adding shared library already exists in the map and so could not be 16749 * added. 16750 */ 16751 private static boolean addSharedLibraryToPackageVersionMap( 16752 Map<String, LongSparseArray<SharedLibraryInfo>> target, 16753 SharedLibraryInfo library) { 16754 final String name = library.getName(); 16755 if (target.containsKey(name)) { 16756 if (library.getType() != SharedLibraryInfo.TYPE_STATIC) { 16757 // We've already added this non-version-specific library to the map. 16758 return false; 16759 } else if (target.get(name).indexOfKey(library.getLongVersion()) >= 0) { 16760 // We've already added this version of a version-specific library to the map. 16761 return false; 16762 } 16763 } else { 16764 target.put(name, new LongSparseArray<>()); 16765 } 16766 target.get(name).put(library.getLongVersion(), library); 16767 return true; 16768 } 16769 16770 @GuardedBy("mPackages") 16771 private void commitPackagesLocked(final CommitRequest request) { 16772 // TODO: remove any expected failures from this method; this should only be able to fail due 16773 // to unavoidable errors (I/O, etc.) 16774 for (ReconciledPackage reconciledPkg : request.reconciledPackages.values()) { 16775 final ScanResult scanResult = reconciledPkg.scanResult; 16776 final ScanRequest scanRequest = scanResult.request; 16777 final PackageParser.Package pkg = scanRequest.pkg; 16778 final String packageName = pkg.packageName; 16779 final PackageInstalledInfo res = reconciledPkg.installResult; 16780 16781 if (reconciledPkg.prepareResult.replace) { 16782 PackageParser.Package oldPackage = mPackages.get(packageName); 16783 16784 // Set the update and install times 16785 PackageSetting deletedPkgSetting = (PackageSetting) oldPackage.mExtras; 16786 setInstallAndUpdateTime(pkg, deletedPkgSetting.firstInstallTime, 16787 System.currentTimeMillis()); 16788 16789 if (reconciledPkg.prepareResult.system) { 16790 // Remove existing system package 16791 removePackageLI(oldPackage, true); 16792 if (!disableSystemPackageLPw(oldPackage, pkg)) { 16793 // We didn't need to disable the .apk as a current system package, 16794 // which means we are replacing another update that is already 16795 // installed. We need to make sure to delete the older one's .apk. 16796 res.removedInfo.args = createInstallArgsForExisting( 16797 oldPackage.applicationInfo.getCodePath(), 16798 oldPackage.applicationInfo.getResourcePath(), 16799 getAppDexInstructionSets(oldPackage.applicationInfo)); 16800 } else { 16801 res.removedInfo.args = null; 16802 } 16803 16804 // Update the package dynamic state if succeeded 16805 // Now that the install succeeded make sure we remove data 16806 // directories for any child package the update removed. 16807 final int deletedChildCount = (oldPackage.childPackages != null) 16808 ? oldPackage.childPackages.size() : 0; 16809 final int newChildCount = (pkg.childPackages != null) 16810 ? pkg.childPackages.size() : 0; 16811 for (int i = 0; i < deletedChildCount; i++) { 16812 PackageParser.Package deletedChildPkg = oldPackage.childPackages.get(i); 16813 boolean childPackageDeleted = true; 16814 for (int j = 0; j < newChildCount; j++) { 16815 PackageParser.Package newChildPkg = pkg.childPackages.get(j); 16816 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16817 childPackageDeleted = false; 16818 break; 16819 } 16820 } 16821 if (childPackageDeleted) { 16822 PackageSetting ps1 = mSettings.getDisabledSystemPkgLPr( 16823 deletedChildPkg.packageName); 16824 if (ps1 != null && res.removedInfo.removedChildPackages != null) { 16825 PackageRemovedInfo removedChildRes = res.removedInfo 16826 .removedChildPackages.get(deletedChildPkg.packageName); 16827 removePackageDataLIF(ps1, request.mAllUsers, removedChildRes, 0, 16828 false); 16829 removedChildRes.removedForAllUsers = mPackages.get(ps1.name) 16830 == null; 16831 } 16832 } 16833 } 16834 } else { 16835 try { 16836 executeDeletePackageLIF(reconciledPkg.deletePackageAction, packageName, 16837 true, request.mAllUsers, true, pkg); 16838 } catch (SystemDeleteException e) { 16839 if (Build.IS_ENG) { 16840 throw new RuntimeException("Unexpected failure", e); 16841 // ignore; not possible for non-system app 16842 } 16843 } 16844 // Successfully deleted the old package; proceed with replace. 16845 16846 // If deleted package lived in a container, give users a chance to 16847 // relinquish resources before killing. 16848 if (oldPackage.isForwardLocked() || isExternal(oldPackage)) { 16849 if (DEBUG_INSTALL) { 16850 Slog.i(TAG, "upgrading pkg " + oldPackage 16851 + " is ASEC-hosted -> UNAVAILABLE"); 16852 } 16853 final int[] uidArray = new int[]{oldPackage.applicationInfo.uid}; 16854 final ArrayList<String> pkgList = new ArrayList<>(1); 16855 pkgList.add(oldPackage.applicationInfo.packageName); 16856 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16857 } 16858 16859 // Update the in-memory copy of the previous code paths. 16860 PackageSetting ps1 = mSettings.mPackages.get( 16861 reconciledPkg.prepareResult.existingPackage.packageName); 16862 if ((reconciledPkg.installArgs.installFlags & PackageManager.DONT_KILL_APP) 16863 == 0) { 16864 if (ps1.mOldCodePaths == null) { 16865 ps1.mOldCodePaths = new ArraySet<>(); 16866 } 16867 Collections.addAll(ps1.mOldCodePaths, oldPackage.baseCodePath); 16868 if (oldPackage.splitCodePaths != null) { 16869 Collections.addAll(ps1.mOldCodePaths, oldPackage.splitCodePaths); 16870 } 16871 } else { 16872 ps1.mOldCodePaths = null; 16873 } 16874 if (ps1.childPackageNames != null) { 16875 for (int i = ps1.childPackageNames.size() - 1; i >= 0; --i) { 16876 final String childPkgName = ps1.childPackageNames.get(i); 16877 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16878 childPs.mOldCodePaths = ps1.mOldCodePaths; 16879 } 16880 } 16881 16882 if (reconciledPkg.installResult.returnCode 16883 == PackageManager.INSTALL_SUCCEEDED) { 16884 PackageSetting ps2 = mSettings.getPackageLPr(pkg.packageName); 16885 if (ps2 != null) { 16886 res.removedInfo.removedForAllUsers = mPackages.get(ps2.name) == null; 16887 if (res.removedInfo.removedChildPackages != null) { 16888 final int childCount1 = res.removedInfo.removedChildPackages.size(); 16889 // Iterate in reverse as we may modify the collection 16890 for (int i = childCount1 - 1; i >= 0; i--) { 16891 String childPackageName = 16892 res.removedInfo.removedChildPackages.keyAt(i); 16893 if (res.addedChildPackages.containsKey(childPackageName)) { 16894 res.removedInfo.removedChildPackages.removeAt(i); 16895 } else { 16896 PackageRemovedInfo childInfo = res.removedInfo 16897 .removedChildPackages.valueAt(i); 16898 childInfo.removedForAllUsers = mPackages.get( 16899 childInfo.removedPackage) == null; 16900 } 16901 } 16902 } 16903 } 16904 } 16905 } 16906 } 16907 16908 commitReconciledScanResultLocked(reconciledPkg); 16909 updateSettingsLI(pkg, reconciledPkg.installArgs.installerPackageName, request.mAllUsers, 16910 res, reconciledPkg.installArgs.user, reconciledPkg.installArgs.installReason); 16911 16912 final PackageSetting ps = mSettings.mPackages.get(packageName); 16913 if (ps != null) { 16914 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16915 ps.setUpdateAvailable(false /*updateAvailable*/); 16916 } 16917 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16918 for (int i = 0; i < childCount; i++) { 16919 PackageParser.Package childPkg = pkg.childPackages.get(i); 16920 PackageInstalledInfo childRes = res.addedChildPackages.get( 16921 childPkg.packageName); 16922 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16923 if (childPs != null) { 16924 childRes.newUsers = childPs.queryInstalledUsers( 16925 sUserManager.getUserIds(), true); 16926 } 16927 } 16928 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16929 updateSequenceNumberLP(ps, res.newUsers); 16930 updateInstantAppInstallerLocked(packageName); 16931 } 16932 } 16933 } 16934 16935 /** 16936 * Installs one or more packages atomically. This operation is broken up into four phases: 16937 * <ul> 16938 * <li><b>Prepare</b> 16939 * <br/>Analyzes any current install state, parses the package and does initial 16940 * validation on it.</li> 16941 * <li><b>Scan</b> 16942 * <br/>Interrogates the parsed packages given the context collected in prepare.</li> 16943 * <li><b>Reconcile</b> 16944 * <br/>Validates scanned packages in the context of each other and the current system 16945 * state to ensure that the install will be successful. 16946 * <li><b>Commit</b> 16947 * <br/>Commits all scanned packages and updates system state. This is the only place 16948 * that system state may be modified in the install flow and all predictable errors 16949 * must be determined before this phase.</li> 16950 * </ul> 16951 * 16952 * Failure at any phase will result in a full failure to install all packages. 16953 */ 16954 @GuardedBy("mInstallLock") 16955 private void installPackagesLI(List<InstallRequest> requests) { 16956 final Map<String, ScanResult> preparedScans = new ArrayMap<>(requests.size()); 16957 final Map<String, InstallArgs> installArgs = new ArrayMap<>(requests.size()); 16958 final Map<String, PackageInstalledInfo> installResults = new ArrayMap<>(requests.size()); 16959 final Map<String, PrepareResult> prepareResults = new ArrayMap<>(requests.size()); 16960 final Map<String, VersionInfo> versionInfos = new ArrayMap<>(requests.size()); 16961 final Map<String, PackageSetting> lastStaticSharedLibSettings = 16962 new ArrayMap<>(requests.size()); 16963 final Map<String, Boolean> createdAppId = new ArrayMap<>(requests.size()); 16964 boolean success = false; 16965 try { 16966 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackagesLI"); 16967 for (InstallRequest request : requests) { 16968 // TODO(b/109941548): remove this once we've pulled everything from it and into 16969 // scan, reconcile or commit. 16970 final PrepareResult prepareResult; 16971 try { 16972 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "preparePackage"); 16973 prepareResult = preparePackageLI(request.args, request.installResult); 16974 } catch (PrepareFailure prepareFailure) { 16975 request.installResult.setError(prepareFailure.error, 16976 prepareFailure.getMessage()); 16977 request.installResult.origPackage = prepareFailure.conflictingPackage; 16978 request.installResult.origPermission = prepareFailure.conflictingPermission; 16979 return; 16980 } finally { 16981 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16982 } 16983 request.installResult.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16984 request.installResult.installerPackageName = request.args.installerPackageName; 16985 16986 final String packageName = prepareResult.packageToScan.packageName; 16987 prepareResults.put(packageName, prepareResult); 16988 installResults.put(packageName, request.installResult); 16989 installArgs.put(packageName, request.args); 16990 try { 16991 final List<ScanResult> scanResults = scanPackageTracedLI( 16992 prepareResult.packageToScan, prepareResult.parseFlags, 16993 prepareResult.scanFlags, System.currentTimeMillis(), 16994 request.args.user); 16995 for (ScanResult result : scanResults) { 16996 if (null != preparedScans.put(result.pkgSetting.pkg.packageName, result)) { 16997 request.installResult.setError( 16998 PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE, 16999 "Duplicate package " + result.pkgSetting.pkg.packageName 17000 + " in multi-package install request."); 17001 return; 17002 } 17003 createdAppId.put(packageName, optimisticallyRegisterAppId(result)); 17004 versionInfos.put(result.pkgSetting.pkg.packageName, 17005 getSettingsVersionForPackage(result.pkgSetting.pkg)); 17006 if (result.staticSharedLibraryInfo != null) { 17007 final PackageSetting sharedLibLatestVersionSetting = 17008 getSharedLibLatestVersionSetting(result); 17009 if (sharedLibLatestVersionSetting != null) { 17010 lastStaticSharedLibSettings.put(result.pkgSetting.pkg.packageName, 17011 sharedLibLatestVersionSetting); 17012 } 17013 } 17014 } 17015 } catch (PackageManagerException e) { 17016 request.installResult.setError("Scanning Failed.", e); 17017 return; 17018 } 17019 } 17020 ReconcileRequest reconcileRequest = new ReconcileRequest(preparedScans, installArgs, 17021 installResults, 17022 prepareResults, 17023 mSharedLibraries, 17024 Collections.unmodifiableMap(mPackages), versionInfos, 17025 lastStaticSharedLibSettings); 17026 CommitRequest commitRequest = null; 17027 synchronized (mPackages) { 17028 Map<String, ReconciledPackage> reconciledPackages; 17029 try { 17030 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "reconcilePackages"); 17031 reconciledPackages = reconcilePackagesLocked( 17032 reconcileRequest, mSettings.mKeySetManagerService); 17033 } catch (ReconcileFailure e) { 17034 for (InstallRequest request : requests) { 17035 request.installResult.setError("Reconciliation failed...", e); 17036 } 17037 return; 17038 } finally { 17039 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17040 } 17041 try { 17042 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "commitPackages"); 17043 commitRequest = new CommitRequest(reconciledPackages, 17044 sUserManager.getUserIds()); 17045 commitPackagesLocked(commitRequest); 17046 success = true; 17047 } finally { 17048 for (PrepareResult result : prepareResults.values()) { 17049 if (result.freezer != null) { 17050 result.freezer.close(); 17051 } 17052 } 17053 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17054 } 17055 } 17056 executePostCommitSteps(commitRequest); 17057 } finally { 17058 if (!success) { 17059 for (ScanResult result : preparedScans.values()) { 17060 if (createdAppId.getOrDefault(result.request.pkg.packageName, false)) { 17061 cleanUpAppIdCreation(result); 17062 } 17063 } 17064 // TODO(patb): create a more descriptive reason than unknown in future release 17065 // mark all non-failure installs as UNKNOWN so we do not treat them as success 17066 for (InstallRequest request : requests) { 17067 if (request.installResult.returnCode == PackageManager.INSTALL_SUCCEEDED) { 17068 request.installResult.returnCode = PackageManager.INSTALL_UNKNOWN; 17069 } 17070 } 17071 } 17072 for (PrepareResult result : prepareResults.values()) { 17073 if (result.freezer != null) { 17074 result.freezer.close(); 17075 } 17076 } 17077 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17078 } 17079 } 17080 17081 /** 17082 * On successful install, executes remaining steps after commit completes and the package lock 17083 * is released. These are typically more expensive or require calls to installd, which often 17084 * locks on {@link #mPackages}. 17085 */ 17086 private void executePostCommitSteps(CommitRequest commitRequest) { 17087 for (ReconciledPackage reconciledPkg : commitRequest.reconciledPackages.values()) { 17088 final boolean instantApp = ((reconciledPkg.scanResult.request.scanFlags 17089 & PackageManagerService.SCAN_AS_INSTANT_APP) != 0); 17090 final PackageParser.Package pkg = reconciledPkg.pkgSetting.pkg; 17091 final String packageName = pkg.packageName; 17092 prepareAppDataAfterInstallLIF(pkg); 17093 if (reconciledPkg.prepareResult.clearCodeCache) { 17094 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 17095 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 17096 } 17097 if (reconciledPkg.prepareResult.replace) { 17098 mDexManager.notifyPackageUpdated(pkg.packageName, 17099 pkg.baseCodePath, pkg.splitCodePaths); 17100 } 17101 17102 // Prepare the application profiles for the new code paths. 17103 // This needs to be done before invoking dexopt so that any install-time profile 17104 // can be used for optimizations. 17105 mArtManagerService.prepareAppProfiles( 17106 pkg, 17107 resolveUserIds(reconciledPkg.installArgs.user.getIdentifier()), 17108 /* updateReferenceProfileContent= */ true); 17109 17110 // Check whether we need to dexopt the app. 17111 // 17112 // NOTE: it is IMPORTANT to call dexopt: 17113 // - after doRename which will sync the package data from PackageParser.Package and 17114 // its corresponding ApplicationInfo. 17115 // - after installNewPackageLIF or replacePackageLIF which will update result with the 17116 // uid of the application (pkg.applicationInfo.uid). 17117 // This update happens in place! 17118 // 17119 // We only need to dexopt if the package meets ALL of the following conditions: 17120 // 1) it is not an instant app or if it is then dexopt is enabled via gservices. 17121 // 2) it is not debuggable. 17122 // 17123 // Note that we do not dexopt instant apps by default. dexopt can take some time to 17124 // complete, so we skip this step during installation. Instead, we'll take extra time 17125 // the first time the instant app starts. It's preferred to do it this way to provide 17126 // continuous progress to the useur instead of mysteriously blocking somewhere in the 17127 // middle of running an instant app. The default behaviour can be overridden 17128 // via gservices. 17129 final boolean performDexopt = 17130 (!instantApp || Global.getInt(mContext.getContentResolver(), 17131 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) 17132 && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0); 17133 17134 if (performDexopt) { 17135 // Compile the layout resources. 17136 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) { 17137 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "compileLayouts"); 17138 mViewCompiler.compileLayouts(pkg); 17139 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17140 } 17141 17142 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 17143 // Do not run PackageDexOptimizer through the local performDexOpt 17144 // method because `pkg` may not be in `mPackages` yet. 17145 // 17146 // Also, don't fail application installs if the dexopt step fails. 17147 DexoptOptions dexoptOptions = new DexoptOptions(packageName, 17148 REASON_INSTALL, 17149 DexoptOptions.DEXOPT_BOOT_COMPLETE 17150 | DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 17151 mPackageDexOptimizer.performDexOpt(pkg, 17152 null /* instructionSets */, 17153 getOrCreateCompilerPackageStats(pkg), 17154 mDexManager.getPackageUseInfoOrDefault(packageName), 17155 dexoptOptions); 17156 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17157 } 17158 17159 // Notify BackgroundDexOptService that the package has been changed. 17160 // If this is an update of a package which used to fail to compile, 17161 // BackgroundDexOptService will remove it from its blacklist. 17162 // TODO: Layering violation 17163 BackgroundDexOptService.notifyPackageChanged(packageName); 17164 } 17165 } 17166 17167 /** 17168 * The set of data needed to successfully install the prepared package. This includes data that 17169 * will be used to scan and reconcile the package. 17170 */ 17171 private static class PrepareResult { 17172 public final int installReason; 17173 public final String volumeUuid; 17174 public final String installerPackageName; 17175 public final UserHandle user; 17176 public final boolean replace; 17177 public final int scanFlags; 17178 public final int parseFlags; 17179 @Nullable /* The original Package if it is being replaced, otherwise {@code null} */ 17180 public final PackageParser.Package existingPackage; 17181 public final PackageParser.Package packageToScan; 17182 public final boolean clearCodeCache; 17183 public final boolean system; 17184 /* The original package name if it was changed during an update, otherwise {@code null}. */ 17185 @Nullable 17186 public final String renamedPackage; 17187 public final PackageFreezer freezer; 17188 public final PackageSetting originalPs; 17189 public final PackageSetting disabledPs; 17190 public final PackageSetting[] childPackageSettings; 17191 17192 private PrepareResult(int installReason, String volumeUuid, 17193 String installerPackageName, UserHandle user, boolean replace, int scanFlags, 17194 int parseFlags, PackageParser.Package existingPackage, 17195 PackageParser.Package packageToScan, boolean clearCodeCache, boolean system, 17196 String renamedPackage, PackageFreezer freezer, PackageSetting originalPs, 17197 PackageSetting disabledPs, PackageSetting[] childPackageSettings) { 17198 this.installReason = installReason; 17199 this.volumeUuid = volumeUuid; 17200 this.installerPackageName = installerPackageName; 17201 this.user = user; 17202 this.replace = replace; 17203 this.scanFlags = scanFlags; 17204 this.parseFlags = parseFlags; 17205 this.existingPackage = existingPackage; 17206 this.packageToScan = packageToScan; 17207 this.clearCodeCache = clearCodeCache; 17208 this.system = system; 17209 this.renamedPackage = renamedPackage; 17210 this.freezer = freezer; 17211 this.originalPs = originalPs; 17212 this.disabledPs = disabledPs; 17213 this.childPackageSettings = childPackageSettings; 17214 } 17215 } 17216 17217 private static class PrepareFailure extends PackageManagerException { 17218 17219 public String conflictingPackage; 17220 public String conflictingPermission; 17221 17222 PrepareFailure(int error) { 17223 super(error, "Failed to prepare for install."); 17224 } 17225 17226 PrepareFailure(int error, String detailMessage) { 17227 super(error, detailMessage); 17228 } 17229 17230 PrepareFailure(String message, Exception e) { 17231 super(e instanceof PackageParserException 17232 ? ((PackageParserException) e).error 17233 : ((PackageManagerException) e).error, 17234 ExceptionUtils.getCompleteMessage(message, e)); 17235 } 17236 17237 PrepareFailure conflictsWithExistingPermission(String conflictingPermission, 17238 String conflictingPackage) { 17239 this.conflictingPermission = conflictingPermission; 17240 this.conflictingPackage = conflictingPackage; 17241 return this; 17242 } 17243 } 17244 17245 @GuardedBy("mInstallLock") 17246 private PrepareResult preparePackageLI(InstallArgs args, PackageInstalledInfo res) 17247 throws PrepareFailure { 17248 final int installFlags = args.installFlags; 17249 final String installerPackageName = args.installerPackageName; 17250 final String volumeUuid = args.volumeUuid; 17251 final File tmpPackageFile = new File(args.getCodePath()); 17252 final boolean onExternal = args.volumeUuid != null; 17253 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 17254 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 17255 final boolean virtualPreload = 17256 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 17257 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 17258 if (args.move != null) { 17259 // moving a complete application; perform an initial scan on the new install location 17260 scanFlags |= SCAN_INITIAL; 17261 } 17262 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 17263 scanFlags |= SCAN_DONT_KILL_APP; 17264 } 17265 if (instantApp) { 17266 scanFlags |= SCAN_AS_INSTANT_APP; 17267 } 17268 if (fullApp) { 17269 scanFlags |= SCAN_AS_FULL_APP; 17270 } 17271 if (virtualPreload) { 17272 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 17273 } 17274 17275 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 17276 17277 // Sanity check 17278 if (instantApp && onExternal) { 17279 Slog.i(TAG, "Incompatible ephemeral install; external=" + onExternal); 17280 throw new PrepareFailure(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17281 } 17282 17283 // Retrieve PackageSettings and parse package 17284 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 17285 | PackageParser.PARSE_ENFORCE_CODE 17286 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 17287 17288 PackageParser pp = new PackageParser(); 17289 pp.setSeparateProcesses(mSeparateProcesses); 17290 pp.setDisplayMetrics(mMetrics); 17291 pp.setCallback(mPackageParserCallback); 17292 17293 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 17294 final PackageParser.Package pkg; 17295 try { 17296 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 17297 DexMetadataHelper.validatePackageDexMetadata(pkg); 17298 } catch (PackageParserException e) { 17299 throw new PrepareFailure("Failed parse during installPackageLI", e); 17300 } finally { 17301 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 17302 } 17303 17304 // Instant apps have several additional install-time checks. 17305 if (instantApp) { 17306 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 17307 Slog.w(TAG, 17308 "Instant app package " + pkg.packageName + " does not target at least O"); 17309 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 17310 "Instant app package must target at least O"); 17311 } 17312 if (pkg.mSharedUserId != null) { 17313 Slog.w(TAG, "Instant app package " + pkg.packageName 17314 + " may not declare sharedUserId."); 17315 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 17316 "Instant app package may not declare a sharedUserId"); 17317 } 17318 } 17319 17320 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17321 // Static shared libraries have synthetic package names 17322 renameStaticSharedLibraryPackage(pkg); 17323 17324 // No static shared libs on external storage 17325 if (onExternal) { 17326 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 17327 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17328 "Packages declaring static-shared libs cannot be updated"); 17329 } 17330 } 17331 17332 // If we are installing a clustered package add results for the children 17333 if (pkg.childPackages != null) { 17334 synchronized (mPackages) { 17335 final int childCount = pkg.childPackages.size(); 17336 for (int i = 0; i < childCount; i++) { 17337 PackageParser.Package childPkg = pkg.childPackages.get(i); 17338 PackageInstalledInfo childRes = new PackageInstalledInfo(); 17339 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17340 childRes.pkg = childPkg; 17341 childRes.name = childPkg.packageName; 17342 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 17343 if (childPs != null) { 17344 childRes.origUsers = childPs.queryInstalledUsers( 17345 sUserManager.getUserIds(), true); 17346 } 17347 if ((mPackages.containsKey(childPkg.packageName))) { 17348 childRes.removedInfo = new PackageRemovedInfo(this); 17349 childRes.removedInfo.removedPackage = childPkg.packageName; 17350 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 17351 } 17352 if (res.addedChildPackages == null) { 17353 res.addedChildPackages = new ArrayMap<>(); 17354 } 17355 res.addedChildPackages.put(childPkg.packageName, childRes); 17356 } 17357 } 17358 } 17359 17360 // If package doesn't declare API override, mark that we have an install 17361 // time CPU ABI override. 17362 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 17363 pkg.cpuAbiOverride = args.abiOverride; 17364 } 17365 17366 String pkgName = res.name = pkg.packageName; 17367 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0) { 17368 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 17369 throw new PrepareFailure(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 17370 } 17371 } 17372 17373 try { 17374 // either use what we've been given or parse directly from the APK 17375 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 17376 pkg.setSigningDetails(args.signingDetails); 17377 } else { 17378 PackageParser.collectCertificates(pkg, false /* skipVerify */); 17379 } 17380 } catch (PackageParserException e) { 17381 throw new PrepareFailure("Failed collect during installPackageLI", e); 17382 } 17383 17384 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 17385 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 17386 Slog.w(TAG, "Instant app package " + pkg.packageName 17387 + " is not signed with at least APK Signature Scheme v2"); 17388 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 17389 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 17390 } 17391 17392 // Get rid of all references to package scan path via parser. 17393 pp = null; 17394 boolean systemApp = false; 17395 boolean replace = false; 17396 synchronized (mPackages) { 17397 // Check if installing already existing package 17398 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 17399 String oldName = mSettings.getRenamedPackageLPr(pkgName); 17400 if (pkg.mOriginalPackages != null 17401 && pkg.mOriginalPackages.contains(oldName) 17402 && mPackages.containsKey(oldName)) { 17403 // This package is derived from an original package, 17404 // and this device has been updating from that original 17405 // name. We must continue using the original name, so 17406 // rename the new package here. 17407 pkg.setPackageName(oldName); 17408 pkgName = pkg.packageName; 17409 replace = true; 17410 if (DEBUG_INSTALL) { 17411 Slog.d(TAG, "Replacing existing renamed package: oldName=" 17412 + oldName + " pkgName=" + pkgName); 17413 } 17414 } else if (mPackages.containsKey(pkgName)) { 17415 // This package, under its official name, already exists 17416 // on the device; we should replace it. 17417 replace = true; 17418 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 17419 } 17420 17421 // Child packages are installed through the parent package 17422 if (pkg.parentPackage != null) { 17423 throw new PrepareFailure( 17424 PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17425 "Package " + pkg.packageName + " is child of package " 17426 + pkg.parentPackage.parentPackage + ". Child packages " 17427 + "can be updated only through the parent package."); 17428 } 17429 17430 if (replace) { 17431 // Prevent apps opting out from runtime permissions 17432 PackageParser.Package oldPackage = mPackages.get(pkgName); 17433 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 17434 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 17435 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 17436 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 17437 throw new PrepareFailure( 17438 PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 17439 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 17440 + " doesn't support runtime permissions but the old" 17441 + " target SDK " + oldTargetSdk + " does."); 17442 } 17443 // Prevent persistent apps from being updated 17444 if (((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) 17445 && ((installFlags & PackageManager.INSTALL_STAGED) == 0)) { 17446 throw new PrepareFailure(PackageManager.INSTALL_FAILED_INVALID_APK, 17447 "Package " + oldPackage.packageName + " is a persistent app. " 17448 + "Persistent apps are not updateable."); 17449 } 17450 // Prevent installing of child packages 17451 if (oldPackage.parentPackage != null) { 17452 throw new PrepareFailure( 17453 PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 17454 "Package " + pkg.packageName + " is child of package " 17455 + oldPackage.parentPackage + ". Child packages " 17456 + "can be updated only through the parent package."); 17457 } 17458 } 17459 } 17460 17461 PackageSetting ps = mSettings.mPackages.get(pkgName); 17462 if (ps != null) { 17463 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 17464 17465 // Static shared libs have same package with different versions where 17466 // we internally use a synthetic package name to allow multiple versions 17467 // of the same package, therefore we need to compare signatures against 17468 // the package setting for the latest library version. 17469 PackageSetting signatureCheckPs = ps; 17470 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17471 SharedLibraryInfo libraryInfo = getLatestSharedLibraVersionLPr(pkg); 17472 if (libraryInfo != null) { 17473 signatureCheckPs = mSettings.getPackageLPr(libraryInfo.getPackageName()); 17474 } 17475 } 17476 17477 // Quick sanity check that we're signed correctly if updating; 17478 // we'll check this again later when scanning, but we want to 17479 // bail early here before tripping over redefined permissions. 17480 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17481 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 17482 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 17483 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 17484 + pkg.packageName + " upgrade keys do not match the " 17485 + "previously installed version"); 17486 } 17487 } else { 17488 try { 17489 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 17490 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 17491 // We don't care about disabledPkgSetting on install for now. 17492 final boolean compatMatch = verifySignatures( 17493 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 17494 compareRecover); 17495 // The new KeySets will be re-added later in the scanning process. 17496 if (compatMatch) { 17497 synchronized (mPackages) { 17498 ksms.removeAppKeySetDataLPw(pkg.packageName); 17499 } 17500 } 17501 } catch (PackageManagerException e) { 17502 throw new PrepareFailure(e.error, e.getMessage()); 17503 } 17504 } 17505 17506 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17507 systemApp = (ps.pkg.applicationInfo.flags & 17508 ApplicationInfo.FLAG_SYSTEM) != 0; 17509 } 17510 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17511 } 17512 17513 17514 int N = pkg.permissions.size(); 17515 for (int i = N - 1; i >= 0; i--) { 17516 final PackageParser.Permission perm = pkg.permissions.get(i); 17517 final BasePermission bp = 17518 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17519 17520 // Don't allow anyone but the system to define ephemeral permissions. 17521 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17522 && !systemApp) { 17523 Slog.w(TAG, "Non-System package " + pkg.packageName 17524 + " attempting to delcare ephemeral permission " 17525 + perm.info.name + "; Removing ephemeral."); 17526 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17527 } 17528 17529 // Check whether the newly-scanned package wants to define an already-defined perm 17530 if (bp != null) { 17531 // If the defining package is signed with our cert, it's okay. This 17532 // also includes the "updating the same package" case, of course. 17533 // "updating same package" could also involve key-rotation. 17534 final boolean sigsOk; 17535 final String sourcePackageName = bp.getSourcePackageName(); 17536 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17537 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17538 if (sourcePackageName.equals(pkg.packageName) 17539 && (ksms.shouldCheckUpgradeKeySetLocked( 17540 sourcePackageSetting, scanFlags))) { 17541 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17542 } else { 17543 17544 // in the event of signing certificate rotation, we need to see if the 17545 // package's certificate has rotated from the current one, or if it is an 17546 // older certificate with which the current is ok with sharing permissions 17547 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17548 pkg.mSigningDetails, 17549 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17550 sigsOk = true; 17551 } else if (pkg.mSigningDetails.checkCapability( 17552 sourcePackageSetting.signatures.mSigningDetails, 17553 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17554 17555 // the scanned package checks out, has signing certificate rotation 17556 // history, and is newer; bring it over 17557 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17558 sigsOk = true; 17559 } else { 17560 sigsOk = false; 17561 } 17562 } 17563 if (!sigsOk) { 17564 // If the owning package is the system itself, we log but allow 17565 // install to proceed; we fail the install on all other permission 17566 // redefinitions. 17567 if (!sourcePackageName.equals("android")) { 17568 throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17569 + pkg.packageName 17570 + " attempting to redeclare permission " 17571 + perm.info.name + " already owned by " 17572 + sourcePackageName) 17573 .conflictsWithExistingPermission(perm.info.name, 17574 sourcePackageName); 17575 } else { 17576 Slog.w(TAG, "Package " + pkg.packageName 17577 + " attempting to redeclare system permission " 17578 + perm.info.name + "; ignoring new declaration"); 17579 pkg.permissions.remove(i); 17580 } 17581 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17582 // Prevent apps to change protection level to dangerous from any other 17583 // type as this would allow a privilege escalation where an app adds a 17584 // normal/signature permission in other app's group and later redefines 17585 // it as dangerous leading to the group auto-grant. 17586 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17587 == PermissionInfo.PROTECTION_DANGEROUS) { 17588 if (bp != null && !bp.isRuntime()) { 17589 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17590 + "non-runtime permission " + perm.info.name 17591 + " to runtime; keeping old protection level"); 17592 perm.info.protectionLevel = bp.getProtectionLevel(); 17593 } 17594 } 17595 } 17596 } 17597 } 17598 } 17599 17600 if (systemApp) { 17601 if (onExternal) { 17602 // Abort update; system app can't be replaced with app on sdcard 17603 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17604 "Cannot install updates to system apps on sdcard"); 17605 } else if (instantApp) { 17606 // Abort update; system app can't be replaced with an instant app 17607 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 17608 "Cannot update a system app with an instant app"); 17609 } 17610 } 17611 17612 if (args.move != null) { 17613 // We did an in-place move, so dex is ready to roll 17614 scanFlags |= SCAN_NO_DEX; 17615 scanFlags |= SCAN_MOVE; 17616 17617 synchronized (mPackages) { 17618 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17619 if (ps == null) { 17620 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17621 "Missing settings for moved package " + pkgName); 17622 } 17623 17624 // We moved the entire application as-is, so bring over the 17625 // previously derived ABI information. 17626 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17627 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17628 } 17629 17630 } else { 17631 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17632 scanFlags |= SCAN_NO_DEX; 17633 17634 try { 17635 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17636 args.abiOverride : pkg.cpuAbiOverride); 17637 final boolean extractNativeLibs = !pkg.isLibrary(); 17638 derivePackageAbi(pkg, abiOverride, extractNativeLibs); 17639 } catch (PackageManagerException pme) { 17640 Slog.e(TAG, "Error deriving application ABI", pme); 17641 throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR, 17642 "Error deriving application ABI"); 17643 } 17644 } 17645 17646 if (!args.doRename(res.returnCode, pkg)) { 17647 throw new PrepareFailure(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17648 } 17649 17650 try { 17651 setUpFsVerityIfPossible(pkg); 17652 } catch (InstallerException | IOException | DigestException | NoSuchAlgorithmException e) { 17653 throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR, 17654 "Failed to set up verity: " + e); 17655 } 17656 17657 if (!instantApp) { 17658 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17659 } else { 17660 if (DEBUG_DOMAIN_VERIFICATION) { 17661 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17662 } 17663 } 17664 final PackageFreezer freezer = 17665 freezePackageForInstall(pkgName, installFlags, "installPackageLI"); 17666 boolean shouldCloseFreezerBeforeReturn = true; 17667 try { 17668 final PackageParser.Package existingPackage; 17669 String renamedPackage = null; 17670 boolean sysPkg = false; 17671 String targetVolumeUuid = volumeUuid; 17672 int targetScanFlags = scanFlags; 17673 int targetParseFlags = parseFlags; 17674 final PackageSetting ps; 17675 final PackageSetting disabledPs; 17676 final PackageSetting[] childPackages; 17677 if (replace) { 17678 targetVolumeUuid = null; 17679 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17680 // Static libs have a synthetic package name containing the version 17681 // and cannot be updated as an update would get a new package name, 17682 // unless this is the exact same version code which is useful for 17683 // development. 17684 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17685 if (existingPkg != null 17686 && existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17687 throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PACKAGE, 17688 "Packages declaring " 17689 + "static-shared libs cannot be updated"); 17690 } 17691 } 17692 17693 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17694 17695 final PackageParser.Package oldPackage; 17696 final String pkgName11 = pkg.packageName; 17697 final int[] allUsers; 17698 final int[] installedUsers; 17699 17700 synchronized (mPackages) { 17701 oldPackage = mPackages.get(pkgName11); 17702 existingPackage = oldPackage; 17703 if (DEBUG_INSTALL) { 17704 Slog.d(TAG, 17705 "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 17706 } 17707 17708 ps = mSettings.mPackages.get(pkgName11); 17709 disabledPs = mSettings.getDisabledSystemPkgLPr(ps); 17710 17711 // verify signatures are valid 17712 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17713 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 17714 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 17715 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17716 "New package not signed by keys specified by upgrade-keysets: " 17717 + pkgName11); 17718 } 17719 } else { 17720 // default to original signature matching 17721 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 17722 SigningDetails.CertCapabilities.INSTALLED_DATA) 17723 && !oldPackage.mSigningDetails.checkCapability( 17724 pkg.mSigningDetails, 17725 SigningDetails.CertCapabilities.ROLLBACK)) { 17726 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17727 "New package has a different signature: " + pkgName11); 17728 } 17729 } 17730 17731 // don't allow a system upgrade unless the upgrade hash matches 17732 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 17733 final byte[] digestBytes; 17734 try { 17735 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 17736 updateDigest(digest, new File(pkg.baseCodePath)); 17737 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 17738 for (String path : pkg.splitCodePaths) { 17739 updateDigest(digest, new File(path)); 17740 } 17741 } 17742 digestBytes = digest.digest(); 17743 } catch (NoSuchAlgorithmException | IOException e) { 17744 throw new PrepareFailure(INSTALL_FAILED_INVALID_APK, 17745 "Could not compute hash: " + pkgName11); 17746 } 17747 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 17748 throw new PrepareFailure(INSTALL_FAILED_INVALID_APK, 17749 "New package fails restrict-update check: " + pkgName11); 17750 } 17751 // retain upgrade restriction 17752 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 17753 } 17754 17755 // Check for shared user id changes 17756 String invalidPackageName = 17757 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 17758 if (invalidPackageName != null) { 17759 throw new PrepareFailure(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 17760 "Package " + invalidPackageName + " tried to change user " 17761 + oldPackage.mSharedUserId); 17762 } 17763 17764 // In case of rollback, remember per-user/profile install state 17765 allUsers = sUserManager.getUserIds(); 17766 installedUsers = ps.queryInstalledUsers(allUsers, true); 17767 17768 17769 // don't allow an upgrade from full to ephemeral 17770 if (isInstantApp) { 17771 if (args.user == null || args.user.getIdentifier() == UserHandle.USER_ALL) { 17772 for (int currentUser : allUsers) { 17773 if (!ps.getInstantApp(currentUser)) { 17774 // can't downgrade from full to instant 17775 Slog.w(TAG, 17776 "Can't replace full app with instant app: " + pkgName11 17777 + " for user: " + currentUser); 17778 throw new PrepareFailure( 17779 PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17780 } 17781 } 17782 } else if (!ps.getInstantApp(args.user.getIdentifier())) { 17783 // can't downgrade from full to instant 17784 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName11 17785 + " for user: " + args.user.getIdentifier()); 17786 throw new PrepareFailure( 17787 PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17788 } 17789 } 17790 } 17791 17792 // Update what is removed 17793 res.removedInfo = new PackageRemovedInfo(this); 17794 res.removedInfo.uid = oldPackage.applicationInfo.uid; 17795 res.removedInfo.removedPackage = oldPackage.packageName; 17796 res.removedInfo.installerPackageName = ps.installerPackageName; 17797 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 17798 res.removedInfo.isUpdate = true; 17799 res.removedInfo.origUsers = installedUsers; 17800 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 17801 for (int i = 0; i < installedUsers.length; i++) { 17802 final int userId = installedUsers[i]; 17803 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 17804 } 17805 17806 childPackages = mSettings.getChildSettingsLPr(ps); 17807 if (childPackages != null) { 17808 for (PackageSetting childPs : childPackages) { 17809 boolean childPackageUpdated = false; 17810 PackageParser.Package childPkg = (childPs == null) ? null : childPs.pkg; 17811 if (res.addedChildPackages != null) { 17812 PackageInstalledInfo childRes = res.addedChildPackages.get( 17813 childPkg.packageName); 17814 if (childRes != null) { 17815 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 17816 childRes.removedInfo.removedPackage = childPkg.packageName; 17817 if (childPs != null) { 17818 childRes.removedInfo.installerPackageName = 17819 childPs.installerPackageName; 17820 } 17821 childRes.removedInfo.isUpdate = true; 17822 childRes.removedInfo.installReasons = 17823 res.removedInfo.installReasons; 17824 childPackageUpdated = true; 17825 } 17826 } 17827 if (!childPackageUpdated) { 17828 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 17829 childRemovedRes.removedPackage = childPkg.packageName; 17830 if (childPs != null) { 17831 childRemovedRes.installerPackageName = childPs.installerPackageName; 17832 } 17833 childRemovedRes.isUpdate = false; 17834 childRemovedRes.dataRemoved = true; 17835 synchronized (mPackages) { 17836 if (childPs != null) { 17837 childRemovedRes.origUsers = childPs.queryInstalledUsers( 17838 allUsers, 17839 true); 17840 } 17841 } 17842 if (res.removedInfo.removedChildPackages == null) { 17843 res.removedInfo.removedChildPackages = new ArrayMap<>(); 17844 } 17845 res.removedInfo.removedChildPackages.put(childPkg.packageName, 17846 childRemovedRes); 17847 } 17848 } 17849 } 17850 17851 17852 sysPkg = (isSystemApp(oldPackage)); 17853 if (sysPkg) { 17854 // Set the system/privileged/oem/vendor/product flags as needed 17855 final boolean privileged = isPrivilegedApp(oldPackage); 17856 final boolean oem = isOemApp(oldPackage); 17857 final boolean vendor = isVendorApp(oldPackage); 17858 final boolean product = isProductApp(oldPackage); 17859 final boolean odm = isOdmApp(oldPackage); 17860 final @ParseFlags int systemParseFlags = parseFlags; 17861 final @ScanFlags int systemScanFlags = scanFlags 17862 | SCAN_AS_SYSTEM 17863 | (privileged ? SCAN_AS_PRIVILEGED : 0) 17864 | (oem ? SCAN_AS_OEM : 0) 17865 | (vendor ? SCAN_AS_VENDOR : 0) 17866 | (product ? SCAN_AS_PRODUCT : 0) 17867 | (odm ? SCAN_AS_ODM : 0); 17868 17869 if (DEBUG_INSTALL) { 17870 Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17871 + ", old=" + oldPackage); 17872 } 17873 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17874 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 17875 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 17876 targetParseFlags = systemParseFlags; 17877 targetScanFlags = systemScanFlags; 17878 } else { // non system replace 17879 replace = true; 17880 if (DEBUG_INSTALL) { 17881 Slog.d(TAG, 17882 "replaceNonSystemPackageLI: new=" + pkg + ", old=" 17883 + oldPackage); 17884 } 17885 17886 String pkgName1 = oldPackage.packageName; 17887 boolean deletedPkg = true; 17888 boolean addedPkg = false; 17889 boolean updatedSettings = false; 17890 17891 final long origUpdateTime = (pkg.mExtras != null) 17892 ? ((PackageSetting) pkg.mExtras).lastUpdateTime : 0; 17893 17894 } 17895 } else { // new package install 17896 ps = null; 17897 childPackages = null; 17898 disabledPs = null; 17899 replace = false; 17900 existingPackage = null; 17901 // Remember this for later, in case we need to rollback this install 17902 String pkgName1 = pkg.packageName; 17903 17904 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 17905 17906 // TODO(patb): MOVE TO RECONCILE 17907 synchronized (mPackages) { 17908 renamedPackage = mSettings.getRenamedPackageLPr(pkgName1); 17909 if (renamedPackage != null) { 17910 // A package with the same name is already installed, though 17911 // it has been renamed to an older name. The package we 17912 // are trying to install should be installed as an update to 17913 // the existing one, but that has not been requested, so bail. 17914 throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS, 17915 "Attempt to re-install " + pkgName1 17916 + " without first uninstalling package running as " 17917 + renamedPackage); 17918 } 17919 if (mPackages.containsKey(pkgName1)) { 17920 // Don't allow installation over an existing package with the same name. 17921 throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS, 17922 "Attempt to re-install " + pkgName1 17923 + " without first uninstalling."); 17924 } 17925 } 17926 } 17927 // we're passing the freezer back to be closed in a later phase of install 17928 shouldCloseFreezerBeforeReturn = false; 17929 17930 return new PrepareResult(args.installReason, targetVolumeUuid, installerPackageName, 17931 args.user, replace, targetScanFlags, targetParseFlags, existingPackage, pkg, 17932 replace /* clearCodeCache */, sysPkg, renamedPackage, freezer, 17933 ps, disabledPs, childPackages); 17934 } finally { 17935 if (shouldCloseFreezerBeforeReturn) { 17936 freezer.close(); 17937 } 17938 } 17939 } 17940 17941 /** 17942 * Set up fs-verity for the given package if possible. This requires a feature flag of system 17943 * property to be enabled only if the kernel supports fs-verity. 17944 * 17945 * <p>When the feature flag is set to legacy mode, only APK is supported (with some experimental 17946 * kernel patches). In normal mode, all file format can be supported. 17947 */ 17948 private void setUpFsVerityIfPossible(PackageParser.Package pkg) throws InstallerException, 17949 PrepareFailure, IOException, DigestException, NoSuchAlgorithmException { 17950 final boolean standardMode = PackageManagerServiceUtils.isApkVerityEnabled(); 17951 final boolean legacyMode = PackageManagerServiceUtils.isLegacyApkVerityEnabled(); 17952 if (!standardMode && !legacyMode) { 17953 return; 17954 } 17955 17956 // Collect files we care for fs-verity setup. 17957 ArrayMap<String, String> fsverityCandidates = new ArrayMap<>(); 17958 if (legacyMode) { 17959 synchronized (mPackages) { 17960 final PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 17961 if (ps != null && ps.isPrivileged()) { 17962 fsverityCandidates.put(pkg.baseCodePath, null); 17963 if (pkg.splitCodePaths != null) { 17964 for (String splitPath : pkg.splitCodePaths) { 17965 fsverityCandidates.put(splitPath, null); 17966 } 17967 } 17968 } 17969 } 17970 } else { 17971 // NB: These files will become only accessible if the signing key is loaded in kernel's 17972 // .fs-verity keyring. 17973 fsverityCandidates.put(pkg.baseCodePath, 17974 VerityUtils.getFsveritySignatureFilePath(pkg.baseCodePath)); 17975 17976 final String dmPath = DexMetadataHelper.buildDexMetadataPathForApk(pkg.baseCodePath); 17977 if (new File(dmPath).exists()) { 17978 fsverityCandidates.put(dmPath, VerityUtils.getFsveritySignatureFilePath(dmPath)); 17979 } 17980 17981 if (pkg.splitCodePaths != null) { 17982 for (String path : pkg.splitCodePaths) { 17983 fsverityCandidates.put(path, VerityUtils.getFsveritySignatureFilePath(path)); 17984 17985 final String splitDmPath = DexMetadataHelper.buildDexMetadataPathForApk(path); 17986 if (new File(splitDmPath).exists()) { 17987 fsverityCandidates.put(splitDmPath, 17988 VerityUtils.getFsveritySignatureFilePath(splitDmPath)); 17989 } 17990 } 17991 } 17992 } 17993 17994 for (Map.Entry<String, String> entry : fsverityCandidates.entrySet()) { 17995 final String filePath = entry.getKey(); 17996 final String signaturePath = entry.getValue(); 17997 17998 if (!legacyMode) { 17999 // fs-verity is optional for now. Only set up if signature is provided. 18000 if (new File(signaturePath).exists() && !VerityUtils.hasFsverity(filePath)) { 18001 try { 18002 VerityUtils.setUpFsverity(filePath, signaturePath); 18003 } catch (IOException | DigestException | NoSuchAlgorithmException 18004 | SecurityException e) { 18005 throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE, 18006 "Failed to enable fs-verity: " + e); 18007 } 18008 } 18009 continue; 18010 } 18011 18012 // In legacy mode, fs-verity can only be enabled by process with CAP_SYS_ADMIN. 18013 final VerityUtils.SetupResult result = VerityUtils.generateApkVeritySetupData(filePath); 18014 if (result.isOk()) { 18015 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling verity to " + filePath); 18016 final FileDescriptor fd = result.getUnownedFileDescriptor(); 18017 try { 18018 final byte[] rootHash = VerityUtils.generateApkVerityRootHash(filePath); 18019 try { 18020 // A file may already have fs-verity, e.g. when reused during a split 18021 // install. If the measurement succeeds, no need to attempt to set up. 18022 mInstaller.assertFsverityRootHashMatches(filePath, rootHash); 18023 } catch (InstallerException e) { 18024 mInstaller.installApkVerity(filePath, fd, result.getContentSize()); 18025 mInstaller.assertFsverityRootHashMatches(filePath, rootHash); 18026 } 18027 } finally { 18028 IoUtils.closeQuietly(fd); 18029 } 18030 } else if (result.isFailed()) { 18031 throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE, 18032 "Failed to generate verity"); 18033 } 18034 } 18035 } 18036 18037 private void startIntentFilterVerifications(int userId, boolean replacing, 18038 PackageParser.Package pkg) { 18039 if (mIntentFilterVerifierComponent == null) { 18040 Slog.w(TAG, "No IntentFilter verification will not be done as " 18041 + "there is no IntentFilterVerifier available!"); 18042 return; 18043 } 18044 18045 final int verifierUid = getPackageUid( 18046 mIntentFilterVerifierComponent.getPackageName(), 18047 MATCH_DEBUG_TRIAGED_MISSING, 18048 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 18049 18050 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18051 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 18052 mHandler.sendMessage(msg); 18053 18054 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18055 for (int i = 0; i < childCount; i++) { 18056 PackageParser.Package childPkg = pkg.childPackages.get(i); 18057 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 18058 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 18059 mHandler.sendMessage(msg); 18060 } 18061 } 18062 18063 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 18064 PackageParser.Package pkg) { 18065 int size = pkg.activities.size(); 18066 if (size == 0) { 18067 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18068 "No activity, so no need to verify any IntentFilter!"); 18069 return; 18070 } 18071 18072 final boolean hasDomainURLs = hasDomainURLs(pkg); 18073 if (!hasDomainURLs) { 18074 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18075 "No domain URLs, so no need to verify any IntentFilter!"); 18076 return; 18077 } 18078 18079 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 18080 + " if any IntentFilter from the " + size 18081 + " Activities needs verification ..."); 18082 18083 int count = 0; 18084 final String packageName = pkg.packageName; 18085 boolean handlesWebUris = false; 18086 ArraySet<String> domains = new ArraySet<>(); 18087 final boolean previouslyVerified; 18088 boolean hostSetExpanded = false; 18089 boolean needToRunVerify = false; 18090 synchronized (mPackages) { 18091 // If this is a new install and we see that we've already run verification for this 18092 // package, we have nothing to do: it means the state was restored from backup. 18093 IntentFilterVerificationInfo ivi = 18094 mSettings.getIntentFilterVerificationLPr(packageName); 18095 previouslyVerified = (ivi != null); 18096 if (!replacing && previouslyVerified) { 18097 if (DEBUG_DOMAIN_VERIFICATION) { 18098 Slog.i(TAG, "Package " + packageName + " already verified: status=" 18099 + ivi.getStatusString()); 18100 } 18101 return; 18102 } 18103 18104 if (DEBUG_DOMAIN_VERIFICATION) { 18105 Slog.i(TAG, " Previous verified hosts: " 18106 + (ivi == null ? "[none]" : ivi.getDomainsString())); 18107 } 18108 18109 // If any filters need to be verified, then all need to be. In addition, we need to 18110 // know whether an updating app has any web navigation intent filters, to re- 18111 // examine handling policy even if not re-verifying. 18112 final boolean needsVerification = needsNetworkVerificationLPr(packageName); 18113 for (PackageParser.Activity a : pkg.activities) { 18114 for (ActivityIntentInfo filter : a.intents) { 18115 if (filter.handlesWebUris(true)) { 18116 handlesWebUris = true; 18117 } 18118 if (needsVerification && filter.needsVerification()) { 18119 if (DEBUG_DOMAIN_VERIFICATION) { 18120 Slog.d(TAG, "autoVerify requested, processing all filters"); 18121 } 18122 needToRunVerify = true; 18123 // It's safe to break out here because filter.needsVerification() 18124 // can only be true if filter.handlesWebUris(true) returned true, so 18125 // we've already noted that. 18126 break; 18127 } 18128 } 18129 } 18130 18131 // Compare the new set of recognized hosts if the app is either requesting 18132 // autoVerify or has previously used autoVerify but no longer does. 18133 if (needToRunVerify || previouslyVerified) { 18134 final int verificationId = mIntentFilterVerificationToken++; 18135 for (PackageParser.Activity a : pkg.activities) { 18136 for (ActivityIntentInfo filter : a.intents) { 18137 // Run verification against hosts mentioned in any web-nav intent filter, 18138 // even if the filter matches non-web schemes as well 18139 if (filter.handlesWebUris(false /*onlyWebSchemes*/)) { 18140 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 18141 "Verification needed for IntentFilter:" + filter.toString()); 18142 mIntentFilterVerifier.addOneIntentFilterVerification( 18143 verifierUid, userId, verificationId, filter, packageName); 18144 domains.addAll(filter.getHostsList()); 18145 count++; 18146 } 18147 } 18148 } 18149 } 18150 18151 if (DEBUG_DOMAIN_VERIFICATION) { 18152 Slog.i(TAG, " Update published hosts: " + domains.toString()); 18153 } 18154 18155 // If we've previously verified this same host set (or a subset), we can trust that 18156 // a current ALWAYS policy is still applicable. If this is the case, we're done. 18157 // (If we aren't in ALWAYS, we want to reverify to allow for apps that had failing 18158 // hosts in their intent filters, then pushed a new apk that removed them and now 18159 // passes.) 18160 // 18161 // Cases: 18162 // + still autoVerify (needToRunVerify): 18163 // - preserve current state if all of: unexpanded, in always 18164 // - otherwise rerun as usual (fall through) 18165 // + no longer autoVerify (alreadyVerified && !needToRunVerify) 18166 // - wipe verification history always 18167 // - preserve current state if all of: unexpanded, in always 18168 hostSetExpanded = !previouslyVerified 18169 || (ivi != null && !ivi.getDomains().containsAll(domains)); 18170 final int currentPolicy = 18171 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 18172 final boolean keepCurState = !hostSetExpanded 18173 && currentPolicy == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 18174 18175 if (needToRunVerify && keepCurState) { 18176 if (DEBUG_DOMAIN_VERIFICATION) { 18177 Slog.i(TAG, "Host set not expanding + ALWAYS -> no need to reverify"); 18178 } 18179 ivi.setDomains(domains); 18180 scheduleWriteSettingsLocked(); 18181 return; 18182 } else if (previouslyVerified && !needToRunVerify) { 18183 // Prior autoVerify state but not requesting it now. Clear autoVerify history, 18184 // and preserve the always policy iff the host set is not expanding. 18185 clearIntentFilterVerificationsLPw(packageName, userId, !keepCurState); 18186 return; 18187 } 18188 } 18189 18190 if (needToRunVerify && count > 0) { 18191 // app requested autoVerify and has at least one matching intent filter 18192 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 18193 + " IntentFilter verification" + (count > 1 ? "s" : "") 18194 + " for userId:" + userId); 18195 mIntentFilterVerifier.startVerifications(userId); 18196 } else { 18197 if (DEBUG_DOMAIN_VERIFICATION) { 18198 Slog.d(TAG, "No web filters or no new host policy for " + packageName); 18199 } 18200 } 18201 } 18202 18203 @GuardedBy("mPackages") 18204 private boolean needsNetworkVerificationLPr(String packageName) { 18205 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 18206 packageName); 18207 if (ivi == null) { 18208 return true; 18209 } 18210 int status = ivi.getStatus(); 18211 switch (status) { 18212 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 18213 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS: 18214 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 18215 return true; 18216 18217 default: 18218 // Nothing to do 18219 return false; 18220 } 18221 } 18222 18223 private static boolean isMultiArch(ApplicationInfo info) { 18224 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 18225 } 18226 18227 private static boolean isExternal(PackageParser.Package pkg) { 18228 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18229 } 18230 18231 private static boolean isExternal(PackageSetting ps) { 18232 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 18233 } 18234 18235 private static boolean isSystemApp(PackageParser.Package pkg) { 18236 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 18237 } 18238 18239 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 18240 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 18241 } 18242 18243 private static boolean isOemApp(PackageParser.Package pkg) { 18244 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 18245 } 18246 18247 private static boolean isVendorApp(PackageParser.Package pkg) { 18248 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 18249 } 18250 18251 private static boolean isProductApp(PackageParser.Package pkg) { 18252 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 18253 } 18254 18255 private static boolean isProductServicesApp(PackageParser.Package pkg) { 18256 return (pkg.applicationInfo.privateFlags 18257 & ApplicationInfo.PRIVATE_FLAG_PRODUCT_SERVICES) != 0; 18258 } 18259 18260 private static boolean isOdmApp(PackageParser.Package pkg) { 18261 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_ODM) != 0; 18262 } 18263 18264 private static boolean hasDomainURLs(PackageParser.Package pkg) { 18265 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 18266 } 18267 18268 private static boolean isSystemApp(PackageSetting ps) { 18269 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 18270 } 18271 18272 private static boolean isUpdatedSystemApp(PackageSetting ps) { 18273 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 18274 } 18275 18276 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 18277 if (isExternal(pkg)) { 18278 if (TextUtils.isEmpty(pkg.volumeUuid)) { 18279 return mSettings.getExternalVersion(); 18280 } else { 18281 return mSettings.findOrCreateVersion(pkg.volumeUuid); 18282 } 18283 } else { 18284 return mSettings.getInternalVersion(); 18285 } 18286 } 18287 18288 private void deleteTempPackageFiles() { 18289 final FilenameFilter filter = 18290 (dir, name) -> name.startsWith("vmdl") && name.endsWith(".tmp"); 18291 } 18292 18293 @Override 18294 public void deletePackageAsUser(String packageName, int versionCode, 18295 IPackageDeleteObserver observer, int userId, int flags) { 18296 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 18297 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 18298 } 18299 18300 @Override 18301 public void deletePackageVersioned(VersionedPackage versionedPackage, 18302 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 18303 final int callingUid = Binder.getCallingUid(); 18304 mContext.enforceCallingOrSelfPermission( 18305 android.Manifest.permission.DELETE_PACKAGES, null); 18306 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 18307 Preconditions.checkNotNull(versionedPackage); 18308 Preconditions.checkNotNull(observer); 18309 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 18310 PackageManager.VERSION_CODE_HIGHEST, 18311 Long.MAX_VALUE, "versionCode must be >= -1"); 18312 18313 final String packageName = versionedPackage.getPackageName(); 18314 final long versionCode = versionedPackage.getLongVersionCode(); 18315 final String internalPackageName; 18316 synchronized (mPackages) { 18317 // Normalize package name to handle renamed packages and static libs 18318 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 18319 } 18320 18321 final int uid = Binder.getCallingUid(); 18322 if (!isOrphaned(internalPackageName) 18323 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 18324 mHandler.post(() -> { 18325 try { 18326 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 18327 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 18328 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 18329 observer.onUserActionRequired(intent); 18330 } catch (RemoteException re) { 18331 } 18332 }); 18333 return; 18334 } 18335 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 18336 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{userId}; 18337 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 18338 mContext.enforceCallingOrSelfPermission( 18339 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 18340 "deletePackage for user " + userId); 18341 } 18342 18343 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 18344 mHandler.post(() -> { 18345 try { 18346 observer.onPackageDeleted(packageName, 18347 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 18348 } catch (RemoteException re) { 18349 } 18350 }); 18351 return; 18352 } 18353 18354 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 18355 mHandler.post(() -> { 18356 try { 18357 observer.onPackageDeleted(packageName, 18358 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 18359 } catch (RemoteException re) { 18360 } 18361 }); 18362 return; 18363 } 18364 18365 if (DEBUG_REMOVE) { 18366 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 18367 + " deleteAllUsers: " + deleteAllUsers + " version=" 18368 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 18369 ? "VERSION_CODE_HIGHEST" : versionCode)); 18370 } 18371 // Queue up an async operation since the package deletion may take a little while. 18372 mHandler.post(() -> { 18373 int returnCode; 18374 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 18375 boolean doDeletePackage = true; 18376 if (ps != null) { 18377 final boolean targetIsInstantApp = 18378 ps.getInstantApp(UserHandle.getUserId(callingUid)); 18379 doDeletePackage = !targetIsInstantApp 18380 || canViewInstantApps; 18381 } 18382 if (doDeletePackage) { 18383 if (!deleteAllUsers) { 18384 returnCode = deletePackageX(internalPackageName, versionCode, 18385 userId, deleteFlags); 18386 } else { 18387 int[] blockUninstallUserIds = getBlockUninstallForUsers( 18388 internalPackageName, users); 18389 // If nobody is blocking uninstall, proceed with delete for all users 18390 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 18391 returnCode = deletePackageX(internalPackageName, versionCode, 18392 userId, deleteFlags); 18393 } else { 18394 // Otherwise uninstall individually for users with blockUninstalls=false 18395 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 18396 for (int userId1 : users) { 18397 if (!ArrayUtils.contains(blockUninstallUserIds, userId1)) { 18398 returnCode = deletePackageX(internalPackageName, versionCode, 18399 userId1, userFlags); 18400 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 18401 Slog.w(TAG, "Package delete failed for user " + userId1 18402 + ", returnCode " + returnCode); 18403 } 18404 } 18405 } 18406 // The app has only been marked uninstalled for certain users. 18407 // We still need to report that delete was blocked 18408 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 18409 } 18410 } 18411 } else { 18412 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18413 } 18414 try { 18415 observer.onPackageDeleted(packageName, returnCode, null); 18416 } catch (RemoteException e) { 18417 Log.i(TAG, "Observer no longer exists."); 18418 } //end catch 18419 }); 18420 } 18421 18422 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 18423 if (pkg.staticSharedLibName != null) { 18424 return pkg.manifestPackageName; 18425 } 18426 return pkg.packageName; 18427 } 18428 18429 @GuardedBy("mPackages") 18430 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 18431 // Handle renamed packages 18432 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 18433 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 18434 18435 // Is this a static library? 18436 LongSparseArray<SharedLibraryInfo> versionedLib = 18437 mStaticLibsByDeclaringPackage.get(packageName); 18438 if (versionedLib == null || versionedLib.size() <= 0) { 18439 return packageName; 18440 } 18441 18442 // Figure out which lib versions the caller can see 18443 LongSparseLongArray versionsCallerCanSee = null; 18444 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 18445 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 18446 && callingAppId != Process.ROOT_UID) { 18447 versionsCallerCanSee = new LongSparseLongArray(); 18448 String libName = versionedLib.valueAt(0).getName(); 18449 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 18450 if (uidPackages != null) { 18451 for (String uidPackage : uidPackages) { 18452 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 18453 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 18454 if (libIdx >= 0) { 18455 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 18456 versionsCallerCanSee.append(libVersion, libVersion); 18457 } 18458 } 18459 } 18460 } 18461 18462 // Caller can see nothing - done 18463 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 18464 return packageName; 18465 } 18466 18467 // Find the version the caller can see and the app version code 18468 SharedLibraryInfo highestVersion = null; 18469 final int versionCount = versionedLib.size(); 18470 for (int i = 0; i < versionCount; i++) { 18471 SharedLibraryInfo libraryInfo = versionedLib.valueAt(i); 18472 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 18473 libraryInfo.getLongVersion()) < 0) { 18474 continue; 18475 } 18476 final long libVersionCode = libraryInfo.getDeclaringPackage().getLongVersionCode(); 18477 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 18478 if (libVersionCode == versionCode) { 18479 return libraryInfo.getPackageName(); 18480 } 18481 } else if (highestVersion == null) { 18482 highestVersion = libraryInfo; 18483 } else if (libVersionCode > highestVersion 18484 .getDeclaringPackage().getLongVersionCode()) { 18485 highestVersion = libraryInfo; 18486 } 18487 } 18488 18489 if (highestVersion != null) { 18490 return highestVersion.getPackageName(); 18491 } 18492 18493 return packageName; 18494 } 18495 18496 boolean isCallerVerifier(int callingUid) { 18497 final int callingUserId = UserHandle.getUserId(callingUid); 18498 return mRequiredVerifierPackage != null && 18499 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 18500 } 18501 18502 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 18503 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 18504 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 18505 return true; 18506 } 18507 final int callingUserId = UserHandle.getUserId(callingUid); 18508 // If the caller installed the pkgName, then allow it to silently uninstall. 18509 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 18510 return true; 18511 } 18512 18513 // Allow package verifier to silently uninstall. 18514 if (mRequiredVerifierPackage != null && 18515 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 18516 return true; 18517 } 18518 18519 // Allow package uninstaller to silently uninstall. 18520 if (mRequiredUninstallerPackage != null && 18521 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 18522 return true; 18523 } 18524 18525 // Allow storage manager to silently uninstall. 18526 if (mStorageManagerPackage != null && 18527 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 18528 return true; 18529 } 18530 18531 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 18532 // uninstall for device owner provisioning. 18533 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 18534 == PERMISSION_GRANTED) { 18535 return true; 18536 } 18537 18538 return false; 18539 } 18540 18541 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 18542 int[] result = EMPTY_INT_ARRAY; 18543 for (int userId : userIds) { 18544 if (getBlockUninstallForUser(packageName, userId)) { 18545 result = ArrayUtils.appendInt(result, userId); 18546 } 18547 } 18548 return result; 18549 } 18550 18551 @Override 18552 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 18553 final int callingUid = Binder.getCallingUid(); 18554 if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid) 18555 != PERMISSION_GRANTED) { 18556 EventLog.writeEvent(0x534e4554, "128599183", -1, ""); 18557 throw new SecurityException(android.Manifest.permission.MANAGE_USERS 18558 + " permission is required to call this API"); 18559 } 18560 if (getInstantAppPackageName(callingUid) != null 18561 && !isCallerSameApp(packageName, callingUid)) { 18562 return false; 18563 } 18564 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 18565 } 18566 18567 private boolean isPackageDeviceAdmin(String packageName, int userId) { 18568 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 18569 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 18570 try { 18571 if (dpm != null) { 18572 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 18573 /* callingUserOnly =*/ false); 18574 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 18575 : deviceOwnerComponentName.getPackageName(); 18576 // Does the package contains the device owner? 18577 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 18578 // this check is probably not needed, since DO should be registered as a device 18579 // admin on some user too. (Original bug for this: b/17657954) 18580 if (packageName.equals(deviceOwnerPackageName)) { 18581 return true; 18582 } 18583 // Does it contain a device admin for any user? 18584 int[] users; 18585 if (userId == UserHandle.USER_ALL) { 18586 users = sUserManager.getUserIds(); 18587 } else { 18588 users = new int[]{userId}; 18589 } 18590 for (int i = 0; i < users.length; ++i) { 18591 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 18592 return true; 18593 } 18594 } 18595 } 18596 } catch (RemoteException e) { 18597 } 18598 return false; 18599 } 18600 18601 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 18602 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 18603 } 18604 18605 /** 18606 * This method is an internal method that could be get invoked either 18607 * to delete an installed package or to clean up a failed installation. 18608 * After deleting an installed package, a broadcast is sent to notify any 18609 * listeners that the package has been removed. For cleaning up a failed 18610 * installation, the broadcast is not necessary since the package's 18611 * installation wouldn't have sent the initial broadcast either 18612 * The key steps in deleting a package are 18613 * deleting the package information in internal structures like mPackages, 18614 * deleting the packages base directories through installd 18615 * updating mSettings to reflect current status 18616 * persisting settings for later use 18617 * sending a broadcast if necessary 18618 */ 18619 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 18620 final PackageRemovedInfo info = new PackageRemovedInfo(this); 18621 final boolean res; 18622 18623 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18624 ? UserHandle.USER_ALL : userId; 18625 18626 if (isPackageDeviceAdmin(packageName, removeUser)) { 18627 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18628 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18629 } 18630 18631 final PackageSetting uninstalledPs; 18632 final PackageSetting disabledSystemPs; 18633 final PackageParser.Package pkg; 18634 18635 // for the uninstall-updates case and restricted profiles, remember the per- 18636 // user handle installed state 18637 int[] allUsers; 18638 /** enabled state of the uninstalled application */ 18639 final int origEnabledState; 18640 synchronized (mPackages) { 18641 uninstalledPs = mSettings.mPackages.get(packageName); 18642 if (uninstalledPs == null) { 18643 Slog.w(TAG, "Not removing non-existent package " + packageName); 18644 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18645 } 18646 18647 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18648 && uninstalledPs.versionCode != versionCode) { 18649 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18650 + uninstalledPs.versionCode + " != " + versionCode); 18651 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18652 } 18653 18654 disabledSystemPs = mSettings.getDisabledSystemPkgLPr(packageName); 18655 // Save the enabled state before we delete the package. When deleting a stub 18656 // application we always set the enabled state to 'disabled'. 18657 origEnabledState = uninstalledPs == null 18658 ? COMPONENT_ENABLED_STATE_DEFAULT : uninstalledPs.getEnabled(userId); 18659 // Static shared libs can be declared by any package, so let us not 18660 // allow removing a package if it provides a lib others depend on. 18661 pkg = mPackages.get(packageName); 18662 18663 allUsers = sUserManager.getUserIds(); 18664 18665 if (pkg != null && pkg.staticSharedLibName != null) { 18666 SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(pkg.staticSharedLibName, 18667 pkg.staticSharedLibVersion); 18668 if (libraryInfo != null) { 18669 for (int currUserId : allUsers) { 18670 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 18671 continue; 18672 } 18673 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18674 libraryInfo, MATCH_KNOWN_PACKAGES, currUserId); 18675 if (!ArrayUtils.isEmpty(libClientPackages)) { 18676 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18677 + " hosting lib " + libraryInfo.getName() + " version " 18678 + libraryInfo.getLongVersion() + " used by " + libClientPackages 18679 + " for user " + currUserId); 18680 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18681 } 18682 } 18683 } 18684 } 18685 18686 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18687 } 18688 18689 final int freezeUser; 18690 if (isUpdatedSystemApp(uninstalledPs) 18691 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18692 // We're downgrading a system app, which will apply to all users, so 18693 // freeze them all during the downgrade 18694 freezeUser = UserHandle.USER_ALL; 18695 } else { 18696 freezeUser = removeUser; 18697 } 18698 18699 synchronized (mInstallLock) { 18700 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18701 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18702 deleteFlags, "deletePackageX")) { 18703 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18704 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 18705 } 18706 synchronized (mPackages) { 18707 if (res) { 18708 if (pkg != null) { 18709 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18710 } 18711 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18712 updateInstantAppInstallerLocked(packageName); 18713 } 18714 } 18715 } 18716 18717 if (res) { 18718 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18719 info.sendPackageRemovedBroadcasts(killApp); 18720 info.sendSystemPackageUpdatedBroadcasts(); 18721 info.sendSystemPackageAppearedBroadcasts(); 18722 } 18723 // Force a gc here. 18724 Runtime.getRuntime().gc(); 18725 // Delete the resources here after sending the broadcast to let 18726 // other processes clean up before deleting resources. 18727 synchronized (mInstallLock) { 18728 if (info.args != null) { 18729 info.args.doPostDeleteLI(true); 18730 } 18731 final PackageParser.Package stubPkg = 18732 (disabledSystemPs == null) ? null : disabledSystemPs.pkg; 18733 if (stubPkg != null && stubPkg.isStub) { 18734 synchronized (mPackages) { 18735 // restore the enabled state of the stub; the state is overwritten when 18736 // the stub is uninstalled 18737 final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName); 18738 if (stubPs != null) { 18739 stubPs.setEnabled(origEnabledState, userId, "android"); 18740 } 18741 } 18742 if (origEnabledState == COMPONENT_ENABLED_STATE_DEFAULT 18743 || origEnabledState == COMPONENT_ENABLED_STATE_ENABLED) { 18744 if (DEBUG_COMPRESSION) { 18745 Slog.i(TAG, "Enabling system stub after removal; pkg: " 18746 + stubPkg.packageName); 18747 } 18748 enableCompressedPackage(stubPkg); 18749 } 18750 } 18751 } 18752 18753 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18754 } 18755 18756 static class PackageRemovedInfo { 18757 final PackageSender packageSender; 18758 String removedPackage; 18759 String installerPackageName; 18760 int uid = -1; 18761 int removedAppId = -1; 18762 int[] origUsers; 18763 int[] removedUsers = null; 18764 int[] broadcastUsers = null; 18765 int[] instantUserIds = null; 18766 SparseArray<Integer> installReasons; 18767 boolean isRemovedPackageSystemUpdate = false; 18768 boolean isUpdate; 18769 boolean dataRemoved; 18770 boolean removedForAllUsers; 18771 boolean isStaticSharedLib; 18772 // Clean up resources deleted packages. 18773 InstallArgs args = null; 18774 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18775 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18776 18777 PackageRemovedInfo(PackageSender packageSender) { 18778 this.packageSender = packageSender; 18779 } 18780 18781 void sendPackageRemovedBroadcasts(boolean killApp) { 18782 sendPackageRemovedBroadcastInternal(killApp); 18783 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18784 for (int i = 0; i < childCount; i++) { 18785 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18786 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18787 } 18788 } 18789 18790 void sendSystemPackageUpdatedBroadcasts() { 18791 if (isRemovedPackageSystemUpdate) { 18792 sendSystemPackageUpdatedBroadcastsInternal(); 18793 final int childCount = (removedChildPackages != null) 18794 ? removedChildPackages.size() : 0; 18795 for (int i = 0; i < childCount; i++) { 18796 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18797 if (childInfo.isRemovedPackageSystemUpdate) { 18798 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18799 } 18800 } 18801 } 18802 } 18803 18804 void sendSystemPackageAppearedBroadcasts() { 18805 final int packageCount = (appearedChildPackages != null) 18806 ? appearedChildPackages.size() : 0; 18807 for (int i = 0; i < packageCount; i++) { 18808 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18809 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18810 true /*sendBootCompleted*/, false /*startReceiver*/, 18811 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18812 } 18813 } 18814 18815 private void sendSystemPackageUpdatedBroadcastsInternal() { 18816 Bundle extras = new Bundle(2); 18817 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18818 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18819 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18820 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18821 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18822 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18823 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18824 null, null, 0, removedPackage, null, null, null); 18825 if (installerPackageName != null) { 18826 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18827 removedPackage, extras, 0 /*flags*/, 18828 installerPackageName, null, null, null); 18829 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18830 removedPackage, extras, 0 /*flags*/, 18831 installerPackageName, null, null, null); 18832 } 18833 } 18834 18835 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18836 // Don't send static shared library removal broadcasts as these 18837 // libs are visible only the the apps that depend on them an one 18838 // cannot remove the library if it has a dependency. 18839 if (isStaticSharedLib) { 18840 return; 18841 } 18842 Bundle extras = new Bundle(2); 18843 final int removedUid = removedAppId >= 0 ? removedAppId : uid; 18844 extras.putInt(Intent.EXTRA_UID, removedUid); 18845 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18846 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18847 if (isUpdate || isRemovedPackageSystemUpdate) { 18848 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18849 } 18850 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18851 if (removedPackage != null) { 18852 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18853 removedPackage, extras, 0, null /*targetPackage*/, null, 18854 broadcastUsers, instantUserIds); 18855 if (installerPackageName != null) { 18856 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18857 removedPackage, extras, 0 /*flags*/, 18858 installerPackageName, null, broadcastUsers, instantUserIds); 18859 } 18860 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18861 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18862 removedPackage, extras, 18863 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18864 null, null, broadcastUsers, instantUserIds); 18865 packageSender.notifyPackageRemoved(removedPackage, removedUid); 18866 } 18867 } 18868 if (removedAppId >= 0) { 18869 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18870 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18871 null, null, broadcastUsers, instantUserIds); 18872 } 18873 } 18874 18875 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18876 removedUsers = userIds; 18877 if (removedUsers == null) { 18878 broadcastUsers = null; 18879 return; 18880 } 18881 18882 broadcastUsers = EMPTY_INT_ARRAY; 18883 instantUserIds = EMPTY_INT_ARRAY; 18884 for (int i = userIds.length - 1; i >= 0; --i) { 18885 final int userId = userIds[i]; 18886 if (deletedPackageSetting.getInstantApp(userId)) { 18887 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18888 } else { 18889 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18890 } 18891 } 18892 } 18893 } 18894 18895 /* 18896 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18897 * flag is not set, the data directory is removed as well. 18898 * make sure this flag is set for partially installed apps. If not its meaningless to 18899 * delete a partially installed application. 18900 */ 18901 private void removePackageDataLIF(final PackageSetting deletedPs, int[] allUserHandles, 18902 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18903 String packageName = deletedPs.name; 18904 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + deletedPs); 18905 // Retrieve object to delete permissions for shared user later on 18906 final PackageParser.Package deletedPkg = deletedPs.pkg; 18907 if (outInfo != null) { 18908 outInfo.removedPackage = packageName; 18909 outInfo.installerPackageName = deletedPs.installerPackageName; 18910 outInfo.isStaticSharedLib = deletedPkg != null 18911 && deletedPkg.staticSharedLibName != null; 18912 outInfo.populateUsers(deletedPs == null ? null 18913 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18914 } 18915 18916 removePackageLI(deletedPs.name, (flags & PackageManager.DELETE_CHATTY) != 0); 18917 18918 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18919 final PackageParser.Package resolvedPkg; 18920 if (deletedPkg != null) { 18921 resolvedPkg = deletedPkg; 18922 } else { 18923 // We don't have a parsed package when it lives on an ejected 18924 // adopted storage device, so fake something together 18925 resolvedPkg = new PackageParser.Package(deletedPs.name); 18926 resolvedPkg.setVolumeUuid(deletedPs.volumeUuid); 18927 } 18928 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18929 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 18930 destroyAppProfilesLIF(resolvedPkg); 18931 if (outInfo != null) { 18932 outInfo.dataRemoved = true; 18933 } 18934 } 18935 18936 int removedAppId = -1; 18937 18938 // writer 18939 boolean installedStateChanged = false; 18940 if (deletedPs != null) { 18941 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18942 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 18943 synchronized (mPackages) { 18944 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL, true); 18945 clearDefaultBrowserIfNeeded(packageName); 18946 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18947 removedAppId = mSettings.removePackageLPw(packageName); 18948 if (outInfo != null) { 18949 outInfo.removedAppId = removedAppId; 18950 } 18951 mPermissionManager.updatePermissions( 18952 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18953 if (deletedPs.sharedUser != null) { 18954 // Remove permissions associated with package. Since runtime 18955 // permissions are per user we have to kill the removed package 18956 // or packages running under the shared user of the removed 18957 // package if revoking the permissions requested only by the removed 18958 // package is successful and this causes a change in gids. 18959 for (int userId : UserManagerService.getInstance().getUserIds()) { 18960 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18961 userId); 18962 if (userIdToKill == UserHandle.USER_ALL 18963 || userIdToKill >= UserHandle.USER_SYSTEM) { 18964 // If gids changed for this user, kill all affected packages. 18965 mHandler.post(() -> { 18966 // This has to happen with no lock held. 18967 killApplication(deletedPs.name, deletedPs.appId, 18968 KILL_APP_REASON_GIDS_CHANGED); 18969 }); 18970 break; 18971 } 18972 } 18973 } 18974 clearPackagePreferredActivitiesLPw( 18975 deletedPs.name, changedUsers, UserHandle.USER_ALL); 18976 } 18977 if (changedUsers.size() > 0) { 18978 updateDefaultHomeNotLocked(changedUsers); 18979 postPreferredActivityChangedBroadcast(UserHandle.USER_ALL); 18980 } 18981 } 18982 // make sure to preserve per-user disabled state if this removal was just 18983 // a downgrade of a system app to the factory package 18984 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18985 if (DEBUG_REMOVE) { 18986 Slog.d(TAG, "Propagating install state across downgrade"); 18987 } 18988 for (int userId : allUserHandles) { 18989 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18990 if (DEBUG_REMOVE) { 18991 Slog.d(TAG, " user " + userId + " => " + installed); 18992 } 18993 if (installed != deletedPs.getInstalled(userId)) { 18994 installedStateChanged = true; 18995 } 18996 deletedPs.setInstalled(installed, userId); 18997 } 18998 } 18999 } 19000 synchronized (mPackages) { 19001 // can downgrade to reader 19002 if (writeSettings) { 19003 // Save settings now 19004 mSettings.writeLPr(); 19005 } 19006 if (installedStateChanged) { 19007 mSettings.writeKernelMappingLPr(deletedPs); 19008 } 19009 } 19010 if (removedAppId != -1) { 19011 // A user ID was deleted here. Go through all users and remove it 19012 // from KeyStore. 19013 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 19014 } 19015 } 19016 19017 static boolean locationIsPrivileged(String path) { 19018 try { 19019 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 19020 final File privilegedVendorAppDir = new File(Environment.getVendorDirectory(), "priv-app"); 19021 final File privilegedOdmAppDir = new File(Environment.getOdmDirectory(), "priv-app"); 19022 final File privilegedProductAppDir = new File(Environment.getProductDirectory(), "priv-app"); 19023 final File privilegedProductServicesAppDir = 19024 new File(Environment.getProductServicesDirectory(), "priv-app"); 19025 return path.startsWith(privilegedAppDir.getCanonicalPath() + "/") 19026 || path.startsWith(privilegedVendorAppDir.getCanonicalPath() + "/") 19027 || path.startsWith(privilegedOdmAppDir.getCanonicalPath() + "/") 19028 || path.startsWith(privilegedProductAppDir.getCanonicalPath() + "/") 19029 || path.startsWith(privilegedProductServicesAppDir.getCanonicalPath() + "/"); 19030 } catch (IOException e) { 19031 Slog.e(TAG, "Unable to access code path " + path); 19032 } 19033 return false; 19034 } 19035 19036 static boolean locationIsOem(String path) { 19037 try { 19038 return path.startsWith(Environment.getOemDirectory().getCanonicalPath() + "/"); 19039 } catch (IOException e) { 19040 Slog.e(TAG, "Unable to access code path " + path); 19041 } 19042 return false; 19043 } 19044 19045 static boolean locationIsVendor(String path) { 19046 try { 19047 return path.startsWith(Environment.getVendorDirectory().getCanonicalPath() + "/") 19048 || path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/"); 19049 } catch (IOException e) { 19050 Slog.e(TAG, "Unable to access code path " + path); 19051 } 19052 return false; 19053 } 19054 19055 static boolean locationIsProduct(String path) { 19056 try { 19057 return path.startsWith(Environment.getProductDirectory().getCanonicalPath() + "/"); 19058 } catch (IOException e) { 19059 Slog.e(TAG, "Unable to access code path " + path); 19060 } 19061 return false; 19062 } 19063 19064 static boolean locationIsProductServices(String path) { 19065 try { 19066 return path.startsWith( 19067 Environment.getProductServicesDirectory().getCanonicalPath() + "/"); 19068 } catch (IOException e) { 19069 Slog.e(TAG, "Unable to access code path " + path); 19070 } 19071 return false; 19072 } 19073 19074 static boolean locationIsOdm(String path) { 19075 try { 19076 return path.startsWith(Environment.getOdmDirectory().getCanonicalPath() + "/"); 19077 } catch (IOException e) { 19078 Slog.e(TAG, "Unable to access code path " + path); 19079 } 19080 return false; 19081 } 19082 19083 /* 19084 * Tries to delete system package. 19085 */ 19086 private void deleteSystemPackageLIF(DeletePackageAction action, PackageSetting deletedPs, 19087 int[] allUserHandles, int flags, @Nullable PackageRemovedInfo outInfo, 19088 boolean writeSettings) 19089 throws SystemDeleteException { 19090 final boolean applyUserRestrictions = 19091 (allUserHandles != null) && outInfo != null && (outInfo.origUsers != null); 19092 final PackageParser.Package deletedPkg = deletedPs.pkg; 19093 // Confirm if the system package has been updated 19094 // An updated system app can be deleted. This will also have to restore 19095 // the system pkg from system partition 19096 // reader 19097 final PackageSetting disabledPs = action.disabledPs; 19098 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 19099 + " disabledPs=" + disabledPs); 19100 Slog.d(TAG, "Deleting system pkg from data partition"); 19101 19102 if (DEBUG_REMOVE) { 19103 if (applyUserRestrictions) { 19104 Slog.d(TAG, "Remembering install states:"); 19105 for (int userId : allUserHandles) { 19106 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 19107 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 19108 } 19109 } 19110 } 19111 19112 if (outInfo != null) { 19113 // Delete the updated package 19114 outInfo.isRemovedPackageSystemUpdate = true; 19115 if (outInfo.removedChildPackages != null) { 19116 final int childCount = (deletedPs.childPackageNames != null) 19117 ? deletedPs.childPackageNames.size() : 0; 19118 for (int i = 0; i < childCount; i++) { 19119 String childPackageName = deletedPs.childPackageNames.get(i); 19120 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 19121 .contains(childPackageName)) { 19122 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19123 childPackageName); 19124 if (childInfo != null) { 19125 childInfo.isRemovedPackageSystemUpdate = true; 19126 } 19127 } 19128 } 19129 } 19130 } 19131 19132 if (disabledPs.versionCode < deletedPs.versionCode) { 19133 // Delete data for downgrades 19134 flags &= ~PackageManager.DELETE_KEEP_DATA; 19135 } else { 19136 // Preserve data by setting flag 19137 flags |= PackageManager.DELETE_KEEP_DATA; 19138 } 19139 19140 deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 19141 outInfo, writeSettings, disabledPs.pkg); 19142 19143 // writer 19144 synchronized (mPackages) { 19145 // NOTE: The system package always needs to be enabled; even if it's for 19146 // a compressed stub. If we don't, installing the system package fails 19147 // during scan [scanning checks the disabled packages]. We will reverse 19148 // this later, after we've "installed" the stub. 19149 // Reinstate the old system package 19150 enableSystemPackageLPw(disabledPs.pkg); 19151 // Remove any native libraries from the upgraded package. 19152 removeNativeBinariesLI(deletedPs); 19153 } 19154 19155 // Install the system package 19156 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 19157 try { 19158 installPackageFromSystemLIF(disabledPs.codePathString, allUserHandles, 19159 outInfo == null ? null : outInfo.origUsers, deletedPs.getPermissionsState(), 19160 writeSettings); 19161 } catch (PackageManagerException e) { 19162 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 19163 + e.getMessage()); 19164 // TODO(patb): can we avoid this; throw would come from scan... 19165 throw new SystemDeleteException(e); 19166 } finally { 19167 if (disabledPs.pkg.isStub) { 19168 // We've re-installed the stub; make sure it's disabled here. If package was 19169 // originally enabled, we'll install the compressed version of the application 19170 // and re-enable it afterward. 19171 final PackageSetting stubPs = mSettings.mPackages.get(deletedPkg.packageName); 19172 if (stubPs != null) { 19173 stubPs.setEnabled( 19174 COMPONENT_ENABLED_STATE_DISABLED, UserHandle.USER_SYSTEM, "android"); 19175 } 19176 } 19177 } 19178 } 19179 19180 /** 19181 * Installs a package that's already on the system partition. 19182 */ 19183 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 19184 @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 19185 @Nullable PermissionsState origPermissionState, boolean writeSettings) 19186 throws PackageManagerException { 19187 @ParseFlags int parseFlags = 19188 mDefParseFlags 19189 | PackageParser.PARSE_MUST_BE_APK 19190 | PackageParser.PARSE_IS_SYSTEM_DIR; 19191 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 19192 if (locationIsPrivileged(codePathString)) { 19193 scanFlags |= SCAN_AS_PRIVILEGED; 19194 } 19195 if (locationIsOem(codePathString)) { 19196 scanFlags |= SCAN_AS_OEM; 19197 } 19198 if (locationIsVendor(codePathString)) { 19199 scanFlags |= SCAN_AS_VENDOR; 19200 } 19201 if (locationIsProduct(codePathString)) { 19202 scanFlags |= SCAN_AS_PRODUCT; 19203 } 19204 if (locationIsProductServices(codePathString)) { 19205 scanFlags |= SCAN_AS_PRODUCT_SERVICES; 19206 } 19207 if (locationIsOdm(codePathString)) { 19208 scanFlags |= SCAN_AS_ODM; 19209 } 19210 19211 final File codePath = new File(codePathString); 19212 final PackageParser.Package pkg = 19213 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 19214 19215 try { 19216 // update shared libraries for the newly re-installed system package 19217 updateSharedLibrariesLocked(pkg, null, Collections.unmodifiableMap(mPackages)); 19218 } catch (PackageManagerException e) { 19219 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 19220 } 19221 19222 prepareAppDataAfterInstallLIF(pkg); 19223 19224 // writer 19225 synchronized (mPackages) { 19226 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 19227 19228 // Propagate the permissions state as we do not want to drop on the floor 19229 // runtime permissions. The update permissions method below will take 19230 // care of removing obsolete permissions and grant install permissions. 19231 if (origPermissionState != null) { 19232 ps.getPermissionsState().copyFrom(origPermissionState); 19233 } 19234 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 19235 mPermissionCallback); 19236 19237 final boolean applyUserRestrictions 19238 = (allUserHandles != null) && (origUserHandles != null); 19239 if (applyUserRestrictions) { 19240 boolean installedStateChanged = false; 19241 if (DEBUG_REMOVE) { 19242 Slog.d(TAG, "Propagating install state across reinstall"); 19243 } 19244 for (int userId : allUserHandles) { 19245 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 19246 if (DEBUG_REMOVE) { 19247 Slog.d(TAG, " user " + userId + " => " + installed); 19248 } 19249 if (installed != ps.getInstalled(userId)) { 19250 installedStateChanged = true; 19251 } 19252 ps.setInstalled(installed, userId); 19253 19254 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 19255 } 19256 // Regardless of writeSettings we need to ensure that this restriction 19257 // state propagation is persisted 19258 mSettings.writeAllUsersPackageRestrictionsLPr(); 19259 if (installedStateChanged) { 19260 mSettings.writeKernelMappingLPr(ps); 19261 } 19262 } 19263 // can downgrade to reader here 19264 if (writeSettings) { 19265 mSettings.writeLPr(); 19266 } 19267 } 19268 return pkg; 19269 } 19270 19271 private void deleteInstalledPackageLIF(PackageSetting ps, 19272 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 19273 PackageRemovedInfo outInfo, boolean writeSettings, 19274 PackageParser.Package replacingPackage) { 19275 synchronized (mPackages) { 19276 if (outInfo != null) { 19277 outInfo.uid = ps.appId; 19278 } 19279 19280 if (outInfo != null && outInfo.removedChildPackages != null) { 19281 final int childCount = (ps.childPackageNames != null) 19282 ? ps.childPackageNames.size() : 0; 19283 for (int i = 0; i < childCount; i++) { 19284 String childPackageName = ps.childPackageNames.get(i); 19285 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 19286 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 19287 childPackageName); 19288 if (childInfo != null) { 19289 childInfo.uid = childPs.appId; 19290 } 19291 } 19292 } 19293 } 19294 19295 // Delete package data from internal structures and also remove data if flag is set 19296 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 19297 19298 // Delete the child packages data 19299 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19300 for (int i = 0; i < childCount; i++) { 19301 PackageSetting childPs; 19302 synchronized (mPackages) { 19303 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 19304 } 19305 if (childPs != null) { 19306 PackageRemovedInfo childOutInfo = (outInfo != null 19307 && outInfo.removedChildPackages != null) 19308 ? outInfo.removedChildPackages.get(childPs.name) : null; 19309 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 19310 && (replacingPackage != null 19311 && !replacingPackage.hasChildPackage(childPs.name)) 19312 ? flags & ~DELETE_KEEP_DATA : flags; 19313 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 19314 deleteFlags, writeSettings); 19315 } 19316 } 19317 19318 // Delete application code and resources only for parent packages 19319 if (ps.parentPackageName == null) { 19320 if (deleteCodeAndResources && (outInfo != null)) { 19321 outInfo.args = createInstallArgsForExisting( 19322 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 19323 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 19324 } 19325 } 19326 } 19327 19328 @Override 19329 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 19330 int userId) { 19331 mContext.enforceCallingOrSelfPermission( 19332 android.Manifest.permission.DELETE_PACKAGES, null); 19333 synchronized (mPackages) { 19334 // Cannot block uninstall of static shared libs as they are 19335 // considered a part of the using app (emulating static linking). 19336 // Also static libs are installed always on internal storage. 19337 PackageParser.Package pkg = mPackages.get(packageName); 19338 if (pkg != null && pkg.staticSharedLibName != null) { 19339 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 19340 + " providing static shared library: " + pkg.staticSharedLibName); 19341 return false; 19342 } 19343 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 19344 mSettings.writePackageRestrictionsLPr(userId); 19345 } 19346 return true; 19347 } 19348 19349 @Override 19350 public boolean getBlockUninstallForUser(String packageName, int userId) { 19351 synchronized (mPackages) { 19352 final PackageSetting ps = mSettings.mPackages.get(packageName); 19353 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 19354 return false; 19355 } 19356 return mSettings.getBlockUninstallLPr(userId, packageName); 19357 } 19358 } 19359 19360 @Override 19361 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 19362 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 19363 synchronized (mPackages) { 19364 PackageSetting ps = mSettings.mPackages.get(packageName); 19365 if (ps == null) { 19366 Log.w(TAG, "Package doesn't exist: " + packageName); 19367 return false; 19368 } 19369 if (systemUserApp) { 19370 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19371 } else { 19372 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 19373 } 19374 mSettings.writeLPr(); 19375 } 19376 return true; 19377 } 19378 19379 private static class DeletePackageAction { 19380 public final PackageSetting deletingPs; 19381 public final PackageSetting disabledPs; 19382 public final PackageRemovedInfo outInfo; 19383 public final int flags; 19384 public final UserHandle user; 19385 19386 private DeletePackageAction(PackageSetting deletingPs, PackageSetting disabledPs, 19387 PackageRemovedInfo outInfo, int flags, UserHandle user) { 19388 this.deletingPs = deletingPs; 19389 this.disabledPs = disabledPs; 19390 this.outInfo = outInfo; 19391 this.flags = flags; 19392 this.user = user; 19393 } 19394 } 19395 19396 /** 19397 * @return a {@link DeletePackageAction} if the provided package and related state may be 19398 * deleted, {@code null} otherwise. 19399 */ 19400 @Nullable 19401 @GuardedBy("mPackages") 19402 private static DeletePackageAction mayDeletePackageLocked( 19403 PackageRemovedInfo outInfo, PackageSetting ps, @Nullable PackageSetting disabledPs, 19404 @Nullable PackageSetting[] children, int flags, UserHandle user) { 19405 if (ps == null) { 19406 return null; 19407 } 19408 if (isSystemApp(ps)) { 19409 if (ps.parentPackageName != null) { 19410 Slog.w(TAG, "Attempt to delete child system package " + ps.pkg.packageName); 19411 return null; 19412 } 19413 19414 final boolean deleteSystem = (flags & PackageManager.DELETE_SYSTEM_APP) != 0; 19415 final boolean deleteAllUsers = 19416 user == null || user.getIdentifier() == UserHandle.USER_ALL; 19417 if ((!deleteSystem || deleteAllUsers) && disabledPs == null) { 19418 Slog.w(TAG, "Attempt to delete unknown system package " + ps.pkg.packageName); 19419 return null; 19420 } 19421 // Confirmed if the system package has been updated 19422 // An updated system app can be deleted. This will also have to restore 19423 // the system pkg from system partition reader 19424 } 19425 final int parentReferenceCount = 19426 (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 19427 final int childCount = children != null ? children.length : 0; 19428 if (childCount != parentReferenceCount) { 19429 return null; 19430 } 19431 if (childCount != 0 && outInfo != null && outInfo.removedChildPackages != null) { 19432 for (PackageSetting child : children) { 19433 if (child == null || !ps.childPackageNames.contains(child.name)) { 19434 return null; 19435 } 19436 } 19437 } 19438 return new DeletePackageAction(ps, disabledPs, outInfo, flags, user); 19439 } 19440 19441 /* 19442 * This method handles package deletion in general 19443 */ 19444 private boolean deletePackageLIF(@NonNull String packageName, UserHandle user, 19445 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 19446 PackageRemovedInfo outInfo, boolean writeSettings, 19447 PackageParser.Package replacingPackage) { 19448 final DeletePackageAction action; 19449 synchronized (mPackages) { 19450 final PackageSetting ps = mSettings.mPackages.get(packageName); 19451 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps); 19452 PackageSetting[] children = mSettings.getChildSettingsLPr(ps); 19453 action = mayDeletePackageLocked(outInfo, ps, disabledPs, children, flags, user); 19454 } 19455 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 19456 if (null == action) { 19457 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: action was null"); 19458 return false; 19459 } 19460 19461 19462 try { 19463 executeDeletePackageLIF(action, packageName, deleteCodeAndResources, 19464 allUserHandles, writeSettings, replacingPackage); 19465 } catch (SystemDeleteException e) { 19466 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: system deletion failure", e); 19467 return false; 19468 } 19469 return true; 19470 } 19471 19472 private static class SystemDeleteException extends Exception { 19473 public final PackageManagerException reason; 19474 19475 private SystemDeleteException(PackageManagerException reason) { 19476 this.reason = reason; 19477 } 19478 } 19479 19480 /** Deletes a package. Only throws when install of a disabled package fails. */ 19481 private void executeDeletePackageLIF(DeletePackageAction action, 19482 String packageName, boolean deleteCodeAndResources, 19483 int[] allUserHandles, boolean writeSettings, 19484 PackageParser.Package replacingPackage) throws SystemDeleteException { 19485 final PackageSetting ps = action.deletingPs; 19486 final PackageRemovedInfo outInfo = action.outInfo; 19487 final UserHandle user = action.user; 19488 final int flags = action.flags; 19489 final boolean systemApp = isSystemApp(ps); 19490 19491 if (ps.parentPackageName != null 19492 && (!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 19493 if (DEBUG_REMOVE) { 19494 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 19495 + ((user == null) ? UserHandle.USER_ALL : user)); 19496 } 19497 final int removedUserId = (user != null) ? user.getIdentifier() 19498 : UserHandle.USER_ALL; 19499 19500 clearPackageStateForUserLIF(ps, removedUserId, outInfo, flags); 19501 synchronized (mPackages) { 19502 markPackageUninstalledForUserLPw(ps, user); 19503 scheduleWritePackageRestrictionsLocked(user); 19504 } 19505 return; 19506 } 19507 19508 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 19509 if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) { 19510 unsuspendForSuspendingPackage(packageName, userId); 19511 } 19512 if ((!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0) 19513 && userId != UserHandle.USER_ALL) { 19514 // The caller is asking that the package only be deleted for a single 19515 // user. To do this, we just mark its uninstalled state and delete 19516 // its data. If this is a system app, we only allow this to happen if 19517 // they have set the special DELETE_SYSTEM_APP which requests different 19518 // semantics than normal for uninstalling system apps. 19519 final boolean clearPackageStateAndReturn; 19520 synchronized (mPackages) { 19521 markPackageUninstalledForUserLPw(ps, user); 19522 if (!systemApp) { 19523 // Do not uninstall the APK if an app should be cached 19524 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 19525 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 19526 // Other users still have this package installed, so all 19527 // we need to do is clear this user's data and save that 19528 // it is uninstalled. 19529 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 19530 clearPackageStateAndReturn = true; 19531 } else { 19532 // We need to set it back to 'installed' so the uninstall 19533 // broadcasts will be sent correctly. 19534 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 19535 ps.setInstalled(true, userId); 19536 mSettings.writeKernelMappingLPr(ps); 19537 clearPackageStateAndReturn = false; 19538 } 19539 } else { 19540 // This is a system app, so we assume that the 19541 // other users still have this package installed, so all 19542 // we need to do is clear this user's data and save that 19543 // it is uninstalled. 19544 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 19545 clearPackageStateAndReturn = true; 19546 } 19547 } 19548 if (clearPackageStateAndReturn) { 19549 clearPackageStateForUserLIF(ps, userId, outInfo, flags); 19550 synchronized (mPackages) { 19551 scheduleWritePackageRestrictionsLocked(user); 19552 } 19553 return; 19554 } 19555 } 19556 19557 // If we are deleting a composite package for all users, keep track 19558 // of result for each child. 19559 if (ps.childPackageNames != null && outInfo != null) { 19560 synchronized (mPackages) { 19561 final int childCount = ps.childPackageNames.size(); 19562 outInfo.removedChildPackages = new ArrayMap<>(childCount); 19563 for (int i = 0; i < childCount; i++) { 19564 String childPackageName = ps.childPackageNames.get(i); 19565 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 19566 childInfo.removedPackage = childPackageName; 19567 childInfo.installerPackageName = ps.installerPackageName; 19568 outInfo.removedChildPackages.put(childPackageName, childInfo); 19569 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19570 if (childPs != null) { 19571 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 19572 } 19573 } 19574 } 19575 } 19576 19577 // TODO(b/109941548): break reasons for ret = false out into mayDelete method 19578 if (systemApp) { 19579 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 19580 // When an updated system application is deleted we delete the existing resources 19581 // as well and fall back to existing code in system partition 19582 deleteSystemPackageLIF(action, ps, allUserHandles, flags, outInfo, writeSettings); 19583 } else { 19584 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 19585 deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 19586 outInfo, writeSettings, replacingPackage); 19587 } 19588 19589 // Take a note whether we deleted the package for all users 19590 if (outInfo != null) { 19591 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 19592 if (outInfo.removedChildPackages != null) { 19593 synchronized (mPackages) { 19594 final int childCount = outInfo.removedChildPackages.size(); 19595 for (int i = 0; i < childCount; i++) { 19596 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 19597 if (childInfo != null) { 19598 childInfo.removedForAllUsers = mPackages.get( 19599 childInfo.removedPackage) == null; 19600 } 19601 } 19602 } 19603 } 19604 // If we uninstalled an update to a system app there may be some 19605 // child packages that appeared as they are declared in the system 19606 // app but were not declared in the update. 19607 if (systemApp) { 19608 synchronized (mPackages) { 19609 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 19610 final int childCount = (updatedPs.childPackageNames != null) 19611 ? updatedPs.childPackageNames.size() : 0; 19612 for (int i = 0; i < childCount; i++) { 19613 String childPackageName = updatedPs.childPackageNames.get(i); 19614 if (outInfo.removedChildPackages == null 19615 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 19616 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19617 if (childPs == null) { 19618 continue; 19619 } 19620 PackageInstalledInfo installRes = new PackageInstalledInfo(); 19621 installRes.name = childPackageName; 19622 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 19623 installRes.pkg = mPackages.get(childPackageName); 19624 installRes.uid = childPs.pkg.applicationInfo.uid; 19625 if (outInfo.appearedChildPackages == null) { 19626 outInfo.appearedChildPackages = new ArrayMap<>(); 19627 } 19628 outInfo.appearedChildPackages.put(childPackageName, installRes); 19629 } 19630 } 19631 } 19632 } 19633 } 19634 } 19635 19636 @GuardedBy("mPackages") 19637 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 19638 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 19639 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 19640 for (int nextUserId : userIds) { 19641 if (DEBUG_REMOVE) { 19642 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 19643 } 19644 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 19645 false /*installed*/, 19646 true /*stopped*/, 19647 true /*notLaunched*/, 19648 false /*hidden*/, 19649 0 /*distractionFlags*/, 19650 false /*suspended*/, 19651 null /*suspendingPackage*/, 19652 null /*dialogInfo*/, 19653 null /*suspendedAppExtras*/, 19654 null /*suspendedLauncherExtras*/, 19655 false /*instantApp*/, 19656 false /*virtualPreload*/, 19657 null /*lastDisableAppCaller*/, 19658 null /*enabledComponents*/, 19659 null /*disabledComponents*/, 19660 ps.readUserState(nextUserId).domainVerificationStatus, 19661 0, PackageManager.INSTALL_REASON_UNKNOWN, 19662 null /*harmfulAppWarning*/); 19663 } 19664 mSettings.writeKernelMappingLPr(ps); 19665 } 19666 19667 private void clearPackageStateForUserLIF(PackageSetting ps, int userId, 19668 PackageRemovedInfo outInfo, int flags) { 19669 final PackageParser.Package pkg; 19670 synchronized (mPackages) { 19671 pkg = mPackages.get(ps.name); 19672 } 19673 19674 destroyAppProfilesLIF(pkg); 19675 19676 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 19677 : new int[] {userId}; 19678 for (int nextUserId : userIds) { 19679 if (DEBUG_REMOVE) { 19680 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 19681 + nextUserId); 19682 } 19683 19684 destroyAppDataLIF(pkg, nextUserId, 19685 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 19686 clearDefaultBrowserIfNeededForUser(ps.name, nextUserId); 19687 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 19688 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 19689 clearPackagePreferredActivitiesLPw(ps.name, changedUsers, nextUserId); 19690 if (changedUsers.size() > 0) { 19691 updateDefaultHomeNotLocked(changedUsers); 19692 postPreferredActivityChangedBroadcast(nextUserId); 19693 synchronized (mPackages) { 19694 scheduleWritePackageRestrictionsLocked(nextUserId); 19695 } 19696 } 19697 synchronized (mPackages) { 19698 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 19699 } 19700 // Also delete contributed media, when requested 19701 if ((flags & PackageManager.DELETE_CONTRIBUTED_MEDIA) != 0) { 19702 try { 19703 MediaStore.deleteContributedMedia(mContext, ps.name, UserHandle.of(nextUserId)); 19704 } catch (IOException e) { 19705 Slog.w(TAG, "Failed to delete contributed media for " + ps.name, e); 19706 } 19707 } 19708 } 19709 19710 if (outInfo != null) { 19711 outInfo.removedPackage = ps.name; 19712 outInfo.installerPackageName = ps.installerPackageName; 19713 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 19714 outInfo.removedAppId = ps.appId; 19715 outInfo.removedUsers = userIds; 19716 outInfo.broadcastUsers = userIds; 19717 } 19718 } 19719 19720 @Override 19721 public void clearApplicationProfileData(String packageName) { 19722 enforceSystemOrRoot("Only the system can clear all profile data"); 19723 19724 final PackageParser.Package pkg; 19725 synchronized (mPackages) { 19726 pkg = mPackages.get(packageName); 19727 } 19728 19729 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19730 synchronized (mInstallLock) { 19731 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19732 } 19733 } 19734 } 19735 19736 @Override 19737 public void clearApplicationUserData(final String packageName, 19738 final IPackageDataObserver observer, final int userId) { 19739 mContext.enforceCallingOrSelfPermission( 19740 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19741 19742 final int callingUid = Binder.getCallingUid(); 19743 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19744 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19745 19746 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19747 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 19748 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19749 throw new SecurityException("Cannot clear data for a protected package: " 19750 + packageName); 19751 } 19752 // Queue up an async operation since the package deletion may take a little while. 19753 mHandler.post(new Runnable() { 19754 public void run() { 19755 mHandler.removeCallbacks(this); 19756 final boolean succeeded; 19757 if (!filterApp) { 19758 try (PackageFreezer freezer = freezePackage(packageName, 19759 "clearApplicationUserData")) { 19760 synchronized (mInstallLock) { 19761 succeeded = clearApplicationUserDataLIF(packageName, userId); 19762 } 19763 synchronized (mPackages) { 19764 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19765 packageName, userId); 19766 } 19767 } 19768 if (succeeded) { 19769 // invoke DeviceStorageMonitor's update method to clear any notifications 19770 DeviceStorageMonitorInternal dsm = LocalServices 19771 .getService(DeviceStorageMonitorInternal.class); 19772 if (dsm != null) { 19773 dsm.checkMemory(); 19774 } 19775 if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId) 19776 == PERMISSION_GRANTED) { 19777 unsuspendForSuspendingPackage(packageName, userId); 19778 } 19779 } 19780 } else { 19781 succeeded = false; 19782 } 19783 if (observer != null) { 19784 try { 19785 observer.onRemoveCompleted(packageName, succeeded); 19786 } catch (RemoteException e) { 19787 Log.i(TAG, "Observer no longer exists."); 19788 } 19789 } //end if observer 19790 } //end run 19791 }); 19792 } 19793 19794 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19795 if (packageName == null) { 19796 Slog.w(TAG, "Attempt to delete null packageName."); 19797 return false; 19798 } 19799 19800 // Try finding details about the requested package 19801 PackageParser.Package pkg; 19802 synchronized (mPackages) { 19803 pkg = mPackages.get(packageName); 19804 if (pkg == null) { 19805 final PackageSetting ps = mSettings.mPackages.get(packageName); 19806 if (ps != null) { 19807 pkg = ps.pkg; 19808 } 19809 } 19810 19811 if (pkg == null) { 19812 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19813 return false; 19814 } 19815 19816 PackageSetting ps = (PackageSetting) pkg.mExtras; 19817 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19818 } 19819 19820 clearAppDataLIF(pkg, userId, 19821 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 19822 19823 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19824 removeKeystoreDataIfNeeded(userId, appId); 19825 19826 UserManagerInternal umInternal = getUserManagerInternal(); 19827 final int flags; 19828 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19829 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19830 } else if (umInternal.isUserRunning(userId)) { 19831 flags = StorageManager.FLAG_STORAGE_DE; 19832 } else { 19833 flags = 0; 19834 } 19835 prepareAppDataContentsLIF(pkg, userId, flags); 19836 19837 return true; 19838 } 19839 19840 /** 19841 * Reverts user permission state changes (permissions and flags) in 19842 * all packages for a given user. 19843 * 19844 * @param userId The device user for which to do a reset. 19845 */ 19846 @GuardedBy("mPackages") 19847 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19848 final int packageCount = mPackages.size(); 19849 for (int i = 0; i < packageCount; i++) { 19850 PackageParser.Package pkg = mPackages.valueAt(i); 19851 PackageSetting ps = (PackageSetting) pkg.mExtras; 19852 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19853 } 19854 } 19855 19856 private void resetNetworkPolicies(int userId) { 19857 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19858 } 19859 19860 /** 19861 * Reverts user permission state changes (permissions and flags). 19862 * 19863 * @param ps The package for which to reset. 19864 * @param userId The device user for which to do a reset. 19865 */ 19866 @GuardedBy("mPackages") 19867 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19868 final PackageSetting ps, final int userId) { 19869 if (ps.pkg == null) { 19870 return; 19871 } 19872 19873 final String packageName = ps.pkg.packageName; 19874 19875 // These are flags that can change base on user actions. 19876 final int userSettableMask = FLAG_PERMISSION_USER_SET 19877 | FLAG_PERMISSION_USER_FIXED 19878 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19879 | FLAG_PERMISSION_REVIEW_REQUIRED; 19880 19881 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19882 | FLAG_PERMISSION_POLICY_FIXED; 19883 19884 // Delay and combine non-async permission callbacks 19885 final boolean[] permissionRemoved = new boolean[1]; 19886 final ArraySet<Long> revokedPermissions = new ArraySet<>(); 19887 final SparseBooleanArray updatedUsers = new SparseBooleanArray(); 19888 19889 PermissionCallback delayingPermCallback = new PermissionCallback() { 19890 public void onGidsChanged(int appId, int userId) { 19891 mPermissionCallback.onGidsChanged(appId, userId); 19892 } 19893 19894 public void onPermissionChanged() { 19895 mPermissionCallback.onPermissionChanged(); 19896 } 19897 19898 public void onPermissionGranted(int uid, int userId) { 19899 mPermissionCallback.onPermissionGranted(uid, userId); 19900 } 19901 19902 public void onInstallPermissionGranted() { 19903 mPermissionCallback.onInstallPermissionGranted(); 19904 } 19905 19906 public void onPermissionRevoked(int uid, int userId) { 19907 revokedPermissions.add(IntPair.of(uid, userId)); 19908 19909 updatedUsers.put(userId, true); 19910 } 19911 19912 public void onInstallPermissionRevoked() { 19913 mPermissionCallback.onInstallPermissionRevoked(); 19914 } 19915 19916 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 19917 for (int userId : updatedUserIds) { 19918 if (sync) { 19919 updatedUsers.put(userId, true); 19920 } else { 19921 // Don't override sync=true by sync=false 19922 if (!updatedUsers.get(userId)) { 19923 updatedUsers.put(userId, false); 19924 } 19925 } 19926 } 19927 } 19928 19929 public void onPermissionRemoved() { 19930 permissionRemoved[0] = true; 19931 } 19932 19933 public void onInstallPermissionUpdated() { 19934 mPermissionCallback.onInstallPermissionUpdated(); 19935 } 19936 }; 19937 19938 final int permissionCount = ps.pkg.requestedPermissions.size(); 19939 for (int i = 0; i < permissionCount; i++) { 19940 final String permName = ps.pkg.requestedPermissions.get(i); 19941 final BasePermission bp = 19942 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19943 if (bp == null) { 19944 continue; 19945 } 19946 19947 if (bp.isRemoved()) { 19948 continue; 19949 } 19950 19951 // If shared user we just reset the state to which only this app contributed. 19952 if (ps.sharedUser != null) { 19953 boolean used = false; 19954 final int packageCount = ps.sharedUser.packages.size(); 19955 for (int j = 0; j < packageCount; j++) { 19956 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19957 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19958 && pkg.pkg.requestedPermissions.contains(permName)) { 19959 used = true; 19960 break; 19961 } 19962 } 19963 if (used) { 19964 continue; 19965 } 19966 } 19967 19968 final int oldFlags = mPermissionManager.getPermissionFlags(permName, packageName, 19969 Process.SYSTEM_UID, userId); 19970 19971 // Always clear the user settable flags. 19972 // If permission review is enabled and this is a legacy app, mark the 19973 // permission as requiring a review as this is the initial state. 19974 int flags = 0; 19975 if (ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M && bp.isRuntime()) { 19976 flags |= FLAG_PERMISSION_REVIEW_REQUIRED | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19977 } 19978 19979 mPermissionManager.updatePermissionFlags(permName, packageName, 19980 userSettableMask, flags, Process.SYSTEM_UID, userId, false, 19981 delayingPermCallback); 19982 19983 // Below is only runtime permission handling. 19984 if (!bp.isRuntime()) { 19985 continue; 19986 } 19987 19988 // Never clobber system or policy. 19989 if ((oldFlags & policyOrSystemFlags) != 0) { 19990 continue; 19991 } 19992 19993 // If this permission was granted by default, make sure it is. 19994 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19995 mPermissionManager.grantRuntimePermission(permName, packageName, false, 19996 Process.SYSTEM_UID, userId, delayingPermCallback); 19997 // If permission review is enabled the permissions for a legacy apps 19998 // are represented as constantly granted runtime ones, so don't revoke. 19999 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 20000 // Otherwise, reset the permission. 20001 mPermissionManager.revokeRuntimePermission(permName, packageName, false, userId, 20002 delayingPermCallback); 20003 } 20004 } 20005 20006 // Execute delayed callbacks 20007 if (permissionRemoved[0]) { 20008 mPermissionCallback.onPermissionRemoved(); 20009 } 20010 20011 // Slight variation on the code in mPermissionCallback.onPermissionRevoked() as we cannot 20012 // kill uid while holding mPackages-lock 20013 if (!revokedPermissions.isEmpty()) { 20014 int numRevokedPermissions = revokedPermissions.size(); 20015 for (int i = 0; i < numRevokedPermissions; i++) { 20016 int revocationUID = IntPair.first(revokedPermissions.valueAt(i)); 20017 int revocationUserId = IntPair.second(revokedPermissions.valueAt(i)); 20018 20019 mOnPermissionChangeListeners.onPermissionsChanged(revocationUID); 20020 20021 // Kill app later as we are holding mPackages 20022 mHandler.post(() -> killUid(UserHandle.getAppId(revocationUID), revocationUserId, 20023 KILL_APP_REASON_PERMISSIONS_REVOKED)); 20024 } 20025 } 20026 20027 int numUpdatedUsers = updatedUsers.size(); 20028 for (int i = 0; i < numUpdatedUsers; i++) { 20029 mSettings.writeRuntimePermissionsForUserLPr(updatedUsers.keyAt(i), 20030 updatedUsers.valueAt(i)); 20031 } 20032 } 20033 20034 /** 20035 * Remove entries from the keystore daemon. Will only remove it if the 20036 * {@code appId} is valid. 20037 */ 20038 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 20039 if (appId < 0) { 20040 return; 20041 } 20042 20043 final KeyStore keyStore = KeyStore.getInstance(); 20044 if (keyStore != null) { 20045 if (userId == UserHandle.USER_ALL) { 20046 for (final int individual : sUserManager.getUserIds()) { 20047 keyStore.clearUid(UserHandle.getUid(individual, appId)); 20048 } 20049 } else { 20050 keyStore.clearUid(UserHandle.getUid(userId, appId)); 20051 } 20052 } else { 20053 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 20054 } 20055 } 20056 20057 @Override 20058 public void deleteApplicationCacheFiles(final String packageName, 20059 final IPackageDataObserver observer) { 20060 final int userId = UserHandle.getCallingUserId(); 20061 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 20062 } 20063 20064 @Override 20065 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 20066 final IPackageDataObserver observer) { 20067 final int callingUid = Binder.getCallingUid(); 20068 if (mContext.checkCallingOrSelfPermission( 20069 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 20070 != PackageManager.PERMISSION_GRANTED) { 20071 // If the caller has the old delete cache permission, silently ignore. Else throw. 20072 if (mContext.checkCallingOrSelfPermission( 20073 android.Manifest.permission.DELETE_CACHE_FILES) 20074 == PackageManager.PERMISSION_GRANTED) { 20075 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 20076 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 20077 ", silently ignoring"); 20078 return; 20079 } 20080 mContext.enforceCallingOrSelfPermission( 20081 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 20082 } 20083 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20084 /* requireFullPermission= */ true, /* checkShell= */ false, 20085 "delete application cache files"); 20086 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 20087 android.Manifest.permission.ACCESS_INSTANT_APPS); 20088 20089 final PackageParser.Package pkg; 20090 synchronized (mPackages) { 20091 pkg = mPackages.get(packageName); 20092 } 20093 20094 // Queue up an async operation since the package deletion may take a little while. 20095 mHandler.post(() -> { 20096 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 20097 boolean doClearData = true; 20098 if (ps != null) { 20099 final boolean targetIsInstantApp = 20100 ps.getInstantApp(UserHandle.getUserId(callingUid)); 20101 doClearData = !targetIsInstantApp 20102 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 20103 } 20104 if (doClearData) { 20105 synchronized (mInstallLock) { 20106 final int flags = FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL; 20107 // We're only clearing cache files, so we don't care if the 20108 // app is unfrozen and still able to run 20109 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 20110 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 20111 } 20112 } 20113 if (observer != null) { 20114 try { 20115 observer.onRemoveCompleted(packageName, true); 20116 } catch (RemoteException e) { 20117 Log.i(TAG, "Observer no longer exists."); 20118 } 20119 } 20120 }); 20121 } 20122 20123 @Override 20124 public void getPackageSizeInfo(final String packageName, int userHandle, 20125 final IPackageStatsObserver observer) { 20126 throw new UnsupportedOperationException( 20127 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 20128 } 20129 20130 @GuardedBy("mInstallLock") 20131 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 20132 final PackageSetting ps; 20133 synchronized (mPackages) { 20134 ps = mSettings.mPackages.get(packageName); 20135 if (ps == null) { 20136 Slog.w(TAG, "Failed to find settings for " + packageName); 20137 return false; 20138 } 20139 } 20140 20141 final String[] packageNames = { packageName }; 20142 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 20143 final String[] codePaths = { ps.codePathString }; 20144 20145 try { 20146 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 20147 ps.appId, ceDataInodes, codePaths, stats); 20148 20149 // For now, ignore code size of packages on system partition 20150 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 20151 stats.codeSize = 0; 20152 } 20153 20154 // External clients expect these to be tracked separately 20155 stats.dataSize -= stats.cacheSize; 20156 20157 } catch (InstallerException e) { 20158 Slog.w(TAG, String.valueOf(e)); 20159 return false; 20160 } 20161 20162 return true; 20163 } 20164 20165 @GuardedBy("mPackages") 20166 private int getUidTargetSdkVersionLockedLPr(int uid) { 20167 final int appId = UserHandle.getAppId(uid); 20168 final Object obj = mSettings.getSettingLPr(appId); 20169 if (obj instanceof SharedUserSetting) { 20170 final SharedUserSetting sus = (SharedUserSetting) obj; 20171 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 20172 final Iterator<PackageSetting> it = sus.packages.iterator(); 20173 while (it.hasNext()) { 20174 final PackageSetting ps = it.next(); 20175 if (ps.pkg != null) { 20176 int v = ps.pkg.applicationInfo.targetSdkVersion; 20177 if (v < vers) vers = v; 20178 } 20179 } 20180 return vers; 20181 } else if (obj instanceof PackageSetting) { 20182 final PackageSetting ps = (PackageSetting) obj; 20183 if (ps.pkg != null) { 20184 return ps.pkg.applicationInfo.targetSdkVersion; 20185 } 20186 } 20187 return Build.VERSION_CODES.CUR_DEVELOPMENT; 20188 } 20189 20190 @GuardedBy("mPackages") 20191 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 20192 final PackageParser.Package p = mPackages.get(packageName); 20193 if (p != null) { 20194 return p.applicationInfo.targetSdkVersion; 20195 } 20196 return Build.VERSION_CODES.CUR_DEVELOPMENT; 20197 } 20198 20199 @Override 20200 public void addPreferredActivity(IntentFilter filter, int match, 20201 ComponentName[] set, ComponentName activity, int userId) { 20202 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20203 "Adding preferred"); 20204 } 20205 20206 private void addPreferredActivityInternal(IntentFilter filter, int match, 20207 ComponentName[] set, ComponentName activity, boolean always, int userId, 20208 String opname) { 20209 // writer 20210 int callingUid = Binder.getCallingUid(); 20211 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20212 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 20213 if (mContext.checkCallingOrSelfPermission( 20214 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20215 != PackageManager.PERMISSION_GRANTED) { 20216 if (getUidTargetSdkVersionLockedLPr(callingUid) 20217 < Build.VERSION_CODES.FROYO) { 20218 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 20219 + callingUid); 20220 return; 20221 } 20222 mContext.enforceCallingOrSelfPermission( 20223 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20224 } 20225 if (filter.countActions() == 0) { 20226 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20227 return; 20228 } 20229 if (DEBUG_PREFERRED) { 20230 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 20231 + userId + ":"); 20232 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20233 } 20234 synchronized (mPackages) { 20235 final PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 20236 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 20237 scheduleWritePackageRestrictionsLocked(userId); 20238 } 20239 if (!updateDefaultHomeNotLocked(userId)) { 20240 postPreferredActivityChangedBroadcast(userId); 20241 } 20242 } 20243 20244 private void postPreferredActivityChangedBroadcast(int userId) { 20245 mHandler.post(() -> { 20246 final IActivityManager am = ActivityManager.getService(); 20247 if (am == null) { 20248 return; 20249 } 20250 20251 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 20252 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 20253 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 20254 try { 20255 am.broadcastIntent(null, intent, null, null, 20256 0, null, null, null, android.app.AppOpsManager.OP_NONE, 20257 null, false, false, userId); 20258 } catch (RemoteException e) { 20259 } 20260 }); 20261 } 20262 20263 @Override 20264 public void replacePreferredActivity(IntentFilter filter, int match, 20265 ComponentName[] set, ComponentName activity, int userId) { 20266 if (filter.countActions() != 1) { 20267 throw new IllegalArgumentException( 20268 "replacePreferredActivity expects filter to have only 1 action."); 20269 } 20270 if (filter.countDataAuthorities() != 0 20271 || filter.countDataPaths() != 0 20272 || filter.countDataSchemes() > 1 20273 || filter.countDataTypes() != 0) { 20274 throw new IllegalArgumentException( 20275 "replacePreferredActivity expects filter to have no data authorities, " + 20276 "paths, or types; and at most one scheme."); 20277 } 20278 20279 final int callingUid = Binder.getCallingUid(); 20280 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20281 true /* requireFullPermission */, false /* checkShell */, 20282 "replace preferred activity"); 20283 if (mContext.checkCallingOrSelfPermission( 20284 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20285 != PackageManager.PERMISSION_GRANTED) { 20286 synchronized (mPackages) { 20287 if (getUidTargetSdkVersionLockedLPr(callingUid) 20288 < Build.VERSION_CODES.FROYO) { 20289 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 20290 + Binder.getCallingUid()); 20291 return; 20292 } 20293 } 20294 mContext.enforceCallingOrSelfPermission( 20295 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20296 } 20297 20298 synchronized (mPackages) { 20299 final PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20300 if (pir != null) { 20301 // Get all of the existing entries that exactly match this filter. 20302 final ArrayList<PreferredActivity> existing = pir.findFilters(filter); 20303 if (existing != null && existing.size() == 1) { 20304 final PreferredActivity cur = existing.get(0); 20305 if (DEBUG_PREFERRED) { 20306 Slog.i(TAG, "Checking replace of preferred:"); 20307 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20308 if (!cur.mPref.mAlways) { 20309 Slog.i(TAG, " -- CUR; not mAlways!"); 20310 } else { 20311 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 20312 Slog.i(TAG, " -- CUR: mSet=" 20313 + Arrays.toString(cur.mPref.mSetComponents)); 20314 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 20315 Slog.i(TAG, " -- NEW: mMatch=" 20316 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 20317 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 20318 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 20319 } 20320 } 20321 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 20322 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 20323 && cur.mPref.sameSet(set)) { 20324 // Setting the preferred activity to what it happens to be already 20325 if (DEBUG_PREFERRED) { 20326 Slog.i(TAG, "Replacing with same preferred activity " 20327 + cur.mPref.mShortComponent + " for user " 20328 + userId + ":"); 20329 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20330 } 20331 return; 20332 } 20333 } 20334 if (existing != null) { 20335 if (DEBUG_PREFERRED) { 20336 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 20337 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20338 } 20339 for (int i = existing.size() - 1; i >= 0; --i) { 20340 final PreferredActivity pa = existing.get(i); 20341 if (DEBUG_PREFERRED) { 20342 Slog.i(TAG, "Removing existing preferred activity " 20343 + pa.mPref.mComponent + ":"); 20344 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 20345 } 20346 pir.removeFilter(pa); 20347 } 20348 } 20349 } 20350 } 20351 addPreferredActivityInternal(filter, match, set, activity, true, userId, 20352 "Replacing preferred"); 20353 } 20354 20355 @Override 20356 public void clearPackagePreferredActivities(String packageName) { 20357 final int callingUid = Binder.getCallingUid(); 20358 if (getInstantAppPackageName(callingUid) != null) { 20359 return; 20360 } 20361 // writer 20362 synchronized (mPackages) { 20363 PackageParser.Package pkg = mPackages.get(packageName); 20364 if (pkg == null || !isCallerSameApp(packageName, callingUid)) { 20365 if (mContext.checkCallingOrSelfPermission( 20366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 20367 != PackageManager.PERMISSION_GRANTED) { 20368 if (getUidTargetSdkVersionLockedLPr(callingUid) 20369 < Build.VERSION_CODES.FROYO) { 20370 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 20371 + callingUid); 20372 return; 20373 } 20374 mContext.enforceCallingOrSelfPermission( 20375 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20376 } 20377 } 20378 final PackageSetting ps = mSettings.getPackageLPr(packageName); 20379 if (ps != null 20380 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20381 return; 20382 } 20383 } 20384 int callingUserId = UserHandle.getCallingUserId(); 20385 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 20386 clearPackagePreferredActivitiesLPw(packageName, changedUsers, callingUserId); 20387 if (changedUsers.size() > 0) { 20388 updateDefaultHomeNotLocked(changedUsers); 20389 postPreferredActivityChangedBroadcast(callingUserId); 20390 synchronized (mPackages) { 20391 scheduleWritePackageRestrictionsLocked(callingUserId); 20392 } 20393 } 20394 } 20395 20396 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20397 @GuardedBy("mPackages") 20398 private void clearPackagePreferredActivitiesLPw(String packageName, 20399 @NonNull SparseBooleanArray outUserChanged, int userId) { 20400 ArrayList<PreferredActivity> removed = null; 20401 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 20402 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 20403 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 20404 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 20405 continue; 20406 } 20407 Iterator<PreferredActivity> it = pir.filterIterator(); 20408 while (it.hasNext()) { 20409 PreferredActivity pa = it.next(); 20410 // Mark entry for removal only if it matches the package name 20411 // and the entry is of type "always". 20412 if (packageName == null || 20413 (pa.mPref.mComponent.getPackageName().equals(packageName) 20414 && pa.mPref.mAlways)) { 20415 if (removed == null) { 20416 removed = new ArrayList<>(); 20417 } 20418 removed.add(pa); 20419 } 20420 } 20421 if (removed != null) { 20422 for (int j=0; j<removed.size(); j++) { 20423 PreferredActivity pa = removed.get(j); 20424 pir.removeFilter(pa); 20425 } 20426 outUserChanged.put(thisUserId, true); 20427 } 20428 } 20429 } 20430 20431 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20432 @GuardedBy("mPackages") 20433 private void clearIntentFilterVerificationsLPw(int userId) { 20434 final int packageCount = mPackages.size(); 20435 for (int i = 0; i < packageCount; i++) { 20436 PackageParser.Package pkg = mPackages.valueAt(i); 20437 clearIntentFilterVerificationsLPw(pkg.packageName, userId, true); 20438 } 20439 } 20440 20441 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 20442 @GuardedBy("mPackages") 20443 void clearIntentFilterVerificationsLPw(String packageName, int userId, 20444 boolean alsoResetStatus) { 20445 if (userId == UserHandle.USER_ALL) { 20446 if (mSettings.removeIntentFilterVerificationLPw(packageName, 20447 sUserManager.getUserIds())) { 20448 for (int oneUserId : sUserManager.getUserIds()) { 20449 scheduleWritePackageRestrictionsLocked(oneUserId); 20450 } 20451 } 20452 } else { 20453 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId, 20454 alsoResetStatus)) { 20455 scheduleWritePackageRestrictionsLocked(userId); 20456 } 20457 } 20458 } 20459 20460 /** Clears state for all users, and touches intent filter verification policy */ 20461 void clearDefaultBrowserIfNeeded(String packageName) { 20462 for (int oneUserId : sUserManager.getUserIds()) { 20463 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 20464 } 20465 } 20466 20467 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 20468 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 20469 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 20470 if (packageName.equals(defaultBrowserPackageName)) { 20471 setDefaultBrowserPackageName(null, userId); 20472 } 20473 } 20474 } 20475 20476 @Override 20477 public void resetApplicationPreferences(int userId) { 20478 mContext.enforceCallingOrSelfPermission( 20479 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 20480 final long identity = Binder.clearCallingIdentity(); 20481 // writer 20482 try { 20483 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 20484 clearPackagePreferredActivitiesLPw(null, changedUsers, userId); 20485 if (changedUsers.size() > 0) { 20486 postPreferredActivityChangedBroadcast(userId); 20487 } 20488 synchronized (mPackages) { 20489 mSettings.applyDefaultPreferredAppsLPw(userId); 20490 clearIntentFilterVerificationsLPw(userId); 20491 primeDomainVerificationsLPw(userId); 20492 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 20493 } 20494 updateDefaultHomeNotLocked(userId); 20495 // TODO: We have to reset the default SMS and Phone. This requires 20496 // significant refactoring to keep all default apps in the package 20497 // manager (cleaner but more work) or have the services provide 20498 // callbacks to the package manager to request a default app reset. 20499 setDefaultBrowserPackageName(null, userId); 20500 resetNetworkPolicies(userId); 20501 synchronized (mPackages) { 20502 scheduleWritePackageRestrictionsLocked(userId); 20503 } 20504 } finally { 20505 Binder.restoreCallingIdentity(identity); 20506 } 20507 } 20508 20509 @Override 20510 public int getPreferredActivities(List<IntentFilter> outFilters, 20511 List<ComponentName> outActivities, String packageName) { 20512 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20513 return 0; 20514 } 20515 int num = 0; 20516 final int userId = UserHandle.getCallingUserId(); 20517 // reader 20518 synchronized (mPackages) { 20519 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 20520 if (pir != null) { 20521 final Iterator<PreferredActivity> it = pir.filterIterator(); 20522 while (it.hasNext()) { 20523 final PreferredActivity pa = it.next(); 20524 if (packageName == null 20525 || (pa.mPref.mComponent.getPackageName().equals(packageName) 20526 && pa.mPref.mAlways)) { 20527 if (outFilters != null) { 20528 outFilters.add(new IntentFilter(pa)); 20529 } 20530 if (outActivities != null) { 20531 outActivities.add(pa.mPref.mComponent); 20532 } 20533 } 20534 } 20535 } 20536 } 20537 20538 return num; 20539 } 20540 20541 @Override 20542 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 20543 int userId) { 20544 int callingUid = Binder.getCallingUid(); 20545 if (callingUid != Process.SYSTEM_UID) { 20546 throw new SecurityException( 20547 "addPersistentPreferredActivity can only be run by the system"); 20548 } 20549 if (filter.countActions() == 0) { 20550 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 20551 return; 20552 } 20553 if (DEBUG_PREFERRED) { 20554 Slog.i(TAG, "Adding persistent preferred activity " + activity 20555 + " for user " + userId + ":"); 20556 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 20557 } 20558 synchronized (mPackages) { 20559 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 20560 new PersistentPreferredActivity(filter, activity)); 20561 scheduleWritePackageRestrictionsLocked(userId); 20562 } 20563 updateDefaultHomeNotLocked(userId); 20564 postPreferredActivityChangedBroadcast(userId); 20565 } 20566 20567 @Override 20568 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 20569 int callingUid = Binder.getCallingUid(); 20570 if (callingUid != Process.SYSTEM_UID) { 20571 throw new SecurityException( 20572 "clearPackagePersistentPreferredActivities can only be run by the system"); 20573 } 20574 ArrayList<PersistentPreferredActivity> removed = null; 20575 boolean changed = false; 20576 synchronized (mPackages) { 20577 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 20578 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 20579 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 20580 .valueAt(i); 20581 if (userId != thisUserId) { 20582 continue; 20583 } 20584 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 20585 while (it.hasNext()) { 20586 PersistentPreferredActivity ppa = it.next(); 20587 // Mark entry for removal only if it matches the package name. 20588 if (ppa.mComponent.getPackageName().equals(packageName)) { 20589 if (removed == null) { 20590 removed = new ArrayList<>(); 20591 } 20592 removed.add(ppa); 20593 } 20594 } 20595 if (removed != null) { 20596 for (int j=0; j<removed.size(); j++) { 20597 PersistentPreferredActivity ppa = removed.get(j); 20598 ppir.removeFilter(ppa); 20599 } 20600 changed = true; 20601 } 20602 } 20603 } 20604 if (changed) { 20605 updateDefaultHomeNotLocked(userId); 20606 postPreferredActivityChangedBroadcast(userId); 20607 synchronized (mPackages) { 20608 scheduleWritePackageRestrictionsLocked(userId); 20609 } 20610 } 20611 } 20612 20613 /** 20614 * Common machinery for picking apart a restored XML blob and passing 20615 * it to a caller-supplied functor to be applied to the running system. 20616 */ 20617 private void restoreFromXml(XmlPullParser parser, int userId, 20618 String expectedStartTag, BlobXmlRestorer functor) 20619 throws IOException, XmlPullParserException { 20620 int type; 20621 while ((type = parser.next()) != XmlPullParser.START_TAG 20622 && type != XmlPullParser.END_DOCUMENT) { 20623 } 20624 if (type != XmlPullParser.START_TAG) { 20625 // oops didn't find a start tag?! 20626 if (DEBUG_BACKUP) { 20627 Slog.e(TAG, "Didn't find start tag during restore"); 20628 } 20629 return; 20630 } 20631 // this is supposed to be TAG_PREFERRED_BACKUP 20632 if (!expectedStartTag.equals(parser.getName())) { 20633 if (DEBUG_BACKUP) { 20634 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 20635 } 20636 return; 20637 } 20638 20639 // skip interfering stuff, then we're aligned with the backing implementation 20640 while ((type = parser.next()) == XmlPullParser.TEXT) { } 20641 functor.apply(parser, userId); 20642 } 20643 20644 private interface BlobXmlRestorer { 20645 void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 20646 } 20647 20648 /** 20649 * Non-Binder method, support for the backup/restore mechanism: write the 20650 * full set of preferred activities in its canonical XML format. Returns the 20651 * XML output as a byte array, or null if there is none. 20652 */ 20653 @Override 20654 public byte[] getPreferredActivityBackup(int userId) { 20655 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20656 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 20657 } 20658 20659 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20660 try { 20661 final XmlSerializer serializer = new FastXmlSerializer(); 20662 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20663 serializer.startDocument(null, true); 20664 serializer.startTag(null, TAG_PREFERRED_BACKUP); 20665 20666 synchronized (mPackages) { 20667 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 20668 } 20669 20670 serializer.endTag(null, TAG_PREFERRED_BACKUP); 20671 serializer.endDocument(); 20672 serializer.flush(); 20673 } catch (Exception e) { 20674 if (DEBUG_BACKUP) { 20675 Slog.e(TAG, "Unable to write preferred activities for backup", e); 20676 } 20677 return null; 20678 } 20679 20680 return dataStream.toByteArray(); 20681 } 20682 20683 @Override 20684 public void restorePreferredActivities(byte[] backup, int userId) { 20685 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20686 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20687 } 20688 20689 try { 20690 final XmlPullParser parser = Xml.newPullParser(); 20691 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20692 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 20693 (readParser, readUserId) -> { 20694 synchronized (mPackages) { 20695 mSettings.readPreferredActivitiesLPw(readParser, readUserId); 20696 } 20697 updateDefaultHomeNotLocked(readUserId); 20698 }); 20699 } catch (Exception e) { 20700 if (DEBUG_BACKUP) { 20701 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20702 } 20703 } 20704 } 20705 20706 /** 20707 * Non-Binder method, support for the backup/restore mechanism: write the 20708 * default browser (etc) settings in its canonical XML format. Returns the default 20709 * browser XML representation as a byte array, or null if there is none. 20710 */ 20711 @Override 20712 public byte[] getDefaultAppsBackup(int userId) { 20713 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20714 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 20715 } 20716 20717 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20718 try { 20719 final XmlSerializer serializer = new FastXmlSerializer(); 20720 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20721 serializer.startDocument(null, true); 20722 serializer.startTag(null, TAG_DEFAULT_APPS); 20723 20724 synchronized (mPackages) { 20725 mSettings.writeDefaultAppsLPr(serializer, userId); 20726 } 20727 20728 serializer.endTag(null, TAG_DEFAULT_APPS); 20729 serializer.endDocument(); 20730 serializer.flush(); 20731 } catch (Exception e) { 20732 if (DEBUG_BACKUP) { 20733 Slog.e(TAG, "Unable to write default apps for backup", e); 20734 } 20735 return null; 20736 } 20737 20738 return dataStream.toByteArray(); 20739 } 20740 20741 @Override 20742 public void restoreDefaultApps(byte[] backup, int userId) { 20743 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20744 throw new SecurityException("Only the system may call restoreDefaultApps()"); 20745 } 20746 20747 try { 20748 final XmlPullParser parser = Xml.newPullParser(); 20749 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20750 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 20751 (parser1, userId1) -> { 20752 String defaultBrowser; 20753 synchronized (mPackages) { 20754 mSettings.readDefaultAppsLPw(parser1, userId1); 20755 defaultBrowser = mSettings.removeDefaultBrowserPackageNameLPw(userId1); 20756 } 20757 if (defaultBrowser != null) { 20758 PackageManagerInternal.DefaultBrowserProvider provider; 20759 synchronized (mPackages) { 20760 provider = mDefaultBrowserProvider; 20761 } 20762 provider.setDefaultBrowser(defaultBrowser, userId1); 20763 } 20764 }); 20765 } catch (Exception e) { 20766 if (DEBUG_BACKUP) { 20767 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 20768 } 20769 } 20770 } 20771 20772 @Override 20773 public byte[] getIntentFilterVerificationBackup(int userId) { 20774 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20775 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20776 } 20777 20778 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20779 try { 20780 final XmlSerializer serializer = new FastXmlSerializer(); 20781 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20782 serializer.startDocument(null, true); 20783 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20784 20785 synchronized (mPackages) { 20786 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20787 } 20788 20789 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20790 serializer.endDocument(); 20791 serializer.flush(); 20792 } catch (Exception e) { 20793 if (DEBUG_BACKUP) { 20794 Slog.e(TAG, "Unable to write default apps for backup", e); 20795 } 20796 return null; 20797 } 20798 20799 return dataStream.toByteArray(); 20800 } 20801 20802 @Override 20803 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20804 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20805 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20806 } 20807 20808 try { 20809 final XmlPullParser parser = Xml.newPullParser(); 20810 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20811 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20812 (parser1, userId1) -> { 20813 synchronized (mPackages) { 20814 mSettings.readAllDomainVerificationsLPr(parser1, userId1); 20815 mSettings.writeLPr(); 20816 } 20817 }); 20818 } catch (Exception e) { 20819 if (DEBUG_BACKUP) { 20820 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20821 } 20822 } 20823 } 20824 20825 @Override 20826 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20827 int sourceUserId, int targetUserId, int flags) { 20828 mContext.enforceCallingOrSelfPermission( 20829 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20830 int callingUid = Binder.getCallingUid(); 20831 enforceOwnerRights(ownerPackage, callingUid); 20832 PackageManagerServiceUtils.enforceShellRestriction( 20833 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20834 if (intentFilter.countActions() == 0) { 20835 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20836 return; 20837 } 20838 synchronized (mPackages) { 20839 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20840 ownerPackage, targetUserId, flags); 20841 CrossProfileIntentResolver resolver = 20842 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20843 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20844 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20845 if (existing != null) { 20846 int size = existing.size(); 20847 for (int i = 0; i < size; i++) { 20848 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20849 return; 20850 } 20851 } 20852 } 20853 resolver.addFilter(newFilter); 20854 scheduleWritePackageRestrictionsLocked(sourceUserId); 20855 } 20856 } 20857 20858 @Override 20859 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20860 mContext.enforceCallingOrSelfPermission( 20861 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20862 final int callingUid = Binder.getCallingUid(); 20863 enforceOwnerRights(ownerPackage, callingUid); 20864 PackageManagerServiceUtils.enforceShellRestriction( 20865 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20866 synchronized (mPackages) { 20867 CrossProfileIntentResolver resolver = 20868 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20869 ArraySet<CrossProfileIntentFilter> set = 20870 new ArraySet<>(resolver.filterSet()); 20871 for (CrossProfileIntentFilter filter : set) { 20872 if (filter.getOwnerPackage().equals(ownerPackage)) { 20873 resolver.removeFilter(filter); 20874 } 20875 } 20876 scheduleWritePackageRestrictionsLocked(sourceUserId); 20877 } 20878 } 20879 20880 // Enforcing that callingUid is owning pkg on userId 20881 private void enforceOwnerRights(String pkg, int callingUid) { 20882 // The system owns everything. 20883 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20884 return; 20885 } 20886 final int callingUserId = UserHandle.getUserId(callingUid); 20887 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20888 if (pi == null) { 20889 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20890 + callingUserId); 20891 } 20892 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20893 throw new SecurityException("Calling uid " + callingUid 20894 + " does not own package " + pkg); 20895 } 20896 } 20897 20898 @Override 20899 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20900 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20901 return null; 20902 } 20903 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20904 } 20905 20906 /** 20907 * Send a {@code PackageInstaller.ACTION_SESSION_UPDATED} broadcast intent, containing 20908 * the {@code sessionInfo} in the extra field {@code PackageInstaller.EXTRA_SESSION}. 20909 */ 20910 public void sendSessionUpdatedBroadcast(PackageInstaller.SessionInfo sessionInfo, 20911 int userId) { 20912 if (TextUtils.isEmpty(sessionInfo.installerPackageName)) { 20913 return; 20914 } 20915 Intent sessionUpdatedIntent = new Intent(PackageInstaller.ACTION_SESSION_UPDATED) 20916 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20917 .setPackage(sessionInfo.installerPackageName); 20918 mContext.sendBroadcastAsUser(sessionUpdatedIntent, UserHandle.of(userId)); 20919 } 20920 20921 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20922 UserManagerService ums = UserManagerService.getInstance(); 20923 if (ums != null) { 20924 final UserInfo parent = ums.getProfileParent(userId); 20925 final int launcherUid = (parent != null) ? parent.id : userId; 20926 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20927 if (launcherComponent != null) { 20928 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20929 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20930 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20931 .setPackage(launcherComponent.getPackageName()); 20932 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20933 } 20934 // TODO(b/122900055) Change/Remove this and replace with new permission role. 20935 if (mAppPredictionServicePackage != null) { 20936 Intent predictorIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20937 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20938 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20939 .setPackage(mAppPredictionServicePackage); 20940 mContext.sendBroadcastAsUser(predictorIntent, UserHandle.of(launcherUid)); 20941 } 20942 } 20943 } 20944 20945 /** 20946 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20947 * then reports the most likely home activity or null if there are more than one. 20948 */ 20949 private ComponentName getDefaultHomeActivity(int userId) { 20950 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20951 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20952 if (cn != null) { 20953 return cn; 20954 } 20955 20956 // Find the launcher with the highest priority and return that component if there are no 20957 // other home activity with the same priority. 20958 int lastPriority = Integer.MIN_VALUE; 20959 ComponentName lastComponent = null; 20960 final int size = allHomeCandidates.size(); 20961 for (int i = 0; i < size; i++) { 20962 final ResolveInfo ri = allHomeCandidates.get(i); 20963 if (ri.priority > lastPriority) { 20964 lastComponent = ri.activityInfo.getComponentName(); 20965 lastPriority = ri.priority; 20966 } else if (ri.priority == lastPriority) { 20967 // Two components found with same priority. 20968 lastComponent = null; 20969 } 20970 } 20971 return lastComponent; 20972 } 20973 20974 private Intent getHomeIntent() { 20975 Intent intent = new Intent(Intent.ACTION_MAIN); 20976 intent.addCategory(Intent.CATEGORY_HOME); 20977 intent.addCategory(Intent.CATEGORY_DEFAULT); 20978 return intent; 20979 } 20980 20981 private IntentFilter getHomeFilter() { 20982 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20983 filter.addCategory(Intent.CATEGORY_HOME); 20984 filter.addCategory(Intent.CATEGORY_DEFAULT); 20985 return filter; 20986 } 20987 20988 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20989 int userId) { 20990 Intent intent = getHomeIntent(); 20991 List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null, 20992 PackageManager.GET_META_DATA, userId); 20993 allHomeCandidates.clear(); 20994 if (resolveInfos == null) { 20995 return null; 20996 } 20997 allHomeCandidates.addAll(resolveInfos); 20998 20999 PackageManagerInternal.DefaultHomeProvider provider; 21000 synchronized (mPackages) { 21001 provider = mDefaultHomeProvider; 21002 } 21003 if (provider == null) { 21004 Slog.e(TAG, "mDefaultHomeProvider is null"); 21005 return null; 21006 } 21007 String packageName = provider.getDefaultHome(userId); 21008 if (packageName == null) { 21009 return null; 21010 } 21011 int resolveInfosSize = resolveInfos.size(); 21012 for (int i = 0; i < resolveInfosSize; i++) { 21013 ResolveInfo resolveInfo = resolveInfos.get(i); 21014 21015 if (resolveInfo.activityInfo != null && TextUtils.equals( 21016 resolveInfo.activityInfo.packageName, packageName)) { 21017 return new ComponentName(resolveInfo.activityInfo.packageName, 21018 resolveInfo.activityInfo.name); 21019 } 21020 } 21021 return null; 21022 } 21023 21024 /** <b>must not hold {@link #mPackages}</b> */ 21025 private void updateDefaultHomeNotLocked(SparseBooleanArray userIds) { 21026 if (Thread.holdsLock(mPackages)) { 21027 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 21028 + " is holding mPackages", new Throwable()); 21029 } 21030 for (int i = userIds.size() - 1; i >= 0; --i) { 21031 final int userId = userIds.keyAt(i); 21032 updateDefaultHomeNotLocked(userId); 21033 } 21034 } 21035 21036 /** 21037 * <b>must not hold {@link #mPackages}</b> 21038 * 21039 * @return Whether the ACTION_PREFERRED_ACTIVITY_CHANGED broadcast has been scheduled. 21040 */ 21041 private boolean updateDefaultHomeNotLocked(int userId) { 21042 if (Thread.holdsLock(mPackages)) { 21043 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 21044 + " is holding mPackages", new Throwable()); 21045 } 21046 if (!mSystemReady) { 21047 // We might get called before system is ready because of package changes etc, but 21048 // finding preferred activity depends on settings provider, so we ignore the update 21049 // before that. 21050 return false; 21051 } 21052 final Intent intent = getHomeIntent(); 21053 final List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null, 21054 PackageManager.GET_META_DATA, userId); 21055 final ResolveInfo preferredResolveInfo = findPreferredActivityNotLocked( 21056 intent, null, 0, resolveInfos, 0, true, false, false, userId); 21057 final String packageName = preferredResolveInfo != null 21058 && preferredResolveInfo.activityInfo != null 21059 ? preferredResolveInfo.activityInfo.packageName : null; 21060 final PackageManagerInternal.DefaultHomeProvider provider; 21061 synchronized (mPackages) { 21062 provider = mDefaultHomeProvider; 21063 } 21064 if (provider == null) { 21065 Slog.e(TAG, "Default home provider has not been set"); 21066 return false; 21067 } 21068 final String currentPackageName = provider.getDefaultHome(userId); 21069 if (TextUtils.equals(currentPackageName, packageName)) { 21070 return false; 21071 } 21072 final String[] callingPackages = getPackagesForUid(Binder.getCallingUid()); 21073 if (callingPackages != null && ArrayUtils.contains(callingPackages, 21074 mRequiredPermissionControllerPackage)) { 21075 // PermissionController manages default home directly. 21076 return false; 21077 } 21078 provider.setDefaultHomeAsync(packageName, userId, (successful) -> { 21079 if (successful) { 21080 postPreferredActivityChangedBroadcast(userId); 21081 } 21082 }); 21083 return true; 21084 } 21085 21086 @Override 21087 public void setHomeActivity(ComponentName comp, int userId) { 21088 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21089 return; 21090 } 21091 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 21092 getHomeActivitiesAsUser(homeActivities, userId); 21093 21094 boolean found = false; 21095 21096 final int size = homeActivities.size(); 21097 final ComponentName[] set = new ComponentName[size]; 21098 for (int i = 0; i < size; i++) { 21099 final ResolveInfo candidate = homeActivities.get(i); 21100 final ActivityInfo info = candidate.activityInfo; 21101 final ComponentName activityName = new ComponentName(info.packageName, info.name); 21102 set[i] = activityName; 21103 if (!found && activityName.equals(comp)) { 21104 found = true; 21105 } 21106 } 21107 if (!found) { 21108 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 21109 + userId); 21110 } 21111 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 21112 set, comp, userId); 21113 } 21114 21115 private @Nullable String getSetupWizardPackageName() { 21116 final Intent intent = new Intent(Intent.ACTION_MAIN); 21117 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 21118 21119 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21120 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21121 | MATCH_DISABLED_COMPONENTS, 21122 UserHandle.myUserId()); 21123 if (matches.size() == 1) { 21124 return matches.get(0).getComponentInfo().packageName; 21125 } else { 21126 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 21127 + ": matches=" + matches); 21128 return null; 21129 } 21130 } 21131 21132 private @Nullable String getStorageManagerPackageName() { 21133 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 21134 21135 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 21136 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21137 | MATCH_DISABLED_COMPONENTS, 21138 UserHandle.myUserId()); 21139 if (matches.size() == 1) { 21140 return matches.get(0).getComponentInfo().packageName; 21141 } else { 21142 Slog.e(TAG, "There should probably be exactly one storage manager; found " 21143 + matches.size() + ": matches=" + matches); 21144 return null; 21145 } 21146 } 21147 21148 @Override 21149 public String getSystemTextClassifierPackageName() { 21150 return ensureSystemPackageName(mContext.getString( 21151 R.string.config_defaultTextClassifierPackage)); 21152 } 21153 21154 @Override 21155 public @Nullable String getAttentionServicePackageName() { 21156 final String flattenedComponentName = 21157 mContext.getString(R.string.config_defaultAttentionService); 21158 if (flattenedComponentName != null) { 21159 ComponentName componentName = ComponentName.unflattenFromString(flattenedComponentName); 21160 if (componentName != null && componentName.getPackageName() != null) { 21161 return ensureSystemPackageName(componentName.getPackageName()); 21162 } 21163 } 21164 return null; 21165 } 21166 21167 private @Nullable String getDocumenterPackageName() { 21168 final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 21169 intent.addCategory(Intent.CATEGORY_OPENABLE); 21170 intent.setType("*/*"); 21171 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 21172 21173 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, resolvedType, 21174 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 21175 | MATCH_DISABLED_COMPONENTS, 21176 UserHandle.myUserId()); 21177 if (matches.size() == 1) { 21178 return matches.get(0).getComponentInfo().packageName; 21179 } else { 21180 Slog.e(TAG, "There should probably be exactly one documenter; found " 21181 + matches.size() + ": matches=" + matches); 21182 return null; 21183 } 21184 } 21185 21186 @Nullable 21187 private String getDeviceConfiguratorPackageName() { 21188 return ensureSystemPackageName(mContext.getString( 21189 R.string.config_deviceConfiguratorPackageName)); 21190 } 21191 21192 @Override 21193 public String getWellbeingPackageName() { 21194 return ensureSystemPackageName(mContext.getString(R.string.config_defaultWellbeingPackage)); 21195 } 21196 21197 @Override 21198 public String getAppPredictionServicePackageName() { 21199 String flattenedAppPredictionServiceComponentName = 21200 mContext.getString(R.string.config_defaultAppPredictionService); 21201 if (flattenedAppPredictionServiceComponentName == null) { 21202 return null; 21203 } 21204 ComponentName appPredictionServiceComponentName = 21205 ComponentName.unflattenFromString(flattenedAppPredictionServiceComponentName); 21206 if (appPredictionServiceComponentName == null) { 21207 return null; 21208 } 21209 return ensureSystemPackageName(appPredictionServiceComponentName.getPackageName()); 21210 } 21211 21212 @Override 21213 public String getSystemCaptionsServicePackageName() { 21214 String flattenedSystemCaptionsServiceComponentName = 21215 mContext.getString(R.string.config_defaultSystemCaptionsService); 21216 21217 if (TextUtils.isEmpty(flattenedSystemCaptionsServiceComponentName)) { 21218 return null; 21219 } 21220 21221 ComponentName systemCaptionsServiceComponentName = 21222 ComponentName.unflattenFromString(flattenedSystemCaptionsServiceComponentName); 21223 if (systemCaptionsServiceComponentName == null) { 21224 return null; 21225 } 21226 return ensureSystemPackageName(systemCaptionsServiceComponentName.getPackageName()); 21227 } 21228 21229 public String getIncidentReportApproverPackageName() { 21230 return ensureSystemPackageName(mContext.getString( 21231 R.string.config_incidentReportApproverPackage)); 21232 } 21233 21234 @Nullable 21235 private String ensureSystemPackageName(@Nullable String packageName) { 21236 if (packageName == null) { 21237 return null; 21238 } 21239 long token = Binder.clearCallingIdentity(); 21240 try { 21241 if (getPackageInfo(packageName, MATCH_FACTORY_ONLY, UserHandle.USER_SYSTEM) == null) { 21242 PackageInfo packageInfo = getPackageInfo(packageName, 0, UserHandle.USER_SYSTEM); 21243 if (packageInfo != null) { 21244 EventLog.writeEvent(0x534e4554, "145981139", packageInfo.applicationInfo.uid, 21245 ""); 21246 } 21247 return null; 21248 } 21249 } finally { 21250 Binder.restoreCallingIdentity(token); 21251 } 21252 return packageName; 21253 } 21254 21255 @Override 21256 public void setApplicationEnabledSetting(String appPackageName, 21257 int newState, int flags, int userId, String callingPackage) { 21258 if (!sUserManager.exists(userId)) return; 21259 if (callingPackage == null) { 21260 callingPackage = Integer.toString(Binder.getCallingUid()); 21261 } 21262 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 21263 } 21264 21265 @Override 21266 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 21267 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 21268 synchronized (mPackages) { 21269 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 21270 if (pkgSetting != null) { 21271 pkgSetting.setUpdateAvailable(updateAvailable); 21272 } 21273 } 21274 } 21275 21276 @Override 21277 public void setComponentEnabledSetting(ComponentName componentName, 21278 int newState, int flags, int userId) { 21279 if (!sUserManager.exists(userId)) return; 21280 setEnabledSetting(componentName.getPackageName(), 21281 componentName.getClassName(), newState, flags, userId, null); 21282 } 21283 21284 private void setEnabledSetting(final String packageName, String className, int newState, 21285 final int flags, int userId, String callingPackage) { 21286 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 21287 || newState == COMPONENT_ENABLED_STATE_ENABLED 21288 || newState == COMPONENT_ENABLED_STATE_DISABLED 21289 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21290 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 21291 throw new IllegalArgumentException("Invalid new component state: " 21292 + newState); 21293 } 21294 PackageSetting pkgSetting; 21295 final int callingUid = Binder.getCallingUid(); 21296 final int permission; 21297 if (callingUid == Process.SYSTEM_UID) { 21298 permission = PackageManager.PERMISSION_GRANTED; 21299 } else { 21300 permission = mContext.checkCallingOrSelfPermission( 21301 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21302 } 21303 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21304 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 21305 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21306 boolean sendNow = false; 21307 boolean isApp = (className == null); 21308 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 21309 String componentName = isApp ? packageName : className; 21310 ArrayList<String> components; 21311 21312 // reader 21313 synchronized (mPackages) { 21314 pkgSetting = mSettings.mPackages.get(packageName); 21315 if (pkgSetting == null) { 21316 if (!isCallerInstantApp) { 21317 if (className == null) { 21318 throw new IllegalArgumentException("Unknown package: " + packageName); 21319 } 21320 throw new IllegalArgumentException( 21321 "Unknown component: " + packageName + "/" + className); 21322 } else { 21323 // throw SecurityException to prevent leaking package information 21324 throw new SecurityException( 21325 "Attempt to change component state; " 21326 + "pid=" + Binder.getCallingPid() 21327 + ", uid=" + callingUid 21328 + (className == null 21329 ? ", package=" + packageName 21330 : ", component=" + packageName + "/" + className)); 21331 } 21332 } 21333 } 21334 21335 // Limit who can change which apps 21336 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 21337 // Don't allow apps that don't have permission to modify other apps 21338 if (!allowedByPermission 21339 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 21340 throw new SecurityException( 21341 "Attempt to change component state; " 21342 + "pid=" + Binder.getCallingPid() 21343 + ", uid=" + callingUid 21344 + (className == null 21345 ? ", package=" + packageName 21346 : ", component=" + packageName + "/" + className)); 21347 } 21348 // Don't allow changing protected packages. 21349 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 21350 throw new SecurityException("Cannot disable a protected package: " + packageName); 21351 } 21352 } 21353 // Only allow apps with CHANGE_COMPONENT_ENABLED_STATE permission to change hidden 21354 // app details activity 21355 if (PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME.equals(className) 21356 && !allowedByPermission) { 21357 throw new SecurityException("Cannot disable a system-generated component"); 21358 } 21359 21360 synchronized (mPackages) { 21361 if (callingUid == Process.SHELL_UID 21362 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 21363 // Shell can only change whole packages between ENABLED and DISABLED_USER states 21364 // unless it is a test package. 21365 int oldState = pkgSetting.getEnabled(userId); 21366 if (className == null 21367 && 21368 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 21369 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 21370 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 21371 && 21372 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 21373 || newState == COMPONENT_ENABLED_STATE_DEFAULT 21374 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 21375 // ok 21376 } else { 21377 throw new SecurityException( 21378 "Shell cannot change component state for " + packageName + "/" 21379 + className + " to " + newState); 21380 } 21381 } 21382 } 21383 if (className == null) { 21384 // We're dealing with an application/package level state change 21385 synchronized (mPackages) { 21386 if (pkgSetting.getEnabled(userId) == newState) { 21387 // Nothing to do 21388 return; 21389 } 21390 } 21391 // If we're enabling a system stub, there's a little more work to do. 21392 // Prior to enabling the package, we need to decompress the APK(s) to the 21393 // data partition and then replace the version on the system partition. 21394 final PackageParser.Package deletedPkg = pkgSetting.pkg; 21395 final boolean isSystemStub = deletedPkg.isStub 21396 && deletedPkg.isSystem(); 21397 if (isSystemStub 21398 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 21399 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 21400 if (!enableCompressedPackage(deletedPkg)) { 21401 return; 21402 } 21403 } 21404 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 21405 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 21406 // Don't care about who enables an app. 21407 callingPackage = null; 21408 } 21409 synchronized (mPackages) { 21410 pkgSetting.setEnabled(newState, userId, callingPackage); 21411 } 21412 } else { 21413 synchronized (mPackages) { 21414 // We're dealing with a component level state change 21415 // First, verify that this is a valid class name. 21416 PackageParser.Package pkg = pkgSetting.pkg; 21417 if (pkg == null || !pkg.hasComponentClassName(className)) { 21418 if (pkg != null && 21419 pkg.applicationInfo.targetSdkVersion >= 21420 Build.VERSION_CODES.JELLY_BEAN) { 21421 throw new IllegalArgumentException("Component class " + className 21422 + " does not exist in " + packageName); 21423 } else { 21424 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 21425 + className + " does not exist in " + packageName); 21426 } 21427 } 21428 switch (newState) { 21429 case COMPONENT_ENABLED_STATE_ENABLED: 21430 if (!pkgSetting.enableComponentLPw(className, userId)) { 21431 return; 21432 } 21433 break; 21434 case COMPONENT_ENABLED_STATE_DISABLED: 21435 if (!pkgSetting.disableComponentLPw(className, userId)) { 21436 return; 21437 } 21438 break; 21439 case COMPONENT_ENABLED_STATE_DEFAULT: 21440 if (!pkgSetting.restoreComponentLPw(className, userId)) { 21441 return; 21442 } 21443 break; 21444 default: 21445 Slog.e(TAG, "Invalid new component state: " + newState); 21446 return; 21447 } 21448 } 21449 } 21450 synchronized (mPackages) { 21451 scheduleWritePackageRestrictionsLocked(userId); 21452 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 21453 final long callingId = Binder.clearCallingIdentity(); 21454 try { 21455 updateInstantAppInstallerLocked(packageName); 21456 } finally { 21457 Binder.restoreCallingIdentity(callingId); 21458 } 21459 components = mPendingBroadcasts.get(userId, packageName); 21460 final boolean newPackage = components == null; 21461 if (newPackage) { 21462 components = new ArrayList<>(); 21463 } 21464 if (!components.contains(componentName)) { 21465 components.add(componentName); 21466 } 21467 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 21468 sendNow = true; 21469 // Purge entry from pending broadcast list if another one exists already 21470 // since we are sending one right away. 21471 mPendingBroadcasts.remove(userId, packageName); 21472 } else { 21473 if (newPackage) { 21474 mPendingBroadcasts.put(userId, packageName, components); 21475 } 21476 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 21477 // Schedule a message - if it has been a "reasonably long time" since the 21478 // service started, send the broadcast with a delay of one second to avoid 21479 // delayed reactions from the receiver, else keep the default ten second delay 21480 // to avoid extreme thrashing on service startup. 21481 final long broadcastDelay = SystemClock.uptimeMillis() > mServiceStartWithDelay 21482 ? BROADCAST_DELAY 21483 : BROADCAST_DELAY_DURING_STARTUP; 21484 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, broadcastDelay); 21485 } 21486 } 21487 } 21488 21489 long callingId = Binder.clearCallingIdentity(); 21490 try { 21491 if (sendNow) { 21492 int packageUid = UserHandle.getUid(userId, pkgSetting.appId); 21493 sendPackageChangedBroadcast(packageName, 21494 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 21495 } 21496 } finally { 21497 Binder.restoreCallingIdentity(callingId); 21498 } 21499 } 21500 21501 @Override 21502 public void flushPackageRestrictionsAsUser(int userId) { 21503 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 21504 return; 21505 } 21506 if (!sUserManager.exists(userId)) { 21507 return; 21508 } 21509 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 21510 false /* checkShell */, "flushPackageRestrictions"); 21511 synchronized (mPackages) { 21512 mSettings.writePackageRestrictionsLPr(userId); 21513 mDirtyUsers.remove(userId); 21514 if (mDirtyUsers.isEmpty()) { 21515 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 21516 } 21517 } 21518 } 21519 21520 private void sendPackageChangedBroadcast(String packageName, 21521 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 21522 if (DEBUG_INSTALL) 21523 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 21524 + componentNames); 21525 Bundle extras = new Bundle(4); 21526 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 21527 String nameList[] = new String[componentNames.size()]; 21528 componentNames.toArray(nameList); 21529 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 21530 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 21531 extras.putInt(Intent.EXTRA_UID, packageUid); 21532 // If this is not reporting a change of the overall package, then only send it 21533 // to registered receivers. We don't want to launch a swath of apps for every 21534 // little component state change. 21535 final int flags = !componentNames.contains(packageName) 21536 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 21537 final int userId = UserHandle.getUserId(packageUid); 21538 final boolean isInstantApp = isInstantApp(packageName, userId); 21539 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 21540 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 21541 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 21542 userIds, instantUserIds); 21543 } 21544 21545 @Override 21546 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 21547 if (!sUserManager.exists(userId)) return; 21548 final int callingUid = Binder.getCallingUid(); 21549 if (getInstantAppPackageName(callingUid) != null) { 21550 return; 21551 } 21552 final int permission = mContext.checkCallingOrSelfPermission( 21553 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 21554 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 21555 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21556 true /* requireFullPermission */, true /* checkShell */, "stop package"); 21557 // writer 21558 synchronized (mPackages) { 21559 final PackageSetting ps = mSettings.mPackages.get(packageName); 21560 if (!filterAppAccessLPr(ps, callingUid, userId) 21561 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 21562 allowedByPermission, callingUid, userId)) { 21563 scheduleWritePackageRestrictionsLocked(userId); 21564 } 21565 } 21566 } 21567 21568 @Override 21569 public String getInstallerPackageName(String packageName) { 21570 final int callingUid = Binder.getCallingUid(); 21571 synchronized (mPackages) { 21572 final PackageSetting ps = mSettings.mPackages.get(packageName); 21573 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 21574 return null; 21575 } 21576 // InstallerPackageName for Apex is not stored in PackageManager 21577 if (ps == null && mApexManager.isApexPackage(packageName)) { 21578 return null; 21579 } 21580 return mSettings.getInstallerPackageNameLPr(packageName); 21581 } 21582 } 21583 21584 public boolean isOrphaned(String packageName) { 21585 // reader 21586 synchronized (mPackages) { 21587 if (!mPackages.containsKey(packageName)) { 21588 return false; 21589 } 21590 return mSettings.isOrphaned(packageName); 21591 } 21592 } 21593 21594 @Override 21595 public int getApplicationEnabledSetting(String packageName, int userId) { 21596 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21597 int callingUid = Binder.getCallingUid(); 21598 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21599 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 21600 // reader 21601 synchronized (mPackages) { 21602 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 21603 return COMPONENT_ENABLED_STATE_DISABLED; 21604 } 21605 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 21606 } 21607 } 21608 21609 @Override 21610 public int getComponentEnabledSetting(@NonNull ComponentName component, int userId) { 21611 if (component == null) return COMPONENT_ENABLED_STATE_DEFAULT; 21612 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21613 int callingUid = Binder.getCallingUid(); 21614 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21615 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 21616 synchronized (mPackages) { 21617 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 21618 component, TYPE_UNKNOWN, userId)) { 21619 return COMPONENT_ENABLED_STATE_DISABLED; 21620 } 21621 return mSettings.getComponentEnabledSettingLPr(component, userId); 21622 } 21623 } 21624 21625 @Override 21626 public void enterSafeMode() { 21627 enforceSystemOrRoot("Only the system can request entering safe mode"); 21628 21629 if (!mSystemReady) { 21630 mSafeMode = true; 21631 } 21632 } 21633 21634 @Override 21635 public void systemReady() { 21636 enforceSystemOrRoot("Only the system can claim the system is ready"); 21637 21638 mSystemReady = true; 21639 final ContentResolver resolver = mContext.getContentResolver(); 21640 ContentObserver co = new ContentObserver(mHandler) { 21641 @Override 21642 public void onChange(boolean selfChange) { 21643 final boolean ephemeralFeatureDisabled = 21644 Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0; 21645 for (int userId : UserManagerService.getInstance().getUserIds()) { 21646 final boolean instantAppsDisabledForUser = 21647 ephemeralFeatureDisabled || Secure.getIntForUser(resolver, 21648 Secure.INSTANT_APPS_ENABLED, 1, userId) == 0; 21649 mWebInstantAppsDisabled.put(userId, instantAppsDisabledForUser); 21650 } 21651 } 21652 }; 21653 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21654 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 21655 false, co, UserHandle.USER_ALL); 21656 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 21657 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_ALL); 21658 co.onChange(true); 21659 21660 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 21661 // disabled after already being started. 21662 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 21663 mContext.getContentResolver(), UserHandle.USER_SYSTEM); 21664 21665 disableSkuSpecificApps(); 21666 21667 // Read the compatibilty setting when the system is ready. 21668 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 21669 mContext.getContentResolver(), 21670 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 21671 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 21672 21673 if (DEBUG_SETTINGS) { 21674 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 21675 } 21676 21677 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 21678 21679 synchronized (mPackages) { 21680 // Verify that all of the preferred activity components actually 21681 // exist. It is possible for applications to be updated and at 21682 // that point remove a previously declared activity component that 21683 // had been set as a preferred activity. We try to clean this up 21684 // the next time we encounter that preferred activity, but it is 21685 // possible for the user flow to never be able to return to that 21686 // situation so here we do a sanity check to make sure we haven't 21687 // left any junk around. 21688 ArrayList<PreferredActivity> removed = new ArrayList<>(); 21689 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21690 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21691 removed.clear(); 21692 for (PreferredActivity pa : pir.filterSet()) { 21693 if (!mComponentResolver.isActivityDefined(pa.mPref.mComponent)) { 21694 removed.add(pa); 21695 } 21696 } 21697 if (removed.size() > 0) { 21698 for (int r=0; r<removed.size(); r++) { 21699 PreferredActivity pa = removed.get(r); 21700 Slog.w(TAG, "Removing dangling preferred activity: " 21701 + pa.mPref.mComponent); 21702 pir.removeFilter(pa); 21703 } 21704 mSettings.writePackageRestrictionsLPr( 21705 mSettings.mPreferredActivities.keyAt(i)); 21706 } 21707 } 21708 21709 for (int userId : UserManagerService.getInstance().getUserIds()) { 21710 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21711 grantPermissionsUserIds = ArrayUtils.appendInt( 21712 grantPermissionsUserIds, userId); 21713 } 21714 } 21715 } 21716 21717 sUserManager.systemReady(); 21718 // If we upgraded grant all default permissions before kicking off. 21719 for (int userId : grantPermissionsUserIds) { 21720 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21721 } 21722 21723 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21724 // If we did not grant default permissions, we preload from this the 21725 // default permission exceptions lazily to ensure we don't hit the 21726 // disk on a new user creation. 21727 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21728 } 21729 21730 // Now that we've scanned all packages, and granted any default 21731 // permissions, ensure permissions are updated. Beware of dragons if you 21732 // try optimizing this. 21733 synchronized (mPackages) { 21734 mPermissionManager.updateAllPermissions( 21735 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 21736 mPermissionCallback); 21737 21738 final PermissionPolicyInternal permissionPolicyInternal = 21739 LocalServices.getService(PermissionPolicyInternal.class); 21740 permissionPolicyInternal.setOnInitializedCallback(userId -> { 21741 // The SDK updated case is already handled when we run during the ctor. 21742 synchronized (mPackages) { 21743 mPermissionManager.updateAllPermissions( 21744 StorageManager.UUID_PRIVATE_INTERNAL, false /*sdkUpdated*/, 21745 mPackages.values(), mPermissionCallback); 21746 } 21747 }); 21748 } 21749 21750 // Watch for external volumes that come and go over time 21751 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21752 storage.registerListener(mStorageListener); 21753 21754 mInstallerService.systemReady(); 21755 mApexManager.systemReady(); 21756 mPackageDexOptimizer.systemReady(); 21757 21758 getStorageManagerInternal().addExternalStoragePolicy( 21759 new StorageManagerInternal.ExternalStorageMountPolicy() { 21760 @Override 21761 public int getMountMode(int uid, String packageName) { 21762 if (Process.isIsolated(uid)) { 21763 return Zygote.MOUNT_EXTERNAL_NONE; 21764 } 21765 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21766 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21767 } 21768 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21769 return Zygote.MOUNT_EXTERNAL_READ; 21770 } 21771 return Zygote.MOUNT_EXTERNAL_WRITE; 21772 } 21773 21774 @Override 21775 public boolean hasExternalStorage(int uid, String packageName) { 21776 return true; 21777 } 21778 }); 21779 21780 // Now that we're mostly running, clean up stale users and apps 21781 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21782 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21783 21784 mPermissionManager.systemReady(); 21785 21786 if (mInstantAppResolverConnection != null) { 21787 mContext.registerReceiver(new BroadcastReceiver() { 21788 @Override 21789 public void onReceive(Context context, Intent intent) { 21790 mInstantAppResolverConnection.optimisticBind(); 21791 mContext.unregisterReceiver(this); 21792 } 21793 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 21794 } 21795 21796 mModuleInfoProvider.systemReady(); 21797 21798 // Installer service might attempt to install some packages that have been staged for 21799 // installation on reboot. Make sure this is the last component to be call since the 21800 // installation might require other components to be ready. 21801 mInstallerService.restoreAndApplyStagedSessionIfNeeded(); 21802 } 21803 21804 public void waitForAppDataPrepared() { 21805 if (mPrepareAppDataFuture == null) { 21806 return; 21807 } 21808 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21809 mPrepareAppDataFuture = null; 21810 } 21811 21812 @Override 21813 public boolean isSafeMode() { 21814 // allow instant applications 21815 return mSafeMode; 21816 } 21817 21818 @Override 21819 public boolean hasSystemUidErrors() { 21820 // allow instant applications 21821 return mHasSystemUidErrors; 21822 } 21823 21824 static String arrayToString(int[] array) { 21825 StringBuilder stringBuilder = new StringBuilder(128); 21826 stringBuilder.append('['); 21827 if (array != null) { 21828 for (int i=0; i<array.length; i++) { 21829 if (i > 0) stringBuilder.append(", "); 21830 stringBuilder.append(array[i]); 21831 } 21832 } 21833 stringBuilder.append(']'); 21834 return stringBuilder.toString(); 21835 } 21836 21837 @Override 21838 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21839 FileDescriptor err, String[] args, ShellCallback callback, 21840 ResultReceiver resultReceiver) { 21841 (new PackageManagerShellCommand(this)).exec( 21842 this, in, out, err, args, callback, resultReceiver); 21843 } 21844 21845 @SuppressWarnings("resource") 21846 @Override 21847 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21848 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21849 21850 DumpState dumpState = new DumpState(); 21851 boolean fullPreferred = false; 21852 boolean checkin = false; 21853 21854 String packageName = null; 21855 ArraySet<String> permissionNames = null; 21856 21857 int opti = 0; 21858 while (opti < args.length) { 21859 String opt = args[opti]; 21860 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21861 break; 21862 } 21863 opti++; 21864 21865 if ("-a".equals(opt)) { 21866 // Right now we only know how to print all. 21867 } else if ("-h".equals(opt)) { 21868 pw.println("Package manager dump options:"); 21869 pw.println(" [-h] [-f] [--checkin] [--all-components] [cmd] ..."); 21870 pw.println(" --checkin: dump for a checkin"); 21871 pw.println(" -f: print details of intent filters"); 21872 pw.println(" -h: print this help"); 21873 pw.println(" --all-components: include all component names in package dump"); 21874 pw.println(" cmd may be one of:"); 21875 pw.println(" apex: list active APEXes and APEX session state"); 21876 pw.println(" l[ibraries]: list known shared libraries"); 21877 pw.println(" f[eatures]: list device features"); 21878 pw.println(" k[eysets]: print known keysets"); 21879 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21880 pw.println(" perm[issions]: dump permissions"); 21881 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21882 pw.println(" pref[erred]: print preferred package settings"); 21883 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21884 pw.println(" prov[iders]: dump content providers"); 21885 pw.println(" p[ackages]: dump installed packages"); 21886 pw.println(" s[hared-users]: dump shared user IDs"); 21887 pw.println(" m[essages]: print collected runtime messages"); 21888 pw.println(" v[erifiers]: print package verifier info"); 21889 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21890 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21891 pw.println(" version: print database version info"); 21892 pw.println(" write: write current settings now"); 21893 pw.println(" installs: details about install sessions"); 21894 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21895 pw.println(" dexopt: dump dexopt state"); 21896 pw.println(" compiler-stats: dump compiler statistics"); 21897 pw.println(" service-permissions: dump permissions required by services"); 21898 pw.println(" <package.name>: info about given package"); 21899 return; 21900 } else if ("--checkin".equals(opt)) { 21901 checkin = true; 21902 } else if ("--all-components".equals(opt)) { 21903 dumpState.setOptionEnabled(DumpState.OPTION_DUMP_ALL_COMPONENTS); 21904 } else if ("-f".equals(opt)) { 21905 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21906 } else if ("--proto".equals(opt)) { 21907 dumpProto(fd); 21908 return; 21909 } else { 21910 pw.println("Unknown argument: " + opt + "; use -h for help"); 21911 } 21912 } 21913 21914 // Is the caller requesting to dump a particular piece of data? 21915 if (opti < args.length) { 21916 String cmd = args[opti]; 21917 opti++; 21918 // Is this a package name? 21919 if ("android".equals(cmd) || cmd.contains(".")) { 21920 packageName = cmd; 21921 // When dumping a single package, we always dump all of its 21922 // filter information since the amount of data will be reasonable. 21923 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21924 } else if ("check-permission".equals(cmd)) { 21925 if (opti >= args.length) { 21926 pw.println("Error: check-permission missing permission argument"); 21927 return; 21928 } 21929 String perm = args[opti]; 21930 opti++; 21931 if (opti >= args.length) { 21932 pw.println("Error: check-permission missing package argument"); 21933 return; 21934 } 21935 21936 String pkg = args[opti]; 21937 opti++; 21938 int user = UserHandle.getUserId(Binder.getCallingUid()); 21939 if (opti < args.length) { 21940 try { 21941 user = Integer.parseInt(args[opti]); 21942 } catch (NumberFormatException e) { 21943 pw.println("Error: check-permission user argument is not a number: " 21944 + args[opti]); 21945 return; 21946 } 21947 } 21948 21949 // Normalize package name to handle renamed packages and static libs 21950 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21951 21952 pw.println(checkPermission(perm, pkg, user)); 21953 return; 21954 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21955 dumpState.setDump(DumpState.DUMP_LIBS); 21956 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21957 dumpState.setDump(DumpState.DUMP_FEATURES); 21958 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21959 if (opti >= args.length) { 21960 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21961 | DumpState.DUMP_SERVICE_RESOLVERS 21962 | DumpState.DUMP_RECEIVER_RESOLVERS 21963 | DumpState.DUMP_CONTENT_RESOLVERS); 21964 } else { 21965 while (opti < args.length) { 21966 String name = args[opti]; 21967 if ("a".equals(name) || "activity".equals(name)) { 21968 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21969 } else if ("s".equals(name) || "service".equals(name)) { 21970 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21971 } else if ("r".equals(name) || "receiver".equals(name)) { 21972 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21973 } else if ("c".equals(name) || "content".equals(name)) { 21974 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21975 } else { 21976 pw.println("Error: unknown resolver table type: " + name); 21977 return; 21978 } 21979 opti++; 21980 } 21981 } 21982 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21983 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21984 } else if ("permission".equals(cmd)) { 21985 if (opti >= args.length) { 21986 pw.println("Error: permission requires permission name"); 21987 return; 21988 } 21989 permissionNames = new ArraySet<>(); 21990 while (opti < args.length) { 21991 permissionNames.add(args[opti]); 21992 opti++; 21993 } 21994 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21995 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21996 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21997 dumpState.setDump(DumpState.DUMP_PREFERRED); 21998 } else if ("preferred-xml".equals(cmd)) { 21999 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 22000 if (opti < args.length && "--full".equals(args[opti])) { 22001 fullPreferred = true; 22002 opti++; 22003 } 22004 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 22005 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 22006 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 22007 dumpState.setDump(DumpState.DUMP_PACKAGES); 22008 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 22009 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 22010 if (opti < args.length && "noperm".equals(args[opti])) { 22011 dumpState.setOptionEnabled(DumpState.OPTION_SKIP_PERMISSIONS); 22012 } 22013 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 22014 dumpState.setDump(DumpState.DUMP_PROVIDERS); 22015 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 22016 dumpState.setDump(DumpState.DUMP_MESSAGES); 22017 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 22018 dumpState.setDump(DumpState.DUMP_VERIFIERS); 22019 } else if ("i".equals(cmd) || "ifv".equals(cmd) 22020 || "intent-filter-verifiers".equals(cmd)) { 22021 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 22022 } else if ("version".equals(cmd)) { 22023 dumpState.setDump(DumpState.DUMP_VERSION); 22024 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 22025 dumpState.setDump(DumpState.DUMP_KEYSETS); 22026 } else if ("installs".equals(cmd)) { 22027 dumpState.setDump(DumpState.DUMP_INSTALLS); 22028 } else if ("frozen".equals(cmd)) { 22029 dumpState.setDump(DumpState.DUMP_FROZEN); 22030 } else if ("volumes".equals(cmd)) { 22031 dumpState.setDump(DumpState.DUMP_VOLUMES); 22032 } else if ("dexopt".equals(cmd)) { 22033 dumpState.setDump(DumpState.DUMP_DEXOPT); 22034 } else if ("compiler-stats".equals(cmd)) { 22035 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 22036 } else if ("changes".equals(cmd)) { 22037 dumpState.setDump(DumpState.DUMP_CHANGES); 22038 } else if ("service-permissions".equals(cmd)) { 22039 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 22040 } else if ("write".equals(cmd)) { 22041 synchronized (mPackages) { 22042 mSettings.writeLPr(); 22043 pw.println("Settings written."); 22044 return; 22045 } 22046 } 22047 } 22048 22049 if (checkin) { 22050 pw.println("vers,1"); 22051 } 22052 22053 // reader 22054 synchronized (mPackages) { 22055 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 22056 if (!checkin) { 22057 if (dumpState.onTitlePrinted()) 22058 pw.println(); 22059 pw.println("Database versions:"); 22060 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 22061 } 22062 } 22063 22064 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 22065 if (!checkin) { 22066 if (dumpState.onTitlePrinted()) 22067 pw.println(); 22068 pw.println("Verifiers:"); 22069 pw.print(" Required: "); 22070 pw.print(mRequiredVerifierPackage); 22071 pw.print(" (uid="); 22072 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 22073 UserHandle.USER_SYSTEM)); 22074 pw.println(")"); 22075 } else if (mRequiredVerifierPackage != null) { 22076 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 22077 pw.print(","); 22078 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 22079 UserHandle.USER_SYSTEM)); 22080 } 22081 } 22082 22083 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 22084 packageName == null) { 22085 if (mIntentFilterVerifierComponent != null) { 22086 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22087 if (!checkin) { 22088 if (dumpState.onTitlePrinted()) 22089 pw.println(); 22090 pw.println("Intent Filter Verifier:"); 22091 pw.print(" Using: "); 22092 pw.print(verifierPackageName); 22093 pw.print(" (uid="); 22094 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 22095 UserHandle.USER_SYSTEM)); 22096 pw.println(")"); 22097 } else if (verifierPackageName != null) { 22098 pw.print("ifv,"); pw.print(verifierPackageName); 22099 pw.print(","); 22100 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 22101 UserHandle.USER_SYSTEM)); 22102 } 22103 } else { 22104 pw.println(); 22105 pw.println("No Intent Filter Verifier available!"); 22106 } 22107 } 22108 22109 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 22110 boolean printedHeader = false; 22111 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 22112 while (it.hasNext()) { 22113 String libName = it.next(); 22114 LongSparseArray<SharedLibraryInfo> versionedLib 22115 = mSharedLibraries.get(libName); 22116 if (versionedLib == null) { 22117 continue; 22118 } 22119 final int versionCount = versionedLib.size(); 22120 for (int i = 0; i < versionCount; i++) { 22121 SharedLibraryInfo libraryInfo = versionedLib.valueAt(i); 22122 if (!checkin) { 22123 if (!printedHeader) { 22124 if (dumpState.onTitlePrinted()) 22125 pw.println(); 22126 pw.println("Libraries:"); 22127 printedHeader = true; 22128 } 22129 pw.print(" "); 22130 } else { 22131 pw.print("lib,"); 22132 } 22133 pw.print(libraryInfo.getName()); 22134 if (libraryInfo.isStatic()) { 22135 pw.print(" version=" + libraryInfo.getLongVersion()); 22136 } 22137 if (!checkin) { 22138 pw.print(" -> "); 22139 } 22140 if (libraryInfo.getPath() != null) { 22141 pw.print(" (jar) "); 22142 pw.print(libraryInfo.getPath()); 22143 } else { 22144 pw.print(" (apk) "); 22145 pw.print(libraryInfo.getPackageName()); 22146 } 22147 pw.println(); 22148 } 22149 } 22150 } 22151 22152 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 22153 if (dumpState.onTitlePrinted()) 22154 pw.println(); 22155 if (!checkin) { 22156 pw.println("Features:"); 22157 } 22158 22159 synchronized (mAvailableFeatures) { 22160 for (FeatureInfo feat : mAvailableFeatures.values()) { 22161 if (checkin) { 22162 pw.print("feat,"); 22163 pw.print(feat.name); 22164 pw.print(","); 22165 pw.println(feat.version); 22166 } else { 22167 pw.print(" "); 22168 pw.print(feat.name); 22169 if (feat.version > 0) { 22170 pw.print(" version="); 22171 pw.print(feat.version); 22172 } 22173 pw.println(); 22174 } 22175 } 22176 } 22177 } 22178 22179 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 22180 mComponentResolver.dumpActivityResolvers(pw, dumpState, packageName); 22181 } 22182 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 22183 mComponentResolver.dumpReceiverResolvers(pw, dumpState, packageName); 22184 } 22185 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 22186 mComponentResolver.dumpServiceResolvers(pw, dumpState, packageName); 22187 } 22188 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 22189 mComponentResolver.dumpProviderResolvers(pw, dumpState, packageName); 22190 } 22191 22192 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 22193 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 22194 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 22195 int user = mSettings.mPreferredActivities.keyAt(i); 22196 if (pir.dump(pw, 22197 dumpState.getTitlePrinted() 22198 ? "\nPreferred Activities User " + user + ":" 22199 : "Preferred Activities User " + user + ":", " ", 22200 packageName, true, false)) { 22201 dumpState.setTitlePrinted(true); 22202 } 22203 } 22204 } 22205 22206 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 22207 pw.flush(); 22208 FileOutputStream fout = new FileOutputStream(fd); 22209 BufferedOutputStream str = new BufferedOutputStream(fout); 22210 XmlSerializer serializer = new FastXmlSerializer(); 22211 try { 22212 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 22213 serializer.startDocument(null, true); 22214 serializer.setFeature( 22215 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 22216 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 22217 serializer.endDocument(); 22218 serializer.flush(); 22219 } catch (IllegalArgumentException e) { 22220 pw.println("Failed writing: " + e); 22221 } catch (IllegalStateException e) { 22222 pw.println("Failed writing: " + e); 22223 } catch (IOException e) { 22224 pw.println("Failed writing: " + e); 22225 } 22226 } 22227 22228 if (!checkin 22229 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 22230 && packageName == null) { 22231 pw.println(); 22232 int count = mSettings.mPackages.size(); 22233 if (count == 0) { 22234 pw.println("No applications!"); 22235 pw.println(); 22236 } else { 22237 final String prefix = " "; 22238 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 22239 if (allPackageSettings.size() == 0) { 22240 pw.println("No domain preferred apps!"); 22241 pw.println(); 22242 } else { 22243 pw.println("App verification status:"); 22244 pw.println(); 22245 count = 0; 22246 for (PackageSetting ps : allPackageSettings) { 22247 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 22248 if (ivi == null || ivi.getPackageName() == null) continue; 22249 pw.println(prefix + "Package: " + ivi.getPackageName()); 22250 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 22251 pw.println(prefix + "Status: " + ivi.getStatusString()); 22252 pw.println(); 22253 count++; 22254 } 22255 if (count == 0) { 22256 pw.println(prefix + "No app verification established."); 22257 pw.println(); 22258 } 22259 for (int userId : sUserManager.getUserIds()) { 22260 pw.println("App linkages for user " + userId + ":"); 22261 pw.println(); 22262 count = 0; 22263 for (PackageSetting ps : allPackageSettings) { 22264 final long status = ps.getDomainVerificationStatusForUser(userId); 22265 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 22266 && !DEBUG_DOMAIN_VERIFICATION) { 22267 continue; 22268 } 22269 pw.println(prefix + "Package: " + ps.name); 22270 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 22271 String statusStr = IntentFilterVerificationInfo. 22272 getStatusStringFromValue(status); 22273 pw.println(prefix + "Status: " + statusStr); 22274 pw.println(); 22275 count++; 22276 } 22277 if (count == 0) { 22278 pw.println(prefix + "No configured app linkages."); 22279 pw.println(); 22280 } 22281 } 22282 } 22283 } 22284 } 22285 22286 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 22287 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 22288 } 22289 22290 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 22291 mComponentResolver.dumpContentProviders(pw, dumpState, packageName); 22292 } 22293 22294 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 22295 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 22296 } 22297 22298 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 22299 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 22300 } 22301 22302 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 22303 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 22304 } 22305 22306 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 22307 if (dumpState.onTitlePrinted()) pw.println(); 22308 pw.println("Package Changes:"); 22309 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 22310 final int K = mChangedPackages.size(); 22311 for (int i = 0; i < K; i++) { 22312 final SparseArray<String> changes = mChangedPackages.valueAt(i); 22313 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 22314 final int N = changes.size(); 22315 if (N == 0) { 22316 pw.print(" "); pw.println("No packages changed"); 22317 } else { 22318 for (int j = 0; j < N; j++) { 22319 final String pkgName = changes.valueAt(j); 22320 final int sequenceNumber = changes.keyAt(j); 22321 pw.print(" "); 22322 pw.print("seq="); 22323 pw.print(sequenceNumber); 22324 pw.print(", package="); 22325 pw.println(pkgName); 22326 } 22327 } 22328 } 22329 } 22330 22331 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 22332 // XXX should handle packageName != null by dumping only install data that 22333 // the given package is involved with. 22334 if (dumpState.onTitlePrinted()) pw.println(); 22335 22336 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22337 ipw.println(); 22338 ipw.println("Frozen packages:"); 22339 ipw.increaseIndent(); 22340 if (mFrozenPackages.size() == 0) { 22341 ipw.println("(none)"); 22342 } else { 22343 for (int i = 0; i < mFrozenPackages.size(); i++) { 22344 ipw.println(mFrozenPackages.valueAt(i)); 22345 } 22346 } 22347 ipw.decreaseIndent(); 22348 } 22349 22350 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 22351 if (dumpState.onTitlePrinted()) pw.println(); 22352 22353 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 22354 ipw.println(); 22355 ipw.println("Loaded volumes:"); 22356 ipw.increaseIndent(); 22357 if (mLoadedVolumes.size() == 0) { 22358 ipw.println("(none)"); 22359 } else { 22360 for (int i = 0; i < mLoadedVolumes.size(); i++) { 22361 ipw.println(mLoadedVolumes.valueAt(i)); 22362 } 22363 } 22364 ipw.decreaseIndent(); 22365 } 22366 22367 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 22368 && packageName == null) { 22369 mComponentResolver.dumpServicePermissions(pw, dumpState, packageName); 22370 } 22371 22372 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 22373 if (dumpState.onTitlePrinted()) pw.println(); 22374 dumpDexoptStateLPr(pw, packageName); 22375 } 22376 22377 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 22378 if (dumpState.onTitlePrinted()) pw.println(); 22379 dumpCompilerStatsLPr(pw, packageName); 22380 } 22381 22382 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 22383 if (dumpState.onTitlePrinted()) pw.println(); 22384 mSettings.dumpReadMessagesLPr(pw, dumpState); 22385 22386 pw.println(); 22387 pw.println("Package warning messages:"); 22388 dumpCriticalInfo(pw, null); 22389 } 22390 22391 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 22392 dumpCriticalInfo(pw, "msg,"); 22393 } 22394 } 22395 22396 // PackageInstaller should be called outside of mPackages lock 22397 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 22398 // XXX should handle packageName != null by dumping only install data that 22399 // the given package is involved with. 22400 if (dumpState.onTitlePrinted()) pw.println(); 22401 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 22402 } 22403 22404 if (!checkin && dumpState.isDumping(DumpState.DUMP_APEX)) { 22405 mApexManager.dump(pw, packageName); 22406 } 22407 } 22408 22409 //TODO: b/111402650 22410 private void disableSkuSpecificApps() { 22411 String apkList[] = mContext.getResources().getStringArray( 22412 R.array.config_disableApksUnlessMatchedSku_apk_list); 22413 String skuArray[] = mContext.getResources().getStringArray( 22414 R.array.config_disableApkUnlessMatchedSku_skus_list); 22415 if (ArrayUtils.isEmpty(apkList)) { 22416 return; 22417 } 22418 String sku = SystemProperties.get("ro.boot.hardware.sku"); 22419 if (!TextUtils.isEmpty(sku) && ArrayUtils.contains(skuArray, sku)) { 22420 return; 22421 } 22422 for (String packageName : apkList) { 22423 setSystemAppHiddenUntilInstalled(packageName, true); 22424 for (UserInfo user : sUserManager.getUsers(false)) { 22425 setSystemAppInstallState(packageName, false, user.id); 22426 } 22427 } 22428 } 22429 22430 private void dumpProto(FileDescriptor fd) { 22431 final ProtoOutputStream proto = new ProtoOutputStream(fd); 22432 22433 synchronized (mPackages) { 22434 final long requiredVerifierPackageToken = 22435 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 22436 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 22437 proto.write( 22438 PackageServiceDumpProto.PackageShortProto.UID, 22439 getPackageUid( 22440 mRequiredVerifierPackage, 22441 MATCH_DEBUG_TRIAGED_MISSING, 22442 UserHandle.USER_SYSTEM)); 22443 proto.end(requiredVerifierPackageToken); 22444 22445 if (mIntentFilterVerifierComponent != null) { 22446 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 22447 final long verifierPackageToken = 22448 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 22449 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 22450 proto.write( 22451 PackageServiceDumpProto.PackageShortProto.UID, 22452 getPackageUid( 22453 verifierPackageName, 22454 MATCH_DEBUG_TRIAGED_MISSING, 22455 UserHandle.USER_SYSTEM)); 22456 proto.end(verifierPackageToken); 22457 } 22458 22459 dumpSharedLibrariesProto(proto); 22460 dumpFeaturesProto(proto); 22461 mSettings.dumpPackagesProto(proto); 22462 mSettings.dumpSharedUsersProto(proto); 22463 dumpCriticalInfo(proto); 22464 } 22465 proto.flush(); 22466 } 22467 22468 private void dumpFeaturesProto(ProtoOutputStream proto) { 22469 synchronized (mAvailableFeatures) { 22470 final int count = mAvailableFeatures.size(); 22471 for (int i = 0; i < count; i++) { 22472 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 22473 } 22474 } 22475 } 22476 22477 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 22478 final int count = mSharedLibraries.size(); 22479 for (int i = 0; i < count; i++) { 22480 final String libName = mSharedLibraries.keyAt(i); 22481 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(libName); 22482 if (versionedLib == null) { 22483 continue; 22484 } 22485 final int versionCount = versionedLib.size(); 22486 for (int j = 0; j < versionCount; j++) { 22487 final SharedLibraryInfo libraryInfo = versionedLib.valueAt(j); 22488 final long sharedLibraryToken = 22489 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 22490 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libraryInfo.getName()); 22491 final boolean isJar = (libraryInfo.getPath() != null); 22492 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 22493 if (isJar) { 22494 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, 22495 libraryInfo.getPath()); 22496 } else { 22497 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, 22498 libraryInfo.getPackageName()); 22499 } 22500 proto.end(sharedLibraryToken); 22501 } 22502 } 22503 } 22504 22505 @GuardedBy("mPackages") 22506 @SuppressWarnings("resource") 22507 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 22508 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 22509 ipw.println(); 22510 ipw.println("Dexopt state:"); 22511 ipw.increaseIndent(); 22512 Collection<PackageParser.Package> packages; 22513 if (packageName != null) { 22514 PackageParser.Package targetPackage = mPackages.get(packageName); 22515 if (targetPackage != null) { 22516 packages = Collections.singletonList(targetPackage); 22517 } else { 22518 ipw.println("Unable to find package: " + packageName); 22519 return; 22520 } 22521 } else { 22522 packages = mPackages.values(); 22523 } 22524 22525 for (PackageParser.Package pkg : packages) { 22526 ipw.println("[" + pkg.packageName + "]"); 22527 ipw.increaseIndent(); 22528 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 22529 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 22530 ipw.decreaseIndent(); 22531 } 22532 } 22533 22534 @GuardedBy("mPackages") 22535 @SuppressWarnings("resource") 22536 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 22537 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 22538 ipw.println(); 22539 ipw.println("Compiler stats:"); 22540 ipw.increaseIndent(); 22541 Collection<PackageParser.Package> packages; 22542 if (packageName != null) { 22543 PackageParser.Package targetPackage = mPackages.get(packageName); 22544 if (targetPackage != null) { 22545 packages = Collections.singletonList(targetPackage); 22546 } else { 22547 ipw.println("Unable to find package: " + packageName); 22548 return; 22549 } 22550 } else { 22551 packages = mPackages.values(); 22552 } 22553 22554 for (PackageParser.Package pkg : packages) { 22555 ipw.println("[" + pkg.packageName + "]"); 22556 ipw.increaseIndent(); 22557 22558 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 22559 if (stats == null) { 22560 ipw.println("(No recorded stats)"); 22561 } else { 22562 stats.dump(ipw); 22563 } 22564 ipw.decreaseIndent(); 22565 } 22566 } 22567 22568 private String dumpDomainString(String packageName) { 22569 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 22570 .getList(); 22571 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 22572 22573 ArraySet<String> result = new ArraySet<>(); 22574 if (iviList.size() > 0) { 22575 for (IntentFilterVerificationInfo ivi : iviList) { 22576 result.addAll(ivi.getDomains()); 22577 } 22578 } 22579 if (filters != null && filters.size() > 0) { 22580 for (IntentFilter filter : filters) { 22581 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 22582 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 22583 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 22584 result.addAll(filter.getHostsList()); 22585 } 22586 } 22587 } 22588 22589 StringBuilder sb = new StringBuilder(result.size() * 16); 22590 for (String domain : result) { 22591 if (sb.length() > 0) sb.append(" "); 22592 sb.append(domain); 22593 } 22594 return sb.toString(); 22595 } 22596 22597 // ------- apps on sdcard specific code ------- 22598 static final boolean DEBUG_SD_INSTALL = false; 22599 22600 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 22601 22602 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 22603 22604 private boolean mMediaMounted = false; 22605 22606 static String getEncryptKey() { 22607 try { 22608 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 22609 SD_ENCRYPTION_KEYSTORE_NAME); 22610 if (sdEncKey == null) { 22611 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 22612 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 22613 if (sdEncKey == null) { 22614 Slog.e(TAG, "Failed to create encryption keys"); 22615 return null; 22616 } 22617 } 22618 return sdEncKey; 22619 } catch (NoSuchAlgorithmException nsae) { 22620 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 22621 return null; 22622 } catch (IOException ioe) { 22623 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 22624 return null; 22625 } 22626 } 22627 22628 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22629 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 22630 final int size = infos.size(); 22631 final String[] packageNames = new String[size]; 22632 final int[] packageUids = new int[size]; 22633 for (int i = 0; i < size; i++) { 22634 final ApplicationInfo info = infos.get(i); 22635 packageNames[i] = info.packageName; 22636 packageUids[i] = info.uid; 22637 } 22638 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 22639 finishedReceiver); 22640 } 22641 22642 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22643 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22644 sendResourcesChangedBroadcast(mediaStatus, replacing, 22645 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 22646 } 22647 22648 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22649 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22650 int size = pkgList.length; 22651 if (size > 0) { 22652 // Send broadcasts here 22653 Bundle extras = new Bundle(); 22654 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 22655 if (uidArr != null) { 22656 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 22657 } 22658 if (replacing) { 22659 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 22660 } 22661 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 22662 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 22663 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 22664 } 22665 } 22666 22667 private void loadPrivatePackages(final VolumeInfo vol) { 22668 mHandler.post(() -> loadPrivatePackagesInner(vol)); 22669 } 22670 22671 private void loadPrivatePackagesInner(VolumeInfo vol) { 22672 final String volumeUuid = vol.fsUuid; 22673 if (TextUtils.isEmpty(volumeUuid)) { 22674 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22675 return; 22676 } 22677 22678 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22679 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22680 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22681 22682 final VersionInfo ver; 22683 final List<PackageSetting> packages; 22684 synchronized (mPackages) { 22685 ver = mSettings.findOrCreateVersion(volumeUuid); 22686 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22687 } 22688 22689 for (PackageSetting ps : packages) { 22690 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22691 synchronized (mInstallLock) { 22692 final PackageParser.Package pkg; 22693 try { 22694 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22695 loaded.add(pkg.applicationInfo); 22696 22697 } catch (PackageManagerException e) { 22698 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22699 } 22700 22701 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22702 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 22703 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 22704 } 22705 } 22706 } 22707 22708 // Reconcile app data for all started/unlocked users 22709 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22710 final UserManager um = mContext.getSystemService(UserManager.class); 22711 UserManagerInternal umInternal = getUserManagerInternal(); 22712 for (UserInfo user : um.getUsers()) { 22713 final int flags; 22714 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22715 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22716 } else if (umInternal.isUserRunning(user.id)) { 22717 flags = StorageManager.FLAG_STORAGE_DE; 22718 } else { 22719 continue; 22720 } 22721 22722 try { 22723 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22724 synchronized (mInstallLock) { 22725 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22726 } 22727 } catch (IllegalStateException e) { 22728 // Device was probably ejected, and we'll process that event momentarily 22729 Slog.w(TAG, "Failed to prepare storage: " + e); 22730 } 22731 } 22732 22733 synchronized (mPackages) { 22734 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 22735 if (sdkUpdated) { 22736 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22737 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22738 } 22739 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 22740 mPermissionCallback); 22741 22742 // Yay, everything is now upgraded 22743 ver.forceCurrent(); 22744 22745 mSettings.writeLPr(); 22746 } 22747 22748 for (PackageFreezer freezer : freezers) { 22749 freezer.close(); 22750 } 22751 22752 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22753 sendResourcesChangedBroadcast(true, false, loaded, null); 22754 mLoadedVolumes.add(vol.getId()); 22755 } 22756 22757 private void unloadPrivatePackages(final VolumeInfo vol) { 22758 mHandler.post(() -> unloadPrivatePackagesInner(vol)); 22759 } 22760 22761 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22762 final String volumeUuid = vol.fsUuid; 22763 if (TextUtils.isEmpty(volumeUuid)) { 22764 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22765 return; 22766 } 22767 22768 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22769 synchronized (mInstallLock) { 22770 synchronized (mPackages) { 22771 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22772 for (PackageSetting ps : packages) { 22773 if (ps.pkg == null) continue; 22774 22775 final ApplicationInfo info = ps.pkg.applicationInfo; 22776 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22777 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22778 22779 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22780 "unloadPrivatePackagesInner")) { 22781 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22782 false, null)) { 22783 unloaded.add(info); 22784 } else { 22785 Slog.w(TAG, "Failed to unload " + ps.codePath); 22786 } 22787 } 22788 22789 // Try very hard to release any references to this package 22790 // so we don't risk the system server being killed due to 22791 // open FDs 22792 AttributeCache.instance().removePackage(ps.name); 22793 } 22794 22795 mSettings.writeLPr(); 22796 } 22797 } 22798 22799 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22800 sendResourcesChangedBroadcast(false, false, unloaded, null); 22801 mLoadedVolumes.remove(vol.getId()); 22802 22803 // Try very hard to release any references to this path so we don't risk 22804 // the system server being killed due to open FDs 22805 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22806 22807 for (int i = 0; i < 3; i++) { 22808 System.gc(); 22809 System.runFinalization(); 22810 } 22811 } 22812 22813 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22814 throws PackageManagerException { 22815 synchronized (mPackages) { 22816 // Normalize package name to handle renamed packages 22817 packageName = normalizePackageNameLPr(packageName); 22818 22819 final PackageSetting ps = mSettings.mPackages.get(packageName); 22820 if (ps == null) { 22821 throw new PackageManagerException("Package " + packageName + " is unknown"); 22822 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22823 throw new PackageManagerException( 22824 "Package " + packageName + " found on unknown volume " + volumeUuid 22825 + "; expected volume " + ps.volumeUuid); 22826 } else if (!ps.getInstalled(userId)) { 22827 throw new PackageManagerException( 22828 "Package " + packageName + " not installed for user " + userId); 22829 } 22830 } 22831 } 22832 22833 private List<String> collectAbsoluteCodePaths() { 22834 synchronized (mPackages) { 22835 List<String> codePaths = new ArrayList<>(); 22836 final int packageCount = mSettings.mPackages.size(); 22837 for (int i = 0; i < packageCount; i++) { 22838 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22839 codePaths.add(ps.codePath.getAbsolutePath()); 22840 } 22841 return codePaths; 22842 } 22843 } 22844 22845 /** 22846 * Examine all apps present on given mounted volume, and destroy apps that 22847 * aren't expected, either due to uninstallation or reinstallation on 22848 * another volume. 22849 */ 22850 private void reconcileApps(String volumeUuid) { 22851 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22852 List<File> filesToDelete = null; 22853 22854 final File[] files = FileUtils.listFilesOrEmpty( 22855 Environment.getDataAppDirectory(volumeUuid)); 22856 for (File file : files) { 22857 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22858 && !PackageInstallerService.isStageName(file.getName()); 22859 if (!isPackage) { 22860 // Ignore entries which are not packages 22861 continue; 22862 } 22863 22864 String absolutePath = file.getAbsolutePath(); 22865 22866 boolean pathValid = false; 22867 final int absoluteCodePathCount = absoluteCodePaths.size(); 22868 for (int i = 0; i < absoluteCodePathCount; i++) { 22869 String absoluteCodePath = absoluteCodePaths.get(i); 22870 if (absolutePath.startsWith(absoluteCodePath)) { 22871 pathValid = true; 22872 break; 22873 } 22874 } 22875 22876 if (!pathValid) { 22877 if (filesToDelete == null) { 22878 filesToDelete = new ArrayList<>(); 22879 } 22880 filesToDelete.add(file); 22881 } 22882 } 22883 22884 if (filesToDelete != null) { 22885 final int fileToDeleteCount = filesToDelete.size(); 22886 for (int i = 0; i < fileToDeleteCount; i++) { 22887 File fileToDelete = filesToDelete.get(i); 22888 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22889 synchronized (mInstallLock) { 22890 removeCodePathLI(fileToDelete); 22891 } 22892 } 22893 } 22894 } 22895 22896 /** 22897 * Reconcile all app data for the given user. 22898 * <p> 22899 * Verifies that directories exist and that ownership and labeling is 22900 * correct for all installed apps on all mounted volumes. 22901 */ 22902 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22903 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22904 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22905 final String volumeUuid = vol.getFsUuid(); 22906 synchronized (mInstallLock) { 22907 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22908 } 22909 } 22910 } 22911 22912 @GuardedBy("mInstallLock") 22913 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22914 boolean migrateAppData) { 22915 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22916 } 22917 22918 /** 22919 * Reconcile all app data on given mounted volume. 22920 * <p> 22921 * Destroys app data that isn't expected, either due to uninstallation or 22922 * reinstallation on another volume. 22923 * <p> 22924 * Verifies that directories exist and that ownership and labeling is 22925 * correct for all installed apps. 22926 * @return list of skipped non-core packages (if {@code onlyCoreApps} is true) 22927 */ 22928 @GuardedBy("mInstallLock") 22929 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22930 boolean migrateAppData, boolean onlyCoreApps) { 22931 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22932 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22933 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22934 22935 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22936 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22937 22938 // First look for stale data that doesn't belong, and check if things 22939 // have changed since we did our last restorecon 22940 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22941 if (StorageManager.isFileEncryptedNativeOrEmulated() 22942 && !StorageManager.isUserKeyUnlocked(userId)) { 22943 throw new RuntimeException( 22944 "Yikes, someone asked us to reconcile CE storage while " + userId 22945 + " was still locked; this would have caused massive data loss!"); 22946 } 22947 22948 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22949 for (File file : files) { 22950 final String packageName = file.getName(); 22951 try { 22952 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22953 } catch (PackageManagerException e) { 22954 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22955 try { 22956 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22957 StorageManager.FLAG_STORAGE_CE, 0); 22958 } catch (InstallerException e2) { 22959 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22960 } 22961 } 22962 } 22963 } 22964 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22965 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22966 for (File file : files) { 22967 final String packageName = file.getName(); 22968 try { 22969 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22970 } catch (PackageManagerException e) { 22971 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22972 try { 22973 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22974 StorageManager.FLAG_STORAGE_DE, 0); 22975 } catch (InstallerException e2) { 22976 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22977 } 22978 } 22979 } 22980 } 22981 22982 // Ensure that data directories are ready to roll for all packages 22983 // installed for this volume and user 22984 final List<PackageSetting> packages; 22985 synchronized (mPackages) { 22986 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22987 } 22988 int preparedCount = 0; 22989 for (PackageSetting ps : packages) { 22990 final String packageName = ps.name; 22991 if (ps.pkg == null) { 22992 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22993 // TODO: might be due to legacy ASEC apps; we should circle back 22994 // and reconcile again once they're scanned 22995 continue; 22996 } 22997 // Skip non-core apps if requested 22998 if (onlyCoreApps && !ps.pkg.coreApp) { 22999 result.add(packageName); 23000 continue; 23001 } 23002 23003 if (ps.getInstalled(userId)) { 23004 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 23005 preparedCount++; 23006 } 23007 } 23008 23009 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 23010 return result; 23011 } 23012 23013 /** 23014 * Prepare app data for the given app just after it was installed or 23015 * upgraded. This method carefully only touches users that it's installed 23016 * for, and it forces a restorecon to handle any seinfo changes. 23017 * <p> 23018 * Verifies that directories exist and that ownership and labeling is 23019 * correct for all installed apps. If there is an ownership mismatch, it 23020 * will try recovering system apps by wiping data; third-party app data is 23021 * left intact. 23022 * <p> 23023 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 23024 */ 23025 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 23026 final PackageSetting ps; 23027 synchronized (mPackages) { 23028 ps = mSettings.mPackages.get(pkg.packageName); 23029 mSettings.writeKernelMappingLPr(ps); 23030 } 23031 23032 final UserManagerService um = sUserManager; 23033 UserManagerInternal umInternal = getUserManagerInternal(); 23034 for (UserInfo user : um.getUsers(false /* excludeDying */)) { 23035 final int flags; 23036 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 23037 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 23038 } else if (umInternal.isUserRunning(user.id)) { 23039 flags = StorageManager.FLAG_STORAGE_DE; 23040 } else { 23041 continue; 23042 } 23043 23044 if (ps.getInstalled(user.id)) { 23045 // TODO: when user data is locked, mark that we're still dirty 23046 prepareAppDataLIF(pkg, user.id, flags); 23047 } 23048 } 23049 } 23050 23051 /** 23052 * Prepare app data for the given app. 23053 * <p> 23054 * Verifies that directories exist and that ownership and labeling is 23055 * correct for all installed apps. If there is an ownership mismatch, this 23056 * will try recovering system apps by wiping data; third-party app data is 23057 * left intact. 23058 */ 23059 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 23060 if (pkg == null) { 23061 Slog.wtf(TAG, "Package was null!", new Throwable()); 23062 return; 23063 } 23064 prepareAppDataLeafLIF(pkg, userId, flags); 23065 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23066 for (int i = 0; i < childCount; i++) { 23067 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 23068 } 23069 } 23070 23071 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 23072 boolean maybeMigrateAppData) { 23073 prepareAppDataLIF(pkg, userId, flags); 23074 23075 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 23076 // We may have just shuffled around app data directories, so 23077 // prepare them one more time 23078 prepareAppDataLIF(pkg, userId, flags); 23079 } 23080 } 23081 23082 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23083 if (DEBUG_APP_DATA) { 23084 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 23085 + Integer.toHexString(flags)); 23086 } 23087 23088 final PackageSetting ps; 23089 synchronized (mPackages) { 23090 ps = mSettings.mPackages.get(pkg.packageName); 23091 } 23092 final String volumeUuid = pkg.volumeUuid; 23093 final String packageName = pkg.packageName; 23094 23095 ApplicationInfo app = (ps == null) 23096 ? pkg.applicationInfo 23097 : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId); 23098 if (app == null) { 23099 app = pkg.applicationInfo; 23100 } 23101 23102 final int appId = UserHandle.getAppId(app.uid); 23103 23104 Preconditions.checkNotNull(app.seInfo); 23105 23106 final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : ""); 23107 long ceDataInode = -1; 23108 try { 23109 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23110 appId, seInfo, app.targetSdkVersion); 23111 } catch (InstallerException e) { 23112 if (app.isSystemApp()) { 23113 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 23114 + ", but trying to recover: " + e); 23115 destroyAppDataLeafLIF(pkg, userId, flags); 23116 try { 23117 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 23118 appId, seInfo, app.targetSdkVersion); 23119 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 23120 } catch (InstallerException e2) { 23121 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 23122 } 23123 } else { 23124 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 23125 } 23126 } 23127 // Prepare the application profiles only for upgrades and first boot (so that we don't 23128 // repeat the same operation at each boot). 23129 // We only have to cover the upgrade and first boot here because for app installs we 23130 // prepare the profiles before invoking dexopt (in installPackageLI). 23131 // 23132 // We also have to cover non system users because we do not call the usual install package 23133 // methods for them. 23134 // 23135 // NOTE: in order to speed up first boot time we only create the current profile and do not 23136 // update the content of the reference profile. A system image should already be configured 23137 // with the right profile keys and the profiles for the speed-profile prebuilds should 23138 // already be copied. That's done in #performDexOptUpgrade. 23139 // 23140 // TODO(calin, mathieuc): We should use .dm files for prebuilds profiles instead of 23141 // manually copying them in #performDexOptUpgrade. When we do that we should have a more 23142 // granular check here and only update the existing profiles. 23143 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 23144 mArtManagerService.prepareAppProfiles(pkg, userId, 23145 /* updateReferenceProfileContent= */ false); 23146 } 23147 23148 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 23149 // TODO: mark this structure as dirty so we persist it! 23150 synchronized (mPackages) { 23151 if (ps != null) { 23152 ps.setCeDataInode(ceDataInode, userId); 23153 } 23154 } 23155 } 23156 23157 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23158 } 23159 23160 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 23161 if (pkg == null) { 23162 Slog.wtf(TAG, "Package was null!", new Throwable()); 23163 return; 23164 } 23165 prepareAppDataContentsLeafLIF(pkg, userId, flags); 23166 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 23167 for (int i = 0; i < childCount; i++) { 23168 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 23169 } 23170 } 23171 23172 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 23173 final String volumeUuid = pkg.volumeUuid; 23174 final String packageName = pkg.packageName; 23175 final ApplicationInfo app = pkg.applicationInfo; 23176 23177 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 23178 // Create a native library symlink only if we have native libraries 23179 // and if the native libraries are 32 bit libraries. We do not provide 23180 // this symlink for 64 bit libraries. 23181 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 23182 final String nativeLibPath = app.nativeLibraryDir; 23183 try { 23184 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 23185 nativeLibPath, userId); 23186 } catch (InstallerException e) { 23187 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 23188 } 23189 } 23190 } 23191 } 23192 23193 /** 23194 * For system apps on non-FBE devices, this method migrates any existing 23195 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 23196 * requested by the app. 23197 */ 23198 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 23199 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 23200 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 23201 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 23202 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 23203 try { 23204 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 23205 storageTarget); 23206 } catch (InstallerException e) { 23207 logCriticalInfo(Log.WARN, 23208 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 23209 } 23210 return true; 23211 } else { 23212 return false; 23213 } 23214 } 23215 23216 public PackageFreezer freezePackage(String packageName, String killReason) { 23217 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 23218 } 23219 23220 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 23221 return new PackageFreezer(packageName, userId, killReason); 23222 } 23223 23224 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 23225 String killReason) { 23226 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 23227 } 23228 23229 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 23230 String killReason) { 23231 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 23232 return new PackageFreezer(); 23233 } else { 23234 return freezePackage(packageName, userId, killReason); 23235 } 23236 } 23237 23238 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 23239 String killReason) { 23240 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 23241 } 23242 23243 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 23244 String killReason) { 23245 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 23246 return new PackageFreezer(); 23247 } else { 23248 return freezePackage(packageName, userId, killReason); 23249 } 23250 } 23251 23252 /** 23253 * Class that freezes and kills the given package upon creation, and 23254 * unfreezes it upon closing. This is typically used when doing surgery on 23255 * app code/data to prevent the app from running while you're working. 23256 */ 23257 private class PackageFreezer implements AutoCloseable { 23258 private final String mPackageName; 23259 private final PackageFreezer[] mChildren; 23260 23261 private final boolean mWeFroze; 23262 23263 private final AtomicBoolean mClosed = new AtomicBoolean(); 23264 private final CloseGuard mCloseGuard = CloseGuard.get(); 23265 23266 /** 23267 * Create and return a stub freezer that doesn't actually do anything, 23268 * typically used when someone requested 23269 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 23270 * {@link PackageManager#DELETE_DONT_KILL_APP}. 23271 */ 23272 public PackageFreezer() { 23273 mPackageName = null; 23274 mChildren = null; 23275 mWeFroze = false; 23276 mCloseGuard.open("close"); 23277 } 23278 23279 public PackageFreezer(String packageName, int userId, String killReason) { 23280 synchronized (mPackages) { 23281 mPackageName = packageName; 23282 mWeFroze = mFrozenPackages.add(mPackageName); 23283 23284 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 23285 if (ps != null) { 23286 killApplication(ps.name, ps.appId, userId, killReason); 23287 } 23288 23289 final PackageParser.Package p = mPackages.get(packageName); 23290 if (p != null && p.childPackages != null) { 23291 final int N = p.childPackages.size(); 23292 mChildren = new PackageFreezer[N]; 23293 for (int i = 0; i < N; i++) { 23294 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 23295 userId, killReason); 23296 } 23297 } else { 23298 mChildren = null; 23299 } 23300 } 23301 mCloseGuard.open("close"); 23302 } 23303 23304 @Override 23305 protected void finalize() throws Throwable { 23306 try { 23307 mCloseGuard.warnIfOpen(); 23308 close(); 23309 } finally { 23310 super.finalize(); 23311 } 23312 } 23313 23314 @Override 23315 public void close() { 23316 mCloseGuard.close(); 23317 if (mClosed.compareAndSet(false, true)) { 23318 synchronized (mPackages) { 23319 if (mWeFroze) { 23320 mFrozenPackages.remove(mPackageName); 23321 } 23322 23323 if (mChildren != null) { 23324 for (PackageFreezer freezer : mChildren) { 23325 freezer.close(); 23326 } 23327 } 23328 } 23329 } 23330 } 23331 } 23332 23333 /** 23334 * Verify that given package is currently frozen. 23335 */ 23336 private void checkPackageFrozen(String packageName) { 23337 synchronized (mPackages) { 23338 if (!mFrozenPackages.contains(packageName)) { 23339 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 23340 } 23341 } 23342 } 23343 23344 @Override 23345 public int movePackage(final String packageName, final String volumeUuid) { 23346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23347 23348 final int callingUid = Binder.getCallingUid(); 23349 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 23350 final int moveId = mNextMoveId.getAndIncrement(); 23351 mHandler.post(() -> { 23352 try { 23353 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 23354 } catch (PackageManagerException e) { 23355 Slog.w(TAG, "Failed to move " + packageName, e); 23356 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 23357 } 23358 }); 23359 return moveId; 23360 } 23361 23362 private void movePackageInternal(final String packageName, final String volumeUuid, 23363 final int moveId, final int callingUid, UserHandle user) 23364 throws PackageManagerException { 23365 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23366 final PackageManager pm = mContext.getPackageManager(); 23367 23368 final String currentVolumeUuid; 23369 final File codeFile; 23370 final String installerPackageName; 23371 final String packageAbiOverride; 23372 final int appId; 23373 final String seinfo; 23374 final String label; 23375 final int targetSdkVersion; 23376 final PackageFreezer freezer; 23377 final int[] installedUserIds; 23378 final boolean isCurrentLocationExternal; 23379 23380 // reader 23381 synchronized (mPackages) { 23382 final PackageParser.Package pkg = mPackages.get(packageName); 23383 final PackageSetting ps = mSettings.mPackages.get(packageName); 23384 if (pkg == null 23385 || ps == null 23386 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 23387 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 23388 } 23389 if (pkg.applicationInfo.isSystemApp()) { 23390 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 23391 "Cannot move system application"); 23392 } 23393 23394 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 23395 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 23396 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 23397 if (isInternalStorage && !allow3rdPartyOnInternal) { 23398 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 23399 "3rd party apps are not allowed on internal storage"); 23400 } 23401 23402 currentVolumeUuid = ps.volumeUuid; 23403 23404 final File probe = new File(pkg.codePath); 23405 final File probeOat = new File(probe, "oat"); 23406 if (!probe.isDirectory() || !probeOat.isDirectory()) { 23407 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23408 "Move only supported for modern cluster style installs"); 23409 } 23410 23411 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 23412 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23413 "Package already moved to " + volumeUuid); 23414 } 23415 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 23416 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 23417 "Device admin cannot be moved"); 23418 } 23419 23420 if (mFrozenPackages.contains(packageName)) { 23421 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 23422 "Failed to move already frozen package"); 23423 } 23424 23425 isCurrentLocationExternal = isExternal(pkg); 23426 codeFile = new File(pkg.codePath); 23427 installerPackageName = ps.installerPackageName; 23428 packageAbiOverride = ps.cpuAbiOverrideString; 23429 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 23430 seinfo = pkg.applicationInfo.seInfo; 23431 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 23432 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 23433 freezer = freezePackage(packageName, "movePackageInternal"); 23434 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 23435 } 23436 23437 final Bundle extras = new Bundle(); 23438 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 23439 extras.putString(Intent.EXTRA_TITLE, label); 23440 mMoveCallbacks.notifyCreated(moveId, extras); 23441 23442 int installFlags; 23443 final boolean moveCompleteApp; 23444 final File measurePath; 23445 23446 installFlags = INSTALL_INTERNAL; 23447 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 23448 moveCompleteApp = true; 23449 measurePath = Environment.getDataAppDirectory(volumeUuid); 23450 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 23451 moveCompleteApp = false; 23452 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 23453 } else { 23454 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 23455 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 23456 || !volume.isMountedWritable()) { 23457 freezer.close(); 23458 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23459 "Move location not mounted private volume"); 23460 } 23461 23462 moveCompleteApp = true; 23463 measurePath = Environment.getDataAppDirectory(volumeUuid); 23464 } 23465 23466 // If we're moving app data around, we need all the users unlocked 23467 if (moveCompleteApp) { 23468 for (int userId : installedUserIds) { 23469 if (StorageManager.isFileEncryptedNativeOrEmulated() 23470 && !StorageManager.isUserKeyUnlocked(userId)) { 23471 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 23472 "User " + userId + " must be unlocked"); 23473 } 23474 } 23475 } 23476 23477 final PackageStats stats = new PackageStats(null, -1); 23478 synchronized (mInstaller) { 23479 for (int userId : installedUserIds) { 23480 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 23481 freezer.close(); 23482 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23483 "Failed to measure package size"); 23484 } 23485 } 23486 } 23487 23488 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 23489 + stats.dataSize); 23490 23491 final long startFreeBytes = measurePath.getUsableSpace(); 23492 final long sizeBytes; 23493 if (moveCompleteApp) { 23494 sizeBytes = stats.codeSize + stats.dataSize; 23495 } else { 23496 sizeBytes = stats.codeSize; 23497 } 23498 23499 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 23500 freezer.close(); 23501 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 23502 "Not enough free space to move"); 23503 } 23504 23505 mMoveCallbacks.notifyStatusChanged(moveId, 10); 23506 23507 final CountDownLatch installedLatch = new CountDownLatch(1); 23508 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 23509 @Override 23510 public void onUserActionRequired(Intent intent) throws RemoteException { 23511 throw new IllegalStateException(); 23512 } 23513 23514 @Override 23515 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 23516 Bundle extras) throws RemoteException { 23517 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 23518 + PackageManager.installStatusToString(returnCode, msg)); 23519 23520 installedLatch.countDown(); 23521 freezer.close(); 23522 23523 final int status = PackageManager.installStatusToPublicStatus(returnCode); 23524 switch (status) { 23525 case PackageInstaller.STATUS_SUCCESS: 23526 mMoveCallbacks.notifyStatusChanged(moveId, 23527 PackageManager.MOVE_SUCCEEDED); 23528 logAppMovedStorage(packageName, isCurrentLocationExternal); 23529 break; 23530 case PackageInstaller.STATUS_FAILURE_STORAGE: 23531 mMoveCallbacks.notifyStatusChanged(moveId, 23532 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 23533 break; 23534 default: 23535 mMoveCallbacks.notifyStatusChanged(moveId, 23536 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 23537 break; 23538 } 23539 } 23540 }; 23541 23542 final MoveInfo move; 23543 if (moveCompleteApp) { 23544 // Kick off a thread to report progress estimates 23545 new Thread(() -> { 23546 while (true) { 23547 try { 23548 if (installedLatch.await(1, TimeUnit.SECONDS)) { 23549 break; 23550 } 23551 } catch (InterruptedException ignored) { 23552 } 23553 23554 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 23555 final int progress = 10 + (int) MathUtils.constrain( 23556 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 23557 mMoveCallbacks.notifyStatusChanged(moveId, progress); 23558 } 23559 }).start(); 23560 23561 final String dataAppName = codeFile.getName(); 23562 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 23563 dataAppName, appId, seinfo, targetSdkVersion); 23564 } else { 23565 move = null; 23566 } 23567 23568 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 23569 23570 final Message msg = mHandler.obtainMessage(INIT_COPY); 23571 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 23572 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 23573 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 23574 packageAbiOverride, null /*grantedPermissions*/, 23575 null /*whitelistedRestrictedPermissions*/, PackageParser.SigningDetails.UNKNOWN, 23576 PackageManager.INSTALL_REASON_UNKNOWN, PackageManager.VERSION_CODE_HIGHEST); 23577 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 23578 msg.obj = params; 23579 23580 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 23581 System.identityHashCode(msg.obj)); 23582 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 23583 System.identityHashCode(msg.obj)); 23584 23585 mHandler.sendMessage(msg); 23586 } 23587 23588 /** 23589 * Logs that an app has been moved from internal to external storage and vice versa. 23590 * @param packageName The package that was moved. 23591 */ 23592 private void logAppMovedStorage(String packageName, boolean isPreviousLocationExternal) { 23593 final PackageParser.Package pkg; 23594 synchronized (mPackages) { 23595 pkg = mPackages.get(packageName); 23596 } 23597 if (pkg == null) { 23598 return; 23599 } 23600 23601 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23602 VolumeInfo volume = storage.findVolumeByUuid(pkg.applicationInfo.storageUuid.toString()); 23603 int packageExternalStorageType = getPackageExternalStorageType(volume, isExternal(pkg)); 23604 23605 if (!isPreviousLocationExternal && isExternal(pkg)) { 23606 // Move from internal to external storage. 23607 StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType, 23608 StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_EXTERNAL, 23609 packageName); 23610 } else if (isPreviousLocationExternal && !isExternal(pkg)) { 23611 // Move from external to internal storage. 23612 StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType, 23613 StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_INTERNAL, 23614 packageName); 23615 } 23616 } 23617 23618 @Override 23619 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 23620 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23621 23622 final int realMoveId = mNextMoveId.getAndIncrement(); 23623 final Bundle extras = new Bundle(); 23624 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 23625 mMoveCallbacks.notifyCreated(realMoveId, extras); 23626 23627 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 23628 @Override 23629 public void onCreated(int moveId, Bundle extras) { 23630 // Ignored 23631 } 23632 23633 @Override 23634 public void onStatusChanged(int moveId, int status, long estMillis) { 23635 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 23636 } 23637 }; 23638 23639 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23640 storage.setPrimaryStorageUuid(volumeUuid, callback); 23641 return realMoveId; 23642 } 23643 23644 @Override 23645 public int getMoveStatus(int moveId) { 23646 mContext.enforceCallingOrSelfPermission( 23647 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23648 return mMoveCallbacks.mLastStatus.get(moveId); 23649 } 23650 23651 @Override 23652 public void registerMoveCallback(IPackageMoveObserver callback) { 23653 mContext.enforceCallingOrSelfPermission( 23654 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23655 mMoveCallbacks.register(callback); 23656 } 23657 23658 @Override 23659 public void unregisterMoveCallback(IPackageMoveObserver callback) { 23660 mContext.enforceCallingOrSelfPermission( 23661 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23662 mMoveCallbacks.unregister(callback); 23663 } 23664 23665 @Override 23666 public boolean setInstallLocation(int loc) { 23667 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 23668 null); 23669 if (getInstallLocation() == loc) { 23670 return true; 23671 } 23672 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 23673 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 23674 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 23675 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23676 return true; 23677 } 23678 return false; 23679 } 23680 23681 @Override 23682 public int getInstallLocation() { 23683 // allow instant app access 23684 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23685 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23686 PackageHelper.APP_INSTALL_AUTO); 23687 } 23688 23689 /** Called by UserManagerService */ 23690 void cleanUpUser(UserManagerService userManager, int userHandle) { 23691 synchronized (mPackages) { 23692 mDirtyUsers.remove(userHandle); 23693 mUserNeedsBadging.delete(userHandle); 23694 mSettings.removeUserLPw(userHandle); 23695 mPendingBroadcasts.remove(userHandle); 23696 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23697 removeUnusedPackagesLPw(userManager, userHandle); 23698 } 23699 } 23700 23701 /** 23702 * We're removing userHandle and would like to remove any downloaded packages 23703 * that are no longer in use by any other user. 23704 * @param userHandle the user being removed 23705 */ 23706 @GuardedBy("mPackages") 23707 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23708 final boolean DEBUG_CLEAN_APKS = false; 23709 int [] users = userManager.getUserIds(); 23710 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23711 while (psit.hasNext()) { 23712 PackageSetting ps = psit.next(); 23713 if (ps.pkg == null) { 23714 continue; 23715 } 23716 final String packageName = ps.pkg.packageName; 23717 // Skip over if system app or static shared library 23718 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0 23719 || !TextUtils.isEmpty(ps.pkg.staticSharedLibName)) { 23720 continue; 23721 } 23722 if (DEBUG_CLEAN_APKS) { 23723 Slog.i(TAG, "Checking package " + packageName); 23724 } 23725 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23726 if (keep) { 23727 if (DEBUG_CLEAN_APKS) { 23728 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23729 } 23730 } else { 23731 for (int i = 0; i < users.length; i++) { 23732 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23733 keep = true; 23734 if (DEBUG_CLEAN_APKS) { 23735 Slog.i(TAG, " Keeping package " + packageName + " for user " 23736 + users[i]); 23737 } 23738 break; 23739 } 23740 } 23741 } 23742 if (!keep) { 23743 if (DEBUG_CLEAN_APKS) { 23744 Slog.i(TAG, " Removing package " + packageName); 23745 } 23746 //end run 23747 mHandler.post(() -> deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23748 userHandle, 0)); 23749 } 23750 } 23751 } 23752 23753 /** Called by UserManagerService */ 23754 void createNewUser(int userId, String[] disallowedPackages) { 23755 synchronized (mInstallLock) { 23756 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23757 } 23758 synchronized (mPackages) { 23759 scheduleWritePackageRestrictionsLocked(userId); 23760 scheduleWritePackageListLocked(userId); 23761 primeDomainVerificationsLPw(userId); 23762 } 23763 } 23764 23765 void onNewUserCreated(final int userId) { 23766 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23767 synchronized(mPackages) { 23768 // NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 23769 mPermissionManager.updateAllPermissions( 23770 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 23771 mPermissionCallback); 23772 } 23773 } 23774 23775 @Override 23776 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23777 mContext.enforceCallingOrSelfPermission( 23778 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23779 "Only package verification agents can read the verifier device identity"); 23780 23781 synchronized (mPackages) { 23782 return mSettings.getVerifierDeviceIdentityLPw(); 23783 } 23784 } 23785 23786 @Override 23787 public void setPermissionEnforced(String permission, boolean enforced) { 23788 // TODO: Now that we no longer change GID for storage, this should to away. 23789 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23790 "setPermissionEnforced"); 23791 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23792 synchronized (mPackages) { 23793 if (mSettings.mReadExternalStorageEnforced == null 23794 || mSettings.mReadExternalStorageEnforced != enforced) { 23795 mSettings.mReadExternalStorageEnforced = 23796 enforced ? Boolean.TRUE : Boolean.FALSE; 23797 mSettings.writeLPr(); 23798 } 23799 } 23800 // kill any non-foreground processes so we restart them and 23801 // grant/revoke the GID. 23802 final IActivityManager am = ActivityManager.getService(); 23803 if (am != null) { 23804 final long token = Binder.clearCallingIdentity(); 23805 try { 23806 am.killProcessesBelowForeground("setPermissionEnforcement"); 23807 } catch (RemoteException e) { 23808 } finally { 23809 Binder.restoreCallingIdentity(token); 23810 } 23811 } 23812 } else { 23813 throw new IllegalArgumentException("No selective enforcement for " + permission); 23814 } 23815 } 23816 23817 @Override 23818 @Deprecated 23819 public boolean isPermissionEnforced(String permission) { 23820 // allow instant applications 23821 return true; 23822 } 23823 23824 @Override 23825 public boolean isStorageLow() { 23826 // allow instant applications 23827 final long token = Binder.clearCallingIdentity(); 23828 try { 23829 final DeviceStorageMonitorInternal 23830 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23831 if (dsm != null) { 23832 return dsm.isMemoryLow(); 23833 } else { 23834 return false; 23835 } 23836 } finally { 23837 Binder.restoreCallingIdentity(token); 23838 } 23839 } 23840 23841 @Override 23842 public IPackageInstaller getPackageInstaller() { 23843 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23844 return null; 23845 } 23846 return mInstallerService; 23847 } 23848 23849 @Override 23850 public IArtManager getArtManager() { 23851 return mArtManagerService; 23852 } 23853 23854 private boolean userNeedsBadging(int userId) { 23855 int index = mUserNeedsBadging.indexOfKey(userId); 23856 if (index < 0) { 23857 final UserInfo userInfo; 23858 final long token = Binder.clearCallingIdentity(); 23859 try { 23860 userInfo = sUserManager.getUserInfo(userId); 23861 } finally { 23862 Binder.restoreCallingIdentity(token); 23863 } 23864 final boolean b; 23865 if (userInfo != null && userInfo.isManagedProfile()) { 23866 b = true; 23867 } else { 23868 b = false; 23869 } 23870 mUserNeedsBadging.put(userId, b); 23871 return b; 23872 } 23873 return mUserNeedsBadging.valueAt(index); 23874 } 23875 23876 @Override 23877 public KeySet getKeySetByAlias(String packageName, String alias) { 23878 if (packageName == null || alias == null) { 23879 return null; 23880 } 23881 synchronized(mPackages) { 23882 final PackageParser.Package pkg = mPackages.get(packageName); 23883 if (pkg == null) { 23884 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23885 throw new IllegalArgumentException("Unknown package: " + packageName); 23886 } 23887 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23888 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23889 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23890 throw new IllegalArgumentException("Unknown package: " + packageName); 23891 } 23892 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23893 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23894 } 23895 } 23896 23897 @Override 23898 public KeySet getSigningKeySet(String packageName) { 23899 if (packageName == null) { 23900 return null; 23901 } 23902 synchronized(mPackages) { 23903 final int callingUid = Binder.getCallingUid(); 23904 final int callingUserId = UserHandle.getUserId(callingUid); 23905 final PackageParser.Package pkg = mPackages.get(packageName); 23906 if (pkg == null) { 23907 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23908 throw new IllegalArgumentException("Unknown package: " + packageName); 23909 } 23910 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23911 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23912 // filter and pretend the package doesn't exist 23913 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23914 + ", uid:" + callingUid); 23915 throw new IllegalArgumentException("Unknown package: " + packageName); 23916 } 23917 if (pkg.applicationInfo.uid != callingUid 23918 && Process.SYSTEM_UID != callingUid) { 23919 throw new SecurityException("May not access signing KeySet of other apps."); 23920 } 23921 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23922 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23923 } 23924 } 23925 23926 @Override 23927 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23928 final int callingUid = Binder.getCallingUid(); 23929 if (getInstantAppPackageName(callingUid) != null) { 23930 return false; 23931 } 23932 if (packageName == null || ks == null) { 23933 return false; 23934 } 23935 synchronized(mPackages) { 23936 final PackageParser.Package pkg = mPackages.get(packageName); 23937 if (pkg == null 23938 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23939 UserHandle.getUserId(callingUid))) { 23940 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23941 throw new IllegalArgumentException("Unknown package: " + packageName); 23942 } 23943 IBinder ksh = ks.getToken(); 23944 if (ksh instanceof KeySetHandle) { 23945 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23946 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23947 } 23948 return false; 23949 } 23950 } 23951 23952 @Override 23953 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23954 final int callingUid = Binder.getCallingUid(); 23955 if (getInstantAppPackageName(callingUid) != null) { 23956 return false; 23957 } 23958 if (packageName == null || ks == null) { 23959 return false; 23960 } 23961 synchronized(mPackages) { 23962 final PackageParser.Package pkg = mPackages.get(packageName); 23963 if (pkg == null 23964 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23965 UserHandle.getUserId(callingUid))) { 23966 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23967 throw new IllegalArgumentException("Unknown package: " + packageName); 23968 } 23969 IBinder ksh = ks.getToken(); 23970 if (ksh instanceof KeySetHandle) { 23971 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23972 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23973 } 23974 return false; 23975 } 23976 } 23977 23978 @GuardedBy("mPackages") 23979 private void deletePackageIfUnusedLPr(final String packageName) { 23980 PackageSetting ps = mSettings.mPackages.get(packageName); 23981 if (ps == null) { 23982 return; 23983 } 23984 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23985 // TODO Implement atomic delete if package is unused 23986 // It is currently possible that the package will be deleted even if it is installed 23987 // after this method returns. 23988 mHandler.post(() -> deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23989 0, PackageManager.DELETE_ALL_USERS)); 23990 } 23991 } 23992 23993 /** 23994 * Check and throw if the given before/after packages would be considered a 23995 * downgrade. 23996 */ 23997 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23998 throws PackageManagerException { 23999 if (after.getLongVersionCode() < before.getLongVersionCode()) { 24000 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24001 "Update version code " + after.versionCode + " is older than current " 24002 + before.getLongVersionCode()); 24003 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 24004 if (after.baseRevisionCode < before.baseRevisionCode) { 24005 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24006 "Update base revision code " + after.baseRevisionCode 24007 + " is older than current " + before.baseRevisionCode); 24008 } 24009 24010 if (!ArrayUtils.isEmpty(after.splitNames)) { 24011 for (int i = 0; i < after.splitNames.length; i++) { 24012 final String splitName = after.splitNames[i]; 24013 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 24014 if (j != -1) { 24015 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 24016 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 24017 "Update split " + splitName + " revision code " 24018 + after.splitRevisionCodes[i] + " is older than current " 24019 + before.splitRevisionCodes[j]); 24020 } 24021 } 24022 } 24023 } 24024 } 24025 } 24026 24027 private static class MoveCallbacks extends Handler { 24028 private static final int MSG_CREATED = 1; 24029 private static final int MSG_STATUS_CHANGED = 2; 24030 24031 private final RemoteCallbackList<IPackageMoveObserver> 24032 mCallbacks = new RemoteCallbackList<>(); 24033 24034 private final SparseIntArray mLastStatus = new SparseIntArray(); 24035 24036 public MoveCallbacks(Looper looper) { 24037 super(looper); 24038 } 24039 24040 public void register(IPackageMoveObserver callback) { 24041 mCallbacks.register(callback); 24042 } 24043 24044 public void unregister(IPackageMoveObserver callback) { 24045 mCallbacks.unregister(callback); 24046 } 24047 24048 @Override 24049 public void handleMessage(Message msg) { 24050 final SomeArgs args = (SomeArgs) msg.obj; 24051 final int n = mCallbacks.beginBroadcast(); 24052 for (int i = 0; i < n; i++) { 24053 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 24054 try { 24055 invokeCallback(callback, msg.what, args); 24056 } catch (RemoteException ignored) { 24057 } 24058 } 24059 mCallbacks.finishBroadcast(); 24060 args.recycle(); 24061 } 24062 24063 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 24064 throws RemoteException { 24065 switch (what) { 24066 case MSG_CREATED: { 24067 callback.onCreated(args.argi1, (Bundle) args.arg2); 24068 break; 24069 } 24070 case MSG_STATUS_CHANGED: { 24071 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 24072 break; 24073 } 24074 } 24075 } 24076 24077 private void notifyCreated(int moveId, Bundle extras) { 24078 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 24079 24080 final SomeArgs args = SomeArgs.obtain(); 24081 args.argi1 = moveId; 24082 args.arg2 = extras; 24083 obtainMessage(MSG_CREATED, args).sendToTarget(); 24084 } 24085 24086 private void notifyStatusChanged(int moveId, int status) { 24087 notifyStatusChanged(moveId, status, -1); 24088 } 24089 24090 private void notifyStatusChanged(int moveId, int status, long estMillis) { 24091 Slog.v(TAG, "Move " + moveId + " status " + status); 24092 24093 final SomeArgs args = SomeArgs.obtain(); 24094 args.argi1 = moveId; 24095 args.argi2 = status; 24096 args.arg3 = estMillis; 24097 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 24098 24099 synchronized (mLastStatus) { 24100 mLastStatus.put(moveId, status); 24101 } 24102 } 24103 } 24104 24105 private final static class OnPermissionChangeListeners extends Handler { 24106 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 24107 24108 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 24109 new RemoteCallbackList<>(); 24110 24111 public OnPermissionChangeListeners(Looper looper) { 24112 super(looper); 24113 } 24114 24115 @Override 24116 public void handleMessage(Message msg) { 24117 switch (msg.what) { 24118 case MSG_ON_PERMISSIONS_CHANGED: { 24119 final int uid = msg.arg1; 24120 handleOnPermissionsChanged(uid); 24121 } break; 24122 } 24123 } 24124 24125 public void addListenerLocked(IOnPermissionsChangeListener listener) { 24126 mPermissionListeners.register(listener); 24127 24128 } 24129 24130 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 24131 mPermissionListeners.unregister(listener); 24132 } 24133 24134 public void onPermissionsChanged(int uid) { 24135 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 24136 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 24137 } 24138 } 24139 24140 private void handleOnPermissionsChanged(int uid) { 24141 final int count = mPermissionListeners.beginBroadcast(); 24142 try { 24143 for (int i = 0; i < count; i++) { 24144 IOnPermissionsChangeListener callback = mPermissionListeners 24145 .getBroadcastItem(i); 24146 try { 24147 callback.onPermissionsChanged(uid); 24148 } catch (RemoteException e) { 24149 Log.e(TAG, "Permission listener is dead", e); 24150 } 24151 } 24152 } finally { 24153 mPermissionListeners.finishBroadcast(); 24154 } 24155 } 24156 } 24157 24158 private class PackageManagerNative extends IPackageManagerNative.Stub { 24159 @Override 24160 public String[] getNamesForUids(int[] uids) throws RemoteException { 24161 final String[] results = PackageManagerService.this.getNamesForUids(uids); 24162 // massage results so they can be parsed by the native binder 24163 for (int i = results.length - 1; i >= 0; --i) { 24164 if (results[i] == null) { 24165 results[i] = ""; 24166 } 24167 } 24168 return results; 24169 } 24170 24171 // NB: this differentiates between preloads and sideloads 24172 @Override 24173 public String getInstallerForPackage(String packageName) throws RemoteException { 24174 final String installerName = getInstallerPackageName(packageName); 24175 if (!TextUtils.isEmpty(installerName)) { 24176 return installerName; 24177 } 24178 // differentiate between preload and sideload 24179 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 24180 ApplicationInfo appInfo = getApplicationInfo(packageName, 24181 /*flags*/ 0, 24182 /*userId*/ callingUser); 24183 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 24184 return "preload"; 24185 } 24186 return ""; 24187 } 24188 24189 @Override 24190 public long getVersionCodeForPackage(String packageName) throws RemoteException { 24191 try { 24192 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 24193 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 24194 if (pInfo != null) { 24195 return pInfo.getLongVersionCode(); 24196 } 24197 } catch (Exception e) { 24198 } 24199 return 0; 24200 } 24201 24202 @Override 24203 public int getTargetSdkVersionForPackage(String packageName) 24204 throws RemoteException { 24205 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 24206 ApplicationInfo info = getApplicationInfo(packageName, 0, callingUser); 24207 if (info == null) { 24208 throw new RemoteException( 24209 "Couldn't get ApplicationInfo for package " + packageName); 24210 } 24211 return info.targetSdkVersion; 24212 } 24213 24214 @Override 24215 public boolean[] isAudioPlaybackCaptureAllowed(String[] packageNames) 24216 throws RemoteException { 24217 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 24218 boolean[] results = new boolean[packageNames.length]; 24219 for (int i = results.length - 1; i >= 0; --i) { 24220 ApplicationInfo appInfo = getApplicationInfo(packageNames[i], 0, callingUser); 24221 results[i] = appInfo == null ? false : appInfo.isAudioPlaybackCaptureAllowed(); 24222 } 24223 return results; 24224 } 24225 24226 @Override 24227 public int getLocationFlags(String packageName) throws RemoteException { 24228 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 24229 ApplicationInfo appInfo = getApplicationInfo(packageName, 24230 /*flags*/ 0, 24231 /*userId*/ callingUser); 24232 if (appInfo == null) { 24233 throw new RemoteException( 24234 "Couldn't get ApplicationInfo for package " + packageName); 24235 } 24236 return ((appInfo.isSystemApp() ? IPackageManagerNative.LOCATION_SYSTEM : 0) 24237 | (appInfo.isVendor() ? IPackageManagerNative.LOCATION_VENDOR : 0) 24238 | (appInfo.isProduct() ? IPackageManagerNative.LOCATION_PRODUCT : 0)); 24239 } 24240 24241 @Override 24242 public String getModuleMetadataPackageName() throws RemoteException { 24243 return PackageManagerService.this.mModuleInfoProvider.getPackageName(); 24244 } 24245 } 24246 24247 private class PackageManagerInternalImpl extends PackageManagerInternal { 24248 @Override 24249 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 24250 int flagValues, int userId) { 24251 PackageManagerService.this.updatePermissionFlags( 24252 permName, packageName, flagMask, flagValues, true, userId); 24253 } 24254 24255 @Override 24256 public List<ApplicationInfo> getInstalledApplications(int flags, int userId, 24257 int callingUid) { 24258 return PackageManagerService.this.getInstalledApplicationsListInternal(flags, userId, 24259 callingUid); 24260 } 24261 24262 24263 @Override 24264 public boolean isPlatformSigned(String packageName) { 24265 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 24266 if (packageSetting == null) { 24267 return false; 24268 } 24269 PackageParser.Package pkg = packageSetting.pkg; 24270 if (pkg == null) { 24271 // May happen if package in on a removable sd card 24272 return false; 24273 } 24274 return pkg.mSigningDetails.hasAncestorOrSelf(mPlatformPackage.mSigningDetails) 24275 || mPlatformPackage.mSigningDetails.checkCapability(pkg.mSigningDetails, 24276 PackageParser.SigningDetails.CertCapabilities.PERMISSION); 24277 } 24278 24279 @Override 24280 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 24281 SigningDetails sd = getSigningDetails(packageName); 24282 if (sd == null) { 24283 return false; 24284 } 24285 return sd.hasSha256Certificate(restoringFromSigHash, 24286 SigningDetails.CertCapabilities.INSTALLED_DATA); 24287 } 24288 24289 @Override 24290 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 24291 SigningDetails sd = getSigningDetails(packageName); 24292 if (sd == null) { 24293 return false; 24294 } 24295 return sd.hasCertificate(restoringFromSig, 24296 SigningDetails.CertCapabilities.INSTALLED_DATA); 24297 } 24298 24299 @Override 24300 public boolean hasSignatureCapability(int serverUid, int clientUid, 24301 @SigningDetails.CertCapabilities int capability) { 24302 SigningDetails serverSigningDetails = getSigningDetails(serverUid); 24303 SigningDetails clientSigningDetails = getSigningDetails(clientUid); 24304 return serverSigningDetails.checkCapability(clientSigningDetails, capability) 24305 || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails); 24306 24307 } 24308 24309 private SigningDetails getSigningDetails(@NonNull String packageName) { 24310 synchronized (mPackages) { 24311 PackageParser.Package p = mPackages.get(packageName); 24312 if (p == null) { 24313 return null; 24314 } 24315 return p.mSigningDetails; 24316 } 24317 } 24318 24319 private SigningDetails getSigningDetails(int uid) { 24320 synchronized (mPackages) { 24321 final int appId = UserHandle.getAppId(uid); 24322 final Object obj = mSettings.getSettingLPr(appId); 24323 if (obj != null) { 24324 if (obj instanceof SharedUserSetting) { 24325 return ((SharedUserSetting) obj).signatures.mSigningDetails; 24326 } else if (obj instanceof PackageSetting) { 24327 final PackageSetting ps = (PackageSetting) obj; 24328 return ps.signatures.mSigningDetails; 24329 } 24330 } 24331 return SigningDetails.UNKNOWN; 24332 } 24333 } 24334 24335 @Override 24336 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 24337 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 24338 } 24339 24340 @Override 24341 public boolean isInstantApp(String packageName, int userId) { 24342 return PackageManagerService.this.isInstantApp(packageName, userId); 24343 } 24344 24345 @Override 24346 public String getInstantAppPackageName(int uid) { 24347 return PackageManagerService.this.getInstantAppPackageName(uid); 24348 } 24349 24350 @Override 24351 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 24352 synchronized (mPackages) { 24353 return PackageManagerService.this.filterAppAccessLPr( 24354 (PackageSetting) pkg.mExtras, callingUid, userId); 24355 } 24356 } 24357 24358 @Override 24359 public PackageParser.Package getPackage(String packageName) { 24360 synchronized (mPackages) { 24361 packageName = resolveInternalPackageNameLPr( 24362 packageName, PackageManager.VERSION_CODE_HIGHEST); 24363 return mPackages.get(packageName); 24364 } 24365 } 24366 24367 @Override 24368 public PackageList getPackageList(PackageListObserver observer) { 24369 synchronized (mPackages) { 24370 final int N = mPackages.size(); 24371 final ArrayList<String> list = new ArrayList<>(N); 24372 for (int i = 0; i < N; i++) { 24373 list.add(mPackages.keyAt(i)); 24374 } 24375 final PackageList packageList = new PackageList(list, observer); 24376 if (observer != null) { 24377 mPackageListObservers.add(packageList); 24378 } 24379 return packageList; 24380 } 24381 } 24382 24383 @Override 24384 public void removePackageListObserver(PackageListObserver observer) { 24385 synchronized (mPackages) { 24386 mPackageListObservers.remove(observer); 24387 } 24388 } 24389 24390 @Override 24391 public PackageParser.Package getDisabledSystemPackage(String packageName) { 24392 synchronized (mPackages) { 24393 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 24394 return (ps != null) ? ps.pkg : null; 24395 } 24396 } 24397 24398 @Override 24399 public @Nullable String getDisabledSystemPackageName(@NonNull String packageName) { 24400 PackageParser.Package pkg = getDisabledSystemPackage(packageName); 24401 return pkg == null ? null : pkg.packageName; 24402 } 24403 24404 @Override 24405 public String getKnownPackageName(int knownPackage, int userId) { 24406 switch(knownPackage) { 24407 case PackageManagerInternal.PACKAGE_BROWSER: 24408 return getDefaultBrowserPackageName(userId); 24409 case PackageManagerInternal.PACKAGE_INSTALLER: 24410 return mRequiredInstallerPackage; 24411 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 24412 return mSetupWizardPackage; 24413 case PackageManagerInternal.PACKAGE_SYSTEM: 24414 return "android"; 24415 case PackageManagerInternal.PACKAGE_VERIFIER: 24416 return mRequiredVerifierPackage; 24417 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 24418 return mSystemTextClassifierPackage; 24419 case PackageManagerInternal.PACKAGE_PERMISSION_CONTROLLER: 24420 return mRequiredPermissionControllerPackage; 24421 case PackageManagerInternal.PACKAGE_WELLBEING: 24422 return mWellbeingPackage; 24423 case PackageManagerInternal.PACKAGE_DOCUMENTER: 24424 return mDocumenterPackage; 24425 case PackageManagerInternal.PACKAGE_CONFIGURATOR: 24426 return mConfiguratorPackage; 24427 case PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER: 24428 return mIncidentReportApproverPackage; 24429 case PackageManagerInternal.PACKAGE_APP_PREDICTOR: 24430 return mAppPredictionServicePackage; 24431 } 24432 return null; 24433 } 24434 24435 @Override 24436 public boolean isResolveActivityComponent(ComponentInfo component) { 24437 return mResolveActivity.packageName.equals(component.packageName) 24438 && mResolveActivity.name.equals(component.name); 24439 } 24440 24441 @Override 24442 public void setLocationPackagesProvider(PackagesProvider provider) { 24443 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 24444 } 24445 24446 @Override 24447 public void setLocationExtraPackagesProvider(PackagesProvider provider) { 24448 mDefaultPermissionPolicy.setLocationExtraPackagesProvider(provider); 24449 } 24450 24451 @Override 24452 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 24453 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 24454 } 24455 24456 @Override 24457 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 24458 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 24459 } 24460 24461 @Override 24462 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 24463 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 24464 } 24465 24466 @Override 24467 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 24468 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 24469 packageName, userId); 24470 } 24471 24472 @Override 24473 public void setKeepUninstalledPackages(final List<String> packageList) { 24474 Preconditions.checkNotNull(packageList); 24475 List<String> removedFromList = null; 24476 synchronized (mPackages) { 24477 if (mKeepUninstalledPackages != null) { 24478 final int packagesCount = mKeepUninstalledPackages.size(); 24479 for (int i = 0; i < packagesCount; i++) { 24480 String oldPackage = mKeepUninstalledPackages.get(i); 24481 if (packageList != null && packageList.contains(oldPackage)) { 24482 continue; 24483 } 24484 if (removedFromList == null) { 24485 removedFromList = new ArrayList<>(); 24486 } 24487 removedFromList.add(oldPackage); 24488 } 24489 } 24490 mKeepUninstalledPackages = new ArrayList<>(packageList); 24491 if (removedFromList != null) { 24492 final int removedCount = removedFromList.size(); 24493 for (int i = 0; i < removedCount; i++) { 24494 deletePackageIfUnusedLPr(removedFromList.get(i)); 24495 } 24496 } 24497 } 24498 } 24499 24500 @Override 24501 public boolean isPermissionsReviewRequired(String packageName, int userId) { 24502 synchronized (mPackages) { 24503 final PackageParser.Package pkg = mPackages.get(packageName); 24504 if (pkg == null) { 24505 return false; 24506 } 24507 24508 return mPermissionManager.isPermissionsReviewRequired(pkg, userId); 24509 } 24510 } 24511 24512 @Override 24513 public PackageInfo getPackageInfo( 24514 String packageName, int flags, int filterCallingUid, int userId) { 24515 return PackageManagerService.this 24516 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 24517 flags, filterCallingUid, userId); 24518 } 24519 24520 @Override 24521 public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) { 24522 synchronized (mPackages) { 24523 final PackageSetting ps = mSettings.mPackages.get(packageName); 24524 PersistableBundle launcherExtras = null; 24525 if (ps != null) { 24526 launcherExtras = ps.readUserState(userId).suspendedLauncherExtras; 24527 } 24528 return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null; 24529 } 24530 } 24531 24532 @Override 24533 public boolean isPackageSuspended(String packageName, int userId) { 24534 synchronized (mPackages) { 24535 final PackageSetting ps = mSettings.mPackages.get(packageName); 24536 return (ps != null) ? ps.getSuspended(userId) : false; 24537 } 24538 } 24539 24540 @Override 24541 public String getSuspendingPackage(String suspendedPackage, int userId) { 24542 synchronized (mPackages) { 24543 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 24544 return (ps != null) ? ps.readUserState(userId).suspendingPackage : null; 24545 } 24546 } 24547 24548 @Override 24549 public SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage, int userId) { 24550 synchronized (mPackages) { 24551 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 24552 return (ps != null) ? ps.readUserState(userId).dialogInfo : null; 24553 } 24554 } 24555 24556 @Override 24557 public int getDistractingPackageRestrictions(String packageName, int userId) { 24558 synchronized (mPackages) { 24559 final PackageSetting ps = mSettings.mPackages.get(packageName); 24560 return (ps != null) ? ps.getDistractionFlags(userId) : RESTRICTION_NONE; 24561 } 24562 } 24563 24564 @Override 24565 public int getPackageUid(String packageName, int flags, int userId) { 24566 return PackageManagerService.this 24567 .getPackageUid(packageName, flags, userId); 24568 } 24569 24570 @Override 24571 public ApplicationInfo getApplicationInfo( 24572 String packageName, int flags, int filterCallingUid, int userId) { 24573 return PackageManagerService.this 24574 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 24575 } 24576 24577 @Override 24578 public ActivityInfo getActivityInfo( 24579 ComponentName component, int flags, int filterCallingUid, int userId) { 24580 return PackageManagerService.this 24581 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 24582 } 24583 24584 @Override 24585 public List<ResolveInfo> queryIntentActivities( 24586 Intent intent, int flags, int filterCallingUid, int userId) { 24587 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24588 return PackageManagerService.this 24589 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 24590 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 24591 } 24592 24593 @Override 24594 public List<ResolveInfo> queryIntentServices( 24595 Intent intent, int flags, int callingUid, int userId) { 24596 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24597 return PackageManagerService.this 24598 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 24599 false); 24600 } 24601 24602 @Override 24603 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 24604 int userId) { 24605 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 24606 } 24607 24608 @Override 24609 public ComponentName getDefaultHomeActivity(int userId) { 24610 return PackageManagerService.this.getDefaultHomeActivity(userId); 24611 } 24612 24613 @Override 24614 public void setDeviceAndProfileOwnerPackages( 24615 int deviceOwnerUserId, String deviceOwnerPackage, 24616 SparseArray<String> profileOwnerPackages) { 24617 mProtectedPackages.setDeviceAndProfileOwnerPackages( 24618 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 24619 24620 final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>(); 24621 if (deviceOwnerPackage != null) { 24622 usersWithPoOrDo.add(deviceOwnerUserId); 24623 } 24624 final int sz = profileOwnerPackages.size(); 24625 for (int i = 0; i < sz; i++) { 24626 if (profileOwnerPackages.valueAt(i) != null) { 24627 usersWithPoOrDo.add(profileOwnerPackages.keyAt(i)); 24628 } 24629 } 24630 unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo); 24631 } 24632 24633 @Override 24634 public boolean isPackageDataProtected(int userId, String packageName) { 24635 return mProtectedPackages.isPackageDataProtected(userId, packageName); 24636 } 24637 24638 @Override 24639 public boolean isPackageStateProtected(String packageName, int userId) { 24640 return mProtectedPackages.isPackageStateProtected(userId, packageName); 24641 } 24642 24643 @Override 24644 public boolean isPackageEphemeral(int userId, String packageName) { 24645 synchronized (mPackages) { 24646 final PackageSetting ps = mSettings.mPackages.get(packageName); 24647 return ps != null ? ps.getInstantApp(userId) : false; 24648 } 24649 } 24650 24651 @Override 24652 public boolean wasPackageEverLaunched(String packageName, int userId) { 24653 synchronized (mPackages) { 24654 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 24655 } 24656 } 24657 24658 @Override 24659 public boolean isEnabledAndMatches(ComponentInfo info, int flags, int userId) { 24660 synchronized (mPackages) { 24661 return mSettings.isEnabledAndMatchLPr(info, flags, userId); 24662 } 24663 } 24664 24665 @Override 24666 public boolean userNeedsBadging(int userId) { 24667 synchronized (mPackages) { 24668 return PackageManagerService.this.userNeedsBadging(userId); 24669 } 24670 } 24671 24672 @Override 24673 public void grantRuntimePermission(String packageName, String permName, int userId, 24674 boolean overridePolicy) { 24675 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 24676 permName, packageName, overridePolicy, getCallingUid(), userId, 24677 mPermissionCallback); 24678 } 24679 24680 @Override 24681 public void revokeRuntimePermission(String packageName, String permName, int userId, 24682 boolean overridePolicy) { 24683 mPermissionManager.revokeRuntimePermission( 24684 permName, packageName, overridePolicy, userId, 24685 mPermissionCallback); 24686 } 24687 24688 @Override 24689 public String getNameForUid(int uid) { 24690 return PackageManagerService.this.getNameForUid(uid); 24691 } 24692 24693 @Override 24694 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 24695 Intent origIntent, String resolvedType, String callingPackage, 24696 Bundle verificationBundle, int userId) { 24697 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 24698 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 24699 userId); 24700 } 24701 24702 @Override 24703 public void grantEphemeralAccess(int userId, Intent intent, 24704 int targetAppId, int ephemeralAppId) { 24705 synchronized (mPackages) { 24706 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 24707 targetAppId, ephemeralAppId); 24708 } 24709 } 24710 24711 @Override 24712 public boolean isInstantAppInstallerComponent(ComponentName component) { 24713 synchronized (mPackages) { 24714 return mInstantAppInstallerActivity != null 24715 && mInstantAppInstallerActivity.getComponentName().equals(component); 24716 } 24717 } 24718 24719 @Override 24720 public void pruneInstantApps() { 24721 mInstantAppRegistry.pruneInstantApps(); 24722 } 24723 24724 @Override 24725 public String getSetupWizardPackageName() { 24726 return mSetupWizardPackage; 24727 } 24728 24729 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 24730 if (policy != null) { 24731 mExternalSourcesPolicy = policy; 24732 } 24733 } 24734 24735 @Override 24736 public boolean isPackagePersistent(String packageName) { 24737 synchronized (mPackages) { 24738 PackageParser.Package pkg = mPackages.get(packageName); 24739 return pkg != null 24740 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 24741 | ApplicationInfo.FLAG_PERSISTENT)) == 24742 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 24743 : false; 24744 } 24745 } 24746 24747 @Override 24748 public boolean isLegacySystemApp(PackageParser.Package pkg) { 24749 synchronized (mPackages) { 24750 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24751 return mPromoteSystemApps 24752 && ps.isSystem() 24753 && mExistingSystemPackages.contains(ps.name); 24754 } 24755 } 24756 24757 @Override 24758 public List<PackageInfo> getOverlayPackages(int userId) { 24759 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 24760 synchronized (mPackages) { 24761 for (PackageParser.Package p : mPackages.values()) { 24762 if (p.mOverlayTarget != null) { 24763 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 24764 if (pkg != null) { 24765 overlayPackages.add(pkg); 24766 } 24767 } 24768 } 24769 } 24770 return overlayPackages; 24771 } 24772 24773 @Override 24774 public List<String> getTargetPackageNames(int userId) { 24775 List<String> targetPackages = new ArrayList<>(); 24776 synchronized (mPackages) { 24777 for (PackageParser.Package p : mPackages.values()) { 24778 if (p.mOverlayTarget == null) { 24779 targetPackages.add(p.packageName); 24780 } 24781 } 24782 } 24783 return targetPackages; 24784 } 24785 24786 @Override 24787 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24788 @Nullable List<String> overlayPackageNames) { 24789 synchronized (mPackages) { 24790 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24791 Slog.e(TAG, "failed to find package " + targetPackageName); 24792 return false; 24793 } 24794 ArrayList<String> overlayPaths = null; 24795 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 24796 final int N = overlayPackageNames.size(); 24797 overlayPaths = new ArrayList<>(N); 24798 for (int i = 0; i < N; i++) { 24799 final String packageName = overlayPackageNames.get(i); 24800 final PackageParser.Package pkg = mPackages.get(packageName); 24801 if (pkg == null) { 24802 Slog.e(TAG, "failed to find package " + packageName); 24803 return false; 24804 } 24805 overlayPaths.add(pkg.baseCodePath); 24806 } 24807 } 24808 24809 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 24810 ps.setOverlayPaths(overlayPaths, userId); 24811 return true; 24812 } 24813 } 24814 24815 @Override 24816 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24817 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 24818 return resolveIntentInternal( 24819 intent, resolvedType, flags, userId, resolveForStart, filterCallingUid); 24820 } 24821 24822 @Override 24823 public ResolveInfo resolveService(Intent intent, String resolvedType, 24824 int flags, int userId, int callingUid) { 24825 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24826 } 24827 24828 @Override 24829 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 24830 return PackageManagerService.this.resolveContentProviderInternal( 24831 name, flags, userId); 24832 } 24833 24834 @Override 24835 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24836 synchronized (mPackages) { 24837 mIsolatedOwners.put(isolatedUid, ownerUid); 24838 } 24839 } 24840 24841 @Override 24842 public void removeIsolatedUid(int isolatedUid) { 24843 synchronized (mPackages) { 24844 mIsolatedOwners.delete(isolatedUid); 24845 } 24846 } 24847 24848 @Override 24849 public int getUidTargetSdkVersion(int uid) { 24850 synchronized (mPackages) { 24851 return getUidTargetSdkVersionLockedLPr(uid); 24852 } 24853 } 24854 24855 @Override 24856 public int getPackageTargetSdkVersion(String packageName) { 24857 synchronized (mPackages) { 24858 return getPackageTargetSdkVersionLockedLPr(packageName); 24859 } 24860 } 24861 24862 @Override 24863 public boolean canAccessInstantApps(int callingUid, int userId) { 24864 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 24865 } 24866 24867 @Override 24868 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 24869 synchronized (mPackages) { 24870 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 24871 return ps != null && !PackageManagerService.this.filterAppAccessLPr( 24872 ps, callingUid, component, TYPE_UNKNOWN, userId); 24873 } 24874 } 24875 24876 @Override 24877 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 24878 synchronized (mPackages) { 24879 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 24880 } 24881 } 24882 24883 @Override 24884 public void notifyPackageUse(String packageName, int reason) { 24885 synchronized (mPackages) { 24886 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 24887 } 24888 } 24889 24890 @Override 24891 public CheckPermissionDelegate getCheckPermissionDelegate() { 24892 synchronized (mPackages) { 24893 return PackageManagerService.this.getCheckPermissionDelegateLocked(); 24894 } 24895 } 24896 24897 @Override 24898 public void setCheckPermissionDelegate(CheckPermissionDelegate delegate) { 24899 synchronized (mPackages) { 24900 PackageManagerService.this.setCheckPermissionDelegateLocked(delegate); 24901 } 24902 } 24903 24904 @Override 24905 public SparseArray<String> getAppsWithSharedUserIds() { 24906 synchronized (mPackages) { 24907 return getAppsWithSharedUserIdsLocked(); 24908 } 24909 } 24910 24911 @Override 24912 public String getSharedUserIdForPackage(String packageName) { 24913 synchronized (mPackages) { 24914 return getSharedUserIdForPackageLocked(packageName); 24915 } 24916 } 24917 24918 @Override 24919 public String[] getPackagesForSharedUserId(String sharedUserId, int userId) { 24920 synchronized (mPackages) { 24921 return getPackagesForSharedUserIdLocked(sharedUserId, userId); 24922 } 24923 } 24924 24925 @Override 24926 public boolean isOnlyCoreApps() { 24927 return PackageManagerService.this.isOnlyCoreApps(); 24928 } 24929 24930 @Override 24931 public void freeStorage(String volumeUuid, long bytes, int storageFlags) 24932 throws IOException { 24933 PackageManagerService.this.freeStorage(volumeUuid, bytes, storageFlags); 24934 } 24935 24936 @Override 24937 public void forEachPackage(Consumer<PackageParser.Package> actionLocked) { 24938 PackageManagerService.this.forEachPackage(actionLocked); 24939 } 24940 24941 @Override 24942 public void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked, 24943 @UserIdInt int userId) { 24944 PackageManagerService.this.forEachInstalledPackage(actionLocked, userId); 24945 } 24946 24947 @Override 24948 public ArraySet<String> getEnabledComponents(String packageName, int userId) { 24949 synchronized (mPackages) { 24950 PackageSetting setting = mSettings.getPackageLPr(packageName); 24951 if (setting == null) { 24952 return new ArraySet<>(); 24953 } 24954 return setting.getEnabledComponents(userId); 24955 } 24956 } 24957 24958 @Override 24959 public ArraySet<String> getDisabledComponents(String packageName, int userId) { 24960 synchronized (mPackages) { 24961 PackageSetting setting = mSettings.getPackageLPr(packageName); 24962 if (setting == null) { 24963 return new ArraySet<>(); 24964 } 24965 return setting.getDisabledComponents(userId); 24966 } 24967 } 24968 24969 @Override 24970 public @PackageManager.EnabledState int getApplicationEnabledState( 24971 String packageName, int userId) { 24972 synchronized (mPackages) { 24973 PackageSetting setting = mSettings.getPackageLPr(packageName); 24974 if (setting == null) { 24975 return COMPONENT_ENABLED_STATE_DEFAULT; 24976 } 24977 return setting.getEnabled(userId); 24978 } 24979 } 24980 24981 @Override 24982 public void setEnableRollbackCode(int token, int enableRollbackCode) { 24983 PackageManagerService.this.setEnableRollbackCode(token, enableRollbackCode); 24984 } 24985 24986 /** 24987 * Ask the package manager to compile layouts in the given package. 24988 */ 24989 @Override 24990 public boolean compileLayouts(String packageName) { 24991 PackageParser.Package pkg; 24992 synchronized (mPackages) { 24993 pkg = mPackages.get(packageName); 24994 if (pkg == null) { 24995 return false; 24996 } 24997 } 24998 return mArtManagerService.compileLayouts(pkg); 24999 } 25000 25001 @Override 25002 public void finishPackageInstall(int token, boolean didLaunch) { 25003 PackageManagerService.this.finishPackageInstall(token, didLaunch); 25004 } 25005 25006 @Nullable 25007 @Override 25008 public String removeLegacyDefaultBrowserPackageName(int userId) { 25009 synchronized (mPackages) { 25010 return mSettings.removeDefaultBrowserPackageNameLPw(userId); 25011 } 25012 } 25013 25014 @Override 25015 public void setDefaultBrowserProvider(@NonNull DefaultBrowserProvider provider) { 25016 synchronized (mPackages) { 25017 mDefaultBrowserProvider = provider; 25018 } 25019 } 25020 25021 @Override 25022 public void setDefaultDialerProvider(@NonNull DefaultDialerProvider provider) { 25023 synchronized (mPackages) { 25024 mDefaultDialerProvider = provider; 25025 } 25026 } 25027 25028 @Override 25029 public void setDefaultHomeProvider(@NonNull DefaultHomeProvider provider) { 25030 synchronized (mPackages) { 25031 mDefaultHomeProvider = provider; 25032 } 25033 } 25034 25035 @Override 25036 public boolean isApexPackage(String packageName) { 25037 return PackageManagerService.this.mApexManager.isApexPackage(packageName); 25038 } 25039 25040 @Override 25041 public void uninstallApex(String packageName, long versionCode, int userId, 25042 IntentSender intentSender) { 25043 final int callerUid = Binder.getCallingUid(); 25044 if (callerUid != Process.ROOT_UID && callerUid != Process.SHELL_UID) { 25045 throw new SecurityException("Not allowed to uninstall apexes"); 25046 } 25047 PackageInstallerService.PackageDeleteObserverAdapter adapter = 25048 new PackageInstallerService.PackageDeleteObserverAdapter( 25049 PackageManagerService.this.mContext, intentSender, packageName, 25050 false, userId); 25051 if (userId != UserHandle.USER_ALL) { 25052 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 25053 "Can't uninstall an apex for a single user"); 25054 return; 25055 } 25056 final ApexManager am = PackageManagerService.this.mApexManager; 25057 PackageInfo activePackage = am.getPackageInfo(packageName, 25058 ApexManager.MATCH_ACTIVE_PACKAGE); 25059 if (activePackage == null) { 25060 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 25061 packageName + " is not an apex package"); 25062 return; 25063 } 25064 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 25065 && activePackage.getLongVersionCode() != versionCode) { 25066 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 25067 "Active version " + activePackage.getLongVersionCode() 25068 + " is not equal to " + versionCode + "]"); 25069 return; 25070 } 25071 if (!am.uninstallApex(activePackage.applicationInfo.sourceDir)) { 25072 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 25073 "Failed to uninstall apex " + packageName); 25074 } else { 25075 adapter.onPackageDeleted(packageName, PackageManager.DELETE_SUCCEEDED, 25076 null); 25077 } 25078 } 25079 25080 @Override 25081 public boolean wereDefaultPermissionsGrantedSinceBoot(int userId) { 25082 synchronized (mPackages) { 25083 return mDefaultPermissionPolicy.wereDefaultPermissionsGrantedSinceBoot(userId); 25084 } 25085 } 25086 25087 @Override 25088 public void setRuntimePermissionsFingerPrint(@NonNull String fingerPrint, 25089 @UserIdInt int userId) { 25090 synchronized (mPackages) { 25091 mSettings.setRuntimePermissionsFingerPrintLPr(fingerPrint, userId); 25092 } 25093 } 25094 25095 @Override 25096 public void migrateLegacyObbData() { 25097 try { 25098 mInstaller.migrateLegacyObbData(); 25099 } catch (Exception e) { 25100 Slog.wtf(TAG, e); 25101 } 25102 } 25103 } 25104 25105 @GuardedBy("mPackages") 25106 private SparseArray<String> getAppsWithSharedUserIdsLocked() { 25107 final SparseArray<String> sharedUserIds = new SparseArray<>(); 25108 synchronized (mPackages) { 25109 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 25110 sharedUserIds.put(UserHandle.getAppId(setting.userId), setting.name); 25111 } 25112 } 25113 return sharedUserIds; 25114 } 25115 25116 @GuardedBy("mPackages") 25117 private String getSharedUserIdForPackageLocked(String packageName) { 25118 final PackageSetting ps = mSettings.mPackages.get(packageName); 25119 return (ps != null && ps.isSharedUser()) ? ps.sharedUser.name : null; 25120 } 25121 25122 @GuardedBy("mPackages") 25123 private String[] getPackagesForSharedUserIdLocked(String sharedUserId, int userId) { 25124 try { 25125 final SharedUserSetting sus = mSettings.getSharedUserLPw( 25126 sharedUserId, 0, 0, false); 25127 if (sus == null) { 25128 return EmptyArray.STRING; 25129 } 25130 String[] res = new String[sus.packages.size()]; 25131 final Iterator<PackageSetting> it = sus.packages.iterator(); 25132 int i = 0; 25133 while (it.hasNext()) { 25134 PackageSetting ps = it.next(); 25135 if (ps.getInstalled(userId)) { 25136 res[i++] = ps.name; 25137 } else { 25138 res = ArrayUtils.removeElement(String.class, res, res[i]); 25139 } 25140 } 25141 return res; 25142 } catch (PackageManagerException e) { 25143 // Should not happen 25144 } 25145 return EmptyArray.STRING; 25146 } 25147 25148 @Override 25149 public int getRuntimePermissionsVersion(@UserIdInt int userId) { 25150 Preconditions.checkArgumentNonnegative(userId); 25151 mContext.enforceCallingOrSelfPermission( 25152 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 25153 "setRuntimePermissionVersion"); 25154 synchronized (mPackages) { 25155 return mSettings.getDefaultRuntimePermissionsVersionLPr(userId); 25156 } 25157 } 25158 25159 @Override 25160 public void setRuntimePermissionsVersion(int version, @UserIdInt int userId) { 25161 Preconditions.checkArgumentNonnegative(version); 25162 Preconditions.checkArgumentNonnegative(userId); 25163 mContext.enforceCallingOrSelfPermission( 25164 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 25165 "setRuntimePermissionVersion"); 25166 synchronized (mPackages) { 25167 mSettings.setDefaultRuntimePermissionsVersionLPr(version, userId); 25168 } 25169 } 25170 25171 @Override 25172 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 25173 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 25174 synchronized (mPackages) { 25175 final long identity = Binder.clearCallingIdentity(); 25176 try { 25177 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 25178 packageNames, userId); 25179 } finally { 25180 Binder.restoreCallingIdentity(identity); 25181 } 25182 } 25183 } 25184 25185 @Override 25186 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 25187 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 25188 synchronized (mPackages) { 25189 final long identity = Binder.clearCallingIdentity(); 25190 try { 25191 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 25192 packageNames, userId); 25193 } finally { 25194 Binder.restoreCallingIdentity(identity); 25195 } 25196 } 25197 } 25198 25199 @Override 25200 public void grantDefaultPermissionsToEnabledTelephonyDataServices( 25201 String[] packageNames, int userId) { 25202 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices"); 25203 synchronized (mPackages) { 25204 Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy. 25205 grantDefaultPermissionsToEnabledTelephonyDataServices( 25206 packageNames, userId)); 25207 } 25208 } 25209 25210 @Override 25211 public void revokeDefaultPermissionsFromDisabledTelephonyDataServices( 25212 String[] packageNames, int userId) { 25213 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices"); 25214 synchronized (mPackages) { 25215 Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy. 25216 revokeDefaultPermissionsFromDisabledTelephonyDataServices( 25217 packageNames, userId)); 25218 } 25219 } 25220 25221 @Override 25222 public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) { 25223 enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp"); 25224 synchronized (mPackages) { 25225 final long identity = Binder.clearCallingIdentity(); 25226 try { 25227 mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp( 25228 packageName, userId); 25229 } finally { 25230 Binder.restoreCallingIdentity(identity); 25231 } 25232 } 25233 } 25234 25235 @Override 25236 public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) { 25237 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps"); 25238 synchronized (mPackages) { 25239 final long identity = Binder.clearCallingIdentity(); 25240 try { 25241 mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId); 25242 } finally { 25243 Binder.restoreCallingIdentity(identity); 25244 } 25245 } 25246 } 25247 25248 void forEachPackage(Consumer<PackageParser.Package> actionLocked) { 25249 synchronized (mPackages) { 25250 int numPackages = mPackages.size(); 25251 for (int i = 0; i < numPackages; i++) { 25252 actionLocked.accept(mPackages.valueAt(i)); 25253 } 25254 } 25255 } 25256 25257 void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked, 25258 @UserIdInt int userId) { 25259 synchronized (mPackages) { 25260 int numPackages = mPackages.size(); 25261 for (int i = 0; i < numPackages; i++) { 25262 PackageParser.Package pkg = mPackages.valueAt(i); 25263 PackageSetting setting = mSettings.getPackageLPr(pkg.packageName); 25264 if (setting == null || !setting.getInstalled(userId)) { 25265 continue; 25266 } 25267 actionLocked.accept(pkg); 25268 } 25269 } 25270 } 25271 25272 private static void enforceSystemOrPhoneCaller(String tag) { 25273 int callingUid = Binder.getCallingUid(); 25274 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 25275 throw new SecurityException( 25276 "Cannot call " + tag + " from UID " + callingUid); 25277 } 25278 } 25279 25280 boolean isHistoricalPackageUsageAvailable() { 25281 return mPackageUsage.isHistoricalPackageUsageAvailable(); 25282 } 25283 25284 /** 25285 * Return a <b>copy</b> of the collection of packages known to the package manager. 25286 * @return A copy of the values of mPackages. 25287 */ 25288 Collection<PackageParser.Package> getPackages() { 25289 synchronized (mPackages) { 25290 return new ArrayList<>(mPackages.values()); 25291 } 25292 } 25293 25294 /** 25295 * Logs process start information (including base APK hash) to the security log. 25296 * @hide 25297 */ 25298 @Override 25299 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 25300 String apkFile, int pid) { 25301 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 25302 return; 25303 } 25304 if (!SecurityLog.isLoggingEnabled()) { 25305 return; 25306 } 25307 Bundle data = new Bundle(); 25308 data.putLong("startTimestamp", System.currentTimeMillis()); 25309 data.putString("processName", processName); 25310 data.putInt("uid", uid); 25311 data.putString("seinfo", seinfo); 25312 data.putString("apkFile", apkFile); 25313 data.putInt("pid", pid); 25314 Message msg = mProcessLoggingHandler.obtainMessage( 25315 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 25316 msg.setData(data); 25317 mProcessLoggingHandler.sendMessage(msg); 25318 } 25319 25320 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 25321 return mCompilerStats.getPackageStats(pkgName); 25322 } 25323 25324 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 25325 return getOrCreateCompilerPackageStats(pkg.packageName); 25326 } 25327 25328 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 25329 return mCompilerStats.getOrCreatePackageStats(pkgName); 25330 } 25331 25332 public void deleteCompilerPackageStats(String pkgName) { 25333 mCompilerStats.deletePackageStats(pkgName); 25334 } 25335 25336 @Override 25337 public int getInstallReason(String packageName, int userId) { 25338 final int callingUid = Binder.getCallingUid(); 25339 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 25340 true /* requireFullPermission */, false /* checkShell */, 25341 "get install reason"); 25342 synchronized (mPackages) { 25343 final PackageSetting ps = mSettings.mPackages.get(packageName); 25344 if (filterAppAccessLPr(ps, callingUid, userId)) { 25345 return PackageManager.INSTALL_REASON_UNKNOWN; 25346 } 25347 if (ps != null) { 25348 return ps.getInstallReason(userId); 25349 } 25350 } 25351 return PackageManager.INSTALL_REASON_UNKNOWN; 25352 } 25353 25354 @Override 25355 public boolean canRequestPackageInstalls(String packageName, int userId) { 25356 return canRequestPackageInstallsInternal(packageName, 0, userId, 25357 true /* throwIfPermNotDeclared*/); 25358 } 25359 25360 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 25361 boolean throwIfPermNotDeclared) { 25362 int callingUid = Binder.getCallingUid(); 25363 int uid = getPackageUid(packageName, 0, userId); 25364 if (callingUid != uid && callingUid != Process.ROOT_UID 25365 && callingUid != Process.SYSTEM_UID) { 25366 throw new SecurityException( 25367 "Caller uid " + callingUid + " does not own package " + packageName); 25368 } 25369 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 25370 if (info == null) { 25371 return false; 25372 } 25373 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 25374 return false; 25375 } 25376 if (isInstantApp(packageName, userId)) { 25377 return false; 25378 } 25379 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 25380 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 25381 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 25382 if (throwIfPermNotDeclared) { 25383 throw new SecurityException("Need to declare " + appOpPermission 25384 + " to call this api"); 25385 } else { 25386 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 25387 return false; 25388 } 25389 } 25390 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId) 25391 || sUserManager.hasUserRestriction( 25392 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, userId)) { 25393 return false; 25394 } 25395 if (mExternalSourcesPolicy != null) { 25396 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 25397 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 25398 } 25399 return false; 25400 } 25401 25402 @Override 25403 public ComponentName getInstantAppResolverSettingsComponent() { 25404 return mInstantAppResolverSettingsComponent; 25405 } 25406 25407 @Override 25408 public ComponentName getInstantAppInstallerComponent() { 25409 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 25410 return null; 25411 } 25412 return mInstantAppInstallerActivity == null 25413 ? null : mInstantAppInstallerActivity.getComponentName(); 25414 } 25415 25416 @Override 25417 public String getInstantAppAndroidId(String packageName, int userId) { 25418 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 25419 "getInstantAppAndroidId"); 25420 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 25421 true /* requireFullPermission */, false /* checkShell */, 25422 "getInstantAppAndroidId"); 25423 // Make sure the target is an Instant App. 25424 if (!isInstantApp(packageName, userId)) { 25425 return null; 25426 } 25427 synchronized (mPackages) { 25428 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 25429 } 25430 } 25431 25432 boolean canHaveOatDir(String packageName) { 25433 synchronized (mPackages) { 25434 PackageParser.Package p = mPackages.get(packageName); 25435 if (p == null) { 25436 return false; 25437 } 25438 return p.canHaveOatDir(); 25439 } 25440 } 25441 25442 private String getOatDir(PackageParser.Package pkg) { 25443 if (!pkg.canHaveOatDir()) { 25444 return null; 25445 } 25446 File codePath = new File(pkg.codePath); 25447 if (codePath.isDirectory()) { 25448 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 25449 } 25450 return null; 25451 } 25452 25453 void deleteOatArtifactsOfPackage(String packageName) { 25454 final String[] instructionSets; 25455 final List<String> codePaths; 25456 final String oatDir; 25457 final PackageParser.Package pkg; 25458 synchronized (mPackages) { 25459 pkg = mPackages.get(packageName); 25460 } 25461 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 25462 codePaths = pkg.getAllCodePaths(); 25463 oatDir = getOatDir(pkg); 25464 25465 for (String codePath : codePaths) { 25466 for (String isa : instructionSets) { 25467 try { 25468 mInstaller.deleteOdex(codePath, isa, oatDir); 25469 } catch (InstallerException e) { 25470 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 25471 } 25472 } 25473 } 25474 } 25475 25476 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 25477 Set<String> unusedPackages = new HashSet<>(); 25478 long currentTimeInMillis = System.currentTimeMillis(); 25479 synchronized (mPackages) { 25480 for (PackageParser.Package pkg : mPackages.values()) { 25481 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 25482 if (ps == null) { 25483 continue; 25484 } 25485 PackageDexUsage.PackageUseInfo packageUseInfo = 25486 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 25487 if (PackageManagerServiceUtils 25488 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 25489 downgradeTimeThresholdMillis, packageUseInfo, 25490 pkg.getLatestPackageUseTimeInMills(), 25491 pkg.getLatestForegroundPackageUseTimeInMills())) { 25492 unusedPackages.add(pkg.packageName); 25493 } 25494 } 25495 } 25496 return unusedPackages; 25497 } 25498 25499 @Override 25500 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 25501 int userId) { 25502 final int callingUid = Binder.getCallingUid(); 25503 final int callingAppId = UserHandle.getAppId(callingUid); 25504 25505 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 25506 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 25507 25508 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 25509 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 25510 throw new SecurityException("Caller must have the " 25511 + SET_HARMFUL_APP_WARNINGS + " permission."); 25512 } 25513 25514 synchronized(mPackages) { 25515 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 25516 scheduleWritePackageRestrictionsLocked(userId); 25517 } 25518 } 25519 25520 @Nullable 25521 @Override 25522 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 25523 final int callingUid = Binder.getCallingUid(); 25524 final int callingAppId = UserHandle.getAppId(callingUid); 25525 25526 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 25527 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 25528 25529 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 25530 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 25531 throw new SecurityException("Caller must have the " 25532 + SET_HARMFUL_APP_WARNINGS + " permission."); 25533 } 25534 25535 synchronized(mPackages) { 25536 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 25537 } 25538 } 25539 25540 @Override 25541 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 25542 final int callingUid = Binder.getCallingUid(); 25543 final int callingAppId = UserHandle.getAppId(callingUid); 25544 25545 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 25546 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected"); 25547 25548 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID 25549 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) { 25550 throw new SecurityException("Caller must have the " 25551 + MANAGE_DEVICE_ADMINS + " permission."); 25552 } 25553 25554 return mProtectedPackages.isPackageStateProtected(userId, packageName); 25555 } 25556 25557 @Override 25558 public void sendDeviceCustomizationReadyBroadcast() { 25559 mContext.enforceCallingPermission(Manifest.permission.SEND_DEVICE_CUSTOMIZATION_READY, 25560 "sendDeviceCustomizationReadyBroadcast"); 25561 25562 final long ident = Binder.clearCallingIdentity(); 25563 try { 25564 final Intent intent = new Intent(Intent.ACTION_DEVICE_CUSTOMIZATION_READY); 25565 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 25566 final IActivityManager am = ActivityManager.getService(); 25567 final String[] requiredPermissions = { 25568 Manifest.permission.RECEIVE_DEVICE_CUSTOMIZATION_READY, 25569 }; 25570 try { 25571 am.broadcastIntent(null, intent, null, null, 0, null, null, requiredPermissions, 25572 android.app.AppOpsManager.OP_NONE, null, false, false, UserHandle.USER_ALL); 25573 } catch (RemoteException e) { 25574 throw e.rethrowFromSystemServer(); 25575 } 25576 } finally { 25577 Binder.restoreCallingIdentity(ident); 25578 } 25579 } 25580 25581 static class ActiveInstallSession { 25582 private final String mPackageName; 25583 private final File mStagedDir; 25584 private final IPackageInstallObserver2 mObserver; 25585 private final PackageInstaller.SessionParams mSessionParams; 25586 private final String mInstallerPackageName; 25587 private final int mInstallerUid; 25588 private final UserHandle mUser; 25589 private final SigningDetails mSigningDetails; 25590 25591 ActiveInstallSession(String packageName, File stagedDir, IPackageInstallObserver2 observer, 25592 PackageInstaller.SessionParams sessionParams, String installerPackageName, 25593 int installerUid, UserHandle user, SigningDetails signingDetails) { 25594 mPackageName = packageName; 25595 mStagedDir = stagedDir; 25596 mObserver = observer; 25597 mSessionParams = sessionParams; 25598 mInstallerPackageName = installerPackageName; 25599 mInstallerUid = installerUid; 25600 mUser = user; 25601 mSigningDetails = signingDetails; 25602 } 25603 25604 public String getPackageName() { 25605 return mPackageName; 25606 } 25607 25608 public File getStagedDir() { 25609 return mStagedDir; 25610 } 25611 25612 public IPackageInstallObserver2 getObserver() { 25613 return mObserver; 25614 } 25615 25616 public PackageInstaller.SessionParams getSessionParams() { 25617 return mSessionParams; 25618 } 25619 25620 public String getInstallerPackageName() { 25621 return mInstallerPackageName; 25622 } 25623 25624 public int getInstallerUid() { 25625 return mInstallerUid; 25626 } 25627 25628 public UserHandle getUser() { 25629 return mUser; 25630 } 25631 25632 public SigningDetails getSigningDetails() { 25633 return mSigningDetails; 25634 } 25635 } 25636 } 25637 25638 interface PackageSender { 25639 /** 25640 * @param userIds User IDs where the action occurred on a full application 25641 * @param instantUserIds User IDs where the action occurred on an instant application 25642 */ 25643 void sendPackageBroadcast(final String action, final String pkg, 25644 final Bundle extras, final int flags, final String targetPkg, 25645 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 25646 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 25647 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 25648 void notifyPackageAdded(String packageName, int uid); 25649 void notifyPackageChanged(String packageName, int uid); 25650 void notifyPackageRemoved(String packageName, int uid); 25651 } 25652