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.annotations.VisibleForTesting.Visibility; 95 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 96 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 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.PackageManagerServiceCompilerMapping.getDefaultCompilerFilter; 104 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 105 import static com.android.server.pm.PackageManagerServiceUtils.compressedFileExists; 106 import static com.android.server.pm.PackageManagerServiceUtils.decompressFile; 107 import static com.android.server.pm.PackageManagerServiceUtils.deriveAbiOverride; 108 import static com.android.server.pm.PackageManagerServiceUtils.dumpCriticalInfo; 109 import static com.android.server.pm.PackageManagerServiceUtils.getCompressedFiles; 110 import static com.android.server.pm.PackageManagerServiceUtils.getLastModifiedTime; 111 import static com.android.server.pm.PackageManagerServiceUtils.logCriticalInfo; 112 import static com.android.server.pm.PackageManagerServiceUtils.verifySignatures; 113 114 import android.Manifest; 115 import android.annotation.IntDef; 116 import android.annotation.NonNull; 117 import android.annotation.Nullable; 118 import android.annotation.UserIdInt; 119 import android.app.ActivityManager; 120 import android.app.ActivityManagerInternal; 121 import android.app.AppOpsManager; 122 import android.app.BroadcastOptions; 123 import android.app.IActivityManager; 124 import android.app.ResourcesManager; 125 import android.app.admin.IDevicePolicyManager; 126 import android.app.admin.SecurityLog; 127 import android.app.backup.IBackupManager; 128 import android.content.BroadcastReceiver; 129 import android.content.ComponentName; 130 import android.content.ContentResolver; 131 import android.content.Context; 132 import android.content.IIntentReceiver; 133 import android.content.Intent; 134 import android.content.IntentFilter; 135 import android.content.IntentSender; 136 import android.content.IntentSender.SendIntentException; 137 import android.content.pm.ActivityInfo; 138 import android.content.pm.ApplicationInfo; 139 import android.content.pm.AppsQueryHelper; 140 import android.content.pm.AuxiliaryResolveInfo; 141 import android.content.pm.ChangedPackages; 142 import android.content.pm.ComponentInfo; 143 import android.content.pm.FallbackCategoryProvider; 144 import android.content.pm.FeatureInfo; 145 import android.content.pm.IDexModuleRegisterCallback; 146 import android.content.pm.IOnPermissionsChangeListener; 147 import android.content.pm.IPackageDataObserver; 148 import android.content.pm.IPackageDeleteObserver; 149 import android.content.pm.IPackageDeleteObserver2; 150 import android.content.pm.IPackageInstallObserver2; 151 import android.content.pm.IPackageInstaller; 152 import android.content.pm.IPackageManager; 153 import android.content.pm.IPackageManagerNative; 154 import android.content.pm.IPackageMoveObserver; 155 import android.content.pm.IPackageStatsObserver; 156 import android.content.pm.InstantAppInfo; 157 import android.content.pm.InstantAppRequest; 158 import android.content.pm.InstrumentationInfo; 159 import android.content.pm.IntentFilterVerificationInfo; 160 import android.content.pm.KeySet; 161 import android.content.pm.ModuleInfo; 162 import android.content.pm.PackageBackwardCompatibility; 163 import android.content.pm.PackageInfo; 164 import android.content.pm.PackageInfoLite; 165 import android.content.pm.PackageInstaller; 166 import android.content.pm.PackageList; 167 import android.content.pm.PackageManager; 168 import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 169 import android.content.pm.PackageManager.ModuleInfoFlags; 170 import android.content.pm.PackageManager.PermissionWhitelistFlags; 171 import android.content.pm.PackageManagerInternal; 172 import android.content.pm.PackageManagerInternal.CheckPermissionDelegate; 173 import android.content.pm.PackageManagerInternal.PackageListObserver; 174 import android.content.pm.PackageParser; 175 import android.content.pm.PackageParser.ActivityIntentInfo; 176 import android.content.pm.PackageParser.PackageLite; 177 import android.content.pm.PackageParser.PackageParserException; 178 import android.content.pm.PackageParser.ParseFlags; 179 import android.content.pm.PackageParser.SigningDetails; 180 import android.content.pm.PackageParser.SigningDetails.SignatureSchemeVersion; 181 import android.content.pm.PackageStats; 182 import android.content.pm.PackageUserState; 183 import android.content.pm.ParceledListSlice; 184 import android.content.pm.PermissionGroupInfo; 185 import android.content.pm.PermissionInfo; 186 import android.content.pm.ProviderInfo; 187 import android.content.pm.ResolveInfo; 188 import android.content.pm.SELinuxUtil; 189 import android.content.pm.ServiceInfo; 190 import android.content.pm.SharedLibraryInfo; 191 import android.content.pm.Signature; 192 import android.content.pm.SuspendDialogInfo; 193 import android.content.pm.UserInfo; 194 import android.content.pm.VerifierDeviceIdentity; 195 import android.content.pm.VerifierInfo; 196 import android.content.pm.VersionedPackage; 197 import android.content.pm.dex.ArtManager; 198 import android.content.pm.dex.DexMetadataHelper; 199 import android.content.pm.dex.IArtManager; 200 import android.content.pm.permission.SplitPermissionInfoParcelable; 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.ConditionVariable; 212 import android.os.Debug; 213 import android.os.Environment; 214 import android.os.FileUtils; 215 import android.os.Handler; 216 import android.os.IBinder; 217 import android.os.Looper; 218 import android.os.Message; 219 import android.os.Parcel; 220 import android.os.PatternMatcher; 221 import android.os.PersistableBundle; 222 import android.os.Process; 223 import android.os.RemoteCallbackList; 224 import android.os.RemoteException; 225 import android.os.ResultReceiver; 226 import android.os.SELinux; 227 import android.os.ServiceManager; 228 import android.os.ShellCallback; 229 import android.os.SystemClock; 230 import android.os.SystemProperties; 231 import android.os.Trace; 232 import android.os.UserHandle; 233 import android.os.UserManager; 234 import android.os.UserManagerInternal; 235 import android.os.storage.DiskInfo; 236 import android.os.storage.IStorageManager; 237 import android.os.storage.StorageEventListener; 238 import android.os.storage.StorageManager; 239 import android.os.storage.StorageManagerInternal; 240 import android.os.storage.VolumeInfo; 241 import android.os.storage.VolumeRecord; 242 import android.permission.PermissionManager; 243 import android.provider.DeviceConfig; 244 import android.provider.MediaStore; 245 import android.provider.Settings.Global; 246 import android.provider.Settings.Secure; 247 import android.security.KeyStore; 248 import android.security.SystemKeyStore; 249 import android.service.pm.PackageServiceDumpProto; 250 import android.stats.storage.StorageEnums; 251 import android.system.ErrnoException; 252 import android.system.Os; 253 import android.text.TextUtils; 254 import android.text.format.DateUtils; 255 import android.util.ArrayMap; 256 import android.util.ArraySet; 257 import android.util.Base64; 258 import android.util.DisplayMetrics; 259 import android.util.EventLog; 260 import android.util.ExceptionUtils; 261 import android.util.IntArray; 262 import android.util.Log; 263 import android.util.LogPrinter; 264 import android.util.LongSparseArray; 265 import android.util.LongSparseLongArray; 266 import android.util.MathUtils; 267 import android.util.PackageUtils; 268 import android.util.Pair; 269 import android.util.PrintStreamPrinter; 270 import android.util.Slog; 271 import android.util.SparseArray; 272 import android.util.SparseBooleanArray; 273 import android.util.SparseIntArray; 274 import android.util.StatsLog; 275 import android.util.TimingsTraceLog; 276 import android.util.Xml; 277 import android.util.jar.StrictJarFile; 278 import android.util.proto.ProtoOutputStream; 279 import android.view.Display; 280 281 import com.android.internal.R; 282 import com.android.internal.annotations.GuardedBy; 283 import com.android.internal.annotations.VisibleForTesting; 284 import com.android.internal.app.ResolverActivity; 285 import com.android.internal.content.NativeLibraryHelper; 286 import com.android.internal.content.PackageHelper; 287 import com.android.internal.logging.MetricsLogger; 288 import com.android.internal.os.SomeArgs; 289 import com.android.internal.os.Zygote; 290 import com.android.internal.telephony.CarrierAppUtils; 291 import com.android.internal.util.ArrayUtils; 292 import com.android.internal.util.ConcurrentUtils; 293 import com.android.internal.util.DumpUtils; 294 import com.android.internal.util.FastXmlSerializer; 295 import com.android.internal.util.IndentingPrintWriter; 296 import com.android.internal.util.IntPair; 297 import com.android.internal.util.Preconditions; 298 import com.android.server.AttributeCache; 299 import com.android.server.DeviceIdleController; 300 import com.android.server.EventLogTags; 301 import com.android.server.FgThread; 302 import com.android.server.LocalServices; 303 import com.android.server.LockGuard; 304 import com.android.server.PackageWatchdog; 305 import com.android.server.ServiceThread; 306 import com.android.server.SystemConfig; 307 import com.android.server.SystemServerInitThreadPool; 308 import com.android.server.Watchdog; 309 import com.android.server.net.NetworkPolicyManagerInternal; 310 import com.android.server.pm.Installer.InstallerException; 311 import com.android.server.pm.Settings.DatabaseVersion; 312 import com.android.server.pm.Settings.VersionInfo; 313 import com.android.server.pm.dex.ArtManagerService; 314 import com.android.server.pm.dex.DexManager; 315 import com.android.server.pm.dex.DexoptOptions; 316 import com.android.server.pm.dex.PackageDexUsage; 317 import com.android.server.pm.dex.ViewCompiler; 318 import com.android.server.pm.permission.BasePermission; 319 import com.android.server.pm.permission.DefaultPermissionGrantPolicy; 320 import com.android.server.pm.permission.PermissionManagerService; 321 import com.android.server.pm.permission.PermissionManagerServiceInternal; 322 import com.android.server.pm.permission.PermissionManagerServiceInternal.PermissionCallback; 323 import com.android.server.pm.permission.PermissionsState; 324 import com.android.server.policy.PermissionPolicyInternal; 325 import com.android.server.security.VerityUtils; 326 import com.android.server.storage.DeviceStorageMonitorInternal; 327 import com.android.server.wm.ActivityTaskManagerInternal; 328 329 import dalvik.system.CloseGuard; 330 import dalvik.system.VMRuntime; 331 332 import libcore.io.IoUtils; 333 import libcore.util.EmptyArray; 334 import libcore.util.HexEncoding; 335 336 import org.xmlpull.v1.XmlPullParser; 337 import org.xmlpull.v1.XmlPullParserException; 338 import org.xmlpull.v1.XmlSerializer; 339 340 import java.io.BufferedOutputStream; 341 import java.io.ByteArrayInputStream; 342 import java.io.ByteArrayOutputStream; 343 import java.io.File; 344 import java.io.FileDescriptor; 345 import java.io.FileInputStream; 346 import java.io.FileOutputStream; 347 import java.io.FilenameFilter; 348 import java.io.IOException; 349 import java.io.PrintWriter; 350 import java.lang.annotation.Retention; 351 import java.lang.annotation.RetentionPolicy; 352 import java.nio.charset.StandardCharsets; 353 import java.security.DigestException; 354 import java.security.DigestInputStream; 355 import java.security.MessageDigest; 356 import java.security.NoSuchAlgorithmException; 357 import java.security.PublicKey; 358 import java.security.SecureRandom; 359 import java.security.cert.CertificateException; 360 import java.util.ArrayList; 361 import java.util.Arrays; 362 import java.util.Collection; 363 import java.util.Collections; 364 import java.util.Comparator; 365 import java.util.HashMap; 366 import java.util.HashSet; 367 import java.util.Iterator; 368 import java.util.LinkedHashSet; 369 import java.util.List; 370 import java.util.Map; 371 import java.util.Objects; 372 import java.util.Set; 373 import java.util.concurrent.CountDownLatch; 374 import java.util.concurrent.Future; 375 import java.util.concurrent.TimeUnit; 376 import java.util.concurrent.atomic.AtomicBoolean; 377 import java.util.concurrent.atomic.AtomicInteger; 378 import java.util.function.BiConsumer; 379 import java.util.function.Consumer; 380 import java.util.function.Predicate; 381 import java.util.stream.Collectors; 382 383 /** 384 * Keep track of all those APKs everywhere. 385 * <p> 386 * Internally there are two important locks: 387 * <ul> 388 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 389 * and other related state. It is a fine-grained lock that should only be held 390 * momentarily, as it's one of the most contended locks in the system. 391 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 392 * operations typically involve heavy lifting of application data on disk. Since 393 * {@code installd} is single-threaded, and it's operations can often be slow, 394 * this lock should never be acquired while already holding {@link #mPackages}. 395 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 396 * holding {@link #mInstallLock}. 397 * </ul> 398 * Many internal methods rely on the caller to hold the appropriate locks, and 399 * this contract is expressed through method name suffixes: 400 * <ul> 401 * <li>fooLI(): the caller must hold {@link #mInstallLock} 402 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 403 * being modified must be frozen 404 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 405 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 406 * </ul> 407 * <p> 408 * Because this class is very central to the platform's security; please run all 409 * CTS and unit tests whenever making modifications: 410 * 411 * <pre> 412 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 413 * $ cts-tradefed run commandAndExit cts -m CtsAppSecurityHostTestCases 414 * </pre> 415 */ 416 public class PackageManagerService extends IPackageManager.Stub 417 implements PackageSender { 418 static final String TAG = "PackageManager"; 419 public static final boolean DEBUG_SETTINGS = false; 420 static final boolean DEBUG_PREFERRED = false; 421 static final boolean DEBUG_UPGRADE = false; 422 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 423 private static final boolean DEBUG_BACKUP = false; 424 public static final boolean DEBUG_INSTALL = false; 425 public static final boolean DEBUG_REMOVE = false; 426 private static final boolean DEBUG_BROADCASTS = false; 427 private static final boolean DEBUG_PACKAGE_INFO = false; 428 private static final boolean DEBUG_INTENT_MATCHING = false; 429 public static final boolean DEBUG_PACKAGE_SCANNING = false; 430 private static final boolean DEBUG_VERIFY = false; 431 public static final boolean DEBUG_PERMISSIONS = false; 432 private static final boolean DEBUG_SHARED_LIBRARIES = false; 433 public static final boolean DEBUG_COMPRESSION = Build.IS_DEBUGGABLE; 434 435 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 436 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 437 // user, but by default initialize to this. 438 public static final boolean DEBUG_DEXOPT = false; 439 440 static final boolean DEBUG_ABI_SELECTION = false; 441 private static final boolean DEBUG_INSTANT = Build.IS_DEBUGGABLE; 442 private static final boolean DEBUG_APP_DATA = false; 443 444 /** REMOVE. According to Svet, this was only used to reset permissions during development. */ 445 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 446 447 private static final boolean HIDE_EPHEMERAL_APIS = false; 448 449 private static final boolean ENABLE_FREE_CACHE_V2 = 450 SystemProperties.getBoolean("fw.free_cache_v2", true); 451 452 private static final String PRECOMPILE_LAYOUTS = "pm.precompile_layouts"; 453 454 private static final int RADIO_UID = Process.PHONE_UID; 455 private static final int LOG_UID = Process.LOG_UID; 456 private static final int NFC_UID = Process.NFC_UID; 457 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 458 private static final int SHELL_UID = Process.SHELL_UID; 459 private static final int SE_UID = Process.SE_UID; 460 private static final int NETWORKSTACK_UID = Process.NETWORK_STACK_UID; 461 462 static final int SCAN_NO_DEX = 1 << 0; 463 static final int SCAN_UPDATE_SIGNATURE = 1 << 1; 464 static final int SCAN_NEW_INSTALL = 1 << 2; 465 static final int SCAN_UPDATE_TIME = 1 << 3; 466 static final int SCAN_BOOTING = 1 << 4; 467 static final int SCAN_REQUIRE_KNOWN = 1 << 7; 468 static final int SCAN_MOVE = 1 << 8; 469 static final int SCAN_INITIAL = 1 << 9; 470 static final int SCAN_CHECK_ONLY = 1 << 10; 471 static final int SCAN_DONT_KILL_APP = 1 << 11; 472 static final int SCAN_IGNORE_FROZEN = 1 << 12; 473 static final int SCAN_FIRST_BOOT_OR_UPGRADE = 1 << 13; 474 static final int SCAN_AS_INSTANT_APP = 1 << 14; 475 static final int SCAN_AS_FULL_APP = 1 << 15; 476 static final int SCAN_AS_VIRTUAL_PRELOAD = 1 << 16; 477 static final int SCAN_AS_SYSTEM = 1 << 17; 478 static final int SCAN_AS_PRIVILEGED = 1 << 18; 479 static final int SCAN_AS_OEM = 1 << 19; 480 static final int SCAN_AS_VENDOR = 1 << 20; 481 static final int SCAN_AS_PRODUCT = 1 << 21; 482 static final int SCAN_AS_SYSTEM_EXT = 1 << 22; 483 static final int SCAN_AS_ODM = 1 << 23; 484 485 @IntDef(flag = true, prefix = { "SCAN_" }, value = { 486 SCAN_NO_DEX, 487 SCAN_UPDATE_SIGNATURE, 488 SCAN_NEW_INSTALL, 489 SCAN_UPDATE_TIME, 490 SCAN_BOOTING, 491 SCAN_REQUIRE_KNOWN, 492 SCAN_MOVE, 493 SCAN_INITIAL, 494 SCAN_CHECK_ONLY, 495 SCAN_DONT_KILL_APP, 496 SCAN_IGNORE_FROZEN, 497 SCAN_FIRST_BOOT_OR_UPGRADE, 498 SCAN_AS_INSTANT_APP, 499 SCAN_AS_FULL_APP, 500 SCAN_AS_VIRTUAL_PRELOAD, 501 }) 502 @Retention(RetentionPolicy.SOURCE) 503 public @interface ScanFlags {} 504 505 private static final String STATIC_SHARED_LIB_DELIMITER = "_"; 506 /** Extension of the compressed packages */ 507 public final static String COMPRESSED_EXTENSION = ".gz"; 508 /** Suffix of stub packages on the system partition */ 509 public final static String STUB_SUFFIX = "-Stub"; 510 511 private static final int[] EMPTY_INT_ARRAY = new int[0]; 512 513 private static final int TYPE_UNKNOWN = 0; 514 private static final int TYPE_ACTIVITY = 1; 515 private static final int TYPE_RECEIVER = 2; 516 private static final int TYPE_SERVICE = 3; 517 private static final int TYPE_PROVIDER = 4; 518 @IntDef(prefix = { "TYPE_" }, value = { 519 TYPE_UNKNOWN, 520 TYPE_ACTIVITY, 521 TYPE_RECEIVER, 522 TYPE_SERVICE, 523 TYPE_PROVIDER, 524 }) 525 @Retention(RetentionPolicy.SOURCE) 526 public @interface ComponentType {} 527 528 /** 529 * Timeout (in milliseconds) after which the watchdog should declare that 530 * our handler thread is wedged. The usual default for such things is one 531 * minute but we sometimes do very lengthy I/O operations on this thread, 532 * such as installing multi-gigabyte applications, so ours needs to be longer. 533 */ 534 static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 535 536 /** 537 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 538 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 539 * settings entry if available, otherwise we use the hardcoded default. If it's been 540 * more than this long since the last fstrim, we force one during the boot sequence. 541 * 542 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 543 * one gets run at the next available charging+idle time. This final mandatory 544 * no-fstrim check kicks in only of the other scheduling criteria is never met. 545 */ 546 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 547 548 /** 549 * Whether verification is enabled by default. 550 */ 551 private static final boolean DEFAULT_VERIFY_ENABLE = true; 552 553 /** 554 * The default maximum time to wait for the verification agent to return in 555 * milliseconds. 556 */ 557 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 558 559 /** 560 * Timeout duration in milliseconds for enabling package rollback. If we fail to enable 561 * rollback within that period, the install will proceed without rollback enabled. 562 * 563 * <p>If flag value is negative, the default value will be assigned. 564 * 565 * Flag type: {@code long} 566 * Namespace: NAMESPACE_ROLLBACK 567 */ 568 private static final String PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS = "enable_rollback_timeout"; 569 570 /** 571 * The default duration to wait for rollback to be enabled in 572 * milliseconds. 573 */ 574 private static final long DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS = 10 * 1000; 575 576 /** 577 * The default response for package verification timeout. 578 * 579 * This can be either PackageManager.VERIFICATION_ALLOW or 580 * PackageManager.VERIFICATION_REJECT. 581 */ 582 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 583 584 public static final String PLATFORM_PACKAGE_NAME = "android"; 585 586 private static final String KILL_APP_REASON_GIDS_CHANGED = 587 "permission grant or revoke changed gids"; 588 589 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 590 "permissions revoked"; 591 592 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 593 594 private static final String PACKAGE_SCHEME = "package"; 595 596 /** Canonical intent used to identify what counts as a "web browser" app */ 597 private static final Intent sBrowserIntent; 598 static { 599 sBrowserIntent = new Intent(); 600 sBrowserIntent.setAction(Intent.ACTION_VIEW); 601 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 602 sBrowserIntent.setData(Uri.parse("http:")); 603 sBrowserIntent.addFlags(Intent.FLAG_IGNORE_EPHEMERAL); 604 } 605 606 // Compilation reasons. 607 public static final int REASON_UNKNOWN = -1; 608 public static final int REASON_FIRST_BOOT = 0; 609 public static final int REASON_BOOT = 1; 610 public static final int REASON_INSTALL = 2; 611 public static final int REASON_BACKGROUND_DEXOPT = 3; 612 public static final int REASON_AB_OTA = 4; 613 public static final int REASON_INACTIVE_PACKAGE_DOWNGRADE = 5; 614 public static final int REASON_SHARED = 6; 615 616 public static final int REASON_LAST = REASON_SHARED; 617 618 /** 619 * Whether the package parser cache is enabled. 620 */ 621 private static final boolean DEFAULT_PACKAGE_PARSER_CACHE_ENABLED = true; 622 623 /** 624 * Permissions required in order to receive instant application lifecycle broadcasts. 625 */ 626 private static final String[] INSTANT_APP_BROADCAST_PERMISSION = 627 new String[] { android.Manifest.permission.ACCESS_INSTANT_APPS }; 628 629 final ServiceThread mHandlerThread; 630 631 final PackageHandler mHandler; 632 633 private final ProcessLoggingHandler mProcessLoggingHandler; 634 635 final int mSdkVersion = Build.VERSION.SDK_INT; 636 637 final Context mContext; 638 final boolean mFactoryTest; 639 final boolean mOnlyCore; 640 final DisplayMetrics mMetrics; 641 final int mDefParseFlags; 642 final String[] mSeparateProcesses; 643 final boolean mIsUpgrade; 644 final boolean mIsPreNUpgrade; 645 final boolean mIsPreNMR1Upgrade; 646 final boolean mIsPreQUpgrade; 647 648 @GuardedBy("mPackages") 649 private boolean mDexOptDialogShown; 650 651 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 652 // LOCK HELD. Can be called with mInstallLock held. 653 @GuardedBy("mInstallLock") 654 final Installer mInstaller; 655 656 /** Directory where installed applications are stored */ 657 private static final File sAppInstallDir = 658 new File(Environment.getDataDirectory(), "app"); 659 /** Directory where installed application's 32-bit native libraries are copied. */ 660 @VisibleForTesting 661 static final File sAppLib32InstallDir = 662 new File(Environment.getDataDirectory(), "app-lib"); 663 664 // ---------------------------------------------------------------- 665 666 // Lock for state used when installing and doing other long running 667 // operations. Methods that must be called with this lock held have 668 // the suffix "LI". 669 final Object mInstallLock = new Object(); 670 671 // ---------------------------------------------------------------- 672 673 // Keys are String (package name), values are Package. This also serves 674 // as the lock for the global state. Methods that must be called with 675 // this lock held have the prefix "LP". 676 @GuardedBy("mPackages") 677 final ArrayMap<String, PackageParser.Package> mPackages = new ArrayMap<>(); 678 679 // Keys are isolated uids and values are the uid of the application 680 // that created the isolated proccess. 681 @GuardedBy("mPackages") 682 final SparseIntArray mIsolatedOwners = new SparseIntArray(); 683 684 /** 685 * Tracks new system packages [received in an OTA] that we expect to 686 * find updated user-installed versions. Keys are package name, values 687 * are package location. 688 */ 689 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 690 691 /** 692 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 693 */ 694 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 695 /** 696 * Whether or not system app permissions should be promoted from install to runtime. 697 */ 698 boolean mPromoteSystemApps; 699 700 @GuardedBy("mPackages") 701 final Settings mSettings; 702 703 /** 704 * Set of package names that are currently "frozen", which means active 705 * surgery is being done on the code/data for that package. The platform 706 * will refuse to launch frozen packages to avoid race conditions. 707 * 708 * @see PackageFreezer 709 */ 710 @GuardedBy("mPackages") 711 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 712 713 final ProtectedPackages mProtectedPackages; 714 715 @GuardedBy("mLoadedVolumes") 716 final ArraySet<String> mLoadedVolumes = new ArraySet<>(); 717 718 boolean mFirstBoot; 719 720 PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 721 722 @GuardedBy("mAvailableFeatures") 723 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 724 725 private final InstantAppRegistry mInstantAppRegistry; 726 727 @GuardedBy("mPackages") 728 int mChangedPackagesSequenceNumber; 729 /** 730 * List of changed [installed, removed or updated] packages. 731 * mapping from user id -> sequence number -> package name 732 */ 733 @GuardedBy("mPackages") 734 final SparseArray<SparseArray<String>> mChangedPackages = new SparseArray<>(); 735 /** 736 * The sequence number of the last change to a package. 737 * mapping from user id -> package name -> sequence number 738 */ 739 @GuardedBy("mPackages") 740 final SparseArray<Map<String, Integer>> mChangedPackagesSequenceNumbers = new SparseArray<>(); 741 742 @GuardedBy("mPackages") 743 final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>(); 744 745 @GuardedBy("mPackages") 746 private final SparseIntArray mDefaultPermissionsGrantedUsers = new SparseIntArray(); 747 748 private final ModuleInfoProvider mModuleInfoProvider; 749 750 private final ApexManager mApexManager; 751 752 private final Injector mInjector; 753 754 /** 755 * The list of all system partitions that may contain packages in ascending order of 756 * specificity (the more generic, the earlier in the list a partition appears). 757 */ 758 @VisibleForTesting(visibility = Visibility.PRIVATE) 759 static final List<SystemPartition> SYSTEM_PARTITIONS = Collections.unmodifiableList( 760 Arrays.asList( 761 new SystemPartition(Environment.getRootDirectory(), 0 /* scanFlag */, 762 false /* hasOverlays */), 763 new SystemPartition(Environment.getVendorDirectory(), SCAN_AS_VENDOR, 764 true /* hasOverlays */), 765 new SystemPartition(Environment.getOdmDirectory(), SCAN_AS_ODM, 766 true /* hasOverlays */), 767 new SystemPartition(Environment.getOemDirectory(), SCAN_AS_OEM, 768 true /* hasOverlays */), 769 new SystemPartition(Environment.getProductDirectory(), SCAN_AS_PRODUCT, 770 true /* hasOverlays */), 771 new SystemPartition(Environment.getSystemExtDirectory(), SCAN_AS_SYSTEM_EXT, 772 true /* hasOverlays */))); 773 774 private final List<SystemPartition> mDirsToScanAsSystem; 775 776 /** 777 * Unit tests will instantiate, extend and/or mock to mock dependencies / behaviors. 778 * 779 * NOTE: All getters should return the same instance for every call. 780 */ 781 @VisibleForTesting 782 static class Injector { 783 private final UserManagerInternal mUserManager; 784 private final PackageAbiHelper mAbiHelper; 785 Injector(UserManagerInternal userManager, PackageAbiHelper abiHelper)786 Injector(UserManagerInternal userManager, PackageAbiHelper abiHelper) { 787 mUserManager = userManager; 788 mAbiHelper = abiHelper; 789 } 790 getUserManager()791 public UserManagerInternal getUserManager() { 792 return mUserManager; 793 } 794 getAbiHelper()795 public PackageAbiHelper getAbiHelper() { 796 return mAbiHelper; 797 } 798 } 799 800 class PackageParserCallback implements PackageParser.Callback { hasFeature(String feature)801 @Override public final boolean hasFeature(String feature) { 802 return PackageManagerService.this.hasSystemFeature(feature, 0); 803 } 804 getStaticOverlayPackages( Collection<PackageParser.Package> allPackages, String targetPackageName)805 final List<PackageParser.Package> getStaticOverlayPackages( 806 Collection<PackageParser.Package> allPackages, String targetPackageName) { 807 if ("android".equals(targetPackageName)) { 808 // Static RROs targeting to "android", ie framework-res.apk, are already applied by 809 // native AssetManager. 810 return null; 811 } 812 813 List<PackageParser.Package> overlayPackages = null; 814 for (PackageParser.Package p : allPackages) { 815 if (targetPackageName.equals(p.mOverlayTarget) && p.mOverlayIsStatic) { 816 if (overlayPackages == null) { 817 overlayPackages = new ArrayList<>(); 818 } 819 overlayPackages.add(p); 820 } 821 } 822 if (overlayPackages != null) { 823 Comparator<PackageParser.Package> cmp = 824 Comparator.comparingInt(p -> p.mOverlayPriority); 825 overlayPackages.sort(cmp); 826 } 827 return overlayPackages; 828 } 829 getStaticOverlayPaths(List<PackageParser.Package> overlayPackages, String targetPath)830 final String[] getStaticOverlayPaths(List<PackageParser.Package> overlayPackages, 831 String targetPath) { 832 if (overlayPackages == null || overlayPackages.isEmpty()) { 833 return null; 834 } 835 List<String> overlayPathList = null; 836 for (PackageParser.Package overlayPackage : overlayPackages) { 837 if (targetPath == null) { 838 if (overlayPathList == null) { 839 overlayPathList = new ArrayList<>(); 840 } 841 overlayPathList.add(overlayPackage.baseCodePath); 842 continue; 843 } 844 845 try { 846 // Creates idmaps for system to parse correctly the Android manifest of the 847 // target package. 848 // 849 // OverlayManagerService will update each of them with a correct gid from its 850 // target package app id. 851 mInstaller.idmap(targetPath, overlayPackage.baseCodePath, 852 UserHandle.getSharedAppGid( 853 UserHandle.getUserGid(UserHandle.USER_SYSTEM))); 854 if (overlayPathList == null) { 855 overlayPathList = new ArrayList<>(); 856 } 857 overlayPathList.add(overlayPackage.baseCodePath); 858 } catch (InstallerException e) { 859 Slog.e(TAG, "Failed to generate idmap for " + targetPath + " and " + 860 overlayPackage.baseCodePath); 861 } 862 } 863 return overlayPathList == null ? null : overlayPathList.toArray(new String[0]); 864 } 865 getStaticOverlayPaths(String targetPackageName, String targetPath)866 String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 867 List<PackageParser.Package> overlayPackages; 868 synchronized (mInstallLock) { 869 synchronized (mPackages) { 870 overlayPackages = getStaticOverlayPackages( 871 mPackages.values(), targetPackageName); 872 } 873 // It is safe to keep overlayPackages without holding mPackages because static overlay 874 // packages can't be uninstalled or disabled. 875 return getStaticOverlayPaths(overlayPackages, targetPath); 876 } 877 } 878 getOverlayApks(String targetPackageName)879 @Override public final String[] getOverlayApks(String targetPackageName) { 880 return getStaticOverlayPaths(targetPackageName, null); 881 } 882 getOverlayPaths(String targetPackageName, String targetPath)883 @Override public final String[] getOverlayPaths(String targetPackageName, 884 String targetPath) { 885 return getStaticOverlayPaths(targetPackageName, targetPath); 886 } 887 } 888 889 class ParallelPackageParserCallback extends PackageParserCallback { 890 List<PackageParser.Package> mOverlayPackages = null; 891 findStaticOverlayPackages()892 void findStaticOverlayPackages() { 893 synchronized (mPackages) { 894 for (PackageParser.Package p : mPackages.values()) { 895 if (p.mOverlayIsStatic) { 896 if (mOverlayPackages == null) { 897 mOverlayPackages = new ArrayList<>(); 898 } 899 mOverlayPackages.add(p); 900 } 901 } 902 } 903 } 904 905 @Override getStaticOverlayPaths(String targetPackageName, String targetPath)906 synchronized String[] getStaticOverlayPaths(String targetPackageName, String targetPath) { 907 // We can trust mOverlayPackages without holding mPackages because package uninstall 908 // can't happen while running parallel parsing. 909 // And we can call mInstaller inside getStaticOverlayPaths without holding mInstallLock 910 // because mInstallLock is held before running parallel parsing. 911 // Moreover holding mPackages or mInstallLock on each parsing thread causes dead-lock. 912 return mOverlayPackages == null ? null : 913 getStaticOverlayPaths( 914 getStaticOverlayPackages(mOverlayPackages, targetPackageName), 915 targetPath); 916 } 917 } 918 919 final PackageParser.Callback mPackageParserCallback = new PackageParserCallback(); 920 final ParallelPackageParserCallback mParallelPackageParserCallback = 921 new ParallelPackageParserCallback(); 922 923 // Currently known shared libraries. 924 final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mSharedLibraries = new ArrayMap<>(); 925 final ArrayMap<String, LongSparseArray<SharedLibraryInfo>> mStaticLibsByDeclaringPackage = 926 new ArrayMap<>(); 927 928 // Mapping from instrumentation class names to info about them. 929 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 930 new ArrayMap<>(); 931 932 // Packages whose data we have transfered into another package, thus 933 // should no longer exist. 934 final ArraySet<String> mTransferedPackages = new ArraySet<>(); 935 936 // Broadcast actions that are only available to the system. 937 @GuardedBy("mProtectedBroadcasts") 938 final ArraySet<String> mProtectedBroadcasts = new ArraySet<>(); 939 940 /** List of packages waiting for verification. */ 941 final SparseArray<PackageVerificationState> mPendingVerification = new SparseArray<>(); 942 943 /** List of packages waiting for rollback to be enabled. */ 944 final SparseArray<InstallParams> mPendingEnableRollback = new SparseArray<>(); 945 946 final PackageInstallerService mInstallerService; 947 948 final ArtManagerService mArtManagerService; 949 950 private final PackageDexOptimizer mPackageDexOptimizer; 951 // DexManager handles the usage of dex files (e.g. secondary files, whether or not a package 952 // is used by other apps). 953 private final DexManager mDexManager; 954 955 private final ViewCompiler mViewCompiler; 956 957 private AtomicInteger mNextMoveId = new AtomicInteger(); 958 private final MoveCallbacks mMoveCallbacks; 959 960 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 961 962 // Cache of users who need badging. 963 private final SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 964 965 /** Token for keys in mPendingVerification. */ 966 private int mPendingVerificationToken = 0; 967 968 /** Token for keys in mPendingEnableRollback. */ 969 private int mPendingEnableRollbackToken = 0; 970 971 volatile boolean mSystemReady; 972 volatile boolean mSafeMode; 973 volatile boolean mHasSystemUidErrors; 974 private volatile SparseBooleanArray mWebInstantAppsDisabled = new SparseBooleanArray(); 975 976 ApplicationInfo mAndroidApplication; 977 final ActivityInfo mResolveActivity = new ActivityInfo(); 978 final ResolveInfo mResolveInfo = new ResolveInfo(); 979 ComponentName mResolveComponentName; 980 PackageParser.Package mPlatformPackage; 981 ComponentName mCustomResolverComponentName; 982 983 boolean mResolverReplaced = false; 984 985 private final @Nullable ComponentName mIntentFilterVerifierComponent; 986 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 987 988 private int mIntentFilterVerificationToken = 0; 989 990 /** The service connection to the ephemeral resolver */ 991 final InstantAppResolverConnection mInstantAppResolverConnection; 992 /** Component used to show resolver settings for Instant Apps */ 993 final ComponentName mInstantAppResolverSettingsComponent; 994 995 /** Activity used to install instant applications */ 996 ActivityInfo mInstantAppInstallerActivity; 997 final ResolveInfo mInstantAppInstallerInfo = new ResolveInfo(); 998 999 private final Map<String, Pair<PackageInstalledInfo, IPackageInstallObserver2>> 1000 mNoKillInstallObservers = Collections.synchronizedMap(new HashMap<>()); 1001 1002 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 1003 = new SparseArray<>(); 1004 1005 // TODO remove this and go through mPermissonManager directly 1006 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy; 1007 private final PermissionManagerServiceInternal mPermissionManager; 1008 1009 private final ComponentResolver mComponentResolver; 1010 // List of packages names to keep cached, even if they are uninstalled for all users 1011 private List<String> mKeepUninstalledPackages; 1012 1013 private UserManagerInternal mUserManagerInternal; 1014 private ActivityManagerInternal mActivityManagerInternal; 1015 private ActivityTaskManagerInternal mActivityTaskManagerInternal; 1016 private StorageManagerInternal mStorageManagerInternal; 1017 1018 private DeviceIdleController.LocalService mDeviceIdleController; 1019 1020 private File mCacheDir; 1021 1022 private Future<?> mPrepareAppDataFuture; 1023 1024 private final ConditionVariable mBlockDeleteOnUserRemoveForTest = new ConditionVariable(true); 1025 1026 private static class IFVerificationParams { 1027 PackageParser.Package pkg; 1028 boolean replacing; 1029 int userId; 1030 int verifierUid; 1031 IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, int _userId, int _verifierUid)1032 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 1033 int _userId, int _verifierUid) { 1034 pkg = _pkg; 1035 replacing = _replacing; 1036 userId = _userId; 1037 verifierUid = _verifierUid; 1038 } 1039 } 1040 1041 private interface IntentFilterVerifier<T extends IntentFilter> { addOneIntentFilterVerification(int verifierId, int userId, int verificationId, T filter, String packageName)1042 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 1043 T filter, String packageName); startVerifications(int userId)1044 void startVerifications(int userId); receiveVerificationResponse(int verificationId)1045 void receiveVerificationResponse(int verificationId); 1046 } 1047 1048 @GuardedBy("mPackages") 1049 private CheckPermissionDelegate mCheckPermissionDelegate; 1050 1051 @GuardedBy("mPackages") 1052 private PackageManagerInternal.DefaultBrowserProvider mDefaultBrowserProvider; 1053 1054 @GuardedBy("mPackages") 1055 private PackageManagerInternal.DefaultDialerProvider mDefaultDialerProvider; 1056 1057 @GuardedBy("mPackages") 1058 private PackageManagerInternal.DefaultHomeProvider mDefaultHomeProvider; 1059 1060 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 1061 private Context mContext; 1062 private ComponentName mIntentFilterVerifierComponent; 1063 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<>(); 1064 IntentVerifierProxy(Context context, ComponentName verifierComponent)1065 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 1066 mContext = context; 1067 mIntentFilterVerifierComponent = verifierComponent; 1068 } 1069 getDefaultScheme()1070 private String getDefaultScheme() { 1071 return IntentFilter.SCHEME_HTTPS; 1072 } 1073 1074 @Override startVerifications(int userId)1075 public void startVerifications(int userId) { 1076 // Launch verifications requests 1077 int count = mCurrentIntentFilterVerifications.size(); 1078 for (int n=0; n<count; n++) { 1079 int verificationId = mCurrentIntentFilterVerifications.get(n); 1080 final IntentFilterVerificationState ivs = 1081 mIntentFilterVerificationStates.get(verificationId); 1082 1083 String packageName = ivs.getPackageName(); 1084 1085 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1086 final int filterCount = filters.size(); 1087 ArraySet<String> domainsSet = new ArraySet<>(); 1088 for (int m=0; m<filterCount; m++) { 1089 PackageParser.ActivityIntentInfo filter = filters.get(m); 1090 domainsSet.addAll(filter.getHostsList()); 1091 } 1092 synchronized (mPackages) { 1093 if (mSettings.createIntentFilterVerificationIfNeededLPw( 1094 packageName, domainsSet) != null) { 1095 scheduleWriteSettingsLocked(); 1096 } 1097 } 1098 sendVerificationRequest(verificationId, ivs); 1099 } 1100 mCurrentIntentFilterVerifications.clear(); 1101 } 1102 sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs)1103 private void sendVerificationRequest(int verificationId, IntentFilterVerificationState ivs) { 1104 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 1105 verificationIntent.putExtra( 1106 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 1107 verificationId); 1108 verificationIntent.putExtra( 1109 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 1110 getDefaultScheme()); 1111 verificationIntent.putExtra( 1112 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 1113 ivs.getHostsString()); 1114 verificationIntent.putExtra( 1115 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 1116 ivs.getPackageName()); 1117 verificationIntent.setComponent(mIntentFilterVerifierComponent); 1118 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 1119 1120 final long whitelistTimeout = getVerificationTimeout(); 1121 final BroadcastOptions options = BroadcastOptions.makeBasic(); 1122 options.setTemporaryAppWhitelistDuration(whitelistTimeout); 1123 1124 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 1125 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 1126 mIntentFilterVerifierComponent.getPackageName(), whitelistTimeout, 1127 UserHandle.USER_SYSTEM, true, "intent filter verifier"); 1128 1129 mContext.sendBroadcastAsUser(verificationIntent, UserHandle.SYSTEM, 1130 null, options.toBundle()); 1131 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1132 "Sending IntentFilter verification broadcast"); 1133 } 1134 receiveVerificationResponse(int verificationId)1135 public void receiveVerificationResponse(int verificationId) { 1136 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1137 1138 final boolean verified = ivs.isVerified(); 1139 1140 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 1141 final int count = filters.size(); 1142 if (DEBUG_DOMAIN_VERIFICATION) { 1143 Slog.i(TAG, "Received verification response " + verificationId 1144 + " for " + count + " filters, verified=" + verified); 1145 } 1146 for (int n=0; n<count; n++) { 1147 PackageParser.ActivityIntentInfo filter = filters.get(n); 1148 filter.setVerified(verified); 1149 1150 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 1151 + " verified with result:" + verified + " and hosts:" 1152 + ivs.getHostsString()); 1153 } 1154 1155 mIntentFilterVerificationStates.remove(verificationId); 1156 1157 final String packageName = ivs.getPackageName(); 1158 IntentFilterVerificationInfo ivi; 1159 1160 synchronized (mPackages) { 1161 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 1162 } 1163 if (ivi == null) { 1164 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 1165 + verificationId + " packageName:" + packageName); 1166 return; 1167 } 1168 1169 synchronized (mPackages) { 1170 if (verified) { 1171 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 1172 } else { 1173 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 1174 } 1175 scheduleWriteSettingsLocked(); 1176 1177 final int userId = ivs.getUserId(); 1178 if (userId != UserHandle.USER_ALL) { 1179 final int userStatus = 1180 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 1181 1182 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 1183 boolean needUpdate = false; 1184 1185 if (DEBUG_DOMAIN_VERIFICATION) { 1186 Slog.d(TAG, 1187 "Updating IntentFilterVerificationInfo for package " + packageName 1188 + " verificationId:" + verificationId 1189 + " verified=" + verified); 1190 } 1191 1192 // In a success case, we promote from undefined or ASK to ALWAYS. This 1193 // supports a flow where the app fails validation but then ships an updated 1194 // APK that passes, and therefore deserves to be in ALWAYS. 1195 // 1196 // If validation failed, the undefined state winds up in the basic ASK behavior, 1197 // but apps that previously passed and became ALWAYS are *demoted* out of 1198 // that state, since they would not deserve the ALWAYS behavior in case of a 1199 // clean install. 1200 switch (userStatus) { 1201 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS: 1202 if (!verified) { 1203 // Don't demote if sysconfig says 'always' 1204 SystemConfig systemConfig = SystemConfig.getInstance(); 1205 ArraySet<String> packages = systemConfig.getLinkedApps(); 1206 if (!packages.contains(packageName)) { 1207 // updatedStatus is already UNDEFINED 1208 needUpdate = true; 1209 1210 if (DEBUG_DOMAIN_VERIFICATION) { 1211 Slog.d(TAG, "Formerly validated but now failing; demoting"); 1212 } 1213 } else { 1214 if (DEBUG_DOMAIN_VERIFICATION) { 1215 Slog.d(TAG, "Updating bundled package " + packageName 1216 + " failed autoVerify, but sysconfig supersedes"); 1217 } 1218 // leave needUpdate == false here intentionally 1219 } 1220 } 1221 break; 1222 1223 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 1224 // Stay in 'undefined' on verification failure 1225 if (verified) { 1226 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1227 } 1228 needUpdate = true; 1229 if (DEBUG_DOMAIN_VERIFICATION) { 1230 Slog.d(TAG, "Applying update; old=" + userStatus 1231 + " new=" + updatedStatus); 1232 } 1233 break; 1234 1235 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 1236 // Keep in 'ask' on failure 1237 if (verified) { 1238 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 1239 needUpdate = true; 1240 } 1241 break; 1242 1243 default: 1244 // Nothing to do 1245 } 1246 1247 if (needUpdate) { 1248 mSettings.updateIntentFilterVerificationStatusLPw( 1249 packageName, updatedStatus, userId); 1250 scheduleWritePackageRestrictionsLocked(userId); 1251 } 1252 } else { 1253 Slog.i(TAG, "autoVerify ignored when installing for all users"); 1254 } 1255 } 1256 } 1257 1258 @Override addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, ActivityIntentInfo filter, String packageName)1259 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 1260 ActivityIntentInfo filter, String packageName) { 1261 if (!hasValidDomains(filter)) { 1262 return false; 1263 } 1264 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 1265 if (ivs == null) { 1266 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 1267 packageName); 1268 } 1269 if (DEBUG_DOMAIN_VERIFICATION) { 1270 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 1271 } 1272 ivs.addFilter(filter); 1273 return true; 1274 } 1275 createDomainVerificationState(int verifierUid, int userId, int verificationId, String packageName)1276 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 1277 int userId, int verificationId, String packageName) { 1278 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 1279 verifierUid, userId, packageName); 1280 ivs.setPendingState(); 1281 synchronized (mPackages) { 1282 mIntentFilterVerificationStates.append(verificationId, ivs); 1283 mCurrentIntentFilterVerifications.add(verificationId); 1284 } 1285 return ivs; 1286 } 1287 } 1288 hasValidDomains(ActivityIntentInfo filter)1289 private static boolean hasValidDomains(ActivityIntentInfo filter) { 1290 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 1291 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 1292 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 1293 } 1294 1295 // Set of pending broadcasts for aggregating enable/disable of components. 1296 static class PendingPackageBroadcasts { 1297 // for each user id, a map of <package name -> components within that package> 1298 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 1299 PendingPackageBroadcasts()1300 public PendingPackageBroadcasts() { 1301 mUidMap = new SparseArray<>(2); 1302 } 1303 get(int userId, String packageName)1304 public ArrayList<String> get(int userId, String packageName) { 1305 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1306 return packages.get(packageName); 1307 } 1308 put(int userId, String packageName, ArrayList<String> components)1309 public void put(int userId, String packageName, ArrayList<String> components) { 1310 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 1311 packages.put(packageName, components); 1312 } 1313 remove(int userId, String packageName)1314 public void remove(int userId, String packageName) { 1315 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 1316 if (packages != null) { 1317 packages.remove(packageName); 1318 } 1319 } 1320 remove(int userId)1321 public void remove(int userId) { 1322 mUidMap.remove(userId); 1323 } 1324 userIdCount()1325 public int userIdCount() { 1326 return mUidMap.size(); 1327 } 1328 userIdAt(int n)1329 public int userIdAt(int n) { 1330 return mUidMap.keyAt(n); 1331 } 1332 packagesForUserId(int userId)1333 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1334 return mUidMap.get(userId); 1335 } 1336 size()1337 public int size() { 1338 // total number of pending broadcast entries across all userIds 1339 int num = 0; 1340 for (int i = 0; i< mUidMap.size(); i++) { 1341 num += mUidMap.valueAt(i).size(); 1342 } 1343 return num; 1344 } 1345 clear()1346 public void clear() { 1347 mUidMap.clear(); 1348 } 1349 getOrAllocate(int userId)1350 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1351 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1352 if (map == null) { 1353 map = new ArrayMap<>(); 1354 mUidMap.put(userId, map); 1355 } 1356 return map; 1357 } 1358 } 1359 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1360 1361 static final int SEND_PENDING_BROADCAST = 1; 1362 static final int INIT_COPY = 5; 1363 static final int POST_INSTALL = 9; 1364 static final int WRITE_SETTINGS = 13; 1365 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1366 static final int PACKAGE_VERIFIED = 15; 1367 static final int CHECK_PENDING_VERIFICATION = 16; 1368 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1369 static final int INTENT_FILTER_VERIFIED = 18; 1370 static final int WRITE_PACKAGE_LIST = 19; 1371 static final int INSTANT_APP_RESOLUTION_PHASE_TWO = 20; 1372 static final int ENABLE_ROLLBACK_STATUS = 21; 1373 static final int ENABLE_ROLLBACK_TIMEOUT = 22; 1374 static final int DEFERRED_NO_KILL_POST_DELETE = 23; 1375 static final int DEFERRED_NO_KILL_INSTALL_OBSERVER = 24; 1376 1377 static final int DEFERRED_NO_KILL_POST_DELETE_DELAY_MS = 3 * 1000; 1378 static final int DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS = 500; 1379 1380 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1381 1382 private static final long BROADCAST_DELAY_DURING_STARTUP = 10 * 1000L; // 10 seconds (in millis) 1383 private static final long BROADCAST_DELAY = 1 * 1000L; // 1 second (in millis) 1384 1385 // When the service constructor finished plus a delay (used for broadcast delay computation) 1386 private long mServiceStartWithDelay; 1387 1388 private static final long DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD = 1389 2 * 60 * 60 * 1000L; /* two hours */ 1390 1391 static UserManagerService sUserManager; 1392 1393 // Stores a list of users whose package restrictions file needs to be updated 1394 private ArraySet<Integer> mDirtyUsers = new ArraySet<>(); 1395 1396 // Recordkeeping of restore-after-install operations that are currently in flight 1397 // between the Package Manager and the Backup Manager 1398 static class PostInstallData { 1399 public final InstallArgs args; 1400 public final PackageInstalledInfo res; 1401 public final Runnable mPostInstallRunnable; 1402 PostInstallData(InstallArgs _a, PackageInstalledInfo _r, Runnable postInstallRunnable)1403 PostInstallData(InstallArgs _a, PackageInstalledInfo _r, Runnable postInstallRunnable) { 1404 args = _a; 1405 res = _r; 1406 mPostInstallRunnable = postInstallRunnable; 1407 } 1408 } 1409 1410 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<>(); 1411 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1412 1413 // XML tags for backup/restore of various bits of state 1414 private static final String TAG_PREFERRED_BACKUP = "pa"; 1415 private static final String TAG_DEFAULT_APPS = "da"; 1416 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1417 1418 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1419 private static final String TAG_ALL_GRANTS = "rt-grants"; 1420 private static final String TAG_GRANT = "grant"; 1421 private static final String ATTR_PACKAGE_NAME = "pkg"; 1422 1423 private static final String TAG_PERMISSION = "perm"; 1424 private static final String ATTR_PERMISSION_NAME = "name"; 1425 private static final String ATTR_IS_GRANTED = "g"; 1426 private static final String ATTR_USER_SET = "set"; 1427 private static final String ATTR_USER_FIXED = "fixed"; 1428 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1429 1430 // System/policy permission grants are not backed up 1431 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1432 FLAG_PERMISSION_POLICY_FIXED 1433 | FLAG_PERMISSION_SYSTEM_FIXED 1434 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1435 1436 // And we back up these user-adjusted states 1437 private static final int USER_RUNTIME_GRANT_MASK = 1438 FLAG_PERMISSION_USER_SET 1439 | FLAG_PERMISSION_USER_FIXED 1440 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1441 1442 final @Nullable String mRequiredVerifierPackage; 1443 final @NonNull String mRequiredInstallerPackage; 1444 final @NonNull String mRequiredUninstallerPackage; 1445 final @NonNull String mRequiredPermissionControllerPackage; 1446 final @Nullable String mSetupWizardPackage; 1447 final @Nullable String mStorageManagerPackage; 1448 final @Nullable String mSystemTextClassifierPackage; 1449 final @Nullable String mWellbeingPackage; 1450 final @Nullable String mDocumenterPackage; 1451 final @Nullable String mConfiguratorPackage; 1452 final @Nullable String mAppPredictionServicePackage; 1453 final @Nullable String mIncidentReportApproverPackage; 1454 final @Nullable String[] mTelephonyPackages; 1455 final @NonNull String mServicesSystemSharedLibraryPackageName; 1456 final @NonNull String mSharedSystemSharedLibraryPackageName; 1457 1458 private final PackageUsage mPackageUsage = new PackageUsage(); 1459 private final CompilerStats mCompilerStats = new CompilerStats(); 1460 1461 class PackageHandler extends Handler { 1462 PackageHandler(Looper looper)1463 PackageHandler(Looper looper) { 1464 super(looper); 1465 } 1466 handleMessage(Message msg)1467 public void handleMessage(Message msg) { 1468 try { 1469 doHandleMessage(msg); 1470 } finally { 1471 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1472 } 1473 } 1474 doHandleMessage(Message msg)1475 void doHandleMessage(Message msg) { 1476 switch (msg.what) { 1477 case INIT_COPY: { 1478 HandlerParams params = (HandlerParams) msg.obj; 1479 if (params != null) { 1480 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy: " + params); 1481 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1482 System.identityHashCode(params)); 1483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1484 params.startCopy(); 1485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1486 } 1487 break; 1488 } 1489 case SEND_PENDING_BROADCAST: { 1490 String packages[]; 1491 ArrayList<String> components[]; 1492 int size = 0; 1493 int uids[]; 1494 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1495 synchronized (mPackages) { 1496 size = mPendingBroadcasts.size(); 1497 if (size <= 0) { 1498 // Nothing to be done. Just return 1499 return; 1500 } 1501 packages = new String[size]; 1502 components = new ArrayList[size]; 1503 uids = new int[size]; 1504 int i = 0; // filling out the above arrays 1505 1506 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1507 int packageUserId = mPendingBroadcasts.userIdAt(n); 1508 Iterator<Map.Entry<String, ArrayList<String>>> it 1509 = mPendingBroadcasts.packagesForUserId(packageUserId) 1510 .entrySet().iterator(); 1511 while (it.hasNext() && i < size) { 1512 Map.Entry<String, ArrayList<String>> ent = it.next(); 1513 packages[i] = ent.getKey(); 1514 components[i] = ent.getValue(); 1515 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1516 uids[i] = (ps != null) 1517 ? UserHandle.getUid(packageUserId, ps.appId) 1518 : -1; 1519 i++; 1520 } 1521 } 1522 size = i; 1523 mPendingBroadcasts.clear(); 1524 } 1525 // Send broadcasts 1526 for (int i = 0; i < size; i++) { 1527 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1528 } 1529 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1530 break; 1531 } 1532 case POST_INSTALL: { 1533 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1534 1535 PostInstallData data = mRunningInstalls.get(msg.arg1); 1536 final boolean didRestore = (msg.arg2 != 0); 1537 mRunningInstalls.delete(msg.arg1); 1538 1539 if (data != null && data.mPostInstallRunnable != null) { 1540 data.mPostInstallRunnable.run(); 1541 } else if (data != null) { 1542 InstallArgs args = data.args; 1543 PackageInstalledInfo parentRes = data.res; 1544 1545 final boolean grantPermissions = (args.installFlags 1546 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1547 final boolean killApp = (args.installFlags 1548 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1549 final boolean virtualPreload = ((args.installFlags 1550 & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 1551 final String[] grantedPermissions = args.installGrantPermissions; 1552 final List<String> whitelistedRestrictedPermissions = ((args.installFlags 1553 & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) != 0 1554 && parentRes.pkg != null) 1555 ? parentRes.pkg.requestedPermissions 1556 : args.whitelistedRestrictedPermissions; 1557 1558 // Handle the parent package 1559 handlePackagePostInstall(parentRes, grantPermissions, 1560 killApp, virtualPreload, grantedPermissions, 1561 whitelistedRestrictedPermissions, didRestore, 1562 args.installerPackageName, args.observer); 1563 1564 // Handle the child packages 1565 final int childCount = (parentRes.addedChildPackages != null) 1566 ? parentRes.addedChildPackages.size() : 0; 1567 for (int i = 0; i < childCount; i++) { 1568 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1569 handlePackagePostInstall(childRes, grantPermissions, 1570 killApp, virtualPreload, grantedPermissions, 1571 whitelistedRestrictedPermissions, false /*didRestore*/, 1572 args.installerPackageName, args.observer); 1573 } 1574 1575 // Log tracing if needed 1576 if (args.traceMethod != null) { 1577 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1578 args.traceCookie); 1579 } 1580 } else if (DEBUG_INSTALL) { 1581 // No post-install when we run restore from installExistingPackageForUser 1582 Slog.i(TAG, "Nothing to do for post-install token " + msg.arg1); 1583 } 1584 1585 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1586 } break; 1587 case DEFERRED_NO_KILL_POST_DELETE: { 1588 synchronized (mInstallLock) { 1589 InstallArgs args = (InstallArgs) msg.obj; 1590 if (args != null) { 1591 args.doPostDeleteLI(true); 1592 } 1593 } 1594 } break; 1595 case DEFERRED_NO_KILL_INSTALL_OBSERVER: { 1596 String packageName = (String) msg.obj; 1597 if (packageName != null) { 1598 notifyInstallObserver(packageName); 1599 } 1600 } break; 1601 case WRITE_SETTINGS: { 1602 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1603 synchronized (mPackages) { 1604 removeMessages(WRITE_SETTINGS); 1605 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1606 mSettings.writeLPr(); 1607 mDirtyUsers.clear(); 1608 } 1609 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1610 } break; 1611 case WRITE_PACKAGE_RESTRICTIONS: { 1612 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1613 synchronized (mPackages) { 1614 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1615 for (int userId : mDirtyUsers) { 1616 mSettings.writePackageRestrictionsLPr(userId); 1617 } 1618 mDirtyUsers.clear(); 1619 } 1620 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1621 } break; 1622 case WRITE_PACKAGE_LIST: { 1623 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1624 synchronized (mPackages) { 1625 removeMessages(WRITE_PACKAGE_LIST); 1626 mSettings.writePackageListLPr(msg.arg1); 1627 } 1628 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1629 } break; 1630 case CHECK_PENDING_VERIFICATION: { 1631 final int verificationId = msg.arg1; 1632 final PackageVerificationState state = mPendingVerification.get(verificationId); 1633 1634 if ((state != null) && !state.timeoutExtended()) { 1635 final InstallParams params = state.getInstallParams(); 1636 final InstallArgs args = params.mArgs; 1637 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1638 1639 Slog.i(TAG, "Verification timed out for " + originUri); 1640 mPendingVerification.remove(verificationId); 1641 1642 final UserHandle user = args.getUser(); 1643 if (getDefaultVerificationResponse(user) 1644 == PackageManager.VERIFICATION_ALLOW) { 1645 Slog.i(TAG, "Continuing with installation of " + originUri); 1646 state.setVerifierResponse(Binder.getCallingUid(), 1647 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1648 broadcastPackageVerified(verificationId, originUri, 1649 PackageManager.VERIFICATION_ALLOW, user); 1650 } else { 1651 broadcastPackageVerified(verificationId, originUri, 1652 PackageManager.VERIFICATION_REJECT, user); 1653 params.setReturnCode( 1654 PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE); 1655 } 1656 1657 Trace.asyncTraceEnd( 1658 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1659 params.handleVerificationFinished(); 1660 } 1661 break; 1662 } 1663 case PACKAGE_VERIFIED: { 1664 final int verificationId = msg.arg1; 1665 1666 final PackageVerificationState state = mPendingVerification.get(verificationId); 1667 if (state == null) { 1668 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1669 break; 1670 } 1671 1672 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1673 1674 state.setVerifierResponse(response.callerUid, response.code); 1675 1676 if (state.isVerificationComplete()) { 1677 mPendingVerification.remove(verificationId); 1678 1679 final InstallParams params = state.getInstallParams(); 1680 final InstallArgs args = params.mArgs; 1681 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1682 1683 if (state.isInstallAllowed()) { 1684 broadcastPackageVerified(verificationId, originUri, 1685 response.code, args.getUser()); 1686 } else { 1687 params.setReturnCode( 1688 PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE); 1689 } 1690 1691 Trace.asyncTraceEnd( 1692 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1693 1694 params.handleVerificationFinished(); 1695 } 1696 1697 break; 1698 } 1699 case START_INTENT_FILTER_VERIFICATIONS: { 1700 IFVerificationParams params = (IFVerificationParams) msg.obj; 1701 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1702 params.replacing, params.pkg); 1703 break; 1704 } 1705 case INTENT_FILTER_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1709 verificationId); 1710 if (state == null) { 1711 Slog.w(TAG, "Invalid IntentFilter verification token " 1712 + verificationId + " received"); 1713 break; 1714 } 1715 1716 final int userId = state.getUserId(); 1717 1718 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1719 "Processing IntentFilter verification with token:" 1720 + verificationId + " and userId:" + userId); 1721 1722 final IntentFilterVerificationResponse response = 1723 (IntentFilterVerificationResponse) msg.obj; 1724 1725 state.setVerifierResponse(response.callerUid, response.code); 1726 1727 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1728 "IntentFilter verification with token:" + verificationId 1729 + " and userId:" + userId 1730 + " is settings verifier response with response code:" 1731 + response.code); 1732 1733 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1734 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1735 + response.getFailedDomainsString()); 1736 } 1737 1738 if (state.isVerificationComplete()) { 1739 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1740 } else { 1741 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1742 "IntentFilter verification with token:" + verificationId 1743 + " was not said to be complete"); 1744 } 1745 1746 break; 1747 } 1748 case INSTANT_APP_RESOLUTION_PHASE_TWO: { 1749 InstantAppResolver.doInstantAppResolutionPhaseTwo(mContext, 1750 mInstantAppResolverConnection, 1751 (InstantAppRequest) msg.obj, 1752 mInstantAppInstallerActivity, 1753 mHandler); 1754 break; 1755 } 1756 case ENABLE_ROLLBACK_STATUS: { 1757 final int enableRollbackToken = msg.arg1; 1758 final int enableRollbackCode = msg.arg2; 1759 InstallParams params = mPendingEnableRollback.get(enableRollbackToken); 1760 if (params == null) { 1761 Slog.w(TAG, "Invalid rollback enabled token " 1762 + enableRollbackToken + " received"); 1763 break; 1764 } 1765 1766 mPendingEnableRollback.remove(enableRollbackToken); 1767 1768 if (enableRollbackCode != PackageManagerInternal.ENABLE_ROLLBACK_SUCCEEDED) { 1769 final InstallArgs args = params.mArgs; 1770 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1771 Slog.w(TAG, "Failed to enable rollback for " + originUri); 1772 Slog.w(TAG, "Continuing with installation of " + originUri); 1773 } 1774 1775 Trace.asyncTraceEnd( 1776 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 1777 1778 params.handleRollbackEnabled(); 1779 break; 1780 } 1781 case ENABLE_ROLLBACK_TIMEOUT: { 1782 final int enableRollbackToken = msg.arg1; 1783 final InstallParams params = mPendingEnableRollback.get(enableRollbackToken); 1784 if (params != null) { 1785 final InstallArgs args = params.mArgs; 1786 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1787 1788 Slog.w(TAG, "Enable rollback timed out for " + originUri); 1789 mPendingEnableRollback.remove(enableRollbackToken); 1790 1791 Slog.w(TAG, "Continuing with installation of " + originUri); 1792 Trace.asyncTraceEnd( 1793 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 1794 params.handleRollbackEnabled(); 1795 Intent rollbackTimeoutIntent = new Intent( 1796 Intent.ACTION_CANCEL_ENABLE_ROLLBACK); 1797 rollbackTimeoutIntent.putExtra( 1798 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN, 1799 enableRollbackToken); 1800 rollbackTimeoutIntent.addFlags( 1801 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 1802 mContext.sendBroadcastAsUser(rollbackTimeoutIntent, UserHandle.SYSTEM, 1803 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT); 1804 } 1805 break; 1806 } 1807 } 1808 } 1809 } 1810 1811 private PermissionCallback mPermissionCallback = new PermissionCallback() { 1812 @Override 1813 public void onGidsChanged(int appId, int userId) { 1814 mHandler.post(() -> killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED)); 1815 } 1816 @Override 1817 public void onPermissionGranted(int uid, int userId) { 1818 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1819 1820 // Not critical; if this is lost, the application has to request again. 1821 synchronized (mPackages) { 1822 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 1823 } 1824 } 1825 @Override 1826 public void onInstallPermissionGranted() { 1827 synchronized (mPackages) { 1828 scheduleWriteSettingsLocked(); 1829 } 1830 } 1831 @Override 1832 public void onPermissionRevoked(int uid, int userId) { 1833 mOnPermissionChangeListeners.onPermissionsChanged(uid); 1834 1835 synchronized (mPackages) { 1836 // Critical; after this call the application should never have the permission 1837 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 1838 } 1839 1840 final int appId = UserHandle.getAppId(uid); 1841 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 1842 } 1843 @Override 1844 public void onInstallPermissionRevoked() { 1845 synchronized (mPackages) { 1846 scheduleWriteSettingsLocked(); 1847 } 1848 } 1849 @Override 1850 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 1851 synchronized (mPackages) { 1852 for (int userId : updatedUserIds) { 1853 mSettings.writeRuntimePermissionsForUserLPr(userId, sync); 1854 } 1855 } 1856 } 1857 @Override 1858 public void onInstallPermissionUpdated() { 1859 synchronized (mPackages) { 1860 scheduleWriteSettingsLocked(); 1861 } 1862 } 1863 @Override 1864 public void onPermissionRemoved() { 1865 synchronized (mPackages) { 1866 mSettings.writeLPr(); 1867 } 1868 } 1869 }; 1870 handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, boolean killApp, boolean virtualPreload, String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, boolean launchedForRestore, String installerPackage, IPackageInstallObserver2 installObserver)1871 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1872 boolean killApp, boolean virtualPreload, 1873 String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, 1874 boolean launchedForRestore, String installerPackage, 1875 IPackageInstallObserver2 installObserver) { 1876 final boolean succeeded = res.returnCode == PackageManager.INSTALL_SUCCEEDED; 1877 final boolean update = res.removedInfo != null && res.removedInfo.removedPackage != null; 1878 1879 if (succeeded) { 1880 // Send the removed broadcasts 1881 if (res.removedInfo != null) { 1882 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1883 } 1884 1885 // Whitelist any restricted permissions first as some may be runtime 1886 // that the installer requested to be granted at install time. 1887 if (whitelistedRestrictedPermissions != null 1888 && !whitelistedRestrictedPermissions.isEmpty()) { 1889 mPermissionManager.setWhitelistedRestrictedPermissions( 1890 res.pkg, res.newUsers, whitelistedRestrictedPermissions, 1891 Process.myUid(), PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER, 1892 mPermissionCallback); 1893 } 1894 1895 // Now that we successfully installed the package, grant runtime 1896 // permissions if requested before broadcasting the install. Also 1897 // for legacy apps in permission review mode we clear the permission 1898 // review flag which is used to emulate runtime permissions for 1899 // legacy apps. 1900 if (grantPermissions) { 1901 final int callingUid = Binder.getCallingUid(); 1902 mPermissionManager.grantRequestedRuntimePermissions( 1903 res.pkg, res.newUsers, grantedPermissions, callingUid, 1904 mPermissionCallback); 1905 } 1906 1907 final String installerPackageName = 1908 res.installerPackageName != null 1909 ? res.installerPackageName 1910 : res.removedInfo != null 1911 ? res.removedInfo.installerPackageName 1912 : null; 1913 1914 // If this is the first time we have child packages for a disabled privileged 1915 // app that had no children, we grant requested runtime permissions to the new 1916 // children if the parent on the system image had them already granted. 1917 if (res.pkg.parentPackage != null) { 1918 final int callingUid = Binder.getCallingUid(); 1919 mPermissionManager.grantRuntimePermissionsGrantedToDisabledPackage( 1920 res.pkg, callingUid, mPermissionCallback); 1921 } 1922 1923 synchronized (mPackages) { 1924 mInstantAppRegistry.onPackageInstalledLPw(res.pkg, res.newUsers); 1925 } 1926 1927 final String packageName = res.pkg.applicationInfo.packageName; 1928 1929 // Determine the set of users who are adding this package for 1930 // the first time vs. those who are seeing an update. 1931 int[] firstUserIds = EMPTY_INT_ARRAY; 1932 int[] firstInstantUserIds = EMPTY_INT_ARRAY; 1933 int[] updateUserIds = EMPTY_INT_ARRAY; 1934 int[] instantUserIds = EMPTY_INT_ARRAY; 1935 final boolean allNewUsers = res.origUsers == null || res.origUsers.length == 0; 1936 final PackageSetting ps = (PackageSetting) res.pkg.mExtras; 1937 for (int newUser : res.newUsers) { 1938 final boolean isInstantApp = ps.getInstantApp(newUser); 1939 if (allNewUsers) { 1940 if (isInstantApp) { 1941 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1942 } else { 1943 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1944 } 1945 continue; 1946 } 1947 boolean isNew = true; 1948 for (int origUser : res.origUsers) { 1949 if (origUser == newUser) { 1950 isNew = false; 1951 break; 1952 } 1953 } 1954 if (isNew) { 1955 if (isInstantApp) { 1956 firstInstantUserIds = ArrayUtils.appendInt(firstInstantUserIds, newUser); 1957 } else { 1958 firstUserIds = ArrayUtils.appendInt(firstUserIds, newUser); 1959 } 1960 } else { 1961 if (isInstantApp) { 1962 instantUserIds = ArrayUtils.appendInt(instantUserIds, newUser); 1963 } else { 1964 updateUserIds = ArrayUtils.appendInt(updateUserIds, newUser); 1965 } 1966 } 1967 } 1968 1969 // Send installed broadcasts if the package is not a static shared lib. 1970 if (res.pkg.staticSharedLibName == null) { 1971 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1972 1973 // Send added for users that see the package for the first time 1974 // sendPackageAddedForNewUsers also deals with system apps 1975 int appId = UserHandle.getAppId(res.uid); 1976 boolean isSystem = res.pkg.applicationInfo.isSystemApp(); 1977 sendPackageAddedForNewUsers(packageName, isSystem || virtualPreload, 1978 virtualPreload /*startReceiver*/, appId, firstUserIds, firstInstantUserIds); 1979 1980 // Send added for users that don't see the package for the first time 1981 Bundle extras = new Bundle(1); 1982 extras.putInt(Intent.EXTRA_UID, res.uid); 1983 if (update) { 1984 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1985 } 1986 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1987 extras, 0 /*flags*/, 1988 null /*targetPackage*/, null /*finishedReceiver*/, 1989 updateUserIds, instantUserIds); 1990 if (installerPackageName != null) { 1991 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1992 extras, 0 /*flags*/, 1993 installerPackageName, null /*finishedReceiver*/, 1994 updateUserIds, instantUserIds); 1995 } 1996 // if the required verifier is defined, but, is not the installer of record 1997 // for the package, it gets notified 1998 final boolean notifyVerifier = mRequiredVerifierPackage != null 1999 && !mRequiredVerifierPackage.equals(installerPackageName); 2000 if (notifyVerifier) { 2001 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2002 extras, 0 /*flags*/, 2003 mRequiredVerifierPackage, null /*finishedReceiver*/, 2004 updateUserIds, instantUserIds); 2005 } 2006 // If package installer is defined, notify package installer about new 2007 // app installed 2008 if (mRequiredInstallerPackage != null) { 2009 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 2010 extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND /*flags*/, 2011 mRequiredInstallerPackage, null /*finishedReceiver*/, 2012 firstUserIds, instantUserIds); 2013 } 2014 2015 // Send replaced for users that don't see the package for the first time 2016 if (update) { 2017 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 2018 packageName, extras, 0 /*flags*/, 2019 null /*targetPackage*/, null /*finishedReceiver*/, 2020 updateUserIds, instantUserIds); 2021 if (installerPackageName != null) { 2022 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2023 extras, 0 /*flags*/, 2024 installerPackageName, null /*finishedReceiver*/, 2025 updateUserIds, instantUserIds); 2026 } 2027 if (notifyVerifier) { 2028 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, packageName, 2029 extras, 0 /*flags*/, 2030 mRequiredVerifierPackage, null /*finishedReceiver*/, 2031 updateUserIds, instantUserIds); 2032 } 2033 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 2034 null /*package*/, null /*extras*/, 0 /*flags*/, 2035 packageName /*targetPackage*/, 2036 null /*finishedReceiver*/, updateUserIds, instantUserIds); 2037 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 2038 // First-install and we did a restore, so we're responsible for the 2039 // first-launch broadcast. 2040 if (DEBUG_BACKUP) { 2041 Slog.i(TAG, "Post-restore of " + packageName 2042 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUserIds)); 2043 } 2044 sendFirstLaunchBroadcast(packageName, installerPackage, 2045 firstUserIds, firstInstantUserIds); 2046 } 2047 2048 // Send broadcast package appeared if external for all users 2049 if (isExternal(res.pkg)) { 2050 if (!update) { 2051 final StorageManager storage = 2052 mContext.getSystemService(StorageManager.class); 2053 VolumeInfo volume = 2054 storage.findVolumeByUuid( 2055 res.pkg.applicationInfo.storageUuid.toString()); 2056 int packageExternalStorageType = 2057 getPackageExternalStorageType(volume, isExternal(res.pkg)); 2058 // If the package was installed externally, log it. 2059 if (packageExternalStorageType != StorageEnums.UNKNOWN) { 2060 StatsLog.write(StatsLog.APP_INSTALL_ON_EXTERNAL_STORAGE_REPORTED, 2061 packageExternalStorageType, res.pkg.packageName); 2062 } 2063 } 2064 if (DEBUG_INSTALL) { 2065 Slog.i(TAG, "upgrading pkg " + res.pkg + " is external"); 2066 } 2067 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 2068 ArrayList<String> pkgList = new ArrayList<>(1); 2069 pkgList.add(packageName); 2070 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 2071 } 2072 } else if (!ArrayUtils.isEmpty(res.libraryConsumers)) { // if static shared lib 2073 for (int i = 0; i < res.libraryConsumers.size(); i++) { 2074 PackageParser.Package pkg = res.libraryConsumers.get(i); 2075 // send broadcast that all consumers of the static shared library have changed 2076 sendPackageChangedBroadcast(pkg.packageName, false /*killFlag*/, 2077 new ArrayList<>(Collections.singletonList(pkg.packageName)), 2078 pkg.applicationInfo.uid); 2079 } 2080 } 2081 2082 // Work that needs to happen on first install within each user 2083 if (firstUserIds != null && firstUserIds.length > 0) { 2084 for (int userId : firstUserIds) { 2085 // If this app is a browser and it's newly-installed for some 2086 // users, clear any default-browser state in those users. The 2087 // app's nature doesn't depend on the user, so we can just check 2088 // its browser nature in any user and generalize. 2089 if (packageIsBrowser(packageName, userId)) { 2090 // If this browser is restored from user's backup, do not clear 2091 // default-browser state for this user 2092 synchronized (mPackages) { 2093 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 2094 if (pkgSetting.getInstallReason(userId) 2095 != PackageManager.INSTALL_REASON_DEVICE_RESTORE) { 2096 setDefaultBrowserAsyncLPw(null, userId); 2097 } 2098 } 2099 } 2100 2101 // We may also need to apply pending (restored) runtime permission grants 2102 // within these users. 2103 mPermissionManager.restoreDelayedRuntimePermissions(packageName, 2104 UserHandle.of(userId)); 2105 2106 // Persistent preferred activity might have came into effect due to this 2107 // install. 2108 updateDefaultHomeNotLocked(userId); 2109 } 2110 } 2111 2112 if (allNewUsers && !update) { 2113 notifyPackageAdded(packageName, res.uid); 2114 } else { 2115 notifyPackageChanged(packageName, res.uid); 2116 } 2117 2118 // Log current value of "unknown sources" setting 2119 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 2120 getUnknownSourcesSettings()); 2121 2122 // Remove the replaced package's older resources safely now 2123 InstallArgs args = res.removedInfo != null ? res.removedInfo.args : null; 2124 if (args != null) { 2125 if (!killApp) { 2126 // If we didn't kill the app, defer the deletion of code/resource files, since 2127 // they may still be in use by the running application. This mitigates problems 2128 // in cases where resources or code is loaded by a new Activity before 2129 // ApplicationInfo changes have propagated to all application threads. 2130 scheduleDeferredNoKillPostDelete(args); 2131 } else { 2132 synchronized (mInstallLock) { 2133 args.doPostDeleteLI(true); 2134 } 2135 } 2136 } else { 2137 // Force a gc to clear up things. Ask for a background one, it's fine to go on 2138 // and not block here. 2139 VMRuntime.getRuntime().requestConcurrentGC(); 2140 } 2141 2142 // Notify DexManager that the package was installed for new users. 2143 // The updated users should already be indexed and the package code paths 2144 // should not change. 2145 // Don't notify the manager for ephemeral apps as they are not expected to 2146 // survive long enough to benefit of background optimizations. 2147 for (int userId : firstUserIds) { 2148 PackageInfo info = getPackageInfo(packageName, /*flags*/ 0, userId); 2149 // There's a race currently where some install events may interleave with an 2150 // uninstall. This can lead to package info being null (b/36642664). 2151 if (info != null) { 2152 mDexManager.notifyPackageInstalled(info, userId); 2153 } 2154 } 2155 } 2156 2157 final boolean deferInstallObserver = succeeded && update && !killApp; 2158 if (deferInstallObserver) { 2159 scheduleDeferredNoKillInstallObserver(res, installObserver); 2160 } else { 2161 notifyInstallObserver(res, installObserver); 2162 } 2163 } 2164 2165 @Override notifyPackagesReplacedReceived(String[] packages)2166 public void notifyPackagesReplacedReceived(String[] packages) { 2167 final int callingUid = Binder.getCallingUid(); 2168 final int callingUserId = UserHandle.getUserId(callingUid); 2169 2170 for (String packageName : packages) { 2171 PackageSetting setting = mSettings.mPackages.get(packageName); 2172 if (setting != null && filterAppAccessLPr(setting, callingUid, callingUserId)) { 2173 notifyInstallObserver(packageName); 2174 } 2175 } 2176 } 2177 2178 @Override getSplitPermissions()2179 public List<SplitPermissionInfoParcelable> getSplitPermissions() { 2180 return PermissionManager.splitPermissionInfoListToParcelableList( 2181 SystemConfig.getInstance().getSplitPermissions()); 2182 } 2183 notifyInstallObserver(String packageName)2184 private void notifyInstallObserver(String packageName) { 2185 Pair<PackageInstalledInfo, IPackageInstallObserver2> pair = 2186 mNoKillInstallObservers.remove(packageName); 2187 2188 if (pair != null) { 2189 notifyInstallObserver(pair.first, pair.second); 2190 } 2191 } 2192 notifyInstallObserver(PackageInstalledInfo info, IPackageInstallObserver2 installObserver)2193 private void notifyInstallObserver(PackageInstalledInfo info, 2194 IPackageInstallObserver2 installObserver) { 2195 if (installObserver != null) { 2196 try { 2197 Bundle extras = extrasForInstallResult(info); 2198 installObserver.onPackageInstalled(info.name, info.returnCode, 2199 info.returnMsg, extras); 2200 } catch (RemoteException e) { 2201 Slog.i(TAG, "Observer no longer exists."); 2202 } 2203 } 2204 } 2205 scheduleDeferredNoKillPostDelete(InstallArgs args)2206 private void scheduleDeferredNoKillPostDelete(InstallArgs args) { 2207 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_POST_DELETE, args); 2208 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_POST_DELETE_DELAY_MS); 2209 } 2210 scheduleDeferredNoKillInstallObserver(PackageInstalledInfo info, IPackageInstallObserver2 observer)2211 private void scheduleDeferredNoKillInstallObserver(PackageInstalledInfo info, 2212 IPackageInstallObserver2 observer) { 2213 String packageName = info.pkg.packageName; 2214 mNoKillInstallObservers.put(packageName, Pair.create(info, observer)); 2215 Message message = mHandler.obtainMessage(DEFERRED_NO_KILL_INSTALL_OBSERVER, packageName); 2216 mHandler.sendMessageDelayed(message, DEFERRED_NO_KILL_INSTALL_OBSERVER_DELAY_MS); 2217 } 2218 2219 /** 2220 * Gets the type of the external storage a package is installed on. 2221 * @param packageVolume The storage volume of the package. 2222 * @param packageIsExternal true if the package is currently installed on 2223 * external/removable/unprotected storage. 2224 * @return {@link StorageEnum#TYPE_UNKNOWN} if the package is not stored externally or the 2225 * corresponding {@link StorageEnum} storage type value if it is. 2226 * corresponding {@link StorageEnum} storage type value if it is. 2227 */ getPackageExternalStorageType(VolumeInfo packageVolume, boolean packageIsExternal)2228 private static int getPackageExternalStorageType(VolumeInfo packageVolume, 2229 boolean packageIsExternal) { 2230 if (packageVolume != null) { 2231 DiskInfo disk = packageVolume.getDisk(); 2232 if (disk != null) { 2233 if (disk.isSd()) { 2234 return StorageEnums.SD_CARD; 2235 } 2236 if (disk.isUsb()) { 2237 return StorageEnums.USB; 2238 } 2239 if (packageIsExternal) { 2240 return StorageEnums.OTHER; 2241 } 2242 } 2243 } 2244 return StorageEnums.UNKNOWN; 2245 } 2246 2247 private StorageEventListener mStorageListener = new StorageEventListener() { 2248 @Override 2249 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2250 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2251 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2252 final String volumeUuid = vol.getFsUuid(); 2253 2254 // Clean up any users or apps that were removed or recreated 2255 // while this volume was missing 2256 sUserManager.reconcileUsers(volumeUuid); 2257 reconcileApps(volumeUuid); 2258 2259 // Clean up any install sessions that expired or were 2260 // cancelled while this volume was missing 2261 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2262 2263 loadPrivatePackages(vol); 2264 2265 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2266 unloadPrivatePackages(vol); 2267 } 2268 } 2269 } 2270 2271 @Override 2272 public void onVolumeForgotten(String fsUuid) { 2273 if (TextUtils.isEmpty(fsUuid)) { 2274 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2275 return; 2276 } 2277 2278 // Remove any apps installed on the forgotten volume 2279 synchronized (mPackages) { 2280 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2281 for (PackageSetting ps : packages) { 2282 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2283 deletePackageVersioned(new VersionedPackage(ps.name, 2284 PackageManager.VERSION_CODE_HIGHEST), 2285 new LegacyPackageDeleteObserver(null).getBinder(), 2286 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2287 // Try very hard to release any references to this package 2288 // so we don't risk the system server being killed due to 2289 // open FDs 2290 AttributeCache.instance().removePackage(ps.name); 2291 } 2292 2293 mSettings.onVolumeForgotten(fsUuid); 2294 mSettings.writeLPr(); 2295 } 2296 } 2297 }; 2298 extrasForInstallResult(PackageInstalledInfo res)2299 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2300 Bundle extras = null; 2301 switch (res.returnCode) { 2302 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2303 extras = new Bundle(); 2304 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2305 res.origPermission); 2306 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2307 res.origPackage); 2308 break; 2309 } 2310 case PackageManager.INSTALL_SUCCEEDED: { 2311 extras = new Bundle(); 2312 extras.putBoolean(Intent.EXTRA_REPLACING, 2313 res.removedInfo != null && res.removedInfo.removedPackage != null); 2314 break; 2315 } 2316 } 2317 return extras; 2318 } 2319 scheduleWriteSettingsLocked()2320 void scheduleWriteSettingsLocked() { 2321 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2322 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2323 } 2324 } 2325 scheduleWritePackageListLocked(int userId)2326 void scheduleWritePackageListLocked(int userId) { 2327 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2328 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2329 msg.arg1 = userId; 2330 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2331 } 2332 } 2333 scheduleWritePackageRestrictionsLocked(UserHandle user)2334 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2335 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2336 scheduleWritePackageRestrictionsLocked(userId); 2337 } 2338 scheduleWritePackageRestrictionsLocked(int userId)2339 void scheduleWritePackageRestrictionsLocked(int userId) { 2340 final int[] userIds = (userId == UserHandle.USER_ALL) 2341 ? sUserManager.getUserIds() : new int[]{userId}; 2342 for (int nextUserId : userIds) { 2343 if (!sUserManager.exists(nextUserId)) return; 2344 mDirtyUsers.add(nextUserId); 2345 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2346 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2347 } 2348 } 2349 } 2350 main(Context context, Installer installer, boolean factoryTest, boolean onlyCore)2351 public static PackageManagerService main(Context context, Installer installer, 2352 boolean factoryTest, boolean onlyCore) { 2353 // Self-check for initial settings. 2354 PackageManagerServiceCompilerMapping.checkProperties(); 2355 2356 PackageManagerService m = new PackageManagerService(context, installer, 2357 factoryTest, onlyCore); 2358 m.enableSystemUserPackages(); 2359 ServiceManager.addService("package", m); 2360 final PackageManagerNative pmn = m.new PackageManagerNative(); 2361 ServiceManager.addService("package_native", pmn); 2362 return m; 2363 } 2364 isSystemUserPackagesBlacklistSupported()2365 private boolean isSystemUserPackagesBlacklistSupported() { 2366 return Resources.getSystem().getBoolean( 2367 R.bool.config_systemUserPackagesBlacklistSupported); 2368 } 2369 enableSystemUserPackages()2370 private void enableSystemUserPackages() { 2371 if (!isSystemUserPackagesBlacklistSupported()) { 2372 Log.i(TAG, "Skipping system user blacklist since " 2373 + "config_systemUserPackagesBlacklistSupported is false"); 2374 return; 2375 } 2376 2377 boolean isHeadlessSystemUserMode = UserManager.isHeadlessSystemUserMode(); 2378 if (!isHeadlessSystemUserMode && !UserManager.isSplitSystemUser()) { 2379 Log.i(TAG, "Skipping system user blacklist on 'regular' device type"); 2380 return; 2381 } 2382 2383 Log.i(TAG, "blacklisting packages for system user"); 2384 2385 Set<String> enableApps = new ArraySet<>(); 2386 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2387 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2388 UserHandle.SYSTEM); 2389 2390 if (isHeadlessSystemUserMode) { 2391 enableApps.addAll(allAps); 2392 } else { 2393 // For split system user, select apps based on the following conditions: 2394 // -- system app which has no launcher icons 2395 // -- system app which has INTERACT_ACROSS_USERS permission 2396 // -- system IME app 2397 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2398 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2399 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2400 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2401 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2402 2403 // Apply whitelist for split system user 2404 ArraySet<String> whitelistedSystemUserApps = SystemConfig.getInstance() 2405 .getSystemUserWhitelistedApps(); 2406 enableApps.addAll(whitelistedSystemUserApps); 2407 Log.i(TAG, "Whitelisted packages: " + whitelistedSystemUserApps); 2408 } 2409 // Apply blacklist for split system user/headless system user 2410 ArraySet<String> blacklistedSystemUserApps = SystemConfig.getInstance() 2411 .getSystemUserBlacklistedApps(); 2412 enableApps.removeAll(blacklistedSystemUserApps); 2413 Log.i(TAG, "Blacklisted packages: " + blacklistedSystemUserApps); 2414 2415 final int allAppsSize = allAps.size(); 2416 synchronized (mPackages) { 2417 for (int i = 0; i < allAppsSize; i++) { 2418 String pName = allAps.get(i); 2419 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2420 // Should not happen, but we shouldn't be failing if it does 2421 if (pkgSetting == null) { 2422 continue; 2423 } 2424 boolean install = enableApps.contains(pName); 2425 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2426 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2427 + " for system user"); 2428 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2429 } 2430 } 2431 scheduleWritePackageRestrictionsLocked(UserHandle.USER_SYSTEM); 2432 } 2433 } 2434 getDefaultDisplayMetrics(Context context, DisplayMetrics metrics)2435 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2436 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2437 Context.DISPLAY_SERVICE); 2438 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2439 } 2440 2441 /** 2442 * Requests that files preopted on a secondary system partition be copied to the data partition 2443 * if possible. Note that the actual copying of the files is accomplished by init for security 2444 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2445 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2446 */ requestCopyPreoptedFiles()2447 private static void requestCopyPreoptedFiles() { 2448 final int WAIT_TIME_MS = 100; 2449 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2450 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2451 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2452 // We will wait for up to 100 seconds. 2453 final long timeStart = SystemClock.uptimeMillis(); 2454 final long timeEnd = timeStart + 100 * 1000; 2455 long timeNow = timeStart; 2456 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2457 try { 2458 Thread.sleep(WAIT_TIME_MS); 2459 } catch (InterruptedException e) { 2460 // Do nothing 2461 } 2462 timeNow = SystemClock.uptimeMillis(); 2463 if (timeNow > timeEnd) { 2464 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2465 Slog.wtf(TAG, "cppreopt did not finish!"); 2466 break; 2467 } 2468 } 2469 2470 Slog.i(TAG, "cppreopts took " + (timeNow - timeStart) + " ms"); 2471 } 2472 } 2473 2474 @VisibleForTesting(visibility = Visibility.PRIVATE) 2475 static class SystemPartition { 2476 public final File folder; 2477 public final int scanFlag; 2478 public final File appFolder; 2479 @Nullable 2480 public final File privAppFolder; 2481 @Nullable 2482 public final File overlayFolder; 2483 2484 shouldScanPrivApps(@canFlags int scanFlags)2485 private static boolean shouldScanPrivApps(@ScanFlags int scanFlags) { 2486 if ((scanFlags & SCAN_AS_OEM) != 0) { 2487 return false; 2488 } 2489 if (scanFlags == 0) { // /system partition 2490 return true; 2491 } 2492 if ((scanFlags 2493 & (SCAN_AS_VENDOR | SCAN_AS_ODM | SCAN_AS_PRODUCT | SCAN_AS_SYSTEM_EXT)) != 0) { 2494 return true; 2495 } 2496 return false; 2497 } 2498 SystemPartition(File folder, int scanFlag, boolean hasOverlays)2499 private SystemPartition(File folder, int scanFlag, boolean hasOverlays) { 2500 this.folder = folder; 2501 this.scanFlag = scanFlag; 2502 this.appFolder = toCanonical(new File(folder, "app")); 2503 this.privAppFolder = shouldScanPrivApps(scanFlag) 2504 ? toCanonical(new File(folder, "priv-app")) 2505 : null; 2506 this.overlayFolder = hasOverlays ? toCanonical(new File(folder, "overlay")) : null; 2507 } 2508 containsPrivApp(File scanFile)2509 public boolean containsPrivApp(File scanFile) { 2510 return FileUtils.contains(privAppFolder, scanFile); 2511 } 2512 containsApp(File scanFile)2513 public boolean containsApp(File scanFile) { 2514 return FileUtils.contains(appFolder, scanFile); 2515 } 2516 containsPath(String path)2517 public boolean containsPath(String path) { 2518 return path.startsWith(folder.getPath() + "/"); 2519 } 2520 containsPrivPath(String path)2521 public boolean containsPrivPath(String path) { 2522 return privAppFolder != null && path.startsWith(privAppFolder.getPath() + "/"); 2523 } 2524 toCanonical(File dir)2525 private static File toCanonical(File dir) { 2526 try { 2527 return dir.getCanonicalFile(); 2528 } catch (IOException e) { 2529 // failed to look up canonical path, continue with original one 2530 return dir; 2531 } 2532 } 2533 } 2534 PackageManagerService(Context context, Installer installer, boolean factoryTest, boolean onlyCore)2535 public PackageManagerService(Context context, Installer installer, 2536 boolean factoryTest, boolean onlyCore) { 2537 LockGuard.installLock(mPackages, LockGuard.INDEX_PACKAGES); 2538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "create package manager"); 2539 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2540 SystemClock.uptimeMillis()); 2541 2542 if (mSdkVersion <= 0) { 2543 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2544 } 2545 2546 mContext = context; 2547 2548 mFactoryTest = factoryTest; 2549 mOnlyCore = onlyCore; 2550 mMetrics = new DisplayMetrics(); 2551 mInstaller = installer; 2552 2553 // Create sub-components that provide services / data. Order here is important. 2554 synchronized (mInstallLock) { 2555 synchronized (mPackages) { 2556 // Expose private service for system components to use. 2557 LocalServices.addService( 2558 PackageManagerInternal.class, new PackageManagerInternalImpl()); 2559 sUserManager = new UserManagerService(context, this, 2560 new UserDataPreparer(mInstaller, mInstallLock, mContext, mOnlyCore), mPackages); 2561 mComponentResolver = new ComponentResolver(sUserManager, 2562 LocalServices.getService(PackageManagerInternal.class), 2563 mPackages); 2564 mPermissionManager = PermissionManagerService.create(context, 2565 mPackages /*externalLock*/); 2566 mDefaultPermissionPolicy = mPermissionManager.getDefaultPermissionGrantPolicy(); 2567 mSettings = new Settings(Environment.getDataDirectory(), 2568 mPermissionManager.getPermissionSettings(), mPackages); 2569 } 2570 } 2571 2572 // TODO(b/137961986): We should pass this via constructor, but would first need to create 2573 // a packages lock that could also be passed in. 2574 mInjector = new Injector(getUserManagerInternal(), new PackageAbiHelperImpl()); 2575 2576 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2577 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2578 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2579 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2580 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2581 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2582 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2583 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2584 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2585 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2586 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2587 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2588 mSettings.addSharedUserLPw("android.uid.se", SE_UID, 2589 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2590 mSettings.addSharedUserLPw("android.uid.networkstack", NETWORKSTACK_UID, 2591 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2592 2593 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2594 if (separateProcesses != null && separateProcesses.length() > 0) { 2595 if ("*".equals(separateProcesses)) { 2596 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2597 mSeparateProcesses = null; 2598 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2599 } else { 2600 mDefParseFlags = 0; 2601 mSeparateProcesses = separateProcesses.split(","); 2602 Slog.w(TAG, "Running with debug.separate_processes: " 2603 + separateProcesses); 2604 } 2605 } else { 2606 mDefParseFlags = 0; 2607 mSeparateProcesses = null; 2608 } 2609 2610 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2611 "*dexopt*"); 2612 mDexManager = new DexManager(mContext, this, mPackageDexOptimizer, installer, mInstallLock); 2613 mArtManagerService = new ArtManagerService(mContext, this, installer, mInstallLock); 2614 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2615 2616 mViewCompiler = new ViewCompiler(mInstallLock, mInstaller); 2617 2618 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2619 FgThread.get().getLooper()); 2620 2621 getDefaultDisplayMetrics(context, mMetrics); 2622 2623 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "get system config"); 2624 SystemConfig systemConfig = SystemConfig.getInstance(); 2625 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2627 2628 mProtectedPackages = new ProtectedPackages(mContext); 2629 2630 mApexManager = ApexManager.create(mContext); 2631 2632 mDirsToScanAsSystem = new ArrayList<>(); 2633 mDirsToScanAsSystem.addAll(SYSTEM_PARTITIONS); 2634 mDirsToScanAsSystem.addAll(mApexManager.getActiveApexInfos().stream() 2635 .map(ai -> resolveApexToSystemPartition(ai)) 2636 .filter(Objects::nonNull).collect(Collectors.toList())); 2637 Slog.d(TAG, 2638 "Directories scanned as system partitions: [" + mDirsToScanAsSystem.stream().map( 2639 d -> (d.folder.getAbsolutePath() + ":" + d.scanFlag)) 2640 .collect(Collectors.joining(",")) + "]"); 2641 2642 // CHECKSTYLE:OFF IndentationCheck 2643 synchronized (mInstallLock) { 2644 // writer 2645 synchronized (mPackages) { 2646 mHandlerThread = new ServiceThread(TAG, 2647 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2648 mHandlerThread.start(); 2649 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2650 mProcessLoggingHandler = new ProcessLoggingHandler(); 2651 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2652 mInstantAppRegistry = new InstantAppRegistry(this); 2653 2654 ArrayMap<String, SystemConfig.SharedLibraryEntry> libConfig 2655 = systemConfig.getSharedLibraries(); 2656 final int builtInLibCount = libConfig.size(); 2657 for (int i = 0; i < builtInLibCount; i++) { 2658 String name = libConfig.keyAt(i); 2659 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i); 2660 addBuiltInSharedLibraryLocked(entry.filename, name); 2661 } 2662 2663 // Now that we have added all the libraries, iterate again to add dependency 2664 // information IFF their dependencies are added. 2665 long undefinedVersion = SharedLibraryInfo.VERSION_UNDEFINED; 2666 for (int i = 0; i < builtInLibCount; i++) { 2667 String name = libConfig.keyAt(i); 2668 SystemConfig.SharedLibraryEntry entry = libConfig.valueAt(i); 2669 final int dependencyCount = entry.dependencies.length; 2670 for (int j = 0; j < dependencyCount; j++) { 2671 final SharedLibraryInfo dependency = 2672 getSharedLibraryInfoLPr(entry.dependencies[j], undefinedVersion); 2673 if (dependency != null) { 2674 getSharedLibraryInfoLPr(name, undefinedVersion).addDependency(dependency); 2675 } 2676 } 2677 } 2678 2679 SELinuxMMAC.readInstallPolicy(); 2680 2681 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "loadFallbacks"); 2682 FallbackCategoryProvider.loadFallbacks(); 2683 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2684 2685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "read user settings"); 2686 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2687 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 2688 2689 // Clean up orphaned packages for which the code path doesn't exist 2690 // and they are an update to a system app - caused by bug/32321269 2691 final int packageSettingCount = mSettings.mPackages.size(); 2692 for (int i = packageSettingCount - 1; i >= 0; i--) { 2693 PackageSetting ps = mSettings.mPackages.valueAt(i); 2694 if (!isExternal(ps) && (ps.codePath == null || !ps.codePath.exists()) 2695 && mSettings.getDisabledSystemPkgLPr(ps.name) != null) { 2696 mSettings.mPackages.removeAt(i); 2697 mSettings.enableSystemPackageLPw(ps.name); 2698 } 2699 } 2700 2701 if (!mOnlyCore && mFirstBoot) { 2702 requestCopyPreoptedFiles(); 2703 } 2704 2705 String customResolverActivityName = Resources.getSystem().getString( 2706 R.string.config_customResolverActivity); 2707 if (!TextUtils.isEmpty(customResolverActivityName)) { 2708 mCustomResolverComponentName = ComponentName.unflattenFromString( 2709 customResolverActivityName); 2710 } 2711 2712 long startTime = SystemClock.uptimeMillis(); 2713 2714 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2715 startTime); 2716 2717 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2718 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2719 2720 if (bootClassPath == null) { 2721 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2722 } 2723 2724 if (systemServerClassPath == null) { 2725 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2726 } 2727 2728 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2729 2730 final VersionInfo ver = mSettings.getInternalVersion(); 2731 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2732 if (mIsUpgrade) { 2733 logCriticalInfo(Log.INFO, 2734 "Upgrading from " + ver.fingerprint + " to " + Build.FINGERPRINT); 2735 } 2736 2737 // when upgrading from pre-M, promote system app permissions from install to runtime 2738 mPromoteSystemApps = 2739 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2740 2741 // When upgrading from pre-N, we need to handle package extraction like first boot, 2742 // as there is no profiling data available. 2743 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2744 2745 mIsPreNMR1Upgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N_MR1; 2746 mIsPreQUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.Q; 2747 2748 int preUpgradeSdkVersion = ver.sdkVersion; 2749 2750 // save off the names of pre-existing system packages prior to scanning; we don't 2751 // want to automatically grant runtime permissions for new system apps 2752 if (mPromoteSystemApps) { 2753 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2754 while (pkgSettingIter.hasNext()) { 2755 PackageSetting ps = pkgSettingIter.next(); 2756 if (isSystemApp(ps)) { 2757 mExistingSystemPackages.add(ps.name); 2758 } 2759 } 2760 } 2761 2762 mCacheDir = preparePackageParserCache(); 2763 2764 // Set flag to monitor and not change apk file paths when 2765 // scanning install directories. 2766 int scanFlags = SCAN_BOOTING | SCAN_INITIAL; 2767 2768 if (mIsUpgrade || mFirstBoot) { 2769 scanFlags = scanFlags | SCAN_FIRST_BOOT_OR_UPGRADE; 2770 } 2771 2772 // Collect vendor/product/system_ext overlay packages. (Do this before scanning 2773 // any apps.) 2774 // For security and version matching reason, only consider overlay packages if they 2775 // reside in the right directory. 2776 final int systemParseFlags = mDefParseFlags | PackageParser.PARSE_IS_SYSTEM_DIR; 2777 final int systemScanFlags = scanFlags | SCAN_AS_SYSTEM; 2778 for (int i = mDirsToScanAsSystem.size() - 1; i >= 0; i--) { 2779 final SystemPartition partition = mDirsToScanAsSystem.get(i); 2780 if (partition.overlayFolder == null) { 2781 continue; 2782 } 2783 scanDirTracedLI(partition.overlayFolder, systemParseFlags, 2784 systemScanFlags | partition.scanFlag, 0); 2785 } 2786 2787 mParallelPackageParserCallback.findStaticOverlayPackages(); 2788 2789 scanDirTracedLI(frameworkDir, systemParseFlags, 2790 systemScanFlags | SCAN_NO_DEX | SCAN_AS_PRIVILEGED, 0); 2791 if (!mPackages.containsKey("android")) { 2792 throw new IllegalStateException( 2793 "Failed to load frameworks package; check log for warnings"); 2794 } 2795 for (int i = 0, size = mDirsToScanAsSystem.size(); i < size; i++) { 2796 final SystemPartition partition = mDirsToScanAsSystem.get(i); 2797 if (partition.privAppFolder != null) { 2798 scanDirTracedLI(partition.privAppFolder, systemParseFlags, 2799 systemScanFlags | SCAN_AS_PRIVILEGED | partition.scanFlag, 0); 2800 } 2801 scanDirTracedLI(partition.appFolder, systemParseFlags, 2802 systemScanFlags | partition.scanFlag, 0); 2803 } 2804 2805 2806 // Prune any system packages that no longer exist. 2807 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<>(); 2808 // Stub packages must either be replaced with full versions in the /data 2809 // partition or be disabled. 2810 final List<String> stubSystemApps = new ArrayList<>(); 2811 if (!mOnlyCore) { 2812 // do this first before mucking with mPackages for the "expecting better" case 2813 final Iterator<PackageParser.Package> pkgIterator = mPackages.values().iterator(); 2814 while (pkgIterator.hasNext()) { 2815 final PackageParser.Package pkg = pkgIterator.next(); 2816 if (pkg.isStub) { 2817 stubSystemApps.add(pkg.packageName); 2818 } 2819 } 2820 2821 final Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2822 while (psit.hasNext()) { 2823 PackageSetting ps = psit.next(); 2824 2825 /* 2826 * If this is not a system app, it can't be a 2827 * disable system app. 2828 */ 2829 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2830 continue; 2831 } 2832 2833 /* 2834 * If the package is scanned, it's not erased. 2835 */ 2836 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2837 if (scannedPkg != null) { 2838 /* 2839 * If the system app is both scanned and in the 2840 * disabled packages list, then it must have been 2841 * added via OTA. Remove it from the currently 2842 * scanned package so the previously user-installed 2843 * application can be scanned. 2844 */ 2845 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2846 logCriticalInfo(Log.WARN, 2847 "Expecting better updated system app for " + ps.name 2848 + "; removing system app. Last known" 2849 + " codePath=" + ps.codePathString 2850 + ", versionCode=" + ps.versionCode 2851 + "; scanned versionCode=" + scannedPkg.getLongVersionCode()); 2852 removePackageLI(scannedPkg, true); 2853 mExpectingBetter.put(ps.name, ps.codePath); 2854 } 2855 2856 continue; 2857 } 2858 2859 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2860 psit.remove(); 2861 logCriticalInfo(Log.WARN, "System package " + ps.name 2862 + " no longer exists; it's data will be wiped"); 2863 // Actual deletion of code and data will be handled by later 2864 // reconciliation step 2865 } else { 2866 // we still have a disabled system package, but, it still might have 2867 // been removed. check the code path still exists and check there's 2868 // still a package. the latter can happen if an OTA keeps the same 2869 // code path, but, changes the package name. 2870 final PackageSetting disabledPs = 2871 mSettings.getDisabledSystemPkgLPr(ps.name); 2872 if (disabledPs.codePath == null || !disabledPs.codePath.exists() 2873 || disabledPs.pkg == null) { 2874 possiblyDeletedUpdatedSystemApps.add(ps.name); 2875 } else { 2876 // We're expecting that the system app should remain disabled, but add 2877 // it to expecting better to recover in case the data version cannot 2878 // be scanned. 2879 mExpectingBetter.put(disabledPs.name, disabledPs.codePath); 2880 } 2881 } 2882 } 2883 } 2884 2885 //delete tmp files 2886 deleteTempPackageFiles(); 2887 2888 final int cachedSystemApps = PackageParser.sCachedPackageReadCount.get(); 2889 2890 // Remove any shared userIDs that have no associated packages 2891 mSettings.pruneSharedUsersLPw(); 2892 final long systemScanTime = SystemClock.uptimeMillis() - startTime; 2893 final int systemPackagesCount = mPackages.size(); 2894 Slog.i(TAG, "Finished scanning system apps. Time: " + systemScanTime 2895 + " ms, packageCount: " + systemPackagesCount 2896 + " , timePerPackage: " 2897 + (systemPackagesCount == 0 ? 0 : systemScanTime / systemPackagesCount) 2898 + " , cached: " + cachedSystemApps); 2899 if (mIsUpgrade && systemPackagesCount > 0) { 2900 MetricsLogger.histogram(null, "ota_package_manager_system_app_avg_scan_time", 2901 ((int) systemScanTime) / systemPackagesCount); 2902 } 2903 if (!mOnlyCore) { 2904 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2905 SystemClock.uptimeMillis()); 2906 scanDirTracedLI(sAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2907 2908 // Remove disable package settings for updated system apps that were 2909 // removed via an OTA. If the update is no longer present, remove the 2910 // app completely. Otherwise, revoke their system privileges. 2911 for (int i = possiblyDeletedUpdatedSystemApps.size() - 1; i >= 0; --i) { 2912 final String packageName = possiblyDeletedUpdatedSystemApps.get(i); 2913 final PackageParser.Package pkg = mPackages.get(packageName); 2914 final String msg; 2915 2916 // remove from the disabled system list; do this first so any future 2917 // scans of this package are performed without this state 2918 mSettings.removeDisabledSystemPackageLPw(packageName); 2919 2920 if (pkg == null) { 2921 // should have found an update, but, we didn't; remove everything 2922 msg = "Updated system package " + packageName 2923 + " no longer exists; removing its data"; 2924 // Actual deletion of code and data will be handled by later 2925 // reconciliation step 2926 } else { 2927 // found an update; revoke system privileges 2928 msg = "Updated system package " + packageName 2929 + " no longer exists; rescanning package on data"; 2930 2931 // NOTE: We don't do anything special if a stub is removed from the 2932 // system image. But, if we were [like removing the uncompressed 2933 // version from the /data partition], this is where it'd be done. 2934 2935 // remove the package from the system and re-scan it without any 2936 // special privileges 2937 removePackageLI(pkg, true); 2938 try { 2939 final File codePath = new File(pkg.applicationInfo.getCodePath()); 2940 scanPackageTracedLI(codePath, 0, scanFlags, 0, null); 2941 } catch (PackageManagerException e) { 2942 Slog.e(TAG, "Failed to parse updated, ex-system package: " 2943 + e.getMessage()); 2944 } 2945 } 2946 2947 // one final check. if we still have a package setting [ie. it was 2948 // previously scanned and known to the system], but, we don't have 2949 // a package [ie. there was an error scanning it from the /data 2950 // partition], completely remove the package data. 2951 final PackageSetting ps = mSettings.mPackages.get(packageName); 2952 if (ps != null && mPackages.get(packageName) == null) { 2953 removePackageDataLIF(ps, null, null, 0, false); 2954 2955 } 2956 logCriticalInfo(Log.WARN, msg); 2957 } 2958 2959 /* 2960 * Make sure all system apps that we expected to appear on 2961 * the userdata partition actually showed up. If they never 2962 * appeared, crawl back and revive the system version. 2963 */ 2964 for (int i = 0; i < mExpectingBetter.size(); i++) { 2965 final String packageName = mExpectingBetter.keyAt(i); 2966 if (!mPackages.containsKey(packageName)) { 2967 final File scanFile = mExpectingBetter.valueAt(i); 2968 2969 logCriticalInfo(Log.WARN, "Expected better " + packageName 2970 + " but never showed up; reverting to system"); 2971 2972 @ParseFlags int reparseFlags = 0; 2973 @ScanFlags int rescanFlags = 0; 2974 for (int i1 = 0, size = mDirsToScanAsSystem.size(); i1 < size; i1++) { 2975 SystemPartition partition = mDirsToScanAsSystem.get(i1); 2976 if (partition.containsPrivApp(scanFile)) { 2977 reparseFlags = systemParseFlags; 2978 rescanFlags = systemScanFlags | SCAN_AS_PRIVILEGED 2979 | partition.scanFlag; 2980 break; 2981 } 2982 if (partition.containsApp(scanFile)) { 2983 reparseFlags = systemParseFlags; 2984 rescanFlags = systemScanFlags | partition.scanFlag; 2985 break; 2986 } 2987 } 2988 if (rescanFlags == 0) { 2989 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2990 continue; 2991 } 2992 mSettings.enableSystemPackageLPw(packageName); 2993 2994 try { 2995 scanPackageTracedLI(scanFile, reparseFlags, rescanFlags, 0, null); 2996 } catch (PackageManagerException e) { 2997 Slog.e(TAG, "Failed to parse original system package: " 2998 + e.getMessage()); 2999 } 3000 } 3001 } 3002 3003 // Uncompress and install any stubbed system applications. 3004 // This must be done last to ensure all stubs are replaced or disabled. 3005 installSystemStubPackages(stubSystemApps, scanFlags); 3006 3007 final int cachedNonSystemApps = PackageParser.sCachedPackageReadCount.get() 3008 - cachedSystemApps; 3009 3010 final long dataScanTime = SystemClock.uptimeMillis() - systemScanTime - startTime; 3011 final int dataPackagesCount = mPackages.size() - systemPackagesCount; 3012 Slog.i(TAG, "Finished scanning non-system apps. Time: " + dataScanTime 3013 + " ms, packageCount: " + dataPackagesCount 3014 + " , timePerPackage: " 3015 + (dataPackagesCount == 0 ? 0 : dataScanTime / dataPackagesCount) 3016 + " , cached: " + cachedNonSystemApps); 3017 if (mIsUpgrade && dataPackagesCount > 0) { 3018 MetricsLogger.histogram(null, "ota_package_manager_data_app_avg_scan_time", 3019 ((int) dataScanTime) / dataPackagesCount); 3020 } 3021 } 3022 mExpectingBetter.clear(); 3023 3024 // Resolve the storage manager. 3025 mStorageManagerPackage = getStorageManagerPackageName(); 3026 3027 // Resolve protected action filters. Only the setup wizard is allowed to 3028 // have a high priority filter for these actions. 3029 mSetupWizardPackage = getSetupWizardPackageName(); 3030 mComponentResolver.fixProtectedFilterPriorities(); 3031 3032 mSystemTextClassifierPackage = getSystemTextClassifierPackageName(); 3033 3034 mWellbeingPackage = getWellbeingPackageName(); 3035 mDocumenterPackage = getDocumenterPackageName(); 3036 mConfiguratorPackage = getDeviceConfiguratorPackageName(); 3037 mAppPredictionServicePackage = getAppPredictionServicePackageName(); 3038 mIncidentReportApproverPackage = getIncidentReportApproverPackageName(); 3039 mTelephonyPackages = getTelephonyPackageNames(); 3040 3041 // Now that we know all of the shared libraries, update all clients to have 3042 // the correct library paths. 3043 updateAllSharedLibrariesLocked(null, Collections.unmodifiableMap(mPackages)); 3044 3045 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 3046 // NOTE: We ignore potential failures here during a system scan (like 3047 // the rest of the commands above) because there's precious little we 3048 // can do about it. A settings error is reported, though. 3049 final List<String> changedAbiCodePath = 3050 applyAdjustedAbiToSharedUser(setting, null /*scannedPackage*/, 3051 mInjector.getAbiHelper().getAdjustedAbiForSharedUser( 3052 setting.packages, null /*scannedPackage*/)); 3053 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 3054 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 3055 final String codePathString = changedAbiCodePath.get(i); 3056 try { 3057 mInstaller.rmdex(codePathString, 3058 getDexCodeInstructionSet(getPreferredInstructionSet())); 3059 } catch (InstallerException ignored) { 3060 } 3061 } 3062 } 3063 // Adjust seInfo to ensure apps which share a sharedUserId are placed in the same 3064 // SELinux domain. 3065 setting.fixSeInfoLocked(); 3066 } 3067 3068 // Now that we know all the packages we are keeping, 3069 // read and update their last usage times. 3070 mPackageUsage.read(mPackages); 3071 mCompilerStats.read(); 3072 3073 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 3074 SystemClock.uptimeMillis()); 3075 Slog.i(TAG, "Time to scan packages: " 3076 + ((SystemClock.uptimeMillis()-startTime)/1000f) 3077 + " seconds"); 3078 3079 // If the platform SDK has changed since the last time we booted, 3080 // we need to re-grant app permission to catch any new ones that 3081 // appear. This is really a hack, and means that apps can in some 3082 // cases get permissions that the user didn't initially explicitly 3083 // allow... it would be nice to have some better way to handle 3084 // this situation. 3085 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 3086 if (sdkUpdated) { 3087 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 3088 + mSdkVersion + "; regranting permissions for internal storage"); 3089 } 3090 mPermissionManager.updateAllPermissions( 3091 StorageManager.UUID_PRIVATE_INTERNAL, sdkUpdated, mPackages.values(), 3092 mPermissionCallback); 3093 ver.sdkVersion = mSdkVersion; 3094 3095 // If this is the first boot or an update from pre-M, and it is a normal 3096 // boot, then we need to initialize the default preferred apps across 3097 // all defined users. 3098 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 3099 for (UserInfo user : sUserManager.getUsers(true)) { 3100 mSettings.applyDefaultPreferredAppsLPw(user.id); 3101 primeDomainVerificationsLPw(user.id); 3102 } 3103 } 3104 3105 // Prepare storage for system user really early during boot, 3106 // since core system apps like SettingsProvider and SystemUI 3107 // can't wait for user to start 3108 final int storageFlags; 3109 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3110 storageFlags = StorageManager.FLAG_STORAGE_DE; 3111 } else { 3112 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 3113 } 3114 List<String> deferPackages = reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, 3115 UserHandle.USER_SYSTEM, storageFlags, true /* migrateAppData */, 3116 true /* onlyCoreApps */); 3117 mPrepareAppDataFuture = SystemServerInitThreadPool.get().submit(() -> { 3118 TimingsTraceLog traceLog = new TimingsTraceLog("SystemServerTimingAsync", 3119 Trace.TRACE_TAG_PACKAGE_MANAGER); 3120 traceLog.traceBegin("AppDataFixup"); 3121 try { 3122 mInstaller.fixupAppData(StorageManager.UUID_PRIVATE_INTERNAL, 3123 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 3124 } catch (InstallerException e) { 3125 Slog.w(TAG, "Trouble fixing GIDs", e); 3126 } 3127 traceLog.traceEnd(); 3128 3129 traceLog.traceBegin("AppDataPrepare"); 3130 if (deferPackages == null || deferPackages.isEmpty()) { 3131 return; 3132 } 3133 int count = 0; 3134 for (String pkgName : deferPackages) { 3135 PackageParser.Package pkg = null; 3136 synchronized (mPackages) { 3137 PackageSetting ps = mSettings.getPackageLPr(pkgName); 3138 if (ps != null && ps.getInstalled(UserHandle.USER_SYSTEM)) { 3139 pkg = ps.pkg; 3140 } 3141 } 3142 if (pkg != null) { 3143 synchronized (mInstallLock) { 3144 prepareAppDataAndMigrateLIF(pkg, UserHandle.USER_SYSTEM, storageFlags, 3145 true /* maybeMigrateAppData */); 3146 } 3147 count++; 3148 } 3149 } 3150 traceLog.traceEnd(); 3151 Slog.i(TAG, "Deferred reconcileAppsData finished " + count + " packages"); 3152 }, "prepareAppData"); 3153 3154 // If this is first boot after an OTA, and a normal boot, then 3155 // we need to clear code cache directories. 3156 // Note that we do *not* clear the application profiles. These remain valid 3157 // across OTAs and are used to drive profile verification (post OTA) and 3158 // profile compilation (without waiting to collect a fresh set of profiles). 3159 if (mIsUpgrade && !onlyCore) { 3160 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 3161 for (int i = 0; i < mSettings.mPackages.size(); i++) { 3162 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3163 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 3164 // No apps are running this early, so no need to freeze 3165 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 3166 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL 3167 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY 3168 | Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES); 3169 } 3170 } 3171 ver.fingerprint = Build.FINGERPRINT; 3172 } 3173 3174 // Grandfather existing (installed before Q) non-system apps to hide 3175 // their icons in launcher. 3176 if (!onlyCore && mIsPreQUpgrade) { 3177 Slog.i(TAG, "Whitelisting all existing apps to hide their icons"); 3178 int size = mSettings.mPackages.size(); 3179 for (int i = 0; i < size; i++) { 3180 final PackageSetting ps = mSettings.mPackages.valueAt(i); 3181 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 3182 continue; 3183 } 3184 ps.disableComponentLPw(PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME, 3185 UserHandle.USER_SYSTEM); 3186 } 3187 } 3188 3189 // clear only after permissions and other defaults have been updated 3190 mExistingSystemPackages.clear(); 3191 mPromoteSystemApps = false; 3192 3193 // All the changes are done during package scanning. 3194 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 3195 3196 // can downgrade to reader 3197 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "write settings"); 3198 mSettings.writeLPr(); 3199 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3200 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 3201 SystemClock.uptimeMillis()); 3202 3203 if (!mOnlyCore) { 3204 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 3205 mRequiredInstallerPackage = getRequiredInstallerLPr(); 3206 mRequiredUninstallerPackage = getRequiredUninstallerLPr(); 3207 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 3208 if (mIntentFilterVerifierComponent != null) { 3209 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 3210 mIntentFilterVerifierComponent); 3211 } else { 3212 mIntentFilterVerifier = null; 3213 } 3214 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3215 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES, 3216 SharedLibraryInfo.VERSION_UNDEFINED); 3217 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 3218 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED, 3219 SharedLibraryInfo.VERSION_UNDEFINED); 3220 } else { 3221 mRequiredVerifierPackage = null; 3222 mRequiredInstallerPackage = null; 3223 mRequiredUninstallerPackage = null; 3224 mIntentFilterVerifierComponent = null; 3225 mIntentFilterVerifier = null; 3226 mServicesSystemSharedLibraryPackageName = null; 3227 mSharedSystemSharedLibraryPackageName = null; 3228 } 3229 // PermissionController hosts default permission granting and role management, so it's a 3230 // critical part of the core system. 3231 mRequiredPermissionControllerPackage = getRequiredPermissionControllerLPr(); 3232 3233 // Initialize InstantAppRegistry's Instant App list for all users. 3234 final int[] userIds = UserManagerService.getInstance().getUserIds(); 3235 for (PackageParser.Package pkg : mPackages.values()) { 3236 if (pkg.isSystem()) { 3237 continue; 3238 } 3239 for (int userId : userIds) { 3240 final PackageSetting ps = (PackageSetting) pkg.mExtras; 3241 if (ps == null || !ps.getInstantApp(userId) || !ps.getInstalled(userId)) { 3242 continue; 3243 } 3244 mInstantAppRegistry.addInstantAppLPw(userId, ps.appId); 3245 } 3246 } 3247 3248 mInstallerService = new PackageInstallerService(context, this, mApexManager); 3249 final Pair<ComponentName, String> instantAppResolverComponent = 3250 getInstantAppResolverLPr(); 3251 if (instantAppResolverComponent != null) { 3252 if (DEBUG_INSTANT) { 3253 Slog.d(TAG, "Set ephemeral resolver: " + instantAppResolverComponent); 3254 } 3255 mInstantAppResolverConnection = new InstantAppResolverConnection( 3256 mContext, instantAppResolverComponent.first, 3257 instantAppResolverComponent.second); 3258 mInstantAppResolverSettingsComponent = 3259 getInstantAppResolverSettingsLPr(instantAppResolverComponent.first); 3260 } else { 3261 mInstantAppResolverConnection = null; 3262 mInstantAppResolverSettingsComponent = null; 3263 } 3264 updateInstantAppInstallerLocked(null); 3265 3266 // Read and update the usage of dex files. 3267 // Do this at the end of PM init so that all the packages have their 3268 // data directory reconciled. 3269 // At this point we know the code paths of the packages, so we can validate 3270 // the disk file and build the internal cache. 3271 // The usage file is expected to be small so loading and verifying it 3272 // should take a fairly small time compare to the other activities (e.g. package 3273 // scanning). 3274 final Map<Integer, List<PackageInfo>> userPackages = new HashMap<>(); 3275 for (int userId : userIds) { 3276 userPackages.put(userId, getInstalledPackages(/*flags*/ 0, userId).getList()); 3277 } 3278 mDexManager.load(userPackages); 3279 if (mIsUpgrade) { 3280 MetricsLogger.histogram(null, "ota_package_manager_init_time", 3281 (int) (SystemClock.uptimeMillis() - startTime)); 3282 } 3283 } // synchronized (mPackages) 3284 } // synchronized (mInstallLock) 3285 3286 mModuleInfoProvider = new ModuleInfoProvider(mContext, this); 3287 3288 // Now after opening every single application zip, make sure they 3289 // are all flushed. Not really needed, but keeps things nice and 3290 // tidy. 3291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "GC"); 3292 Runtime.getRuntime().gc(); 3293 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3294 3295 // The initial scanning above does many calls into installd while 3296 // holding the mPackages lock, but we're mostly interested in yelling 3297 // once we have a booted system. 3298 mInstaller.setWarnIfHeld(mPackages); 3299 3300 PackageParser.readConfigUseRoundIcon(mContext.getResources()); 3301 3302 mServiceStartWithDelay = SystemClock.uptimeMillis() + (60 * 1000L); 3303 3304 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 3305 } 3306 3307 /** 3308 * Uncompress and install stub applications. 3309 * <p>In order to save space on the system partition, some applications are shipped in a 3310 * compressed form. In addition the compressed bits for the full application, the 3311 * system image contains a tiny stub comprised of only the Android manifest. 3312 * <p>During the first boot, attempt to uncompress and install the full application. If 3313 * the application can't be installed for any reason, disable the stub and prevent 3314 * uncompressing the full application during future boots. 3315 * <p>In order to forcefully attempt an installation of a full application, go to app 3316 * settings and enable the application. 3317 */ 3318 private void installSystemStubPackages(@NonNull List<String> systemStubPackageNames, 3319 @ScanFlags int scanFlags) { 3320 for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) { 3321 final String packageName = systemStubPackageNames.get(i); 3322 // skip if the system package is already disabled 3323 if (mSettings.isDisabledSystemPackageLPr(packageName)) { 3324 systemStubPackageNames.remove(i); 3325 continue; 3326 } 3327 // skip if the package isn't installed (?!); this should never happen 3328 final PackageParser.Package pkg = mPackages.get(packageName); 3329 if (pkg == null) { 3330 systemStubPackageNames.remove(i); 3331 continue; 3332 } 3333 // skip if the package has been disabled by the user 3334 final PackageSetting ps = mSettings.mPackages.get(packageName); 3335 if (ps != null) { 3336 final int enabledState = ps.getEnabled(UserHandle.USER_SYSTEM); 3337 if (enabledState == PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER) { 3338 systemStubPackageNames.remove(i); 3339 continue; 3340 } 3341 } 3342 3343 // install the package to replace the stub on /system 3344 try { 3345 installStubPackageLI(pkg, 0, scanFlags); 3346 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 3347 UserHandle.USER_SYSTEM, "android"); 3348 systemStubPackageNames.remove(i); 3349 } catch (PackageManagerException e) { 3350 Slog.e(TAG, "Failed to parse uncompressed system package: " + e.getMessage()); 3351 } 3352 3353 // any failed attempt to install the package will be cleaned up later 3354 } 3355 3356 // disable any stub still left; these failed to install the full application 3357 for (int i = systemStubPackageNames.size() - 1; i >= 0; --i) { 3358 final String pkgName = systemStubPackageNames.get(i); 3359 final PackageSetting ps = mSettings.mPackages.get(pkgName); 3360 ps.setEnabled(PackageManager.COMPONENT_ENABLED_STATE_DISABLED, 3361 UserHandle.USER_SYSTEM, "android"); 3362 logCriticalInfo(Log.ERROR, "Stub disabled; pkg: " + pkgName); 3363 } 3364 } 3365 3366 /** 3367 * Extract, install and enable a stub package. 3368 * <p>If the compressed file can not be extracted / installed for any reason, the stub 3369 * APK will be installed and the package will be disabled. To recover from this situation, 3370 * the user will need to go into system settings and re-enable the package. 3371 */ 3372 private boolean enableCompressedPackage(PackageParser.Package stubPkg) { 3373 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 3374 | PackageParser.PARSE_ENFORCE_CODE; 3375 synchronized (mInstallLock) { 3376 final PackageParser.Package pkg; 3377 try (PackageFreezer freezer = 3378 freezePackage(stubPkg.packageName, "setEnabledSetting")) { 3379 pkg = installStubPackageLI(stubPkg, parseFlags, 0 /*scanFlags*/); 3380 synchronized (mPackages) { 3381 prepareAppDataAfterInstallLIF(pkg); 3382 try { 3383 updateSharedLibrariesLocked(pkg, null, mPackages); 3384 } catch (PackageManagerException e) { 3385 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: ", e); 3386 } 3387 mPermissionManager.updatePermissions( 3388 pkg.packageName, pkg, true, mPackages.values(), 3389 mPermissionCallback); 3390 mSettings.writeLPr(); 3391 } 3392 } catch (PackageManagerException e) { 3393 // Whoops! Something went very wrong; roll back to the stub and disable the package 3394 try (PackageFreezer freezer = 3395 freezePackage(stubPkg.packageName, "setEnabledSetting")) { 3396 synchronized (mPackages) { 3397 // NOTE: Ensure the system package is enabled; even for a compressed stub. 3398 // If we don't, installing the system package fails during scan 3399 enableSystemPackageLPw(stubPkg); 3400 } 3401 installPackageFromSystemLIF(stubPkg.codePath, 3402 null /*allUserHandles*/, null /*origUserHandles*/, 3403 null /*origPermissionsState*/, true /*writeSettings*/); 3404 } catch (PackageManagerException pme) { 3405 // Serious WTF; we have to be able to install the stub 3406 Slog.wtf(TAG, "Failed to restore system package:" + stubPkg.packageName, pme); 3407 } finally { 3408 // Disable the package; the stub by itself is not runnable 3409 synchronized (mPackages) { 3410 final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName); 3411 if (stubPs != null) { 3412 stubPs.setEnabled(COMPONENT_ENABLED_STATE_DISABLED, 3413 UserHandle.USER_SYSTEM, "android"); 3414 } 3415 mSettings.writeLPr(); 3416 } 3417 } 3418 return false; 3419 } 3420 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 3421 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 3422 mDexManager.notifyPackageUpdated(pkg.packageName, 3423 pkg.baseCodePath, pkg.splitCodePaths); 3424 } 3425 return true; 3426 } 3427 3428 private PackageParser.Package installStubPackageLI(PackageParser.Package stubPkg, 3429 @ParseFlags int parseFlags, @ScanFlags int scanFlags) 3430 throws PackageManagerException { 3431 if (DEBUG_COMPRESSION) { 3432 Slog.i(TAG, "Uncompressing system stub; pkg: " + stubPkg.packageName); 3433 } 3434 // uncompress the binary to its eventual destination on /data 3435 final File scanFile = decompressPackage(stubPkg.packageName, stubPkg.codePath); 3436 if (scanFile == null) { 3437 throw new PackageManagerException("Unable to decompress stub at " + stubPkg.codePath); 3438 } 3439 synchronized (mPackages) { 3440 mSettings.disableSystemPackageLPw(stubPkg.packageName, true /*replaced*/); 3441 } 3442 removePackageLI(stubPkg, true /*chatty*/); 3443 try { 3444 return scanPackageTracedLI(scanFile, parseFlags, scanFlags, 0, null); 3445 } catch (PackageManagerException e) { 3446 Slog.w(TAG, "Failed to install compressed system package:" + stubPkg.packageName, e); 3447 // Remove the failed install 3448 removeCodePathLI(scanFile); 3449 throw e; 3450 } 3451 } 3452 3453 /** 3454 * Decompresses the given package on the system image onto 3455 * the /data partition. 3456 * @return The directory the package was decompressed into. Otherwise, {@code null}. 3457 */ 3458 private File decompressPackage(String packageName, String codePath) { 3459 final File[] compressedFiles = getCompressedFiles(codePath); 3460 if (compressedFiles == null || compressedFiles.length == 0) { 3461 if (DEBUG_COMPRESSION) { 3462 Slog.i(TAG, "No files to decompress: " + codePath); 3463 } 3464 return null; 3465 } 3466 final File dstCodePath = 3467 getNextCodePath(Environment.getDataAppDirectory(null), packageName); 3468 int ret = PackageManager.INSTALL_SUCCEEDED; 3469 try { 3470 Os.mkdir(dstCodePath.getAbsolutePath(), 0755); 3471 Os.chmod(dstCodePath.getAbsolutePath(), 0755); 3472 for (File srcFile : compressedFiles) { 3473 final String srcFileName = srcFile.getName(); 3474 final String dstFileName = srcFileName.substring( 3475 0, srcFileName.length() - COMPRESSED_EXTENSION.length()); 3476 final File dstFile = new File(dstCodePath, dstFileName); 3477 ret = decompressFile(srcFile, dstFile); 3478 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3479 logCriticalInfo(Log.ERROR, "Failed to decompress" 3480 + "; pkg: " + packageName 3481 + ", file: " + dstFileName); 3482 break; 3483 } 3484 } 3485 } catch (ErrnoException e) { 3486 logCriticalInfo(Log.ERROR, "Failed to decompress" 3487 + "; pkg: " + packageName 3488 + ", err: " + e.errno); 3489 } 3490 if (ret == PackageManager.INSTALL_SUCCEEDED) { 3491 final File libraryRoot = new File(dstCodePath, LIB_DIR_NAME); 3492 NativeLibraryHelper.Handle handle = null; 3493 try { 3494 handle = NativeLibraryHelper.Handle.create(dstCodePath); 3495 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 3496 null /*abiOverride*/); 3497 } catch (IOException e) { 3498 logCriticalInfo(Log.ERROR, "Failed to extract native libraries" 3499 + "; pkg: " + packageName); 3500 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 3501 } finally { 3502 IoUtils.closeQuietly(handle); 3503 } 3504 } 3505 if (ret != PackageManager.INSTALL_SUCCEEDED) { 3506 if (!dstCodePath.exists()) { 3507 return null; 3508 } 3509 removeCodePathLI(dstCodePath); 3510 return null; 3511 } 3512 3513 return dstCodePath; 3514 } 3515 3516 @GuardedBy("mPackages") 3517 private void updateInstantAppInstallerLocked(String modifiedPackage) { 3518 // we're only interested in updating the installer appliction when 1) it's not 3519 // already set or 2) the modified package is the installer 3520 if (mInstantAppInstallerActivity != null 3521 && !mInstantAppInstallerActivity.getComponentName().getPackageName() 3522 .equals(modifiedPackage)) { 3523 return; 3524 } 3525 setUpInstantAppInstallerActivityLP(getInstantAppInstallerLPr()); 3526 } 3527 3528 private static @Nullable File preparePackageParserCache() { 3529 if (!DEFAULT_PACKAGE_PARSER_CACHE_ENABLED) { 3530 return null; 3531 } 3532 3533 // Disable package parsing on eng builds to allow for faster incremental development. 3534 if (Build.IS_ENG) { 3535 return null; 3536 } 3537 3538 if (SystemProperties.getBoolean("pm.boot.disable_package_cache", false)) { 3539 Slog.i(TAG, "Disabling package parser cache due to system property."); 3540 return null; 3541 } 3542 3543 // The base directory for the package parser cache lives under /data/system/. 3544 final File cacheBaseDir = Environment.getPackageCacheDirectory(); 3545 if (!FileUtils.createDir(cacheBaseDir)) { 3546 return null; 3547 } 3548 3549 // There are several items that need to be combined together to safely 3550 // identify cached items. In particular, changing the value of certain 3551 // feature flags should cause us to invalidate any caches. 3552 final String cacheName = SystemProperties.digestOf( 3553 "ro.build.fingerprint", 3554 StorageManager.PROP_ISOLATED_STORAGE, 3555 StorageManager.PROP_ISOLATED_STORAGE_SNAPSHOT); 3556 3557 // Reconcile cache directories, keeping only what we'd actually use. 3558 for (File cacheDir : FileUtils.listFilesOrEmpty(cacheBaseDir)) { 3559 if (Objects.equals(cacheName, cacheDir.getName())) { 3560 Slog.d(TAG, "Keeping known cache " + cacheDir.getName()); 3561 } else { 3562 Slog.d(TAG, "Destroying unknown cache " + cacheDir.getName()); 3563 FileUtils.deleteContentsAndDir(cacheDir); 3564 } 3565 } 3566 3567 // Return the versioned package cache directory. 3568 File cacheDir = FileUtils.createDir(cacheBaseDir, cacheName); 3569 3570 if (cacheDir == null) { 3571 // Something went wrong. Attempt to delete everything and return. 3572 Slog.wtf(TAG, "Cache directory cannot be created - wiping base dir " + cacheBaseDir); 3573 FileUtils.deleteContentsAndDir(cacheBaseDir); 3574 return null; 3575 } 3576 3577 // The following is a workaround to aid development on non-numbered userdebug 3578 // builds or cases where "adb sync" is used on userdebug builds. If we detect that 3579 // the system partition is newer. 3580 // 3581 // NOTE: When no BUILD_NUMBER is set by the build system, it defaults to a build 3582 // that starts with "eng." to signify that this is an engineering build and not 3583 // destined for release. 3584 if (Build.IS_USERDEBUG && Build.VERSION.INCREMENTAL.startsWith("eng.")) { 3585 Slog.w(TAG, "Wiping cache directory because the system partition changed."); 3586 3587 // Heuristic: If the /system directory has been modified recently due to an "adb sync" 3588 // or a regular make, then blow away the cache. Note that mtimes are *NOT* reliable 3589 // in general and should not be used for production changes. In this specific case, 3590 // we know that they will work. 3591 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 3592 if (cacheDir.lastModified() < frameworkDir.lastModified()) { 3593 FileUtils.deleteContents(cacheBaseDir); 3594 cacheDir = FileUtils.createDir(cacheBaseDir, cacheName); 3595 } 3596 } 3597 3598 return cacheDir; 3599 } 3600 3601 @Override 3602 public boolean isFirstBoot() { 3603 // allow instant applications 3604 return mFirstBoot; 3605 } 3606 3607 @Override 3608 public boolean isOnlyCoreApps() { 3609 // allow instant applications 3610 return mOnlyCore; 3611 } 3612 3613 @Override 3614 public boolean isDeviceUpgrading() { 3615 // allow instant applications 3616 // The system property allows testing ota flow when upgraded to the same image. 3617 return mIsUpgrade || SystemProperties.getBoolean( 3618 "persist.pm.mock-upgrade", false /* default */); 3619 } 3620 3621 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 3622 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 3623 3624 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3625 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3626 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3627 if (matches.size() == 1) { 3628 return matches.get(0).getComponentInfo().packageName; 3629 } else if (matches.size() == 0) { 3630 Log.e(TAG, "There should probably be a verifier, but, none were found"); 3631 return null; 3632 } 3633 throw new RuntimeException("There must be exactly one verifier; found " + matches); 3634 } 3635 3636 private @NonNull String getRequiredSharedLibraryLPr(String name, int version) { 3637 synchronized (mPackages) { 3638 SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(name, version); 3639 if (libraryInfo == null) { 3640 throw new IllegalStateException("Missing required shared library:" + name); 3641 } 3642 String packageName = libraryInfo.getPackageName(); 3643 if (packageName == null) { 3644 throw new IllegalStateException("Expected a package for shared library " + name); 3645 } 3646 return packageName; 3647 } 3648 } 3649 3650 private @NonNull String getRequiredInstallerLPr() { 3651 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 3652 intent.addCategory(Intent.CATEGORY_DEFAULT); 3653 intent.setDataAndType(Uri.parse("content://com.example/foo.apk"), PACKAGE_MIME_TYPE); 3654 3655 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3656 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3657 UserHandle.USER_SYSTEM); 3658 if (matches.size() == 1) { 3659 ResolveInfo resolveInfo = matches.get(0); 3660 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3661 throw new RuntimeException("The installer must be a privileged app"); 3662 } 3663 return matches.get(0).getComponentInfo().packageName; 3664 } else { 3665 throw new RuntimeException("There must be exactly one installer; found " + matches); 3666 } 3667 } 3668 3669 private @NonNull String getRequiredUninstallerLPr() { 3670 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 3671 intent.addCategory(Intent.CATEGORY_DEFAULT); 3672 intent.setData(Uri.fromParts(PACKAGE_SCHEME, "foo.bar", null)); 3673 3674 final ResolveInfo resolveInfo = resolveIntent(intent, null, 3675 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3676 UserHandle.USER_SYSTEM); 3677 if (resolveInfo == null || 3678 mResolveActivity.name.equals(resolveInfo.getComponentInfo().name)) { 3679 throw new RuntimeException("There must be exactly one uninstaller; found " 3680 + resolveInfo); 3681 } 3682 return resolveInfo.getComponentInfo().packageName; 3683 } 3684 3685 private @NonNull String getRequiredPermissionControllerLPr() { 3686 final Intent intent = new Intent(Intent.ACTION_MANAGE_PERMISSIONS); 3687 intent.addCategory(Intent.CATEGORY_DEFAULT); 3688 3689 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 3690 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3691 UserHandle.USER_SYSTEM); 3692 if (matches.size() == 1) { 3693 ResolveInfo resolveInfo = matches.get(0); 3694 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 3695 throw new RuntimeException("The permissions manager must be a privileged app"); 3696 } 3697 return matches.get(0).getComponentInfo().packageName; 3698 } else { 3699 throw new RuntimeException("There must be exactly one permissions manager; found " 3700 + matches); 3701 } 3702 } 3703 3704 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 3705 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 3706 3707 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 3708 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3709 UserHandle.USER_SYSTEM, false /*allowDynamicSplits*/); 3710 ResolveInfo best = null; 3711 final int N = matches.size(); 3712 for (int i = 0; i < N; i++) { 3713 final ResolveInfo cur = matches.get(i); 3714 final String packageName = cur.getComponentInfo().packageName; 3715 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 3716 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 3717 continue; 3718 } 3719 3720 if (best == null || cur.priority > best.priority) { 3721 best = cur; 3722 } 3723 } 3724 3725 if (best != null) { 3726 return best.getComponentInfo().getComponentName(); 3727 } 3728 Slog.w(TAG, "Intent filter verifier not found"); 3729 return null; 3730 } 3731 3732 @Override 3733 public @Nullable ComponentName getInstantAppResolverComponent() { 3734 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 3735 return null; 3736 } 3737 synchronized (mPackages) { 3738 final Pair<ComponentName, String> instantAppResolver = getInstantAppResolverLPr(); 3739 if (instantAppResolver == null) { 3740 return null; 3741 } 3742 return instantAppResolver.first; 3743 } 3744 } 3745 3746 private @Nullable Pair<ComponentName, String> getInstantAppResolverLPr() { 3747 final String[] packageArray = 3748 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 3749 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 3750 if (DEBUG_INSTANT) { 3751 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 3752 } 3753 return null; 3754 } 3755 3756 final int callingUid = Binder.getCallingUid(); 3757 final int resolveFlags = 3758 MATCH_DIRECT_BOOT_AWARE 3759 | MATCH_DIRECT_BOOT_UNAWARE 3760 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3761 String actionName = Intent.ACTION_RESOLVE_INSTANT_APP_PACKAGE; 3762 final Intent resolverIntent = new Intent(actionName); 3763 List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 3764 resolveFlags, UserHandle.USER_SYSTEM, callingUid, false /*includeInstantApps*/); 3765 final int N = resolvers.size(); 3766 if (N == 0) { 3767 if (DEBUG_INSTANT) { 3768 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 3769 } 3770 return null; 3771 } 3772 3773 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3774 for (int i = 0; i < N; i++) { 3775 final ResolveInfo info = resolvers.get(i); 3776 3777 if (info.serviceInfo == null) { 3778 continue; 3779 } 3780 3781 final String packageName = info.serviceInfo.packageName; 3782 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3783 if (DEBUG_INSTANT) { 3784 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3785 + " pkg: " + packageName + ", info:" + info); 3786 } 3787 continue; 3788 } 3789 3790 if (DEBUG_INSTANT) { 3791 Slog.v(TAG, "Ephemeral resolver found;" 3792 + " pkg: " + packageName + ", info:" + info); 3793 } 3794 return new Pair<>(new ComponentName(packageName, info.serviceInfo.name), actionName); 3795 } 3796 if (DEBUG_INSTANT) { 3797 Slog.v(TAG, "Ephemeral resolver NOT found"); 3798 } 3799 return null; 3800 } 3801 3802 @GuardedBy("mPackages") 3803 private @Nullable ActivityInfo getInstantAppInstallerLPr() { 3804 String[] orderedActions = Build.IS_ENG 3805 ? new String[]{ 3806 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE + "_TEST", 3807 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE} 3808 : new String[]{ 3809 Intent.ACTION_INSTALL_INSTANT_APP_PACKAGE}; 3810 3811 final int resolveFlags = 3812 MATCH_DIRECT_BOOT_AWARE 3813 | MATCH_DIRECT_BOOT_UNAWARE 3814 | Intent.FLAG_IGNORE_EPHEMERAL 3815 | (!Build.IS_ENG ? MATCH_SYSTEM_ONLY : 0); 3816 final Intent intent = new Intent(); 3817 intent.addCategory(Intent.CATEGORY_DEFAULT); 3818 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3819 List<ResolveInfo> matches = null; 3820 for (String action : orderedActions) { 3821 intent.setAction(action); 3822 matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3823 resolveFlags, UserHandle.USER_SYSTEM); 3824 if (matches.isEmpty()) { 3825 if (DEBUG_INSTANT) { 3826 Slog.d(TAG, "Instant App installer not found with " + action); 3827 } 3828 } else { 3829 break; 3830 } 3831 } 3832 Iterator<ResolveInfo> iter = matches.iterator(); 3833 while (iter.hasNext()) { 3834 final ResolveInfo rInfo = iter.next(); 3835 final PackageSetting ps = mSettings.mPackages.get(rInfo.activityInfo.packageName); 3836 if (ps != null) { 3837 final PermissionsState permissionsState = ps.getPermissionsState(); 3838 if (permissionsState.hasPermission(Manifest.permission.INSTALL_PACKAGES, 0) 3839 || Build.IS_ENG) { 3840 continue; 3841 } 3842 } 3843 iter.remove(); 3844 } 3845 if (matches.size() == 0) { 3846 return null; 3847 } else if (matches.size() == 1) { 3848 return (ActivityInfo) matches.get(0).getComponentInfo(); 3849 } else { 3850 throw new RuntimeException( 3851 "There must be at most one ephemeral installer; found " + matches); 3852 } 3853 } 3854 3855 private @Nullable ComponentName getInstantAppResolverSettingsLPr( 3856 @NonNull ComponentName resolver) { 3857 final Intent intent = new Intent(Intent.ACTION_INSTANT_APP_RESOLVER_SETTINGS) 3858 .addCategory(Intent.CATEGORY_DEFAULT) 3859 .setPackage(resolver.getPackageName()); 3860 final int resolveFlags = MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3861 List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, resolveFlags, 3862 UserHandle.USER_SYSTEM); 3863 if (matches.isEmpty()) { 3864 return null; 3865 } 3866 return matches.get(0).getComponentInfo().getComponentName(); 3867 } 3868 3869 @GuardedBy("mPackages") 3870 private void primeDomainVerificationsLPw(int userId) { 3871 if (DEBUG_DOMAIN_VERIFICATION) { 3872 Slog.d(TAG, "Priming domain verifications in user " + userId); 3873 } 3874 3875 SystemConfig systemConfig = SystemConfig.getInstance(); 3876 ArraySet<String> packages = systemConfig.getLinkedApps(); 3877 3878 for (String packageName : packages) { 3879 PackageParser.Package pkg = mPackages.get(packageName); 3880 if (pkg != null) { 3881 if (!pkg.isSystem()) { 3882 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3883 continue; 3884 } 3885 3886 ArraySet<String> domains = null; 3887 for (PackageParser.Activity a : pkg.activities) { 3888 for (ActivityIntentInfo filter : a.intents) { 3889 if (hasValidDomains(filter)) { 3890 if (domains == null) { 3891 domains = new ArraySet<>(); 3892 } 3893 domains.addAll(filter.getHostsList()); 3894 } 3895 } 3896 } 3897 3898 if (domains != null && domains.size() > 0) { 3899 if (DEBUG_DOMAIN_VERIFICATION) { 3900 Slog.v(TAG, " + " + packageName); 3901 } 3902 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3903 // state w.r.t. the formal app-linkage "no verification attempted" state; 3904 // and then 'always' in the per-user state actually used for intent resolution. 3905 final IntentFilterVerificationInfo ivi; 3906 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, domains); 3907 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3908 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3909 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3910 } else { 3911 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3912 + "' does not handle web links"); 3913 } 3914 } else { 3915 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3916 } 3917 } 3918 3919 scheduleWritePackageRestrictionsLocked(userId); 3920 scheduleWriteSettingsLocked(); 3921 } 3922 3923 private boolean packageIsBrowser(String packageName, int userId) { 3924 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3925 PackageManager.MATCH_ALL, userId); 3926 final int N = list.size(); 3927 for (int i = 0; i < N; i++) { 3928 ResolveInfo info = list.get(i); 3929 if (info.priority >= 0 && packageName.equals(info.activityInfo.packageName)) { 3930 return true; 3931 } 3932 } 3933 return false; 3934 } 3935 3936 @Override 3937 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3938 throws RemoteException { 3939 try { 3940 return super.onTransact(code, data, reply, flags); 3941 } catch (RuntimeException e) { 3942 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3943 Slog.wtf(TAG, "Package Manager Crash", e); 3944 } 3945 throw e; 3946 } 3947 } 3948 3949 /** 3950 * Returns whether or not a full application can see an instant application. 3951 * <p> 3952 * Currently, there are four cases in which this can occur: 3953 * <ol> 3954 * <li>The calling application is a "special" process. Special processes 3955 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 3956 * <li>The calling application has the permission 3957 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 3958 * <li>The calling application is the default launcher on the 3959 * system partition.</li> 3960 * <li>The calling application is the default app prediction service.</li> 3961 * </ol> 3962 */ 3963 private boolean canViewInstantApps(int callingUid, int userId) { 3964 if (callingUid < Process.FIRST_APPLICATION_UID) { 3965 return true; 3966 } 3967 if (mContext.checkCallingOrSelfPermission( 3968 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 3969 return true; 3970 } 3971 if (mContext.checkCallingOrSelfPermission( 3972 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 3973 final ComponentName homeComponent = getDefaultHomeActivity(userId); 3974 if (homeComponent != null 3975 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 3976 return true; 3977 } 3978 // TODO(b/122900055) Change/Remove this and replace with new permission role. 3979 if (mAppPredictionServicePackage != null 3980 && isCallerSameApp(mAppPredictionServicePackage, callingUid)) { 3981 return true; 3982 } 3983 } 3984 return false; 3985 } 3986 3987 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3988 if (!sUserManager.exists(userId)) return null; 3989 if (ps == null) { 3990 return null; 3991 } 3992 final int callingUid = Binder.getCallingUid(); 3993 // Filter out ephemeral app metadata: 3994 // * The system/shell/root can see metadata for any app 3995 // * An installed app can see metadata for 1) other installed apps 3996 // and 2) ephemeral apps that have explicitly interacted with it 3997 // * Ephemeral apps can only see their own data and exposed installed apps 3998 // * Holding a signature permission allows seeing instant apps 3999 if (filterAppAccessLPr(ps, callingUid, userId)) { 4000 return null; 4001 } 4002 4003 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 4004 && ps.isSystem()) { 4005 flags |= MATCH_ANY_USER; 4006 } 4007 4008 final PackageUserState state = ps.readUserState(userId); 4009 PackageParser.Package p = ps.pkg; 4010 if (p != null) { 4011 final PermissionsState permissionsState = ps.getPermissionsState(); 4012 4013 // Compute GIDs only if requested 4014 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 4015 ? EMPTY_INT_ARRAY : permissionsState.computeGids(userId); 4016 // Compute granted permissions only if package has requested permissions 4017 final Set<String> permissions = ArrayUtils.isEmpty(p.requestedPermissions) 4018 ? Collections.emptySet() : permissionsState.getPermissions(userId); 4019 4020 PackageInfo packageInfo = PackageParser.generatePackageInfo(p, gids, flags, 4021 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 4022 4023 if (packageInfo == null) { 4024 return null; 4025 } 4026 4027 packageInfo.packageName = packageInfo.applicationInfo.packageName = 4028 resolveExternalPackageNameLPr(p); 4029 4030 return packageInfo; 4031 } else if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 && state.isAvailable(flags)) { 4032 PackageInfo pi = new PackageInfo(); 4033 pi.packageName = ps.name; 4034 pi.setLongVersionCode(ps.versionCode); 4035 pi.sharedUserId = (ps.sharedUser != null) ? ps.sharedUser.name : null; 4036 pi.firstInstallTime = ps.firstInstallTime; 4037 pi.lastUpdateTime = ps.lastUpdateTime; 4038 4039 ApplicationInfo ai = new ApplicationInfo(); 4040 ai.packageName = ps.name; 4041 ai.uid = UserHandle.getUid(userId, ps.appId); 4042 ai.primaryCpuAbi = ps.primaryCpuAbiString; 4043 ai.secondaryCpuAbi = ps.secondaryCpuAbiString; 4044 ai.setVersionCode(ps.versionCode); 4045 ai.flags = ps.pkgFlags; 4046 ai.privateFlags = ps.pkgPrivateFlags; 4047 pi.applicationInfo = PackageParser.generateApplicationInfo(ai, flags, state, userId); 4048 4049 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "ps.pkg is n/a for [" 4050 + ps.name + "]. Provides a minimum info."); 4051 return pi; 4052 } else { 4053 return null; 4054 } 4055 } 4056 4057 @Override 4058 public void checkPackageStartable(String packageName, int userId) { 4059 final int callingUid = Binder.getCallingUid(); 4060 if (getInstantAppPackageName(callingUid) != null) { 4061 throw new SecurityException("Instant applications don't have access to this method"); 4062 } 4063 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 4064 synchronized (mPackages) { 4065 final PackageSetting ps = mSettings.mPackages.get(packageName); 4066 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 4067 throw new SecurityException("Package " + packageName + " was not found!"); 4068 } 4069 4070 if (!ps.getInstalled(userId)) { 4071 throw new SecurityException( 4072 "Package " + packageName + " was not installed for user " + userId + "!"); 4073 } 4074 4075 if (mSafeMode && !ps.isSystem()) { 4076 throw new SecurityException("Package " + packageName + " not a system app!"); 4077 } 4078 4079 if (mFrozenPackages.contains(packageName)) { 4080 throw new SecurityException("Package " + packageName + " is currently frozen!"); 4081 } 4082 4083 if (!userKeyUnlocked && !ps.pkg.applicationInfo.isEncryptionAware()) { 4084 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 4085 } 4086 } 4087 } 4088 4089 @Override 4090 public boolean isPackageAvailable(String packageName, int userId) { 4091 if (!sUserManager.exists(userId)) return false; 4092 final int callingUid = Binder.getCallingUid(); 4093 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4094 false /*requireFullPermission*/, false /*checkShell*/, "is package available"); 4095 synchronized (mPackages) { 4096 PackageParser.Package p = mPackages.get(packageName); 4097 if (p != null) { 4098 final PackageSetting ps = (PackageSetting) p.mExtras; 4099 if (filterAppAccessLPr(ps, callingUid, userId)) { 4100 return false; 4101 } 4102 if (ps != null) { 4103 final PackageUserState state = ps.readUserState(userId); 4104 if (state != null) { 4105 return PackageParser.isAvailable(state); 4106 } 4107 } 4108 } 4109 } 4110 return false; 4111 } 4112 4113 @Override 4114 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 4115 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 4116 flags, Binder.getCallingUid(), userId); 4117 } 4118 4119 @Override 4120 public PackageInfo getPackageInfoVersioned(VersionedPackage versionedPackage, 4121 int flags, int userId) { 4122 return getPackageInfoInternal(versionedPackage.getPackageName(), 4123 versionedPackage.getLongVersionCode(), flags, Binder.getCallingUid(), userId); 4124 } 4125 4126 /** 4127 * Important: The provided filterCallingUid is used exclusively to filter out packages 4128 * that can be seen based on user state. It's typically the original caller uid prior 4129 * to clearing. Because it can only be provided by trusted code, it's value can be 4130 * trusted and will be used as-is; unlike userId which will be validated by this method. 4131 */ 4132 private PackageInfo getPackageInfoInternal(String packageName, long versionCode, 4133 int flags, int filterCallingUid, int userId) { 4134 if (!sUserManager.exists(userId)) return null; 4135 flags = updateFlagsForPackage(flags, userId, packageName); 4136 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4137 false /* requireFullPermission */, false /* checkShell */, "get package info"); 4138 4139 // reader 4140 synchronized (mPackages) { 4141 // Normalize package name to handle renamed packages and static libs 4142 packageName = resolveInternalPackageNameLPr(packageName, versionCode); 4143 4144 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 4145 if (matchFactoryOnly) { 4146 // Instant app filtering for APEX modules is ignored 4147 if ((flags & MATCH_APEX) != 0) { 4148 return mApexManager.getPackageInfo(packageName, 4149 ApexManager.MATCH_FACTORY_PACKAGE); 4150 } 4151 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 4152 if (ps != null) { 4153 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4154 return null; 4155 } 4156 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4157 return null; 4158 } 4159 return generatePackageInfo(ps, flags, userId); 4160 } 4161 } 4162 4163 PackageParser.Package p = mPackages.get(packageName); 4164 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 4165 return null; 4166 } 4167 if (DEBUG_PACKAGE_INFO) 4168 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 4169 if (p != null) { 4170 final PackageSetting ps = (PackageSetting) p.mExtras; 4171 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4172 return null; 4173 } 4174 if (ps != null && filterAppAccessLPr(ps, filterCallingUid, userId)) { 4175 return null; 4176 } 4177 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 4178 } 4179 if (!matchFactoryOnly && (flags & MATCH_KNOWN_PACKAGES) != 0) { 4180 final PackageSetting ps = mSettings.mPackages.get(packageName); 4181 if (ps == null) return null; 4182 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4183 return null; 4184 } 4185 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4186 return null; 4187 } 4188 return generatePackageInfo(ps, flags, userId); 4189 } 4190 if ((flags & MATCH_APEX) != 0) { 4191 return mApexManager.getPackageInfo(packageName, ApexManager.MATCH_ACTIVE_PACKAGE); 4192 } 4193 } 4194 return null; 4195 } 4196 4197 private boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 4198 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 4199 return true; 4200 } 4201 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 4202 return true; 4203 } 4204 if (isComponentVisibleToInstantApp(component, TYPE_PROVIDER)) { 4205 return true; 4206 } 4207 return false; 4208 } 4209 4210 private boolean isComponentVisibleToInstantApp( 4211 @Nullable ComponentName component, @ComponentType int type) { 4212 if (type == TYPE_ACTIVITY) { 4213 final PackageParser.Activity activity = mComponentResolver.getActivity(component); 4214 if (activity == null) { 4215 return false; 4216 } 4217 final boolean visibleToInstantApp = 4218 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4219 final boolean explicitlyVisibleToInstantApp = 4220 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4221 return visibleToInstantApp && explicitlyVisibleToInstantApp; 4222 } else if (type == TYPE_RECEIVER) { 4223 final PackageParser.Activity activity = mComponentResolver.getReceiver(component); 4224 if (activity == null) { 4225 return false; 4226 } 4227 final boolean visibleToInstantApp = 4228 (activity.info.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 4229 final boolean explicitlyVisibleToInstantApp = 4230 (activity.info.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 4231 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 4232 } else if (type == TYPE_SERVICE) { 4233 final PackageParser.Service service = mComponentResolver.getService(component); 4234 return service != null 4235 ? (service.info.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4236 : false; 4237 } else if (type == TYPE_PROVIDER) { 4238 final PackageParser.Provider provider = mComponentResolver.getProvider(component); 4239 return provider != null 4240 ? (provider.info.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0 4241 : false; 4242 } else if (type == TYPE_UNKNOWN) { 4243 return isComponentVisibleToInstantApp(component); 4244 } 4245 return false; 4246 } 4247 4248 /** 4249 * Returns whether or not access to the application should be filtered. 4250 * <p> 4251 * Access may be limited based upon whether the calling or target applications 4252 * are instant applications. 4253 * 4254 * @see #canViewInstantApps(int, int) 4255 */ 4256 @GuardedBy("mPackages") 4257 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, 4258 @Nullable ComponentName component, @ComponentType int componentType, int userId) { 4259 // if we're in an isolated process, get the real calling UID 4260 if (Process.isIsolated(callingUid)) { 4261 callingUid = mIsolatedOwners.get(callingUid); 4262 } 4263 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4264 final boolean callerIsInstantApp = instantAppPkgName != null; 4265 if (ps == null) { 4266 if (callerIsInstantApp) { 4267 // pretend the application exists, but, needs to be filtered 4268 return true; 4269 } 4270 return false; 4271 } 4272 // if the target and caller are the same application, don't filter 4273 if (isCallerSameApp(ps.name, callingUid)) { 4274 return false; 4275 } 4276 if (callerIsInstantApp) { 4277 // both caller and target are both instant, but, different applications, filter 4278 if (ps.getInstantApp(userId)) { 4279 return true; 4280 } 4281 // request for a specific component; if it hasn't been explicitly exposed through 4282 // property or instrumentation target, filter 4283 if (component != null) { 4284 final PackageParser.Instrumentation instrumentation = 4285 mInstrumentation.get(component); 4286 if (instrumentation != null 4287 && isCallerSameApp(instrumentation.info.targetPackage, callingUid)) { 4288 return false; 4289 } 4290 return !isComponentVisibleToInstantApp(component, componentType); 4291 } 4292 // request for application; if no components have been explicitly exposed, filter 4293 return !ps.pkg.visibleToInstantApps; 4294 } 4295 if (ps.getInstantApp(userId)) { 4296 // caller can see all components of all instant applications, don't filter 4297 if (canViewInstantApps(callingUid, userId)) { 4298 return false; 4299 } 4300 // request for a specific instant application component, filter 4301 if (component != null) { 4302 return true; 4303 } 4304 // request for an instant application; if the caller hasn't been granted access, filter 4305 return !mInstantAppRegistry.isInstantAccessGranted( 4306 userId, UserHandle.getAppId(callingUid), ps.appId); 4307 } 4308 return false; 4309 } 4310 4311 /** 4312 * @see #filterAppAccessLPr(PackageSetting, int, ComponentName, int, int) 4313 */ 4314 @GuardedBy("mPackages") 4315 private boolean filterAppAccessLPr(@Nullable PackageSetting ps, int callingUid, int userId) { 4316 return filterAppAccessLPr(ps, callingUid, null, TYPE_UNKNOWN, userId); 4317 } 4318 4319 @GuardedBy("mPackages") 4320 private boolean filterSharedLibPackageLPr(@Nullable PackageSetting ps, int uid, int userId, 4321 int flags) { 4322 // Callers can access only the libs they depend on, otherwise they need to explicitly 4323 // ask for the shared libraries given the caller is allowed to access all static libs. 4324 if ((flags & PackageManager.MATCH_STATIC_SHARED_LIBRARIES) != 0) { 4325 // System/shell/root get to see all static libs 4326 final int appId = UserHandle.getAppId(uid); 4327 if (appId == Process.SYSTEM_UID || appId == Process.SHELL_UID 4328 || appId == Process.ROOT_UID) { 4329 return false; 4330 } 4331 // Installer gets to see all static libs. 4332 if (PackageManager.PERMISSION_GRANTED 4333 == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) { 4334 return false; 4335 } 4336 } 4337 4338 // No package means no static lib as it is always on internal storage 4339 if (ps == null || ps.pkg == null || !ps.pkg.applicationInfo.isStaticSharedLibrary()) { 4340 return false; 4341 } 4342 4343 final SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(ps.pkg.staticSharedLibName, 4344 ps.pkg.staticSharedLibVersion); 4345 if (libraryInfo == null) { 4346 return false; 4347 } 4348 4349 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 4350 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 4351 if (uidPackageNames == null) { 4352 return true; 4353 } 4354 4355 for (String uidPackageName : uidPackageNames) { 4356 if (ps.name.equals(uidPackageName)) { 4357 return false; 4358 } 4359 PackageSetting uidPs = mSettings.getPackageLPr(uidPackageName); 4360 if (uidPs != null) { 4361 final int index = ArrayUtils.indexOf(uidPs.usesStaticLibraries, 4362 libraryInfo.getName()); 4363 if (index < 0) { 4364 continue; 4365 } 4366 if (uidPs.pkg.usesStaticLibrariesVersions[index] == libraryInfo.getLongVersion()) { 4367 return false; 4368 } 4369 } 4370 } 4371 return true; 4372 } 4373 4374 @Override 4375 public String[] currentToCanonicalPackageNames(String[] names) { 4376 final int callingUid = Binder.getCallingUid(); 4377 if (getInstantAppPackageName(callingUid) != null) { 4378 return names; 4379 } 4380 final String[] out = new String[names.length]; 4381 // reader 4382 synchronized (mPackages) { 4383 final int callingUserId = UserHandle.getUserId(callingUid); 4384 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4385 for (int i=names.length-1; i>=0; i--) { 4386 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4387 boolean translateName = false; 4388 if (ps != null && ps.realName != null) { 4389 final boolean targetIsInstantApp = ps.getInstantApp(callingUserId); 4390 translateName = !targetIsInstantApp 4391 || canViewInstantApps 4392 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4393 UserHandle.getAppId(callingUid), ps.appId); 4394 } 4395 out[i] = translateName ? ps.realName : names[i]; 4396 } 4397 } 4398 return out; 4399 } 4400 4401 @Override 4402 public String[] canonicalToCurrentPackageNames(String[] names) { 4403 final int callingUid = Binder.getCallingUid(); 4404 if (getInstantAppPackageName(callingUid) != null) { 4405 return names; 4406 } 4407 final String[] out = new String[names.length]; 4408 // reader 4409 synchronized (mPackages) { 4410 final int callingUserId = UserHandle.getUserId(callingUid); 4411 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 4412 for (int i=names.length-1; i>=0; i--) { 4413 final String cur = mSettings.getRenamedPackageLPr(names[i]); 4414 boolean translateName = false; 4415 if (cur != null) { 4416 final PackageSetting ps = mSettings.mPackages.get(names[i]); 4417 final boolean targetIsInstantApp = 4418 ps != null && ps.getInstantApp(callingUserId); 4419 translateName = !targetIsInstantApp 4420 || canViewInstantApps 4421 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4422 UserHandle.getAppId(callingUid), ps.appId); 4423 } 4424 out[i] = translateName ? cur : names[i]; 4425 } 4426 } 4427 return out; 4428 } 4429 4430 @Override 4431 public int getPackageUid(String packageName, int flags, int userId) { 4432 if (!sUserManager.exists(userId)) return -1; 4433 final int callingUid = Binder.getCallingUid(); 4434 flags = updateFlagsForPackage(flags, userId, packageName); 4435 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4436 false /*requireFullPermission*/, false /*checkShell*/, "getPackageUid"); 4437 4438 // reader 4439 synchronized (mPackages) { 4440 final PackageParser.Package p = mPackages.get(packageName); 4441 if (p != null && p.isMatch(flags)) { 4442 PackageSetting ps = (PackageSetting) p.mExtras; 4443 if (filterAppAccessLPr(ps, callingUid, userId)) { 4444 return -1; 4445 } 4446 return UserHandle.getUid(userId, p.applicationInfo.uid); 4447 } 4448 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4449 final PackageSetting ps = mSettings.mPackages.get(packageName); 4450 if (ps != null && ps.isMatch(flags) 4451 && !filterAppAccessLPr(ps, callingUid, userId)) { 4452 return UserHandle.getUid(userId, ps.appId); 4453 } 4454 } 4455 } 4456 4457 return -1; 4458 } 4459 4460 /** 4461 * Check if any package sharing/holding a uid has a low enough target SDK. 4462 * 4463 * @param uid The uid of the packages 4464 * @param higherTargetSDK The target SDK that might be higher than the searched package 4465 * 4466 * @return {@code true} if there is a package sharing/holding the uid with 4467 * {@code package.targetSDK < higherTargetSDK} 4468 */ 4469 private boolean hasTargetSdkInUidLowerThan(int uid, int higherTargetSDK) { 4470 int userId = UserHandle.getUserId(uid); 4471 4472 synchronized (mPackages) { 4473 Object obj = mSettings.getSettingLPr(UserHandle.getAppId(uid)); 4474 if (obj == null) { 4475 return false; 4476 } 4477 4478 if (obj instanceof PackageSetting) { 4479 final PackageSetting ps = (PackageSetting) obj; 4480 4481 if (!ps.getInstalled(userId)) { 4482 return false; 4483 } 4484 4485 return ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK; 4486 } else if (obj instanceof SharedUserSetting) { 4487 final SharedUserSetting sus = (SharedUserSetting) obj; 4488 4489 final int numPkgs = sus.packages.size(); 4490 for (int i = 0; i < numPkgs; i++) { 4491 final PackageSetting ps = sus.packages.valueAt(i); 4492 4493 if (!ps.getInstalled(userId)) { 4494 continue; 4495 } 4496 4497 if (ps.pkg.applicationInfo.targetSdkVersion < higherTargetSDK) { 4498 return true; 4499 } 4500 } 4501 4502 return false; 4503 } else { 4504 return false; 4505 } 4506 } 4507 } 4508 4509 @Override 4510 public int[] getPackageGids(String packageName, int flags, int userId) { 4511 if (!sUserManager.exists(userId)) return null; 4512 final int callingUid = Binder.getCallingUid(); 4513 flags = updateFlagsForPackage(flags, userId, packageName); 4514 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 4515 false /*requireFullPermission*/, false /*checkShell*/, "getPackageGids"); 4516 4517 // reader 4518 synchronized (mPackages) { 4519 final PackageParser.Package p = mPackages.get(packageName); 4520 if (p != null && p.isMatch(flags)) { 4521 PackageSetting ps = (PackageSetting) p.mExtras; 4522 if (filterAppAccessLPr(ps, callingUid, userId)) { 4523 return null; 4524 } 4525 // TODO: Shouldn't this be checking for package installed state for userId and 4526 // return null? 4527 return ps.getPermissionsState().computeGids(userId); 4528 } 4529 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4530 final PackageSetting ps = mSettings.mPackages.get(packageName); 4531 if (ps != null && ps.isMatch(flags) 4532 && !filterAppAccessLPr(ps, callingUid, userId)) { 4533 return ps.getPermissionsState().computeGids(userId); 4534 } 4535 } 4536 } 4537 4538 return null; 4539 } 4540 4541 @Override 4542 public PermissionInfo getPermissionInfo(String name, String packageName, int flags) { 4543 return mPermissionManager.getPermissionInfo(name, packageName, flags, getCallingUid()); 4544 } 4545 4546 @Override 4547 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String groupName, 4548 int flags) { 4549 final List<PermissionInfo> permissionList = 4550 mPermissionManager.getPermissionInfoByGroup(groupName, flags, getCallingUid()); 4551 return (permissionList == null) ? null : new ParceledListSlice<>(permissionList); 4552 } 4553 4554 @Override 4555 public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags) { 4556 return mPermissionManager.getPermissionGroupInfo(groupName, flags, getCallingUid()); 4557 } 4558 4559 @Override 4560 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 4561 final List<PermissionGroupInfo> permissionList = 4562 mPermissionManager.getAllPermissionGroups(flags, getCallingUid()); 4563 return (permissionList == null) 4564 ? ParceledListSlice.emptyList() : new ParceledListSlice<>(permissionList); 4565 } 4566 4567 @GuardedBy("mPackages") 4568 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 4569 int filterCallingUid, int userId) { 4570 if (!sUserManager.exists(userId)) return null; 4571 PackageSetting ps = mSettings.mPackages.get(packageName); 4572 if (ps != null) { 4573 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4574 return null; 4575 } 4576 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4577 return null; 4578 } 4579 if (ps.pkg == null) { 4580 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 4581 if (pInfo != null) { 4582 return pInfo.applicationInfo; 4583 } 4584 return null; 4585 } 4586 ApplicationInfo ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 4587 ps.readUserState(userId), userId); 4588 if (ai != null) { 4589 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 4590 } 4591 return ai; 4592 } 4593 return null; 4594 } 4595 4596 @Override 4597 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 4598 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 4599 } 4600 4601 /** 4602 * Important: The provided filterCallingUid is used exclusively to filter out applications 4603 * that can be seen based on user state. It's typically the original caller uid prior 4604 * to clearing. Because it can only be provided by trusted code, it's value can be 4605 * trusted and will be used as-is; unlike userId which will be validated by this method. 4606 */ 4607 private ApplicationInfo getApplicationInfoInternal(String packageName, int flags, 4608 int filterCallingUid, int userId) { 4609 if (!sUserManager.exists(userId)) return null; 4610 flags = updateFlagsForApplication(flags, userId, packageName); 4611 4612 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 4613 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 4614 false /* requireFullPermission */, false /* checkShell */, 4615 "get application info"); 4616 } 4617 4618 // writer 4619 synchronized (mPackages) { 4620 // Normalize package name to handle renamed packages and static libs 4621 packageName = resolveInternalPackageNameLPr(packageName, 4622 PackageManager.VERSION_CODE_HIGHEST); 4623 4624 PackageParser.Package p = mPackages.get(packageName); 4625 if (DEBUG_PACKAGE_INFO) Log.v( 4626 TAG, "getApplicationInfo " + packageName 4627 + ": " + p); 4628 if (p != null) { 4629 PackageSetting ps = mSettings.mPackages.get(packageName); 4630 if (ps == null) return null; 4631 if (filterSharedLibPackageLPr(ps, filterCallingUid, userId, flags)) { 4632 return null; 4633 } 4634 if (filterAppAccessLPr(ps, filterCallingUid, userId)) { 4635 return null; 4636 } 4637 // Note: isEnabledLP() does not apply here - always return info 4638 ApplicationInfo ai = PackageParser.generateApplicationInfo( 4639 p, flags, ps.readUserState(userId), userId); 4640 if (ai != null) { 4641 ai.packageName = resolveExternalPackageNameLPr(p); 4642 } 4643 return ai; 4644 } 4645 if ("android".equals(packageName)||"system".equals(packageName)) { 4646 return mAndroidApplication; 4647 } 4648 if ((flags & MATCH_KNOWN_PACKAGES) != 0) { 4649 // Already generates the external package name 4650 return generateApplicationInfoFromSettingsLPw(packageName, 4651 flags, filterCallingUid, userId); 4652 } 4653 } 4654 return null; 4655 } 4656 4657 @GuardedBy("mPackages") 4658 private String normalizePackageNameLPr(String packageName) { 4659 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 4660 return normalizedPackageName != null ? normalizedPackageName : packageName; 4661 } 4662 4663 @Override 4664 public void deletePreloadsFileCache() { 4665 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.CLEAR_APP_CACHE, 4666 "deletePreloadsFileCache"); 4667 File dir = Environment.getDataPreloadsFileCacheDirectory(); 4668 Slog.i(TAG, "Deleting preloaded file cache " + dir); 4669 FileUtils.deleteContents(dir); 4670 } 4671 4672 @Override 4673 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 4674 final int storageFlags, final IPackageDataObserver observer) { 4675 mContext.enforceCallingOrSelfPermission( 4676 android.Manifest.permission.CLEAR_APP_CACHE, null); 4677 mHandler.post(() -> { 4678 boolean success = false; 4679 try { 4680 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4681 success = true; 4682 } catch (IOException e) { 4683 Slog.w(TAG, e); 4684 } 4685 if (observer != null) { 4686 try { 4687 observer.onRemoveCompleted(null, success); 4688 } catch (RemoteException e) { 4689 Slog.w(TAG, e); 4690 } 4691 } 4692 }); 4693 } 4694 4695 @Override 4696 public void freeStorage(final String volumeUuid, final long freeStorageSize, 4697 final int storageFlags, final IntentSender pi) { 4698 mContext.enforceCallingOrSelfPermission( 4699 android.Manifest.permission.CLEAR_APP_CACHE, TAG); 4700 mHandler.post(() -> { 4701 boolean success = false; 4702 try { 4703 freeStorage(volumeUuid, freeStorageSize, storageFlags); 4704 success = true; 4705 } catch (IOException e) { 4706 Slog.w(TAG, e); 4707 } 4708 if (pi != null) { 4709 try { 4710 pi.sendIntent(null, success ? 1 : 0, null, null, null); 4711 } catch (SendIntentException e) { 4712 Slog.w(TAG, e); 4713 } 4714 } 4715 }); 4716 } 4717 4718 /** 4719 * Blocking call to clear various types of cached data across the system 4720 * until the requested bytes are available. 4721 */ 4722 public void freeStorage(String volumeUuid, long bytes, int storageFlags) throws IOException { 4723 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4724 final File file = storage.findPathForUuid(volumeUuid); 4725 if (file.getUsableSpace() >= bytes) return; 4726 4727 if (ENABLE_FREE_CACHE_V2) { 4728 final boolean internalVolume = Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, 4729 volumeUuid); 4730 final boolean aggressive = (storageFlags 4731 & StorageManager.FLAG_ALLOCATE_AGGRESSIVE) != 0; 4732 final long reservedBytes = storage.getStorageCacheBytes(file, storageFlags); 4733 4734 // 1. Pre-flight to determine if we have any chance to succeed 4735 // 2. Consider preloaded data (after 1w honeymoon, unless aggressive) 4736 if (internalVolume && (aggressive || SystemProperties 4737 .getBoolean("persist.sys.preloads.file_cache_expired", false))) { 4738 deletePreloadsFileCache(); 4739 if (file.getUsableSpace() >= bytes) return; 4740 } 4741 4742 // 3. Consider parsed APK data (aggressive only) 4743 if (internalVolume && aggressive) { 4744 FileUtils.deleteContents(mCacheDir); 4745 if (file.getUsableSpace() >= bytes) return; 4746 } 4747 4748 // 4. Consider cached app data (above quotas) 4749 try { 4750 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4751 Installer.FLAG_FREE_CACHE_V2); 4752 } catch (InstallerException ignored) { 4753 } 4754 if (file.getUsableSpace() >= bytes) return; 4755 4756 // 5. Consider shared libraries with refcount=0 and age>min cache period 4757 if (internalVolume && pruneUnusedStaticSharedLibraries(bytes, 4758 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4759 Global.UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD, 4760 DEFAULT_UNUSED_STATIC_SHARED_LIB_MIN_CACHE_PERIOD))) { 4761 return; 4762 } 4763 4764 // 6. Consider dexopt output (aggressive only) 4765 // TODO: Implement 4766 4767 // 7. Consider installed instant apps unused longer than min cache period 4768 if (internalVolume && mInstantAppRegistry.pruneInstalledInstantApps(bytes, 4769 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4770 Global.INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4771 InstantAppRegistry.DEFAULT_INSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4772 return; 4773 } 4774 4775 // 8. Consider cached app data (below quotas) 4776 try { 4777 mInstaller.freeCache(volumeUuid, bytes, reservedBytes, 4778 Installer.FLAG_FREE_CACHE_V2 | Installer.FLAG_FREE_CACHE_V2_DEFY_QUOTA); 4779 } catch (InstallerException ignored) { 4780 } 4781 if (file.getUsableSpace() >= bytes) return; 4782 4783 // 9. Consider DropBox entries 4784 // TODO: Implement 4785 4786 // 10. Consider instant meta-data (uninstalled apps) older that min cache period 4787 if (internalVolume && mInstantAppRegistry.pruneUninstalledInstantApps(bytes, 4788 android.provider.Settings.Global.getLong(mContext.getContentResolver(), 4789 Global.UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD, 4790 InstantAppRegistry.DEFAULT_UNINSTALLED_INSTANT_APP_MIN_CACHE_PERIOD))) { 4791 return; 4792 } 4793 } else { 4794 try { 4795 mInstaller.freeCache(volumeUuid, bytes, 0, 0); 4796 } catch (InstallerException ignored) { 4797 } 4798 if (file.getUsableSpace() >= bytes) return; 4799 } 4800 4801 throw new IOException("Failed to free " + bytes + " on storage device at " + file); 4802 } 4803 4804 private boolean pruneUnusedStaticSharedLibraries(long neededSpace, long maxCachePeriod) 4805 throws IOException { 4806 final StorageManager storage = mContext.getSystemService(StorageManager.class); 4807 final File volume = storage.findPathForUuid(StorageManager.UUID_PRIVATE_INTERNAL); 4808 4809 List<VersionedPackage> packagesToDelete = null; 4810 final long now = System.currentTimeMillis(); 4811 4812 synchronized (mPackages) { 4813 final int[] allUsers = sUserManager.getUserIds(); 4814 final int libCount = mSharedLibraries.size(); 4815 for (int i = 0; i < libCount; i++) { 4816 final LongSparseArray<SharedLibraryInfo> versionedLib 4817 = mSharedLibraries.valueAt(i); 4818 if (versionedLib == null) { 4819 continue; 4820 } 4821 final int versionCount = versionedLib.size(); 4822 for (int j = 0; j < versionCount; j++) { 4823 SharedLibraryInfo libInfo = versionedLib.valueAt(j); 4824 // Skip packages that are not static shared libs. 4825 if (!libInfo.isStatic()) { 4826 break; 4827 } 4828 // Important: We skip static shared libs used for some user since 4829 // in such a case we need to keep the APK on the device. The check for 4830 // a lib being used for any user is performed by the uninstall call. 4831 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 4832 // Resolve the package name - we use synthetic package names internally 4833 final String internalPackageName = resolveInternalPackageNameLPr( 4834 declaringPackage.getPackageName(), 4835 declaringPackage.getLongVersionCode()); 4836 final PackageSetting ps = mSettings.getPackageLPr(internalPackageName); 4837 // Skip unused static shared libs cached less than the min period 4838 // to prevent pruning a lib needed by a subsequently installed package. 4839 if (ps == null || now - ps.lastUpdateTime < maxCachePeriod) { 4840 continue; 4841 } 4842 4843 if (ps.pkg.isSystem()) { 4844 continue; 4845 } 4846 4847 if (packagesToDelete == null) { 4848 packagesToDelete = new ArrayList<>(); 4849 } 4850 packagesToDelete.add(new VersionedPackage(internalPackageName, 4851 declaringPackage.getLongVersionCode())); 4852 } 4853 } 4854 } 4855 4856 if (packagesToDelete != null) { 4857 final int packageCount = packagesToDelete.size(); 4858 for (int i = 0; i < packageCount; i++) { 4859 final VersionedPackage pkgToDelete = packagesToDelete.get(i); 4860 // Delete the package synchronously (will fail of the lib used for any user). 4861 if (deletePackageX(pkgToDelete.getPackageName(), pkgToDelete.getLongVersionCode(), 4862 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS) 4863 == PackageManager.DELETE_SUCCEEDED) { 4864 if (volume.getUsableSpace() >= neededSpace) { 4865 return true; 4866 } 4867 } 4868 } 4869 } 4870 4871 return false; 4872 } 4873 4874 /** 4875 * Update given flags based on encryption status of current user. 4876 */ 4877 private int updateFlags(int flags, int userId) { 4878 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 4879 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 4880 // Caller expressed an explicit opinion about what encryption 4881 // aware/unaware components they want to see, so fall through and 4882 // give them what they want 4883 } else { 4884 // Caller expressed no opinion, so match based on user state 4885 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 4886 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 4887 } else { 4888 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 4889 } 4890 } 4891 return flags; 4892 } 4893 4894 private UserManagerInternal getUserManagerInternal() { 4895 if (mUserManagerInternal == null) { 4896 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 4897 } 4898 return mUserManagerInternal; 4899 } 4900 4901 private ActivityManagerInternal getActivityManagerInternal() { 4902 if (mActivityManagerInternal == null) { 4903 mActivityManagerInternal = LocalServices.getService(ActivityManagerInternal.class); 4904 } 4905 return mActivityManagerInternal; 4906 } 4907 4908 private ActivityTaskManagerInternal getActivityTaskManagerInternal() { 4909 if (mActivityTaskManagerInternal == null) { 4910 mActivityTaskManagerInternal = 4911 LocalServices.getService(ActivityTaskManagerInternal.class); 4912 } 4913 return mActivityTaskManagerInternal; 4914 } 4915 4916 private DeviceIdleController.LocalService getDeviceIdleController() { 4917 if (mDeviceIdleController == null) { 4918 mDeviceIdleController = 4919 LocalServices.getService(DeviceIdleController.LocalService.class); 4920 } 4921 return mDeviceIdleController; 4922 } 4923 4924 private StorageManagerInternal getStorageManagerInternal() { 4925 if (mStorageManagerInternal == null) { 4926 mStorageManagerInternal = LocalServices.getService(StorageManagerInternal.class); 4927 } 4928 return mStorageManagerInternal; 4929 } 4930 4931 /** 4932 * Update given flags when being used to request {@link PackageInfo}. 4933 */ 4934 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 4935 final boolean isCallerSystemUser = UserHandle.getCallingUserId() == UserHandle.USER_SYSTEM; 4936 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 4937 // require the permission to be held; the calling uid and given user id referring 4938 // to the same user is not sufficient 4939 mPermissionManager.enforceCrossUserPermission( 4940 Binder.getCallingUid(), userId, false, false, 4941 !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId), 4942 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission at " 4943 + Debug.getCallers(5)); 4944 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 && isCallerSystemUser 4945 && sUserManager.hasManagedProfile(UserHandle.USER_SYSTEM)) { 4946 // If the caller wants all packages and has a restricted profile associated with it, 4947 // then match all users. This is to make sure that launchers that need to access work 4948 // profile apps don't start breaking. TODO: Remove this hack when launchers stop using 4949 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 4950 flags |= PackageManager.MATCH_ANY_USER; 4951 } 4952 return updateFlags(flags, userId); 4953 } 4954 4955 /** 4956 * Update given flags when being used to request {@link ApplicationInfo}. 4957 */ 4958 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 4959 return updateFlagsForPackage(flags, userId, cookie); 4960 } 4961 4962 /** 4963 * Update given flags when being used to request {@link ComponentInfo}. 4964 */ 4965 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 4966 return updateFlags(flags, userId); 4967 } 4968 4969 /** 4970 * Update given intent when being used to request {@link ResolveInfo}. 4971 */ 4972 private Intent updateIntentForResolve(Intent intent) { 4973 if (intent.getSelector() != null) { 4974 intent = intent.getSelector(); 4975 } 4976 if (DEBUG_PREFERRED) { 4977 intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 4978 } 4979 return intent; 4980 } 4981 4982 /** 4983 * Update given flags when being used to request {@link ResolveInfo}. 4984 * <p>Instant apps are resolved specially, depending upon context. Minimally, 4985 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 4986 * flag set. However, this flag is only honoured in three circumstances: 4987 * <ul> 4988 * <li>when called from a system process</li> 4989 * <li>when the caller holds the permission {@code android.permission.ACCESS_INSTANT_APPS}</li> 4990 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 4991 * action and a {@code android.intent.category.BROWSABLE} category</li> 4992 * </ul> 4993 */ 4994 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid) { 4995 return updateFlagsForResolve(flags, userId, intent, callingUid, 4996 false /*wantInstantApps*/, false /*onlyExposedExplicitly*/); 4997 } 4998 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 4999 boolean wantInstantApps) { 5000 return updateFlagsForResolve(flags, userId, intent, callingUid, 5001 wantInstantApps, false /*onlyExposedExplicitly*/); 5002 } 5003 int updateFlagsForResolve(int flags, int userId, Intent intent, int callingUid, 5004 boolean wantInstantApps, boolean onlyExposedExplicitly) { 5005 // Safe mode means we shouldn't match any third-party components 5006 if (mSafeMode) { 5007 flags |= PackageManager.MATCH_SYSTEM_ONLY; 5008 } 5009 if (getInstantAppPackageName(callingUid) != null) { 5010 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 5011 if (onlyExposedExplicitly) { 5012 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 5013 } 5014 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 5015 flags |= PackageManager.MATCH_INSTANT; 5016 } else { 5017 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 5018 final boolean allowMatchInstant = wantInstantApps 5019 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 5020 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 5021 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 5022 if (!allowMatchInstant) { 5023 flags &= ~PackageManager.MATCH_INSTANT; 5024 } 5025 } 5026 return updateFlagsForComponent(flags, userId, intent /*cookie*/); 5027 } 5028 5029 @Override 5030 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 5031 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 5032 } 5033 5034 /** 5035 * Important: The provided filterCallingUid is used exclusively to filter out activities 5036 * that can be seen based on user state. It's typically the original caller uid prior 5037 * to clearing. Because it can only be provided by trusted code, it's value can be 5038 * trusted and will be used as-is; unlike userId which will be validated by this method. 5039 */ 5040 private ActivityInfo getActivityInfoInternal(ComponentName component, int flags, 5041 int filterCallingUid, int userId) { 5042 if (!sUserManager.exists(userId)) return null; 5043 flags = updateFlagsForComponent(flags, userId, component); 5044 5045 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 5046 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 5047 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 5048 } 5049 5050 synchronized (mPackages) { 5051 PackageParser.Activity a = mComponentResolver.getActivity(component); 5052 5053 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 5054 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 5055 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5056 if (ps == null) return null; 5057 if (filterAppAccessLPr(ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 5058 return null; 5059 } 5060 return PackageParser.generateActivityInfo( 5061 a, flags, ps.readUserState(userId), userId); 5062 } 5063 if (mResolveComponentName.equals(component)) { 5064 return PackageParser.generateActivityInfo( 5065 mResolveActivity, flags, new PackageUserState(), userId); 5066 } 5067 } 5068 return null; 5069 } 5070 5071 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 5072 if (!getActivityTaskManagerInternal().isCallerRecents(callingUid)) { 5073 return false; 5074 } 5075 final long token = Binder.clearCallingIdentity(); 5076 try { 5077 final int callingUserId = UserHandle.getUserId(callingUid); 5078 if (ActivityManager.getCurrentUser() != callingUserId) { 5079 return false; 5080 } 5081 return sUserManager.isSameProfileGroup(callingUserId, targetUserId); 5082 } finally { 5083 Binder.restoreCallingIdentity(token); 5084 } 5085 } 5086 5087 @Override 5088 public boolean activitySupportsIntent(ComponentName component, Intent intent, 5089 String resolvedType) { 5090 synchronized (mPackages) { 5091 if (component.equals(mResolveComponentName)) { 5092 // The resolver supports EVERYTHING! 5093 return true; 5094 } 5095 final int callingUid = Binder.getCallingUid(); 5096 final int callingUserId = UserHandle.getUserId(callingUid); 5097 PackageParser.Activity a = mComponentResolver.getActivity(component); 5098 if (a == null) { 5099 return false; 5100 } 5101 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5102 if (ps == null) { 5103 return false; 5104 } 5105 if (filterAppAccessLPr(ps, callingUid, component, TYPE_ACTIVITY, callingUserId)) { 5106 return false; 5107 } 5108 for (int i=0; i<a.intents.size(); i++) { 5109 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 5110 intent.getData(), intent.getCategories(), TAG) >= 0) { 5111 return true; 5112 } 5113 } 5114 return false; 5115 } 5116 } 5117 5118 @Override 5119 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 5120 if (!sUserManager.exists(userId)) return null; 5121 final int callingUid = Binder.getCallingUid(); 5122 flags = updateFlagsForComponent(flags, userId, component); 5123 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5124 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 5125 synchronized (mPackages) { 5126 PackageParser.Activity a = mComponentResolver.getReceiver(component); 5127 if (DEBUG_PACKAGE_INFO) Log.v( 5128 TAG, "getReceiverInfo " + component + ": " + a); 5129 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 5130 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5131 if (ps == null) return null; 5132 if (filterAppAccessLPr(ps, callingUid, component, TYPE_RECEIVER, userId)) { 5133 return null; 5134 } 5135 return PackageParser.generateActivityInfo( 5136 a, flags, ps.readUserState(userId), userId); 5137 } 5138 } 5139 return null; 5140 } 5141 5142 @Override 5143 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(String packageName, 5144 int flags, int userId) { 5145 if (!sUserManager.exists(userId)) return null; 5146 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 5147 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5148 return null; 5149 } 5150 5151 flags = updateFlagsForPackage(flags, userId, null); 5152 5153 final boolean canSeeStaticLibraries = 5154 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 5155 == PERMISSION_GRANTED 5156 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 5157 == PERMISSION_GRANTED 5158 || canRequestPackageInstallsInternal(packageName, 5159 PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId, 5160 false /* throwIfPermNotDeclared*/) 5161 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 5162 == PERMISSION_GRANTED 5163 || mContext.checkCallingOrSelfPermission( 5164 Manifest.permission.ACCESS_SHARED_LIBRARIES) == PERMISSION_GRANTED; 5165 5166 synchronized (mPackages) { 5167 List<SharedLibraryInfo> result = null; 5168 5169 final int libCount = mSharedLibraries.size(); 5170 for (int i = 0; i < libCount; i++) { 5171 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i); 5172 if (versionedLib == null) { 5173 continue; 5174 } 5175 5176 final int versionCount = versionedLib.size(); 5177 for (int j = 0; j < versionCount; j++) { 5178 SharedLibraryInfo libInfo = versionedLib.valueAt(j); 5179 if (!canSeeStaticLibraries && libInfo.isStatic()) { 5180 break; 5181 } 5182 final long identity = Binder.clearCallingIdentity(); 5183 try { 5184 PackageInfo packageInfo = getPackageInfoVersioned( 5185 libInfo.getDeclaringPackage(), flags 5186 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5187 if (packageInfo == null) { 5188 continue; 5189 } 5190 } finally { 5191 Binder.restoreCallingIdentity(identity); 5192 } 5193 5194 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getPath(), 5195 libInfo.getPackageName(), libInfo.getAllCodePaths(), 5196 libInfo.getName(), libInfo.getLongVersion(), 5197 libInfo.getType(), libInfo.getDeclaringPackage(), 5198 getPackagesUsingSharedLibraryLPr(libInfo, flags, userId), 5199 (libInfo.getDependencies() == null 5200 ? null 5201 : new ArrayList<>(libInfo.getDependencies()))); 5202 5203 if (result == null) { 5204 result = new ArrayList<>(); 5205 } 5206 result.add(resLibInfo); 5207 } 5208 } 5209 5210 return result != null ? new ParceledListSlice<>(result) : null; 5211 } 5212 } 5213 5214 @Nullable 5215 @Override 5216 public ParceledListSlice<SharedLibraryInfo> getDeclaredSharedLibraries( 5217 @NonNull String packageName, int flags, @NonNull int userId) { 5218 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES, 5219 "getDeclaredSharedLibraries"); 5220 int callingUid = Binder.getCallingUid(); 5221 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5222 true /* requireFullPermission */, false /* checkShell */, 5223 "getDeclaredSharedLibraries"); 5224 5225 Preconditions.checkNotNull(packageName, "packageName cannot be null"); 5226 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 5227 if (!sUserManager.exists(userId)) { 5228 return null; 5229 } 5230 5231 if (getInstantAppPackageName(callingUid) != null) { 5232 return null; 5233 } 5234 5235 synchronized (mPackages) { 5236 List<SharedLibraryInfo> result = null; 5237 5238 int libraryCount = mSharedLibraries.size(); 5239 for (int i = 0; i < libraryCount; i++) { 5240 LongSparseArray<SharedLibraryInfo> versionedLibrary = mSharedLibraries.valueAt(i); 5241 if (versionedLibrary == null) { 5242 continue; 5243 } 5244 5245 int versionCount = versionedLibrary.size(); 5246 for (int j = 0; j < versionCount; j++) { 5247 SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j); 5248 5249 VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage(); 5250 if (!Objects.equals(declaringPackage.getPackageName(), packageName)) { 5251 continue; 5252 } 5253 5254 long identity = Binder.clearCallingIdentity(); 5255 try { 5256 PackageInfo packageInfo = getPackageInfoVersioned(declaringPackage, flags 5257 | PackageManager.MATCH_STATIC_SHARED_LIBRARIES, userId); 5258 if (packageInfo == null) { 5259 continue; 5260 } 5261 } finally { 5262 Binder.restoreCallingIdentity(identity); 5263 } 5264 5265 SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo( 5266 libraryInfo.getPath(), libraryInfo.getPackageName(), 5267 libraryInfo.getAllCodePaths(), libraryInfo.getName(), 5268 libraryInfo.getLongVersion(), libraryInfo.getType(), 5269 libraryInfo.getDeclaringPackage(), getPackagesUsingSharedLibraryLPr( 5270 libraryInfo, flags, userId), libraryInfo.getDependencies() == null 5271 ? null : new ArrayList<>(libraryInfo.getDependencies())); 5272 5273 if (result == null) { 5274 result = new ArrayList<>(); 5275 } 5276 result.add(resultLibraryInfo); 5277 } 5278 } 5279 5280 return result != null ? new ParceledListSlice<>(result) : null; 5281 } 5282 } 5283 5284 @GuardedBy("mPackages") 5285 private List<VersionedPackage> getPackagesUsingSharedLibraryLPr( 5286 SharedLibraryInfo libInfo, int flags, int userId) { 5287 List<VersionedPackage> versionedPackages = null; 5288 final int packageCount = mSettings.mPackages.size(); 5289 for (int i = 0; i < packageCount; i++) { 5290 PackageSetting ps = mSettings.mPackages.valueAt(i); 5291 5292 if (ps == null) { 5293 continue; 5294 } 5295 5296 if (!ps.readUserState(userId).isAvailable(flags)) { 5297 continue; 5298 } 5299 5300 final String libName = libInfo.getName(); 5301 if (libInfo.isStatic()) { 5302 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 5303 if (libIdx < 0) { 5304 continue; 5305 } 5306 if (ps.usesStaticLibrariesVersions[libIdx] != libInfo.getLongVersion()) { 5307 continue; 5308 } 5309 if (versionedPackages == null) { 5310 versionedPackages = new ArrayList<>(); 5311 } 5312 // If the dependent is a static shared lib, use the public package name 5313 String dependentPackageName = ps.name; 5314 if (ps.pkg != null && ps.pkg.applicationInfo.isStaticSharedLibrary()) { 5315 dependentPackageName = ps.pkg.manifestPackageName; 5316 } 5317 versionedPackages.add(new VersionedPackage(dependentPackageName, ps.versionCode)); 5318 } else if (ps.pkg != null) { 5319 if (ArrayUtils.contains(ps.pkg.usesLibraries, libName) 5320 || ArrayUtils.contains(ps.pkg.usesOptionalLibraries, libName)) { 5321 if (versionedPackages == null) { 5322 versionedPackages = new ArrayList<>(); 5323 } 5324 versionedPackages.add(new VersionedPackage(ps.name, ps.versionCode)); 5325 } 5326 } 5327 } 5328 5329 return versionedPackages; 5330 } 5331 5332 @Override 5333 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 5334 if (!sUserManager.exists(userId)) return null; 5335 final int callingUid = Binder.getCallingUid(); 5336 flags = updateFlagsForComponent(flags, userId, component); 5337 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5338 false /* requireFullPermission */, false /* checkShell */, "get service info"); 5339 synchronized (mPackages) { 5340 PackageParser.Service s = mComponentResolver.getService(component); 5341 if (DEBUG_PACKAGE_INFO) Log.v( 5342 TAG, "getServiceInfo " + component + ": " + s); 5343 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 5344 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5345 if (ps == null) return null; 5346 if (filterAppAccessLPr(ps, callingUid, component, TYPE_SERVICE, userId)) { 5347 return null; 5348 } 5349 return PackageParser.generateServiceInfo( 5350 s, flags, ps.readUserState(userId), userId); 5351 } 5352 } 5353 return null; 5354 } 5355 5356 @Override 5357 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 5358 if (!sUserManager.exists(userId)) return null; 5359 final int callingUid = Binder.getCallingUid(); 5360 flags = updateFlagsForComponent(flags, userId, component); 5361 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 5362 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 5363 synchronized (mPackages) { 5364 PackageParser.Provider p = mComponentResolver.getProvider(component); 5365 if (DEBUG_PACKAGE_INFO) Log.v( 5366 TAG, "getProviderInfo " + component + ": " + p); 5367 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 5368 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 5369 if (ps == null) return null; 5370 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 5371 return null; 5372 } 5373 return PackageParser.generateProviderInfo( 5374 p, flags, ps.readUserState(userId), userId); 5375 } 5376 } 5377 return null; 5378 } 5379 5380 @Override 5381 public ModuleInfo getModuleInfo(String packageName, @ModuleInfoFlags int flags) { 5382 return mModuleInfoProvider.getModuleInfo(packageName, flags); 5383 } 5384 5385 @Override 5386 public List<ModuleInfo> getInstalledModules(int flags) { 5387 return mModuleInfoProvider.getInstalledModules(flags); 5388 } 5389 5390 @Override 5391 public String[] getSystemSharedLibraryNames() { 5392 // allow instant applications 5393 synchronized (mPackages) { 5394 Set<String> libs = null; 5395 final int libCount = mSharedLibraries.size(); 5396 for (int i = 0; i < libCount; i++) { 5397 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.valueAt(i); 5398 if (versionedLib == null) { 5399 continue; 5400 } 5401 final int versionCount = versionedLib.size(); 5402 for (int j = 0; j < versionCount; j++) { 5403 SharedLibraryInfo libraryInfo = versionedLib.valueAt(j); 5404 if (!libraryInfo.isStatic()) { 5405 if (libs == null) { 5406 libs = new ArraySet<>(); 5407 } 5408 libs.add(libraryInfo.getName()); 5409 break; 5410 } 5411 PackageSetting ps = mSettings.getPackageLPr(libraryInfo.getPackageName()); 5412 if (ps != null && !filterSharedLibPackageLPr(ps, Binder.getCallingUid(), 5413 UserHandle.getUserId(Binder.getCallingUid()), 5414 PackageManager.MATCH_STATIC_SHARED_LIBRARIES)) { 5415 if (libs == null) { 5416 libs = new ArraySet<>(); 5417 } 5418 libs.add(libraryInfo.getName()); 5419 break; 5420 } 5421 } 5422 } 5423 5424 if (libs != null) { 5425 String[] libsArray = new String[libs.size()]; 5426 libs.toArray(libsArray); 5427 return libsArray; 5428 } 5429 5430 return null; 5431 } 5432 } 5433 5434 @Override 5435 public @NonNull String getServicesSystemSharedLibraryPackageName() { 5436 // allow instant applications 5437 synchronized (mPackages) { 5438 return mServicesSystemSharedLibraryPackageName; 5439 } 5440 } 5441 5442 @Override 5443 public @NonNull String getSharedSystemSharedLibraryPackageName() { 5444 // allow instant applications 5445 synchronized (mPackages) { 5446 return mSharedSystemSharedLibraryPackageName; 5447 } 5448 } 5449 5450 @GuardedBy("mPackages") 5451 private void updateSequenceNumberLP(PackageSetting pkgSetting, int[] userList) { 5452 for (int i = userList.length - 1; i >= 0; --i) { 5453 final int userId = userList[i]; 5454 // don't add instant app to the list of updates 5455 if (pkgSetting.getInstantApp(userId)) { 5456 continue; 5457 } 5458 SparseArray<String> changedPackages = mChangedPackages.get(userId); 5459 if (changedPackages == null) { 5460 changedPackages = new SparseArray<>(); 5461 mChangedPackages.put(userId, changedPackages); 5462 } 5463 Map<String, Integer> sequenceNumbers = mChangedPackagesSequenceNumbers.get(userId); 5464 if (sequenceNumbers == null) { 5465 sequenceNumbers = new HashMap<>(); 5466 mChangedPackagesSequenceNumbers.put(userId, sequenceNumbers); 5467 } 5468 final Integer sequenceNumber = sequenceNumbers.get(pkgSetting.name); 5469 if (sequenceNumber != null) { 5470 changedPackages.remove(sequenceNumber); 5471 } 5472 changedPackages.put(mChangedPackagesSequenceNumber, pkgSetting.name); 5473 sequenceNumbers.put(pkgSetting.name, mChangedPackagesSequenceNumber); 5474 } 5475 mChangedPackagesSequenceNumber++; 5476 } 5477 5478 @Override 5479 public ChangedPackages getChangedPackages(int sequenceNumber, int userId) { 5480 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 5481 return null; 5482 } 5483 synchronized (mPackages) { 5484 if (sequenceNumber >= mChangedPackagesSequenceNumber) { 5485 return null; 5486 } 5487 final SparseArray<String> changedPackages = mChangedPackages.get(userId); 5488 if (changedPackages == null) { 5489 return null; 5490 } 5491 final List<String> packageNames = 5492 new ArrayList<>(mChangedPackagesSequenceNumber - sequenceNumber); 5493 for (int i = sequenceNumber; i < mChangedPackagesSequenceNumber; i++) { 5494 final String packageName = changedPackages.get(i); 5495 if (packageName != null) { 5496 packageNames.add(packageName); 5497 } 5498 } 5499 return packageNames.isEmpty() 5500 ? null : new ChangedPackages(mChangedPackagesSequenceNumber, packageNames); 5501 } 5502 } 5503 5504 @Override 5505 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 5506 // allow instant applications 5507 ArrayList<FeatureInfo> res; 5508 synchronized (mAvailableFeatures) { 5509 res = new ArrayList<>(mAvailableFeatures.size() + 1); 5510 res.addAll(mAvailableFeatures.values()); 5511 } 5512 final FeatureInfo fi = new FeatureInfo(); 5513 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 5514 FeatureInfo.GL_ES_VERSION_UNDEFINED); 5515 res.add(fi); 5516 5517 return new ParceledListSlice<>(res); 5518 } 5519 5520 @Override 5521 public boolean hasSystemFeature(String name, int version) { 5522 // allow instant applications 5523 synchronized (mAvailableFeatures) { 5524 final FeatureInfo feat = mAvailableFeatures.get(name); 5525 if (feat == null) { 5526 return false; 5527 } else { 5528 return feat.version >= version; 5529 } 5530 } 5531 } 5532 5533 @Override 5534 public int checkPermission(String permName, String pkgName, int userId) { 5535 final CheckPermissionDelegate checkPermissionDelegate; 5536 synchronized (mPackages) { 5537 if (mCheckPermissionDelegate == null) { 5538 return checkPermissionImpl(permName, pkgName, userId); 5539 } 5540 checkPermissionDelegate = mCheckPermissionDelegate; 5541 } 5542 return checkPermissionDelegate.checkPermission(permName, pkgName, userId, 5543 PackageManagerService.this::checkPermissionImpl); 5544 } 5545 5546 private int checkPermissionImpl(String permName, String pkgName, int userId) { 5547 return mPermissionManager.checkPermission(permName, pkgName, getCallingUid(), userId); 5548 } 5549 5550 @Override 5551 public int checkUidPermission(String permName, int uid) { 5552 final CheckPermissionDelegate checkPermissionDelegate; 5553 synchronized (mPackages) { 5554 if (mCheckPermissionDelegate == null) { 5555 return checkUidPermissionImpl(permName, uid); 5556 } 5557 checkPermissionDelegate = mCheckPermissionDelegate; 5558 } 5559 return checkPermissionDelegate.checkUidPermission(permName, uid, 5560 PackageManagerService.this::checkUidPermissionImpl); 5561 } 5562 5563 private int checkUidPermissionImpl(String permName, int uid) { 5564 synchronized (mPackages) { 5565 final String[] packageNames = getPackagesForUid(uid); 5566 PackageParser.Package pkg = null; 5567 final int N = packageNames == null ? 0 : packageNames.length; 5568 for (int i = 0; pkg == null && i < N; i++) { 5569 pkg = mPackages.get(packageNames[i]); 5570 } 5571 return mPermissionManager.checkUidPermission(permName, pkg, uid, getCallingUid()); 5572 } 5573 } 5574 5575 @Override 5576 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 5577 if (UserHandle.getCallingUserId() != userId) { 5578 mContext.enforceCallingPermission( 5579 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5580 "isPermissionRevokedByPolicy for user " + userId); 5581 } 5582 5583 if (checkPermission(permission, packageName, userId) 5584 == PackageManager.PERMISSION_GRANTED) { 5585 return false; 5586 } 5587 5588 final int callingUid = Binder.getCallingUid(); 5589 if (getInstantAppPackageName(callingUid) != null) { 5590 if (!isCallerSameApp(packageName, callingUid)) { 5591 return false; 5592 } 5593 } else { 5594 if (isInstantApp(packageName, userId)) { 5595 return false; 5596 } 5597 } 5598 5599 final long identity = Binder.clearCallingIdentity(); 5600 try { 5601 final int flags = getPermissionFlags(permission, packageName, userId); 5602 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 5603 } finally { 5604 Binder.restoreCallingIdentity(identity); 5605 } 5606 } 5607 5608 @Override 5609 public String getPermissionControllerPackageName() { 5610 synchronized (mPackages) { 5611 return mRequiredPermissionControllerPackage; 5612 } 5613 } 5614 5615 String getPackageInstallerPackageName() { 5616 synchronized (mPackages) { 5617 return mRequiredInstallerPackage; 5618 } 5619 } 5620 5621 private boolean addDynamicPermission(PermissionInfo info, final boolean async) { 5622 return mPermissionManager.addDynamicPermission( 5623 info, async, getCallingUid(), new PermissionCallback() { 5624 @Override 5625 public void onPermissionChanged() { 5626 if (!async) { 5627 mSettings.writeLPr(); 5628 } else { 5629 scheduleWriteSettingsLocked(); 5630 } 5631 } 5632 }); 5633 } 5634 5635 @Override 5636 public boolean addPermission(PermissionInfo info) { 5637 synchronized (mPackages) { 5638 return addDynamicPermission(info, false); 5639 } 5640 } 5641 5642 @Override 5643 public boolean addPermissionAsync(PermissionInfo info) { 5644 synchronized (mPackages) { 5645 return addDynamicPermission(info, true); 5646 } 5647 } 5648 5649 @Override 5650 public void removePermission(String permName) { 5651 mPermissionManager.removeDynamicPermission(permName, getCallingUid(), mPermissionCallback); 5652 } 5653 5654 @Override 5655 public void grantRuntimePermission(String packageName, String permName, final int userId) { 5656 boolean overridePolicy = (checkUidPermission( 5657 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid()) 5658 == PackageManager.PERMISSION_GRANTED); 5659 5660 mPermissionManager.grantRuntimePermission(permName, packageName, overridePolicy, 5661 getCallingUid(), userId, mPermissionCallback); 5662 } 5663 5664 @Override 5665 public void revokeRuntimePermission(String packageName, String permName, int userId) { 5666 boolean overridePolicy = (checkUidPermission( 5667 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, Binder.getCallingUid()) 5668 == PackageManager.PERMISSION_GRANTED); 5669 5670 mPermissionManager.revokeRuntimePermission(permName, packageName, overridePolicy, 5671 userId, mPermissionCallback); 5672 } 5673 5674 @Override 5675 public void resetRuntimePermissions() { 5676 mContext.enforceCallingOrSelfPermission( 5677 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 5678 "revokeRuntimePermission"); 5679 5680 int callingUid = Binder.getCallingUid(); 5681 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 5682 mContext.enforceCallingOrSelfPermission( 5683 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5684 "resetRuntimePermissions"); 5685 } 5686 5687 synchronized (mPackages) { 5688 mPermissionManager.updateAllPermissions( 5689 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 5690 mPermissionCallback); 5691 for (int userId : UserManagerService.getInstance().getUserIds()) { 5692 final int packageCount = mPackages.size(); 5693 for (int i = 0; i < packageCount; i++) { 5694 PackageParser.Package pkg = mPackages.valueAt(i); 5695 if (!(pkg.mExtras instanceof PackageSetting)) { 5696 continue; 5697 } 5698 PackageSetting ps = (PackageSetting) pkg.mExtras; 5699 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 5700 } 5701 } 5702 } 5703 } 5704 5705 @Override 5706 public int getPermissionFlags(String permName, String packageName, int userId) { 5707 return mPermissionManager.getPermissionFlags( 5708 permName, packageName, getCallingUid(), userId); 5709 } 5710 5711 @Override 5712 public void updatePermissionFlags(String permName, String packageName, int flagMask, 5713 int flagValues, boolean checkAdjustPolicyFlagPermission, int userId) { 5714 int callingUid = getCallingUid(); 5715 boolean overridePolicy = false; 5716 5717 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 5718 long callingIdentity = Binder.clearCallingIdentity(); 5719 try { 5720 if ((flagMask & FLAG_PERMISSION_POLICY_FIXED) != 0) { 5721 if (checkAdjustPolicyFlagPermission) { 5722 mContext.enforceCallingOrSelfPermission( 5723 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 5724 "Need " + Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY 5725 + " to change policy flags"); 5726 } else if (!hasTargetSdkInUidLowerThan(callingUid, Build.VERSION_CODES.Q)) { 5727 throw new IllegalArgumentException( 5728 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY + " needs " 5729 + " to be checked for packages targeting " 5730 + Build.VERSION_CODES.Q + " or later when changing policy " 5731 + "flags"); 5732 } 5733 5734 overridePolicy = true; 5735 } 5736 } finally { 5737 Binder.restoreCallingIdentity(callingIdentity); 5738 } 5739 } 5740 5741 mPermissionManager.updatePermissionFlags( 5742 permName, packageName, flagMask, flagValues, callingUid, userId, 5743 overridePolicy, mPermissionCallback); 5744 } 5745 5746 /** 5747 * Update the permission flags for all packages and runtime permissions of a user in order 5748 * to allow device or profile owner to remove POLICY_FIXED. 5749 */ 5750 @Override 5751 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 5752 synchronized (mPackages) { 5753 final boolean changed = mPermissionManager.updatePermissionFlagsForAllApps( 5754 flagMask, flagValues, getCallingUid(), userId, mPackages.values(), 5755 mPermissionCallback); 5756 if (changed) { 5757 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 5758 } 5759 } 5760 } 5761 5762 @Override 5763 public @Nullable List<String> getWhitelistedRestrictedPermissions(@NonNull String packageName, 5764 @PermissionWhitelistFlags int whitelistFlags, @UserIdInt int userId) { 5765 Preconditions.checkNotNull(packageName); 5766 Preconditions.checkFlagsArgument(whitelistFlags, 5767 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5768 | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM 5769 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER); 5770 Preconditions.checkArgumentNonNegative(userId, null); 5771 5772 if (UserHandle.getCallingUserId() != userId) { 5773 mContext.enforceCallingOrSelfPermission( 5774 android.Manifest.permission.INTERACT_ACROSS_USERS, 5775 "getWhitelistedRestrictedPermissions for user " + userId); 5776 } 5777 5778 final PackageParser.Package pkg; 5779 5780 synchronized (mPackages) { 5781 final PackageSetting packageSetting = mSettings.mPackages.get(packageName); 5782 if (packageSetting == null) { 5783 Slog.w(TAG, "Unknown package: " + packageName); 5784 return null; 5785 } 5786 5787 pkg = packageSetting.pkg; 5788 5789 final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission( 5790 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5791 == PackageManager.PERMISSION_GRANTED; 5792 final PackageSetting installerPackageSetting = mSettings.mPackages.get( 5793 packageSetting.installerPackageName); 5794 final boolean isCallerInstallerOnRecord = installerPackageSetting != null 5795 && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid()); 5796 5797 if ((whitelistFlags & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0 5798 && !isCallerPrivileged) { 5799 throw new SecurityException("Querying system whitelist requires " 5800 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5801 } 5802 5803 if ((whitelistFlags & (PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5804 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER)) != 0) { 5805 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 5806 throw new SecurityException("Querying upgrade or installer whitelist" 5807 + " requires being installer on record or " 5808 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5809 } 5810 } 5811 5812 if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(), 5813 UserHandle.getCallingUserId())) { 5814 return null; 5815 } 5816 } 5817 5818 final long identity = Binder.clearCallingIdentity(); 5819 try { 5820 return mPermissionManager.getWhitelistedRestrictedPermissions( 5821 pkg, whitelistFlags, userId); 5822 } finally { 5823 Binder.restoreCallingIdentity(identity); 5824 } 5825 } 5826 5827 @Override 5828 public boolean addWhitelistedRestrictedPermission(@NonNull String packageName, 5829 @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags, 5830 @UserIdInt int userId) { 5831 // Other argument checks are done in get/setWhitelistedRestrictedPermissions 5832 Preconditions.checkNotNull(permission); 5833 5834 if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) { 5835 return false; 5836 } 5837 5838 List<String> permissions = getWhitelistedRestrictedPermissions(packageName, 5839 whitelistFlags, userId); 5840 if (permissions == null) { 5841 permissions = new ArrayList<>(1); 5842 } 5843 if (permissions.indexOf(permission) < 0) { 5844 permissions.add(permission); 5845 return setWhitelistedRestrictedPermissions(packageName, permissions, 5846 whitelistFlags, userId); 5847 } 5848 return false; 5849 } 5850 5851 private boolean checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission( 5852 @NonNull String permission) { 5853 synchronized (mPackages) { 5854 final BasePermission bp = mPermissionManager.getPermissionTEMP(permission); 5855 if (bp == null) { 5856 Slog.w(TAG, "No such permissions: " + permission); 5857 return false; 5858 } 5859 if (bp.isHardOrSoftRestricted() && bp.isImmutablyRestricted() 5860 && mContext.checkCallingOrSelfPermission( 5861 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5862 != PackageManager.PERMISSION_GRANTED) { 5863 throw new SecurityException("Cannot modify whitelisting of an immutably " 5864 + "restricted permission: " + permission); 5865 } 5866 return true; 5867 } 5868 } 5869 5870 @Override 5871 public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName, 5872 @NonNull String permission, @PermissionWhitelistFlags int whitelistFlags, 5873 @UserIdInt int userId) { 5874 // Other argument checks are done in get/setWhitelistedRestrictedPermissions 5875 Preconditions.checkNotNull(permission); 5876 5877 if (!checkExistsAndEnforceCannotModifyImmutablyRestrictedPermission(permission)) { 5878 return false; 5879 } 5880 5881 final List<String> permissions = getWhitelistedRestrictedPermissions(packageName, 5882 whitelistFlags, userId); 5883 if (permissions != null && permissions.remove(permission)) { 5884 return setWhitelistedRestrictedPermissions(packageName, permissions, 5885 whitelistFlags, userId); 5886 } 5887 return false; 5888 } 5889 5890 private boolean setWhitelistedRestrictedPermissions(@NonNull String packageName, 5891 @Nullable List<String> permissions, @PermissionWhitelistFlags int whitelistFlag, 5892 @UserIdInt int userId) { 5893 Preconditions.checkNotNull(packageName); 5894 Preconditions.checkFlagsArgument(whitelistFlag, 5895 PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE 5896 | PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM 5897 | PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER); 5898 Preconditions.checkArgument(Integer.bitCount(whitelistFlag) == 1); 5899 Preconditions.checkArgumentNonNegative(userId, null); 5900 5901 if (UserHandle.getCallingUserId() != userId) { 5902 mContext.enforceCallingOrSelfPermission( 5903 Manifest.permission.INTERACT_ACROSS_USERS, 5904 "setWhitelistedRestrictedPermissions for user " + userId); 5905 } 5906 5907 final PackageParser.Package pkg; 5908 5909 synchronized (mPackages) { 5910 final PackageSetting packageSetting = mSettings.mPackages.get(packageName); 5911 if (packageSetting == null) { 5912 Slog.w(TAG, "Unknown package: " + packageName); 5913 return false; 5914 } 5915 5916 pkg = packageSetting.pkg; 5917 5918 final boolean isCallerPrivileged = mContext.checkCallingOrSelfPermission( 5919 Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS) 5920 == PackageManager.PERMISSION_GRANTED; 5921 final PackageSetting installerPackageSetting = mSettings.mPackages.get( 5922 packageSetting.installerPackageName); 5923 final boolean isCallerInstallerOnRecord = installerPackageSetting != null 5924 && UserHandle.isSameApp(installerPackageSetting.appId, Binder.getCallingUid()); 5925 5926 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_SYSTEM) != 0 5927 && !isCallerPrivileged) { 5928 throw new SecurityException("Modifying system whitelist requires " 5929 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5930 } 5931 5932 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_UPGRADE) != 0) { 5933 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 5934 throw new SecurityException("Modifying upgrade whitelist requires" 5935 + " being installer on record or " 5936 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5937 } 5938 final List<String> whitelistedPermissions = getWhitelistedRestrictedPermissions( 5939 packageName, whitelistFlag, userId); 5940 if (permissions == null || permissions.isEmpty()) { 5941 if (whitelistedPermissions == null || whitelistedPermissions.isEmpty()) { 5942 return true; 5943 } 5944 } else { 5945 // Only the system can add and remove while the installer can only remove. 5946 final int permissionCount = permissions.size(); 5947 for (int i = 0; i < permissionCount; i++) { 5948 if ((whitelistedPermissions == null 5949 || !whitelistedPermissions.contains(permissions.get(i))) 5950 && !isCallerPrivileged) { 5951 throw new SecurityException("Adding to upgrade whitelist requires" 5952 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5953 } 5954 } 5955 } 5956 } 5957 5958 if ((whitelistFlag & PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER) != 0) { 5959 if (!isCallerPrivileged && !isCallerInstallerOnRecord) { 5960 throw new SecurityException("Modifying installer whitelist requires" 5961 + " being installer on record or " 5962 + Manifest.permission.WHITELIST_RESTRICTED_PERMISSIONS); 5963 } 5964 } 5965 5966 if (filterAppAccessLPr(packageSetting, Binder.getCallingUid(), 5967 UserHandle.getCallingUserId())) { 5968 return false; 5969 } 5970 } 5971 5972 final long identity = Binder.clearCallingIdentity(); 5973 try { 5974 mPermissionManager.setWhitelistedRestrictedPermissions(pkg, 5975 new int[]{userId}, permissions, Process.myUid(), whitelistFlag, 5976 mPermissionCallback); 5977 } finally { 5978 Binder.restoreCallingIdentity(identity); 5979 } 5980 5981 return true; 5982 } 5983 5984 @Override 5985 public boolean shouldShowRequestPermissionRationale(String permissionName, 5986 String packageName, int userId) { 5987 if (UserHandle.getCallingUserId() != userId) { 5988 mContext.enforceCallingPermission( 5989 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 5990 "canShowRequestPermissionRationale for user " + userId); 5991 } 5992 5993 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 5994 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 5995 return false; 5996 } 5997 5998 if (checkPermission(permissionName, packageName, userId) 5999 == PackageManager.PERMISSION_GRANTED) { 6000 return false; 6001 } 6002 6003 final int flags; 6004 6005 final long identity = Binder.clearCallingIdentity(); 6006 try { 6007 flags = getPermissionFlags(permissionName, 6008 packageName, userId); 6009 } finally { 6010 Binder.restoreCallingIdentity(identity); 6011 } 6012 6013 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 6014 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 6015 | PackageManager.FLAG_PERMISSION_USER_FIXED; 6016 6017 if ((flags & fixedFlags) != 0) { 6018 return false; 6019 } 6020 6021 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 6022 } 6023 6024 @Override 6025 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6026 mContext.enforceCallingOrSelfPermission( 6027 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 6028 "addOnPermissionsChangeListener"); 6029 6030 synchronized (mPackages) { 6031 mOnPermissionChangeListeners.addListenerLocked(listener); 6032 } 6033 } 6034 6035 @Override 6036 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 6037 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6038 throw new SecurityException("Instant applications don't have access to this method"); 6039 } 6040 synchronized (mPackages) { 6041 mOnPermissionChangeListeners.removeListenerLocked(listener); 6042 } 6043 } 6044 6045 @Override 6046 public boolean isProtectedBroadcast(String actionName) { 6047 // allow instant applications 6048 synchronized (mProtectedBroadcasts) { 6049 if (mProtectedBroadcasts.contains(actionName)) { 6050 return true; 6051 } else if (actionName != null) { 6052 // TODO: remove these terrible hacks 6053 if (actionName.startsWith("android.net.netmon.lingerExpired") 6054 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 6055 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 6056 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 6057 return true; 6058 } 6059 } 6060 } 6061 return false; 6062 } 6063 6064 @Override 6065 public int checkSignatures(String pkg1, String pkg2) { 6066 synchronized (mPackages) { 6067 final PackageParser.Package p1 = mPackages.get(pkg1); 6068 final PackageParser.Package p2 = mPackages.get(pkg2); 6069 if (p1 == null || p1.mExtras == null 6070 || p2 == null || p2.mExtras == null) { 6071 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6072 } 6073 final int callingUid = Binder.getCallingUid(); 6074 final int callingUserId = UserHandle.getUserId(callingUid); 6075 final PackageSetting ps1 = (PackageSetting) p1.mExtras; 6076 final PackageSetting ps2 = (PackageSetting) p2.mExtras; 6077 if (filterAppAccessLPr(ps1, callingUid, callingUserId) 6078 || filterAppAccessLPr(ps2, callingUid, callingUserId)) { 6079 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6080 } 6081 return compareSignatures(p1.mSigningDetails.signatures, p2.mSigningDetails.signatures); 6082 } 6083 } 6084 6085 @Override 6086 public int checkUidSignatures(int uid1, int uid2) { 6087 final int callingUid = Binder.getCallingUid(); 6088 final int callingUserId = UserHandle.getUserId(callingUid); 6089 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6090 // Map to base uids. 6091 final int appId1 = UserHandle.getAppId(uid1); 6092 final int appId2 = UserHandle.getAppId(uid2); 6093 // reader 6094 synchronized (mPackages) { 6095 Signature[] s1; 6096 Signature[] s2; 6097 Object obj = mSettings.getSettingLPr(appId1); 6098 if (obj != null) { 6099 if (obj instanceof SharedUserSetting) { 6100 if (isCallerInstantApp) { 6101 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6102 } 6103 s1 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 6104 } else if (obj instanceof PackageSetting) { 6105 final PackageSetting ps = (PackageSetting) obj; 6106 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6107 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6108 } 6109 s1 = ps.signatures.mSigningDetails.signatures; 6110 } else { 6111 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6112 } 6113 } else { 6114 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6115 } 6116 obj = mSettings.getSettingLPr(appId2); 6117 if (obj != null) { 6118 if (obj instanceof SharedUserSetting) { 6119 if (isCallerInstantApp) { 6120 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6121 } 6122 s2 = ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 6123 } else if (obj instanceof PackageSetting) { 6124 final PackageSetting ps = (PackageSetting) obj; 6125 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6126 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6127 } 6128 s2 = ps.signatures.mSigningDetails.signatures; 6129 } else { 6130 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6131 } 6132 } else { 6133 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 6134 } 6135 return compareSignatures(s1, s2); 6136 } 6137 } 6138 6139 @Override 6140 public boolean hasSigningCertificate( 6141 String packageName, byte[] certificate, @PackageManager.CertificateInputType int type) { 6142 6143 synchronized (mPackages) { 6144 final PackageParser.Package p = mPackages.get(packageName); 6145 if (p == null || p.mExtras == null) { 6146 return false; 6147 } 6148 final int callingUid = Binder.getCallingUid(); 6149 final int callingUserId = UserHandle.getUserId(callingUid); 6150 final PackageSetting ps = (PackageSetting) p.mExtras; 6151 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6152 return false; 6153 } 6154 switch (type) { 6155 case CERT_INPUT_RAW_X509: 6156 return p.mSigningDetails.hasCertificate(certificate); 6157 case CERT_INPUT_SHA256: 6158 return p.mSigningDetails.hasSha256Certificate(certificate); 6159 default: 6160 return false; 6161 } 6162 } 6163 } 6164 6165 @Override 6166 public boolean hasUidSigningCertificate( 6167 int uid, byte[] certificate, @PackageManager.CertificateInputType int type) { 6168 final int callingUid = Binder.getCallingUid(); 6169 final int callingUserId = UserHandle.getUserId(callingUid); 6170 // Map to base uids. 6171 final int appId = UserHandle.getAppId(uid); 6172 // reader 6173 synchronized (mPackages) { 6174 final PackageParser.SigningDetails signingDetails; 6175 final Object obj = mSettings.getSettingLPr(appId); 6176 if (obj != null) { 6177 if (obj instanceof SharedUserSetting) { 6178 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6179 if (isCallerInstantApp) { 6180 return false; 6181 } 6182 signingDetails = ((SharedUserSetting)obj).signatures.mSigningDetails; 6183 } else if (obj instanceof PackageSetting) { 6184 final PackageSetting ps = (PackageSetting) obj; 6185 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 6186 return false; 6187 } 6188 signingDetails = ps.signatures.mSigningDetails; 6189 } else { 6190 return false; 6191 } 6192 } else { 6193 return false; 6194 } 6195 switch (type) { 6196 case CERT_INPUT_RAW_X509: 6197 return signingDetails.hasCertificate(certificate); 6198 case CERT_INPUT_SHA256: 6199 return signingDetails.hasSha256Certificate(certificate); 6200 default: 6201 return false; 6202 } 6203 } 6204 } 6205 6206 /** 6207 * This method should typically only be used when granting or revoking 6208 * permissions, since the app may immediately restart after this call. 6209 * <p> 6210 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 6211 * guard your work against the app being relaunched. 6212 */ 6213 private void killUid(int appId, int userId, String reason) { 6214 final long identity = Binder.clearCallingIdentity(); 6215 try { 6216 IActivityManager am = ActivityManager.getService(); 6217 if (am != null) { 6218 try { 6219 am.killUid(appId, userId, reason); 6220 } catch (RemoteException e) { 6221 /* ignore - same process */ 6222 } 6223 } 6224 } finally { 6225 Binder.restoreCallingIdentity(identity); 6226 } 6227 } 6228 6229 /** 6230 * If the database version for this type of package (internal storage or 6231 * external storage) is less than the version where package signatures 6232 * were updated, return true. 6233 */ 6234 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6235 return isCompatSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg)); 6236 } 6237 6238 private static boolean isCompatSignatureUpdateNeeded(VersionInfo ver) { 6239 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 6240 } 6241 6242 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 6243 return isRecoverSignatureUpdateNeeded(getSettingsVersionForPackage(scannedPkg)); 6244 } 6245 6246 private static boolean isRecoverSignatureUpdateNeeded(VersionInfo ver) { 6247 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 6248 } 6249 6250 @Override 6251 public List<String> getAllPackages() { 6252 final int callingUid = Binder.getCallingUid(); 6253 final int callingUserId = UserHandle.getUserId(callingUid); 6254 synchronized (mPackages) { 6255 if (canViewInstantApps(callingUid, callingUserId)) { 6256 return new ArrayList<>(mPackages.keySet()); 6257 } 6258 final String instantAppPkgName = getInstantAppPackageName(callingUid); 6259 final List<String> result = new ArrayList<>(); 6260 if (instantAppPkgName != null) { 6261 // caller is an instant application; filter unexposed applications 6262 for (PackageParser.Package pkg : mPackages.values()) { 6263 if (!pkg.visibleToInstantApps) { 6264 continue; 6265 } 6266 result.add(pkg.packageName); 6267 } 6268 } else { 6269 // caller is a normal application; filter instant applications 6270 for (PackageParser.Package pkg : mPackages.values()) { 6271 final PackageSetting ps = 6272 pkg.mExtras != null ? (PackageSetting) pkg.mExtras : null; 6273 if (ps != null 6274 && ps.getInstantApp(callingUserId) 6275 && !mInstantAppRegistry.isInstantAccessGranted( 6276 callingUserId, UserHandle.getAppId(callingUid), ps.appId)) { 6277 continue; 6278 } 6279 result.add(pkg.packageName); 6280 } 6281 } 6282 return result; 6283 } 6284 } 6285 6286 /** 6287 * <em>IMPORTANT:</em> Not all packages returned by this method may be known 6288 * to the system. There are two conditions in which this may occur: 6289 * <ol> 6290 * <li>The package is on adoptable storage and the device has been removed</li> 6291 * <li>The package is being removed and the internal structures are partially updated</li> 6292 * </ol> 6293 * The second is an artifact of the current data structures and should be fixed. See 6294 * b/111075456 for one such instance. 6295 */ 6296 @Override 6297 public String[] getPackagesForUid(int uid) { 6298 final int callingUid = Binder.getCallingUid(); 6299 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 6300 final int userId = UserHandle.getUserId(uid); 6301 final int appId = UserHandle.getAppId(uid); 6302 // reader 6303 synchronized (mPackages) { 6304 final Object obj = mSettings.getSettingLPr(appId); 6305 if (obj instanceof SharedUserSetting) { 6306 if (isCallerInstantApp) { 6307 return null; 6308 } 6309 final SharedUserSetting sus = (SharedUserSetting) obj; 6310 final int N = sus.packages.size(); 6311 String[] res = new String[N]; 6312 final Iterator<PackageSetting> it = sus.packages.iterator(); 6313 int i = 0; 6314 while (it.hasNext()) { 6315 PackageSetting ps = it.next(); 6316 if (ps.getInstalled(userId)) { 6317 res[i++] = ps.name; 6318 } else { 6319 res = ArrayUtils.removeElement(String.class, res, res[i]); 6320 } 6321 } 6322 return res; 6323 } else if (obj instanceof PackageSetting) { 6324 final PackageSetting ps = (PackageSetting) obj; 6325 if (ps.getInstalled(userId) && !filterAppAccessLPr(ps, callingUid, userId)) { 6326 return new String[]{ps.name}; 6327 } 6328 } 6329 } 6330 return null; 6331 } 6332 6333 @Override 6334 public String getNameForUid(int uid) { 6335 final int callingUid = Binder.getCallingUid(); 6336 if (getInstantAppPackageName(callingUid) != null) { 6337 return null; 6338 } 6339 final int appId = UserHandle.getAppId(uid); 6340 synchronized (mPackages) { 6341 final Object obj = mSettings.getSettingLPr(appId); 6342 if (obj instanceof SharedUserSetting) { 6343 final SharedUserSetting sus = (SharedUserSetting) obj; 6344 return sus.name + ":" + sus.userId; 6345 } else if (obj instanceof PackageSetting) { 6346 final PackageSetting ps = (PackageSetting) obj; 6347 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6348 return null; 6349 } 6350 return ps.name; 6351 } 6352 return null; 6353 } 6354 } 6355 6356 @Override 6357 public String[] getNamesForUids(int[] uids) { 6358 if (uids == null || uids.length == 0) { 6359 return null; 6360 } 6361 final int callingUid = Binder.getCallingUid(); 6362 if (getInstantAppPackageName(callingUid) != null) { 6363 return null; 6364 } 6365 final String[] names = new String[uids.length]; 6366 synchronized (mPackages) { 6367 for (int i = uids.length - 1; i >= 0; i--) { 6368 final int appId = UserHandle.getAppId(uids[i]); 6369 final Object obj = mSettings.getSettingLPr(appId); 6370 if (obj instanceof SharedUserSetting) { 6371 final SharedUserSetting sus = (SharedUserSetting) obj; 6372 names[i] = "shared:" + sus.name; 6373 } else if (obj instanceof PackageSetting) { 6374 final PackageSetting ps = (PackageSetting) obj; 6375 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6376 names[i] = null; 6377 } else { 6378 names[i] = ps.name; 6379 } 6380 } else { 6381 names[i] = null; 6382 } 6383 } 6384 } 6385 return names; 6386 } 6387 6388 @Override 6389 public int getUidForSharedUser(String sharedUserName) { 6390 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6391 return -1; 6392 } 6393 if (sharedUserName == null) { 6394 return -1; 6395 } 6396 // reader 6397 synchronized (mPackages) { 6398 SharedUserSetting suid; 6399 try { 6400 suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 6401 if (suid != null) { 6402 return suid.userId; 6403 } 6404 } catch (PackageManagerException ignore) { 6405 // can't happen, but, still need to catch it 6406 } 6407 return -1; 6408 } 6409 } 6410 6411 @Override 6412 public int getFlagsForUid(int uid) { 6413 final int callingUid = Binder.getCallingUid(); 6414 if (getInstantAppPackageName(callingUid) != null) { 6415 return 0; 6416 } 6417 final int appId = UserHandle.getAppId(uid); 6418 synchronized (mPackages) { 6419 final Object obj = mSettings.getSettingLPr(appId); 6420 if (obj instanceof SharedUserSetting) { 6421 final SharedUserSetting sus = (SharedUserSetting) obj; 6422 return sus.pkgFlags; 6423 } else if (obj instanceof PackageSetting) { 6424 final PackageSetting ps = (PackageSetting) obj; 6425 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6426 return 0; 6427 } 6428 return ps.pkgFlags; 6429 } 6430 } 6431 return 0; 6432 } 6433 6434 @Override 6435 public int getPrivateFlagsForUid(int uid) { 6436 final int callingUid = Binder.getCallingUid(); 6437 if (getInstantAppPackageName(callingUid) != null) { 6438 return 0; 6439 } 6440 final int appId = UserHandle.getAppId(uid); 6441 synchronized (mPackages) { 6442 final Object obj = mSettings.getSettingLPr(appId); 6443 if (obj instanceof SharedUserSetting) { 6444 final SharedUserSetting sus = (SharedUserSetting) obj; 6445 return sus.pkgPrivateFlags; 6446 } else if (obj instanceof PackageSetting) { 6447 final PackageSetting ps = (PackageSetting) obj; 6448 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 6449 return 0; 6450 } 6451 return ps.pkgPrivateFlags; 6452 } 6453 } 6454 return 0; 6455 } 6456 6457 @Override 6458 public boolean isUidPrivileged(int uid) { 6459 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6460 return false; 6461 } 6462 final int appId = UserHandle.getAppId(uid); 6463 // reader 6464 synchronized (mPackages) { 6465 final Object obj = mSettings.getSettingLPr(appId); 6466 if (obj instanceof SharedUserSetting) { 6467 final SharedUserSetting sus = (SharedUserSetting) obj; 6468 final Iterator<PackageSetting> it = sus.packages.iterator(); 6469 while (it.hasNext()) { 6470 if (it.next().isPrivileged()) { 6471 return true; 6472 } 6473 } 6474 } else if (obj instanceof PackageSetting) { 6475 final PackageSetting ps = (PackageSetting) obj; 6476 return ps.isPrivileged(); 6477 } 6478 } 6479 return false; 6480 } 6481 6482 @Override 6483 public String[] getAppOpPermissionPackages(String permName) { 6484 return mPermissionManager.getAppOpPermissionPackages(permName); 6485 } 6486 6487 @Override 6488 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 6489 int flags, int userId) { 6490 return resolveIntentInternal(intent, resolvedType, flags, userId, false, 6491 Binder.getCallingUid()); 6492 } 6493 6494 /** 6495 * Normally instant apps can only be resolved when they're visible to the caller. 6496 * However, if {@code resolveForStart} is {@code true}, all instant apps are visible 6497 * since we need to allow the system to start any installed application. 6498 */ 6499 private ResolveInfo resolveIntentInternal(Intent intent, String resolvedType, 6500 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 6501 try { 6502 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 6503 6504 if (!sUserManager.exists(userId)) return null; 6505 final int callingUid = Binder.getCallingUid(); 6506 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart); 6507 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 6508 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 6509 6510 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 6511 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 6512 flags, filterCallingUid, userId, resolveForStart, true /*allowDynamicSplits*/); 6513 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6514 6515 final ResolveInfo bestChoice = 6516 chooseBestActivity(intent, resolvedType, flags, query, userId); 6517 return bestChoice; 6518 } finally { 6519 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6520 } 6521 } 6522 6523 @Override 6524 public ResolveInfo findPersistentPreferredActivity(Intent intent, int userId) { 6525 if (!UserHandle.isSameApp(Binder.getCallingUid(), Process.SYSTEM_UID)) { 6526 throw new SecurityException( 6527 "findPersistentPreferredActivity can only be run by the system"); 6528 } 6529 if (!sUserManager.exists(userId)) { 6530 return null; 6531 } 6532 final int callingUid = Binder.getCallingUid(); 6533 intent = updateIntentForResolve(intent); 6534 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 6535 final int flags = updateFlagsForResolve( 6536 0, userId, intent, callingUid, false /*includeInstantApps*/); 6537 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6538 userId); 6539 synchronized (mPackages) { 6540 return findPersistentPreferredActivityLP(intent, resolvedType, flags, query, false, 6541 userId); 6542 } 6543 } 6544 6545 @Override 6546 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 6547 IntentFilter filter, int match, ComponentName activity) { 6548 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6549 return; 6550 } 6551 final int userId = UserHandle.getCallingUserId(); 6552 if (DEBUG_PREFERRED) { 6553 Log.v(TAG, "setLastChosenActivity intent=" + intent 6554 + " resolvedType=" + resolvedType 6555 + " flags=" + flags 6556 + " filter=" + filter 6557 + " match=" + match 6558 + " activity=" + activity); 6559 filter.dump(new PrintStreamPrinter(System.out), " "); 6560 } 6561 intent.setComponent(null); 6562 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6563 userId); 6564 // Find any earlier preferred or last chosen entries and nuke them 6565 findPreferredActivityNotLocked( 6566 intent, resolvedType, flags, query, 0, false, true, false, userId); 6567 // Add the new activity as the last chosen for this filter 6568 addPreferredActivityInternal(filter, match, null, activity, false, userId, 6569 "Setting last chosen"); 6570 } 6571 6572 @Override 6573 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 6574 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 6575 return null; 6576 } 6577 final int userId = UserHandle.getCallingUserId(); 6578 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 6579 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 6580 userId); 6581 return findPreferredActivityNotLocked( 6582 intent, resolvedType, flags, query, 0, false, false, false, userId); 6583 } 6584 6585 /** 6586 * Returns whether or not instant apps have been disabled remotely. 6587 */ 6588 private boolean areWebInstantAppsDisabled(int userId) { 6589 return mWebInstantAppsDisabled.get(userId); 6590 } 6591 6592 private boolean isInstantAppResolutionAllowed( 6593 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 6594 boolean skipPackageCheck) { 6595 if (mInstantAppResolverConnection == null) { 6596 return false; 6597 } 6598 if (mInstantAppInstallerActivity == null) { 6599 return false; 6600 } 6601 if (intent.getComponent() != null) { 6602 return false; 6603 } 6604 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 6605 return false; 6606 } 6607 if (!skipPackageCheck && intent.getPackage() != null) { 6608 return false; 6609 } 6610 if (!intent.isWebIntent()) { 6611 // for non web intents, we should not resolve externally if an app already exists to 6612 // handle it or if the caller didn't explicitly request it. 6613 if ((resolvedActivities != null && resolvedActivities.size() != 0) 6614 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 6615 return false; 6616 } 6617 } else { 6618 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 6619 return false; 6620 } else if (areWebInstantAppsDisabled(userId)) { 6621 return false; 6622 } 6623 } 6624 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 6625 // Or if there's already an ephemeral app installed that handles the action 6626 synchronized (mPackages) { 6627 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 6628 for (int n = 0; n < count; n++) { 6629 final ResolveInfo info = resolvedActivities.get(n); 6630 final String packageName = info.activityInfo.packageName; 6631 final PackageSetting ps = mSettings.mPackages.get(packageName); 6632 if (ps != null) { 6633 // only check domain verification status if the app is not a browser 6634 if (!info.handleAllWebDataURI) { 6635 // Try to get the status from User settings first 6636 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6637 final int status = (int) (packedStatus >> 32); 6638 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 6639 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6640 if (DEBUG_INSTANT) { 6641 Slog.v(TAG, "DENY instant app;" 6642 + " pkg: " + packageName + ", status: " + status); 6643 } 6644 return false; 6645 } 6646 } 6647 if (ps.getInstantApp(userId)) { 6648 if (DEBUG_INSTANT) { 6649 Slog.v(TAG, "DENY instant app installed;" 6650 + " pkg: " + packageName); 6651 } 6652 return false; 6653 } 6654 } 6655 } 6656 } 6657 // We've exhausted all ways to deny ephemeral application; let the system look for them. 6658 return true; 6659 } 6660 6661 private void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 6662 Intent origIntent, String resolvedType, String callingPackage, 6663 Bundle verificationBundle, int userId) { 6664 final Message msg = mHandler.obtainMessage(INSTANT_APP_RESOLUTION_PHASE_TWO, 6665 new InstantAppRequest(responseObj, origIntent, resolvedType, 6666 callingPackage, userId, verificationBundle, false /*resolveForStart*/)); 6667 mHandler.sendMessage(msg); 6668 } 6669 6670 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 6671 int flags, List<ResolveInfo> query, int userId) { 6672 if (query != null) { 6673 final int N = query.size(); 6674 if (N == 1) { 6675 return query.get(0); 6676 } else if (N > 1) { 6677 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 6678 // If there is more than one activity with the same priority, 6679 // then let the user decide between them. 6680 ResolveInfo r0 = query.get(0); 6681 ResolveInfo r1 = query.get(1); 6682 if (DEBUG_INTENT_MATCHING || debug) { 6683 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 6684 + r1.activityInfo.name + "=" + r1.priority); 6685 } 6686 // If the first activity has a higher priority, or a different 6687 // default, then it is always desirable to pick it. 6688 if (r0.priority != r1.priority 6689 || r0.preferredOrder != r1.preferredOrder 6690 || r0.isDefault != r1.isDefault) { 6691 return query.get(0); 6692 } 6693 // If we have saved a preference for a preferred activity for 6694 // this Intent, use that. 6695 ResolveInfo ri = findPreferredActivityNotLocked(intent, resolvedType, 6696 flags, query, r0.priority, true, false, debug, userId); 6697 if (ri != null) { 6698 return ri; 6699 } 6700 // If we have an ephemeral app, use it 6701 for (int i = 0; i < N; i++) { 6702 ri = query.get(i); 6703 if (ri.activityInfo.applicationInfo.isInstantApp()) { 6704 final String packageName = ri.activityInfo.packageName; 6705 final PackageSetting ps = mSettings.mPackages.get(packageName); 6706 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 6707 final int status = (int)(packedStatus >> 32); 6708 if (status != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 6709 return ri; 6710 } 6711 } 6712 } 6713 ri = new ResolveInfo(mResolveInfo); 6714 ri.activityInfo = new ActivityInfo(ri.activityInfo); 6715 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 6716 // If all of the options come from the same package, show the application's 6717 // label and icon instead of the generic resolver's. 6718 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 6719 // and then throw away the ResolveInfo itself, meaning that the caller loses 6720 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 6721 // a fallback for this case; we only set the target package's resources on 6722 // the ResolveInfo, not the ActivityInfo. 6723 final String intentPackage = intent.getPackage(); 6724 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 6725 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 6726 ri.resolvePackageName = intentPackage; 6727 if (userNeedsBadging(userId)) { 6728 ri.noResourceId = true; 6729 } else { 6730 ri.icon = appi.icon; 6731 } 6732 ri.iconResourceId = appi.icon; 6733 ri.labelRes = appi.labelRes; 6734 } 6735 ri.activityInfo.applicationInfo = new ApplicationInfo( 6736 ri.activityInfo.applicationInfo); 6737 if (userId != 0) { 6738 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 6739 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 6740 } 6741 // Make sure that the resolver is displayable in car mode 6742 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 6743 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 6744 return ri; 6745 } 6746 } 6747 return null; 6748 } 6749 6750 /** 6751 * Return true if the given list is not empty and all of its contents have 6752 * an activityInfo with the given package name. 6753 */ 6754 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 6755 if (ArrayUtils.isEmpty(list)) { 6756 return false; 6757 } 6758 for (int i = 0, N = list.size(); i < N; i++) { 6759 final ResolveInfo ri = list.get(i); 6760 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 6761 if (ai == null || !packageName.equals(ai.packageName)) { 6762 return false; 6763 } 6764 } 6765 return true; 6766 } 6767 6768 @GuardedBy("mPackages") 6769 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 6770 int flags, List<ResolveInfo> query, boolean debug, int userId) { 6771 final int N = query.size(); 6772 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 6773 .get(userId); 6774 // Get the list of persistent preferred activities that handle the intent 6775 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 6776 List<PersistentPreferredActivity> pprefs = ppir != null 6777 ? ppir.queryIntent(intent, resolvedType, 6778 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6779 userId) 6780 : null; 6781 if (pprefs != null && pprefs.size() > 0) { 6782 final int M = pprefs.size(); 6783 for (int i=0; i<M; i++) { 6784 final PersistentPreferredActivity ppa = pprefs.get(i); 6785 if (DEBUG_PREFERRED || debug) { 6786 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 6787 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 6788 + "\n component=" + ppa.mComponent); 6789 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6790 } 6791 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 6792 flags | MATCH_DISABLED_COMPONENTS, userId); 6793 if (DEBUG_PREFERRED || debug) { 6794 Slog.v(TAG, "Found persistent preferred activity:"); 6795 if (ai != null) { 6796 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6797 } else { 6798 Slog.v(TAG, " null"); 6799 } 6800 } 6801 if (ai == null) { 6802 // This previously registered persistent preferred activity 6803 // component is no longer known. Ignore it and do NOT remove it. 6804 continue; 6805 } 6806 for (int j=0; j<N; j++) { 6807 final ResolveInfo ri = query.get(j); 6808 if (!ri.activityInfo.applicationInfo.packageName 6809 .equals(ai.applicationInfo.packageName)) { 6810 continue; 6811 } 6812 if (!ri.activityInfo.name.equals(ai.name)) { 6813 continue; 6814 } 6815 // Found a persistent preference that can handle the intent. 6816 if (DEBUG_PREFERRED || debug) { 6817 Slog.v(TAG, "Returning persistent preferred activity: " + 6818 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 6819 } 6820 return ri; 6821 } 6822 } 6823 } 6824 return null; 6825 } 6826 6827 private boolean isHomeIntent(Intent intent) { 6828 return ACTION_MAIN.equals(intent.getAction()) 6829 && intent.hasCategory(CATEGORY_HOME) 6830 && intent.hasCategory(CATEGORY_DEFAULT); 6831 } 6832 6833 // TODO: handle preferred activities missing while user has amnesia 6834 /** <b>must not hold {@link #mPackages}</b> */ 6835 ResolveInfo findPreferredActivityNotLocked(Intent intent, String resolvedType, int flags, 6836 List<ResolveInfo> query, int priority, boolean always, 6837 boolean removeMatches, boolean debug, int userId) { 6838 if (Thread.holdsLock(mPackages)) { 6839 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 6840 + " is holding mPackages", new Throwable()); 6841 } 6842 if (!sUserManager.exists(userId)) return null; 6843 final int callingUid = Binder.getCallingUid(); 6844 // Do NOT hold the packages lock; this calls up into the settings provider which 6845 // could cause a deadlock. 6846 final boolean isDeviceProvisioned = 6847 android.provider.Settings.Global.getInt(mContext.getContentResolver(), 6848 android.provider.Settings.Global.DEVICE_PROVISIONED, 0) == 1; 6849 flags = updateFlagsForResolve( 6850 flags, userId, intent, callingUid, false /*includeInstantApps*/); 6851 intent = updateIntentForResolve(intent); 6852 // writer 6853 synchronized (mPackages) { 6854 // Try to find a matching persistent preferred activity. 6855 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 6856 debug, userId); 6857 6858 // If a persistent preferred activity matched, use it. 6859 if (pri != null) { 6860 return pri; 6861 } 6862 6863 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 6864 // Get the list of preferred activities that handle the intent 6865 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 6866 List<PreferredActivity> prefs = pir != null 6867 ? pir.queryIntent(intent, resolvedType, 6868 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 6869 userId) 6870 : null; 6871 if (prefs != null && prefs.size() > 0) { 6872 boolean changed = false; 6873 try { 6874 // First figure out how good the original match set is. 6875 // We will only allow preferred activities that came 6876 // from the same match quality. 6877 int match = 0; 6878 6879 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 6880 6881 final int N = query.size(); 6882 for (int j=0; j<N; j++) { 6883 final ResolveInfo ri = query.get(j); 6884 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 6885 + ": 0x" + Integer.toHexString(match)); 6886 if (ri.match > match) { 6887 match = ri.match; 6888 } 6889 } 6890 6891 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 6892 + Integer.toHexString(match)); 6893 6894 match &= IntentFilter.MATCH_CATEGORY_MASK; 6895 final int M = prefs.size(); 6896 for (int i=0; i<M; i++) { 6897 final PreferredActivity pa = prefs.get(i); 6898 if (DEBUG_PREFERRED || debug) { 6899 Slog.v(TAG, "Checking PreferredActivity ds=" 6900 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 6901 + "\n component=" + pa.mPref.mComponent); 6902 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6903 } 6904 if (pa.mPref.mMatch != match) { 6905 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 6906 + Integer.toHexString(pa.mPref.mMatch)); 6907 continue; 6908 } 6909 // If it's not an "always" type preferred activity and that's what we're 6910 // looking for, skip it. 6911 if (always && !pa.mPref.mAlways) { 6912 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 6913 continue; 6914 } 6915 final ActivityInfo ai = getActivityInfo( 6916 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 6917 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 6918 userId); 6919 if (DEBUG_PREFERRED || debug) { 6920 Slog.v(TAG, "Found preferred activity:"); 6921 if (ai != null) { 6922 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 6923 } else { 6924 Slog.v(TAG, " null"); 6925 } 6926 } 6927 final boolean excludeSetupWizardHomeActivity = isHomeIntent(intent) 6928 && !isDeviceProvisioned; 6929 if (ai == null) { 6930 // Do not remove launcher's preferred activity during SetupWizard 6931 // due to it may not install yet 6932 if (excludeSetupWizardHomeActivity) { 6933 continue; 6934 } 6935 6936 // This previously registered preferred activity 6937 // component is no longer known. Most likely an update 6938 // to the app was installed and in the new version this 6939 // component no longer exists. Clean it up by removing 6940 // it from the preferred activities list, and skip it. 6941 Slog.w(TAG, "Removing dangling preferred activity: " 6942 + pa.mPref.mComponent); 6943 pir.removeFilter(pa); 6944 changed = true; 6945 continue; 6946 } 6947 for (int j=0; j<N; j++) { 6948 final ResolveInfo ri = query.get(j); 6949 if (!ri.activityInfo.applicationInfo.packageName 6950 .equals(ai.applicationInfo.packageName)) { 6951 continue; 6952 } 6953 if (!ri.activityInfo.name.equals(ai.name)) { 6954 continue; 6955 } 6956 6957 if (removeMatches) { 6958 pir.removeFilter(pa); 6959 changed = true; 6960 if (DEBUG_PREFERRED) { 6961 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 6962 } 6963 break; 6964 } 6965 6966 // Okay we found a previously set preferred or last chosen app. 6967 // If the result set is different from when this 6968 // was created, and is not a subset of the preferred set, we need to 6969 // clear it and re-ask the user their preference, if we're looking for 6970 // an "always" type entry. 6971 6972 if (always && !pa.mPref.sameSet(query, excludeSetupWizardHomeActivity)) { 6973 if (pa.mPref.isSuperset(query, excludeSetupWizardHomeActivity)) { 6974 if (!excludeSetupWizardHomeActivity) { 6975 // some components of the set are no longer present in 6976 // the query, but the preferred activity can still be reused 6977 if (DEBUG_PREFERRED) { 6978 Slog.i(TAG, "Result set changed, but PreferredActivity" 6979 + " is still valid as only non-preferred" 6980 + " components were removed for " + intent 6981 + " type " + resolvedType); 6982 } 6983 // remove obsolete components and re-add the up-to-date 6984 // filter 6985 PreferredActivity freshPa = new PreferredActivity(pa, 6986 pa.mPref.mMatch, 6987 pa.mPref.discardObsoleteComponents(query), 6988 pa.mPref.mComponent, 6989 pa.mPref.mAlways); 6990 pir.removeFilter(pa); 6991 pir.addFilter(freshPa); 6992 changed = true; 6993 } else { 6994 if (DEBUG_PREFERRED) { 6995 Slog.i(TAG, "Do not remove preferred activity for launcher" 6996 + " during SetupWizard"); 6997 } 6998 } 6999 } else { 7000 Slog.i(TAG, 7001 "Result set changed, dropping preferred activity for " 7002 + intent + " type " + resolvedType); 7003 if (DEBUG_PREFERRED) { 7004 Slog.v(TAG, "Removing preferred activity since set changed " 7005 + pa.mPref.mComponent); 7006 } 7007 pir.removeFilter(pa); 7008 // Re-add the filter as a "last chosen" entry (!always) 7009 PreferredActivity lastChosen = new PreferredActivity( 7010 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 7011 pir.addFilter(lastChosen); 7012 changed = true; 7013 return null; 7014 } 7015 } 7016 7017 // Yay! Either the set matched or we're looking for the last chosen 7018 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 7019 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 7020 return ri; 7021 } 7022 } 7023 } finally { 7024 if (changed) { 7025 if (DEBUG_PREFERRED) { 7026 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 7027 } 7028 scheduleWritePackageRestrictionsLocked(userId); 7029 } 7030 } 7031 } 7032 } 7033 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 7034 return null; 7035 } 7036 7037 /* 7038 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 7039 */ 7040 @Override 7041 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 7042 int targetUserId) { 7043 mContext.enforceCallingOrSelfPermission( 7044 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 7045 List<CrossProfileIntentFilter> matches = 7046 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 7047 if (matches != null) { 7048 int size = matches.size(); 7049 for (int i = 0; i < size; i++) { 7050 if (matches.get(i).getTargetUserId() == targetUserId) return true; 7051 } 7052 } 7053 if (intent.hasWebURI()) { 7054 // cross-profile app linking works only towards the parent. 7055 final int callingUid = Binder.getCallingUid(); 7056 final UserInfo parent = getProfileParent(sourceUserId); 7057 synchronized(mPackages) { 7058 int flags = updateFlagsForResolve(0, parent.id, intent, callingUid, 7059 false /*includeInstantApps*/); 7060 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 7061 intent, resolvedType, flags, sourceUserId, parent.id); 7062 return xpDomainInfo != null; 7063 } 7064 } 7065 return false; 7066 } 7067 7068 private UserInfo getProfileParent(int userId) { 7069 final long identity = Binder.clearCallingIdentity(); 7070 try { 7071 return sUserManager.getProfileParent(userId); 7072 } finally { 7073 Binder.restoreCallingIdentity(identity); 7074 } 7075 } 7076 7077 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 7078 String resolvedType, int userId) { 7079 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 7080 if (resolver != null) { 7081 return resolver.queryIntent(intent, resolvedType, false /*defaultOnly*/, userId); 7082 } 7083 return null; 7084 } 7085 7086 @Override 7087 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 7088 String resolvedType, int flags, int userId) { 7089 try { 7090 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 7091 7092 return new ParceledListSlice<>( 7093 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 7094 } finally { 7095 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7096 } 7097 } 7098 7099 /** 7100 * Returns the package name of the calling Uid if it's an instant app. If it isn't 7101 * instant, returns {@code null}. 7102 */ 7103 private String getInstantAppPackageName(int callingUid) { 7104 synchronized (mPackages) { 7105 // If the caller is an isolated app use the owner's uid for the lookup. 7106 if (Process.isIsolated(callingUid)) { 7107 callingUid = mIsolatedOwners.get(callingUid); 7108 } 7109 final int appId = UserHandle.getAppId(callingUid); 7110 final Object obj = mSettings.getSettingLPr(appId); 7111 if (obj instanceof PackageSetting) { 7112 final PackageSetting ps = (PackageSetting) obj; 7113 final boolean isInstantApp = ps.getInstantApp(UserHandle.getUserId(callingUid)); 7114 return isInstantApp ? ps.pkg.packageName : null; 7115 } 7116 } 7117 return null; 7118 } 7119 7120 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7121 String resolvedType, int flags, int userId) { 7122 return queryIntentActivitiesInternal( 7123 intent, resolvedType, flags, Binder.getCallingUid(), userId, 7124 false /*resolveForStart*/, true /*allowDynamicSplits*/); 7125 } 7126 7127 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 7128 String resolvedType, int flags, int filterCallingUid, int userId, 7129 boolean resolveForStart, boolean allowDynamicSplits) { 7130 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7131 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 7132 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 7133 false /* requireFullPermission */, false /* checkShell */, 7134 "query intent activities"); 7135 final String pkgName = intent.getPackage(); 7136 ComponentName comp = intent.getComponent(); 7137 if (comp == null) { 7138 if (intent.getSelector() != null) { 7139 intent = intent.getSelector(); 7140 comp = intent.getComponent(); 7141 } 7142 } 7143 7144 flags = updateFlagsForResolve(flags, userId, intent, filterCallingUid, resolveForStart, 7145 comp != null || pkgName != null /*onlyExposedExplicitly*/); 7146 if (comp != null) { 7147 final List<ResolveInfo> list = new ArrayList<>(1); 7148 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 7149 if (ai != null) { 7150 // When specifying an explicit component, we prevent the activity from being 7151 // used when either 1) the calling package is normal and the activity is within 7152 // an ephemeral application or 2) the calling package is ephemeral and the 7153 // activity is not visible to ephemeral applications. 7154 final boolean matchInstantApp = 7155 (flags & PackageManager.MATCH_INSTANT) != 0; 7156 final boolean matchVisibleToInstantAppOnly = 7157 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 7158 final boolean matchExplicitlyVisibleOnly = 7159 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 7160 final boolean isCallerInstantApp = 7161 instantAppPkgName != null; 7162 final boolean isTargetSameInstantApp = 7163 comp.getPackageName().equals(instantAppPkgName); 7164 final boolean isTargetInstantApp = 7165 (ai.applicationInfo.privateFlags 7166 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 7167 final boolean isTargetVisibleToInstantApp = 7168 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 7169 final boolean isTargetExplicitlyVisibleToInstantApp = 7170 isTargetVisibleToInstantApp 7171 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 7172 final boolean isTargetHiddenFromInstantApp = 7173 !isTargetVisibleToInstantApp 7174 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 7175 final boolean blockResolution = 7176 !isTargetSameInstantApp 7177 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 7178 || (matchVisibleToInstantAppOnly && isCallerInstantApp 7179 && isTargetHiddenFromInstantApp)); 7180 if (!blockResolution) { 7181 final ResolveInfo ri = new ResolveInfo(); 7182 ri.activityInfo = ai; 7183 list.add(ri); 7184 } 7185 } 7186 return applyPostResolutionFilter( 7187 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart, 7188 userId, intent); 7189 } 7190 7191 // reader 7192 boolean sortResult = false; 7193 boolean addInstant = false; 7194 List<ResolveInfo> result; 7195 synchronized (mPackages) { 7196 if (pkgName == null) { 7197 List<CrossProfileIntentFilter> matchingFilters = 7198 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 7199 // Check for results that need to skip the current profile. 7200 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 7201 resolvedType, flags, userId); 7202 if (xpResolveInfo != null) { 7203 List<ResolveInfo> xpResult = new ArrayList<>(1); 7204 xpResult.add(xpResolveInfo); 7205 return applyPostResolutionFilter( 7206 filterIfNotSystemUser(xpResult, userId), instantAppPkgName, 7207 allowDynamicSplits, filterCallingUid, resolveForStart, userId, intent); 7208 } 7209 7210 // Check for results in the current profile. 7211 result = filterIfNotSystemUser(mComponentResolver.queryActivities( 7212 intent, resolvedType, flags, userId), userId); 7213 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 7214 false /*skipPackageCheck*/); 7215 // Check for cross profile results. 7216 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 7217 xpResolveInfo = queryCrossProfileIntents( 7218 matchingFilters, intent, resolvedType, flags, userId, 7219 hasNonNegativePriorityResult); 7220 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 7221 boolean isVisibleToUser = filterIfNotSystemUser( 7222 Collections.singletonList(xpResolveInfo), userId).size() > 0; 7223 if (isVisibleToUser) { 7224 result.add(xpResolveInfo); 7225 sortResult = true; 7226 } 7227 } 7228 if (intent.hasWebURI()) { 7229 CrossProfileDomainInfo xpDomainInfo = null; 7230 final UserInfo parent = getProfileParent(userId); 7231 if (parent != null) { 7232 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 7233 flags, userId, parent.id); 7234 } 7235 if (xpDomainInfo != null) { 7236 if (xpResolveInfo != null) { 7237 // If we didn't remove it, the cross-profile ResolveInfo would be twice 7238 // in the result. 7239 result.remove(xpResolveInfo); 7240 } 7241 if (result.size() == 0 && !addInstant) { 7242 // No result in current profile, but found candidate in parent user. 7243 // And we are not going to add emphemeral app, so we can return the 7244 // result straight away. 7245 result.add(xpDomainInfo.resolveInfo); 7246 return applyPostResolutionFilter(result, instantAppPkgName, 7247 allowDynamicSplits, filterCallingUid, resolveForStart, userId, 7248 intent); 7249 } 7250 } else if (result.size() <= 1 && !addInstant) { 7251 // No result in parent user and <= 1 result in current profile, and we 7252 // are not going to add emphemeral app, so we can return the result without 7253 // further processing. 7254 return applyPostResolutionFilter(result, instantAppPkgName, 7255 allowDynamicSplits, filterCallingUid, resolveForStart, userId, 7256 intent); 7257 } 7258 // We have more than one candidate (combining results from current and parent 7259 // profile), so we need filtering and sorting. 7260 result = filterCandidatesWithDomainPreferredActivitiesLPr( 7261 intent, flags, result, xpDomainInfo, userId); 7262 sortResult = true; 7263 } 7264 } else { 7265 final PackageParser.Package pkg = mPackages.get(pkgName); 7266 result = null; 7267 if (pkg != null) { 7268 result = filterIfNotSystemUser(mComponentResolver.queryActivities( 7269 intent, resolvedType, flags, pkg.activities, userId), userId); 7270 } 7271 if (result == null || result.size() == 0) { 7272 // the caller wants to resolve for a particular package; however, there 7273 // were no installed results, so, try to find an ephemeral result 7274 addInstant = isInstantAppResolutionAllowed( 7275 intent, null /*result*/, userId, true /*skipPackageCheck*/); 7276 if (result == null) { 7277 result = new ArrayList<>(); 7278 } 7279 } 7280 } 7281 } 7282 if (addInstant) { 7283 result = maybeAddInstantAppInstaller( 7284 result, intent, resolvedType, flags, userId, resolveForStart); 7285 } 7286 if (sortResult) { 7287 Collections.sort(result, RESOLVE_PRIORITY_SORTER); 7288 } 7289 return applyPostResolutionFilter( 7290 result, instantAppPkgName, allowDynamicSplits, filterCallingUid, resolveForStart, 7291 userId, intent); 7292 } 7293 7294 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, 7295 String resolvedType, int flags, int userId, boolean resolveForStart) { 7296 // first, check to see if we've got an instant app already installed 7297 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 7298 ResolveInfo localInstantApp = null; 7299 boolean blockResolution = false; 7300 if (!alreadyResolvedLocally) { 7301 final List<ResolveInfo> instantApps = mComponentResolver.queryActivities( 7302 intent, 7303 resolvedType, 7304 flags 7305 | PackageManager.GET_RESOLVED_FILTER 7306 | PackageManager.MATCH_INSTANT 7307 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 7308 userId); 7309 for (int i = instantApps.size() - 1; i >= 0; --i) { 7310 final ResolveInfo info = instantApps.get(i); 7311 final String packageName = info.activityInfo.packageName; 7312 final PackageSetting ps = mSettings.mPackages.get(packageName); 7313 if (ps.getInstantApp(userId)) { 7314 final long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7315 final int status = (int)(packedStatus >> 32); 7316 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7317 // there's a local instant application installed, but, the user has 7318 // chosen to never use it; skip resolution and don't acknowledge 7319 // an instant application is even available 7320 if (DEBUG_INSTANT) { 7321 Slog.v(TAG, "Instant app marked to never run; pkg: " + packageName); 7322 } 7323 blockResolution = true; 7324 break; 7325 } else { 7326 // we have a locally installed instant application; skip resolution 7327 // but acknowledge there's an instant application available 7328 if (DEBUG_INSTANT) { 7329 Slog.v(TAG, "Found installed instant app; pkg: " + packageName); 7330 } 7331 localInstantApp = info; 7332 break; 7333 } 7334 } 7335 } 7336 } 7337 // no app installed, let's see if one's available 7338 AuxiliaryResolveInfo auxiliaryResponse = null; 7339 if (!blockResolution) { 7340 if (localInstantApp == null) { 7341 // we don't have an instant app locally, resolve externally 7342 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 7343 final InstantAppRequest requestObject = new InstantAppRequest( 7344 null /*responseObj*/, intent /*origIntent*/, resolvedType, 7345 null /*callingPackage*/, userId, null /*verificationBundle*/, 7346 resolveForStart); 7347 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne( 7348 mInstantAppResolverConnection, requestObject); 7349 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7350 } else { 7351 // we have an instant application locally, but, we can't admit that since 7352 // callers shouldn't be able to determine prior browsing. create a dummy 7353 // auxiliary response so the downstream code behaves as if there's an 7354 // instant application available externally. when it comes time to start 7355 // the instant application, we'll do the right thing. 7356 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 7357 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 7358 ai.packageName, ai.longVersionCode, null /* splitName */); 7359 } 7360 } 7361 if (intent.isWebIntent() && auxiliaryResponse == null) { 7362 return result; 7363 } 7364 final PackageSetting ps = mSettings.mPackages.get(mInstantAppInstallerActivity.packageName); 7365 if (ps == null 7366 || !ps.readUserState(userId).isEnabled(mInstantAppInstallerActivity, 0)) { 7367 return result; 7368 } 7369 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 7370 ephemeralInstaller.activityInfo = PackageParser.generateActivityInfo( 7371 mInstantAppInstallerActivity, 0, ps.readUserState(userId), userId); 7372 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 7373 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 7374 // add a non-generic filter 7375 ephemeralInstaller.filter = new IntentFilter(); 7376 if (intent.getAction() != null) { 7377 ephemeralInstaller.filter.addAction(intent.getAction()); 7378 } 7379 if (intent.getData() != null && intent.getData().getPath() != null) { 7380 ephemeralInstaller.filter.addDataPath( 7381 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 7382 } 7383 ephemeralInstaller.isInstantAppAvailable = true; 7384 // make sure this resolver is the default 7385 ephemeralInstaller.isDefault = true; 7386 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 7387 if (DEBUG_INSTANT) { 7388 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 7389 } 7390 7391 result.add(ephemeralInstaller); 7392 return result; 7393 } 7394 7395 private static class CrossProfileDomainInfo { 7396 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 7397 ResolveInfo resolveInfo; 7398 /* Best domain verification status of the activities found in the other profile */ 7399 int bestDomainVerificationStatus; 7400 } 7401 7402 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 7403 String resolvedType, int flags, int sourceUserId, int parentUserId) { 7404 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 7405 sourceUserId)) { 7406 return null; 7407 } 7408 List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent, 7409 resolvedType, flags, parentUserId); 7410 7411 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 7412 return null; 7413 } 7414 CrossProfileDomainInfo result = null; 7415 int size = resultTargetUser.size(); 7416 for (int i = 0; i < size; i++) { 7417 ResolveInfo riTargetUser = resultTargetUser.get(i); 7418 // Intent filter verification is only for filters that specify a host. So don't return 7419 // those that handle all web uris. 7420 if (riTargetUser.handleAllWebDataURI) { 7421 continue; 7422 } 7423 String packageName = riTargetUser.activityInfo.packageName; 7424 PackageSetting ps = mSettings.mPackages.get(packageName); 7425 if (ps == null) { 7426 continue; 7427 } 7428 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 7429 int status = (int)(verificationState >> 32); 7430 if (result == null) { 7431 result = new CrossProfileDomainInfo(); 7432 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 7433 sourceUserId, parentUserId); 7434 result.bestDomainVerificationStatus = status; 7435 } else { 7436 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 7437 result.bestDomainVerificationStatus); 7438 } 7439 } 7440 // Don't consider matches with status NEVER across profiles. 7441 if (result != null && result.bestDomainVerificationStatus 7442 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7443 return null; 7444 } 7445 return result; 7446 } 7447 7448 /** 7449 * Verification statuses are ordered from the worse to the best, except for 7450 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 7451 */ 7452 private int bestDomainVerificationStatus(int status1, int status2) { 7453 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7454 return status2; 7455 } 7456 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7457 return status1; 7458 } 7459 return (int) MathUtils.max(status1, status2); 7460 } 7461 7462 private boolean isUserEnabled(int userId) { 7463 long callingId = Binder.clearCallingIdentity(); 7464 try { 7465 UserInfo userInfo = sUserManager.getUserInfo(userId); 7466 return userInfo != null && userInfo.isEnabled(); 7467 } finally { 7468 Binder.restoreCallingIdentity(callingId); 7469 } 7470 } 7471 7472 /** 7473 * Filter out activities with systemUserOnly flag set, when current user is not System. 7474 * 7475 * @return filtered list 7476 */ 7477 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 7478 if (userId == UserHandle.USER_SYSTEM) { 7479 return resolveInfos; 7480 } 7481 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7482 ResolveInfo info = resolveInfos.get(i); 7483 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 7484 resolveInfos.remove(i); 7485 } 7486 } 7487 return resolveInfos; 7488 } 7489 7490 /** 7491 * Filters out ephemeral activities. 7492 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 7493 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 7494 * 7495 * @param resolveInfos The pre-filtered list of resolved activities 7496 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 7497 * is performed. 7498 * @param intent 7499 * @return A filtered list of resolved activities. 7500 */ 7501 private List<ResolveInfo> applyPostResolutionFilter(List<ResolveInfo> resolveInfos, 7502 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, 7503 boolean resolveForStart, int userId, Intent intent) { 7504 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(userId); 7505 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 7506 final ResolveInfo info = resolveInfos.get(i); 7507 // remove locally resolved instant app web results when disabled 7508 if (info.isInstantAppAvailable && blockInstant) { 7509 resolveInfos.remove(i); 7510 continue; 7511 } 7512 // allow activities that are defined in the provided package 7513 if (allowDynamicSplits 7514 && info.activityInfo != null 7515 && info.activityInfo.splitName != null 7516 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 7517 info.activityInfo.splitName)) { 7518 if (mInstantAppInstallerActivity == null) { 7519 if (DEBUG_INSTALL) { 7520 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 7521 } 7522 resolveInfos.remove(i); 7523 continue; 7524 } 7525 if (blockInstant && isInstantApp(info.activityInfo.packageName, userId)) { 7526 resolveInfos.remove(i); 7527 continue; 7528 } 7529 // requested activity is defined in a split that hasn't been installed yet. 7530 // add the installer to the resolve list 7531 if (DEBUG_INSTALL) { 7532 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 7533 } 7534 final ResolveInfo installerInfo = new ResolveInfo( 7535 mInstantAppInstallerInfo); 7536 final ComponentName installFailureActivity = findInstallFailureActivity( 7537 info.activityInfo.packageName, filterCallingUid, userId); 7538 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 7539 installFailureActivity, 7540 info.activityInfo.packageName, 7541 info.activityInfo.applicationInfo.longVersionCode, 7542 info.activityInfo.splitName); 7543 // add a non-generic filter 7544 installerInfo.filter = new IntentFilter(); 7545 7546 // This resolve info may appear in the chooser UI, so let us make it 7547 // look as the one it replaces as far as the user is concerned which 7548 // requires loading the correct label and icon for the resolve info. 7549 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 7550 installerInfo.labelRes = info.resolveLabelResId(); 7551 installerInfo.icon = info.resolveIconResId(); 7552 installerInfo.isInstantAppAvailable = true; 7553 resolveInfos.set(i, installerInfo); 7554 continue; 7555 } 7556 // caller is a full app, don't need to apply any other filtering 7557 if (ephemeralPkgName == null) { 7558 continue; 7559 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 7560 // caller is same app; don't need to apply any other filtering 7561 continue; 7562 } else if (resolveForStart 7563 && (intent.isWebIntent() 7564 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) 7565 && intent.getPackage() == null 7566 && intent.getComponent() == null) { 7567 // ephemeral apps can launch other ephemeral apps indirectly 7568 continue; 7569 } 7570 // allow activities that have been explicitly exposed to ephemeral apps 7571 final boolean isEphemeralApp = info.activityInfo.applicationInfo.isInstantApp(); 7572 if (!isEphemeralApp 7573 && ((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 7574 continue; 7575 } 7576 resolveInfos.remove(i); 7577 } 7578 return resolveInfos; 7579 } 7580 7581 /** 7582 * Returns the activity component that can handle install failures. 7583 * <p>By default, the instant application installer handles failures. However, an 7584 * application may want to handle failures on its own. Applications do this by 7585 * creating an activity with an intent filter that handles the action 7586 * {@link Intent#ACTION_INSTALL_FAILURE}. 7587 */ 7588 private @Nullable ComponentName findInstallFailureActivity( 7589 String packageName, int filterCallingUid, int userId) { 7590 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 7591 failureActivityIntent.setPackage(packageName); 7592 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 7593 final List<ResolveInfo> result = queryIntentActivitiesInternal( 7594 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, filterCallingUid, userId, 7595 false /*resolveForStart*/, false /*allowDynamicSplits*/); 7596 final int NR = result.size(); 7597 if (NR > 0) { 7598 for (int i = 0; i < NR; i++) { 7599 final ResolveInfo info = result.get(i); 7600 if (info.activityInfo.splitName != null) { 7601 continue; 7602 } 7603 return new ComponentName(packageName, info.activityInfo.name); 7604 } 7605 } 7606 return null; 7607 } 7608 7609 /** 7610 * @param resolveInfos list of resolve infos in descending priority order 7611 * @return if the list contains a resolve info with non-negative priority 7612 */ 7613 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 7614 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 7615 } 7616 7617 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 7618 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 7619 int userId) { 7620 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 7621 7622 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7623 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 7624 candidates.size()); 7625 } 7626 7627 final ArrayList<ResolveInfo> result = new ArrayList<>(); 7628 final ArrayList<ResolveInfo> alwaysList = new ArrayList<>(); 7629 final ArrayList<ResolveInfo> undefinedList = new ArrayList<>(); 7630 final ArrayList<ResolveInfo> alwaysAskList = new ArrayList<>(); 7631 final ArrayList<ResolveInfo> neverList = new ArrayList<>(); 7632 final ArrayList<ResolveInfo> matchAllList = new ArrayList<>(); 7633 7634 synchronized (mPackages) { 7635 final int count = candidates.size(); 7636 // First, try to use linked apps. Partition the candidates into four lists: 7637 // one for the final results, one for the "do not use ever", one for "undefined status" 7638 // and finally one for "browser app type". 7639 for (int n=0; n<count; n++) { 7640 ResolveInfo info = candidates.get(n); 7641 String packageName = info.activityInfo.packageName; 7642 PackageSetting ps = mSettings.mPackages.get(packageName); 7643 if (ps != null) { 7644 // Add to the special match all list (Browser use case) 7645 if (info.handleAllWebDataURI) { 7646 matchAllList.add(info); 7647 continue; 7648 } 7649 // Try to get the status from User settings first 7650 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 7651 int status = (int)(packedStatus >> 32); 7652 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 7653 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 7654 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7655 Slog.i(TAG, " + always: " + info.activityInfo.packageName 7656 + " : linkgen=" + linkGeneration); 7657 } 7658 // Use link-enabled generation as preferredOrder, i.e. 7659 // prefer newly-enabled over earlier-enabled. 7660 info.preferredOrder = linkGeneration; 7661 alwaysList.add(info); 7662 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 7663 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7664 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 7665 } 7666 neverList.add(info); 7667 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 7668 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7669 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 7670 } 7671 alwaysAskList.add(info); 7672 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 7673 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 7674 if (DEBUG_DOMAIN_VERIFICATION || debug) { 7675 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 7676 } 7677 undefinedList.add(info); 7678 } 7679 } 7680 } 7681 7682 // We'll want to include browser possibilities in a few cases 7683 boolean includeBrowser = false; 7684 7685 // First try to add the "always" resolution(s) for the current user, if any 7686 if (alwaysList.size() > 0) { 7687 result.addAll(alwaysList); 7688 } else { 7689 // Add all undefined apps as we want them to appear in the disambiguation dialog. 7690 result.addAll(undefinedList); 7691 // Maybe add one for the other profile. 7692 if (xpDomainInfo != null && ( 7693 xpDomainInfo.bestDomainVerificationStatus 7694 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 7695 result.add(xpDomainInfo.resolveInfo); 7696 } 7697 includeBrowser = true; 7698 } 7699 7700 // The presence of any 'always ask' alternatives means we'll also offer browsers. 7701 // If there were 'always' entries their preferred order has been set, so we also 7702 // back that off to make the alternatives equivalent 7703 if (alwaysAskList.size() > 0) { 7704 for (ResolveInfo i : result) { 7705 i.preferredOrder = 0; 7706 } 7707 result.addAll(alwaysAskList); 7708 includeBrowser = true; 7709 } 7710 7711 if (includeBrowser) { 7712 // Also add browsers (all of them or only the default one) 7713 if (DEBUG_DOMAIN_VERIFICATION) { 7714 Slog.v(TAG, " ...including browsers in candidate set"); 7715 } 7716 if ((matchFlags & MATCH_ALL) != 0) { 7717 result.addAll(matchAllList); 7718 } else { 7719 // Browser/generic handling case. If there's a default browser, go straight 7720 // to that (but only if there is no other higher-priority match). 7721 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 7722 int maxMatchPrio = 0; 7723 ResolveInfo defaultBrowserMatch = null; 7724 final int numCandidates = matchAllList.size(); 7725 for (int n = 0; n < numCandidates; n++) { 7726 ResolveInfo info = matchAllList.get(n); 7727 // track the highest overall match priority... 7728 if (info.priority > maxMatchPrio) { 7729 maxMatchPrio = info.priority; 7730 } 7731 // ...and the highest-priority default browser match 7732 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 7733 if (defaultBrowserMatch == null 7734 || (defaultBrowserMatch.priority < info.priority)) { 7735 if (debug) { 7736 Slog.v(TAG, "Considering default browser match " + info); 7737 } 7738 defaultBrowserMatch = info; 7739 } 7740 } 7741 } 7742 if (defaultBrowserMatch != null 7743 && defaultBrowserMatch.priority >= maxMatchPrio 7744 && !TextUtils.isEmpty(defaultBrowserPackageName)) 7745 { 7746 if (debug) { 7747 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 7748 } 7749 result.add(defaultBrowserMatch); 7750 } else { 7751 result.addAll(matchAllList); 7752 } 7753 } 7754 7755 // If there is nothing selected, add all candidates and remove the ones that the user 7756 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 7757 if (result.size() == 0) { 7758 result.addAll(candidates); 7759 result.removeAll(neverList); 7760 } 7761 } 7762 } 7763 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 7764 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 7765 result.size()); 7766 for (ResolveInfo info : result) { 7767 Slog.v(TAG, " + " + info.activityInfo); 7768 } 7769 } 7770 return result; 7771 } 7772 7773 // Returns a packed value as a long: 7774 // 7775 // high 'int'-sized word: link status: undefined/ask/never/always. 7776 // low 'int'-sized word: relative priority among 'always' results. 7777 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 7778 long result = ps.getDomainVerificationStatusForUser(userId); 7779 // if none available, get the master status 7780 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 7781 if (ps.getIntentFilterVerificationInfo() != null) { 7782 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 7783 } 7784 } 7785 return result; 7786 } 7787 7788 private ResolveInfo querySkipCurrentProfileIntents( 7789 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7790 int flags, int sourceUserId) { 7791 if (matchingFilters != null) { 7792 int size = matchingFilters.size(); 7793 for (int i = 0; i < size; i ++) { 7794 CrossProfileIntentFilter filter = matchingFilters.get(i); 7795 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 7796 // Checking if there are activities in the target user that can handle the 7797 // intent. 7798 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7799 resolvedType, flags, sourceUserId); 7800 if (resolveInfo != null) { 7801 return resolveInfo; 7802 } 7803 } 7804 } 7805 } 7806 return null; 7807 } 7808 7809 // Return matching ResolveInfo in target user if any. 7810 private ResolveInfo queryCrossProfileIntents( 7811 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 7812 int flags, int sourceUserId, boolean matchInCurrentProfile) { 7813 if (matchingFilters != null) { 7814 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 7815 // match the same intent. For performance reasons, it is better not to 7816 // run queryIntent twice for the same userId 7817 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 7818 int size = matchingFilters.size(); 7819 for (int i = 0; i < size; i++) { 7820 CrossProfileIntentFilter filter = matchingFilters.get(i); 7821 int targetUserId = filter.getTargetUserId(); 7822 boolean skipCurrentProfile = 7823 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 7824 boolean skipCurrentProfileIfNoMatchFound = 7825 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 7826 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 7827 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 7828 // Checking if there are activities in the target user that can handle the 7829 // intent. 7830 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 7831 resolvedType, flags, sourceUserId); 7832 if (resolveInfo != null) return resolveInfo; 7833 alreadyTriedUserIds.put(targetUserId, true); 7834 } 7835 } 7836 } 7837 return null; 7838 } 7839 7840 /** 7841 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 7842 * will forward the intent to the filter's target user. 7843 * Otherwise, returns null. 7844 */ 7845 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 7846 String resolvedType, int flags, int sourceUserId) { 7847 int targetUserId = filter.getTargetUserId(); 7848 List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(intent, 7849 resolvedType, flags, targetUserId); 7850 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 7851 // If all the matches in the target profile are suspended, return null. 7852 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 7853 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 7854 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 7855 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 7856 targetUserId); 7857 } 7858 } 7859 } 7860 return null; 7861 } 7862 7863 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 7864 int sourceUserId, int targetUserId) { 7865 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 7866 long ident = Binder.clearCallingIdentity(); 7867 boolean targetIsProfile; 7868 try { 7869 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 7870 } finally { 7871 Binder.restoreCallingIdentity(ident); 7872 } 7873 String className; 7874 if (targetIsProfile) { 7875 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 7876 } else { 7877 className = FORWARD_INTENT_TO_PARENT; 7878 } 7879 ComponentName forwardingActivityComponentName = new ComponentName( 7880 mAndroidApplication.packageName, className); 7881 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 7882 sourceUserId); 7883 if (!targetIsProfile) { 7884 forwardingActivityInfo.showUserIcon = targetUserId; 7885 forwardingResolveInfo.noResourceId = true; 7886 } 7887 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 7888 forwardingResolveInfo.priority = 0; 7889 forwardingResolveInfo.preferredOrder = 0; 7890 forwardingResolveInfo.match = 0; 7891 forwardingResolveInfo.isDefault = true; 7892 forwardingResolveInfo.filter = filter; 7893 forwardingResolveInfo.targetUserId = targetUserId; 7894 return forwardingResolveInfo; 7895 } 7896 7897 @Override 7898 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 7899 Intent[] specifics, String[] specificTypes, Intent intent, 7900 String resolvedType, int flags, int userId) { 7901 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 7902 specificTypes, intent, resolvedType, flags, userId)); 7903 } 7904 7905 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 7906 Intent[] specifics, String[] specificTypes, Intent intent, 7907 String resolvedType, int flags, int userId) { 7908 if (!sUserManager.exists(userId)) return Collections.emptyList(); 7909 final int callingUid = Binder.getCallingUid(); 7910 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 7911 false /*includeInstantApps*/); 7912 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 7913 false /*requireFullPermission*/, false /*checkShell*/, 7914 "query intent activity options"); 7915 final String resultsAction = intent.getAction(); 7916 7917 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 7918 | PackageManager.GET_RESOLVED_FILTER, userId); 7919 7920 if (DEBUG_INTENT_MATCHING) { 7921 Log.v(TAG, "Query " + intent + ": " + results); 7922 } 7923 7924 int specificsPos = 0; 7925 int N; 7926 7927 // todo: note that the algorithm used here is O(N^2). This 7928 // isn't a problem in our current environment, but if we start running 7929 // into situations where we have more than 5 or 10 matches then this 7930 // should probably be changed to something smarter... 7931 7932 // First we go through and resolve each of the specific items 7933 // that were supplied, taking care of removing any corresponding 7934 // duplicate items in the generic resolve list. 7935 if (specifics != null) { 7936 for (int i=0; i<specifics.length; i++) { 7937 final Intent sintent = specifics[i]; 7938 if (sintent == null) { 7939 continue; 7940 } 7941 7942 if (DEBUG_INTENT_MATCHING) { 7943 Log.v(TAG, "Specific #" + i + ": " + sintent); 7944 } 7945 7946 String action = sintent.getAction(); 7947 if (resultsAction != null && resultsAction.equals(action)) { 7948 // If this action was explicitly requested, then don't 7949 // remove things that have it. 7950 action = null; 7951 } 7952 7953 ResolveInfo ri = null; 7954 ActivityInfo ai = null; 7955 7956 ComponentName comp = sintent.getComponent(); 7957 if (comp == null) { 7958 ri = resolveIntent( 7959 sintent, 7960 specificTypes != null ? specificTypes[i] : null, 7961 flags, userId); 7962 if (ri == null) { 7963 continue; 7964 } 7965 if (ri == mResolveInfo) { 7966 // ACK! Must do something better with this. 7967 } 7968 ai = ri.activityInfo; 7969 comp = new ComponentName(ai.applicationInfo.packageName, 7970 ai.name); 7971 } else { 7972 ai = getActivityInfo(comp, flags, userId); 7973 if (ai == null) { 7974 continue; 7975 } 7976 } 7977 7978 // Look for any generic query activities that are duplicates 7979 // of this specific one, and remove them from the results. 7980 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 7981 N = results.size(); 7982 int j; 7983 for (j=specificsPos; j<N; j++) { 7984 ResolveInfo sri = results.get(j); 7985 if ((sri.activityInfo.name.equals(comp.getClassName()) 7986 && sri.activityInfo.applicationInfo.packageName.equals( 7987 comp.getPackageName())) 7988 || (action != null && sri.filter.matchAction(action))) { 7989 results.remove(j); 7990 if (DEBUG_INTENT_MATCHING) Log.v( 7991 TAG, "Removing duplicate item from " + j 7992 + " due to specific " + specificsPos); 7993 if (ri == null) { 7994 ri = sri; 7995 } 7996 j--; 7997 N--; 7998 } 7999 } 8000 8001 // Add this specific item to its proper place. 8002 if (ri == null) { 8003 ri = new ResolveInfo(); 8004 ri.activityInfo = ai; 8005 } 8006 results.add(specificsPos, ri); 8007 ri.specificIndex = i; 8008 specificsPos++; 8009 } 8010 } 8011 8012 // Now we go through the remaining generic results and remove any 8013 // duplicate actions that are found here. 8014 N = results.size(); 8015 for (int i=specificsPos; i<N-1; i++) { 8016 final ResolveInfo rii = results.get(i); 8017 if (rii.filter == null) { 8018 continue; 8019 } 8020 8021 // Iterate over all of the actions of this result's intent 8022 // filter... typically this should be just one. 8023 final Iterator<String> it = rii.filter.actionsIterator(); 8024 if (it == null) { 8025 continue; 8026 } 8027 while (it.hasNext()) { 8028 final String action = it.next(); 8029 if (resultsAction != null && resultsAction.equals(action)) { 8030 // If this action was explicitly requested, then don't 8031 // remove things that have it. 8032 continue; 8033 } 8034 for (int j=i+1; j<N; j++) { 8035 final ResolveInfo rij = results.get(j); 8036 if (rij.filter != null && rij.filter.hasAction(action)) { 8037 results.remove(j); 8038 if (DEBUG_INTENT_MATCHING) Log.v( 8039 TAG, "Removing duplicate item from " + j 8040 + " due to action " + action + " at " + i); 8041 j--; 8042 N--; 8043 } 8044 } 8045 } 8046 8047 // If the caller didn't request filter information, drop it now 8048 // so we don't have to marshall/unmarshall it. 8049 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8050 rii.filter = null; 8051 } 8052 } 8053 8054 // Filter out the caller activity if so requested. 8055 if (caller != null) { 8056 N = results.size(); 8057 for (int i=0; i<N; i++) { 8058 ActivityInfo ainfo = results.get(i).activityInfo; 8059 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 8060 && caller.getClassName().equals(ainfo.name)) { 8061 results.remove(i); 8062 break; 8063 } 8064 } 8065 } 8066 8067 // If the caller didn't request filter information, 8068 // drop them now so we don't have to 8069 // marshall/unmarshall it. 8070 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 8071 N = results.size(); 8072 for (int i=0; i<N; i++) { 8073 results.get(i).filter = null; 8074 } 8075 } 8076 8077 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 8078 return results; 8079 } 8080 8081 @Override 8082 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 8083 String resolvedType, int flags, int userId) { 8084 return new ParceledListSlice<>( 8085 queryIntentReceiversInternal(intent, resolvedType, flags, userId, 8086 false /*allowDynamicSplits*/)); 8087 } 8088 8089 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 8090 String resolvedType, int flags, int userId, boolean allowDynamicSplits) { 8091 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8092 final int callingUid = Binder.getCallingUid(); 8093 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8094 false /*requireFullPermission*/, false /*checkShell*/, 8095 "query intent receivers"); 8096 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8097 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8098 false /*includeInstantApps*/); 8099 ComponentName comp = intent.getComponent(); 8100 if (comp == null) { 8101 if (intent.getSelector() != null) { 8102 intent = intent.getSelector(); 8103 comp = intent.getComponent(); 8104 } 8105 } 8106 if (comp != null) { 8107 final List<ResolveInfo> list = new ArrayList<>(1); 8108 final ActivityInfo ai = getReceiverInfo(comp, flags, userId); 8109 if (ai != null) { 8110 // When specifying an explicit component, we prevent the activity from being 8111 // used when either 1) the calling package is normal and the activity is within 8112 // an instant application or 2) the calling package is ephemeral and the 8113 // activity is not visible to instant applications. 8114 final boolean matchInstantApp = 8115 (flags & PackageManager.MATCH_INSTANT) != 0; 8116 final boolean matchVisibleToInstantAppOnly = 8117 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8118 final boolean matchExplicitlyVisibleOnly = 8119 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 8120 final boolean isCallerInstantApp = 8121 instantAppPkgName != null; 8122 final boolean isTargetSameInstantApp = 8123 comp.getPackageName().equals(instantAppPkgName); 8124 final boolean isTargetInstantApp = 8125 (ai.applicationInfo.privateFlags 8126 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8127 final boolean isTargetVisibleToInstantApp = 8128 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 8129 final boolean isTargetExplicitlyVisibleToInstantApp = 8130 isTargetVisibleToInstantApp 8131 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) == 0; 8132 final boolean isTargetHiddenFromInstantApp = 8133 !isTargetVisibleToInstantApp 8134 || (matchExplicitlyVisibleOnly && !isTargetExplicitlyVisibleToInstantApp); 8135 final boolean blockResolution = 8136 !isTargetSameInstantApp 8137 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8138 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8139 && isTargetHiddenFromInstantApp)); 8140 if (!blockResolution) { 8141 ResolveInfo ri = new ResolveInfo(); 8142 ri.activityInfo = ai; 8143 list.add(ri); 8144 } 8145 } 8146 return applyPostResolutionFilter( 8147 list, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8148 intent); 8149 } 8150 8151 // reader 8152 synchronized (mPackages) { 8153 String pkgName = intent.getPackage(); 8154 if (pkgName == null) { 8155 final List<ResolveInfo> result = 8156 mComponentResolver.queryReceivers(intent, resolvedType, flags, userId); 8157 return applyPostResolutionFilter( 8158 result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8159 intent); 8160 } 8161 final PackageParser.Package pkg = mPackages.get(pkgName); 8162 if (pkg != null) { 8163 final List<ResolveInfo> result = mComponentResolver.queryReceivers( 8164 intent, resolvedType, flags, pkg.receivers, userId); 8165 return applyPostResolutionFilter( 8166 result, instantAppPkgName, allowDynamicSplits, callingUid, false, userId, 8167 intent); 8168 } 8169 return Collections.emptyList(); 8170 } 8171 } 8172 8173 @Override 8174 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 8175 final int callingUid = Binder.getCallingUid(); 8176 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 8177 } 8178 8179 private ResolveInfo resolveServiceInternal(Intent intent, String resolvedType, int flags, 8180 int userId, int callingUid) { 8181 if (!sUserManager.exists(userId)) return null; 8182 flags = updateFlagsForResolve( 8183 flags, userId, intent, callingUid, false /*includeInstantApps*/); 8184 List<ResolveInfo> query = queryIntentServicesInternal( 8185 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/); 8186 if (query != null) { 8187 if (query.size() >= 1) { 8188 // If there is more than one service with the same priority, 8189 // just arbitrarily pick the first one. 8190 return query.get(0); 8191 } 8192 } 8193 return null; 8194 } 8195 8196 @Override 8197 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 8198 String resolvedType, int flags, int userId) { 8199 final int callingUid = Binder.getCallingUid(); 8200 return new ParceledListSlice<>(queryIntentServicesInternal( 8201 intent, resolvedType, flags, userId, callingUid, false /*includeInstantApps*/)); 8202 } 8203 8204 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 8205 String resolvedType, int flags, int userId, int callingUid, 8206 boolean includeInstantApps) { 8207 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8208 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8209 false /*requireFullPermission*/, false /*checkShell*/, 8210 "query intent receivers"); 8211 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8212 flags = updateFlagsForResolve(flags, userId, intent, callingUid, includeInstantApps); 8213 ComponentName comp = intent.getComponent(); 8214 if (comp == null) { 8215 if (intent.getSelector() != null) { 8216 intent = intent.getSelector(); 8217 comp = intent.getComponent(); 8218 } 8219 } 8220 if (comp != null) { 8221 final List<ResolveInfo> list = new ArrayList<>(1); 8222 final ServiceInfo si = getServiceInfo(comp, flags, userId); 8223 if (si != null) { 8224 // When specifying an explicit component, we prevent the service from being 8225 // used when either 1) the service is in an instant application and the 8226 // caller is not the same instant application or 2) the calling package is 8227 // ephemeral and the activity is not visible to ephemeral applications. 8228 final boolean matchInstantApp = 8229 (flags & PackageManager.MATCH_INSTANT) != 0; 8230 final boolean matchVisibleToInstantAppOnly = 8231 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8232 final boolean isCallerInstantApp = 8233 instantAppPkgName != null; 8234 final boolean isTargetSameInstantApp = 8235 comp.getPackageName().equals(instantAppPkgName); 8236 final boolean isTargetInstantApp = 8237 (si.applicationInfo.privateFlags 8238 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8239 final boolean isTargetHiddenFromInstantApp = 8240 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8241 final boolean blockResolution = 8242 !isTargetSameInstantApp 8243 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8244 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8245 && isTargetHiddenFromInstantApp)); 8246 if (!blockResolution) { 8247 final ResolveInfo ri = new ResolveInfo(); 8248 ri.serviceInfo = si; 8249 list.add(ri); 8250 } 8251 } 8252 return list; 8253 } 8254 8255 // reader 8256 synchronized (mPackages) { 8257 String pkgName = intent.getPackage(); 8258 if (pkgName == null) { 8259 return applyPostServiceResolutionFilter( 8260 mComponentResolver.queryServices(intent, resolvedType, flags, userId), 8261 instantAppPkgName); 8262 } 8263 final PackageParser.Package pkg = mPackages.get(pkgName); 8264 if (pkg != null) { 8265 return applyPostServiceResolutionFilter( 8266 mComponentResolver.queryServices(intent, resolvedType, flags, pkg.services, 8267 userId), 8268 instantAppPkgName); 8269 } 8270 return Collections.emptyList(); 8271 } 8272 } 8273 8274 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 8275 String instantAppPkgName) { 8276 if (instantAppPkgName == null) { 8277 return resolveInfos; 8278 } 8279 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8280 final ResolveInfo info = resolveInfos.get(i); 8281 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 8282 // allow services that are defined in the provided package 8283 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 8284 if (info.serviceInfo.splitName != null 8285 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 8286 info.serviceInfo.splitName)) { 8287 // requested service is defined in a split that hasn't been installed yet. 8288 // add the installer to the resolve list 8289 if (DEBUG_INSTANT) { 8290 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8291 } 8292 final ResolveInfo installerInfo = new ResolveInfo( 8293 mInstantAppInstallerInfo); 8294 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8295 null /* installFailureActivity */, 8296 info.serviceInfo.packageName, 8297 info.serviceInfo.applicationInfo.longVersionCode, 8298 info.serviceInfo.splitName); 8299 // add a non-generic filter 8300 installerInfo.filter = new IntentFilter(); 8301 // load resources from the correct package 8302 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8303 resolveInfos.set(i, installerInfo); 8304 } 8305 continue; 8306 } 8307 // allow services that have been explicitly exposed to ephemeral apps 8308 if (!isEphemeralApp 8309 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8310 continue; 8311 } 8312 resolveInfos.remove(i); 8313 } 8314 return resolveInfos; 8315 } 8316 8317 @Override 8318 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 8319 String resolvedType, int flags, int userId) { 8320 return new ParceledListSlice<>( 8321 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 8322 } 8323 8324 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 8325 Intent intent, String resolvedType, int flags, int userId) { 8326 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8327 final int callingUid = Binder.getCallingUid(); 8328 final String instantAppPkgName = getInstantAppPackageName(callingUid); 8329 flags = updateFlagsForResolve(flags, userId, intent, callingUid, 8330 false /*includeInstantApps*/); 8331 ComponentName comp = intent.getComponent(); 8332 if (comp == null) { 8333 if (intent.getSelector() != null) { 8334 intent = intent.getSelector(); 8335 comp = intent.getComponent(); 8336 } 8337 } 8338 if (comp != null) { 8339 final List<ResolveInfo> list = new ArrayList<>(1); 8340 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 8341 if (pi != null) { 8342 // When specifying an explicit component, we prevent the provider from being 8343 // used when either 1) the provider is in an instant application and the 8344 // caller is not the same instant application or 2) the calling package is an 8345 // instant application and the provider is not visible to instant applications. 8346 final boolean matchInstantApp = 8347 (flags & PackageManager.MATCH_INSTANT) != 0; 8348 final boolean matchVisibleToInstantAppOnly = 8349 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 8350 final boolean isCallerInstantApp = 8351 instantAppPkgName != null; 8352 final boolean isTargetSameInstantApp = 8353 comp.getPackageName().equals(instantAppPkgName); 8354 final boolean isTargetInstantApp = 8355 (pi.applicationInfo.privateFlags 8356 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 8357 final boolean isTargetHiddenFromInstantApp = 8358 (pi.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 8359 final boolean blockResolution = 8360 !isTargetSameInstantApp 8361 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 8362 || (matchVisibleToInstantAppOnly && isCallerInstantApp 8363 && isTargetHiddenFromInstantApp)); 8364 if (!blockResolution) { 8365 final ResolveInfo ri = new ResolveInfo(); 8366 ri.providerInfo = pi; 8367 list.add(ri); 8368 } 8369 } 8370 return list; 8371 } 8372 8373 // reader 8374 synchronized (mPackages) { 8375 String pkgName = intent.getPackage(); 8376 if (pkgName == null) { 8377 return applyPostContentProviderResolutionFilter( 8378 mComponentResolver.queryProviders(intent, resolvedType, flags, userId), 8379 instantAppPkgName); 8380 } 8381 final PackageParser.Package pkg = mPackages.get(pkgName); 8382 if (pkg != null) { 8383 return applyPostContentProviderResolutionFilter( 8384 mComponentResolver.queryProviders(intent, resolvedType, flags, 8385 pkg.providers, userId), 8386 instantAppPkgName); 8387 } 8388 return Collections.emptyList(); 8389 } 8390 } 8391 8392 private List<ResolveInfo> applyPostContentProviderResolutionFilter( 8393 List<ResolveInfo> resolveInfos, String instantAppPkgName) { 8394 if (instantAppPkgName == null) { 8395 return resolveInfos; 8396 } 8397 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 8398 final ResolveInfo info = resolveInfos.get(i); 8399 final boolean isEphemeralApp = info.providerInfo.applicationInfo.isInstantApp(); 8400 // allow providers that are defined in the provided package 8401 if (isEphemeralApp && instantAppPkgName.equals(info.providerInfo.packageName)) { 8402 if (info.providerInfo.splitName != null 8403 && !ArrayUtils.contains(info.providerInfo.applicationInfo.splitNames, 8404 info.providerInfo.splitName)) { 8405 // requested provider is defined in a split that hasn't been installed yet. 8406 // add the installer to the resolve list 8407 if (DEBUG_INSTANT) { 8408 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 8409 } 8410 final ResolveInfo installerInfo = new ResolveInfo( 8411 mInstantAppInstallerInfo); 8412 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 8413 null /*failureActivity*/, 8414 info.providerInfo.packageName, 8415 info.providerInfo.applicationInfo.longVersionCode, 8416 info.providerInfo.splitName); 8417 // add a non-generic filter 8418 installerInfo.filter = new IntentFilter(); 8419 // load resources from the correct package 8420 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 8421 resolveInfos.set(i, installerInfo); 8422 } 8423 continue; 8424 } 8425 // allow providers that have been explicitly exposed to instant applications 8426 if (!isEphemeralApp 8427 && ((info.providerInfo.flags & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0)) { 8428 continue; 8429 } 8430 resolveInfos.remove(i); 8431 } 8432 return resolveInfos; 8433 } 8434 8435 @Override 8436 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 8437 final int callingUid = Binder.getCallingUid(); 8438 if (getInstantAppPackageName(callingUid) != null) { 8439 return ParceledListSlice.emptyList(); 8440 } 8441 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8442 flags = updateFlagsForPackage(flags, userId, null); 8443 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8444 final boolean listApex = (flags & MATCH_APEX) != 0; 8445 final boolean listFactory = (flags & MATCH_FACTORY_ONLY) != 0; 8446 8447 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 8448 false /* requireFullPermission */, false /* checkShell */, 8449 "get installed packages"); 8450 8451 // writer 8452 synchronized (mPackages) { 8453 ArrayList<PackageInfo> list; 8454 if (listUninstalled) { 8455 list = new ArrayList<>(mSettings.mPackages.size()); 8456 for (PackageSetting ps : mSettings.mPackages.values()) { 8457 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8458 continue; 8459 } 8460 if (filterAppAccessLPr(ps, callingUid, userId)) { 8461 continue; 8462 } 8463 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8464 if (pi != null) { 8465 list.add(pi); 8466 } 8467 } 8468 } else { 8469 list = new ArrayList<>(mPackages.size()); 8470 for (PackageParser.Package p : mPackages.values()) { 8471 final PackageSetting ps = (PackageSetting) p.mExtras; 8472 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8473 continue; 8474 } 8475 if (filterAppAccessLPr(ps, callingUid, userId)) { 8476 continue; 8477 } 8478 final PackageInfo pi = generatePackageInfo((PackageSetting) 8479 p.mExtras, flags, userId); 8480 if (pi != null) { 8481 list.add(pi); 8482 } 8483 } 8484 } 8485 if (listApex) { 8486 if (listFactory) { 8487 list.addAll(mApexManager.getFactoryPackages()); 8488 } else { 8489 list.addAll(mApexManager.getActivePackages()); 8490 } 8491 if (listUninstalled) { 8492 list.addAll(mApexManager.getInactivePackages()); 8493 } 8494 } 8495 return new ParceledListSlice<>(list); 8496 } 8497 } 8498 8499 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 8500 String[] permissions, boolean[] tmp, int flags, int userId) { 8501 int numMatch = 0; 8502 final PermissionsState permissionsState = ps.getPermissionsState(); 8503 for (int i=0; i<permissions.length; i++) { 8504 final String permission = permissions[i]; 8505 if (permissionsState.hasPermission(permission, userId)) { 8506 tmp[i] = true; 8507 numMatch++; 8508 } else { 8509 tmp[i] = false; 8510 } 8511 } 8512 if (numMatch == 0) { 8513 return; 8514 } 8515 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 8516 8517 // The above might return null in cases of uninstalled apps or install-state 8518 // skew across users/profiles. 8519 if (pi != null) { 8520 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 8521 if (numMatch == permissions.length) { 8522 pi.requestedPermissions = permissions; 8523 } else { 8524 pi.requestedPermissions = new String[numMatch]; 8525 numMatch = 0; 8526 for (int i=0; i<permissions.length; i++) { 8527 if (tmp[i]) { 8528 pi.requestedPermissions[numMatch] = permissions[i]; 8529 numMatch++; 8530 } 8531 } 8532 } 8533 } 8534 list.add(pi); 8535 } 8536 } 8537 8538 @Override 8539 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 8540 String[] permissions, int flags, int userId) { 8541 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8542 flags = updateFlagsForPackage(flags, userId, permissions); 8543 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8544 true /* requireFullPermission */, false /* checkShell */, 8545 "get packages holding permissions"); 8546 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8547 8548 // writer 8549 synchronized (mPackages) { 8550 ArrayList<PackageInfo> list = new ArrayList<>(); 8551 boolean[] tmpBools = new boolean[permissions.length]; 8552 if (listUninstalled) { 8553 for (PackageSetting ps : mSettings.mPackages.values()) { 8554 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8555 userId); 8556 } 8557 } else { 8558 for (PackageParser.Package pkg : mPackages.values()) { 8559 PackageSetting ps = (PackageSetting)pkg.mExtras; 8560 if (ps != null) { 8561 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 8562 userId); 8563 } 8564 } 8565 } 8566 8567 return new ParceledListSlice<>(list); 8568 } 8569 } 8570 8571 @Override 8572 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 8573 final int callingUid = Binder.getCallingUid(); 8574 return new ParceledListSlice<>( 8575 getInstalledApplicationsListInternal(flags, userId, callingUid)); 8576 } 8577 8578 private List<ApplicationInfo> getInstalledApplicationsListInternal(int flags, int userId, 8579 int callingUid) { 8580 if (getInstantAppPackageName(callingUid) != null) { 8581 return Collections.emptyList(); 8582 } 8583 if (!sUserManager.exists(userId)) return Collections.emptyList(); 8584 flags = updateFlagsForApplication(flags, userId, null); 8585 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 8586 8587 mPermissionManager.enforceCrossUserPermission( 8588 callingUid, 8589 userId, 8590 false /* requireFullPermission */, 8591 false /* checkShell */, 8592 "get installed application info"); 8593 8594 // writer 8595 synchronized (mPackages) { 8596 ArrayList<ApplicationInfo> list; 8597 if (listUninstalled) { 8598 list = new ArrayList<>(mSettings.mPackages.size()); 8599 for (PackageSetting ps : mSettings.mPackages.values()) { 8600 ApplicationInfo ai; 8601 int effectiveFlags = flags; 8602 if (ps.isSystem()) { 8603 effectiveFlags |= PackageManager.MATCH_ANY_USER; 8604 } 8605 if (ps.pkg != null) { 8606 if (filterSharedLibPackageLPr(ps, callingUid, userId, flags)) { 8607 continue; 8608 } 8609 if (filterAppAccessLPr(ps, callingUid, userId)) { 8610 continue; 8611 } 8612 ai = PackageParser.generateApplicationInfo(ps.pkg, effectiveFlags, 8613 ps.readUserState(userId), userId); 8614 if (ai != null) { 8615 ai.packageName = resolveExternalPackageNameLPr(ps.pkg); 8616 } 8617 } else { 8618 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 8619 // and already converts to externally visible package name 8620 ai = generateApplicationInfoFromSettingsLPw(ps.name, 8621 callingUid, effectiveFlags, userId); 8622 } 8623 if (ai != null) { 8624 list.add(ai); 8625 } 8626 } 8627 } else { 8628 list = new ArrayList<>(mPackages.size()); 8629 for (PackageParser.Package p : mPackages.values()) { 8630 if (p.mExtras != null) { 8631 PackageSetting ps = (PackageSetting) p.mExtras; 8632 if (filterSharedLibPackageLPr(ps, Binder.getCallingUid(), userId, flags)) { 8633 continue; 8634 } 8635 if (filterAppAccessLPr(ps, callingUid, userId)) { 8636 continue; 8637 } 8638 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8639 ps.readUserState(userId), userId); 8640 if (ai != null) { 8641 ai.packageName = resolveExternalPackageNameLPr(p); 8642 list.add(ai); 8643 } 8644 } 8645 } 8646 } 8647 8648 return list; 8649 } 8650 } 8651 8652 @Override 8653 public ParceledListSlice<InstantAppInfo> getInstantApps(int userId) { 8654 if (HIDE_EPHEMERAL_APIS) { 8655 return null; 8656 } 8657 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8658 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8659 "getEphemeralApplications"); 8660 } 8661 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8662 true /* requireFullPermission */, false /* checkShell */, 8663 "getEphemeralApplications"); 8664 synchronized (mPackages) { 8665 List<InstantAppInfo> instantApps = mInstantAppRegistry 8666 .getInstantAppsLPr(userId); 8667 if (instantApps != null) { 8668 return new ParceledListSlice<>(instantApps); 8669 } 8670 } 8671 return null; 8672 } 8673 8674 @Override 8675 public boolean isInstantApp(String packageName, int userId) { 8676 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8677 true /* requireFullPermission */, false /* checkShell */, 8678 "isInstantApp"); 8679 if (HIDE_EPHEMERAL_APIS) { 8680 return false; 8681 } 8682 8683 synchronized (mPackages) { 8684 int callingUid = Binder.getCallingUid(); 8685 if (Process.isIsolated(callingUid)) { 8686 callingUid = mIsolatedOwners.get(callingUid); 8687 } 8688 final PackageSetting ps = mSettings.mPackages.get(packageName); 8689 PackageParser.Package pkg = mPackages.get(packageName); 8690 final boolean returnAllowed = 8691 ps != null 8692 && (isCallerSameApp(packageName, callingUid) 8693 || canViewInstantApps(callingUid, userId) 8694 || mInstantAppRegistry.isInstantAccessGranted( 8695 userId, UserHandle.getAppId(callingUid), ps.appId)); 8696 if (returnAllowed) { 8697 return ps.getInstantApp(userId); 8698 } 8699 } 8700 return false; 8701 } 8702 8703 @Override 8704 public byte[] getInstantAppCookie(String packageName, int userId) { 8705 if (HIDE_EPHEMERAL_APIS) { 8706 return null; 8707 } 8708 8709 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8710 true /* requireFullPermission */, false /* checkShell */, 8711 "getInstantAppCookie"); 8712 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8713 return null; 8714 } 8715 synchronized (mPackages) { 8716 return mInstantAppRegistry.getInstantAppCookieLPw( 8717 packageName, userId); 8718 } 8719 } 8720 8721 @Override 8722 public boolean setInstantAppCookie(String packageName, byte[] cookie, int userId) { 8723 if (HIDE_EPHEMERAL_APIS) { 8724 return true; 8725 } 8726 8727 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8728 true /* requireFullPermission */, true /* checkShell */, 8729 "setInstantAppCookie"); 8730 if (!isCallerSameApp(packageName, Binder.getCallingUid())) { 8731 return false; 8732 } 8733 synchronized (mPackages) { 8734 return mInstantAppRegistry.setInstantAppCookieLPw( 8735 packageName, cookie, userId); 8736 } 8737 } 8738 8739 @Override 8740 public Bitmap getInstantAppIcon(String packageName, int userId) { 8741 if (HIDE_EPHEMERAL_APIS) { 8742 return null; 8743 } 8744 8745 if (!canViewInstantApps(Binder.getCallingUid(), userId)) { 8746 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_INSTANT_APPS, 8747 "getInstantAppIcon"); 8748 } 8749 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 8750 true /* requireFullPermission */, false /* checkShell */, 8751 "getInstantAppIcon"); 8752 8753 synchronized (mPackages) { 8754 return mInstantAppRegistry.getInstantAppIconLPw( 8755 packageName, userId); 8756 } 8757 } 8758 8759 private boolean isCallerSameApp(String packageName, int uid) { 8760 PackageParser.Package pkg = mPackages.get(packageName); 8761 return pkg != null 8762 && UserHandle.getAppId(uid) == pkg.applicationInfo.uid; 8763 } 8764 8765 @Override 8766 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 8767 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8768 return ParceledListSlice.emptyList(); 8769 } 8770 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 8771 } 8772 8773 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 8774 final ArrayList<ApplicationInfo> finalList = new ArrayList<>(); 8775 8776 // reader 8777 synchronized (mPackages) { 8778 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 8779 final int userId = UserHandle.getCallingUserId(); 8780 while (i.hasNext()) { 8781 final PackageParser.Package p = i.next(); 8782 if (p.applicationInfo == null) continue; 8783 8784 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 8785 && !p.applicationInfo.isDirectBootAware(); 8786 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 8787 && p.applicationInfo.isDirectBootAware(); 8788 8789 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 8790 && (!mSafeMode || isSystemApp(p)) 8791 && (matchesUnaware || matchesAware)) { 8792 PackageSetting ps = mSettings.mPackages.get(p.packageName); 8793 if (ps != null) { 8794 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 8795 ps.readUserState(userId), userId); 8796 if (ai != null) { 8797 finalList.add(ai); 8798 } 8799 } 8800 } 8801 } 8802 } 8803 8804 return finalList; 8805 } 8806 8807 @Override 8808 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 8809 return resolveContentProviderInternal(name, flags, userId); 8810 } 8811 8812 private ProviderInfo resolveContentProviderInternal(String name, int flags, int userId) { 8813 if (!sUserManager.exists(userId)) return null; 8814 flags = updateFlagsForComponent(flags, userId, name); 8815 final int callingUid = Binder.getCallingUid(); 8816 final ProviderInfo providerInfo = mComponentResolver.queryProvider(name, flags, userId); 8817 if (providerInfo == null) { 8818 return null; 8819 } 8820 if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) { 8821 return null; 8822 } 8823 synchronized (mPackages) { 8824 final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName); 8825 final ComponentName component = 8826 new ComponentName(providerInfo.packageName, providerInfo.name); 8827 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8828 return null; 8829 } 8830 return providerInfo; 8831 } 8832 } 8833 8834 /** 8835 * @deprecated 8836 */ 8837 @Deprecated 8838 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 8839 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 8840 return; 8841 } 8842 mComponentResolver.querySyncProviders( 8843 outNames, outInfo, mSafeMode, UserHandle.getCallingUserId()); 8844 } 8845 8846 @Override 8847 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 8848 int uid, int flags, String metaDataKey) { 8849 final int callingUid = Binder.getCallingUid(); 8850 final int userId = processName != null ? UserHandle.getUserId(uid) 8851 : UserHandle.getCallingUserId(); 8852 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 8853 flags = updateFlagsForComponent(flags, userId, processName); 8854 ArrayList<ProviderInfo> finalList = null; 8855 final List<ProviderInfo> matchList = 8856 mComponentResolver.queryProviders(processName, metaDataKey, uid, flags, userId); 8857 final int listSize = (matchList == null ? 0 : matchList.size()); 8858 synchronized (mPackages) { 8859 for (int i = 0; i < listSize; i++) { 8860 final ProviderInfo providerInfo = matchList.get(i); 8861 if (!mSettings.isEnabledAndMatchLPr(providerInfo, flags, userId)) { 8862 continue; 8863 } 8864 final PackageSetting ps = mSettings.mPackages.get(providerInfo.packageName); 8865 final ComponentName component = 8866 new ComponentName(providerInfo.packageName, providerInfo.name); 8867 if (filterAppAccessLPr(ps, callingUid, component, TYPE_PROVIDER, userId)) { 8868 continue; 8869 } 8870 if (finalList == null) { 8871 finalList = new ArrayList<>(listSize - i); 8872 } 8873 finalList.add(providerInfo); 8874 } 8875 } 8876 8877 if (finalList != null) { 8878 finalList.sort(sProviderInitOrderSorter); 8879 return new ParceledListSlice<>(finalList); 8880 } 8881 8882 return ParceledListSlice.emptyList(); 8883 } 8884 8885 @Override 8886 public InstrumentationInfo getInstrumentationInfo(ComponentName component, int flags) { 8887 // reader 8888 synchronized (mPackages) { 8889 final int callingUid = Binder.getCallingUid(); 8890 final int callingUserId = UserHandle.getUserId(callingUid); 8891 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 8892 if (ps == null) return null; 8893 if (filterAppAccessLPr(ps, callingUid, component, TYPE_UNKNOWN, callingUserId)) { 8894 return null; 8895 } 8896 final PackageParser.Instrumentation i = mInstrumentation.get(component); 8897 return PackageParser.generateInstrumentationInfo(i, flags); 8898 } 8899 } 8900 8901 @Override 8902 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 8903 String targetPackage, int flags) { 8904 final int callingUid = Binder.getCallingUid(); 8905 final int callingUserId = UserHandle.getUserId(callingUid); 8906 final PackageSetting ps = mSettings.mPackages.get(targetPackage); 8907 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 8908 return ParceledListSlice.emptyList(); 8909 } 8910 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 8911 } 8912 8913 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 8914 int flags) { 8915 ArrayList<InstrumentationInfo> finalList = new ArrayList<>(); 8916 8917 // reader 8918 synchronized (mPackages) { 8919 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 8920 while (i.hasNext()) { 8921 final PackageParser.Instrumentation p = i.next(); 8922 if (targetPackage == null 8923 || targetPackage.equals(p.info.targetPackage)) { 8924 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 8925 flags); 8926 if (ii != null) { 8927 finalList.add(ii); 8928 } 8929 } 8930 } 8931 } 8932 8933 return finalList; 8934 } 8935 8936 private void scanDirTracedLI(File scanDir, final int parseFlags, int scanFlags, long currentTime) { 8937 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir [" + scanDir.getAbsolutePath() + "]"); 8938 try { 8939 scanDirLI(scanDir, parseFlags, scanFlags, currentTime); 8940 } finally { 8941 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8942 } 8943 } 8944 8945 private void scanDirLI(File scanDir, int parseFlags, int scanFlags, long currentTime) { 8946 final File[] files = scanDir.listFiles(); 8947 if (ArrayUtils.isEmpty(files)) { 8948 Log.d(TAG, "No files in app dir " + scanDir); 8949 return; 8950 } 8951 8952 if (DEBUG_PACKAGE_SCANNING) { 8953 Log.d(TAG, "Scanning app dir " + scanDir + " scanFlags=" + scanFlags 8954 + " flags=0x" + Integer.toHexString(parseFlags)); 8955 } 8956 try (ParallelPackageParser parallelPackageParser = new ParallelPackageParser( 8957 mSeparateProcesses, mOnlyCore, mMetrics, mCacheDir, 8958 mParallelPackageParserCallback)) { 8959 // Submit files for parsing in parallel 8960 int fileCount = 0; 8961 for (File file : files) { 8962 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 8963 && !PackageInstallerService.isStageName(file.getName()); 8964 if (!isPackage) { 8965 // Ignore entries which are not packages 8966 continue; 8967 } 8968 parallelPackageParser.submit(file, parseFlags); 8969 fileCount++; 8970 } 8971 8972 // Process results one by one 8973 for (; fileCount > 0; fileCount--) { 8974 ParallelPackageParser.ParseResult parseResult = parallelPackageParser.take(); 8975 Throwable throwable = parseResult.throwable; 8976 int errorCode = PackageManager.INSTALL_SUCCEEDED; 8977 8978 if (throwable == null) { 8979 // TODO(toddke): move lower in the scan chain 8980 // Static shared libraries have synthetic package names 8981 if (parseResult.pkg.applicationInfo.isStaticSharedLibrary()) { 8982 renameStaticSharedLibraryPackage(parseResult.pkg); 8983 } 8984 try { 8985 scanPackageChildLI(parseResult.pkg, parseFlags, scanFlags, 8986 currentTime, null); 8987 } catch (PackageManagerException e) { 8988 errorCode = e.error; 8989 Slog.w(TAG, "Failed to scan " + parseResult.scanFile + ": " + e.getMessage()); 8990 } 8991 } else if (throwable instanceof PackageParser.PackageParserException) { 8992 PackageParser.PackageParserException e = (PackageParser.PackageParserException) 8993 throwable; 8994 errorCode = e.error; 8995 Slog.w(TAG, "Failed to parse " + parseResult.scanFile + ": " + e.getMessage()); 8996 } else { 8997 throw new IllegalStateException("Unexpected exception occurred while parsing " 8998 + parseResult.scanFile, throwable); 8999 } 9000 9001 // Delete invalid userdata apps 9002 if ((scanFlags & SCAN_AS_SYSTEM) == 0 && 9003 errorCode != PackageManager.INSTALL_SUCCEEDED) { 9004 logCriticalInfo(Log.WARN, 9005 "Deleting invalid package at " + parseResult.scanFile); 9006 removeCodePathLI(parseResult.scanFile); 9007 } 9008 } 9009 } 9010 } 9011 9012 public static void reportSettingsProblem(int priority, String msg) { 9013 logCriticalInfo(priority, msg); 9014 } 9015 9016 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, 9017 boolean forceCollect, boolean skipVerify) throws PackageManagerException { 9018 // When upgrading from pre-N MR1, verify the package time stamp using the package 9019 // directory and not the APK file. 9020 final long lastModifiedTime = mIsPreNMR1Upgrade 9021 ? new File(pkg.codePath).lastModified() : getLastModifiedTime(pkg); 9022 final VersionInfo settingsVersionForPackage = getSettingsVersionForPackage(pkg); 9023 if (ps != null && !forceCollect 9024 && ps.codePathString.equals(pkg.codePath) 9025 && ps.timeStamp == lastModifiedTime 9026 && !isCompatSignatureUpdateNeeded(settingsVersionForPackage) 9027 && !isRecoverSignatureUpdateNeeded(settingsVersionForPackage)) { 9028 if (ps.signatures.mSigningDetails.signatures != null 9029 && ps.signatures.mSigningDetails.signatures.length != 0 9030 && ps.signatures.mSigningDetails.signatureSchemeVersion 9031 != SignatureSchemeVersion.UNKNOWN) { 9032 // Optimization: reuse the existing cached signing data 9033 // if the package appears to be unchanged. 9034 pkg.mSigningDetails = 9035 new PackageParser.SigningDetails(ps.signatures.mSigningDetails); 9036 return; 9037 } 9038 9039 Slog.w(TAG, "PackageSetting for " + ps.name 9040 + " is missing signatures. Collecting certs again to recover them."); 9041 } else { 9042 Slog.i(TAG, pkg.codePath + " changed; collecting certs" + 9043 (forceCollect ? " (forced)" : "")); 9044 } 9045 9046 try { 9047 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "collectCertificates"); 9048 PackageParser.collectCertificates(pkg, skipVerify); 9049 } catch (PackageParserException e) { 9050 throw PackageManagerException.from(e); 9051 } finally { 9052 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9053 } 9054 } 9055 9056 /** 9057 * Clear the package profile if this was an upgrade and the package 9058 * version was updated. 9059 */ 9060 private void maybeClearProfilesForUpgradesLI( 9061 @Nullable PackageSetting originalPkgSetting, 9062 @NonNull PackageParser.Package currentPkg) { 9063 if (originalPkgSetting == null || !isDeviceUpgrading()) { 9064 return; 9065 } 9066 if (originalPkgSetting.versionCode == currentPkg.mVersionCode) { 9067 return; 9068 } 9069 9070 clearAppProfilesLIF(currentPkg, UserHandle.USER_ALL); 9071 if (DEBUG_INSTALL) { 9072 Slog.d(TAG, originalPkgSetting.name 9073 + " clear profile due to version change " 9074 + originalPkgSetting.versionCode + " != " 9075 + currentPkg.mVersionCode); 9076 } 9077 } 9078 9079 /** 9080 * Traces a package scan. 9081 * @see #scanPackageLI(File, int, int, long, UserHandle) 9082 */ 9083 @GuardedBy({"mInstallLock", "mPackages"}) 9084 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 9085 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 9086 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage [" + scanFile.toString() + "]"); 9087 try { 9088 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 9089 } finally { 9090 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9091 } 9092 } 9093 9094 /** 9095 * Scans a package and returns the newly parsed package. 9096 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 9097 */ 9098 @GuardedBy({"mInstallLock", "mPackages"}) 9099 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 9100 long currentTime, UserHandle user) throws PackageManagerException { 9101 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 9102 PackageParser pp = new PackageParser(); 9103 pp.setSeparateProcesses(mSeparateProcesses); 9104 pp.setOnlyCoreApps(mOnlyCore); 9105 pp.setDisplayMetrics(mMetrics); 9106 pp.setCallback(mPackageParserCallback); 9107 9108 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 9109 final PackageParser.Package pkg; 9110 try { 9111 pkg = pp.parsePackage(scanFile, parseFlags); 9112 } catch (PackageParserException e) { 9113 throw PackageManagerException.from(e); 9114 } finally { 9115 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9116 } 9117 9118 // Static shared libraries have synthetic package names 9119 if (pkg.applicationInfo.isStaticSharedLibrary()) { 9120 renameStaticSharedLibraryPackage(pkg); 9121 } 9122 9123 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 9124 } 9125 9126 /** 9127 * Scans a package and returns the newly parsed package. 9128 * @throws PackageManagerException on a parse error. 9129 */ 9130 @GuardedBy({"mInstallLock", "mPackages"}) 9131 private PackageParser.Package scanPackageChildLI(PackageParser.Package pkg, 9132 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9133 @Nullable UserHandle user) 9134 throws PackageManagerException { 9135 // If the package has children and this is the first dive in the function 9136 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 9137 // packages (parent and children) would be successfully scanned before the 9138 // actual scan since scanning mutates internal state and we want to atomically 9139 // install the package and its children. 9140 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 9141 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 9142 scanFlags |= SCAN_CHECK_ONLY; 9143 } 9144 } else { 9145 scanFlags &= ~SCAN_CHECK_ONLY; 9146 } 9147 9148 // Scan the parent 9149 PackageParser.Package scannedPkg = addForInitLI(pkg, parseFlags, 9150 scanFlags, currentTime, user); 9151 9152 // Scan the children 9153 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9154 for (int i = 0; i < childCount; i++) { 9155 PackageParser.Package childPackage = pkg.childPackages.get(i); 9156 addForInitLI(childPackage, parseFlags, scanFlags, 9157 currentTime, user); 9158 } 9159 9160 9161 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 9162 return scanPackageChildLI(pkg, parseFlags, scanFlags, currentTime, user); 9163 } 9164 9165 return scannedPkg; 9166 } 9167 9168 /** 9169 * Returns if forced apk verification can be skipped for the whole package, including splits. 9170 */ 9171 private boolean canSkipForcedPackageVerification(PackageParser.Package pkg) { 9172 if (!canSkipForcedApkVerification(pkg.baseCodePath)) { 9173 return false; 9174 } 9175 // TODO: Allow base and splits to be verified individually. 9176 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 9177 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 9178 if (!canSkipForcedApkVerification(pkg.splitCodePaths[i])) { 9179 return false; 9180 } 9181 } 9182 } 9183 return true; 9184 } 9185 9186 /** 9187 * Returns if forced apk verification can be skipped, depending on current FSVerity setup and 9188 * whether the apk contains signed root hash. Note that the signer's certificate still needs to 9189 * match one in a trusted source, and should be done separately. 9190 */ 9191 private boolean canSkipForcedApkVerification(String apkPath) { 9192 if (!PackageManagerServiceUtils.isLegacyApkVerityEnabled()) { 9193 return VerityUtils.hasFsverity(apkPath); 9194 } 9195 9196 try { 9197 final byte[] rootHashObserved = VerityUtils.generateApkVerityRootHash(apkPath); 9198 if (rootHashObserved == null) { 9199 return false; // APK does not contain Merkle tree root hash. 9200 } 9201 synchronized (mInstallLock) { 9202 // Returns whether the observed root hash matches what kernel has. 9203 mInstaller.assertFsverityRootHashMatches(apkPath, rootHashObserved); 9204 return true; 9205 } 9206 } catch (InstallerException | IOException | DigestException | 9207 NoSuchAlgorithmException e) { 9208 Slog.w(TAG, "Error in fsverity check. Fallback to full apk verification.", e); 9209 } 9210 return false; 9211 } 9212 9213 /** 9214 * Adds a new package to the internal data structures during platform initialization. 9215 * <p>After adding, the package is known to the system and available for querying. 9216 * <p>For packages located on the device ROM [eg. packages located in /system, /vendor, 9217 * etc...], additional checks are performed. Basic verification [such as ensuring 9218 * matching signatures, checking version codes, etc...] occurs if the package is 9219 * identical to a previously known package. If the package fails a signature check, 9220 * the version installed on /data will be removed. If the version of the new package 9221 * is less than or equal than the version on /data, it will be ignored. 9222 * <p>Regardless of the package location, the results are applied to the internal 9223 * structures and the package is made available to the rest of the system. 9224 * <p>NOTE: The return value should be removed. It's the passed in package object. 9225 */ 9226 @GuardedBy({"mInstallLock", "mPackages"}) 9227 private PackageParser.Package addForInitLI(PackageParser.Package pkg, 9228 @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 9229 @Nullable UserHandle user) 9230 throws PackageManagerException { 9231 final boolean scanSystemPartition = (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0; 9232 final String renamedPkgName; 9233 final PackageSetting disabledPkgSetting; 9234 final boolean isSystemPkgUpdated; 9235 final boolean pkgAlreadyExists; 9236 PackageSetting pkgSetting; 9237 9238 // NOTE: installPackageLI() has the same code to setup the package's 9239 // application info. This probably should be done lower in the call 9240 // stack [such as scanPackageOnly()]. However, we verify the application 9241 // info prior to that [in scanPackageNew()] and thus have to setup 9242 // the application info early. 9243 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 9244 pkg.setApplicationInfoCodePath(pkg.codePath); 9245 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 9246 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 9247 pkg.setApplicationInfoResourcePath(pkg.codePath); 9248 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 9249 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 9250 9251 synchronized (mPackages) { 9252 renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 9253 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 9254 if (realPkgName != null) { 9255 ensurePackageRenamed(pkg, renamedPkgName); 9256 } 9257 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 9258 final PackageSetting installedPkgSetting = mSettings.getPackageLPr(pkg.packageName); 9259 pkgSetting = originalPkgSetting == null ? installedPkgSetting : originalPkgSetting; 9260 pkgAlreadyExists = pkgSetting != null; 9261 final String disabledPkgName = pkgAlreadyExists ? pkgSetting.name : pkg.packageName; 9262 if (scanSystemPartition && !pkgAlreadyExists 9263 && mSettings.getDisabledSystemPkgLPr(disabledPkgName) != null) { 9264 // The updated-package data for /system apk remains inconsistently 9265 // after the package data for /data apk is lost accidentally. 9266 // To recover it, enable /system apk and install it as non-updated system app. 9267 Slog.w(TAG, "Inconsistent package setting of updated system app for " 9268 + disabledPkgName + ". To recover it, enable the system app" 9269 + "and install it as non-updated system app."); 9270 mSettings.removeDisabledSystemPackageLPw(disabledPkgName); 9271 } 9272 disabledPkgSetting = mSettings.getDisabledSystemPkgLPr(disabledPkgName); 9273 isSystemPkgUpdated = disabledPkgSetting != null; 9274 9275 if (DEBUG_INSTALL && isSystemPkgUpdated) { 9276 Slog.d(TAG, "updatedPkg = " + disabledPkgSetting); 9277 } 9278 9279 final SharedUserSetting sharedUserSetting = (pkg.mSharedUserId != null) 9280 ? mSettings.getSharedUserLPw(pkg.mSharedUserId, 9281 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true) 9282 : null; 9283 if (DEBUG_PACKAGE_SCANNING 9284 && (parseFlags & PackageParser.PARSE_CHATTY) != 0 9285 && sharedUserSetting != null) { 9286 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 9287 + " (uid=" + sharedUserSetting.userId + "):" 9288 + " packages=" + sharedUserSetting.packages); 9289 } 9290 9291 if (scanSystemPartition) { 9292 // Potentially prune child packages. If the application on the /system 9293 // partition has been updated via OTA, but, is still disabled by a 9294 // version on /data, cycle through all of its children packages and 9295 // remove children that are no longer defined. 9296 if (isSystemPkgUpdated) { 9297 final int scannedChildCount = (pkg.childPackages != null) 9298 ? pkg.childPackages.size() : 0; 9299 final int disabledChildCount = disabledPkgSetting.childPackageNames != null 9300 ? disabledPkgSetting.childPackageNames.size() : 0; 9301 for (int i = 0; i < disabledChildCount; i++) { 9302 String disabledChildPackageName = 9303 disabledPkgSetting.childPackageNames.get(i); 9304 boolean disabledPackageAvailable = false; 9305 for (int j = 0; j < scannedChildCount; j++) { 9306 PackageParser.Package childPkg = pkg.childPackages.get(j); 9307 if (childPkg.packageName.equals(disabledChildPackageName)) { 9308 disabledPackageAvailable = true; 9309 break; 9310 } 9311 } 9312 if (!disabledPackageAvailable) { 9313 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 9314 } 9315 } 9316 // we're updating the disabled package, so, scan it as the package setting 9317 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, null, 9318 disabledPkgSetting /* pkgSetting */, null /* disabledPkgSetting */, 9319 null /* originalPkgSetting */, null, parseFlags, scanFlags, 9320 (pkg == mPlatformPackage), user); 9321 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 9322 final ScanResult scanResult = 9323 scanPackageOnlyLI(request, mInjector, mFactoryTest, -1L); 9324 if (scanResult.existingSettingCopied && scanResult.request.pkgSetting != null) { 9325 scanResult.request.pkgSetting.updateFrom(scanResult.pkgSetting); 9326 } 9327 } 9328 } 9329 } 9330 9331 final boolean newPkgChangedPaths = 9332 pkgAlreadyExists && !pkgSetting.codePathString.equals(pkg.codePath); 9333 final boolean newPkgVersionGreater = 9334 pkgAlreadyExists && pkg.getLongVersionCode() > pkgSetting.versionCode; 9335 final boolean isSystemPkgBetter = scanSystemPartition && isSystemPkgUpdated 9336 && newPkgChangedPaths && newPkgVersionGreater; 9337 if (isSystemPkgBetter) { 9338 // The version of the application on /system is greater than the version on 9339 // /data. Switch back to the application on /system. 9340 // It's safe to assume the application on /system will correctly scan. If not, 9341 // there won't be a working copy of the application. 9342 synchronized (mPackages) { 9343 // just remove the loaded entries from package lists 9344 mPackages.remove(pkgSetting.name); 9345 } 9346 9347 logCriticalInfo(Log.WARN, 9348 "System package updated;" 9349 + " name: " + pkgSetting.name 9350 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 9351 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 9352 9353 final InstallArgs args = createInstallArgsForExisting( 9354 pkgSetting.codePathString, 9355 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 9356 args.cleanUpResourcesLI(); 9357 synchronized (mPackages) { 9358 mSettings.enableSystemPackageLPw(pkgSetting.name); 9359 } 9360 } 9361 9362 if (scanSystemPartition && isSystemPkgUpdated && !isSystemPkgBetter) { 9363 // The version of the application on the /system partition is less than or 9364 // equal to the version on the /data partition. Throw an exception and use 9365 // the application already installed on the /data partition. 9366 throw new PackageManagerException(Log.WARN, "Package " + pkg.packageName + " at " 9367 + pkg.codePath + " ignored: updated version " + pkgSetting.versionCode 9368 + " better than this " + pkg.getLongVersionCode()); 9369 } 9370 9371 // Verify certificates against what was last scanned. If there was an upgrade and this is an 9372 // app in a system partition, or if this is an updated priv app, we will force re-collecting 9373 // certificate. 9374 final boolean forceCollect = (mIsUpgrade && scanSystemPartition) 9375 || PackageManagerServiceUtils.isApkVerificationForced(disabledPkgSetting); 9376 // Full APK verification can be skipped during certificate collection, only if the file is 9377 // in verified partition, or can be verified on access (when apk verity is enabled). In both 9378 // cases, only data in Signing Block is verified instead of the whole file. 9379 final boolean skipVerify = scanSystemPartition 9380 || (forceCollect && canSkipForcedPackageVerification(pkg)); 9381 collectCertificatesLI(pkgSetting, pkg, forceCollect, skipVerify); 9382 9383 // Reset profile if the application version is changed 9384 maybeClearProfilesForUpgradesLI(pkgSetting, pkg); 9385 9386 /* 9387 * A new system app appeared, but we already had a non-system one of the 9388 * same name installed earlier. 9389 */ 9390 boolean shouldHideSystemApp = false; 9391 // A new application appeared on /system, but, we already have a copy of 9392 // the application installed on /data. 9393 if (scanSystemPartition && !isSystemPkgUpdated && pkgAlreadyExists 9394 && !pkgSetting.isSystem()) { 9395 9396 if (!pkg.mSigningDetails.checkCapability(pkgSetting.signatures.mSigningDetails, 9397 PackageParser.SigningDetails.CertCapabilities.INSTALLED_DATA) 9398 && !pkgSetting.signatures.mSigningDetails.checkCapability( 9399 pkg.mSigningDetails, 9400 PackageParser.SigningDetails.CertCapabilities.ROLLBACK)) { 9401 logCriticalInfo(Log.WARN, 9402 "System package signature mismatch;" 9403 + " name: " + pkgSetting.name); 9404 try (PackageFreezer freezer = freezePackage(pkg.packageName, 9405 "scanPackageInternalLI")) { 9406 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 9407 } 9408 pkgSetting = null; 9409 } else if (newPkgVersionGreater) { 9410 // The application on /system is newer than the application on /data. 9411 // Simply remove the application on /data [keeping application data] 9412 // and replace it with the version on /system. 9413 logCriticalInfo(Log.WARN, 9414 "System package enabled;" 9415 + " name: " + pkgSetting.name 9416 + "; " + pkgSetting.versionCode + " --> " + pkg.getLongVersionCode() 9417 + "; " + pkgSetting.codePathString + " --> " + pkg.codePath); 9418 InstallArgs args = createInstallArgsForExisting( 9419 pkgSetting.codePathString, 9420 pkgSetting.resourcePathString, getAppDexInstructionSets(pkgSetting)); 9421 synchronized (mInstallLock) { 9422 args.cleanUpResourcesLI(); 9423 } 9424 } else { 9425 // The application on /system is older than the application on /data. Hide 9426 // the application on /system and the version on /data will be scanned later 9427 // and re-added like an update. 9428 shouldHideSystemApp = true; 9429 logCriticalInfo(Log.INFO, 9430 "System package disabled;" 9431 + " name: " + pkgSetting.name 9432 + "; old: " + pkgSetting.codePathString + " @ " + pkgSetting.versionCode 9433 + "; new: " + pkg.codePath + " @ " + pkg.codePath); 9434 } 9435 } 9436 9437 final ScanResult scanResult = scanPackageNewLI(pkg, parseFlags, scanFlags 9438 | SCAN_UPDATE_SIGNATURE, currentTime, user); 9439 if (scanResult.success) { 9440 synchronized (mPackages) { 9441 boolean appIdCreated = false; 9442 try { 9443 final String pkgName = scanResult.pkgSetting.name; 9444 final Map<String, ReconciledPackage> reconcileResult = reconcilePackagesLocked( 9445 new ReconcileRequest( 9446 Collections.singletonMap(pkgName, scanResult), 9447 mSharedLibraries, 9448 mPackages, 9449 Collections.singletonMap( 9450 pkgName, getSettingsVersionForPackage(pkg)), 9451 Collections.singletonMap(pkgName, 9452 getSharedLibLatestVersionSetting(scanResult))), 9453 mSettings.mKeySetManagerService); 9454 appIdCreated = optimisticallyRegisterAppId(scanResult); 9455 commitReconciledScanResultLocked(reconcileResult.get(pkgName)); 9456 } catch (PackageManagerException e) { 9457 if (appIdCreated) { 9458 cleanUpAppIdCreation(scanResult); 9459 } 9460 throw e; 9461 } 9462 } 9463 } 9464 9465 if (shouldHideSystemApp) { 9466 synchronized (mPackages) { 9467 mSettings.disableSystemPackageLPw(pkg.packageName, true); 9468 } 9469 } 9470 return scanResult.pkgSetting.pkg; 9471 } 9472 9473 private static void renameStaticSharedLibraryPackage(PackageParser.Package pkg) { 9474 // Derive the new package synthetic package name 9475 pkg.setPackageName(pkg.packageName + STATIC_SHARED_LIB_DELIMITER 9476 + pkg.staticSharedLibVersion); 9477 } 9478 9479 static String fixProcessName(String defProcessName, String processName) { 9480 if (processName == null) { 9481 return defProcessName; 9482 } 9483 return processName; 9484 } 9485 9486 /** 9487 * Enforces that only the system UID or root's UID can call a method exposed 9488 * via Binder. 9489 * 9490 * @param message used as message if SecurityException is thrown 9491 * @throws SecurityException if the caller is not system or root 9492 */ 9493 private static void enforceSystemOrRoot(String message) { 9494 final int uid = Binder.getCallingUid(); 9495 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID) { 9496 throw new SecurityException(message); 9497 } 9498 } 9499 9500 /** 9501 * Enforces that only the system UID or root's UID or shell's UID can call 9502 * a method exposed via Binder. 9503 * 9504 * @param message used as message if SecurityException is thrown 9505 * @throws SecurityException if the caller is not system or shell 9506 */ 9507 private static void enforceSystemOrRootOrShell(String message) { 9508 final int uid = Binder.getCallingUid(); 9509 if (uid != Process.SYSTEM_UID && uid != Process.ROOT_UID && uid != Process.SHELL_UID) { 9510 throw new SecurityException(message); 9511 } 9512 } 9513 9514 @Override 9515 public void performFstrimIfNeeded() { 9516 enforceSystemOrRoot("Only the system can request fstrim"); 9517 9518 // Before everything else, see whether we need to fstrim. 9519 try { 9520 IStorageManager sm = PackageHelper.getStorageManager(); 9521 if (sm != null) { 9522 boolean doTrim = false; 9523 final long interval = android.provider.Settings.Global.getLong( 9524 mContext.getContentResolver(), 9525 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 9526 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 9527 if (interval > 0) { 9528 final long timeSinceLast = System.currentTimeMillis() - sm.lastMaintenance(); 9529 if (timeSinceLast > interval) { 9530 doTrim = true; 9531 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 9532 + "; running immediately"); 9533 } 9534 } 9535 if (doTrim) { 9536 final boolean dexOptDialogShown; 9537 synchronized (mPackages) { 9538 dexOptDialogShown = mDexOptDialogShown; 9539 } 9540 if (!isFirstBoot() && dexOptDialogShown) { 9541 try { 9542 ActivityManager.getService().showBootMessage( 9543 mContext.getResources().getString( 9544 R.string.android_upgrading_fstrim), true); 9545 } catch (RemoteException e) { 9546 } 9547 } 9548 sm.runMaintenance(); 9549 } 9550 } else { 9551 Slog.e(TAG, "storageManager service unavailable!"); 9552 } 9553 } catch (RemoteException e) { 9554 // Can't happen; StorageManagerService is local 9555 } 9556 } 9557 9558 @Override 9559 public void updatePackagesIfNeeded() { 9560 enforceSystemOrRoot("Only the system can request package update"); 9561 9562 // We need to re-extract after an OTA. 9563 boolean causeUpgrade = isDeviceUpgrading(); 9564 9565 // First boot or factory reset. 9566 // Note: we also handle devices that are upgrading to N right now as if it is their 9567 // first boot, as they do not have profile data. 9568 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 9569 9570 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 9571 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 9572 9573 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 9574 return; 9575 } 9576 9577 List<PackageParser.Package> pkgs; 9578 synchronized (mPackages) { 9579 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 9580 } 9581 9582 final long startTime = System.nanoTime(); 9583 final int[] stats = performDexOptUpgrade(pkgs, mIsPreNUpgrade /* showDialog */, 9584 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 9585 false /* bootComplete */); 9586 9587 final int elapsedTimeSeconds = 9588 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 9589 9590 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 9591 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 9592 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 9593 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 9594 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 9595 } 9596 9597 /* 9598 * Return the prebuilt profile path given a package base code path. 9599 */ 9600 private static String getPrebuildProfilePath(PackageParser.Package pkg) { 9601 return pkg.baseCodePath + ".prof"; 9602 } 9603 9604 /** 9605 * Performs dexopt on the set of packages in {@code packages} and returns an int array 9606 * containing statistics about the invocation. The array consists of three elements, 9607 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 9608 * and {@code numberOfPackagesFailed}. 9609 */ 9610 private int[] performDexOptUpgrade(List<PackageParser.Package> pkgs, boolean showDialog, 9611 final int compilationReason, boolean bootComplete) { 9612 9613 int numberOfPackagesVisited = 0; 9614 int numberOfPackagesOptimized = 0; 9615 int numberOfPackagesSkipped = 0; 9616 int numberOfPackagesFailed = 0; 9617 final int numberOfPackagesToDexopt = pkgs.size(); 9618 9619 for (PackageParser.Package pkg : pkgs) { 9620 numberOfPackagesVisited++; 9621 9622 boolean useProfileForDexopt = false; 9623 9624 if ((isFirstBoot() || isDeviceUpgrading()) && isSystemApp(pkg)) { 9625 // Copy over initial preopt profiles since we won't get any JIT samples for methods 9626 // that are already compiled. 9627 File profileFile = new File(getPrebuildProfilePath(pkg)); 9628 // Copy profile if it exists. 9629 if (profileFile.exists()) { 9630 try { 9631 // We could also do this lazily before calling dexopt in 9632 // PackageDexOptimizer to prevent this happening on first boot. The issue 9633 // is that we don't have a good way to say "do this only once". 9634 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9635 pkg.applicationInfo.uid, pkg.packageName, 9636 ArtManager.getProfileName(null))) { 9637 Log.e(TAG, "Installer failed to copy system profile!"); 9638 } else { 9639 // Disabled as this causes speed-profile compilation during first boot 9640 // even if things are already compiled. 9641 // useProfileForDexopt = true; 9642 } 9643 } catch (Exception e) { 9644 Log.e(TAG, "Failed to copy profile " + profileFile.getAbsolutePath() + " ", 9645 e); 9646 } 9647 } else { 9648 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 9649 // Handle compressed APKs in this path. Only do this for stubs with profiles to 9650 // minimize the number off apps being speed-profile compiled during first boot. 9651 // The other paths will not change the filter. 9652 if (disabledPs != null && disabledPs.pkg.isStub) { 9653 // The package is the stub one, remove the stub suffix to get the normal 9654 // package and APK names. 9655 String systemProfilePath = 9656 getPrebuildProfilePath(disabledPs.pkg).replace(STUB_SUFFIX, ""); 9657 profileFile = new File(systemProfilePath); 9658 // If we have a profile for a compressed APK, copy it to the reference 9659 // location. 9660 // Note that copying the profile here will cause it to override the 9661 // reference profile every OTA even though the existing reference profile 9662 // may have more data. We can't copy during decompression since the 9663 // directories are not set up at that point. 9664 if (profileFile.exists()) { 9665 try { 9666 // We could also do this lazily before calling dexopt in 9667 // PackageDexOptimizer to prevent this happening on first boot. The 9668 // issue is that we don't have a good way to say "do this only 9669 // once". 9670 if (!mInstaller.copySystemProfile(profileFile.getAbsolutePath(), 9671 pkg.applicationInfo.uid, pkg.packageName, 9672 ArtManager.getProfileName(null))) { 9673 Log.e(TAG, "Failed to copy system profile for stub package!"); 9674 } else { 9675 useProfileForDexopt = true; 9676 } 9677 } catch (Exception e) { 9678 Log.e(TAG, "Failed to copy profile " + 9679 profileFile.getAbsolutePath() + " ", e); 9680 } 9681 } 9682 } 9683 } 9684 } 9685 9686 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 9687 if (DEBUG_DEXOPT) { 9688 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 9689 } 9690 numberOfPackagesSkipped++; 9691 continue; 9692 } 9693 9694 if (DEBUG_DEXOPT) { 9695 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 9696 numberOfPackagesToDexopt + ": " + pkg.packageName); 9697 } 9698 9699 if (showDialog) { 9700 try { 9701 ActivityManager.getService().showBootMessage( 9702 mContext.getResources().getString(R.string.android_upgrading_apk, 9703 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 9704 } catch (RemoteException e) { 9705 } 9706 synchronized (mPackages) { 9707 mDexOptDialogShown = true; 9708 } 9709 } 9710 9711 int pkgCompilationReason = compilationReason; 9712 if (useProfileForDexopt) { 9713 // Use background dexopt mode to try and use the profile. Note that this does not 9714 // guarantee usage of the profile. 9715 pkgCompilationReason = PackageManagerService.REASON_BACKGROUND_DEXOPT; 9716 } 9717 9718 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) { 9719 mArtManagerService.compileLayouts(pkg); 9720 } 9721 9722 // checkProfiles is false to avoid merging profiles during boot which 9723 // might interfere with background compilation (b/28612421). 9724 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 9725 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 9726 // trade-off worth doing to save boot time work. 9727 int dexoptFlags = bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0; 9728 if (compilationReason == REASON_FIRST_BOOT) { 9729 // TODO: This doesn't cover the upgrade case, we should check for this too. 9730 dexoptFlags |= DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE; 9731 } 9732 int primaryDexOptStaus = performDexOptTraced(new DexoptOptions( 9733 pkg.packageName, 9734 pkgCompilationReason, 9735 dexoptFlags)); 9736 9737 switch (primaryDexOptStaus) { 9738 case PackageDexOptimizer.DEX_OPT_PERFORMED: 9739 numberOfPackagesOptimized++; 9740 break; 9741 case PackageDexOptimizer.DEX_OPT_SKIPPED: 9742 numberOfPackagesSkipped++; 9743 break; 9744 case PackageDexOptimizer.DEX_OPT_FAILED: 9745 numberOfPackagesFailed++; 9746 break; 9747 default: 9748 Log.e(TAG, "Unexpected dexopt return code " + primaryDexOptStaus); 9749 break; 9750 } 9751 } 9752 9753 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 9754 numberOfPackagesFailed }; 9755 } 9756 9757 @Override 9758 public void notifyPackageUse(String packageName, int reason) { 9759 synchronized (mPackages) { 9760 final int callingUid = Binder.getCallingUid(); 9761 final int callingUserId = UserHandle.getUserId(callingUid); 9762 if (getInstantAppPackageName(callingUid) != null) { 9763 if (!isCallerSameApp(packageName, callingUid)) { 9764 return; 9765 } 9766 } else { 9767 if (isInstantApp(packageName, callingUserId)) { 9768 return; 9769 } 9770 } 9771 notifyPackageUseLocked(packageName, reason); 9772 } 9773 } 9774 9775 @GuardedBy("mPackages") 9776 public CheckPermissionDelegate getCheckPermissionDelegateLocked() { 9777 return mCheckPermissionDelegate; 9778 } 9779 9780 @GuardedBy("mPackages") 9781 public void setCheckPermissionDelegateLocked(CheckPermissionDelegate delegate) { 9782 mCheckPermissionDelegate = delegate; 9783 } 9784 9785 @GuardedBy("mPackages") 9786 private void notifyPackageUseLocked(String packageName, int reason) { 9787 final PackageParser.Package p = mPackages.get(packageName); 9788 if (p == null) { 9789 return; 9790 } 9791 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 9792 } 9793 9794 @Override 9795 public void notifyDexLoad(String loadingPackageName, Map<String, String> classLoaderContextMap, 9796 String loaderIsa) { 9797 int userId = UserHandle.getCallingUserId(); 9798 ApplicationInfo ai = getApplicationInfo(loadingPackageName, /*flags*/ 0, userId); 9799 if (ai == null) { 9800 Slog.w(TAG, "Loading a package that does not exist for the calling user. package=" 9801 + loadingPackageName + ", user=" + userId); 9802 return; 9803 } 9804 mDexManager.notifyDexLoad(ai, classLoaderContextMap, loaderIsa, userId); 9805 } 9806 9807 @Override 9808 public void registerDexModule(String packageName, String dexModulePath, boolean isSharedModule, 9809 IDexModuleRegisterCallback callback) { 9810 int userId = UserHandle.getCallingUserId(); 9811 ApplicationInfo ai = getApplicationInfo(packageName, /*flags*/ 0, userId); 9812 DexManager.RegisterDexModuleResult result; 9813 if (ai == null) { 9814 Slog.w(TAG, "Registering a dex module for a package that does not exist for the" + 9815 " calling user. package=" + packageName + ", user=" + userId); 9816 result = new DexManager.RegisterDexModuleResult(false, "Package not installed"); 9817 } else { 9818 result = mDexManager.registerDexModule(ai, dexModulePath, isSharedModule, userId); 9819 } 9820 9821 if (callback != null) { 9822 mHandler.post(() -> { 9823 try { 9824 callback.onDexModuleRegistered(dexModulePath, result.success, result.message); 9825 } catch (RemoteException e) { 9826 Slog.w(TAG, "Failed to callback after module registration " + dexModulePath, e); 9827 } 9828 }); 9829 } 9830 } 9831 9832 /** 9833 * Ask the package manager to perform a dex-opt with the given compiler filter. 9834 * 9835 * Note: exposed only for the shell command to allow moving packages explicitly to a 9836 * definite state. 9837 */ 9838 @Override 9839 public boolean performDexOptMode(String packageName, 9840 boolean checkProfiles, String targetCompilerFilter, boolean force, 9841 boolean bootComplete, String splitName) { 9842 int flags = (checkProfiles ? DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES : 0) | 9843 (force ? DexoptOptions.DEXOPT_FORCE : 0) | 9844 (bootComplete ? DexoptOptions.DEXOPT_BOOT_COMPLETE : 0); 9845 return performDexOpt(new DexoptOptions(packageName, REASON_UNKNOWN, 9846 targetCompilerFilter, splitName, flags)); 9847 } 9848 9849 /** 9850 * Ask the package manager to perform a dex-opt with the given compiler filter on the 9851 * secondary dex files belonging to the given package. 9852 * 9853 * Note: exposed only for the shell command to allow moving packages explicitly to a 9854 * definite state. 9855 */ 9856 @Override 9857 public boolean performDexOptSecondary(String packageName, String compilerFilter, 9858 boolean force) { 9859 int flags = DexoptOptions.DEXOPT_ONLY_SECONDARY_DEX | 9860 DexoptOptions.DEXOPT_CHECK_FOR_PROFILES_UPDATES | 9861 DexoptOptions.DEXOPT_BOOT_COMPLETE | 9862 (force ? DexoptOptions.DEXOPT_FORCE : 0); 9863 return performDexOpt(new DexoptOptions(packageName, compilerFilter, flags)); 9864 } 9865 9866 /** 9867 * Ask the package manager to compile layouts in the given package. 9868 */ 9869 @Override 9870 public boolean compileLayouts(String packageName) { 9871 PackageParser.Package pkg; 9872 synchronized (mPackages) { 9873 pkg = mPackages.get(packageName); 9874 if (pkg == null) { 9875 return false; 9876 } 9877 } 9878 return mViewCompiler.compileLayouts(pkg); 9879 } 9880 9881 /*package*/ boolean performDexOpt(DexoptOptions options) { 9882 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 9883 return false; 9884 } else if (isInstantApp(options.getPackageName(), UserHandle.getCallingUserId())) { 9885 return false; 9886 } 9887 9888 if (options.isDexoptOnlySecondaryDex()) { 9889 return mDexManager.dexoptSecondaryDex(options); 9890 } else { 9891 int dexoptStatus = performDexOptWithStatus(options); 9892 return dexoptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 9893 } 9894 } 9895 9896 /** 9897 * Perform dexopt on the given package and return one of following result: 9898 * {@link PackageDexOptimizer#DEX_OPT_SKIPPED} 9899 * {@link PackageDexOptimizer#DEX_OPT_PERFORMED} 9900 * {@link PackageDexOptimizer#DEX_OPT_FAILED} 9901 */ 9902 /* package */ int performDexOptWithStatus(DexoptOptions options) { 9903 return performDexOptTraced(options); 9904 } 9905 9906 private int performDexOptTraced(DexoptOptions options) { 9907 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 9908 try { 9909 return performDexOptInternal(options); 9910 } finally { 9911 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9912 } 9913 } 9914 9915 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 9916 // if the package can now be considered up to date for the given filter. 9917 private int performDexOptInternal(DexoptOptions options) { 9918 PackageParser.Package p; 9919 synchronized (mPackages) { 9920 p = mPackages.get(options.getPackageName()); 9921 if (p == null) { 9922 // Package could not be found. Report failure. 9923 return PackageDexOptimizer.DEX_OPT_FAILED; 9924 } 9925 mPackageUsage.maybeWriteAsync(mPackages); 9926 mCompilerStats.maybeWriteAsync(); 9927 } 9928 long callingId = Binder.clearCallingIdentity(); 9929 try { 9930 synchronized (mInstallLock) { 9931 return performDexOptInternalWithDependenciesLI(p, options); 9932 } 9933 } finally { 9934 Binder.restoreCallingIdentity(callingId); 9935 } 9936 } 9937 9938 public ArraySet<String> getOptimizablePackages() { 9939 ArraySet<String> pkgs = new ArraySet<>(); 9940 synchronized (mPackages) { 9941 for (PackageParser.Package p : mPackages.values()) { 9942 if (PackageDexOptimizer.canOptimizePackage(p)) { 9943 pkgs.add(p.packageName); 9944 } 9945 } 9946 } 9947 return pkgs; 9948 } 9949 9950 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 9951 DexoptOptions options) { 9952 // Select the dex optimizer based on the force parameter. 9953 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 9954 // allocate an object here. 9955 PackageDexOptimizer pdo = options.isForce() 9956 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 9957 : mPackageDexOptimizer; 9958 9959 // Dexopt all dependencies first. Note: we ignore the return value and march on 9960 // on errors. 9961 // Note that we are going to call performDexOpt on those libraries as many times as 9962 // they are referenced in packages. When we do a batch of performDexOpt (for example 9963 // at boot, or background job), the passed 'targetCompilerFilter' stays the same, 9964 // and the first package that uses the library will dexopt it. The 9965 // others will see that the compiled code for the library is up to date. 9966 Collection<SharedLibraryInfo> deps = findSharedLibraries(p); 9967 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 9968 if (!deps.isEmpty()) { 9969 DexoptOptions libraryOptions = new DexoptOptions(options.getPackageName(), 9970 options.getCompilationReason(), options.getCompilerFilter(), 9971 options.getSplitName(), 9972 options.getFlags() | DexoptOptions.DEXOPT_AS_SHARED_LIBRARY); 9973 for (SharedLibraryInfo info : deps) { 9974 PackageParser.Package depPackage = null; 9975 synchronized (mPackages) { 9976 depPackage = mPackages.get(info.getPackageName()); 9977 } 9978 if (depPackage != null) { 9979 // TODO: Analyze and investigate if we (should) profile libraries. 9980 pdo.performDexOpt(depPackage, instructionSets, 9981 getOrCreateCompilerPackageStats(depPackage), 9982 mDexManager.getPackageUseInfoOrDefault(depPackage.packageName), 9983 libraryOptions); 9984 } else { 9985 // TODO(ngeoffray): Support dexopting system shared libraries. 9986 } 9987 } 9988 } 9989 return pdo.performDexOpt(p, instructionSets, 9990 getOrCreateCompilerPackageStats(p), 9991 mDexManager.getPackageUseInfoOrDefault(p.packageName), options); 9992 } 9993 9994 /** 9995 * Reconcile the information we have about the secondary dex files belonging to 9996 * {@code packageName} and the actual dex files. For all dex files that were 9997 * deleted, update the internal records and delete the generated oat files. 9998 */ 9999 @Override 10000 public void reconcileSecondaryDexFiles(String packageName) { 10001 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10002 return; 10003 } else if (isInstantApp(packageName, UserHandle.getCallingUserId())) { 10004 return; 10005 } 10006 mDexManager.reconcileSecondaryDexFiles(packageName); 10007 } 10008 10009 // TODO(calin): this is only needed for BackgroundDexOptService. Find a cleaner way to inject 10010 // a reference there. 10011 /*package*/ DexManager getDexManager() { 10012 return mDexManager; 10013 } 10014 10015 /** 10016 * Execute the background dexopt job immediately. 10017 */ 10018 @Override 10019 public boolean runBackgroundDexoptJob(@Nullable List<String> packageNames) { 10020 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 10021 return false; 10022 } 10023 enforceSystemOrRootOrShell("runBackgroundDexoptJob"); 10024 final long identity = Binder.clearCallingIdentity(); 10025 try { 10026 return BackgroundDexOptService.runIdleOptimizationsNow(this, mContext, packageNames); 10027 } finally { 10028 Binder.restoreCallingIdentity(identity); 10029 } 10030 } 10031 10032 private static List<SharedLibraryInfo> findSharedLibraries(PackageParser.Package p) { 10033 if (p.usesLibraryInfos != null) { 10034 ArrayList<SharedLibraryInfo> retValue = new ArrayList<>(); 10035 Set<String> collectedNames = new HashSet<>(); 10036 for (SharedLibraryInfo info : p.usesLibraryInfos) { 10037 findSharedLibrariesRecursive(info, retValue, collectedNames); 10038 } 10039 return retValue; 10040 } else { 10041 return Collections.emptyList(); 10042 } 10043 } 10044 10045 private static void findSharedLibrariesRecursive(SharedLibraryInfo info, 10046 ArrayList<SharedLibraryInfo> collected, Set<String> collectedNames) { 10047 if (!collectedNames.contains(info.getName())) { 10048 collectedNames.add(info.getName()); 10049 collected.add(info); 10050 10051 if (info.getDependencies() != null) { 10052 for (SharedLibraryInfo dep : info.getDependencies()) { 10053 findSharedLibrariesRecursive(dep, collected, collectedNames); 10054 } 10055 } 10056 } 10057 } 10058 10059 List<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package pkg) { 10060 List<SharedLibraryInfo> deps = findSharedLibraries(pkg); 10061 if (!deps.isEmpty()) { 10062 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 10063 synchronized (mPackages) { 10064 for (SharedLibraryInfo info : deps) { 10065 PackageParser.Package depPackage = mPackages.get(info.getPackageName()); 10066 if (depPackage != null) { 10067 retValue.add(depPackage); 10068 } 10069 } 10070 } 10071 return retValue; 10072 } else { 10073 return Collections.emptyList(); 10074 } 10075 } 10076 10077 @Nullable 10078 private SharedLibraryInfo getSharedLibraryInfoLPr(String name, long version) { 10079 return getSharedLibraryInfo(name, version, mSharedLibraries, null); 10080 } 10081 10082 @Nullable 10083 private static SharedLibraryInfo getSharedLibraryInfo(String name, long version, 10084 Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10085 @Nullable Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) { 10086 if (newLibraries != null) { 10087 final LongSparseArray<SharedLibraryInfo> versionedLib = newLibraries.get(name); 10088 SharedLibraryInfo info = null; 10089 if (versionedLib != null) { 10090 info = versionedLib.get(version); 10091 } 10092 if (info != null) { 10093 return info; 10094 } 10095 } 10096 final LongSparseArray<SharedLibraryInfo> versionedLib = existingLibraries.get(name); 10097 if (versionedLib == null) { 10098 return null; 10099 } 10100 return versionedLib.get(version); 10101 } 10102 10103 private SharedLibraryInfo getLatestSharedLibraVersionLPr(PackageParser.Package pkg) { 10104 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get( 10105 pkg.staticSharedLibName); 10106 if (versionedLib == null) { 10107 return null; 10108 } 10109 long previousLibVersion = -1; 10110 final int versionCount = versionedLib.size(); 10111 for (int i = 0; i < versionCount; i++) { 10112 final long libVersion = versionedLib.keyAt(i); 10113 if (libVersion < pkg.staticSharedLibVersion) { 10114 previousLibVersion = Math.max(previousLibVersion, libVersion); 10115 } 10116 } 10117 if (previousLibVersion >= 0) { 10118 return versionedLib.get(previousLibVersion); 10119 } 10120 return null; 10121 } 10122 10123 10124 @Nullable 10125 private PackageSetting getSharedLibLatestVersionSetting(@NonNull ScanResult scanResult) { 10126 PackageSetting sharedLibPackage = null; 10127 synchronized (mPackages) { 10128 final SharedLibraryInfo latestSharedLibraVersionLPr = 10129 getLatestSharedLibraVersionLPr(scanResult.pkgSetting.pkg); 10130 if (latestSharedLibraVersionLPr != null) { 10131 sharedLibPackage = mSettings.getPackageLPr( 10132 latestSharedLibraVersionLPr.getPackageName()); 10133 } 10134 } 10135 return sharedLibPackage; 10136 } 10137 10138 public void shutdown() { 10139 mPackageUsage.writeNow(mPackages); 10140 mCompilerStats.writeNow(); 10141 mDexManager.writePackageDexUsageNow(); 10142 PackageWatchdog.getInstance(mContext).writeNow(); 10143 10144 // This is the last chance to write out pending restriction settings 10145 synchronized (mPackages) { 10146 if (mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 10147 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 10148 for (int userId : mDirtyUsers) { 10149 mSettings.writePackageRestrictionsLPr(userId); 10150 } 10151 mDirtyUsers.clear(); 10152 } 10153 } 10154 } 10155 10156 @Override 10157 public void dumpProfiles(String packageName) { 10158 PackageParser.Package pkg; 10159 synchronized (mPackages) { 10160 pkg = mPackages.get(packageName); 10161 if (pkg == null) { 10162 throw new IllegalArgumentException("Unknown package: " + packageName); 10163 } 10164 } 10165 /* Only the shell, root, or the app user should be able to dump profiles. */ 10166 int callingUid = Binder.getCallingUid(); 10167 if (callingUid != Process.SHELL_UID && 10168 callingUid != Process.ROOT_UID && 10169 callingUid != pkg.applicationInfo.uid) { 10170 throw new SecurityException("dumpProfiles"); 10171 } 10172 10173 synchronized (mInstallLock) { 10174 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 10175 mArtManagerService.dumpProfiles(pkg); 10176 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10177 } 10178 } 10179 10180 @Override 10181 public void forceDexOpt(String packageName) { 10182 enforceSystemOrRoot("forceDexOpt"); 10183 10184 PackageParser.Package pkg; 10185 synchronized (mPackages) { 10186 pkg = mPackages.get(packageName); 10187 if (pkg == null) { 10188 throw new IllegalArgumentException("Unknown package: " + packageName); 10189 } 10190 } 10191 10192 synchronized (mInstallLock) { 10193 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 10194 10195 // Whoever is calling forceDexOpt wants a compiled package. 10196 // Don't use profiles since that may cause compilation to be skipped. 10197 final int res = performDexOptInternalWithDependenciesLI( 10198 pkg, 10199 new DexoptOptions(packageName, 10200 getDefaultCompilerFilter(), 10201 DexoptOptions.DEXOPT_FORCE | DexoptOptions.DEXOPT_BOOT_COMPLETE)); 10202 10203 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10204 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 10205 throw new IllegalStateException("Failed to dexopt: " + res); 10206 } 10207 } 10208 } 10209 10210 @GuardedBy("mPackages") 10211 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 10212 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 10213 Slog.w(TAG, "Unable to update from " + oldPkg.name 10214 + " to " + newPkg.packageName 10215 + ": old package not in system partition"); 10216 return false; 10217 } else if (mPackages.get(oldPkg.name) != null) { 10218 Slog.w(TAG, "Unable to update from " + oldPkg.name 10219 + " to " + newPkg.packageName 10220 + ": old package still exists"); 10221 return false; 10222 } 10223 return true; 10224 } 10225 10226 @GuardedBy("mInstallLock") 10227 void removeCodePathLI(File codePath) { 10228 if (codePath.isDirectory()) { 10229 try { 10230 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 10231 } catch (InstallerException e) { 10232 Slog.w(TAG, "Failed to remove code path", e); 10233 } 10234 } else { 10235 codePath.delete(); 10236 } 10237 } 10238 10239 private int[] resolveUserIds(int userId) { 10240 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 10241 } 10242 10243 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10244 if (pkg == null) { 10245 Slog.wtf(TAG, "Package was null!", new Throwable()); 10246 return; 10247 } 10248 clearAppDataLeafLIF(pkg, userId, flags); 10249 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10250 for (int i = 0; i < childCount; i++) { 10251 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10252 } 10253 10254 if ((flags & Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES) == 0) { 10255 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 10256 } 10257 } 10258 10259 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10260 final PackageSetting ps; 10261 synchronized (mPackages) { 10262 ps = mSettings.mPackages.get(pkg.packageName); 10263 } 10264 for (int realUserId : resolveUserIds(userId)) { 10265 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10266 try { 10267 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10268 ceDataInode); 10269 } catch (InstallerException e) { 10270 Slog.w(TAG, String.valueOf(e)); 10271 } 10272 } 10273 } 10274 10275 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 10276 if (pkg == null) { 10277 Slog.wtf(TAG, "Package was null!", new Throwable()); 10278 return; 10279 } 10280 destroyAppDataLeafLIF(pkg, userId, flags); 10281 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10282 for (int i = 0; i < childCount; i++) { 10283 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 10284 } 10285 } 10286 10287 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 10288 final PackageSetting ps; 10289 synchronized (mPackages) { 10290 ps = mSettings.mPackages.get(pkg.packageName); 10291 } 10292 for (int realUserId : resolveUserIds(userId)) { 10293 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 10294 try { 10295 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 10296 ceDataInode); 10297 } catch (InstallerException e) { 10298 Slog.w(TAG, String.valueOf(e)); 10299 } 10300 mDexManager.notifyPackageDataDestroyed(pkg.packageName, userId); 10301 } 10302 } 10303 10304 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 10305 if (pkg == null) { 10306 Slog.wtf(TAG, "Package was null!", new Throwable()); 10307 return; 10308 } 10309 destroyAppProfilesLeafLIF(pkg); 10310 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10311 for (int i = 0; i < childCount; i++) { 10312 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 10313 } 10314 } 10315 10316 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 10317 try { 10318 mInstaller.destroyAppProfiles(pkg.packageName); 10319 } catch (InstallerException e) { 10320 Slog.w(TAG, String.valueOf(e)); 10321 } 10322 } 10323 10324 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 10325 if (pkg == null) { 10326 Slog.wtf(TAG, "Package was null!", new Throwable()); 10327 return; 10328 } 10329 mArtManagerService.clearAppProfiles(pkg); 10330 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10331 for (int i = 0; i < childCount; i++) { 10332 mArtManagerService.clearAppProfiles(pkg.childPackages.get(i)); 10333 } 10334 } 10335 10336 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 10337 long lastUpdateTime) { 10338 // Set parent install/update time 10339 PackageSetting ps = (PackageSetting) pkg.mExtras; 10340 if (ps != null) { 10341 ps.firstInstallTime = firstInstallTime; 10342 ps.lastUpdateTime = lastUpdateTime; 10343 } 10344 // Set children install/update time 10345 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10346 for (int i = 0; i < childCount; i++) { 10347 PackageParser.Package childPkg = pkg.childPackages.get(i); 10348 ps = (PackageSetting) childPkg.mExtras; 10349 if (ps != null) { 10350 ps.firstInstallTime = firstInstallTime; 10351 ps.lastUpdateTime = lastUpdateTime; 10352 } 10353 } 10354 } 10355 10356 @GuardedBy("mPackages") 10357 private void applyDefiningSharedLibraryUpdateLocked( 10358 PackageParser.Package pkg, SharedLibraryInfo libInfo, 10359 BiConsumer<SharedLibraryInfo, SharedLibraryInfo> action) { 10360 // Note that libraries defined by this package may be null if: 10361 // - Package manager was unable to create the shared library. The package still 10362 // gets installed, but the shared library does not get created. 10363 // Or: 10364 // - Package manager is in a state where package isn't scanned yet. This will 10365 // get called again after scanning to fix the dependencies. 10366 if (pkg.isLibrary()) { 10367 if (pkg.staticSharedLibName != null) { 10368 SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr( 10369 pkg.staticSharedLibName, pkg.staticSharedLibVersion); 10370 if (definedLibrary != null) { 10371 action.accept(definedLibrary, libInfo); 10372 } 10373 } else { 10374 for (String libraryName : pkg.libraryNames) { 10375 SharedLibraryInfo definedLibrary = getSharedLibraryInfoLPr( 10376 libraryName, SharedLibraryInfo.VERSION_UNDEFINED); 10377 if (definedLibrary != null) { 10378 action.accept(definedLibrary, libInfo); 10379 } 10380 } 10381 } 10382 } 10383 } 10384 10385 @GuardedBy("mPackages") 10386 private void addSharedLibraryLPr(PackageParser.Package pkg, Set<String> usesLibraryFiles, 10387 SharedLibraryInfo libInfo, PackageParser.Package changingLib) { 10388 if (libInfo.getPath() != null) { 10389 usesLibraryFiles.add(libInfo.getPath()); 10390 return; 10391 } 10392 PackageParser.Package p = mPackages.get(libInfo.getPackageName()); 10393 if (changingLib != null && changingLib.packageName.equals(libInfo.getPackageName())) { 10394 // If we are doing this while in the middle of updating a library apk, 10395 // then we need to make sure to use that new apk for determining the 10396 // dependencies here. (We haven't yet finished committing the new apk 10397 // to the package manager state.) 10398 if (p == null || p.packageName.equals(changingLib.packageName)) { 10399 p = changingLib; 10400 } 10401 } 10402 if (p != null) { 10403 usesLibraryFiles.addAll(p.getAllCodePaths()); 10404 // If the package provides libraries, add the dependency to them. 10405 applyDefiningSharedLibraryUpdateLocked(pkg, libInfo, (definingLibrary, dependency) -> { 10406 definingLibrary.addDependency(dependency); 10407 }); 10408 if (p.usesLibraryFiles != null) { 10409 Collections.addAll(usesLibraryFiles, p.usesLibraryFiles); 10410 } 10411 } 10412 } 10413 10414 @GuardedBy("mPackages") 10415 private void updateSharedLibrariesLocked(PackageParser.Package pkg, 10416 PackageParser.Package changingLib, Map<String, PackageParser.Package> availablePackages) 10417 throws PackageManagerException { 10418 final ArrayList<SharedLibraryInfo> sharedLibraryInfos = 10419 collectSharedLibraryInfos(pkg, availablePackages, mSharedLibraries, null); 10420 executeSharedLibrariesUpdateLPr(pkg, changingLib, sharedLibraryInfos); 10421 } 10422 10423 private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos(PackageParser.Package pkg, 10424 Map<String, PackageParser.Package> availablePackages, 10425 @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10426 @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) 10427 throws PackageManagerException { 10428 if (pkg == null) { 10429 return null; 10430 } 10431 // The collection used here must maintain the order of addition (so 10432 // that libraries are searched in the correct order) and must have no 10433 // duplicates. 10434 ArrayList<SharedLibraryInfo> usesLibraryInfos = null; 10435 if (pkg.usesLibraries != null) { 10436 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesLibraries, null, null, 10437 pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, null, 10438 availablePackages, existingLibraries, newLibraries); 10439 } 10440 if (pkg.usesStaticLibraries != null) { 10441 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesStaticLibraries, 10442 pkg.usesStaticLibrariesVersions, pkg.usesStaticLibrariesCertDigests, 10443 pkg.packageName, true, pkg.applicationInfo.targetSdkVersion, usesLibraryInfos, 10444 availablePackages, existingLibraries, newLibraries); 10445 } 10446 if (pkg.usesOptionalLibraries != null) { 10447 usesLibraryInfos = collectSharedLibraryInfos(pkg.usesOptionalLibraries, 10448 null, null, pkg.packageName, false, pkg.applicationInfo.targetSdkVersion, 10449 usesLibraryInfos, availablePackages, existingLibraries, newLibraries); 10450 } 10451 return usesLibraryInfos; 10452 } 10453 10454 private void executeSharedLibrariesUpdateLPr(PackageParser.Package pkg, 10455 PackageParser.Package changingLib, ArrayList<SharedLibraryInfo> usesLibraryInfos) { 10456 // If the package provides libraries, clear their old dependencies. 10457 // This method will set them up again. 10458 applyDefiningSharedLibraryUpdateLocked(pkg, null, (definingLibrary, dependency) -> { 10459 definingLibrary.clearDependencies(); 10460 }); 10461 if (usesLibraryInfos != null) { 10462 pkg.usesLibraryInfos = usesLibraryInfos; 10463 // Use LinkedHashSet to preserve the order of files added to 10464 // usesLibraryFiles while eliminating duplicates. 10465 Set<String> usesLibraryFiles = new LinkedHashSet<>(); 10466 for (SharedLibraryInfo libInfo : usesLibraryInfos) { 10467 addSharedLibraryLPr(pkg, usesLibraryFiles, libInfo, changingLib); 10468 } 10469 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[usesLibraryFiles.size()]); 10470 } else { 10471 pkg.usesLibraryInfos = null; 10472 pkg.usesLibraryFiles = null; 10473 } 10474 } 10475 10476 @GuardedBy("mPackages") 10477 private static ArrayList<SharedLibraryInfo> collectSharedLibraryInfos( 10478 @NonNull List<String> requestedLibraries, 10479 @Nullable long[] requiredVersions, @Nullable String[][] requiredCertDigests, 10480 @NonNull String packageName, boolean required, int targetSdk, 10481 @Nullable ArrayList<SharedLibraryInfo> outUsedLibraries, 10482 @NonNull final Map<String, PackageParser.Package> availablePackages, 10483 @NonNull final Map<String, LongSparseArray<SharedLibraryInfo>> existingLibraries, 10484 @Nullable final Map<String, LongSparseArray<SharedLibraryInfo>> newLibraries) 10485 throws PackageManagerException { 10486 final int libCount = requestedLibraries.size(); 10487 for (int i = 0; i < libCount; i++) { 10488 final String libName = requestedLibraries.get(i); 10489 final long libVersion = requiredVersions != null ? requiredVersions[i] 10490 : SharedLibraryInfo.VERSION_UNDEFINED; 10491 final SharedLibraryInfo libraryInfo = getSharedLibraryInfo(libName, libVersion, 10492 existingLibraries, newLibraries); 10493 if (libraryInfo == null) { 10494 if (required) { 10495 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10496 "Package " + packageName + " requires unavailable shared library " 10497 + libName + "; failing!"); 10498 } else if (DEBUG_SHARED_LIBRARIES) { 10499 Slog.i(TAG, "Package " + packageName 10500 + " desires unavailable shared library " 10501 + libName + "; ignoring!"); 10502 } 10503 } else { 10504 if (requiredVersions != null && requiredCertDigests != null) { 10505 if (libraryInfo.getLongVersion() != requiredVersions[i]) { 10506 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10507 "Package " + packageName + " requires unavailable static shared" 10508 + " library " + libName + " version " 10509 + libraryInfo.getLongVersion() + "; failing!"); 10510 } 10511 PackageParser.Package libPkg = 10512 availablePackages.get(libraryInfo.getPackageName()); 10513 if (libPkg == null) { 10514 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10515 "Package " + packageName + " requires unavailable static shared" 10516 + " library; failing!"); 10517 } 10518 final String[] expectedCertDigests = requiredCertDigests[i]; 10519 if (expectedCertDigests.length > 1) { 10520 // For apps targeting O MR1 we require explicit enumeration of all certs. 10521 final String[] libCertDigests = (targetSdk >= Build.VERSION_CODES.O_MR1) 10522 ? PackageUtils.computeSignaturesSha256Digests( 10523 libPkg.mSigningDetails.signatures) 10524 : PackageUtils.computeSignaturesSha256Digests( 10525 new Signature[]{libPkg.mSigningDetails.signatures[0]}); 10526 10527 // Take a shortcut if sizes don't match. Note that if an app doesn't 10528 // target O we don't parse the "additional-certificate" tags similarly 10529 // how we only consider all certs only for apps targeting O (see above). 10530 // Therefore, the size check is safe to make. 10531 if (expectedCertDigests.length != libCertDigests.length) { 10532 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10533 "Package " + packageName + " requires differently signed" + 10534 " static shared library; failing!"); 10535 } 10536 10537 // Use a predictable order as signature order may vary 10538 Arrays.sort(libCertDigests); 10539 Arrays.sort(expectedCertDigests); 10540 10541 final int certCount = libCertDigests.length; 10542 for (int j = 0; j < certCount; j++) { 10543 if (!libCertDigests[j].equalsIgnoreCase(expectedCertDigests[j])) { 10544 throw new PackageManagerException( 10545 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10546 "Package " + packageName + " requires differently signed" + 10547 " static shared library; failing!"); 10548 } 10549 } 10550 } else { 10551 // lib signing cert could have rotated beyond the one expected, check to see 10552 // if the new one has been blessed by the old 10553 byte[] digestBytes = HexEncoding.decode( 10554 expectedCertDigests[0], false /* allowSingleChar */); 10555 if (!libPkg.mSigningDetails.hasSha256Certificate(digestBytes)) { 10556 throw new PackageManagerException( 10557 INSTALL_FAILED_MISSING_SHARED_LIBRARY, 10558 "Package " + packageName + " requires differently signed" + 10559 " static shared library; failing!"); 10560 } 10561 } 10562 } 10563 if (outUsedLibraries == null) { 10564 outUsedLibraries = new ArrayList<>(); 10565 } 10566 outUsedLibraries.add(libraryInfo); 10567 } 10568 } 10569 return outUsedLibraries; 10570 } 10571 10572 private static boolean hasString(List<String> list, List<String> which) { 10573 if (list == null || which == null) { 10574 return false; 10575 } 10576 for (int i=list.size()-1; i>=0; i--) { 10577 for (int j=which.size()-1; j>=0; j--) { 10578 if (which.get(j).equals(list.get(i))) { 10579 return true; 10580 } 10581 } 10582 } 10583 return false; 10584 } 10585 10586 @GuardedBy("mPackages") 10587 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLocked( 10588 PackageParser.Package updatedPkg, 10589 Map<String, PackageParser.Package> availablePackages) { 10590 ArrayList<PackageParser.Package> resultList = null; 10591 // Set of all descendants of a library; used to eliminate cycles 10592 ArraySet<String> descendants = null; 10593 // The current list of packages that need updating 10594 ArrayList<PackageParser.Package> needsUpdating = null; 10595 if (updatedPkg != null) { 10596 needsUpdating = new ArrayList<>(1); 10597 needsUpdating.add(updatedPkg); 10598 } 10599 do { 10600 final PackageParser.Package changingPkg = 10601 (needsUpdating == null) ? null : needsUpdating.remove(0); 10602 for (int i = mPackages.size() - 1; i >= 0; --i) { 10603 final PackageParser.Package pkg = mPackages.valueAt(i); 10604 if (changingPkg != null 10605 && !hasString(pkg.usesLibraries, changingPkg.libraryNames) 10606 && !hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames) 10607 && !ArrayUtils.contains(pkg.usesStaticLibraries, 10608 changingPkg.staticSharedLibName)) { 10609 continue; 10610 } 10611 if (resultList == null) { 10612 resultList = new ArrayList<>(); 10613 } 10614 resultList.add(pkg); 10615 // if we're updating a shared library, all of its descendants must be updated 10616 if (changingPkg != null) { 10617 if (descendants == null) { 10618 descendants = new ArraySet<>(); 10619 } 10620 if (!descendants.contains(pkg.packageName)) { 10621 descendants.add(pkg.packageName); 10622 needsUpdating.add(pkg); 10623 } 10624 } 10625 try { 10626 updateSharedLibrariesLocked(pkg, changingPkg, availablePackages); 10627 } catch (PackageManagerException e) { 10628 // If a system app update or an app and a required lib missing we 10629 // delete the package and for updated system apps keep the data as 10630 // it is better for the user to reinstall than to be in an limbo 10631 // state. Also libs disappearing under an app should never happen 10632 // - just in case. 10633 if (!pkg.isSystem() || pkg.isUpdatedSystemApp()) { 10634 final int flags = pkg.isUpdatedSystemApp() 10635 ? PackageManager.DELETE_KEEP_DATA : 0; 10636 deletePackageLIF(pkg.packageName, null, true, sUserManager.getUserIds(), 10637 flags , null, true, null); 10638 } 10639 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 10640 } 10641 } 10642 } while (needsUpdating != null && needsUpdating.size() > 0); 10643 return resultList; 10644 } 10645 10646 @GuardedBy({"mInstallLock", "mPackages"}) 10647 private List<ScanResult> scanPackageTracedLI(PackageParser.Package pkg, 10648 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10649 @Nullable UserHandle user) throws PackageManagerException { 10650 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 10651 // If the package has children and this is the first dive in the function 10652 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 10653 // whether all packages (parent and children) would be successfully scanned 10654 // before the actual scan since scanning mutates internal state and we want 10655 // to atomically install the package and its children. 10656 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 10657 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 10658 scanFlags |= SCAN_CHECK_ONLY; 10659 } 10660 } else { 10661 scanFlags &= ~SCAN_CHECK_ONLY; 10662 } 10663 10664 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 10665 final List<ScanResult> scanResults = new ArrayList<>(1 + childCount); 10666 try { 10667 // Scan the parent 10668 scanResults.add(scanPackageNewLI(pkg, parseFlags, scanFlags, currentTime, user)); 10669 // Scan the children 10670 for (int i = 0; i < childCount; i++) { 10671 PackageParser.Package childPkg = pkg.childPackages.get(i); 10672 scanResults.add(scanPackageNewLI(childPkg, parseFlags, 10673 scanFlags, currentTime, user)); 10674 } 10675 } finally { 10676 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10677 } 10678 10679 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 10680 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 10681 } 10682 10683 return scanResults; 10684 } 10685 10686 /** The result of a package scan. */ 10687 @VisibleForTesting 10688 static class ScanResult { 10689 /** The request that initiated the scan that produced this result. */ 10690 public final ScanRequest request; 10691 /** Whether or not the package scan was successful */ 10692 public final boolean success; 10693 /** 10694 * Whether or not the original PackageSetting needs to be updated with this result on 10695 * commit. 10696 */ 10697 public final boolean existingSettingCopied; 10698 /** 10699 * The final package settings. This may be the same object passed in 10700 * the {@link ScanRequest}, but, with modified values. 10701 */ 10702 @Nullable public final PackageSetting pkgSetting; 10703 /** ABI code paths that have changed in the package scan */ 10704 @Nullable public final List<String> changedAbiCodePath; 10705 10706 public final SharedLibraryInfo staticSharedLibraryInfo; 10707 10708 public final List<SharedLibraryInfo> dynamicSharedLibraryInfos; 10709 10710 public ScanResult( 10711 ScanRequest request, boolean success, 10712 @Nullable PackageSetting pkgSetting, 10713 @Nullable List<String> changedAbiCodePath, boolean existingSettingCopied, 10714 SharedLibraryInfo staticSharedLibraryInfo, 10715 List<SharedLibraryInfo> dynamicSharedLibraryInfos) { 10716 this.request = request; 10717 this.success = success; 10718 this.pkgSetting = pkgSetting; 10719 this.changedAbiCodePath = changedAbiCodePath; 10720 this.existingSettingCopied = existingSettingCopied; 10721 this.staticSharedLibraryInfo = staticSharedLibraryInfo; 10722 this.dynamicSharedLibraryInfos = dynamicSharedLibraryInfos; 10723 } 10724 } 10725 10726 /** A package to be scanned */ 10727 @VisibleForTesting 10728 static class ScanRequest { 10729 /** The parsed package */ 10730 @NonNull public final PackageParser.Package pkg; 10731 /** The package this package replaces */ 10732 @Nullable public final PackageParser.Package oldPkg; 10733 /** Shared user settings, if the package has a shared user */ 10734 @Nullable public final SharedUserSetting sharedUserSetting; 10735 /** 10736 * Package settings of the currently installed version. 10737 * <p><em>IMPORTANT:</em> The contents of this object may be modified 10738 * during scan. 10739 */ 10740 @Nullable public final PackageSetting pkgSetting; 10741 /** A copy of the settings for the currently installed version */ 10742 @Nullable public final PackageSetting oldPkgSetting; 10743 /** Package settings for the disabled version on the /system partition */ 10744 @Nullable public final PackageSetting disabledPkgSetting; 10745 /** Package settings for the installed version under its original package name */ 10746 @Nullable public final PackageSetting originalPkgSetting; 10747 /** The real package name of a renamed application */ 10748 @Nullable public final String realPkgName; 10749 public final @ParseFlags int parseFlags; 10750 public final @ScanFlags int scanFlags; 10751 /** The user for which the package is being scanned */ 10752 @Nullable public final UserHandle user; 10753 /** Whether or not the platform package is being scanned */ 10754 public final boolean isPlatformPackage; 10755 public ScanRequest( 10756 @NonNull PackageParser.Package pkg, 10757 @Nullable SharedUserSetting sharedUserSetting, 10758 @Nullable PackageParser.Package oldPkg, 10759 @Nullable PackageSetting pkgSetting, 10760 @Nullable PackageSetting disabledPkgSetting, 10761 @Nullable PackageSetting originalPkgSetting, 10762 @Nullable String realPkgName, 10763 @ParseFlags int parseFlags, 10764 @ScanFlags int scanFlags, 10765 boolean isPlatformPackage, 10766 @Nullable UserHandle user) { 10767 this.pkg = pkg; 10768 this.oldPkg = oldPkg; 10769 this.pkgSetting = pkgSetting; 10770 this.sharedUserSetting = sharedUserSetting; 10771 this.oldPkgSetting = pkgSetting == null ? null : new PackageSetting(pkgSetting); 10772 this.disabledPkgSetting = disabledPkgSetting; 10773 this.originalPkgSetting = originalPkgSetting; 10774 this.realPkgName = realPkgName; 10775 this.parseFlags = parseFlags; 10776 this.scanFlags = scanFlags; 10777 this.isPlatformPackage = isPlatformPackage; 10778 this.user = user; 10779 } 10780 } 10781 10782 /** 10783 * Returns the actual scan flags depending upon the state of the other settings. 10784 * <p>Updated system applications will not have the following flags set 10785 * by default and need to be adjusted after the fact: 10786 * <ul> 10787 * <li>{@link #SCAN_AS_SYSTEM}</li> 10788 * <li>{@link #SCAN_AS_PRIVILEGED}</li> 10789 * <li>{@link #SCAN_AS_OEM}</li> 10790 * <li>{@link #SCAN_AS_VENDOR}</li> 10791 * <li>{@link #SCAN_AS_PRODUCT}</li> 10792 * <li>{@link #SCAN_AS_SYSTEM_EXT}</li> 10793 * <li>{@link #SCAN_AS_INSTANT_APP}</li> 10794 * <li>{@link #SCAN_AS_VIRTUAL_PRELOAD}</li> 10795 * <li>{@link #SCAN_AS_ODM}</li> 10796 * </ul> 10797 */ 10798 private @ScanFlags int adjustScanFlags(@ScanFlags int scanFlags, 10799 PackageSetting pkgSetting, PackageSetting disabledPkgSetting, UserHandle user, 10800 PackageParser.Package pkg) { 10801 10802 // TODO(patb): Do away entirely with disabledPkgSetting here. PkgSetting will always contain 10803 // the correct isSystem value now that we don't disable system packages before scan. 10804 final PackageSetting systemPkgSetting = 10805 (scanFlags & SCAN_NEW_INSTALL) != 0 && disabledPkgSetting == null 10806 && pkgSetting != null && pkgSetting.isSystem() 10807 ? pkgSetting 10808 : disabledPkgSetting; 10809 if (systemPkgSetting != null) { 10810 // updated system application, must at least have SCAN_AS_SYSTEM 10811 scanFlags |= SCAN_AS_SYSTEM; 10812 if ((systemPkgSetting.pkgPrivateFlags 10813 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 10814 scanFlags |= SCAN_AS_PRIVILEGED; 10815 } 10816 if ((systemPkgSetting.pkgPrivateFlags 10817 & ApplicationInfo.PRIVATE_FLAG_OEM) != 0) { 10818 scanFlags |= SCAN_AS_OEM; 10819 } 10820 if ((systemPkgSetting.pkgPrivateFlags 10821 & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0) { 10822 scanFlags |= SCAN_AS_VENDOR; 10823 } 10824 if ((systemPkgSetting.pkgPrivateFlags 10825 & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0) { 10826 scanFlags |= SCAN_AS_PRODUCT; 10827 } 10828 if ((systemPkgSetting.pkgPrivateFlags 10829 & ApplicationInfo.PRIVATE_FLAG_SYSTEM_EXT) != 0) { 10830 scanFlags |= SCAN_AS_SYSTEM_EXT; 10831 } 10832 if ((systemPkgSetting.pkgPrivateFlags 10833 & ApplicationInfo.PRIVATE_FLAG_ODM) != 0) { 10834 scanFlags |= SCAN_AS_ODM; 10835 } 10836 } 10837 if (pkgSetting != null) { 10838 final int userId = ((user == null) ? 0 : user.getIdentifier()); 10839 if (pkgSetting.getInstantApp(userId)) { 10840 scanFlags |= SCAN_AS_INSTANT_APP; 10841 } 10842 if (pkgSetting.getVirtulalPreload(userId)) { 10843 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 10844 } 10845 } 10846 10847 // Scan as privileged apps that share a user with a priv-app. 10848 final boolean skipVendorPrivilegeScan = ((scanFlags & SCAN_AS_VENDOR) != 0) 10849 && SystemProperties.getInt("ro.vndk.version", 28) < 28; 10850 if (((scanFlags & SCAN_AS_PRIVILEGED) == 0) 10851 && !pkg.isPrivileged() 10852 && (pkg.mSharedUserId != null) 10853 && !skipVendorPrivilegeScan) { 10854 SharedUserSetting sharedUserSetting = null; 10855 try { 10856 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 10857 } catch (PackageManagerException ignore) {} 10858 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 10859 // Exempt SharedUsers signed with the platform key. 10860 // TODO(b/72378145) Fix this exemption. Force signature apps 10861 // to whitelist their privileged permissions just like other 10862 // priv-apps. 10863 synchronized (mPackages) { 10864 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 10865 if ((compareSignatures(platformPkgSetting.signatures.mSigningDetails.signatures, 10866 pkg.mSigningDetails.signatures) != PackageManager.SIGNATURE_MATCH)) { 10867 scanFlags |= SCAN_AS_PRIVILEGED; 10868 } 10869 } 10870 } 10871 } 10872 10873 return scanFlags; 10874 } 10875 10876 // TODO: scanPackageNewLI() and scanPackageOnly() should be merged. But, first, commiting 10877 // the results / removing app data needs to be moved up a level to the callers of this 10878 // method. Also, we need to solve the problem of potentially creating a new shared user 10879 // setting. That can probably be done later and patch things up after the fact. 10880 @GuardedBy({"mInstallLock", "mPackages"}) 10881 private ScanResult scanPackageNewLI(@NonNull PackageParser.Package pkg, 10882 final @ParseFlags int parseFlags, @ScanFlags int scanFlags, long currentTime, 10883 @Nullable UserHandle user) throws PackageManagerException { 10884 10885 final String renamedPkgName = mSettings.getRenamedPackageLPr(pkg.mRealPackage); 10886 final String realPkgName = getRealPackageName(pkg, renamedPkgName); 10887 if (realPkgName != null) { 10888 ensurePackageRenamed(pkg, renamedPkgName); 10889 } 10890 final PackageSetting originalPkgSetting = getOriginalPackageLocked(pkg, renamedPkgName); 10891 final PackageSetting pkgSetting = mSettings.getPackageLPr(pkg.packageName); 10892 final PackageSetting disabledPkgSetting = 10893 mSettings.getDisabledSystemPkgLPr(pkg.packageName); 10894 10895 if (mTransferedPackages.contains(pkg.packageName)) { 10896 Slog.w(TAG, "Package " + pkg.packageName 10897 + " was transferred to another, but its .apk remains"); 10898 } 10899 10900 scanFlags = adjustScanFlags(scanFlags, pkgSetting, disabledPkgSetting, user, pkg); 10901 synchronized (mPackages) { 10902 applyPolicy(pkg, parseFlags, scanFlags, mPlatformPackage); 10903 assertPackageIsValid(pkg, parseFlags, scanFlags); 10904 10905 SharedUserSetting sharedUserSetting = null; 10906 if (pkg.mSharedUserId != null) { 10907 // SIDE EFFECTS; may potentially allocate a new shared user 10908 sharedUserSetting = mSettings.getSharedUserLPw( 10909 pkg.mSharedUserId, 0 /*pkgFlags*/, 0 /*pkgPrivateFlags*/, true /*create*/); 10910 if (DEBUG_PACKAGE_SCANNING) { 10911 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 10912 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId 10913 + " (uid=" + sharedUserSetting.userId + "):" 10914 + " packages=" + sharedUserSetting.packages); 10915 } 10916 } 10917 final ScanRequest request = new ScanRequest(pkg, sharedUserSetting, 10918 pkgSetting == null ? null : pkgSetting.pkg, pkgSetting, disabledPkgSetting, 10919 originalPkgSetting, realPkgName, parseFlags, scanFlags, 10920 (pkg == mPlatformPackage), user); 10921 return scanPackageOnlyLI(request, mInjector, mFactoryTest, currentTime); 10922 } 10923 } 10924 10925 10926 /** 10927 * Prepares the system to commit a {@link ScanResult} in a way that will not fail by registering 10928 * the app ID required for reconcile. 10929 * @return {@code true} if a new app ID was registered and will need to be cleaned up on 10930 * failure. 10931 */ 10932 private boolean optimisticallyRegisterAppId(@NonNull ScanResult result) 10933 throws PackageManagerException { 10934 if (!result.existingSettingCopied) { 10935 // THROWS: when we can't allocate a user id. add call to check if there's 10936 // enough space to ensure we won't throw; otherwise, don't modify state 10937 return mSettings.registerAppIdLPw(result.pkgSetting); 10938 } 10939 return false; 10940 } 10941 10942 /** 10943 * Reverts any app ID creation that were made by 10944 * {@link #optimisticallyRegisterAppId(ScanResult)}. Note: this is only necessary if the 10945 * referenced method returned true. 10946 */ 10947 private void cleanUpAppIdCreation(@NonNull ScanResult result) { 10948 // iff we've acquired an app ID for a new package setting, remove it so that it can be 10949 // acquired by another request. 10950 if (result.pkgSetting.appId > 0) { 10951 mSettings.removeAppIdLPw(result.pkgSetting.appId); 10952 } 10953 } 10954 10955 /** 10956 * Commits the package scan and modifies system state. 10957 * <p><em>WARNING:</em> The method may throw an excpetion in the middle 10958 * of committing the package, leaving the system in an inconsistent state. 10959 * This needs to be fixed so, once we get to this point, no errors are 10960 * possible and the system is not left in an inconsistent state. 10961 */ 10962 @GuardedBy({"mPackages", "mInstallLock"}) 10963 private void commitReconciledScanResultLocked(@NonNull ReconciledPackage reconciledPkg) { 10964 final ScanResult result = reconciledPkg.scanResult; 10965 final ScanRequest request = result.request; 10966 final PackageParser.Package pkg = request.pkg; 10967 final PackageParser.Package oldPkg = request.oldPkg; 10968 final @ParseFlags int parseFlags = request.parseFlags; 10969 final @ScanFlags int scanFlags = request.scanFlags; 10970 final PackageSetting oldPkgSetting = request.oldPkgSetting; 10971 final PackageSetting originalPkgSetting = request.originalPkgSetting; 10972 final UserHandle user = request.user; 10973 final String realPkgName = request.realPkgName; 10974 final List<String> changedAbiCodePath = result.changedAbiCodePath; 10975 final PackageSetting pkgSetting; 10976 if (request.pkgSetting != null && request.pkgSetting.sharedUser != null 10977 && request.pkgSetting.sharedUser != result.pkgSetting.sharedUser) { 10978 // shared user changed, remove from old shared user 10979 request.pkgSetting.sharedUser.removePackage(request.pkgSetting); 10980 } 10981 if (result.existingSettingCopied) { 10982 pkgSetting = request.pkgSetting; 10983 pkgSetting.updateFrom(result.pkgSetting); 10984 pkg.mExtras = pkgSetting; 10985 } else { 10986 pkgSetting = result.pkgSetting; 10987 if (originalPkgSetting != null) { 10988 mSettings.addRenamedPackageLPw(pkg.packageName, originalPkgSetting.name); 10989 } 10990 if (originalPkgSetting != null && (scanFlags & SCAN_CHECK_ONLY) == 0) { 10991 mTransferedPackages.add(originalPkgSetting.name); 10992 } 10993 } 10994 if (pkgSetting.sharedUser != null) { 10995 pkgSetting.sharedUser.addPackage(pkgSetting); 10996 } 10997 // TODO(toddke): Consider a method specifically for modifying the Package object 10998 // post scan; or, moving this stuff out of the Package object since it has nothing 10999 // to do with the package on disk. 11000 // We need to have this here because addUserToSettingLPw() is sometimes responsible 11001 // for creating the application ID. If we did this earlier, we would be saving the 11002 // correct ID. 11003 pkg.applicationInfo.uid = pkgSetting.appId; 11004 11005 mSettings.writeUserRestrictionsLPw(pkgSetting, oldPkgSetting); 11006 11007 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realPkgName != null) { 11008 mTransferedPackages.add(pkg.packageName); 11009 } 11010 11011 if (reconciledPkg.collectedSharedLibraryInfos != null) { 11012 executeSharedLibrariesUpdateLPr(pkg, null, reconciledPkg.collectedSharedLibraryInfos); 11013 } 11014 11015 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 11016 if (reconciledPkg.removeAppKeySetData) { 11017 ksms.removeAppKeySetDataLPw(pkg.packageName); 11018 } 11019 if (reconciledPkg.sharedUserSignaturesChanged) { 11020 pkgSetting.sharedUser.signaturesChanged = Boolean.TRUE; 11021 pkgSetting.sharedUser.signatures.mSigningDetails = reconciledPkg.signingDetails; 11022 } 11023 pkgSetting.signatures.mSigningDetails = reconciledPkg.signingDetails; 11024 11025 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 11026 // This package wants to adopt ownership of permissions from 11027 // another package. 11028 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 11029 final String origName = pkg.mAdoptPermissions.get(i); 11030 final PackageSetting orig = mSettings.getPackageLPr(origName); 11031 if (orig != null) { 11032 if (verifyPackageUpdateLPr(orig, pkg)) { 11033 Slog.i(TAG, "Adopting permissions from " + origName + " to " 11034 + pkg.packageName); 11035 mSettings.mPermissions.transferPermissions(origName, pkg.packageName); 11036 } 11037 } 11038 } 11039 } 11040 11041 if (changedAbiCodePath != null && changedAbiCodePath.size() > 0) { 11042 for (int i = changedAbiCodePath.size() - 1; i >= 0; --i) { 11043 final String codePathString = changedAbiCodePath.get(i); 11044 try { 11045 mInstaller.rmdex(codePathString, 11046 getDexCodeInstructionSet(getPreferredInstructionSet())); 11047 } catch (InstallerException ignored) { 11048 } 11049 } 11050 } 11051 11052 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 11053 if (oldPkgSetting != null) { 11054 synchronized (mPackages) { 11055 mSettings.mPackages.put(oldPkgSetting.name, oldPkgSetting); 11056 } 11057 } 11058 } else { 11059 final int userId = user == null ? 0 : user.getIdentifier(); 11060 // Modify state for the given package setting 11061 commitPackageSettings(pkg, oldPkg, pkgSetting, scanFlags, 11062 (parseFlags & PackageParser.PARSE_CHATTY) != 0 /*chatty*/, reconciledPkg); 11063 if (pkgSetting.getInstantApp(userId)) { 11064 mInstantAppRegistry.addInstantAppLPw(userId, pkgSetting.appId); 11065 } 11066 } 11067 } 11068 11069 /** 11070 * Returns the "real" name of the package. 11071 * <p>This may differ from the package's actual name if the application has already 11072 * been installed under one of this package's original names. 11073 */ 11074 private static @Nullable String getRealPackageName(@NonNull PackageParser.Package pkg, 11075 @Nullable String renamedPkgName) { 11076 if (isPackageRenamed(pkg, renamedPkgName)) { 11077 return pkg.mRealPackage; 11078 } 11079 return null; 11080 } 11081 11082 /** Returns {@code true} if the package has been renamed. Otherwise, {@code false}. */ 11083 private static boolean isPackageRenamed(@NonNull PackageParser.Package pkg, 11084 @Nullable String renamedPkgName) { 11085 return pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(renamedPkgName); 11086 } 11087 11088 /** 11089 * Returns the original package setting. 11090 * <p>A package can migrate its name during an update. In this scenario, a package 11091 * designates a set of names that it considers as one of its original names. 11092 * <p>An original package must be signed identically and it must have the same 11093 * shared user [if any]. 11094 */ 11095 @GuardedBy("mPackages") 11096 private @Nullable PackageSetting getOriginalPackageLocked(@NonNull PackageParser.Package pkg, 11097 @Nullable String renamedPkgName) { 11098 if (!isPackageRenamed(pkg, renamedPkgName)) { 11099 return null; 11100 } 11101 for (int i = pkg.mOriginalPackages.size() - 1; i >= 0; --i) { 11102 final PackageSetting originalPs = 11103 mSettings.getPackageLPr(pkg.mOriginalPackages.get(i)); 11104 if (originalPs != null) { 11105 // the package is already installed under its original name... 11106 // but, should we use it? 11107 if (!verifyPackageUpdateLPr(originalPs, pkg)) { 11108 // the new package is incompatible with the original 11109 continue; 11110 } else if (originalPs.sharedUser != null) { 11111 if (!originalPs.sharedUser.name.equals(pkg.mSharedUserId)) { 11112 // the shared user id is incompatible with the original 11113 Slog.w(TAG, "Unable to migrate data from " + originalPs.name 11114 + " to " + pkg.packageName + ": old uid " 11115 + originalPs.sharedUser.name 11116 + " differs from " + pkg.mSharedUserId); 11117 continue; 11118 } 11119 // TODO: Add case when shared user id is added [b/28144775] 11120 } else { 11121 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 11122 + pkg.packageName + " to old name " + originalPs.name); 11123 } 11124 return originalPs; 11125 } 11126 } 11127 return null; 11128 } 11129 11130 /** 11131 * Renames the package if it was installed under a different name. 11132 * <p>When we've already installed the package under an original name, update 11133 * the new package so we can continue to have the old name. 11134 */ 11135 private static void ensurePackageRenamed(@NonNull PackageParser.Package pkg, 11136 @NonNull String renamedPackageName) { 11137 if (pkg.mOriginalPackages == null 11138 || !pkg.mOriginalPackages.contains(renamedPackageName) 11139 || pkg.packageName.equals(renamedPackageName)) { 11140 return; 11141 } 11142 pkg.setPackageName(renamedPackageName); 11143 } 11144 11145 /** 11146 * Applies the adjusted ABI calculated by 11147 * {@link PackageAbiHelper#getAdjustedAbiForSharedUser(Set, PackageParser.Package)} to all 11148 * relevant packages and settings. 11149 * @param sharedUserSetting The {@code SharedUserSetting} to adjust 11150 * @param scannedPackage the package being scanned or null 11151 * @param adjustedAbi the adjusted ABI calculated by {@link PackageAbiHelper} 11152 * @return the list of code paths that belong to packages that had their ABIs adjusted. 11153 */ 11154 private static List<String> applyAdjustedAbiToSharedUser(SharedUserSetting sharedUserSetting, 11155 PackageParser.Package scannedPackage, String adjustedAbi) { 11156 if (scannedPackage != null) { 11157 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 11158 } 11159 List<String> changedAbiCodePath = null; 11160 for (PackageSetting ps : sharedUserSetting.packages) { 11161 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 11162 if (ps.primaryCpuAbiString != null) { 11163 continue; 11164 } 11165 11166 ps.primaryCpuAbiString = adjustedAbi; 11167 if (ps.pkg != null && ps.pkg.applicationInfo != null 11168 && !TextUtils.equals( 11169 adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 11170 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 11171 if (DEBUG_ABI_SELECTION) { 11172 Slog.i(TAG, 11173 "Adjusting ABI for " + ps.name + " to " + adjustedAbi 11174 + " (scannedPackage=" 11175 + (scannedPackage != null ? scannedPackage : "null") 11176 + ")"); 11177 } 11178 if (changedAbiCodePath == null) { 11179 changedAbiCodePath = new ArrayList<>(); 11180 } 11181 changedAbiCodePath.add(ps.codePathString); 11182 } 11183 } 11184 } 11185 return changedAbiCodePath; 11186 } 11187 11188 11189 /** 11190 * Just scans the package without any side effects. 11191 * <p>Not entirely true at the moment. There is still one side effect -- this 11192 * method potentially modifies a live {@link PackageSetting} object representing 11193 * the package being scanned. This will be resolved in the future. 11194 * 11195 * @param injector injector for acquiring dependencies 11196 * @param request Information about the package to be scanned 11197 * @param isUnderFactoryTest Whether or not the device is under factory test 11198 * @param currentTime The current time, in millis 11199 * @return The results of the scan 11200 */ 11201 @GuardedBy("mInstallLock") 11202 @VisibleForTesting 11203 @NonNull 11204 static ScanResult scanPackageOnlyLI(@NonNull ScanRequest request, 11205 Injector injector, 11206 boolean isUnderFactoryTest, long currentTime) 11207 throws PackageManagerException { 11208 final PackageAbiHelper packageAbiHelper = injector.getAbiHelper(); 11209 final UserManagerInternal userManager = injector.getUserManager(); 11210 final PackageParser.Package pkg = request.pkg; 11211 PackageSetting pkgSetting = request.pkgSetting; 11212 final PackageSetting disabledPkgSetting = request.disabledPkgSetting; 11213 final PackageSetting originalPkgSetting = request.originalPkgSetting; 11214 final @ParseFlags int parseFlags = request.parseFlags; 11215 final @ScanFlags int scanFlags = request.scanFlags; 11216 final String realPkgName = request.realPkgName; 11217 final SharedUserSetting sharedUserSetting = request.sharedUserSetting; 11218 final UserHandle user = request.user; 11219 final boolean isPlatformPackage = request.isPlatformPackage; 11220 11221 List<String> changedAbiCodePath = null; 11222 11223 if (DEBUG_PACKAGE_SCANNING) { 11224 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 11225 Log.d(TAG, "Scanning package " + pkg.packageName); 11226 } 11227 11228 // Initialize package source and resource directories 11229 final File scanFile = new File(pkg.codePath); 11230 final File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 11231 final File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 11232 11233 // We keep references to the derived CPU Abis from settings in oder to reuse 11234 // them in the case where we're not upgrading or booting for the first time. 11235 String primaryCpuAbiFromSettings = null; 11236 String secondaryCpuAbiFromSettings = null; 11237 boolean needToDeriveAbi = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 11238 if (!needToDeriveAbi) { 11239 if (pkgSetting != null) { 11240 primaryCpuAbiFromSettings = pkgSetting.primaryCpuAbiString; 11241 secondaryCpuAbiFromSettings = pkgSetting.secondaryCpuAbiString; 11242 } else { 11243 // Re-scanning a system package after uninstalling updates; need to derive ABI 11244 needToDeriveAbi = true; 11245 } 11246 } 11247 11248 if (pkgSetting != null && pkgSetting.sharedUser != sharedUserSetting) { 11249 PackageManagerService.reportSettingsProblem(Log.WARN, 11250 "Package " + pkg.packageName + " shared user changed from " 11251 + (pkgSetting.sharedUser != null 11252 ? pkgSetting.sharedUser.name : "<nothing>") 11253 + " to " 11254 + (sharedUserSetting != null ? sharedUserSetting.name : "<nothing>") 11255 + "; replacing with new"); 11256 pkgSetting = null; 11257 } 11258 11259 String[] usesStaticLibraries = null; 11260 if (pkg.usesStaticLibraries != null) { 11261 usesStaticLibraries = new String[pkg.usesStaticLibraries.size()]; 11262 pkg.usesStaticLibraries.toArray(usesStaticLibraries); 11263 } 11264 final boolean createNewPackage = (pkgSetting == null); 11265 if (createNewPackage) { 11266 final String parentPackageName = (pkg.parentPackage != null) 11267 ? pkg.parentPackage.packageName : null; 11268 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 11269 final boolean virtualPreload = (scanFlags & SCAN_AS_VIRTUAL_PRELOAD) != 0; 11270 // REMOVE SharedUserSetting from method; update in a separate call 11271 pkgSetting = Settings.createNewSetting(pkg.packageName, originalPkgSetting, 11272 disabledPkgSetting, realPkgName, sharedUserSetting, destCodeFile, 11273 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 11274 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 11275 pkg.mVersionCode, pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 11276 user, true /*allowInstall*/, instantApp, virtualPreload, 11277 parentPackageName, pkg.getChildPackageNames(), 11278 UserManagerService.getInstance(), usesStaticLibraries, 11279 pkg.usesStaticLibrariesVersions); 11280 } else { 11281 // make a deep copy to avoid modifying any existing system state. 11282 pkgSetting = new PackageSetting(pkgSetting); 11283 pkgSetting.pkg = pkg; 11284 11285 // REMOVE SharedUserSetting from method; update in a separate call. 11286 // 11287 // TODO(narayan): This update is bogus. nativeLibraryDir & primaryCpuAbi, 11288 // secondaryCpuAbi are not known at this point so we always update them 11289 // to null here, only to reset them at a later point. 11290 Settings.updatePackageSetting(pkgSetting, disabledPkgSetting, sharedUserSetting, 11291 destCodeFile, destResourceFile, pkg.applicationInfo.nativeLibraryDir, 11292 pkg.applicationInfo.primaryCpuAbi, pkg.applicationInfo.secondaryCpuAbi, 11293 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 11294 pkg.getChildPackageNames(), UserManagerService.getInstance(), 11295 usesStaticLibraries, pkg.usesStaticLibrariesVersions); 11296 } 11297 if (createNewPackage && originalPkgSetting != null) { 11298 // This is the initial transition from the original package, so, 11299 // fix up the new package's name now. We must do this after looking 11300 // up the package under its new name, so getPackageLP takes care of 11301 // fiddling things correctly. 11302 pkg.setPackageName(originalPkgSetting.name); 11303 11304 // File a report about this. 11305 String msg = "New package " + pkgSetting.realName 11306 + " renamed to replace old package " + pkgSetting.name; 11307 reportSettingsProblem(Log.WARN, msg); 11308 } 11309 11310 final int userId = (user == null ? UserHandle.USER_SYSTEM : user.getIdentifier()); 11311 // for existing packages, change the install state; but, only if it's explicitly specified 11312 if (!createNewPackage) { 11313 final boolean instantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 11314 final boolean fullApp = (scanFlags & SCAN_AS_FULL_APP) != 0; 11315 setInstantAppForUser(userManager, pkgSetting, userId, instantApp, fullApp); 11316 } 11317 // TODO(patb): see if we can do away with disabled check here. 11318 if (disabledPkgSetting != null 11319 || (0 != (scanFlags & SCAN_NEW_INSTALL) 11320 && pkgSetting != null && pkgSetting.isSystem())) { 11321 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 11322 } 11323 11324 // Apps which share a sharedUserId must be placed in the same selinux domain. If this 11325 // package is the first app installed as this shared user, set seInfoTargetSdkVersion to its 11326 // targetSdkVersion. These are later adjusted in PackageManagerService's constructor to be 11327 // the lowest targetSdkVersion of all apps within the shared user, which corresponds to the 11328 // least restrictive selinux domain. 11329 // NOTE: As new packages are installed / updated, the shared user's seinfoTargetSdkVersion 11330 // will NOT be modified until next boot, even if a lower targetSdkVersion is used. This 11331 // ensures that all packages continue to run in the same selinux domain. 11332 final int targetSdkVersion = 11333 ((sharedUserSetting != null) && (sharedUserSetting.packages.size() != 0)) ? 11334 sharedUserSetting.seInfoTargetSdkVersion : pkg.applicationInfo.targetSdkVersion; 11335 // TODO(b/71593002): isPrivileged for sharedUser and appInfo should never be out of sync. 11336 // They currently can be if the sharedUser apps are signed with the platform key. 11337 final boolean isPrivileged = (sharedUserSetting != null) ? 11338 sharedUserSetting.isPrivileged() | pkg.isPrivileged() : pkg.isPrivileged(); 11339 11340 pkg.applicationInfo.seInfo = SELinuxMMAC.getSeInfo(pkg, isPrivileged, 11341 targetSdkVersion); 11342 pkg.applicationInfo.seInfoUser = SELinuxUtil.assignSeinfoUser(pkgSetting.readUserState( 11343 userId == UserHandle.USER_ALL ? UserHandle.USER_SYSTEM : userId)); 11344 11345 pkg.mExtras = pkgSetting; 11346 pkg.applicationInfo.processName = fixProcessName( 11347 pkg.applicationInfo.packageName, 11348 pkg.applicationInfo.processName); 11349 11350 if (!isPlatformPackage) { 11351 // Get all of our default paths setup 11352 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 11353 } 11354 11355 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 11356 11357 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 11358 if (needToDeriveAbi) { 11359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "derivePackageAbi"); 11360 final boolean extractNativeLibs = !pkg.isLibrary(); 11361 final Pair<PackageAbiHelper.Abis, PackageAbiHelper.NativeLibraryPaths> derivedAbi = 11362 packageAbiHelper.derivePackageAbi(pkg, cpuAbiOverride, extractNativeLibs); 11363 derivedAbi.first.applyTo(pkg); 11364 derivedAbi.second.applyTo(pkg); 11365 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 11366 11367 // Some system apps still use directory structure for native libraries 11368 // in which case we might end up not detecting abi solely based on apk 11369 // structure. Try to detect abi based on directory structure. 11370 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 11371 pkg.applicationInfo.primaryCpuAbi == null) { 11372 final PackageAbiHelper.Abis abis = packageAbiHelper.getBundledAppAbis( 11373 pkg); 11374 abis.applyTo(pkg); 11375 abis.applyTo(pkgSetting); 11376 final PackageAbiHelper.NativeLibraryPaths nativeLibraryPaths = 11377 packageAbiHelper.getNativeLibraryPaths(pkg, sAppLib32InstallDir); 11378 nativeLibraryPaths.applyTo(pkg); 11379 } 11380 } else { 11381 // This is not a first boot or an upgrade, don't bother deriving the 11382 // ABI during the scan. Instead, trust the value that was stored in the 11383 // package setting. 11384 pkg.applicationInfo.primaryCpuAbi = primaryCpuAbiFromSettings; 11385 pkg.applicationInfo.secondaryCpuAbi = secondaryCpuAbiFromSettings; 11386 11387 final PackageAbiHelper.NativeLibraryPaths nativeLibraryPaths = 11388 packageAbiHelper.getNativeLibraryPaths(pkg, sAppLib32InstallDir); 11389 nativeLibraryPaths.applyTo(pkg); 11390 11391 if (DEBUG_ABI_SELECTION) { 11392 Slog.i(TAG, "Using ABIS and native lib paths from settings : " + 11393 pkg.packageName + " " + pkg.applicationInfo.primaryCpuAbi + ", " + 11394 pkg.applicationInfo.secondaryCpuAbi); 11395 } 11396 } 11397 } else { 11398 if ((scanFlags & SCAN_MOVE) != 0) { 11399 // We haven't run dex-opt for this move (since we've moved the compiled output too) 11400 // but we already have this packages package info in the PackageSetting. We just 11401 // use that and derive the native library path based on the new codepath. 11402 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 11403 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 11404 } 11405 11406 // Set native library paths again. For moves, the path will be updated based on the 11407 // ABIs we've determined above. For non-moves, the path will be updated based on the 11408 // ABIs we determined during compilation, but the path will depend on the final 11409 // package path (after the rename away from the stage path). 11410 final PackageAbiHelper.NativeLibraryPaths nativeLibraryPaths = 11411 packageAbiHelper.getNativeLibraryPaths(pkg, sAppLib32InstallDir); 11412 nativeLibraryPaths.applyTo(pkg); 11413 } 11414 11415 // This is a special case for the "system" package, where the ABI is 11416 // dictated by the zygote configuration (and init.rc). We should keep track 11417 // of this ABI so that we can deal with "normal" applications that run under 11418 // the same UID correctly. 11419 if (isPlatformPackage) { 11420 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 11421 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 11422 } 11423 11424 // If there's a mismatch between the abi-override in the package setting 11425 // and the abiOverride specified for the install. Warn about this because we 11426 // would've already compiled the app without taking the package setting into 11427 // account. 11428 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 11429 if (cpuAbiOverride == null && pkg.packageName != null) { 11430 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 11431 " for package " + pkg.packageName); 11432 } 11433 } 11434 11435 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 11436 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 11437 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 11438 11439 // Copy the derived override back to the parsed package, so that we can 11440 // update the package settings accordingly. 11441 pkg.cpuAbiOverride = cpuAbiOverride; 11442 11443 if (DEBUG_ABI_SELECTION) { 11444 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.packageName 11445 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 11446 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 11447 } 11448 11449 // Push the derived path down into PackageSettings so we know what to 11450 // clean up at uninstall time. 11451 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 11452 11453 if (DEBUG_ABI_SELECTION) { 11454 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 11455 " primary=" + pkg.applicationInfo.primaryCpuAbi + 11456 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 11457 } 11458 11459 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 11460 // We don't do this here during boot because we can do it all 11461 // at once after scanning all existing packages. 11462 // 11463 // We also do this *before* we perform dexopt on this package, so that 11464 // we can avoid redundant dexopts, and also to make sure we've got the 11465 // code and package path correct. 11466 changedAbiCodePath = applyAdjustedAbiToSharedUser(pkgSetting.sharedUser, pkg, 11467 packageAbiHelper.getAdjustedAbiForSharedUser( 11468 pkgSetting.sharedUser.packages, pkg)); 11469 } 11470 11471 if (isUnderFactoryTest && pkg.requestedPermissions.contains( 11472 android.Manifest.permission.FACTORY_TEST)) { 11473 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 11474 } 11475 11476 if (isSystemApp(pkg)) { 11477 pkgSetting.isOrphaned = true; 11478 } 11479 11480 // Take care of first install / last update times. 11481 final long scanFileTime = getLastModifiedTime(pkg); 11482 if (currentTime != 0) { 11483 if (pkgSetting.firstInstallTime == 0) { 11484 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 11485 } else if ((scanFlags & SCAN_UPDATE_TIME) != 0) { 11486 pkgSetting.lastUpdateTime = currentTime; 11487 } 11488 } else if (pkgSetting.firstInstallTime == 0) { 11489 // We need *something*. Take time time stamp of the file. 11490 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 11491 } else if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 11492 if (scanFileTime != pkgSetting.timeStamp) { 11493 // A package on the system image has changed; consider this 11494 // to be an update. 11495 pkgSetting.lastUpdateTime = scanFileTime; 11496 } 11497 } 11498 pkgSetting.setTimeStamp(scanFileTime); 11499 11500 pkgSetting.pkg = pkg; 11501 pkgSetting.pkgFlags = pkg.applicationInfo.flags; 11502 if (pkg.getLongVersionCode() != pkgSetting.versionCode) { 11503 pkgSetting.versionCode = pkg.getLongVersionCode(); 11504 } 11505 // Update volume if needed 11506 final String volumeUuid = pkg.applicationInfo.volumeUuid; 11507 if (!Objects.equals(volumeUuid, pkgSetting.volumeUuid)) { 11508 Slog.i(PackageManagerService.TAG, 11509 "Update" + (pkgSetting.isSystem() ? " system" : "") 11510 + " package " + pkg.packageName 11511 + " volume from " + pkgSetting.volumeUuid 11512 + " to " + volumeUuid); 11513 pkgSetting.volumeUuid = volumeUuid; 11514 } 11515 11516 SharedLibraryInfo staticSharedLibraryInfo = null; 11517 if (!TextUtils.isEmpty(pkg.staticSharedLibName)) { 11518 staticSharedLibraryInfo = SharedLibraryInfo.createForStatic(pkg); 11519 } 11520 List<SharedLibraryInfo> dynamicSharedLibraryInfos = null; 11521 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 11522 dynamicSharedLibraryInfos = new ArrayList<>(pkg.libraryNames.size()); 11523 for (String name : pkg.libraryNames) { 11524 dynamicSharedLibraryInfos.add(SharedLibraryInfo.createForDynamic(pkg, name)); 11525 } 11526 } 11527 11528 return new ScanResult(request, true, pkgSetting, changedAbiCodePath, 11529 !createNewPackage /* existingSettingCopied */, staticSharedLibraryInfo, 11530 dynamicSharedLibraryInfos); 11531 } 11532 11533 /** 11534 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 11535 */ 11536 private static boolean apkHasCode(String fileName) { 11537 StrictJarFile jarFile = null; 11538 try { 11539 jarFile = new StrictJarFile(fileName, 11540 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 11541 return jarFile.findEntry("classes.dex") != null; 11542 } catch (IOException ignore) { 11543 } finally { 11544 try { 11545 if (jarFile != null) { 11546 jarFile.close(); 11547 } 11548 } catch (IOException ignore) {} 11549 } 11550 return false; 11551 } 11552 11553 /** 11554 * Enforces code policy for the package. This ensures that if an APK has 11555 * declared hasCode="true" in its manifest that the APK actually contains 11556 * code. 11557 * 11558 * @throws PackageManagerException If bytecode could not be found when it should exist 11559 */ 11560 private static void assertCodePolicy(PackageParser.Package pkg) 11561 throws PackageManagerException { 11562 final boolean shouldHaveCode = 11563 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 11564 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 11565 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11566 "Package " + pkg.baseCodePath + " code is missing"); 11567 } 11568 11569 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 11570 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 11571 final boolean splitShouldHaveCode = 11572 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 11573 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 11574 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11575 "Package " + pkg.splitCodePaths[i] + " code is missing"); 11576 } 11577 } 11578 } 11579 } 11580 11581 /** 11582 * Applies policy to the parsed package based upon the given policy flags. 11583 * Ensures the package is in a good state. 11584 * <p> 11585 * Implementation detail: This method must NOT have any side effect. It would 11586 * ideally be static, but, it requires locks to read system state. 11587 */ 11588 private static void applyPolicy(PackageParser.Package pkg, final @ParseFlags int parseFlags, 11589 final @ScanFlags int scanFlags, PackageParser.Package platformPkg) { 11590 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11591 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 11592 if (pkg.applicationInfo.isDirectBootAware()) { 11593 // we're direct boot aware; set for all components 11594 for (PackageParser.Service s : pkg.services) { 11595 s.info.encryptionAware = s.info.directBootAware = true; 11596 } 11597 for (PackageParser.Provider p : pkg.providers) { 11598 p.info.encryptionAware = p.info.directBootAware = true; 11599 } 11600 for (PackageParser.Activity a : pkg.activities) { 11601 a.info.encryptionAware = a.info.directBootAware = true; 11602 } 11603 for (PackageParser.Activity r : pkg.receivers) { 11604 r.info.encryptionAware = r.info.directBootAware = true; 11605 } 11606 } 11607 if (compressedFileExists(pkg.codePath)) { 11608 pkg.isStub = true; 11609 } 11610 } else { 11611 // non system apps can't be flagged as core 11612 pkg.coreApp = false; 11613 // clear flags not applicable to regular apps 11614 pkg.applicationInfo.flags &= 11615 ~ApplicationInfo.FLAG_PERSISTENT; 11616 pkg.applicationInfo.privateFlags &= 11617 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 11618 pkg.applicationInfo.privateFlags &= 11619 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 11620 // cap permission priorities 11621 if (pkg.permissionGroups != null && pkg.permissionGroups.size() > 0) { 11622 for (int i = pkg.permissionGroups.size() - 1; i >= 0; --i) { 11623 pkg.permissionGroups.get(i).info.priority = 0; 11624 } 11625 } 11626 } 11627 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 11628 // clear protected broadcasts 11629 pkg.protectedBroadcasts = null; 11630 // ignore export request for single user receivers 11631 if (pkg.receivers != null) { 11632 for (int i = pkg.receivers.size() - 1; i >= 0; --i) { 11633 final PackageParser.Activity receiver = pkg.receivers.get(i); 11634 if ((receiver.info.flags & ActivityInfo.FLAG_SINGLE_USER) != 0) { 11635 receiver.info.exported = false; 11636 } 11637 } 11638 } 11639 // ignore export request for single user services 11640 if (pkg.services != null) { 11641 for (int i = pkg.services.size() - 1; i >= 0; --i) { 11642 final PackageParser.Service service = pkg.services.get(i); 11643 if ((service.info.flags & ServiceInfo.FLAG_SINGLE_USER) != 0) { 11644 service.info.exported = false; 11645 } 11646 } 11647 } 11648 // ignore export request for single user providers 11649 if (pkg.providers != null) { 11650 for (int i = pkg.providers.size() - 1; i >= 0; --i) { 11651 final PackageParser.Provider provider = pkg.providers.get(i); 11652 if ((provider.info.flags & ProviderInfo.FLAG_SINGLE_USER) != 0) { 11653 provider.info.exported = false; 11654 } 11655 } 11656 } 11657 } 11658 11659 if ((scanFlags & SCAN_AS_PRIVILEGED) != 0) { 11660 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 11661 } 11662 11663 if ((scanFlags & SCAN_AS_OEM) != 0) { 11664 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_OEM; 11665 } 11666 11667 if ((scanFlags & SCAN_AS_VENDOR) != 0) { 11668 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_VENDOR; 11669 } 11670 11671 if ((scanFlags & SCAN_AS_PRODUCT) != 0) { 11672 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRODUCT; 11673 } 11674 11675 if ((scanFlags & SCAN_AS_SYSTEM_EXT) != 0) { 11676 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_SYSTEM_EXT; 11677 } 11678 11679 if ((scanFlags & SCAN_AS_ODM) != 0) { 11680 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_ODM; 11681 } 11682 11683 // Check if the package is signed with the same key as the platform package. 11684 if (PLATFORM_PACKAGE_NAME.equals(pkg.packageName) || 11685 (platformPkg != null && compareSignatures( 11686 platformPkg.mSigningDetails.signatures, 11687 pkg.mSigningDetails.signatures) == PackageManager.SIGNATURE_MATCH)) { 11688 pkg.applicationInfo.privateFlags |= 11689 ApplicationInfo.PRIVATE_FLAG_SIGNED_WITH_PLATFORM_KEY; 11690 } 11691 11692 if (!isSystemApp(pkg)) { 11693 // Only system apps can use these features. 11694 pkg.mOriginalPackages = null; 11695 pkg.mRealPackage = null; 11696 pkg.mAdoptPermissions = null; 11697 } 11698 11699 PackageBackwardCompatibility.modifySharedLibraries(pkg); 11700 } 11701 11702 private static @NonNull <T> T assertNotNull(@Nullable T object, String message) 11703 throws PackageManagerException { 11704 if (object == null) { 11705 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, message); 11706 } 11707 return object; 11708 } 11709 11710 /** 11711 * Asserts the parsed package is valid according to the given policy. If the 11712 * package is invalid, for whatever reason, throws {@link PackageManagerException}. 11713 * <p> 11714 * Implementation detail: This method must NOT have any side effects. It would 11715 * ideally be static, but, it requires locks to read system state. 11716 * 11717 * @throws PackageManagerException If the package fails any of the validation checks 11718 */ 11719 private void assertPackageIsValid(PackageParser.Package pkg, final @ParseFlags int parseFlags, 11720 final @ScanFlags int scanFlags) 11721 throws PackageManagerException { 11722 if ((parseFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 11723 assertCodePolicy(pkg); 11724 } 11725 11726 if (pkg.applicationInfo.getCodePath() == null || 11727 pkg.applicationInfo.getResourcePath() == null) { 11728 // Bail out. The resource and code paths haven't been set. 11729 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 11730 "Code and resource paths haven't been set correctly"); 11731 } 11732 11733 // Check that there is an APEX package with the same name only during install/first boot 11734 // after OTA. 11735 final boolean isUserInstall = (scanFlags & SCAN_BOOTING) == 0; 11736 final boolean isFirstBootOrUpgrade = (scanFlags & SCAN_FIRST_BOOT_OR_UPGRADE) != 0; 11737 if ((isUserInstall || isFirstBootOrUpgrade) 11738 && mApexManager.isApexPackage(pkg.packageName)) { 11739 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11740 pkg.packageName + " is an APEX package and can't be installed as an APK."); 11741 } 11742 11743 // Make sure we're not adding any bogus keyset info 11744 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 11745 ksms.assertScannedPackageValid(pkg); 11746 11747 synchronized (mPackages) { 11748 // The special "android" package can only be defined once 11749 if (pkg.packageName.equals("android")) { 11750 if (mAndroidApplication != null) { 11751 Slog.w(TAG, "*************************************************"); 11752 Slog.w(TAG, "Core android package being redefined. Skipping."); 11753 Slog.w(TAG, " codePath=" + pkg.codePath); 11754 Slog.w(TAG, "*************************************************"); 11755 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11756 "Core android package being redefined. Skipping."); 11757 } 11758 } 11759 11760 // A package name must be unique; don't allow duplicates 11761 if ((scanFlags & SCAN_NEW_INSTALL) == 0 && mPackages.containsKey(pkg.packageName)) { 11762 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 11763 "Application package " + pkg.packageName 11764 + " already installed. Skipping duplicate."); 11765 } 11766 11767 if (pkg.applicationInfo.isStaticSharedLibrary()) { 11768 // Static libs have a synthetic package name containing the version 11769 // but we still want the base name to be unique. 11770 if ((scanFlags & SCAN_NEW_INSTALL) == 0 11771 && mPackages.containsKey(pkg.manifestPackageName)) { 11772 throw new PackageManagerException( 11773 "Duplicate static shared lib provider package"); 11774 } 11775 11776 // Static shared libraries should have at least O target SDK 11777 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 11778 throw new PackageManagerException( 11779 "Packages declaring static-shared libs must target O SDK or higher"); 11780 } 11781 11782 // Package declaring static a shared lib cannot be instant apps 11783 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 11784 throw new PackageManagerException( 11785 "Packages declaring static-shared libs cannot be instant apps"); 11786 } 11787 11788 // Package declaring static a shared lib cannot be renamed since the package 11789 // name is synthetic and apps can't code around package manager internals. 11790 if (!ArrayUtils.isEmpty(pkg.mOriginalPackages)) { 11791 throw new PackageManagerException( 11792 "Packages declaring static-shared libs cannot be renamed"); 11793 } 11794 11795 // Package declaring static a shared lib cannot declare child packages 11796 if (!ArrayUtils.isEmpty(pkg.childPackages)) { 11797 throw new PackageManagerException( 11798 "Packages declaring static-shared libs cannot have child packages"); 11799 } 11800 11801 // Package declaring static a shared lib cannot declare dynamic libs 11802 if (!ArrayUtils.isEmpty(pkg.libraryNames)) { 11803 throw new PackageManagerException( 11804 "Packages declaring static-shared libs cannot declare dynamic libs"); 11805 } 11806 11807 // Package declaring static a shared lib cannot declare shared users 11808 if (pkg.mSharedUserId != null) { 11809 throw new PackageManagerException( 11810 "Packages declaring static-shared libs cannot declare shared users"); 11811 } 11812 11813 // Static shared libs cannot declare activities 11814 if (!pkg.activities.isEmpty()) { 11815 throw new PackageManagerException( 11816 "Static shared libs cannot declare activities"); 11817 } 11818 11819 // Static shared libs cannot declare services 11820 if (!pkg.services.isEmpty()) { 11821 throw new PackageManagerException( 11822 "Static shared libs cannot declare services"); 11823 } 11824 11825 // Static shared libs cannot declare providers 11826 if (!pkg.providers.isEmpty()) { 11827 throw new PackageManagerException( 11828 "Static shared libs cannot declare content providers"); 11829 } 11830 11831 // Static shared libs cannot declare receivers 11832 if (!pkg.receivers.isEmpty()) { 11833 throw new PackageManagerException( 11834 "Static shared libs cannot declare broadcast receivers"); 11835 } 11836 11837 // Static shared libs cannot declare permission groups 11838 if (!pkg.permissionGroups.isEmpty()) { 11839 throw new PackageManagerException( 11840 "Static shared libs cannot declare permission groups"); 11841 } 11842 11843 // Static shared libs cannot declare permissions 11844 if (!pkg.permissions.isEmpty()) { 11845 throw new PackageManagerException( 11846 "Static shared libs cannot declare permissions"); 11847 } 11848 11849 // Static shared libs cannot declare protected broadcasts 11850 if (pkg.protectedBroadcasts != null) { 11851 throw new PackageManagerException( 11852 "Static shared libs cannot declare protected broadcasts"); 11853 } 11854 11855 // Static shared libs cannot be overlay targets 11856 if (pkg.mOverlayTarget != null) { 11857 throw new PackageManagerException( 11858 "Static shared libs cannot be overlay targets"); 11859 } 11860 11861 // The version codes must be ordered as lib versions 11862 long minVersionCode = Long.MIN_VALUE; 11863 long maxVersionCode = Long.MAX_VALUE; 11864 11865 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get( 11866 pkg.staticSharedLibName); 11867 if (versionedLib != null) { 11868 final int versionCount = versionedLib.size(); 11869 for (int i = 0; i < versionCount; i++) { 11870 SharedLibraryInfo libInfo = versionedLib.valueAt(i); 11871 final long libVersionCode = libInfo.getDeclaringPackage() 11872 .getLongVersionCode(); 11873 if (libInfo.getLongVersion() < pkg.staticSharedLibVersion) { 11874 minVersionCode = Math.max(minVersionCode, libVersionCode + 1); 11875 } else if (libInfo.getLongVersion() > pkg.staticSharedLibVersion) { 11876 maxVersionCode = Math.min(maxVersionCode, libVersionCode - 1); 11877 } else { 11878 minVersionCode = maxVersionCode = libVersionCode; 11879 break; 11880 } 11881 } 11882 } 11883 if (pkg.getLongVersionCode() < minVersionCode 11884 || pkg.getLongVersionCode() > maxVersionCode) { 11885 throw new PackageManagerException("Static shared" 11886 + " lib version codes must be ordered as lib versions"); 11887 } 11888 } 11889 11890 // Only privileged apps and updated privileged apps can add child packages. 11891 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 11892 if ((scanFlags & SCAN_AS_PRIVILEGED) == 0) { 11893 throw new PackageManagerException("Only privileged apps can add child " 11894 + "packages. Ignoring package " + pkg.packageName); 11895 } 11896 final int childCount = pkg.childPackages.size(); 11897 for (int i = 0; i < childCount; i++) { 11898 PackageParser.Package childPkg = pkg.childPackages.get(i); 11899 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 11900 childPkg.packageName)) { 11901 throw new PackageManagerException("Can't override child of " 11902 + "another disabled app. Ignoring package " + pkg.packageName); 11903 } 11904 } 11905 } 11906 11907 // If we're only installing presumed-existing packages, require that the 11908 // scanned APK is both already known and at the path previously established 11909 // for it. Previously unknown packages we pick up normally, but if we have an 11910 // a priori expectation about this package's install presence, enforce it. 11911 // With a singular exception for new system packages. When an OTA contains 11912 // a new system package, we allow the codepath to change from a system location 11913 // to the user-installed location. If we don't allow this change, any newer, 11914 // user-installed version of the application will be ignored. 11915 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 11916 if (mExpectingBetter.containsKey(pkg.packageName)) { 11917 logCriticalInfo(Log.WARN, 11918 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 11919 } else { 11920 PackageSetting known = mSettings.getPackageLPr(pkg.packageName); 11921 if (known != null) { 11922 if (DEBUG_PACKAGE_SCANNING) { 11923 Log.d(TAG, "Examining " + pkg.codePath 11924 + " and requiring known paths " + known.codePathString 11925 + " & " + known.resourcePathString); 11926 } 11927 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 11928 || !pkg.applicationInfo.getResourcePath().equals( 11929 known.resourcePathString)) { 11930 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 11931 "Application package " + pkg.packageName 11932 + " found at " + pkg.applicationInfo.getCodePath() 11933 + " but expected at " + known.codePathString 11934 + "; ignoring."); 11935 } 11936 } else { 11937 throw new PackageManagerException(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 11938 "Application package " + pkg.packageName 11939 + " not found; ignoring."); 11940 } 11941 } 11942 } 11943 11944 // Verify that this new package doesn't have any content providers 11945 // that conflict with existing packages. Only do this if the 11946 // package isn't already installed, since we don't want to break 11947 // things that are installed. 11948 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 11949 mComponentResolver.assertProvidersNotDefined(pkg); 11950 } 11951 11952 // Verify that packages sharing a user with a privileged app are marked as privileged. 11953 if (!pkg.isPrivileged() && (pkg.mSharedUserId != null)) { 11954 SharedUserSetting sharedUserSetting = null; 11955 try { 11956 sharedUserSetting = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, false); 11957 } catch (PackageManagerException ignore) {} 11958 if (sharedUserSetting != null && sharedUserSetting.isPrivileged()) { 11959 // Exempt SharedUsers signed with the platform key. 11960 PackageSetting platformPkgSetting = mSettings.mPackages.get("android"); 11961 if ((platformPkgSetting.signatures.mSigningDetails 11962 != PackageParser.SigningDetails.UNKNOWN) 11963 && (compareSignatures( 11964 platformPkgSetting.signatures.mSigningDetails.signatures, 11965 pkg.mSigningDetails.signatures) 11966 != PackageManager.SIGNATURE_MATCH)) { 11967 throw new PackageManagerException("Apps that share a user with a " + 11968 "privileged app must themselves be marked as privileged. " + 11969 pkg.packageName + " shares privileged user " + 11970 pkg.mSharedUserId + "."); 11971 } 11972 } 11973 } 11974 11975 // Apply policies specific for runtime resource overlays (RROs). 11976 if (pkg.mOverlayTarget != null) { 11977 // System overlays have some restrictions on their use of the 'static' state. 11978 if ((scanFlags & SCAN_AS_SYSTEM) != 0) { 11979 // We are scanning a system overlay. This can be the first scan of the 11980 // system/vendor/oem partition, or an update to the system overlay. 11981 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 11982 // This must be an update to a system overlay. 11983 final PackageSetting previousPkg = assertNotNull( 11984 mSettings.getPackageLPr(pkg.packageName), 11985 "previous package state not present"); 11986 11987 // previousPkg.pkg may be null: the package will be not be scanned if the 11988 // package manager knows there is a newer version on /data. 11989 // TODO[b/79435695]: Find a better way to keep track of the "static" 11990 // property for RROs instead of having to parse packages on /system 11991 PackageParser.Package ppkg = previousPkg.pkg; 11992 if (ppkg == null) { 11993 try { 11994 final PackageParser pp = new PackageParser(); 11995 ppkg = pp.parsePackage(previousPkg.codePath, 11996 parseFlags | PackageParser.PARSE_IS_SYSTEM_DIR); 11997 } catch (PackageParserException e) { 11998 Slog.w(TAG, "failed to parse " + previousPkg.codePath, e); 11999 } 12000 } 12001 12002 // Static overlays cannot be updated. 12003 if (ppkg != null && ppkg.mOverlayIsStatic) { 12004 throw new PackageManagerException("Overlay " + pkg.packageName + 12005 " is static and cannot be upgraded."); 12006 // Non-static overlays cannot be converted to static overlays. 12007 } else if (pkg.mOverlayIsStatic) { 12008 throw new PackageManagerException("Overlay " + pkg.packageName + 12009 " cannot be upgraded into a static overlay."); 12010 } 12011 } 12012 } else { 12013 // The overlay is a non-system overlay. Non-system overlays cannot be static. 12014 if (pkg.mOverlayIsStatic) { 12015 throw new PackageManagerException("Overlay " + pkg.packageName + 12016 " is static but not pre-installed."); 12017 } 12018 12019 // A non-preloaded overlay packages must have targetSdkVersion >= Q, or be 12020 // signed with the platform certificate. Check this in increasing order of 12021 // computational cost. 12022 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.Q) { 12023 final PackageSetting platformPkgSetting = 12024 mSettings.getPackageLPr("android"); 12025 if ((platformPkgSetting.signatures.mSigningDetails 12026 != PackageParser.SigningDetails.UNKNOWN) 12027 && (compareSignatures( 12028 platformPkgSetting.signatures.mSigningDetails.signatures, 12029 pkg.mSigningDetails.signatures) 12030 != PackageManager.SIGNATURE_MATCH)) { 12031 throw new PackageManagerException("Overlay " + pkg.packageName 12032 + " must target Q or later, " 12033 + "or be signed with the platform certificate"); 12034 } 12035 } 12036 12037 // A non-preloaded overlay package, without <overlay android:targetName>, will 12038 // only be used if it is signed with the same certificate as its target. If the 12039 // target is already installed, check this here to augment the last line of 12040 // defence which is OMS. 12041 if (pkg.mOverlayTargetName == null) { 12042 final PackageSetting targetPkgSetting = 12043 mSettings.getPackageLPr(pkg.mOverlayTarget); 12044 if (targetPkgSetting != null) { 12045 if ((targetPkgSetting.signatures.mSigningDetails 12046 != PackageParser.SigningDetails.UNKNOWN) 12047 && (compareSignatures( 12048 targetPkgSetting.signatures.mSigningDetails.signatures, 12049 pkg.mSigningDetails.signatures) 12050 != PackageManager.SIGNATURE_MATCH)) { 12051 throw new PackageManagerException("Overlay " + pkg.packageName 12052 + " and target " + pkg.mOverlayTarget + " signed with" 12053 + " different certificates, and the overlay lacks" 12054 + " <overlay android:targetName>"); 12055 } 12056 } 12057 } 12058 } 12059 } 12060 } 12061 } 12062 12063 @GuardedBy("mPackages") 12064 private boolean addBuiltInSharedLibraryLocked(String path, String name) { 12065 if (nonStaticSharedLibExistsLocked(name)) { 12066 return false; 12067 } 12068 12069 SharedLibraryInfo libraryInfo = new SharedLibraryInfo(path, null, null, name, 12070 (long) SharedLibraryInfo.VERSION_UNDEFINED, SharedLibraryInfo.TYPE_BUILTIN, 12071 new VersionedPackage(PLATFORM_PACKAGE_NAME, (long) 0), 12072 null, null); 12073 12074 commitSharedLibraryInfoLocked(libraryInfo); 12075 return true; 12076 } 12077 12078 @GuardedBy("mPackages") 12079 private boolean nonStaticSharedLibExistsLocked(String name) { 12080 return sharedLibExists(name, SharedLibraryInfo.VERSION_UNDEFINED, mSharedLibraries); 12081 } 12082 12083 private static boolean sharedLibExists(final String name, final long version, 12084 Map<String, LongSparseArray<SharedLibraryInfo>> librarySource) { 12085 LongSparseArray<SharedLibraryInfo> versionedLib = librarySource.get(name); 12086 if (versionedLib != null && versionedLib.indexOfKey(version) >= 0) { 12087 return true; 12088 } 12089 return false; 12090 } 12091 12092 @GuardedBy("mPackages") 12093 private void commitSharedLibraryInfoLocked(SharedLibraryInfo libraryInfo) { 12094 final String name = libraryInfo.getName(); 12095 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name); 12096 if (versionedLib == null) { 12097 versionedLib = new LongSparseArray<>(); 12098 mSharedLibraries.put(name, versionedLib); 12099 } 12100 final String declaringPackageName = libraryInfo.getDeclaringPackage().getPackageName(); 12101 if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) { 12102 mStaticLibsByDeclaringPackage.put(declaringPackageName, versionedLib); 12103 } 12104 versionedLib.put(libraryInfo.getLongVersion(), libraryInfo); 12105 } 12106 12107 private boolean removeSharedLibraryLPw(String name, long version) { 12108 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(name); 12109 if (versionedLib == null) { 12110 return false; 12111 } 12112 final int libIdx = versionedLib.indexOfKey(version); 12113 if (libIdx < 0) { 12114 return false; 12115 } 12116 SharedLibraryInfo libraryInfo = versionedLib.valueAt(libIdx); 12117 versionedLib.remove(version); 12118 if (versionedLib.size() <= 0) { 12119 mSharedLibraries.remove(name); 12120 if (libraryInfo.getType() == SharedLibraryInfo.TYPE_STATIC) { 12121 mStaticLibsByDeclaringPackage.remove(libraryInfo.getDeclaringPackage() 12122 .getPackageName()); 12123 } 12124 } 12125 return true; 12126 } 12127 12128 /** 12129 * Adds a scanned package to the system. When this method is finished, the package will 12130 * be available for query, resolution, etc... 12131 */ 12132 private void commitPackageSettings(PackageParser.Package pkg, 12133 @Nullable PackageParser.Package oldPkg, PackageSetting pkgSetting, 12134 final @ScanFlags int scanFlags, boolean chatty, ReconciledPackage reconciledPkg) { 12135 final String pkgName = pkg.packageName; 12136 if (mCustomResolverComponentName != null && 12137 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 12138 setUpCustomResolverActivity(pkg); 12139 } 12140 12141 if (pkg.packageName.equals("android")) { 12142 synchronized (mPackages) { 12143 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 12144 // Set up information for our fall-back user intent resolution activity. 12145 mPlatformPackage = pkg; 12146 pkg.mVersionCode = mSdkVersion; 12147 pkg.mVersionCodeMajor = 0; 12148 mAndroidApplication = pkg.applicationInfo; 12149 if (!mResolverReplaced) { 12150 mResolveActivity.applicationInfo = mAndroidApplication; 12151 mResolveActivity.name = ResolverActivity.class.getName(); 12152 mResolveActivity.packageName = mAndroidApplication.packageName; 12153 mResolveActivity.processName = "system:ui"; 12154 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 12155 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 12156 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 12157 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 12158 mResolveActivity.exported = true; 12159 mResolveActivity.enabled = true; 12160 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 12161 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 12162 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 12163 | ActivityInfo.CONFIG_SCREEN_LAYOUT 12164 | ActivityInfo.CONFIG_ORIENTATION 12165 | ActivityInfo.CONFIG_KEYBOARD 12166 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 12167 mResolveInfo.activityInfo = mResolveActivity; 12168 mResolveInfo.priority = 0; 12169 mResolveInfo.preferredOrder = 0; 12170 mResolveInfo.match = 0; 12171 mResolveComponentName = new ComponentName( 12172 mAndroidApplication.packageName, mResolveActivity.name); 12173 } 12174 } 12175 } 12176 } 12177 12178 ArrayList<PackageParser.Package> clientLibPkgs = null; 12179 // writer 12180 synchronized (mPackages) { 12181 if (!ArrayUtils.isEmpty(reconciledPkg.allowedSharedLibraryInfos)) { 12182 for (SharedLibraryInfo info : reconciledPkg.allowedSharedLibraryInfos) { 12183 commitSharedLibraryInfoLocked(info); 12184 } 12185 final Map<String, PackageParser.Package> combinedPackages = 12186 reconciledPkg.getCombinedPackages(); 12187 try { 12188 // Shared libraries for the package need to be updated. 12189 updateSharedLibrariesLocked(pkg, null, combinedPackages); 12190 } catch (PackageManagerException e) { 12191 Slog.e(TAG, "updateSharedLibrariesLPr failed: ", e); 12192 } 12193 // Update all applications that use this library. Skip when booting 12194 // since this will be done after all packages are scaned. 12195 if ((scanFlags & SCAN_BOOTING) == 0) { 12196 clientLibPkgs = updateAllSharedLibrariesLocked(pkg, combinedPackages); 12197 } 12198 } 12199 } 12200 if (reconciledPkg.installResult != null) { 12201 reconciledPkg.installResult.libraryConsumers = clientLibPkgs; 12202 } 12203 12204 if ((scanFlags & SCAN_BOOTING) != 0) { 12205 // No apps can run during boot scan, so they don't need to be frozen 12206 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 12207 // Caller asked to not kill app, so it's probably not frozen 12208 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 12209 // Caller asked us to ignore frozen check for some reason; they 12210 // probably didn't know the package name 12211 } else { 12212 // We're doing major surgery on this package, so it better be frozen 12213 // right now to keep it from launching 12214 checkPackageFrozen(pkgName); 12215 } 12216 12217 // Also need to kill any apps that are dependent on the library. 12218 if (clientLibPkgs != null) { 12219 for (int i=0; i<clientLibPkgs.size(); i++) { 12220 PackageParser.Package clientPkg = clientLibPkgs.get(i); 12221 killApplication(clientPkg.applicationInfo.packageName, 12222 clientPkg.applicationInfo.uid, "update lib"); 12223 } 12224 } 12225 12226 // writer 12227 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 12228 12229 synchronized (mPackages) { 12230 // We don't expect installation to fail beyond this point 12231 12232 // Add the new setting to mSettings 12233 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 12234 // Add the new setting to mPackages 12235 mPackages.put(pkg.applicationInfo.packageName, pkg); 12236 12237 // Add the package's KeySets to the global KeySetManagerService 12238 KeySetManagerService ksms = mSettings.mKeySetManagerService; 12239 ksms.addScannedPackageLPw(pkg); 12240 12241 mComponentResolver.addAllComponents(pkg, chatty); 12242 12243 // Don't allow ephemeral applications to define new permissions groups. 12244 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 12245 Slog.w(TAG, "Permission groups from package " + pkg.packageName 12246 + " ignored: instant apps cannot define new permission groups."); 12247 } else { 12248 mPermissionManager.addAllPermissionGroups(pkg, chatty); 12249 } 12250 12251 // Don't allow ephemeral applications to define new permissions. 12252 if ((scanFlags & SCAN_AS_INSTANT_APP) != 0) { 12253 Slog.w(TAG, "Permissions from package " + pkg.packageName 12254 + " ignored: instant apps cannot define new permissions."); 12255 } else { 12256 mPermissionManager.addAllPermissions(pkg, chatty); 12257 } 12258 12259 int collectionSize = pkg.instrumentation.size(); 12260 StringBuilder r = null; 12261 int i; 12262 for (i = 0; i < collectionSize; i++) { 12263 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12264 a.info.packageName = pkg.applicationInfo.packageName; 12265 a.info.sourceDir = pkg.applicationInfo.sourceDir; 12266 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 12267 a.info.splitNames = pkg.splitNames; 12268 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 12269 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 12270 a.info.splitDependencies = pkg.applicationInfo.splitDependencies; 12271 a.info.dataDir = pkg.applicationInfo.dataDir; 12272 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 12273 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 12274 a.info.primaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 12275 a.info.secondaryCpuAbi = pkg.applicationInfo.secondaryCpuAbi; 12276 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 12277 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 12278 mInstrumentation.put(a.getComponentName(), a); 12279 if (chatty) { 12280 if (r == null) { 12281 r = new StringBuilder(256); 12282 } else { 12283 r.append(' '); 12284 } 12285 r.append(a.info.name); 12286 } 12287 } 12288 if (r != null) { 12289 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 12290 } 12291 12292 if (pkg.protectedBroadcasts != null) { 12293 collectionSize = pkg.protectedBroadcasts.size(); 12294 synchronized (mProtectedBroadcasts) { 12295 for (i = 0; i < collectionSize; i++) { 12296 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 12297 } 12298 } 12299 } 12300 12301 if (oldPkg != null) { 12302 // We need to call revokeRuntimePermissionsIfGroupChanged async as permission 12303 // revoke callbacks from this method might need to kill apps which need the 12304 // mPackages lock on a different thread. This would dead lock. 12305 // 12306 // Hence create a copy of all package names and pass it into 12307 // revokeRuntimePermissionsIfGroupChanged. Only for those permissions might get 12308 // revoked. If a new package is added before the async code runs the permission 12309 // won't be granted yet, hence new packages are no problem. 12310 final ArrayList<String> allPackageNames = new ArrayList<>(mPackages.keySet()); 12311 12312 AsyncTask.execute(() -> 12313 mPermissionManager.revokeRuntimePermissionsIfGroupChanged(pkg, oldPkg, 12314 allPackageNames, mPermissionCallback)); 12315 } 12316 } 12317 12318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12319 } 12320 12321 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 12322 synchronized (mPackages) { 12323 mResolverReplaced = true; 12324 // Set up information for custom user intent resolution activity. 12325 mResolveActivity.applicationInfo = pkg.applicationInfo; 12326 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 12327 mResolveActivity.packageName = pkg.applicationInfo.packageName; 12328 mResolveActivity.processName = pkg.applicationInfo.packageName; 12329 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 12330 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 12331 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12332 mResolveActivity.theme = 0; 12333 mResolveActivity.exported = true; 12334 mResolveActivity.enabled = true; 12335 mResolveInfo.activityInfo = mResolveActivity; 12336 mResolveInfo.priority = 0; 12337 mResolveInfo.preferredOrder = 0; 12338 mResolveInfo.match = 0; 12339 mResolveComponentName = mCustomResolverComponentName; 12340 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 12341 mResolveComponentName); 12342 } 12343 } 12344 12345 private void setUpInstantAppInstallerActivityLP(ActivityInfo installerActivity) { 12346 if (installerActivity == null) { 12347 if (DEBUG_INSTANT) { 12348 Slog.d(TAG, "Clear ephemeral installer activity"); 12349 } 12350 mInstantAppInstallerActivity = null; 12351 return; 12352 } 12353 12354 if (DEBUG_INSTANT) { 12355 Slog.d(TAG, "Set ephemeral installer activity: " 12356 + installerActivity.getComponentName()); 12357 } 12358 // Set up information for ephemeral installer activity 12359 mInstantAppInstallerActivity = installerActivity; 12360 mInstantAppInstallerActivity.flags |= ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS 12361 | ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 12362 mInstantAppInstallerActivity.exported = true; 12363 mInstantAppInstallerActivity.enabled = true; 12364 mInstantAppInstallerInfo.activityInfo = mInstantAppInstallerActivity; 12365 mInstantAppInstallerInfo.priority = 1; 12366 mInstantAppInstallerInfo.preferredOrder = 1; 12367 mInstantAppInstallerInfo.isDefault = true; 12368 mInstantAppInstallerInfo.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 12369 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 12370 } 12371 12372 private void killApplication(String pkgName, int appId, String reason) { 12373 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 12374 } 12375 12376 private void killApplication(String pkgName, int appId, int userId, String reason) { 12377 // Request the ActivityManager to kill the process(only for existing packages) 12378 // so that we do not end up in a confused state while the user is still using the older 12379 // version of the application while the new one gets installed. 12380 final long token = Binder.clearCallingIdentity(); 12381 try { 12382 IActivityManager am = ActivityManager.getService(); 12383 if (am != null) { 12384 try { 12385 am.killApplication(pkgName, appId, userId, reason); 12386 } catch (RemoteException e) { 12387 } 12388 } 12389 } finally { 12390 Binder.restoreCallingIdentity(token); 12391 } 12392 } 12393 12394 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 12395 // Remove the parent package setting 12396 PackageSetting ps = (PackageSetting) pkg.mExtras; 12397 if (ps != null) { 12398 removePackageLI(ps.name, chatty); 12399 } else if (DEBUG_REMOVE && chatty) { 12400 Log.d(TAG, "Not removing package " + pkg.packageName + "; mExtras == null"); 12401 } 12402 // Remove the child package setting 12403 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12404 for (int i = 0; i < childCount; i++) { 12405 PackageParser.Package childPkg = pkg.childPackages.get(i); 12406 ps = (PackageSetting) childPkg.mExtras; 12407 if (ps != null) { 12408 removePackageLI(ps.name, chatty); 12409 } 12410 } 12411 } 12412 12413 void removePackageLI(String packageName, boolean chatty) { 12414 if (DEBUG_INSTALL) { 12415 if (chatty) 12416 Log.d(TAG, "Removing package " + packageName); 12417 } 12418 12419 // writer 12420 synchronized (mPackages) { 12421 final PackageParser.Package removedPackage = mPackages.remove(packageName); 12422 if (removedPackage != null) { 12423 cleanPackageDataStructuresLILPw(removedPackage, chatty); 12424 } 12425 } 12426 } 12427 12428 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 12429 if (DEBUG_INSTALL) { 12430 if (chatty) 12431 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 12432 } 12433 12434 // writer 12435 synchronized (mPackages) { 12436 // Remove the parent package 12437 mPackages.remove(pkg.applicationInfo.packageName); 12438 cleanPackageDataStructuresLILPw(pkg, chatty); 12439 12440 // Remove the child packages 12441 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 12442 for (int i = 0; i < childCount; i++) { 12443 PackageParser.Package childPkg = pkg.childPackages.get(i); 12444 mPackages.remove(childPkg.applicationInfo.packageName); 12445 cleanPackageDataStructuresLILPw(childPkg, chatty); 12446 } 12447 } 12448 } 12449 12450 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 12451 mComponentResolver.removeAllComponents(pkg, chatty); 12452 12453 mPermissionManager.removeAllPermissions(pkg, chatty); 12454 12455 final int instrumentationSize = pkg.instrumentation.size(); 12456 StringBuilder r = null; 12457 int i; 12458 for (i = 0; i < instrumentationSize; i++) { 12459 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 12460 mInstrumentation.remove(a.getComponentName()); 12461 if (DEBUG_REMOVE && chatty) { 12462 if (r == null) { 12463 r = new StringBuilder(256); 12464 } else { 12465 r.append(' '); 12466 } 12467 r.append(a.info.name); 12468 } 12469 } 12470 if (r != null) { 12471 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 12472 } 12473 12474 r = null; 12475 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 12476 // Only system apps can hold shared libraries. 12477 if (pkg.libraryNames != null) { 12478 final int libraryNamesSize = pkg.libraryNames.size(); 12479 for (i = 0; i < libraryNamesSize; i++) { 12480 String name = pkg.libraryNames.get(i); 12481 if (removeSharedLibraryLPw(name, 0)) { 12482 if (DEBUG_REMOVE && chatty) { 12483 if (r == null) { 12484 r = new StringBuilder(256); 12485 } else { 12486 r.append(' '); 12487 } 12488 r.append(name); 12489 } 12490 } 12491 } 12492 } 12493 } 12494 12495 r = null; 12496 12497 // Any package can hold static shared libraries. 12498 if (pkg.staticSharedLibName != null) { 12499 if (removeSharedLibraryLPw(pkg.staticSharedLibName, pkg.staticSharedLibVersion)) { 12500 if (DEBUG_REMOVE && chatty) { 12501 if (r == null) { 12502 r = new StringBuilder(256); 12503 } else { 12504 r.append(' '); 12505 } 12506 r.append(pkg.staticSharedLibName); 12507 } 12508 } 12509 } 12510 12511 if (r != null) { 12512 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 12513 } 12514 } 12515 12516 @Override 12517 public void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 12518 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 12519 final int[] userIds, int[] instantUserIds) { 12520 mHandler.post(() -> { 12521 try { 12522 final IActivityManager am = ActivityManager.getService(); 12523 if (am == null) return; 12524 final int[] resolvedUserIds; 12525 if (userIds == null) { 12526 resolvedUserIds = am.getRunningUserIds(); 12527 } else { 12528 resolvedUserIds = userIds; 12529 } 12530 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12531 resolvedUserIds, false); 12532 if (instantUserIds != null && instantUserIds != EMPTY_INT_ARRAY) { 12533 doSendBroadcast(am, action, pkg, extras, flags, targetPkg, finishedReceiver, 12534 instantUserIds, true); 12535 } 12536 } catch (RemoteException ex) { 12537 } 12538 }); 12539 } 12540 12541 @Override 12542 public void notifyPackageAdded(String packageName, int uid) { 12543 final PackageListObserver[] observers; 12544 synchronized (mPackages) { 12545 if (mPackageListObservers.size() == 0) { 12546 return; 12547 } 12548 final PackageListObserver[] observerArray = 12549 new PackageListObserver[mPackageListObservers.size()]; 12550 observers = mPackageListObservers.toArray(observerArray); 12551 } 12552 for (int i = observers.length - 1; i >= 0; --i) { 12553 observers[i].onPackageAdded(packageName, uid); 12554 } 12555 } 12556 12557 @Override 12558 public void notifyPackageChanged(String packageName, int uid) { 12559 final PackageListObserver[] observers; 12560 synchronized (mPackages) { 12561 if (mPackageListObservers.size() == 0) { 12562 return; 12563 } 12564 final PackageListObserver[] observerArray = 12565 new PackageListObserver[mPackageListObservers.size()]; 12566 observers = mPackageListObservers.toArray(observerArray); 12567 } 12568 for (int i = observers.length - 1; i >= 0; --i) { 12569 observers[i].onPackageChanged(packageName, uid); 12570 } 12571 } 12572 12573 private static final Comparator<ProviderInfo> sProviderInitOrderSorter = (p1, p2) -> { 12574 final int v1 = p1.initOrder; 12575 final int v2 = p2.initOrder; 12576 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 12577 }; 12578 12579 @Override 12580 public void notifyPackageRemoved(String packageName, int uid) { 12581 final PackageListObserver[] observers; 12582 synchronized (mPackages) { 12583 if (mPackageListObservers.size() == 0) { 12584 return; 12585 } 12586 final PackageListObserver[] observerArray = 12587 new PackageListObserver[mPackageListObservers.size()]; 12588 observers = mPackageListObservers.toArray(observerArray); 12589 } 12590 for (int i = observers.length - 1; i >= 0; --i) { 12591 observers[i].onPackageRemoved(packageName, uid); 12592 } 12593 } 12594 12595 /** 12596 * Sends a broadcast for the given action. 12597 * <p>If {@code isInstantApp} is {@code true}, then the broadcast is protected with 12598 * the {@link android.Manifest.permission#ACCESS_INSTANT_APPS} permission. This allows 12599 * the system and applications allowed to see instant applications to receive package 12600 * lifecycle events for instant applications. 12601 */ 12602 private void doSendBroadcast(IActivityManager am, String action, String pkg, Bundle extras, 12603 int flags, String targetPkg, IIntentReceiver finishedReceiver, 12604 int[] userIds, boolean isInstantApp) 12605 throws RemoteException { 12606 for (int id : userIds) { 12607 final Intent intent = new Intent(action, 12608 pkg != null ? Uri.fromParts(PACKAGE_SCHEME, pkg, null) : null); 12609 final String[] requiredPermissions = 12610 isInstantApp ? INSTANT_APP_BROADCAST_PERMISSION : null; 12611 if (extras != null) { 12612 intent.putExtras(extras); 12613 } 12614 if (targetPkg != null) { 12615 intent.setPackage(targetPkg); 12616 } 12617 // Modify the UID when posting to other users 12618 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 12619 if (uid > 0 && UserHandle.getUserId(uid) != id) { 12620 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 12621 intent.putExtra(Intent.EXTRA_UID, uid); 12622 } 12623 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 12624 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 12625 if (DEBUG_BROADCASTS) { 12626 RuntimeException here = new RuntimeException("here"); 12627 here.fillInStackTrace(); 12628 Slog.d(TAG, "Sending to user " + id + ": " 12629 + intent.toShortString(false, true, false, false) 12630 + " " + intent.getExtras(), here); 12631 } 12632 am.broadcastIntent(null, intent, null, finishedReceiver, 12633 0, null, null, requiredPermissions, android.app.AppOpsManager.OP_NONE, 12634 null, finishedReceiver != null, false, id); 12635 } 12636 } 12637 12638 /** 12639 * Check if the external storage media is available. This is true if there 12640 * is a mounted external storage medium or if the external storage is 12641 * emulated. 12642 */ 12643 private boolean isExternalMediaAvailable() { 12644 return mMediaMounted || Environment.isExternalStorageEmulated(); 12645 } 12646 12647 /** 12648 * Ensure that the install reason matches what we know about the package installer (e.g. whether 12649 * it is acting on behalf on an enterprise or the user). 12650 * 12651 * Note that the ordering of the conditionals in this method is important. The checks we perform 12652 * are as follows, in this order: 12653 * 12654 * 1) If the install is being performed by a system app, we can trust the app to have set the 12655 * install reason correctly. Thus, we pass through the install reason unchanged, no matter 12656 * what it is. 12657 * 2) If the install is being performed by a device or profile owner app, the install reason 12658 * should be enterprise policy. However, we cannot be sure that the device or profile owner 12659 * set the install reason correctly. If the app targets an older SDK version where install 12660 * reasons did not exist yet, or if the app author simply forgot, the install reason may be 12661 * unset or wrong. Thus, we force the install reason to be enterprise policy. 12662 * 3) In all other cases, the install is being performed by a regular app that is neither part 12663 * of the system nor a device or profile owner. We have no reason to believe that this app is 12664 * acting on behalf of the enterprise admin. Thus, we check whether the install reason was 12665 * set to enterprise policy and if so, change it to unknown instead. 12666 */ 12667 private int fixUpInstallReason(String installerPackageName, int installerUid, 12668 int installReason) { 12669 if (checkUidPermission(android.Manifest.permission.INSTALL_PACKAGES, installerUid) 12670 == PERMISSION_GRANTED) { 12671 // If the install is being performed by a system app, we trust that app to have set the 12672 // install reason correctly. 12673 return installReason; 12674 } 12675 final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage( 12676 UserHandle.getUserId(installerUid)); 12677 if (ownerPackage != null && ownerPackage.equals(installerPackageName)) { 12678 // If the install is being performed by a device or profile owner, the install 12679 // reason should be enterprise policy. 12680 return PackageManager.INSTALL_REASON_POLICY; 12681 } 12682 12683 12684 if (installReason == PackageManager.INSTALL_REASON_POLICY) { 12685 // If the install is being performed by a regular app (i.e. neither system app nor 12686 // device or profile owner), we have no reason to believe that the app is acting on 12687 // behalf of an enterprise. If the app set the install reason to enterprise policy, 12688 // change it to unknown instead. 12689 return PackageManager.INSTALL_REASON_UNKNOWN; 12690 } 12691 12692 // If the install is being performed by a regular app and the install reason was set to any 12693 // value but enterprise policy, leave the install reason unchanged. 12694 return installReason; 12695 } 12696 12697 void installStage(ActiveInstallSession activeInstallSession) { 12698 if (DEBUG_INSTANT) { 12699 if ((activeInstallSession.getSessionParams().installFlags 12700 & PackageManager.INSTALL_INSTANT_APP) != 0) { 12701 Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName()); 12702 } 12703 } 12704 final Message msg = mHandler.obtainMessage(INIT_COPY); 12705 final InstallParams params = new InstallParams(activeInstallSession); 12706 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 12707 msg.obj = params; 12708 12709 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 12710 System.identityHashCode(msg.obj)); 12711 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12712 System.identityHashCode(msg.obj)); 12713 12714 mHandler.sendMessage(msg); 12715 } 12716 12717 void installStage(List<ActiveInstallSession> children) 12718 throws PackageManagerException { 12719 final Message msg = mHandler.obtainMessage(INIT_COPY); 12720 final MultiPackageInstallParams params = 12721 new MultiPackageInstallParams(UserHandle.ALL, children); 12722 params.setTraceMethod("installStageMultiPackage") 12723 .setTraceCookie(System.identityHashCode(params)); 12724 msg.obj = params; 12725 12726 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStageMultiPackage", 12727 System.identityHashCode(msg.obj)); 12728 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 12729 System.identityHashCode(msg.obj)); 12730 mHandler.sendMessage(msg); 12731 } 12732 12733 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 12734 int userId) { 12735 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 12736 final boolean isInstantApp = pkgSetting.getInstantApp(userId); 12737 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 12738 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 12739 sendPackageAddedForNewUsers(packageName, isSystem /*sendBootCompleted*/, 12740 false /*startReceiver*/, pkgSetting.appId, userIds, instantUserIds); 12741 12742 // Send a session commit broadcast 12743 final PackageInstaller.SessionInfo info = new PackageInstaller.SessionInfo(); 12744 info.installReason = pkgSetting.getInstallReason(userId); 12745 info.appPackageName = packageName; 12746 sendSessionCommitBroadcast(info, userId); 12747 } 12748 12749 @Override 12750 public void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 12751 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds) { 12752 if (ArrayUtils.isEmpty(userIds) && ArrayUtils.isEmpty(instantUserIds)) { 12753 return; 12754 } 12755 Bundle extras = new Bundle(1); 12756 // Set to UID of the first user, EXTRA_UID is automatically updated in sendPackageBroadcast 12757 final int uid = UserHandle.getUid( 12758 (ArrayUtils.isEmpty(userIds) ? instantUserIds[0] : userIds[0]), appId); 12759 extras.putInt(Intent.EXTRA_UID, uid); 12760 12761 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 12762 packageName, extras, 0, null, null, userIds, instantUserIds); 12763 if (sendBootCompleted && !ArrayUtils.isEmpty(userIds)) { 12764 mHandler.post(() -> { 12765 for (int userId : userIds) { 12766 sendBootCompletedBroadcastToSystemApp( 12767 packageName, includeStopped, userId); 12768 } 12769 } 12770 ); 12771 } 12772 } 12773 12774 /** 12775 * The just-installed/enabled app is bundled on the system, so presumed to be able to run 12776 * automatically without needing an explicit launch. 12777 * Send it a LOCKED_BOOT_COMPLETED/BOOT_COMPLETED if it would ordinarily have gotten ones. 12778 */ 12779 private void sendBootCompletedBroadcastToSystemApp(String packageName, boolean includeStopped, 12780 int userId) { 12781 // If user is not running, the app didn't miss any broadcast 12782 if (!mUserManagerInternal.isUserRunning(userId)) { 12783 return; 12784 } 12785 final IActivityManager am = ActivityManager.getService(); 12786 try { 12787 // Deliver LOCKED_BOOT_COMPLETED first 12788 Intent lockedBcIntent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED) 12789 .setPackage(packageName); 12790 if (includeStopped) { 12791 lockedBcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 12792 } 12793 final String[] requiredPermissions = {Manifest.permission.RECEIVE_BOOT_COMPLETED}; 12794 am.broadcastIntent(null, lockedBcIntent, null, null, 0, null, null, requiredPermissions, 12795 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12796 12797 // Deliver BOOT_COMPLETED only if user is unlocked 12798 if (mUserManagerInternal.isUserUnlockingOrUnlocked(userId)) { 12799 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED).setPackage(packageName); 12800 if (includeStopped) { 12801 bcIntent.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES); 12802 } 12803 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, requiredPermissions, 12804 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 12805 } 12806 } catch (RemoteException e) { 12807 throw e.rethrowFromSystemServer(); 12808 } 12809 } 12810 12811 @Override 12812 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 12813 int userId) { 12814 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12815 PackageSetting pkgSetting; 12816 final int callingUid = Binder.getCallingUid(); 12817 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 12818 true /* requireFullPermission */, true /* checkShell */, 12819 "setApplicationHiddenSetting for user " + userId); 12820 12821 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 12822 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 12823 return false; 12824 } 12825 12826 long callingId = Binder.clearCallingIdentity(); 12827 try { 12828 boolean sendAdded = false; 12829 boolean sendRemoved = false; 12830 // writer 12831 synchronized (mPackages) { 12832 pkgSetting = mSettings.mPackages.get(packageName); 12833 if (pkgSetting == null) { 12834 return false; 12835 } 12836 if (filterAppAccessLPr(pkgSetting, callingUid, userId)) { 12837 return false; 12838 } 12839 // Do not allow "android" is being disabled 12840 if ("android".equals(packageName)) { 12841 Slog.w(TAG, "Cannot hide package: android"); 12842 return false; 12843 } 12844 // Cannot hide static shared libs as they are considered 12845 // a part of the using app (emulating static linking). Also 12846 // static libs are installed always on internal storage. 12847 PackageParser.Package pkg = mPackages.get(packageName); 12848 if (pkg != null && pkg.staticSharedLibName != null) { 12849 Slog.w(TAG, "Cannot hide package: " + packageName 12850 + " providing static shared library: " 12851 + pkg.staticSharedLibName); 12852 return false; 12853 } 12854 // Only allow protected packages to hide themselves. 12855 if (hidden && !UserHandle.isSameApp(callingUid, pkgSetting.appId) 12856 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 12857 Slog.w(TAG, "Not hiding protected package: " + packageName); 12858 return false; 12859 } 12860 12861 if (pkgSetting.getHidden(userId) != hidden) { 12862 pkgSetting.setHidden(hidden, userId); 12863 mSettings.writePackageRestrictionsLPr(userId); 12864 if (hidden) { 12865 sendRemoved = true; 12866 } else { 12867 sendAdded = true; 12868 } 12869 } 12870 } 12871 if (sendAdded) { 12872 sendPackageAddedForUser(packageName, pkgSetting, userId); 12873 return true; 12874 } 12875 if (sendRemoved) { 12876 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 12877 "hiding pkg"); 12878 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 12879 return true; 12880 } 12881 } finally { 12882 Binder.restoreCallingIdentity(callingId); 12883 } 12884 return false; 12885 } 12886 12887 @Override 12888 public void setSystemAppHiddenUntilInstalled(String packageName, boolean hidden) { 12889 enforceSystemOrPhoneCaller("setSystemAppHiddenUntilInstalled"); 12890 synchronized (mPackages) { 12891 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12892 if (pkgSetting == null || !pkgSetting.isSystem()) { 12893 return; 12894 } 12895 PackageParser.Package pkg = pkgSetting.pkg; 12896 if (pkg != null && pkg.applicationInfo != null) { 12897 pkg.applicationInfo.hiddenUntilInstalled = hidden; 12898 } 12899 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(packageName); 12900 if (disabledPs == null) { 12901 return; 12902 } 12903 pkg = disabledPs.pkg; 12904 if (pkg != null && pkg.applicationInfo != null) { 12905 pkg.applicationInfo.hiddenUntilInstalled = hidden; 12906 } 12907 } 12908 } 12909 12910 @Override 12911 public boolean setSystemAppInstallState(String packageName, boolean installed, int userId) { 12912 enforceSystemOrPhoneCaller("setSystemAppInstallState"); 12913 synchronized (mPackages) { 12914 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 12915 // The target app should always be in system 12916 if (pkgSetting == null || !pkgSetting.isSystem()) { 12917 return false; 12918 } 12919 // Check if the install state is the same 12920 if (pkgSetting.getInstalled(userId) == installed) { 12921 return false; 12922 } 12923 } 12924 12925 final long callingId = Binder.clearCallingIdentity(); 12926 try { 12927 if (installed) { 12928 // install the app from uninstalled state 12929 installExistingPackageAsUser( 12930 packageName, 12931 userId, 12932 PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, 12933 PackageManager.INSTALL_REASON_DEVICE_SETUP, 12934 null); 12935 return true; 12936 } 12937 12938 // uninstall the app from installed state 12939 deletePackageVersioned( 12940 new VersionedPackage(packageName, PackageManager.VERSION_CODE_HIGHEST), 12941 new LegacyPackageDeleteObserver(null).getBinder(), 12942 userId, 12943 PackageManager.DELETE_SYSTEM_APP); 12944 return true; 12945 } finally { 12946 Binder.restoreCallingIdentity(callingId); 12947 } 12948 } 12949 12950 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 12951 int userId) { 12952 final PackageRemovedInfo info = new PackageRemovedInfo(this); 12953 info.removedPackage = packageName; 12954 info.installerPackageName = pkgSetting.installerPackageName; 12955 info.removedUsers = new int[] {userId}; 12956 info.broadcastUsers = new int[] {userId}; 12957 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 12958 info.sendPackageRemovedBroadcasts(true /*killApp*/); 12959 } 12960 12961 private void sendDistractingPackagesChanged(String[] pkgList, int[] uidList, int userId, 12962 int distractionFlags) { 12963 final Bundle extras = new Bundle(3); 12964 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12965 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList); 12966 extras.putInt(Intent.EXTRA_DISTRACTION_RESTRICTIONS, distractionFlags); 12967 sendPackageBroadcast(Intent.ACTION_DISTRACTING_PACKAGES_CHANGED, null, extras, 12968 Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, new int[]{userId}, null); 12969 } 12970 12971 private void sendPackagesSuspendedForUser(String[] pkgList, int[] uidList, int userId, 12972 boolean suspended, PersistableBundle launcherExtras) { 12973 final Bundle extras = new Bundle(3); 12974 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 12975 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidList); 12976 if (launcherExtras != null) { 12977 extras.putBundle(Intent.EXTRA_LAUNCHER_EXTRAS, 12978 new Bundle(launcherExtras.deepCopy())); 12979 } 12980 sendPackageBroadcast( 12981 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 12982 : Intent.ACTION_PACKAGES_UNSUSPENDED, 12983 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 12984 new int[] {userId}, null); 12985 } 12986 12987 /** 12988 * Returns true if application is not found or there was an error. Otherwise it returns 12989 * the hidden state of the package for the given user. 12990 */ 12991 @Override 12992 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 12993 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 12994 final int callingUid = Binder.getCallingUid(); 12995 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 12996 true /* requireFullPermission */, false /* checkShell */, 12997 "getApplicationHidden for user " + userId); 12998 PackageSetting ps; 12999 long callingId = Binder.clearCallingIdentity(); 13000 try { 13001 // writer 13002 synchronized (mPackages) { 13003 ps = mSettings.mPackages.get(packageName); 13004 if (ps == null) { 13005 return true; 13006 } 13007 if (filterAppAccessLPr(ps, callingUid, userId)) { 13008 return true; 13009 } 13010 return ps.getHidden(userId); 13011 } 13012 } finally { 13013 Binder.restoreCallingIdentity(callingId); 13014 } 13015 } 13016 13017 /** 13018 * @hide 13019 */ 13020 @Override 13021 public int installExistingPackageAsUser(String packageName, int userId, int installFlags, 13022 int installReason, List<String> whiteListedPermissions) { 13023 return installExistingPackageAsUser(packageName, userId, installFlags, installReason, 13024 whiteListedPermissions, null); 13025 } 13026 13027 int installExistingPackageAsUser(@Nullable String packageName, @UserIdInt int userId, 13028 @PackageManager.InstallFlags int installFlags, 13029 @PackageManager.InstallReason int installReason, 13030 @Nullable List<String> whiteListedPermissions, @Nullable IntentSender intentSender) { 13031 if (DEBUG_INSTALL) { 13032 Log.v(TAG, "installExistingPackageAsUser package=" + packageName + " userId=" + userId 13033 + " installFlags=" + installFlags + " installReason=" + installReason 13034 + " whiteListedPermissions=" + whiteListedPermissions); 13035 } 13036 13037 final int callingUid = Binder.getCallingUid(); 13038 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES) 13039 != PackageManager.PERMISSION_GRANTED 13040 && mContext.checkCallingOrSelfPermission( 13041 android.Manifest.permission.INSTALL_EXISTING_PACKAGES) 13042 != PackageManager.PERMISSION_GRANTED) { 13043 throw new SecurityException("Neither user " + callingUid + " nor current process has " 13044 + android.Manifest.permission.INSTALL_PACKAGES + "."); 13045 } 13046 PackageSetting pkgSetting; 13047 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13048 true /* requireFullPermission */, true /* checkShell */, 13049 "installExistingPackage for user " + userId); 13050 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 13051 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 13052 } 13053 13054 long callingId = Binder.clearCallingIdentity(); 13055 try { 13056 boolean installed = false; 13057 final boolean instantApp = 13058 (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 13059 final boolean fullApp = 13060 (installFlags & PackageManager.INSTALL_FULL_APP) != 0; 13061 13062 // writer 13063 synchronized (mPackages) { 13064 pkgSetting = mSettings.mPackages.get(packageName); 13065 if (pkgSetting == null) { 13066 return PackageManager.INSTALL_FAILED_INVALID_URI; 13067 } 13068 if (!canViewInstantApps(callingUid, UserHandle.getUserId(callingUid))) { 13069 // only allow the existing package to be used if it's installed as a full 13070 // application for at least one user 13071 boolean installAllowed = false; 13072 for (int checkUserId : sUserManager.getUserIds()) { 13073 installAllowed = !pkgSetting.getInstantApp(checkUserId); 13074 if (installAllowed) { 13075 break; 13076 } 13077 } 13078 if (!installAllowed) { 13079 return PackageManager.INSTALL_FAILED_INVALID_URI; 13080 } 13081 } 13082 if (!pkgSetting.getInstalled(userId)) { 13083 pkgSetting.setInstalled(true, userId); 13084 pkgSetting.setHidden(false, userId); 13085 pkgSetting.setInstallReason(installReason, userId); 13086 mSettings.writePackageRestrictionsLPr(userId); 13087 mSettings.writeKernelMappingLPr(pkgSetting); 13088 installed = true; 13089 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13090 // upgrade app from instant to full; we don't allow app downgrade 13091 installed = true; 13092 } 13093 setInstantAppForUser( 13094 getUserManagerInternal(), pkgSetting, userId, instantApp, fullApp); 13095 } 13096 13097 if (installed) { 13098 if ((installFlags & PackageManager.INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS) 13099 != 0 && pkgSetting.pkg != null) { 13100 whiteListedPermissions = pkgSetting.pkg.requestedPermissions; 13101 } 13102 setWhitelistedRestrictedPermissions(packageName, whiteListedPermissions, 13103 PackageManager.FLAG_PERMISSION_WHITELIST_INSTALLER, userId); 13104 13105 if (pkgSetting.pkg != null) { 13106 synchronized (mInstallLock) { 13107 // We don't need to freeze for a brand new install 13108 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 13109 } 13110 } 13111 sendPackageAddedForUser(packageName, pkgSetting, userId); 13112 synchronized (mPackages) { 13113 updateSequenceNumberLP(pkgSetting, new int[]{ userId }); 13114 } 13115 // start async restore with no post-install since we finish install here 13116 PackageInstalledInfo res = 13117 createPackageInstalledInfo(PackageManager.INSTALL_SUCCEEDED); 13118 res.pkg = pkgSetting.pkg; 13119 res.newUsers = new int[]{ userId }; 13120 PostInstallData postInstallData = intentSender == null ? null : 13121 new PostInstallData(null, res, () -> onRestoreComplete(res.returnCode, 13122 mContext, intentSender)); 13123 restoreAndPostInstall(userId, res, postInstallData); 13124 } 13125 } finally { 13126 Binder.restoreCallingIdentity(callingId); 13127 } 13128 13129 return PackageManager.INSTALL_SUCCEEDED; 13130 } 13131 13132 static void onRestoreComplete(int returnCode, Context context, IntentSender target) { 13133 Intent fillIn = new Intent(); 13134 fillIn.putExtra(PackageInstaller.EXTRA_STATUS, 13135 PackageManager.installStatusToPublicStatus(returnCode)); 13136 try { 13137 target.sendIntent(context, 0, fillIn, null, null); 13138 } catch (SendIntentException ignored) { 13139 } 13140 } 13141 13142 static void setInstantAppForUser(UserManagerInternal userManager, PackageSetting pkgSetting, 13143 int userId, boolean instantApp, boolean fullApp) { 13144 // no state specified; do nothing 13145 if (!instantApp && !fullApp) { 13146 return; 13147 } 13148 if (userId != UserHandle.USER_ALL) { 13149 if (instantApp && !pkgSetting.getInstantApp(userId)) { 13150 pkgSetting.setInstantApp(true /*instantApp*/, userId); 13151 } else if (fullApp && pkgSetting.getInstantApp(userId)) { 13152 pkgSetting.setInstantApp(false /*instantApp*/, userId); 13153 } 13154 } else { 13155 for (int currentUserId : userManager.getUserIds()) { 13156 if (instantApp && !pkgSetting.getInstantApp(currentUserId)) { 13157 pkgSetting.setInstantApp(true /*instantApp*/, currentUserId); 13158 } else if (fullApp && pkgSetting.getInstantApp(currentUserId)) { 13159 pkgSetting.setInstantApp(false /*instantApp*/, currentUserId); 13160 } 13161 } 13162 } 13163 } 13164 13165 boolean isUserRestricted(int userId, String restrictionKey) { 13166 Bundle restrictions = sUserManager.getUserRestrictions(userId); 13167 if (restrictions.getBoolean(restrictionKey, false)) { 13168 Log.w(TAG, "User is restricted: " + restrictionKey); 13169 return true; 13170 } 13171 return false; 13172 } 13173 13174 @Override 13175 public String[] setDistractingPackageRestrictionsAsUser(String[] packageNames, 13176 int restrictionFlags, int userId) { 13177 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, 13178 "setDistractingPackageRestrictionsAsUser"); 13179 13180 final int callingUid = Binder.getCallingUid(); 13181 if (callingUid != Process.ROOT_UID && callingUid != Process.SYSTEM_UID 13182 && UserHandle.getUserId(callingUid) != userId) { 13183 throw new SecurityException("Calling uid " + callingUid + " cannot call for user " 13184 + userId); 13185 } 13186 Preconditions.checkNotNull(packageNames, "packageNames cannot be null"); 13187 13188 final List<String> changedPackagesList = new ArrayList<>(packageNames.length); 13189 final IntArray changedUids = new IntArray(packageNames.length); 13190 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13191 final boolean[] canRestrict = (restrictionFlags != 0) ? canSuspendPackageForUserInternal( 13192 packageNames, userId) : null; 13193 13194 for (int i = 0; i < packageNames.length; i++) { 13195 final String packageName = packageNames[i]; 13196 final PackageSetting pkgSetting; 13197 synchronized (mPackages) { 13198 pkgSetting = mSettings.mPackages.get(packageName); 13199 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13200 Slog.w(TAG, "Could not find package setting for package: " + packageName 13201 + ". Skipping..."); 13202 unactionedPackages.add(packageName); 13203 continue; 13204 } 13205 } 13206 if (canRestrict != null && !canRestrict[i]) { 13207 unactionedPackages.add(packageName); 13208 continue; 13209 } 13210 synchronized (mPackages) { 13211 final int oldDistractionFlags = pkgSetting.getDistractionFlags(userId); 13212 if (restrictionFlags != oldDistractionFlags) { 13213 pkgSetting.setDistractionFlags(restrictionFlags, userId); 13214 changedPackagesList.add(packageName); 13215 changedUids.add(UserHandle.getUid(userId, pkgSetting.appId)); 13216 } 13217 } 13218 } 13219 13220 if (!changedPackagesList.isEmpty()) { 13221 final String[] changedPackages = changedPackagesList.toArray( 13222 new String[changedPackagesList.size()]); 13223 sendDistractingPackagesChanged(changedPackages, changedUids.toArray(), userId, 13224 restrictionFlags); 13225 synchronized (mPackages) { 13226 scheduleWritePackageRestrictionsLocked(userId); 13227 } 13228 } 13229 return unactionedPackages.toArray(new String[0]); 13230 } 13231 13232 private void enforceCanSetPackagesSuspendedAsUser(String callingPackage, int callingUid, 13233 int userId, String callingMethod) { 13234 if (callingUid == Process.ROOT_UID || callingUid == Process.SYSTEM_UID) { 13235 return; 13236 } 13237 13238 final String ownerPackage = mProtectedPackages.getDeviceOwnerOrProfileOwnerPackage(userId); 13239 if (ownerPackage != null) { 13240 final int ownerUid = getPackageUid(ownerPackage, 0, userId); 13241 if (ownerUid == callingUid) { 13242 return; 13243 } 13244 throw new UnsupportedOperationException("Cannot suspend/unsuspend packages. User " 13245 + userId + " has an active DO or PO"); 13246 } 13247 13248 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.SUSPEND_APPS, 13249 callingMethod); 13250 13251 final int packageUid = getPackageUid(callingPackage, 0, userId); 13252 final boolean allowedPackageUid = packageUid == callingUid; 13253 final boolean allowedShell = callingUid == SHELL_UID 13254 && UserHandle.isSameApp(packageUid, callingUid); 13255 13256 if (!allowedShell && !allowedPackageUid) { 13257 throw new SecurityException("Calling package " + callingPackage + " in user " 13258 + userId + " does not belong to calling uid " + callingUid); 13259 } 13260 } 13261 13262 @Override 13263 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 13264 PersistableBundle appExtras, PersistableBundle launcherExtras, 13265 SuspendDialogInfo dialogInfo, String callingPackage, int userId) { 13266 final int callingUid = Binder.getCallingUid(); 13267 enforceCanSetPackagesSuspendedAsUser(callingPackage, callingUid, userId, 13268 "setPackagesSuspendedAsUser"); 13269 13270 if (ArrayUtils.isEmpty(packageNames)) { 13271 return packageNames; 13272 } 13273 13274 final List<String> changedPackagesList = new ArrayList<>(packageNames.length); 13275 final IntArray changedUids = new IntArray(packageNames.length); 13276 final List<String> unactionedPackages = new ArrayList<>(packageNames.length); 13277 final boolean[] canSuspend = suspended ? canSuspendPackageForUserInternal(packageNames, 13278 userId) : null; 13279 13280 for (int i = 0; i < packageNames.length; i++) { 13281 final String packageName = packageNames[i]; 13282 if (callingPackage.equals(packageName)) { 13283 Slog.w(TAG, "Calling package: " + callingPackage + " trying to " 13284 + (suspended ? "" : "un") + "suspend itself. Ignoring"); 13285 unactionedPackages.add(packageName); 13286 continue; 13287 } 13288 final PackageSetting pkgSetting; 13289 synchronized (mPackages) { 13290 pkgSetting = mSettings.mPackages.get(packageName); 13291 if (pkgSetting == null || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 13292 Slog.w(TAG, "Could not find package setting for package: " + packageName 13293 + ". Skipping suspending/un-suspending."); 13294 unactionedPackages.add(packageName); 13295 continue; 13296 } 13297 } 13298 if (canSuspend != null && !canSuspend[i]) { 13299 unactionedPackages.add(packageName); 13300 continue; 13301 } 13302 synchronized (mPackages) { 13303 pkgSetting.setSuspended(suspended, callingPackage, dialogInfo, appExtras, 13304 launcherExtras, userId); 13305 } 13306 changedPackagesList.add(packageName); 13307 changedUids.add(UserHandle.getUid(userId, pkgSetting.appId)); 13308 } 13309 13310 if (!changedPackagesList.isEmpty()) { 13311 final String[] changedPackages = changedPackagesList.toArray( 13312 new String[changedPackagesList.size()]); 13313 sendPackagesSuspendedForUser( 13314 changedPackages, changedUids.toArray(), userId, suspended, launcherExtras); 13315 sendMyPackageSuspendedOrUnsuspended(changedPackages, suspended, appExtras, userId); 13316 synchronized (mPackages) { 13317 scheduleWritePackageRestrictionsLocked(userId); 13318 } 13319 } 13320 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 13321 } 13322 13323 @Override 13324 public PersistableBundle getSuspendedPackageAppExtras(String packageName, int userId) { 13325 final int callingUid = Binder.getCallingUid(); 13326 if (getPackageUid(packageName, 0, userId) != callingUid) { 13327 throw new SecurityException("Calling package " + packageName 13328 + " does not belong to calling uid " + callingUid); 13329 } 13330 synchronized (mPackages) { 13331 final PackageSetting ps = mSettings.mPackages.get(packageName); 13332 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13333 throw new IllegalArgumentException("Unknown target package: " + packageName); 13334 } 13335 final PackageUserState packageUserState = ps.readUserState(userId); 13336 if (packageUserState.suspended) { 13337 return packageUserState.suspendedAppExtras; 13338 } 13339 return null; 13340 } 13341 } 13342 13343 private void sendMyPackageSuspendedOrUnsuspended(String[] affectedPackages, boolean suspended, 13344 PersistableBundle appExtras, int userId) { 13345 final String action; 13346 final Bundle intentExtras = new Bundle(); 13347 if (suspended) { 13348 action = Intent.ACTION_MY_PACKAGE_SUSPENDED; 13349 if (appExtras != null) { 13350 final Bundle bundledAppExtras = new Bundle(appExtras.deepCopy()); 13351 intentExtras.putBundle(Intent.EXTRA_SUSPENDED_PACKAGE_EXTRAS, bundledAppExtras); 13352 } 13353 } else { 13354 action = Intent.ACTION_MY_PACKAGE_UNSUSPENDED; 13355 } 13356 mHandler.post(() -> { 13357 try { 13358 final IActivityManager am = ActivityManager.getService(); 13359 if (am == null) { 13360 Slog.wtf(TAG, "IActivityManager null. Cannot send MY_PACKAGE_ " 13361 + (suspended ? "" : "UN") + "SUSPENDED broadcasts"); 13362 return; 13363 } 13364 final int[] targetUserIds = new int[] {userId}; 13365 for (String packageName : affectedPackages) { 13366 doSendBroadcast(am, action, null, intentExtras, 13367 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, packageName, null, 13368 targetUserIds, false); 13369 } 13370 } catch (RemoteException ex) { 13371 // Shouldn't happen as AMS is in the same process. 13372 } 13373 }); 13374 } 13375 13376 @Override 13377 public boolean isPackageSuspendedForUser(String packageName, int userId) { 13378 final int callingUid = Binder.getCallingUid(); 13379 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 13380 true /* requireFullPermission */, false /* checkShell */, 13381 "isPackageSuspendedForUser for user " + userId); 13382 synchronized (mPackages) { 13383 final PackageSetting ps = mSettings.mPackages.get(packageName); 13384 if (ps == null || filterAppAccessLPr(ps, callingUid, userId)) { 13385 throw new IllegalArgumentException("Unknown target package: " + packageName); 13386 } 13387 return ps.getSuspended(userId); 13388 } 13389 } 13390 13391 /** 13392 * Immediately unsuspends any packages suspended by the given package. To be called 13393 * when such a package's data is cleared or it is removed from the device. 13394 * 13395 * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk 13396 * synchronously 13397 * 13398 * @param packageName The package holding {@link Manifest.permission#SUSPEND_APPS} permission 13399 * @param affectedUser The user for which the changes are taking place. 13400 */ 13401 void unsuspendForSuspendingPackage(final String packageName, int affectedUser) { 13402 final int[] userIds = (affectedUser == UserHandle.USER_ALL) ? sUserManager.getUserIds() 13403 : new int[] {affectedUser}; 13404 for (int userId : userIds) { 13405 unsuspendForSuspendingPackages(packageName::equals, userId); 13406 } 13407 } 13408 13409 /** 13410 * Immediately unsuspends any packages in the given users not suspended by the platform or root. 13411 * To be called when a profile owner or a device owner is added. 13412 * 13413 * <p><b>Should not be used on a frequent code path</b> as it flushes state to disk 13414 * synchronously 13415 * 13416 * @param userIds The users for which to unsuspend packages 13417 */ 13418 void unsuspendForNonSystemSuspendingPackages(ArraySet<Integer> userIds) { 13419 final int sz = userIds.size(); 13420 for (int i = 0; i < sz; i++) { 13421 unsuspendForSuspendingPackages( 13422 (suspendingPackage) -> !PLATFORM_PACKAGE_NAME.equals(suspendingPackage), 13423 userIds.valueAt(i)); 13424 } 13425 } 13426 13427 private void unsuspendForSuspendingPackages(Predicate<String> packagePredicate, int userId) { 13428 final List<String> affectedPackages = new ArrayList<>(); 13429 final IntArray affectedUids = new IntArray(); 13430 synchronized (mPackages) { 13431 for (PackageSetting ps : mSettings.mPackages.values()) { 13432 final PackageUserState pus = ps.readUserState(userId); 13433 if (pus.suspended && packagePredicate.test(pus.suspendingPackage)) { 13434 ps.setSuspended(false, null, null, null, null, userId); 13435 affectedPackages.add(ps.name); 13436 affectedUids.add(UserHandle.getUid(userId, ps.getAppId())); 13437 } 13438 } 13439 } 13440 if (!affectedPackages.isEmpty()) { 13441 final String[] packageArray = affectedPackages.toArray( 13442 new String[affectedPackages.size()]); 13443 sendMyPackageSuspendedOrUnsuspended(packageArray, false, null, userId); 13444 sendPackagesSuspendedForUser( 13445 packageArray, affectedUids.toArray(), userId, false, null); 13446 // Write package restrictions immediately to avoid an inconsistent state. 13447 mSettings.writePackageRestrictionsLPr(userId); 13448 } 13449 } 13450 13451 @Override 13452 public String[] getUnsuspendablePackagesForUser(String[] packageNames, int userId) { 13453 Preconditions.checkNotNull("packageNames cannot be null", packageNames); 13454 mContext.enforceCallingOrSelfPermission(Manifest.permission.SUSPEND_APPS, 13455 "getUnsuspendablePackagesForUser"); 13456 final int callingUid = Binder.getCallingUid(); 13457 if (UserHandle.getUserId(callingUid) != userId) { 13458 throw new SecurityException("Calling uid " + callingUid 13459 + " cannot query getUnsuspendablePackagesForUser for user " + userId); 13460 } 13461 final ArraySet<String> unactionablePackages = new ArraySet<>(); 13462 final boolean[] canSuspend = canSuspendPackageForUserInternal(packageNames, userId); 13463 for (int i = 0; i < packageNames.length; i++) { 13464 if (!canSuspend[i]) { 13465 unactionablePackages.add(packageNames[i]); 13466 } 13467 } 13468 return unactionablePackages.toArray(new String[unactionablePackages.size()]); 13469 } 13470 13471 /** 13472 * Returns an array of booleans, such that the ith boolean denotes whether the ith package can 13473 * be suspended or not. 13474 * 13475 * @param packageNames The package names to check suspendability for. 13476 * @param userId The user to check in 13477 * @return An array containing results of the checks 13478 */ 13479 @NonNull 13480 private boolean[] canSuspendPackageForUserInternal(@NonNull String[] packageNames, int userId) { 13481 final boolean[] canSuspend = new boolean[packageNames.length]; 13482 final long callingId = Binder.clearCallingIdentity(); 13483 try { 13484 final String activeLauncherPackageName = getActiveLauncherPackageName(userId); 13485 final String dialerPackageName = getDefaultDialerPackageName(userId); 13486 for (int i = 0; i < packageNames.length; i++) { 13487 canSuspend[i] = false; 13488 final String packageName = packageNames[i]; 13489 13490 if (isPackageDeviceAdmin(packageName, userId)) { 13491 Slog.w(TAG, "Cannot suspend package \"" + packageName 13492 + "\": has an active device admin"); 13493 continue; 13494 } 13495 if (packageName.equals(activeLauncherPackageName)) { 13496 Slog.w(TAG, "Cannot suspend package \"" + packageName 13497 + "\": contains the active launcher"); 13498 continue; 13499 } 13500 if (packageName.equals(mRequiredInstallerPackage)) { 13501 Slog.w(TAG, "Cannot suspend package \"" + packageName 13502 + "\": required for package installation"); 13503 continue; 13504 } 13505 if (packageName.equals(mRequiredUninstallerPackage)) { 13506 Slog.w(TAG, "Cannot suspend package \"" + packageName 13507 + "\": required for package uninstallation"); 13508 continue; 13509 } 13510 if (packageName.equals(mRequiredVerifierPackage)) { 13511 Slog.w(TAG, "Cannot suspend package \"" + packageName 13512 + "\": required for package verification"); 13513 continue; 13514 } 13515 if (packageName.equals(dialerPackageName)) { 13516 Slog.w(TAG, "Cannot suspend package \"" + packageName 13517 + "\": is the default dialer"); 13518 continue; 13519 } 13520 if (packageName.equals(mRequiredPermissionControllerPackage)) { 13521 Slog.w(TAG, "Cannot suspend package \"" + packageName 13522 + "\": required for permissions management"); 13523 continue; 13524 } 13525 synchronized (mPackages) { 13526 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 13527 Slog.w(TAG, "Cannot suspend package \"" + packageName 13528 + "\": protected package"); 13529 continue; 13530 } 13531 13532 // Cannot suspend static shared libs as they are considered 13533 // a part of the using app (emulating static linking). Also 13534 // static libs are installed always on internal storage. 13535 PackageParser.Package pkg = mPackages.get(packageName); 13536 if (pkg != null && pkg.applicationInfo.isStaticSharedLibrary()) { 13537 Slog.w(TAG, "Cannot suspend package: " + packageName 13538 + " providing static shared library: " 13539 + pkg.staticSharedLibName); 13540 continue; 13541 } 13542 } 13543 if (PLATFORM_PACKAGE_NAME.equals(packageName)) { 13544 Slog.w(TAG, "Cannot suspend the platform package: " + packageName); 13545 continue; 13546 } 13547 canSuspend[i] = true; 13548 } 13549 } finally { 13550 Binder.restoreCallingIdentity(callingId); 13551 } 13552 return canSuspend; 13553 } 13554 13555 private String getActiveLauncherPackageName(int userId) { 13556 Intent intent = new Intent(Intent.ACTION_MAIN); 13557 intent.addCategory(Intent.CATEGORY_HOME); 13558 ResolveInfo resolveInfo = resolveIntent( 13559 intent, 13560 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 13561 PackageManager.MATCH_DEFAULT_ONLY, 13562 userId); 13563 13564 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 13565 } 13566 13567 @Nullable 13568 private String getDefaultDialerPackageName(@UserIdInt int userId) { 13569 PackageManagerInternal.DefaultDialerProvider provider; 13570 synchronized (mPackages) { 13571 provider = mDefaultDialerProvider; 13572 } 13573 if (provider == null) { 13574 Slog.e(TAG, "mDefaultDialerProvider is null"); 13575 return null; 13576 } 13577 return provider.getDefaultDialer(userId); 13578 } 13579 13580 @Override 13581 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 13582 mContext.enforceCallingOrSelfPermission( 13583 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13584 "Only package verification agents can verify applications"); 13585 13586 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13587 final PackageVerificationResponse response = new PackageVerificationResponse( 13588 verificationCode, Binder.getCallingUid()); 13589 msg.arg1 = id; 13590 msg.obj = response; 13591 mHandler.sendMessage(msg); 13592 } 13593 13594 @Override 13595 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 13596 long millisecondsToDelay) { 13597 mContext.enforceCallingOrSelfPermission( 13598 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13599 "Only package verification agents can extend verification timeouts"); 13600 13601 final PackageVerificationState state = mPendingVerification.get(id); 13602 final PackageVerificationResponse response = new PackageVerificationResponse( 13603 verificationCodeAtTimeout, Binder.getCallingUid()); 13604 13605 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 13606 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 13607 } 13608 if (millisecondsToDelay < 0) { 13609 millisecondsToDelay = 0; 13610 } 13611 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 13612 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 13613 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 13614 } 13615 13616 if ((state != null) && !state.timeoutExtended()) { 13617 state.extendTimeout(); 13618 13619 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 13620 msg.arg1 = id; 13621 msg.obj = response; 13622 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 13623 } 13624 } 13625 13626 private void broadcastPackageVerified(int verificationId, Uri packageUri, 13627 int verificationCode, UserHandle user) { 13628 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 13629 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 13630 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13631 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13632 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 13633 13634 mContext.sendBroadcastAsUser(intent, user, 13635 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 13636 } 13637 13638 private ComponentName matchComponentForVerifier(String packageName, 13639 List<ResolveInfo> receivers) { 13640 ActivityInfo targetReceiver = null; 13641 13642 final int NR = receivers.size(); 13643 for (int i = 0; i < NR; i++) { 13644 final ResolveInfo info = receivers.get(i); 13645 if (info.activityInfo == null) { 13646 continue; 13647 } 13648 13649 if (packageName.equals(info.activityInfo.packageName)) { 13650 targetReceiver = info.activityInfo; 13651 break; 13652 } 13653 } 13654 13655 if (targetReceiver == null) { 13656 return null; 13657 } 13658 13659 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 13660 } 13661 13662 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 13663 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 13664 if (pkgInfo.verifiers.length == 0) { 13665 return null; 13666 } 13667 13668 final int N = pkgInfo.verifiers.length; 13669 final List<ComponentName> sufficientVerifiers = new ArrayList<>(N + 1); 13670 for (int i = 0; i < N; i++) { 13671 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 13672 13673 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 13674 receivers); 13675 if (comp == null) { 13676 continue; 13677 } 13678 13679 final int verifierUid = getUidForVerifier(verifierInfo); 13680 if (verifierUid == -1) { 13681 continue; 13682 } 13683 13684 if (DEBUG_VERIFY) { 13685 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 13686 + " with the correct signature"); 13687 } 13688 sufficientVerifiers.add(comp); 13689 verificationState.addSufficientVerifier(verifierUid); 13690 } 13691 13692 return sufficientVerifiers; 13693 } 13694 13695 private int getUidForVerifier(VerifierInfo verifierInfo) { 13696 synchronized (mPackages) { 13697 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 13698 if (pkg == null) { 13699 return -1; 13700 } else if (pkg.mSigningDetails.signatures.length != 1) { 13701 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13702 + " has more than one signature; ignoring"); 13703 return -1; 13704 } 13705 13706 /* 13707 * If the public key of the package's signature does not match 13708 * our expected public key, then this is a different package and 13709 * we should skip. 13710 */ 13711 13712 final byte[] expectedPublicKey; 13713 try { 13714 final Signature verifierSig = pkg.mSigningDetails.signatures[0]; 13715 final PublicKey publicKey = verifierSig.getPublicKey(); 13716 expectedPublicKey = publicKey.getEncoded(); 13717 } catch (CertificateException e) { 13718 return -1; 13719 } 13720 13721 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 13722 13723 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 13724 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 13725 + " does not have the expected public key; ignoring"); 13726 return -1; 13727 } 13728 13729 return pkg.applicationInfo.uid; 13730 } 13731 } 13732 13733 private void setEnableRollbackCode(int token, int enableRollbackCode) { 13734 final Message msg = mHandler.obtainMessage(ENABLE_ROLLBACK_STATUS); 13735 msg.arg1 = token; 13736 msg.arg2 = enableRollbackCode; 13737 mHandler.sendMessage(msg); 13738 } 13739 13740 @Override 13741 public void finishPackageInstall(int token, boolean didLaunch) { 13742 enforceSystemOrRoot("Only the system is allowed to finish installs"); 13743 13744 if (DEBUG_INSTALL) { 13745 Slog.v(TAG, "BM finishing package install for " + token); 13746 } 13747 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 13748 13749 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 13750 mHandler.sendMessage(msg); 13751 } 13752 13753 /** 13754 * Get the verification agent timeout. Used for both the APK verifier and the 13755 * intent filter verifier. 13756 * 13757 * @return verification timeout in milliseconds 13758 */ 13759 private long getVerificationTimeout() { 13760 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 13761 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 13762 DEFAULT_VERIFICATION_TIMEOUT); 13763 } 13764 13765 /** 13766 * Get the default verification agent response code. 13767 * 13768 * @return default verification response code 13769 */ 13770 private int getDefaultVerificationResponse(UserHandle user) { 13771 if (sUserManager.hasUserRestriction(UserManager.ENSURE_VERIFY_APPS, user.getIdentifier())) { 13772 return PackageManager.VERIFICATION_REJECT; 13773 } 13774 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13775 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 13776 DEFAULT_VERIFICATION_RESPONSE); 13777 } 13778 13779 /** 13780 * Check whether or not package verification has been enabled. 13781 * 13782 * @return true if verification should be performed 13783 */ 13784 private boolean isVerificationEnabled(int userId, int installFlags, int installerUid) { 13785 if (!DEFAULT_VERIFY_ENABLE) { 13786 return false; 13787 } 13788 13789 if ((installFlags & PackageManager.INSTALL_DISABLE_VERIFICATION) != 0) { 13790 return false; 13791 } 13792 13793 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 13794 13795 // Check if installing from ADB 13796 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 13797 // Do not run verification in a test harness environment 13798 if (ActivityManager.isRunningInTestHarness()) { 13799 return false; 13800 } 13801 if (ensureVerifyAppsEnabled) { 13802 return true; 13803 } 13804 // Check if the developer does not want package verification for ADB installs 13805 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13806 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 13807 return false; 13808 } 13809 } else { 13810 // only when not installed from ADB, skip verification for instant apps when 13811 // the installer and verifier are the same. 13812 if ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0) { 13813 if (mInstantAppInstallerActivity != null 13814 && mInstantAppInstallerActivity.packageName.equals( 13815 mRequiredVerifierPackage)) { 13816 try { 13817 mContext.getSystemService(AppOpsManager.class) 13818 .checkPackage(installerUid, mRequiredVerifierPackage); 13819 if (DEBUG_VERIFY) { 13820 Slog.i(TAG, "disable verification for instant app"); 13821 } 13822 return false; 13823 } catch (SecurityException ignore) { } 13824 } 13825 } 13826 } 13827 13828 if (ensureVerifyAppsEnabled) { 13829 return true; 13830 } 13831 13832 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 13833 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 13834 } 13835 13836 @Override 13837 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 13838 throws RemoteException { 13839 mContext.enforceCallingOrSelfPermission( 13840 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 13841 "Only intentfilter verification agents can verify applications"); 13842 13843 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 13844 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 13845 Binder.getCallingUid(), verificationCode, failedDomains); 13846 msg.arg1 = id; 13847 msg.obj = response; 13848 mHandler.sendMessage(msg); 13849 } 13850 13851 @Override 13852 public int getIntentVerificationStatus(String packageName, int userId) { 13853 final int callingUid = Binder.getCallingUid(); 13854 if (UserHandle.getUserId(callingUid) != userId) { 13855 mContext.enforceCallingOrSelfPermission( 13856 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 13857 "getIntentVerificationStatus" + userId); 13858 } 13859 if (getInstantAppPackageName(callingUid) != null) { 13860 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13861 } 13862 synchronized (mPackages) { 13863 final PackageSetting ps = mSettings.mPackages.get(packageName); 13864 if (ps == null 13865 || filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 13866 return INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 13867 } 13868 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 13869 } 13870 } 13871 13872 @Override 13873 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 13874 mContext.enforceCallingOrSelfPermission( 13875 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13876 13877 boolean result = false; 13878 synchronized (mPackages) { 13879 final PackageSetting ps = mSettings.mPackages.get(packageName); 13880 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 13881 return false; 13882 } 13883 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 13884 } 13885 if (result) { 13886 scheduleWritePackageRestrictionsLocked(userId); 13887 } 13888 return result; 13889 } 13890 13891 @Override 13892 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 13893 String packageName) { 13894 final int callingUid = Binder.getCallingUid(); 13895 if (getInstantAppPackageName(callingUid) != null) { 13896 return ParceledListSlice.emptyList(); 13897 } 13898 synchronized (mPackages) { 13899 final PackageSetting ps = mSettings.mPackages.get(packageName); 13900 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 13901 return ParceledListSlice.emptyList(); 13902 } 13903 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 13904 } 13905 } 13906 13907 @Override 13908 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 13909 if (TextUtils.isEmpty(packageName)) { 13910 return ParceledListSlice.emptyList(); 13911 } 13912 final int callingUid = Binder.getCallingUid(); 13913 final int callingUserId = UserHandle.getUserId(callingUid); 13914 synchronized (mPackages) { 13915 PackageParser.Package pkg = mPackages.get(packageName); 13916 if (pkg == null || pkg.activities == null) { 13917 return ParceledListSlice.emptyList(); 13918 } 13919 if (pkg.mExtras == null) { 13920 return ParceledListSlice.emptyList(); 13921 } 13922 final PackageSetting ps = (PackageSetting) pkg.mExtras; 13923 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 13924 return ParceledListSlice.emptyList(); 13925 } 13926 final int count = pkg.activities.size(); 13927 ArrayList<IntentFilter> result = new ArrayList<>(); 13928 for (int n=0; n<count; n++) { 13929 PackageParser.Activity activity = pkg.activities.get(n); 13930 if (activity.intents != null && activity.intents.size() > 0) { 13931 result.addAll(activity.intents); 13932 } 13933 } 13934 return new ParceledListSlice<>(result); 13935 } 13936 } 13937 13938 @Override 13939 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 13940 mContext.enforceCallingOrSelfPermission( 13941 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 13942 if (UserHandle.getCallingUserId() != userId) { 13943 mContext.enforceCallingOrSelfPermission( 13944 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13945 } 13946 if (userId == UserHandle.USER_ALL) { 13947 return false; 13948 } 13949 PackageManagerInternal.DefaultBrowserProvider provider; 13950 synchronized (mPackages) { 13951 provider = mDefaultBrowserProvider; 13952 } 13953 if (provider == null) { 13954 Slog.e(TAG, "mDefaultBrowserProvider is null"); 13955 return false; 13956 } 13957 boolean successful = provider.setDefaultBrowser(packageName, userId); 13958 if (!successful) { 13959 return false; 13960 } 13961 if (packageName != null) { 13962 synchronized (mPackages) { 13963 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName, 13964 userId); 13965 } 13966 } 13967 return true; 13968 } 13969 13970 private void setDefaultBrowserAsyncLPw(@Nullable String packageName, @UserIdInt int userId) { 13971 if (userId == UserHandle.USER_ALL) { 13972 return; 13973 } 13974 if (mDefaultBrowserProvider == null) { 13975 Slog.e(TAG, "mDefaultBrowserProvider is null"); 13976 return; 13977 } 13978 mDefaultBrowserProvider.setDefaultBrowserAsync(packageName, userId); 13979 if (packageName != null) { 13980 synchronized (mPackages) { 13981 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowser(packageName, 13982 userId); 13983 } 13984 } 13985 } 13986 13987 @Override 13988 public String getDefaultBrowserPackageName(int userId) { 13989 if (UserHandle.getCallingUserId() != userId) { 13990 mContext.enforceCallingOrSelfPermission( 13991 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 13992 } 13993 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 13994 return null; 13995 } 13996 PackageManagerInternal.DefaultBrowserProvider provider; 13997 synchronized (mPackages) { 13998 provider = mDefaultBrowserProvider; 13999 } 14000 if (provider == null) { 14001 Slog.e(TAG, "mDefaultBrowserProvider is null"); 14002 return null; 14003 } 14004 return provider.getDefaultBrowser(userId); 14005 } 14006 14007 /** 14008 * Get the "allow unknown sources" setting. 14009 * 14010 * @return the current "allow unknown sources" setting 14011 */ 14012 private int getUnknownSourcesSettings() { 14013 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 14014 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 14015 -1); 14016 } 14017 14018 @Override 14019 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 14020 final int callingUid = Binder.getCallingUid(); 14021 if (getInstantAppPackageName(callingUid) != null) { 14022 return; 14023 } 14024 // writer 14025 synchronized (mPackages) { 14026 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 14027 if (targetPackageSetting == null 14028 || filterAppAccessLPr( 14029 targetPackageSetting, callingUid, UserHandle.getUserId(callingUid))) { 14030 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 14031 } 14032 14033 PackageSetting installerPackageSetting; 14034 if (installerPackageName != null) { 14035 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 14036 if (installerPackageSetting == null) { 14037 throw new IllegalArgumentException("Unknown installer package: " 14038 + installerPackageName); 14039 } 14040 } else { 14041 installerPackageSetting = null; 14042 } 14043 14044 Signature[] callerSignature; 14045 final int appId = UserHandle.getAppId(callingUid); 14046 final Object obj = mSettings.getSettingLPr(appId); 14047 if (obj != null) { 14048 if (obj instanceof SharedUserSetting) { 14049 callerSignature = 14050 ((SharedUserSetting)obj).signatures.mSigningDetails.signatures; 14051 } else if (obj instanceof PackageSetting) { 14052 callerSignature = ((PackageSetting)obj).signatures.mSigningDetails.signatures; 14053 } else { 14054 throw new SecurityException("Bad object " + obj + " for uid " + callingUid); 14055 } 14056 } else { 14057 throw new SecurityException("Unknown calling UID: " + callingUid); 14058 } 14059 14060 // Verify: can't set installerPackageName to a package that is 14061 // not signed with the same cert as the caller. 14062 if (installerPackageSetting != null) { 14063 if (compareSignatures(callerSignature, 14064 installerPackageSetting.signatures.mSigningDetails.signatures) 14065 != PackageManager.SIGNATURE_MATCH) { 14066 throw new SecurityException( 14067 "Caller does not have same cert as new installer package " 14068 + installerPackageName); 14069 } 14070 } 14071 14072 // Verify: if target already has an installer package, it must 14073 // be signed with the same cert as the caller. 14074 if (targetPackageSetting.installerPackageName != null) { 14075 PackageSetting setting = mSettings.mPackages.get( 14076 targetPackageSetting.installerPackageName); 14077 // If the currently set package isn't valid, then it's always 14078 // okay to change it. 14079 if (setting != null) { 14080 if (compareSignatures(callerSignature, 14081 setting.signatures.mSigningDetails.signatures) 14082 != PackageManager.SIGNATURE_MATCH) { 14083 throw new SecurityException( 14084 "Caller does not have same cert as old installer package " 14085 + targetPackageSetting.installerPackageName); 14086 } 14087 } 14088 } 14089 14090 // Okay! 14091 targetPackageSetting.installerPackageName = installerPackageName; 14092 if (installerPackageName != null) { 14093 mSettings.mInstallerPackages.add(installerPackageName); 14094 } 14095 scheduleWriteSettingsLocked(); 14096 } 14097 } 14098 14099 @Override 14100 public void setApplicationCategoryHint(String packageName, int categoryHint, 14101 String callerPackageName) { 14102 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 14103 throw new SecurityException("Instant applications don't have access to this method"); 14104 } 14105 mContext.getSystemService(AppOpsManager.class).checkPackage(Binder.getCallingUid(), 14106 callerPackageName); 14107 synchronized (mPackages) { 14108 PackageSetting ps = mSettings.mPackages.get(packageName); 14109 if (ps == null) { 14110 throw new IllegalArgumentException("Unknown target package " + packageName); 14111 } 14112 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 14113 throw new IllegalArgumentException("Unknown target package " + packageName); 14114 } 14115 if (!Objects.equals(callerPackageName, ps.installerPackageName)) { 14116 throw new IllegalArgumentException("Calling package " + callerPackageName 14117 + " is not installer for " + packageName); 14118 } 14119 14120 if (ps.categoryHint != categoryHint) { 14121 ps.categoryHint = categoryHint; 14122 scheduleWriteSettingsLocked(); 14123 } 14124 } 14125 } 14126 14127 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 14128 if (args.mMultiPackageInstallParams != null) { 14129 args.mMultiPackageInstallParams.tryProcessInstallRequest(args, currentStatus); 14130 } else { 14131 PackageInstalledInfo res = createPackageInstalledInfo(currentStatus); 14132 processInstallRequestsAsync( 14133 res.returnCode == PackageManager.INSTALL_SUCCEEDED, 14134 Collections.singletonList(new InstallRequest(args, res))); 14135 } 14136 } 14137 14138 // Queue up an async operation since the package installation may take a little while. 14139 private void processInstallRequestsAsync(boolean success, 14140 List<InstallRequest> installRequests) { 14141 mHandler.post(() -> { 14142 if (success) { 14143 for (InstallRequest request : installRequests) { 14144 request.args.doPreInstall(request.installResult.returnCode); 14145 } 14146 synchronized (mInstallLock) { 14147 installPackagesTracedLI(installRequests); 14148 } 14149 for (InstallRequest request : installRequests) { 14150 request.args.doPostInstall( 14151 request.installResult.returnCode, request.installResult.uid); 14152 } 14153 } 14154 for (InstallRequest request : installRequests) { 14155 restoreAndPostInstall(request.args.user.getIdentifier(), request.installResult, 14156 new PostInstallData(request.args, request.installResult, null)); 14157 } 14158 }); 14159 } 14160 14161 private PackageInstalledInfo createPackageInstalledInfo( 14162 int currentStatus) { 14163 PackageInstalledInfo res = new PackageInstalledInfo(); 14164 res.setReturnCode(currentStatus); 14165 res.uid = -1; 14166 res.pkg = null; 14167 res.removedInfo = null; 14168 return res; 14169 } 14170 14171 /** @param data Post-install is performed only if this is non-null. */ 14172 private void restoreAndPostInstall( 14173 int userId, PackageInstalledInfo res, @Nullable PostInstallData data) { 14174 if (DEBUG_INSTALL) { 14175 Log.v(TAG, "restoreAndPostInstall userId=" + userId + " package=" 14176 + res.pkg.packageName); 14177 } 14178 14179 // A restore should be performed at this point if (a) the install 14180 // succeeded, (b) the operation is not an update, and (c) the new 14181 // package has not opted out of backup participation. 14182 final boolean update = res.removedInfo != null 14183 && res.removedInfo.removedPackage != null; 14184 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 14185 boolean doRestore = !update 14186 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 14187 14188 // Set up the post-install work request bookkeeping. This will be used 14189 // and cleaned up by the post-install event handling regardless of whether 14190 // there's a restore pass performed. Token values are >= 1. 14191 int token; 14192 if (mNextInstallToken < 0) mNextInstallToken = 1; 14193 token = mNextInstallToken++; 14194 if (data != null) { 14195 mRunningInstalls.put(token, data); 14196 } else if (DEBUG_INSTALL) { 14197 Log.v(TAG, "No post-install required for " + token); 14198 } 14199 14200 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 14201 14202 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 14203 // Pass responsibility to the Backup Manager. It will perform a 14204 // restore if appropriate, then pass responsibility back to the 14205 // Package Manager to run the post-install observer callbacks 14206 // and broadcasts. 14207 IBackupManager bm = IBackupManager.Stub.asInterface( 14208 ServiceManager.getService(Context.BACKUP_SERVICE)); 14209 if (bm != null) { 14210 // For backwards compatibility as USER_ALL previously routed directly to USER_SYSTEM 14211 // in the BackupManager. USER_ALL is used in compatibility tests. 14212 if (userId == UserHandle.USER_ALL) { 14213 userId = UserHandle.USER_SYSTEM; 14214 } 14215 if (DEBUG_INSTALL) { 14216 Log.v(TAG, "token " + token + " to BM for possible restore for user " + userId); 14217 } 14218 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 14219 try { 14220 if (bm.isBackupServiceActive(userId)) { 14221 bm.restoreAtInstallForUser( 14222 userId, res.pkg.applicationInfo.packageName, token); 14223 } else { 14224 doRestore = false; 14225 } 14226 } catch (RemoteException e) { 14227 // can't happen; the backup manager is local 14228 } catch (Exception e) { 14229 Slog.e(TAG, "Exception trying to enqueue restore", e); 14230 doRestore = false; 14231 } 14232 } else { 14233 Slog.e(TAG, "Backup Manager not found!"); 14234 doRestore = false; 14235 } 14236 } 14237 14238 // If this is an update to a package that might be potentially downgraded, then we 14239 // need to check with the rollback manager whether there's any userdata that might 14240 // need to be restored for the package. 14241 // 14242 // TODO(narayan): Get this working for cases where userId == UserHandle.USER_ALL. 14243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && !doRestore && update) { 14244 IRollbackManager rm = IRollbackManager.Stub.asInterface( 14245 ServiceManager.getService(Context.ROLLBACK_SERVICE)); 14246 14247 final String packageName = res.pkg.applicationInfo.packageName; 14248 final String seInfo = res.pkg.applicationInfo.seInfo; 14249 final int[] allUsers = sUserManager.getUserIds(); 14250 final int[] installedUsers; 14251 14252 final PackageSetting ps; 14253 int appId = -1; 14254 long ceDataInode = -1; 14255 synchronized (mSettings) { 14256 ps = mSettings.getPackageLPr(packageName); 14257 if (ps != null) { 14258 appId = ps.appId; 14259 ceDataInode = ps.getCeDataInode(userId); 14260 } 14261 14262 // NOTE: We ignore the user specified in the InstallParam because we know this is 14263 // an update, and hence need to restore data for all installed users. 14264 installedUsers = ps.queryInstalledUsers(allUsers, true); 14265 } 14266 14267 if (ps != null) { 14268 try { 14269 rm.snapshotAndRestoreUserData(packageName, installedUsers, appId, ceDataInode, 14270 seInfo, token); 14271 } catch (RemoteException re) { 14272 // Cannot happen, the RollbackManager is hosted in the same process. 14273 } 14274 doRestore = true; 14275 } 14276 } 14277 14278 if (!doRestore) { 14279 // No restore possible, or the Backup Manager was mysteriously not 14280 // available -- just fire the post-install work request directly. 14281 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 14282 14283 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 14284 14285 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 14286 mHandler.sendMessage(msg); 14287 } 14288 } 14289 14290 /** 14291 * Callback from PackageSettings whenever an app is first transitioned out of the 14292 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 14293 * the app was "launched" for a restoreAtInstall operation. Therefore we check 14294 * here whether the app is the target of an ongoing install, and only send the 14295 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 14296 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 14297 * handling. 14298 */ 14299 void notifyFirstLaunch(final String packageName, final String installerPackage, 14300 final int userId) { 14301 // Serialize this with the rest of the install-process message chain. In the 14302 // restore-at-install case, this Runnable will necessarily run before the 14303 // POST_INSTALL message is processed, so the contents of mRunningInstalls 14304 // are coherent. In the non-restore case, the app has already completed install 14305 // and been launched through some other means, so it is not in a problematic 14306 // state for observers to see the FIRST_LAUNCH signal. 14307 mHandler.post(() -> { 14308 for (int i = 0; i < mRunningInstalls.size(); i++) { 14309 final PostInstallData data = mRunningInstalls.valueAt(i); 14310 if (data.res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14311 continue; 14312 } 14313 if (packageName.equals(data.res.pkg.applicationInfo.packageName)) { 14314 // right package; but is it for the right user? 14315 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 14316 if (userId == data.res.newUsers[uIndex]) { 14317 if (DEBUG_BACKUP) { 14318 Slog.i(TAG, "Package " + packageName 14319 + " being restored so deferring FIRST_LAUNCH"); 14320 } 14321 return; 14322 } 14323 } 14324 } 14325 } 14326 // didn't find it, so not being restored 14327 if (DEBUG_BACKUP) { 14328 Slog.i(TAG, "Package " + packageName + " sending normal FIRST_LAUNCH"); 14329 } 14330 final boolean isInstantApp = isInstantApp(packageName, userId); 14331 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 14332 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 14333 sendFirstLaunchBroadcast(packageName, installerPackage, userIds, instantUserIds); 14334 }); 14335 } 14336 14337 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, 14338 int[] userIds, int[] instantUserIds) { 14339 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 14340 installerPkg, null, userIds, instantUserIds); 14341 } 14342 14343 private abstract class HandlerParams { 14344 /** User handle for the user requesting the information or installation. */ 14345 private final UserHandle mUser; 14346 String traceMethod; 14347 int traceCookie; 14348 14349 HandlerParams(UserHandle user) { 14350 mUser = user; 14351 } 14352 14353 UserHandle getUser() { 14354 return mUser; 14355 } 14356 14357 /** 14358 * Gets the user handle for the user that the rollback agent should 14359 * use to look up information about this installation when enabling 14360 * rollback. 14361 */ 14362 UserHandle getRollbackUser() { 14363 // The session for packages installed for "all" users is 14364 // associated with the "system" user. 14365 if (mUser == UserHandle.ALL) { 14366 return UserHandle.SYSTEM; 14367 } 14368 return mUser; 14369 } 14370 14371 HandlerParams setTraceMethod(String traceMethod) { 14372 this.traceMethod = traceMethod; 14373 return this; 14374 } 14375 14376 HandlerParams setTraceCookie(int traceCookie) { 14377 this.traceCookie = traceCookie; 14378 return this; 14379 } 14380 14381 final void startCopy() { 14382 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 14383 handleStartCopy(); 14384 handleReturnCode(); 14385 } 14386 14387 abstract void handleStartCopy(); 14388 abstract void handleReturnCode(); 14389 } 14390 14391 static class OriginInfo { 14392 /** 14393 * Location where install is coming from, before it has been 14394 * copied/renamed into place. This could be a single monolithic APK 14395 * file, or a cluster directory. This location may be untrusted. 14396 */ 14397 final File file; 14398 14399 /** 14400 * Flag indicating that {@link #file} has already been staged, meaning downstream users 14401 * don't need to defensively copy the contents. 14402 */ 14403 final boolean staged; 14404 14405 /** 14406 * Flag indicating that {@link #file} is an already installed app that is being moved. 14407 */ 14408 final boolean existing; 14409 14410 final String resolvedPath; 14411 final File resolvedFile; 14412 14413 static OriginInfo fromNothing() { 14414 return new OriginInfo(null, false, false); 14415 } 14416 14417 static OriginInfo fromUntrustedFile(File file) { 14418 return new OriginInfo(file, false, false); 14419 } 14420 14421 static OriginInfo fromExistingFile(File file) { 14422 return new OriginInfo(file, false, true); 14423 } 14424 14425 static OriginInfo fromStagedFile(File file) { 14426 return new OriginInfo(file, true, false); 14427 } 14428 14429 private OriginInfo(File file, boolean staged, boolean existing) { 14430 this.file = file; 14431 this.staged = staged; 14432 this.existing = existing; 14433 14434 if (file != null) { 14435 resolvedPath = file.getAbsolutePath(); 14436 resolvedFile = file; 14437 } else { 14438 resolvedPath = null; 14439 resolvedFile = null; 14440 } 14441 } 14442 } 14443 14444 static class MoveInfo { 14445 final int moveId; 14446 final String fromUuid; 14447 final String toUuid; 14448 final String packageName; 14449 final String dataAppName; 14450 final int appId; 14451 final String seinfo; 14452 final int targetSdkVersion; 14453 14454 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 14455 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 14456 this.moveId = moveId; 14457 this.fromUuid = fromUuid; 14458 this.toUuid = toUuid; 14459 this.packageName = packageName; 14460 this.dataAppName = dataAppName; 14461 this.appId = appId; 14462 this.seinfo = seinfo; 14463 this.targetSdkVersion = targetSdkVersion; 14464 } 14465 } 14466 14467 static class VerificationInfo { 14468 /** A constant used to indicate that a uid value is not present. */ 14469 public static final int NO_UID = -1; 14470 14471 /** URI referencing where the package was downloaded from. */ 14472 final Uri originatingUri; 14473 14474 /** HTTP referrer URI associated with the originatingURI. */ 14475 final Uri referrer; 14476 14477 /** UID of the application that the install request originated from. */ 14478 final int originatingUid; 14479 14480 /** UID of application requesting the install */ 14481 final int installerUid; 14482 14483 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 14484 this.originatingUri = originatingUri; 14485 this.referrer = referrer; 14486 this.originatingUid = originatingUid; 14487 this.installerUid = installerUid; 14488 } 14489 } 14490 14491 /** 14492 * Container for a multi-package install which refers to all install sessions and args being 14493 * committed together. 14494 */ 14495 class MultiPackageInstallParams extends HandlerParams { 14496 14497 private int mRet = INSTALL_SUCCEEDED; 14498 @NonNull 14499 private final ArrayList<InstallParams> mChildParams; 14500 @NonNull 14501 private final Map<InstallArgs, Integer> mCurrentState; 14502 14503 MultiPackageInstallParams( 14504 @NonNull UserHandle user, 14505 @NonNull List<ActiveInstallSession> activeInstallSessions) 14506 throws PackageManagerException { 14507 super(user); 14508 if (activeInstallSessions.size() == 0) { 14509 throw new PackageManagerException("No child sessions found!"); 14510 } 14511 mChildParams = new ArrayList<>(activeInstallSessions.size()); 14512 for (int i = 0; i < activeInstallSessions.size(); i++) { 14513 final InstallParams childParams = new InstallParams(activeInstallSessions.get(i)); 14514 childParams.mParentInstallParams = this; 14515 this.mChildParams.add(childParams); 14516 } 14517 this.mCurrentState = new ArrayMap<>(mChildParams.size()); 14518 } 14519 14520 @Override 14521 void handleStartCopy() { 14522 for (InstallParams params : mChildParams) { 14523 params.handleStartCopy(); 14524 if (params.mRet != INSTALL_SUCCEEDED) { 14525 mRet = params.mRet; 14526 } 14527 } 14528 } 14529 14530 @Override 14531 void handleReturnCode() { 14532 for (InstallParams params : mChildParams) { 14533 params.handleReturnCode(); 14534 if (params.mRet != INSTALL_SUCCEEDED) { 14535 mRet = params.mRet; 14536 } 14537 } 14538 } 14539 14540 void tryProcessInstallRequest(InstallArgs args, int currentStatus) { 14541 mCurrentState.put(args, currentStatus); 14542 if (mCurrentState.size() != mChildParams.size()) { 14543 return; 14544 } 14545 int completeStatus = PackageManager.INSTALL_SUCCEEDED; 14546 for (Integer status : mCurrentState.values()) { 14547 if (status == PackageManager.INSTALL_UNKNOWN) { 14548 return; 14549 } else if (status != PackageManager.INSTALL_SUCCEEDED) { 14550 completeStatus = status; 14551 break; 14552 } 14553 } 14554 final List<InstallRequest> installRequests = new ArrayList<>(mCurrentState.size()); 14555 for (Map.Entry<InstallArgs, Integer> entry : mCurrentState.entrySet()) { 14556 installRequests.add(new InstallRequest(entry.getKey(), 14557 createPackageInstalledInfo(completeStatus))); 14558 } 14559 processInstallRequestsAsync( 14560 completeStatus == PackageManager.INSTALL_SUCCEEDED, 14561 installRequests); 14562 } 14563 } 14564 14565 class InstallParams extends HandlerParams { 14566 // TODO: see if we can collapse this into ActiveInstallSession 14567 14568 final OriginInfo origin; 14569 final MoveInfo move; 14570 final IPackageInstallObserver2 observer; 14571 int installFlags; 14572 final String installerPackageName; 14573 final String volumeUuid; 14574 private boolean mVerificationCompleted; 14575 private boolean mEnableRollbackCompleted; 14576 private InstallArgs mArgs; 14577 int mRet; 14578 final String packageAbiOverride; 14579 final String[] grantedRuntimePermissions; 14580 final List<String> whitelistedRestrictedPermissions; 14581 final VerificationInfo verificationInfo; 14582 final PackageParser.SigningDetails signingDetails; 14583 final int installReason; 14584 @Nullable 14585 MultiPackageInstallParams mParentInstallParams; 14586 final long requiredInstalledVersionCode; 14587 14588 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 14589 int installFlags, String installerPackageName, String volumeUuid, 14590 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 14591 String[] grantedPermissions, List<String> whitelistedRestrictedPermissions, 14592 PackageParser.SigningDetails signingDetails, int installReason, 14593 long requiredInstalledVersionCode) { 14594 super(user); 14595 this.origin = origin; 14596 this.move = move; 14597 this.observer = observer; 14598 this.installFlags = installFlags; 14599 this.installerPackageName = installerPackageName; 14600 this.volumeUuid = volumeUuid; 14601 this.verificationInfo = verificationInfo; 14602 this.packageAbiOverride = packageAbiOverride; 14603 this.grantedRuntimePermissions = grantedPermissions; 14604 this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions; 14605 this.signingDetails = signingDetails; 14606 this.installReason = installReason; 14607 this.requiredInstalledVersionCode = requiredInstalledVersionCode; 14608 } 14609 14610 InstallParams(ActiveInstallSession activeInstallSession) { 14611 super(activeInstallSession.getUser()); 14612 if (DEBUG_INSTANT) { 14613 if ((activeInstallSession.getSessionParams().installFlags 14614 & PackageManager.INSTALL_INSTANT_APP) != 0) { 14615 Slog.d(TAG, "Ephemeral install of " + activeInstallSession.getPackageName()); 14616 } 14617 } 14618 verificationInfo = new VerificationInfo( 14619 activeInstallSession.getSessionParams().originatingUri, 14620 activeInstallSession.getSessionParams().referrerUri, 14621 activeInstallSession.getSessionParams().originatingUid, 14622 activeInstallSession.getInstallerUid()); 14623 origin = OriginInfo.fromStagedFile(activeInstallSession.getStagedDir()); 14624 move = null; 14625 installReason = fixUpInstallReason(activeInstallSession.getInstallerPackageName(), 14626 activeInstallSession.getInstallerUid(), 14627 activeInstallSession.getSessionParams().installReason); 14628 observer = activeInstallSession.getObserver(); 14629 installFlags = activeInstallSession.getSessionParams().installFlags; 14630 installerPackageName = activeInstallSession.getInstallerPackageName(); 14631 volumeUuid = activeInstallSession.getSessionParams().volumeUuid; 14632 packageAbiOverride = activeInstallSession.getSessionParams().abiOverride; 14633 grantedRuntimePermissions = activeInstallSession.getSessionParams() 14634 .grantedRuntimePermissions; 14635 whitelistedRestrictedPermissions = activeInstallSession.getSessionParams() 14636 .whitelistedRestrictedPermissions; 14637 signingDetails = activeInstallSession.getSigningDetails(); 14638 requiredInstalledVersionCode = activeInstallSession.getSessionParams() 14639 .requiredInstalledVersionCode; 14640 } 14641 14642 @Override 14643 public String toString() { 14644 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 14645 + " file=" + origin.file + "}"; 14646 } 14647 14648 private int installLocationPolicy(PackageInfoLite pkgLite) { 14649 String packageName = pkgLite.packageName; 14650 int installLocation = pkgLite.installLocation; 14651 // reader 14652 synchronized (mPackages) { 14653 // Currently installed package which the new package is attempting to replace or 14654 // null if no such package is installed. 14655 PackageParser.Package installedPkg = mPackages.get(packageName); 14656 // Package which currently owns the data which the new package will own if installed. 14657 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 14658 // will be null whereas dataOwnerPkg will contain information about the package 14659 // which was uninstalled while keeping its data. 14660 PackageParser.Package dataOwnerPkg = installedPkg; 14661 if (dataOwnerPkg == null) { 14662 PackageSetting ps = mSettings.mPackages.get(packageName); 14663 if (ps != null) { 14664 dataOwnerPkg = ps.pkg; 14665 } 14666 } 14667 14668 if (requiredInstalledVersionCode != PackageManager.VERSION_CODE_HIGHEST) { 14669 if (dataOwnerPkg == null) { 14670 Slog.w(TAG, "Required installed version code was " 14671 + requiredInstalledVersionCode 14672 + " but package is not installed"); 14673 return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION; 14674 } 14675 14676 if (dataOwnerPkg.getLongVersionCode() != requiredInstalledVersionCode) { 14677 Slog.w(TAG, "Required installed version code was " 14678 + requiredInstalledVersionCode 14679 + " but actual installed version is " 14680 + dataOwnerPkg.getLongVersionCode()); 14681 return PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION; 14682 } 14683 } 14684 14685 if (dataOwnerPkg != null) { 14686 if (!PackageManagerServiceUtils.isDowngradePermitted(installFlags, 14687 dataOwnerPkg.applicationInfo.flags)) { 14688 try { 14689 checkDowngrade(dataOwnerPkg, pkgLite); 14690 } catch (PackageManagerException e) { 14691 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 14692 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 14693 } 14694 } 14695 } 14696 14697 if (installedPkg != null) { 14698 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14699 // Check for updated system application. 14700 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 14701 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14702 } else { 14703 // If current upgrade specifies particular preference 14704 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 14705 // Application explicitly specified internal. 14706 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14707 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 14708 // App explictly prefers external. Let policy decide 14709 } else { 14710 // Prefer previous location 14711 if (isExternal(installedPkg)) { 14712 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 14713 } 14714 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 14715 } 14716 } 14717 } else { 14718 // Invalid install. Return error code 14719 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 14720 } 14721 } 14722 } 14723 return pkgLite.recommendedInstallLocation; 14724 } 14725 14726 /* 14727 * Invoke remote method to get package information and install 14728 * location values. Override install location based on default 14729 * policy if needed and then create install arguments based 14730 * on the install location. 14731 */ 14732 public void handleStartCopy() { 14733 int ret = PackageManager.INSTALL_SUCCEEDED; 14734 14735 // If we're already staged, we've firmly committed to an install location 14736 if (origin.staged) { 14737 if (origin.file != null) { 14738 installFlags |= PackageManager.INSTALL_INTERNAL; 14739 } else { 14740 throw new IllegalStateException("Invalid stage location"); 14741 } 14742 } 14743 14744 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 14745 final boolean ephemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 14746 PackageInfoLite pkgLite = null; 14747 14748 14749 pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext, 14750 origin.resolvedPath, installFlags, packageAbiOverride); 14751 14752 if (DEBUG_INSTANT && ephemeral) { 14753 Slog.v(TAG, "pkgLite for install: " + pkgLite); 14754 } 14755 14756 /* 14757 * If we have too little free space, try to free cache 14758 * before giving up. 14759 */ 14760 if (!origin.staged && pkgLite.recommendedInstallLocation 14761 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14762 // TODO: focus freeing disk space on the target device 14763 final StorageManager storage = StorageManager.from(mContext); 14764 final long lowThreshold = storage.getStorageLowBytes( 14765 Environment.getDataDirectory()); 14766 14767 final long sizeBytes = PackageManagerServiceUtils.calculateInstalledSize( 14768 origin.resolvedPath, packageAbiOverride); 14769 if (sizeBytes >= 0) { 14770 try { 14771 mInstaller.freeCache(null, sizeBytes + lowThreshold, 0, 0); 14772 pkgLite = PackageManagerServiceUtils.getMinimalPackageInfo(mContext, 14773 origin.resolvedPath, installFlags, packageAbiOverride); 14774 } catch (InstallerException e) { 14775 Slog.w(TAG, "Failed to free cache", e); 14776 } 14777 } 14778 14779 /* 14780 * The cache free must have deleted the file we downloaded to install. 14781 * 14782 * TODO: fix the "freeCache" call to not delete the file we care about. 14783 */ 14784 if (pkgLite.recommendedInstallLocation 14785 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14786 pkgLite.recommendedInstallLocation 14787 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 14788 } 14789 } 14790 14791 14792 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14793 int loc = pkgLite.recommendedInstallLocation; 14794 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 14795 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 14796 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 14797 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 14798 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 14799 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 14800 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 14801 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 14802 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 14803 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 14804 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 14805 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 14806 } else { 14807 // Override with defaults if needed. 14808 loc = installLocationPolicy(pkgLite); 14809 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 14810 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 14811 } else if (loc == PackageHelper.RECOMMEND_FAILED_WRONG_INSTALLED_VERSION) { 14812 ret = PackageManager.INSTALL_FAILED_WRONG_INSTALLED_VERSION; 14813 } else if (!onInt) { 14814 // Override install location with flags 14815 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 14816 // Set the flag to install on external media. 14817 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14818 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 14819 if (DEBUG_INSTANT) { 14820 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 14821 } 14822 installFlags |= PackageManager.INSTALL_INSTANT_APP; 14823 installFlags &= ~PackageManager.INSTALL_INTERNAL; 14824 } else { 14825 // Make sure the flag for installing on external 14826 // media is unset 14827 installFlags |= PackageManager.INSTALL_INTERNAL; 14828 } 14829 } 14830 } 14831 } 14832 14833 final InstallArgs args = createInstallArgs(this); 14834 mVerificationCompleted = true; 14835 mEnableRollbackCompleted = true; 14836 mArgs = args; 14837 14838 if (ret == PackageManager.INSTALL_SUCCEEDED) { 14839 // TODO: http://b/22976637 14840 // Apps installed for "all" users use the device owner to verify the app 14841 UserHandle verifierUser = getUser(); 14842 if (verifierUser == UserHandle.ALL) { 14843 verifierUser = UserHandle.SYSTEM; 14844 } 14845 14846 /* 14847 * Determine if we have any installed package verifiers. If we 14848 * do, then we'll defer to them to verify the packages. 14849 */ 14850 final int requiredUid = mRequiredVerifierPackage == null ? -1 14851 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 14852 verifierUser.getIdentifier()); 14853 final int installerUid = 14854 verificationInfo == null ? -1 : verificationInfo.installerUid; 14855 if (!origin.existing && requiredUid != -1 14856 && isVerificationEnabled( 14857 verifierUser.getIdentifier(), installFlags, installerUid)) { 14858 final Intent verification = new Intent( 14859 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 14860 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 14861 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 14862 PACKAGE_MIME_TYPE); 14863 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 14864 14865 // Query all live verifiers based on current user state 14866 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 14867 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier(), 14868 false /*allowDynamicSplits*/); 14869 14870 if (DEBUG_VERIFY) { 14871 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 14872 + verification.toString() + " with " + pkgLite.verifiers.length 14873 + " optional verifiers"); 14874 } 14875 14876 final int verificationId = mPendingVerificationToken++; 14877 14878 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 14879 14880 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 14881 installerPackageName); 14882 14883 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 14884 installFlags); 14885 14886 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 14887 pkgLite.packageName); 14888 14889 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 14890 pkgLite.versionCode); 14891 14892 verification.putExtra(PackageManager.EXTRA_VERIFICATION_LONG_VERSION_CODE, 14893 pkgLite.getLongVersionCode()); 14894 14895 if (verificationInfo != null) { 14896 if (verificationInfo.originatingUri != null) { 14897 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 14898 verificationInfo.originatingUri); 14899 } 14900 if (verificationInfo.referrer != null) { 14901 verification.putExtra(Intent.EXTRA_REFERRER, 14902 verificationInfo.referrer); 14903 } 14904 if (verificationInfo.originatingUid >= 0) { 14905 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 14906 verificationInfo.originatingUid); 14907 } 14908 if (verificationInfo.installerUid >= 0) { 14909 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 14910 verificationInfo.installerUid); 14911 } 14912 } 14913 14914 final PackageVerificationState verificationState = new PackageVerificationState( 14915 requiredUid, this); 14916 14917 mPendingVerification.append(verificationId, verificationState); 14918 14919 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 14920 receivers, verificationState); 14921 14922 DeviceIdleController.LocalService idleController = getDeviceIdleController(); 14923 final long idleDuration = getVerificationTimeout(); 14924 14925 /* 14926 * If any sufficient verifiers were listed in the package 14927 * manifest, attempt to ask them. 14928 */ 14929 if (sufficientVerifiers != null) { 14930 final int N = sufficientVerifiers.size(); 14931 if (N == 0) { 14932 Slog.i(TAG, "Additional verifiers required, but none installed."); 14933 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 14934 } else { 14935 for (int i = 0; i < N; i++) { 14936 final ComponentName verifierComponent = sufficientVerifiers.get(i); 14937 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14938 verifierComponent.getPackageName(), idleDuration, 14939 verifierUser.getIdentifier(), false, "package verifier"); 14940 14941 final Intent sufficientIntent = new Intent(verification); 14942 sufficientIntent.setComponent(verifierComponent); 14943 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 14944 } 14945 } 14946 } 14947 14948 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 14949 mRequiredVerifierPackage, receivers); 14950 if (ret == PackageManager.INSTALL_SUCCEEDED 14951 && mRequiredVerifierPackage != null) { 14952 Trace.asyncTraceBegin( 14953 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 14954 /* 14955 * Send the intent to the required verification agent, 14956 * but only start the verification timeout after the 14957 * target BroadcastReceivers have run. 14958 */ 14959 verification.setComponent(requiredVerifierComponent); 14960 idleController.addPowerSaveTempWhitelistApp(Process.myUid(), 14961 mRequiredVerifierPackage, idleDuration, 14962 verifierUser.getIdentifier(), false, "package verifier"); 14963 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 14964 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 14965 new BroadcastReceiver() { 14966 @Override 14967 public void onReceive(Context context, Intent intent) { 14968 final Message msg = mHandler 14969 .obtainMessage(CHECK_PENDING_VERIFICATION); 14970 msg.arg1 = verificationId; 14971 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 14972 } 14973 }, null, 0, null, null); 14974 14975 /* 14976 * We don't want the copy to proceed until verification 14977 * succeeds. 14978 */ 14979 mVerificationCompleted = false; 14980 } 14981 } 14982 14983 if ((installFlags & PackageManager.INSTALL_ENABLE_ROLLBACK) != 0) { 14984 // TODO(ruhler) b/112431924: Don't do this in case of 'move'? 14985 final int enableRollbackToken = mPendingEnableRollbackToken++; 14986 Trace.asyncTraceBegin( 14987 TRACE_TAG_PACKAGE_MANAGER, "enable_rollback", enableRollbackToken); 14988 mPendingEnableRollback.append(enableRollbackToken, this); 14989 14990 Intent enableRollbackIntent = new Intent(Intent.ACTION_PACKAGE_ENABLE_ROLLBACK); 14991 enableRollbackIntent.putExtra( 14992 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_TOKEN, 14993 enableRollbackToken); 14994 enableRollbackIntent.putExtra( 14995 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_INSTALL_FLAGS, 14996 installFlags); 14997 enableRollbackIntent.putExtra( 14998 PackageManagerInternal.EXTRA_ENABLE_ROLLBACK_USER, 14999 getRollbackUser().getIdentifier()); 15000 enableRollbackIntent.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 15001 PACKAGE_MIME_TYPE); 15002 enableRollbackIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 15003 15004 // Allow the broadcast to be sent before boot complete. 15005 // This is needed when committing the apk part of a staged 15006 // session in early boot. The rollback manager registers 15007 // its receiver early enough during the boot process that 15008 // it will not miss the broadcast. 15009 enableRollbackIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 15010 15011 mContext.sendOrderedBroadcastAsUser(enableRollbackIntent, UserHandle.SYSTEM, 15012 android.Manifest.permission.PACKAGE_ROLLBACK_AGENT, 15013 new BroadcastReceiver() { 15014 @Override 15015 public void onReceive(Context context, Intent intent) { 15016 // the duration to wait for rollback to be enabled, in millis 15017 long rollbackTimeout = DeviceConfig.getLong( 15018 DeviceConfig.NAMESPACE_ROLLBACK, 15019 PROPERTY_ENABLE_ROLLBACK_TIMEOUT_MILLIS, 15020 DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS); 15021 if (rollbackTimeout < 0) { 15022 rollbackTimeout = DEFAULT_ENABLE_ROLLBACK_TIMEOUT_MILLIS; 15023 } 15024 final Message msg = mHandler.obtainMessage( 15025 ENABLE_ROLLBACK_TIMEOUT); 15026 msg.arg1 = enableRollbackToken; 15027 mHandler.sendMessageDelayed(msg, rollbackTimeout); 15028 } 15029 }, null, 0, null, null); 15030 15031 mEnableRollbackCompleted = false; 15032 } 15033 } 15034 15035 mRet = ret; 15036 } 15037 15038 void setReturnCode(int ret) { 15039 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 15040 // Only update mRet if it was previously INSTALL_SUCCEEDED to 15041 // ensure we do not overwrite any previous failure results. 15042 mRet = ret; 15043 } 15044 } 15045 15046 void handleVerificationFinished() { 15047 mVerificationCompleted = true; 15048 handleReturnCode(); 15049 } 15050 15051 void handleRollbackEnabled() { 15052 // TODO(ruhler) b/112431924: Consider halting the install if we 15053 // couldn't enable rollback. 15054 mEnableRollbackCompleted = true; 15055 handleReturnCode(); 15056 } 15057 15058 @Override 15059 void handleReturnCode() { 15060 if (mVerificationCompleted && mEnableRollbackCompleted) { 15061 if ((installFlags & PackageManager.INSTALL_DRY_RUN) != 0) { 15062 String packageName = ""; 15063 try { 15064 PackageLite packageInfo = 15065 new PackageParser().parsePackageLite(origin.file, 0); 15066 packageName = packageInfo.packageName; 15067 } catch (PackageParserException e) { 15068 Slog.e(TAG, "Can't parse package at " + origin.file.getAbsolutePath(), e); 15069 } 15070 try { 15071 observer.onPackageInstalled(packageName, mRet, "Dry run", new Bundle()); 15072 } catch (RemoteException e) { 15073 Slog.i(TAG, "Observer no longer exists."); 15074 } 15075 return; 15076 } 15077 if (mRet == PackageManager.INSTALL_SUCCEEDED) { 15078 mRet = mArgs.copyApk(); 15079 } 15080 processPendingInstall(mArgs, mRet); 15081 } 15082 } 15083 } 15084 15085 private InstallArgs createInstallArgs(InstallParams params) { 15086 if (params.move != null) { 15087 return new MoveInstallArgs(params); 15088 } else { 15089 return new FileInstallArgs(params); 15090 } 15091 } 15092 15093 /** 15094 * Create args that describe an existing installed package. Typically used 15095 * when cleaning up old installs, or used as a move source. 15096 */ 15097 private InstallArgs createInstallArgsForExisting(String codePath, 15098 String resourcePath, String[] instructionSets) { 15099 return new FileInstallArgs(codePath, resourcePath, instructionSets); 15100 } 15101 15102 static abstract class InstallArgs { 15103 /** @see InstallParams#origin */ 15104 final OriginInfo origin; 15105 /** @see InstallParams#move */ 15106 final MoveInfo move; 15107 15108 final IPackageInstallObserver2 observer; 15109 // Always refers to PackageManager flags only 15110 final int installFlags; 15111 final String installerPackageName; 15112 final String volumeUuid; 15113 final UserHandle user; 15114 final String abiOverride; 15115 final String[] installGrantPermissions; 15116 final List<String> whitelistedRestrictedPermissions; 15117 /** If non-null, drop an async trace when the install completes */ 15118 final String traceMethod; 15119 final int traceCookie; 15120 final PackageParser.SigningDetails signingDetails; 15121 final int installReason; 15122 @Nullable final MultiPackageInstallParams mMultiPackageInstallParams; 15123 15124 // The list of instruction sets supported by this app. This is currently 15125 // only used during the rmdex() phase to clean up resources. We can get rid of this 15126 // if we move dex files under the common app path. 15127 /* nullable */ String[] instructionSets; 15128 15129 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 15130 int installFlags, String installerPackageName, String volumeUuid, 15131 UserHandle user, String[] instructionSets, 15132 String abiOverride, String[] installGrantPermissions, 15133 List<String> whitelistedRestrictedPermissions, 15134 String traceMethod, int traceCookie, SigningDetails signingDetails, 15135 int installReason, 15136 MultiPackageInstallParams multiPackageInstallParams) { 15137 this.origin = origin; 15138 this.move = move; 15139 this.installFlags = installFlags; 15140 this.observer = observer; 15141 this.installerPackageName = installerPackageName; 15142 this.volumeUuid = volumeUuid; 15143 this.user = user; 15144 this.instructionSets = instructionSets; 15145 this.abiOverride = abiOverride; 15146 this.installGrantPermissions = installGrantPermissions; 15147 this.whitelistedRestrictedPermissions = whitelistedRestrictedPermissions; 15148 this.traceMethod = traceMethod; 15149 this.traceCookie = traceCookie; 15150 this.signingDetails = signingDetails; 15151 this.installReason = installReason; 15152 this.mMultiPackageInstallParams = multiPackageInstallParams; 15153 } 15154 15155 abstract int copyApk(); 15156 abstract int doPreInstall(int status); 15157 15158 /** 15159 * Rename package into final resting place. All paths on the given 15160 * scanned package should be updated to reflect the rename. 15161 */ 15162 abstract boolean doRename(int status, PackageParser.Package pkg); 15163 abstract int doPostInstall(int status, int uid); 15164 15165 /** @see PackageSettingBase#codePathString */ 15166 abstract String getCodePath(); 15167 /** @see PackageSettingBase#resourcePathString */ 15168 abstract String getResourcePath(); 15169 15170 // Need installer lock especially for dex file removal. 15171 abstract void cleanUpResourcesLI(); 15172 abstract boolean doPostDeleteLI(boolean delete); 15173 15174 /** 15175 * Called before the source arguments are copied. This is used mostly 15176 * for MoveParams when it needs to read the source file to put it in the 15177 * destination. 15178 */ 15179 int doPreCopy() { 15180 return PackageManager.INSTALL_SUCCEEDED; 15181 } 15182 15183 /** 15184 * Called after the source arguments are copied. This is used mostly for 15185 * MoveParams when it needs to read the source file to put it in the 15186 * destination. 15187 */ 15188 int doPostCopy(int uid) { 15189 return PackageManager.INSTALL_SUCCEEDED; 15190 } 15191 15192 protected boolean isEphemeral() { 15193 return (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15194 } 15195 15196 UserHandle getUser() { 15197 return user; 15198 } 15199 } 15200 15201 void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 15202 if (!allCodePaths.isEmpty()) { 15203 if (instructionSets == null) { 15204 throw new IllegalStateException("instructionSet == null"); 15205 } 15206 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 15207 for (String codePath : allCodePaths) { 15208 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 15209 try { 15210 mInstaller.rmdex(codePath, dexCodeInstructionSet); 15211 } catch (InstallerException ignored) { 15212 } 15213 } 15214 } 15215 } 15216 } 15217 15218 /** 15219 * Logic to handle installation of new applications, including copying 15220 * and renaming logic. 15221 */ 15222 class FileInstallArgs extends InstallArgs { 15223 private File codeFile; 15224 private File resourceFile; 15225 15226 // Example topology: 15227 // /data/app/com.example/base.apk 15228 // /data/app/com.example/split_foo.apk 15229 // /data/app/com.example/lib/arm/libfoo.so 15230 // /data/app/com.example/lib/arm64/libfoo.so 15231 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 15232 15233 /** New install */ 15234 FileInstallArgs(InstallParams params) { 15235 super(params.origin, params.move, params.observer, params.installFlags, 15236 params.installerPackageName, params.volumeUuid, 15237 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 15238 params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions, 15239 params.traceMethod, params.traceCookie, params.signingDetails, 15240 params.installReason, params.mParentInstallParams); 15241 } 15242 15243 /** Existing install */ 15244 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 15245 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 15246 null, null, null, null, 0, PackageParser.SigningDetails.UNKNOWN, 15247 PackageManager.INSTALL_REASON_UNKNOWN, null /* parent */); 15248 this.codeFile = (codePath != null) ? new File(codePath) : null; 15249 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 15250 } 15251 15252 int copyApk() { 15253 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 15254 try { 15255 return doCopyApk(); 15256 } finally { 15257 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15258 } 15259 } 15260 15261 private int doCopyApk() { 15262 if (origin.staged) { 15263 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 15264 codeFile = origin.file; 15265 resourceFile = origin.file; 15266 return PackageManager.INSTALL_SUCCEEDED; 15267 } 15268 15269 try { 15270 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_INSTANT_APP) != 0; 15271 final File tempDir = 15272 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 15273 codeFile = tempDir; 15274 resourceFile = tempDir; 15275 } catch (IOException e) { 15276 Slog.w(TAG, "Failed to create copy file: " + e); 15277 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 15278 } 15279 15280 int ret = PackageManagerServiceUtils.copyPackage( 15281 origin.file.getAbsolutePath(), codeFile); 15282 if (ret != PackageManager.INSTALL_SUCCEEDED) { 15283 Slog.e(TAG, "Failed to copy package"); 15284 return ret; 15285 } 15286 15287 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 15288 NativeLibraryHelper.Handle handle = null; 15289 try { 15290 handle = NativeLibraryHelper.Handle.create(codeFile); 15291 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 15292 abiOverride); 15293 } catch (IOException e) { 15294 Slog.e(TAG, "Copying native libraries failed", e); 15295 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15296 } finally { 15297 IoUtils.closeQuietly(handle); 15298 } 15299 15300 return ret; 15301 } 15302 15303 int doPreInstall(int status) { 15304 if (status != PackageManager.INSTALL_SUCCEEDED) { 15305 cleanUp(); 15306 } 15307 return status; 15308 } 15309 15310 boolean doRename(int status, PackageParser.Package pkg) { 15311 if (status != PackageManager.INSTALL_SUCCEEDED) { 15312 cleanUp(); 15313 return false; 15314 } 15315 15316 final File targetDir = codeFile.getParentFile(); 15317 final File beforeCodeFile = codeFile; 15318 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 15319 15320 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 15321 try { 15322 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 15323 } catch (ErrnoException e) { 15324 Slog.w(TAG, "Failed to rename", e); 15325 return false; 15326 } 15327 15328 if (!SELinux.restoreconRecursive(afterCodeFile)) { 15329 Slog.w(TAG, "Failed to restorecon"); 15330 return false; 15331 } 15332 15333 // Reflect the rename internally 15334 codeFile = afterCodeFile; 15335 resourceFile = afterCodeFile; 15336 15337 // Reflect the rename in scanned details 15338 try { 15339 pkg.setCodePath(afterCodeFile.getCanonicalPath()); 15340 } catch (IOException e) { 15341 Slog.e(TAG, "Failed to get path: " + afterCodeFile, e); 15342 return false; 15343 } 15344 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 15345 afterCodeFile, pkg.baseCodePath)); 15346 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 15347 afterCodeFile, pkg.splitCodePaths)); 15348 15349 // Reflect the rename in app info 15350 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15351 pkg.setApplicationInfoCodePath(pkg.codePath); 15352 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15353 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15354 pkg.setApplicationInfoResourcePath(pkg.codePath); 15355 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15356 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15357 15358 return true; 15359 } 15360 15361 int doPostInstall(int status, int uid) { 15362 if (status != PackageManager.INSTALL_SUCCEEDED) { 15363 cleanUp(); 15364 } 15365 return status; 15366 } 15367 15368 @Override 15369 String getCodePath() { 15370 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15371 } 15372 15373 @Override 15374 String getResourcePath() { 15375 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15376 } 15377 15378 private boolean cleanUp() { 15379 if (codeFile == null || !codeFile.exists()) { 15380 return false; 15381 } 15382 15383 removeCodePathLI(codeFile); 15384 15385 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 15386 resourceFile.delete(); 15387 } 15388 15389 return true; 15390 } 15391 15392 void cleanUpResourcesLI() { 15393 // Try enumerating all code paths before deleting 15394 List<String> allCodePaths = Collections.EMPTY_LIST; 15395 if (codeFile != null && codeFile.exists()) { 15396 try { 15397 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 15398 allCodePaths = pkg.getAllCodePaths(); 15399 } catch (PackageParserException e) { 15400 // Ignored; we tried our best 15401 } 15402 } 15403 15404 cleanUp(); 15405 removeDexFiles(allCodePaths, instructionSets); 15406 } 15407 15408 boolean doPostDeleteLI(boolean delete) { 15409 // XXX err, shouldn't we respect the delete flag? 15410 cleanUpResourcesLI(); 15411 return true; 15412 } 15413 } 15414 15415 /** 15416 * Logic to handle movement of existing installed applications. 15417 */ 15418 class MoveInstallArgs extends InstallArgs { 15419 private File codeFile; 15420 private File resourceFile; 15421 15422 /** New install */ 15423 MoveInstallArgs(InstallParams params) { 15424 super(params.origin, params.move, params.observer, params.installFlags, 15425 params.installerPackageName, params.volumeUuid, 15426 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 15427 params.grantedRuntimePermissions, params.whitelistedRestrictedPermissions, 15428 params.traceMethod, params.traceCookie, params.signingDetails, 15429 params.installReason, params.mParentInstallParams); 15430 } 15431 15432 int copyApk() { 15433 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 15434 + move.fromUuid + " to " + move.toUuid); 15435 synchronized (mInstaller) { 15436 try { 15437 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 15438 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 15439 } catch (InstallerException e) { 15440 Slog.w(TAG, "Failed to move app", e); 15441 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 15442 } 15443 } 15444 15445 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 15446 resourceFile = codeFile; 15447 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 15448 15449 return PackageManager.INSTALL_SUCCEEDED; 15450 } 15451 15452 int doPreInstall(int status) { 15453 if (status != PackageManager.INSTALL_SUCCEEDED) { 15454 cleanUp(move.toUuid); 15455 } 15456 return status; 15457 } 15458 15459 boolean doRename(int status, PackageParser.Package pkg) { 15460 if (status != PackageManager.INSTALL_SUCCEEDED) { 15461 cleanUp(move.toUuid); 15462 return false; 15463 } 15464 15465 // Reflect the move in app info 15466 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 15467 pkg.setApplicationInfoCodePath(pkg.codePath); 15468 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 15469 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 15470 pkg.setApplicationInfoResourcePath(pkg.codePath); 15471 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 15472 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 15473 15474 return true; 15475 } 15476 15477 int doPostInstall(int status, int uid) { 15478 if (status == PackageManager.INSTALL_SUCCEEDED) { 15479 cleanUp(move.fromUuid); 15480 } else { 15481 cleanUp(move.toUuid); 15482 } 15483 return status; 15484 } 15485 15486 @Override 15487 String getCodePath() { 15488 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 15489 } 15490 15491 @Override 15492 String getResourcePath() { 15493 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 15494 } 15495 15496 private boolean cleanUp(String volumeUuid) { 15497 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 15498 move.dataAppName); 15499 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 15500 final int[] userIds = sUserManager.getUserIds(); 15501 synchronized (mInstallLock) { 15502 // Clean up both app data and code 15503 // All package moves are frozen until finished 15504 15505 // We purposefully exclude FLAG_STORAGE_EXTERNAL here, since 15506 // this task was only focused on moving data on internal storage. 15507 for (int userId : userIds) { 15508 try { 15509 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 15510 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 15511 } catch (InstallerException e) { 15512 Slog.w(TAG, String.valueOf(e)); 15513 } 15514 } 15515 removeCodePathLI(codeFile); 15516 } 15517 return true; 15518 } 15519 15520 void cleanUpResourcesLI() { 15521 throw new UnsupportedOperationException(); 15522 } 15523 15524 boolean doPostDeleteLI(boolean delete) { 15525 throw new UnsupportedOperationException(); 15526 } 15527 } 15528 15529 private File getNextCodePath(File targetDir, String packageName) { 15530 File result; 15531 SecureRandom random = new SecureRandom(); 15532 byte[] bytes = new byte[16]; 15533 do { 15534 random.nextBytes(bytes); 15535 String suffix = Base64.encodeToString(bytes, Base64.URL_SAFE | Base64.NO_WRAP); 15536 result = new File(targetDir, packageName + "-" + suffix); 15537 } while (result.exists()); 15538 return result; 15539 } 15540 15541 static class PackageInstalledInfo { 15542 String name; 15543 int uid; 15544 // The set of users that originally had this package installed. 15545 int[] origUsers; 15546 // The set of users that now have this package installed. 15547 int[] newUsers; 15548 PackageParser.Package pkg; 15549 int returnCode; 15550 String returnMsg; 15551 String installerPackageName; 15552 PackageRemovedInfo removedInfo; 15553 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 15554 // The set of packages consuming this shared library or null if no consumers exist. 15555 ArrayList<PackageParser.Package> libraryConsumers; 15556 15557 public void setError(int code, String msg) { 15558 setReturnCode(code); 15559 setReturnMessage(msg); 15560 Slog.w(TAG, msg); 15561 } 15562 15563 public void setError(String msg, PackageParserException e) { 15564 setReturnCode(e.error); 15565 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15566 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15567 for (int i = 0; i < childCount; i++) { 15568 addedChildPackages.valueAt(i).setError(msg, e); 15569 } 15570 Slog.w(TAG, msg, e); 15571 } 15572 15573 public void setError(String msg, PackageManagerException e) { 15574 returnCode = e.error; 15575 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 15576 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15577 for (int i = 0; i < childCount; i++) { 15578 addedChildPackages.valueAt(i).setError(msg, e); 15579 } 15580 Slog.w(TAG, msg, e); 15581 } 15582 15583 public void setReturnCode(int returnCode) { 15584 this.returnCode = returnCode; 15585 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15586 for (int i = 0; i < childCount; i++) { 15587 addedChildPackages.valueAt(i).returnCode = returnCode; 15588 } 15589 } 15590 15591 private void setReturnMessage(String returnMsg) { 15592 this.returnMsg = returnMsg; 15593 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 15594 for (int i = 0; i < childCount; i++) { 15595 addedChildPackages.valueAt(i).returnMsg = returnMsg; 15596 } 15597 } 15598 15599 // In some error cases we want to convey more info back to the observer 15600 String origPackage; 15601 String origPermission; 15602 } 15603 15604 private static void updateDigest(MessageDigest digest, File file) throws IOException { 15605 try (DigestInputStream digestStream = 15606 new DigestInputStream(new FileInputStream(file), digest)) { 15607 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 15608 } 15609 } 15610 15611 /** 15612 * Checks whether the parent or any of the child packages have a change shared 15613 * user. For a package to be a valid update the shred users of the parent and 15614 * the children should match. We may later support changing child shared users. 15615 * @param oldPkg The updated package. 15616 * @param newPkg The update package. 15617 * @return The shared user that change between the versions. 15618 */ 15619 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 15620 PackageParser.Package newPkg) { 15621 // Check parent shared user 15622 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 15623 return newPkg.packageName; 15624 } 15625 // Check child shared users 15626 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15627 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 15628 for (int i = 0; i < newChildCount; i++) { 15629 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 15630 // If this child was present, did it have the same shared user? 15631 for (int j = 0; j < oldChildCount; j++) { 15632 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 15633 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 15634 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 15635 return newChildPkg.packageName; 15636 } 15637 } 15638 } 15639 return null; 15640 } 15641 15642 private void removeNativeBinariesLI(PackageSetting ps) { 15643 // Remove the lib path for the parent package 15644 if (ps != null) { 15645 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 15646 // Remove the lib path for the child packages 15647 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15648 for (int i = 0; i < childCount; i++) { 15649 PackageSetting childPs = null; 15650 synchronized (mPackages) { 15651 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 15652 } 15653 if (childPs != null) { 15654 NativeLibraryHelper.removeNativeBinariesLI(childPs 15655 .legacyNativeLibraryPathString); 15656 } 15657 } 15658 } 15659 } 15660 15661 @GuardedBy("mPackages") 15662 private void enableSystemPackageLPw(PackageParser.Package pkg) { 15663 // Enable the parent package 15664 mSettings.enableSystemPackageLPw(pkg.packageName); 15665 // Enable the child packages 15666 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15667 for (int i = 0; i < childCount; i++) { 15668 PackageParser.Package childPkg = pkg.childPackages.get(i); 15669 mSettings.enableSystemPackageLPw(childPkg.packageName); 15670 } 15671 } 15672 15673 @GuardedBy("mPackages") 15674 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 15675 PackageParser.Package newPkg) { 15676 // Disable the parent package (parent always replaced) 15677 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 15678 // Disable the child packages 15679 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 15680 for (int i = 0; i < childCount; i++) { 15681 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 15682 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 15683 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 15684 } 15685 return disabled; 15686 } 15687 15688 @GuardedBy("mPackages") 15689 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 15690 String installerPackageName) { 15691 // Enable the parent package 15692 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 15693 // Enable the child packages 15694 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15695 for (int i = 0; i < childCount; i++) { 15696 PackageParser.Package childPkg = pkg.childPackages.get(i); 15697 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 15698 } 15699 } 15700 15701 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 15702 int[] allUsers, PackageInstalledInfo res, UserHandle user, int installReason) { 15703 // Update the parent package setting 15704 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 15705 res, user, installReason); 15706 // Update the child packages setting 15707 final int childCount = (newPackage.childPackages != null) 15708 ? newPackage.childPackages.size() : 0; 15709 for (int i = 0; i < childCount; i++) { 15710 PackageParser.Package childPackage = newPackage.childPackages.get(i); 15711 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 15712 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 15713 childRes.origUsers, childRes, user, installReason); 15714 } 15715 } 15716 15717 private void updateSettingsInternalLI(PackageParser.Package pkg, 15718 String installerPackageName, int[] allUsers, int[] installedForUsers, 15719 PackageInstalledInfo res, UserHandle user, int installReason) { 15720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 15721 15722 final String pkgName = pkg.packageName; 15723 15724 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + pkg.codePath); 15725 synchronized (mPackages) { 15726 // NOTE: This changes slightly to include UPDATE_PERMISSIONS_ALL regardless of the size of pkg.permissions 15727 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 15728 mPermissionCallback); 15729 // For system-bundled packages, we assume that installing an upgraded version 15730 // of the package implies that the user actually wants to run that new code, 15731 // so we enable the package. 15732 PackageSetting ps = mSettings.mPackages.get(pkgName); 15733 final int userId = user.getIdentifier(); 15734 if (ps != null) { 15735 if (isSystemApp(pkg)) { 15736 if (DEBUG_INSTALL) { 15737 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 15738 } 15739 // Enable system package for requested users 15740 if (res.origUsers != null) { 15741 for (int origUserId : res.origUsers) { 15742 if (userId == UserHandle.USER_ALL || userId == origUserId) { 15743 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 15744 origUserId, installerPackageName); 15745 } 15746 } 15747 } 15748 // Also convey the prior install/uninstall state 15749 if (allUsers != null && installedForUsers != null) { 15750 for (int currentUserId : allUsers) { 15751 final boolean installed = ArrayUtils.contains( 15752 installedForUsers, currentUserId); 15753 if (DEBUG_INSTALL) { 15754 Slog.d(TAG, " user " + currentUserId + " => " + installed); 15755 } 15756 ps.setInstalled(installed, currentUserId); 15757 } 15758 // these install state changes will be persisted in the 15759 // upcoming call to mSettings.writeLPr(). 15760 } 15761 } 15762 // It's implied that when a user requests installation, they want the app to be 15763 // installed and enabled. 15764 if (userId != UserHandle.USER_ALL) { 15765 ps.setInstalled(true, userId); 15766 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 15767 } 15768 15769 // When replacing an existing package, preserve the original install reason for all 15770 // users that had the package installed before. 15771 final Set<Integer> previousUserIds = new ArraySet<>(); 15772 if (res.removedInfo != null && res.removedInfo.installReasons != null) { 15773 final int installReasonCount = res.removedInfo.installReasons.size(); 15774 for (int i = 0; i < installReasonCount; i++) { 15775 final int previousUserId = res.removedInfo.installReasons.keyAt(i); 15776 final int previousInstallReason = res.removedInfo.installReasons.valueAt(i); 15777 ps.setInstallReason(previousInstallReason, previousUserId); 15778 previousUserIds.add(previousUserId); 15779 } 15780 } 15781 15782 // Set install reason for users that are having the package newly installed. 15783 if (userId == UserHandle.USER_ALL) { 15784 for (int currentUserId : sUserManager.getUserIds()) { 15785 if (!previousUserIds.contains(currentUserId)) { 15786 ps.setInstallReason(installReason, currentUserId); 15787 } 15788 } 15789 } else if (!previousUserIds.contains(userId)) { 15790 ps.setInstallReason(installReason, userId); 15791 } 15792 mSettings.writeKernelMappingLPr(ps); 15793 } 15794 res.name = pkgName; 15795 res.uid = pkg.applicationInfo.uid; 15796 res.pkg = pkg; 15797 mSettings.setInstallerPackageName(pkgName, installerPackageName); 15798 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 15799 //to update install status 15800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 15801 mSettings.writeLPr(); 15802 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15803 } 15804 15805 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15806 } 15807 15808 private static class InstallRequest { 15809 public final InstallArgs args; 15810 public final PackageInstalledInfo installResult; 15811 15812 private InstallRequest(InstallArgs args, PackageInstalledInfo res) { 15813 this.args = args; 15814 this.installResult = res; 15815 } 15816 } 15817 15818 @GuardedBy({"mInstallLock", "mPackages"}) 15819 private void installPackagesTracedLI(List<InstallRequest> requests) { 15820 try { 15821 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackages"); 15822 installPackagesLI(requests); 15823 } finally { 15824 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15825 } 15826 } 15827 15828 /** 15829 * Package state to commit to memory and disk after reconciliation has completed. 15830 */ 15831 private static class CommitRequest { 15832 final Map<String, ReconciledPackage> reconciledPackages; 15833 final int[] mAllUsers; 15834 15835 private CommitRequest(Map<String, ReconciledPackage> reconciledPackages, int[] allUsers) { 15836 this.reconciledPackages = reconciledPackages; 15837 this.mAllUsers = allUsers; 15838 } 15839 } 15840 15841 /** 15842 * Package scan results and related request details used to reconcile the potential addition of 15843 * one or more packages to the system. 15844 * 15845 * Reconcile will take a set of package details that need to be committed to the system and make 15846 * sure that they are valid in the context of the system and the other installing apps. Any 15847 * invalid state or app will result in a failed reconciliation and thus whatever operation (such 15848 * as install) led to the request. 15849 */ 15850 private static class ReconcileRequest { 15851 public final Map<String, ScanResult> scannedPackages; 15852 15853 public final Map<String, PackageParser.Package> allPackages; 15854 public final Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource; 15855 public final Map<String, InstallArgs> installArgs; 15856 public final Map<String, PackageInstalledInfo> installResults; 15857 public final Map<String, PrepareResult> preparedPackages; 15858 public final Map<String, VersionInfo> versionInfos; 15859 public final Map<String, PackageSetting> lastStaticSharedLibSettings; 15860 15861 private ReconcileRequest(Map<String, ScanResult> scannedPackages, 15862 Map<String, InstallArgs> installArgs, 15863 Map<String, PackageInstalledInfo> installResults, 15864 Map<String, PrepareResult> preparedPackages, 15865 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource, 15866 Map<String, PackageParser.Package> allPackages, 15867 Map<String, VersionInfo> versionInfos, 15868 Map<String, PackageSetting> lastStaticSharedLibSettings) { 15869 this.scannedPackages = scannedPackages; 15870 this.installArgs = installArgs; 15871 this.installResults = installResults; 15872 this.preparedPackages = preparedPackages; 15873 this.sharedLibrarySource = sharedLibrarySource; 15874 this.allPackages = allPackages; 15875 this.versionInfos = versionInfos; 15876 this.lastStaticSharedLibSettings = lastStaticSharedLibSettings; 15877 } 15878 15879 private ReconcileRequest(Map<String, ScanResult> scannedPackages, 15880 Map<String, LongSparseArray<SharedLibraryInfo>> sharedLibrarySource, 15881 Map<String, PackageParser.Package> allPackages, 15882 Map<String, VersionInfo> versionInfos, 15883 Map<String, PackageSetting> lastStaticSharedLibSettings) { 15884 this(scannedPackages, Collections.emptyMap(), Collections.emptyMap(), 15885 Collections.emptyMap(), sharedLibrarySource, allPackages, versionInfos, 15886 lastStaticSharedLibSettings); 15887 } 15888 } 15889 private static class ReconcileFailure extends PackageManagerException { 15890 ReconcileFailure(String message) { 15891 super("Reconcile failed: " + message); 15892 } 15893 ReconcileFailure(int reason, String message) { 15894 super(reason, "Reconcile failed: " + message); 15895 } 15896 ReconcileFailure(PackageManagerException e) { 15897 this(e.error, e.getMessage()); 15898 } 15899 } 15900 15901 /** 15902 * A container of all data needed to commit a package to in-memory data structures and to disk. 15903 * TODO: move most of the data contained her into a PackageSetting for commit. 15904 */ 15905 private static class ReconciledPackage { 15906 public final ReconcileRequest request; 15907 public final PackageSetting pkgSetting; 15908 public final ScanResult scanResult; 15909 // TODO: Remove install-specific details from the reconcile result 15910 public final PackageInstalledInfo installResult; 15911 @Nullable public final PrepareResult prepareResult; 15912 @Nullable public final InstallArgs installArgs; 15913 public final DeletePackageAction deletePackageAction; 15914 public final List<SharedLibraryInfo> allowedSharedLibraryInfos; 15915 public final SigningDetails signingDetails; 15916 public final boolean sharedUserSignaturesChanged; 15917 public ArrayList<SharedLibraryInfo> collectedSharedLibraryInfos; 15918 public final boolean removeAppKeySetData; 15919 15920 private ReconciledPackage(ReconcileRequest request, 15921 InstallArgs installArgs, 15922 PackageSetting pkgSetting, 15923 PackageInstalledInfo installResult, 15924 PrepareResult prepareResult, 15925 ScanResult scanResult, 15926 DeletePackageAction deletePackageAction, 15927 List<SharedLibraryInfo> allowedSharedLibraryInfos, 15928 SigningDetails signingDetails, 15929 boolean sharedUserSignaturesChanged, 15930 boolean removeAppKeySetData) { 15931 this.request = request; 15932 this.installArgs = installArgs; 15933 this.pkgSetting = pkgSetting; 15934 this.installResult = installResult; 15935 this.prepareResult = prepareResult; 15936 this.scanResult = scanResult; 15937 this.deletePackageAction = deletePackageAction; 15938 this.allowedSharedLibraryInfos = allowedSharedLibraryInfos; 15939 this.signingDetails = signingDetails; 15940 this.sharedUserSignaturesChanged = sharedUserSignaturesChanged; 15941 this.removeAppKeySetData = removeAppKeySetData; 15942 } 15943 15944 /** 15945 * Returns a combined set of packages containing the packages already installed combined 15946 * with the package(s) currently being installed. The to-be installed packages take 15947 * precedence and may shadow already installed packages. 15948 */ 15949 private Map<String, PackageParser.Package> getCombinedPackages() { 15950 final ArrayMap<String, PackageParser.Package> combinedPackages = 15951 new ArrayMap<>(request.allPackages.size() + request.scannedPackages.size()); 15952 15953 combinedPackages.putAll(request.allPackages); 15954 for (ScanResult scanResult : request.scannedPackages.values()) { 15955 combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg); 15956 } 15957 return combinedPackages; 15958 } 15959 } 15960 15961 @GuardedBy("mPackages") 15962 private static Map<String, ReconciledPackage> reconcilePackagesLocked( 15963 final ReconcileRequest request, KeySetManagerService ksms) 15964 throws ReconcileFailure { 15965 final Map<String, ScanResult> scannedPackages = request.scannedPackages; 15966 15967 final Map<String, ReconciledPackage> result = new ArrayMap<>(scannedPackages.size()); 15968 15969 // make a copy of the existing set of packages so we can combine them with incoming packages 15970 final ArrayMap<String, PackageParser.Package> combinedPackages = 15971 new ArrayMap<>(request.allPackages.size() + scannedPackages.size()); 15972 combinedPackages.putAll(request.allPackages); 15973 15974 final Map<String, LongSparseArray<SharedLibraryInfo>> incomingSharedLibraries = 15975 new ArrayMap<>(); 15976 15977 for (String installPackageName : scannedPackages.keySet()) { 15978 final ScanResult scanResult = scannedPackages.get(installPackageName); 15979 15980 // add / replace existing with incoming packages 15981 combinedPackages.put(scanResult.pkgSetting.name, scanResult.request.pkg); 15982 15983 // in the first pass, we'll build up the set of incoming shared libraries 15984 final List<SharedLibraryInfo> allowedSharedLibInfos = 15985 getAllowedSharedLibInfos(scanResult, request.sharedLibrarySource); 15986 final SharedLibraryInfo staticLib = scanResult.staticSharedLibraryInfo; 15987 if (allowedSharedLibInfos != null) { 15988 for (SharedLibraryInfo info : allowedSharedLibInfos) { 15989 if (!addSharedLibraryToPackageVersionMap(incomingSharedLibraries, info)) { 15990 throw new ReconcileFailure("Static Shared Library " + staticLib.getName() 15991 + " is being installed twice in this set!"); 15992 } 15993 } 15994 } 15995 15996 // the following may be null if we're just reconciling on boot (and not during install) 15997 final InstallArgs installArgs = request.installArgs.get(installPackageName); 15998 final PackageInstalledInfo res = request.installResults.get(installPackageName); 15999 final PrepareResult prepareResult = request.preparedPackages.get(installPackageName); 16000 final boolean isInstall = installArgs != null; 16001 if (isInstall && (res == null || prepareResult == null)) { 16002 throw new ReconcileFailure("Reconcile arguments are not balanced for " 16003 + installPackageName + "!"); 16004 } 16005 16006 final DeletePackageAction deletePackageAction; 16007 // we only want to try to delete for non system apps 16008 if (isInstall && prepareResult.replace && !prepareResult.system) { 16009 final boolean killApp = (scanResult.request.scanFlags & SCAN_DONT_KILL_APP) == 0; 16010 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 16011 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 16012 deletePackageAction = mayDeletePackageLocked(res.removedInfo, 16013 prepareResult.originalPs, prepareResult.disabledPs, 16014 prepareResult.childPackageSettings, deleteFlags, null /* all users */); 16015 if (deletePackageAction == null) { 16016 throw new ReconcileFailure( 16017 PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE, 16018 "May not delete " + installPackageName + " to replace"); 16019 } 16020 } else { 16021 deletePackageAction = null; 16022 } 16023 16024 final int scanFlags = scanResult.request.scanFlags; 16025 final int parseFlags = scanResult.request.parseFlags; 16026 final PackageParser.Package pkg = scanResult.request.pkg; 16027 16028 final PackageSetting disabledPkgSetting = scanResult.request.disabledPkgSetting; 16029 final PackageSetting lastStaticSharedLibSetting = 16030 request.lastStaticSharedLibSettings.get(installPackageName); 16031 final PackageSetting signatureCheckPs = 16032 (prepareResult != null && lastStaticSharedLibSetting != null) 16033 ? lastStaticSharedLibSetting 16034 : scanResult.pkgSetting; 16035 boolean removeAppKeySetData = false; 16036 boolean sharedUserSignaturesChanged = false; 16037 SigningDetails signingDetails = null; 16038 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16039 if (ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16040 // We just determined the app is signed correctly, so bring 16041 // over the latest parsed certs. 16042 } else { 16043 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 16044 throw new ReconcileFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 16045 "Package " + pkg.packageName + " upgrade keys do not match the " 16046 + "previously installed version"); 16047 } else { 16048 String msg = "System package " + pkg.packageName 16049 + " signature changed; retaining data."; 16050 reportSettingsProblem(Log.WARN, msg); 16051 } 16052 } 16053 signingDetails = pkg.mSigningDetails; 16054 } else { 16055 try { 16056 final VersionInfo versionInfo = request.versionInfos.get(installPackageName); 16057 final boolean compareCompat = isCompatSignatureUpdateNeeded(versionInfo); 16058 final boolean compareRecover = isRecoverSignatureUpdateNeeded(versionInfo); 16059 final boolean compatMatch = verifySignatures(signatureCheckPs, 16060 disabledPkgSetting, pkg.mSigningDetails, compareCompat, compareRecover); 16061 // The new KeySets will be re-added later in the scanning process. 16062 if (compatMatch) { 16063 removeAppKeySetData = true; 16064 } 16065 // We just determined the app is signed correctly, so bring 16066 // over the latest parsed certs. 16067 signingDetails = pkg.mSigningDetails; 16068 16069 16070 // if this is is a sharedUser, check to see if the new package is signed by a 16071 // newer 16072 // signing certificate than the existing one, and if so, copy over the new 16073 // details 16074 if (signatureCheckPs.sharedUser != null) { 16075 if (pkg.mSigningDetails.hasAncestor( 16076 signatureCheckPs.sharedUser.signatures.mSigningDetails)) { 16077 signatureCheckPs.sharedUser.signatures.mSigningDetails = 16078 pkg.mSigningDetails; 16079 } 16080 if (signatureCheckPs.sharedUser.signaturesChanged == null) { 16081 signatureCheckPs.sharedUser.signaturesChanged = Boolean.FALSE; 16082 } 16083 } 16084 } catch (PackageManagerException e) { 16085 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 16086 throw new ReconcileFailure(e); 16087 } 16088 signingDetails = pkg.mSigningDetails; 16089 16090 // If the system app is part of a shared user we allow that shared user to 16091 // change 16092 // signatures as well as part of an OTA. We still need to verify that the 16093 // signatures 16094 // are consistent within the shared user for a given boot, so only allow 16095 // updating 16096 // the signatures on the first package scanned for the shared user (i.e. if the 16097 // signaturesChanged state hasn't been initialized yet in SharedUserSetting). 16098 if (signatureCheckPs.sharedUser != null) { 16099 final Signature[] sharedUserSignatures = 16100 signatureCheckPs.sharedUser.signatures.mSigningDetails.signatures; 16101 if (signatureCheckPs.sharedUser.signaturesChanged != null 16102 && compareSignatures(sharedUserSignatures, 16103 pkg.mSigningDetails.signatures) 16104 != PackageManager.SIGNATURE_MATCH) { 16105 if (SystemProperties.getInt("ro.product.first_api_level", 0) <= 29) { 16106 // Mismatched signatures is an error and silently skipping system 16107 // packages will likely break the device in unforeseen ways. 16108 // However, we allow the device to boot anyway because, prior to Q, 16109 // vendors were not expecting the platform to crash in this 16110 // situation. 16111 // This WILL be a hard failure on any new API levels after Q. 16112 throw new ReconcileFailure( 16113 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 16114 "Signature mismatch for shared user: " 16115 + scanResult.pkgSetting.sharedUser); 16116 } else { 16117 // Treat mismatched signatures on system packages using a shared 16118 // UID as 16119 // fatal for the system overall, rather than just failing to install 16120 // whichever package happened to be scanned later. 16121 throw new IllegalStateException( 16122 "Signature mismatch on system package " 16123 + pkg.packageName + " for shared user " 16124 + scanResult.pkgSetting.sharedUser); 16125 } 16126 } 16127 16128 sharedUserSignaturesChanged = true; 16129 signatureCheckPs.sharedUser.signatures.mSigningDetails = 16130 pkg.mSigningDetails; 16131 signatureCheckPs.sharedUser.signaturesChanged = Boolean.TRUE; 16132 } 16133 // File a report about this. 16134 String msg = "System package " + pkg.packageName 16135 + " signature changed; retaining data."; 16136 reportSettingsProblem(Log.WARN, msg); 16137 } catch (IllegalArgumentException e) { 16138 // should never happen: certs matched when checking, but not when comparing 16139 // old to new for sharedUser 16140 throw new RuntimeException( 16141 "Signing certificates comparison made on incomparable signing details" 16142 + " but somehow passed verifySignatures!", e); 16143 } 16144 } 16145 16146 result.put(installPackageName, 16147 new ReconciledPackage(request, installArgs, scanResult.pkgSetting, 16148 res, request.preparedPackages.get(installPackageName), scanResult, 16149 deletePackageAction, allowedSharedLibInfos, signingDetails, 16150 sharedUserSignaturesChanged, removeAppKeySetData)); 16151 } 16152 16153 for (String installPackageName : scannedPackages.keySet()) { 16154 // Check all shared libraries and map to their actual file path. 16155 // We only do this here for apps not on a system dir, because those 16156 // are the only ones that can fail an install due to this. We 16157 // will take care of the system apps by updating all of their 16158 // library paths after the scan is done. Also during the initial 16159 // scan don't update any libs as we do this wholesale after all 16160 // apps are scanned to avoid dependency based scanning. 16161 final ScanResult scanResult = scannedPackages.get(installPackageName); 16162 if ((scanResult.request.scanFlags & SCAN_BOOTING) != 0 16163 || (scanResult.request.parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 16164 continue; 16165 } 16166 try { 16167 result.get(installPackageName).collectedSharedLibraryInfos = 16168 collectSharedLibraryInfos(scanResult.request.pkg, combinedPackages, 16169 request.sharedLibrarySource, incomingSharedLibraries); 16170 16171 } catch (PackageManagerException e) { 16172 throw new ReconcileFailure(e.error, e.getMessage()); 16173 } 16174 } 16175 16176 return result; 16177 } 16178 16179 /** 16180 * Compare the newly scanned package with current system state to see which of its declared 16181 * shared libraries should be allowed to be added to the system. 16182 */ 16183 private static List<SharedLibraryInfo> getAllowedSharedLibInfos( 16184 ScanResult scanResult, 16185 Map<String, LongSparseArray<SharedLibraryInfo>> existingSharedLibraries) { 16186 // Let's used the parsed package as scanResult.pkgSetting may be null 16187 final PackageParser.Package pkg = scanResult.request.pkg; 16188 if (scanResult.staticSharedLibraryInfo == null 16189 && scanResult.dynamicSharedLibraryInfos == null) { 16190 return null; 16191 } 16192 16193 // Any app can add new static shared libraries 16194 if (scanResult.staticSharedLibraryInfo != null) { 16195 return Collections.singletonList(scanResult.staticSharedLibraryInfo); 16196 } 16197 final boolean hasDynamicLibraries = 16198 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 16199 && scanResult.dynamicSharedLibraryInfos != null; 16200 if (!hasDynamicLibraries) { 16201 return null; 16202 } 16203 final boolean isUpdatedSystemApp = pkg.isUpdatedSystemApp(); 16204 // We may not yet have disabled the updated package yet, so be sure to grab the 16205 // current setting if that's the case. 16206 final PackageSetting updatedSystemPs = isUpdatedSystemApp 16207 ? scanResult.request.disabledPkgSetting == null 16208 ? scanResult.request.oldPkgSetting 16209 : scanResult.request.disabledPkgSetting 16210 : null; 16211 if (isUpdatedSystemApp && (updatedSystemPs.pkg == null 16212 || updatedSystemPs.pkg.libraryNames == null)) { 16213 Slog.w(TAG, "Package " + pkg.packageName + " declares libraries that are not " 16214 + "declared on the system image; skipping"); 16215 return null; 16216 } 16217 final ArrayList<SharedLibraryInfo> infos = 16218 new ArrayList<>(scanResult.dynamicSharedLibraryInfos.size()); 16219 for (SharedLibraryInfo info : scanResult.dynamicSharedLibraryInfos) { 16220 final String name = info.getName(); 16221 if (isUpdatedSystemApp) { 16222 // New library entries can only be added through the 16223 // system image. This is important to get rid of a lot 16224 // of nasty edge cases: for example if we allowed a non- 16225 // system update of the app to add a library, then uninstalling 16226 // the update would make the library go away, and assumptions 16227 // we made such as through app install filtering would now 16228 // have allowed apps on the device which aren't compatible 16229 // with it. Better to just have the restriction here, be 16230 // conservative, and create many fewer cases that can negatively 16231 // impact the user experience. 16232 if (!updatedSystemPs.pkg.libraryNames.contains(name)) { 16233 Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name 16234 + " that is not declared on system image; skipping"); 16235 continue; 16236 } 16237 } 16238 if (sharedLibExists( 16239 name, SharedLibraryInfo.VERSION_UNDEFINED, existingSharedLibraries)) { 16240 Slog.w(TAG, "Package " + pkg.packageName + " declares library " + name 16241 + " that already exists; skipping"); 16242 continue; 16243 } 16244 infos.add(info); 16245 } 16246 return infos; 16247 } 16248 16249 /** 16250 * Returns false if the adding shared library already exists in the map and so could not be 16251 * added. 16252 */ 16253 private static boolean addSharedLibraryToPackageVersionMap( 16254 Map<String, LongSparseArray<SharedLibraryInfo>> target, 16255 SharedLibraryInfo library) { 16256 final String name = library.getName(); 16257 if (target.containsKey(name)) { 16258 if (library.getType() != SharedLibraryInfo.TYPE_STATIC) { 16259 // We've already added this non-version-specific library to the map. 16260 return false; 16261 } else if (target.get(name).indexOfKey(library.getLongVersion()) >= 0) { 16262 // We've already added this version of a version-specific library to the map. 16263 return false; 16264 } 16265 } else { 16266 target.put(name, new LongSparseArray<>()); 16267 } 16268 target.get(name).put(library.getLongVersion(), library); 16269 return true; 16270 } 16271 16272 @GuardedBy("mPackages") 16273 private void commitPackagesLocked(final CommitRequest request) { 16274 // TODO: remove any expected failures from this method; this should only be able to fail due 16275 // to unavoidable errors (I/O, etc.) 16276 for (ReconciledPackage reconciledPkg : request.reconciledPackages.values()) { 16277 final ScanResult scanResult = reconciledPkg.scanResult; 16278 final ScanRequest scanRequest = scanResult.request; 16279 final PackageParser.Package pkg = scanRequest.pkg; 16280 final String packageName = pkg.packageName; 16281 final PackageInstalledInfo res = reconciledPkg.installResult; 16282 16283 if (reconciledPkg.prepareResult.replace) { 16284 PackageParser.Package oldPackage = mPackages.get(packageName); 16285 16286 // Set the update and install times 16287 PackageSetting deletedPkgSetting = (PackageSetting) oldPackage.mExtras; 16288 setInstallAndUpdateTime(pkg, deletedPkgSetting.firstInstallTime, 16289 System.currentTimeMillis()); 16290 16291 if (reconciledPkg.prepareResult.system) { 16292 // Remove existing system package 16293 removePackageLI(oldPackage, true); 16294 if (!disableSystemPackageLPw(oldPackage, pkg)) { 16295 // We didn't need to disable the .apk as a current system package, 16296 // which means we are replacing another update that is already 16297 // installed. We need to make sure to delete the older one's .apk. 16298 res.removedInfo.args = createInstallArgsForExisting( 16299 oldPackage.applicationInfo.getCodePath(), 16300 oldPackage.applicationInfo.getResourcePath(), 16301 getAppDexInstructionSets(oldPackage.applicationInfo)); 16302 } else { 16303 res.removedInfo.args = null; 16304 } 16305 16306 // Update the package dynamic state if succeeded 16307 // Now that the install succeeded make sure we remove data 16308 // directories for any child package the update removed. 16309 final int deletedChildCount = (oldPackage.childPackages != null) 16310 ? oldPackage.childPackages.size() : 0; 16311 final int newChildCount = (pkg.childPackages != null) 16312 ? pkg.childPackages.size() : 0; 16313 for (int i = 0; i < deletedChildCount; i++) { 16314 PackageParser.Package deletedChildPkg = oldPackage.childPackages.get(i); 16315 boolean childPackageDeleted = true; 16316 for (int j = 0; j < newChildCount; j++) { 16317 PackageParser.Package newChildPkg = pkg.childPackages.get(j); 16318 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 16319 childPackageDeleted = false; 16320 break; 16321 } 16322 } 16323 if (childPackageDeleted) { 16324 PackageSetting ps1 = mSettings.getDisabledSystemPkgLPr( 16325 deletedChildPkg.packageName); 16326 if (ps1 != null && res.removedInfo.removedChildPackages != null) { 16327 PackageRemovedInfo removedChildRes = res.removedInfo 16328 .removedChildPackages.get(deletedChildPkg.packageName); 16329 removePackageDataLIF(ps1, request.mAllUsers, removedChildRes, 0, 16330 false); 16331 removedChildRes.removedForAllUsers = mPackages.get(ps1.name) 16332 == null; 16333 } 16334 } 16335 } 16336 } else { 16337 try { 16338 executeDeletePackageLIF(reconciledPkg.deletePackageAction, packageName, 16339 true, request.mAllUsers, true, pkg); 16340 } catch (SystemDeleteException e) { 16341 if (Build.IS_ENG) { 16342 throw new RuntimeException("Unexpected failure", e); 16343 // ignore; not possible for non-system app 16344 } 16345 } 16346 // Successfully deleted the old package; proceed with replace. 16347 16348 // If deleted package lived in a container, give users a chance to 16349 // relinquish resources before killing. 16350 if (oldPackage.isForwardLocked() || isExternal(oldPackage)) { 16351 if (DEBUG_INSTALL) { 16352 Slog.i(TAG, "upgrading pkg " + oldPackage 16353 + " is ASEC-hosted -> UNAVAILABLE"); 16354 } 16355 final int[] uidArray = new int[]{oldPackage.applicationInfo.uid}; 16356 final ArrayList<String> pkgList = new ArrayList<>(1); 16357 pkgList.add(oldPackage.applicationInfo.packageName); 16358 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 16359 } 16360 16361 // Update the in-memory copy of the previous code paths. 16362 PackageSetting ps1 = mSettings.mPackages.get( 16363 reconciledPkg.prepareResult.existingPackage.packageName); 16364 if ((reconciledPkg.installArgs.installFlags & PackageManager.DONT_KILL_APP) 16365 == 0) { 16366 if (ps1.mOldCodePaths == null) { 16367 ps1.mOldCodePaths = new ArraySet<>(); 16368 } 16369 Collections.addAll(ps1.mOldCodePaths, oldPackage.baseCodePath); 16370 if (oldPackage.splitCodePaths != null) { 16371 Collections.addAll(ps1.mOldCodePaths, oldPackage.splitCodePaths); 16372 } 16373 } else { 16374 ps1.mOldCodePaths = null; 16375 } 16376 if (ps1.childPackageNames != null) { 16377 for (int i = ps1.childPackageNames.size() - 1; i >= 0; --i) { 16378 final String childPkgName = ps1.childPackageNames.get(i); 16379 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 16380 childPs.mOldCodePaths = ps1.mOldCodePaths; 16381 } 16382 } 16383 16384 if (reconciledPkg.installResult.returnCode 16385 == PackageManager.INSTALL_SUCCEEDED) { 16386 PackageSetting ps2 = mSettings.getPackageLPr(pkg.packageName); 16387 if (ps2 != null) { 16388 res.removedInfo.removedForAllUsers = mPackages.get(ps2.name) == null; 16389 if (res.removedInfo.removedChildPackages != null) { 16390 final int childCount1 = res.removedInfo.removedChildPackages.size(); 16391 // Iterate in reverse as we may modify the collection 16392 for (int i = childCount1 - 1; i >= 0; i--) { 16393 String childPackageName = 16394 res.removedInfo.removedChildPackages.keyAt(i); 16395 if (res.addedChildPackages.containsKey(childPackageName)) { 16396 res.removedInfo.removedChildPackages.removeAt(i); 16397 } else { 16398 PackageRemovedInfo childInfo = res.removedInfo 16399 .removedChildPackages.valueAt(i); 16400 childInfo.removedForAllUsers = mPackages.get( 16401 childInfo.removedPackage) == null; 16402 } 16403 } 16404 } 16405 } 16406 } 16407 } 16408 } 16409 16410 commitReconciledScanResultLocked(reconciledPkg); 16411 updateSettingsLI(pkg, reconciledPkg.installArgs.installerPackageName, request.mAllUsers, 16412 res, reconciledPkg.installArgs.user, reconciledPkg.installArgs.installReason); 16413 16414 final PackageSetting ps = mSettings.mPackages.get(packageName); 16415 if (ps != null) { 16416 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 16417 ps.setUpdateAvailable(false /*updateAvailable*/); 16418 } 16419 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 16420 for (int i = 0; i < childCount; i++) { 16421 PackageParser.Package childPkg = pkg.childPackages.get(i); 16422 PackageInstalledInfo childRes = res.addedChildPackages.get( 16423 childPkg.packageName); 16424 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16425 if (childPs != null) { 16426 childRes.newUsers = childPs.queryInstalledUsers( 16427 sUserManager.getUserIds(), true); 16428 } 16429 } 16430 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16431 updateSequenceNumberLP(ps, res.newUsers); 16432 updateInstantAppInstallerLocked(packageName); 16433 } 16434 } 16435 } 16436 16437 /** 16438 * Installs one or more packages atomically. This operation is broken up into four phases: 16439 * <ul> 16440 * <li><b>Prepare</b> 16441 * <br/>Analyzes any current install state, parses the package and does initial 16442 * validation on it.</li> 16443 * <li><b>Scan</b> 16444 * <br/>Interrogates the parsed packages given the context collected in prepare.</li> 16445 * <li><b>Reconcile</b> 16446 * <br/>Validates scanned packages in the context of each other and the current system 16447 * state to ensure that the install will be successful. 16448 * <li><b>Commit</b> 16449 * <br/>Commits all scanned packages and updates system state. This is the only place 16450 * that system state may be modified in the install flow and all predictable errors 16451 * must be determined before this phase.</li> 16452 * </ul> 16453 * 16454 * Failure at any phase will result in a full failure to install all packages. 16455 */ 16456 @GuardedBy("mInstallLock") 16457 private void installPackagesLI(List<InstallRequest> requests) { 16458 final Map<String, ScanResult> preparedScans = new ArrayMap<>(requests.size()); 16459 final Map<String, InstallArgs> installArgs = new ArrayMap<>(requests.size()); 16460 final Map<String, PackageInstalledInfo> installResults = new ArrayMap<>(requests.size()); 16461 final Map<String, PrepareResult> prepareResults = new ArrayMap<>(requests.size()); 16462 final Map<String, VersionInfo> versionInfos = new ArrayMap<>(requests.size()); 16463 final Map<String, PackageSetting> lastStaticSharedLibSettings = 16464 new ArrayMap<>(requests.size()); 16465 final Map<String, Boolean> createdAppId = new ArrayMap<>(requests.size()); 16466 boolean success = false; 16467 try { 16468 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackagesLI"); 16469 for (InstallRequest request : requests) { 16470 // TODO(b/109941548): remove this once we've pulled everything from it and into 16471 // scan, reconcile or commit. 16472 final PrepareResult prepareResult; 16473 try { 16474 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "preparePackage"); 16475 prepareResult = 16476 preparePackageLI(request.args, request.installResult); 16477 } catch (PrepareFailure prepareFailure) { 16478 request.installResult.setError(prepareFailure.error, 16479 prepareFailure.getMessage()); 16480 request.installResult.origPackage = prepareFailure.conflictingPackage; 16481 request.installResult.origPermission = prepareFailure.conflictingPermission; 16482 return; 16483 } finally { 16484 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16485 } 16486 request.installResult.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16487 request.installResult.installerPackageName = request.args.installerPackageName; 16488 16489 final String packageName = prepareResult.packageToScan.packageName; 16490 prepareResults.put(packageName, prepareResult); 16491 installResults.put(packageName, request.installResult); 16492 installArgs.put(packageName, request.args); 16493 try { 16494 final List<ScanResult> scanResults = scanPackageTracedLI( 16495 prepareResult.packageToScan, prepareResult.parseFlags, 16496 prepareResult.scanFlags, System.currentTimeMillis(), 16497 request.args.user); 16498 for (ScanResult result : scanResults) { 16499 if (null != preparedScans.put(result.pkgSetting.pkg.packageName, result)) { 16500 request.installResult.setError( 16501 PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE, 16502 "Duplicate package " + result.pkgSetting.pkg.packageName 16503 + " in multi-package install request."); 16504 return; 16505 } 16506 createdAppId.put(packageName, optimisticallyRegisterAppId(result)); 16507 versionInfos.put(result.pkgSetting.pkg.packageName, 16508 getSettingsVersionForPackage(result.pkgSetting.pkg)); 16509 if (result.staticSharedLibraryInfo != null) { 16510 final PackageSetting sharedLibLatestVersionSetting = 16511 getSharedLibLatestVersionSetting(result); 16512 if (sharedLibLatestVersionSetting != null) { 16513 lastStaticSharedLibSettings.put(result.pkgSetting.pkg.packageName, 16514 sharedLibLatestVersionSetting); 16515 } 16516 } 16517 } 16518 } catch (PackageManagerException e) { 16519 request.installResult.setError("Scanning Failed.", e); 16520 return; 16521 } 16522 } 16523 ReconcileRequest reconcileRequest = new ReconcileRequest(preparedScans, installArgs, 16524 installResults, 16525 prepareResults, 16526 mSharedLibraries, 16527 Collections.unmodifiableMap(mPackages), versionInfos, 16528 lastStaticSharedLibSettings); 16529 CommitRequest commitRequest = null; 16530 synchronized (mPackages) { 16531 Map<String, ReconciledPackage> reconciledPackages; 16532 try { 16533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "reconcilePackages"); 16534 reconciledPackages = reconcilePackagesLocked( 16535 reconcileRequest, mSettings.mKeySetManagerService); 16536 } catch (ReconcileFailure e) { 16537 for (InstallRequest request : requests) { 16538 request.installResult.setError("Reconciliation failed...", e); 16539 } 16540 return; 16541 } finally { 16542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16543 } 16544 try { 16545 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "commitPackages"); 16546 commitRequest = new CommitRequest(reconciledPackages, 16547 sUserManager.getUserIds()); 16548 commitPackagesLocked(commitRequest); 16549 success = true; 16550 } finally { 16551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16552 } 16553 } 16554 executePostCommitSteps(commitRequest); 16555 } finally { 16556 if (!success) { 16557 for (ScanResult result : preparedScans.values()) { 16558 if (createdAppId.getOrDefault(result.request.pkg.packageName, false)) { 16559 cleanUpAppIdCreation(result); 16560 } 16561 } 16562 // TODO(patb): create a more descriptive reason than unknown in future release 16563 // mark all non-failure installs as UNKNOWN so we do not treat them as success 16564 for (InstallRequest request : requests) { 16565 if (request.installResult.returnCode == PackageManager.INSTALL_SUCCEEDED) { 16566 request.installResult.returnCode = PackageManager.INSTALL_UNKNOWN; 16567 } 16568 } 16569 } 16570 for (PrepareResult result : prepareResults.values()) { 16571 if (result.freezer != null) { 16572 result.freezer.close(); 16573 } 16574 } 16575 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16576 } 16577 } 16578 16579 /** 16580 * On successful install, executes remaining steps after commit completes and the package lock 16581 * is released. These are typically more expensive or require calls to installd, which often 16582 * locks on {@link #mPackages}. 16583 */ 16584 private void executePostCommitSteps(CommitRequest commitRequest) { 16585 for (ReconciledPackage reconciledPkg : commitRequest.reconciledPackages.values()) { 16586 final boolean instantApp = ((reconciledPkg.scanResult.request.scanFlags 16587 & PackageManagerService.SCAN_AS_INSTANT_APP) != 0); 16588 final PackageParser.Package pkg = reconciledPkg.pkgSetting.pkg; 16589 final String packageName = pkg.packageName; 16590 prepareAppDataAfterInstallLIF(pkg); 16591 if (reconciledPkg.prepareResult.clearCodeCache) { 16592 clearAppDataLIF(pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 16593 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16594 } 16595 if (reconciledPkg.prepareResult.replace) { 16596 mDexManager.notifyPackageUpdated(pkg.packageName, 16597 pkg.baseCodePath, pkg.splitCodePaths); 16598 } 16599 16600 // Prepare the application profiles for the new code paths. 16601 // This needs to be done before invoking dexopt so that any install-time profile 16602 // can be used for optimizations. 16603 mArtManagerService.prepareAppProfiles( 16604 pkg, 16605 resolveUserIds(reconciledPkg.installArgs.user.getIdentifier()), 16606 /* updateReferenceProfileContent= */ true); 16607 16608 // Check whether we need to dexopt the app. 16609 // 16610 // NOTE: it is IMPORTANT to call dexopt: 16611 // - after doRename which will sync the package data from PackageParser.Package and 16612 // its corresponding ApplicationInfo. 16613 // - after installNewPackageLIF or replacePackageLIF which will update result with the 16614 // uid of the application (pkg.applicationInfo.uid). 16615 // This update happens in place! 16616 // 16617 // We only need to dexopt if the package meets ALL of the following conditions: 16618 // 1) it is not an instant app or if it is then dexopt is enabled via gservices. 16619 // 2) it is not debuggable. 16620 // 16621 // Note that we do not dexopt instant apps by default. dexopt can take some time to 16622 // complete, so we skip this step during installation. Instead, we'll take extra time 16623 // the first time the instant app starts. It's preferred to do it this way to provide 16624 // continuous progress to the useur instead of mysteriously blocking somewhere in the 16625 // middle of running an instant app. The default behaviour can be overridden 16626 // via gservices. 16627 final boolean performDexopt = 16628 (!instantApp || Global.getInt(mContext.getContentResolver(), 16629 Global.INSTANT_APP_DEXOPT_ENABLED, 0) != 0) 16630 && ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_DEBUGGABLE) == 0); 16631 16632 if (performDexopt) { 16633 // Compile the layout resources. 16634 if (SystemProperties.getBoolean(PRECOMPILE_LAYOUTS, false)) { 16635 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "compileLayouts"); 16636 mViewCompiler.compileLayouts(pkg); 16637 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16638 } 16639 16640 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 16641 // Do not run PackageDexOptimizer through the local performDexOpt 16642 // method because `pkg` may not be in `mPackages` yet. 16643 // 16644 // Also, don't fail application installs if the dexopt step fails. 16645 DexoptOptions dexoptOptions = new DexoptOptions(packageName, 16646 REASON_INSTALL, 16647 DexoptOptions.DEXOPT_BOOT_COMPLETE 16648 | DexoptOptions.DEXOPT_INSTALL_WITH_DEX_METADATA_FILE); 16649 mPackageDexOptimizer.performDexOpt(pkg, 16650 null /* instructionSets */, 16651 getOrCreateCompilerPackageStats(pkg), 16652 mDexManager.getPackageUseInfoOrDefault(packageName), 16653 dexoptOptions); 16654 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16655 } 16656 16657 // Notify BackgroundDexOptService that the package has been changed. 16658 // If this is an update of a package which used to fail to compile, 16659 // BackgroundDexOptService will remove it from its blacklist. 16660 // TODO: Layering violation 16661 BackgroundDexOptService.notifyPackageChanged(packageName); 16662 } 16663 } 16664 16665 /** 16666 * The set of data needed to successfully install the prepared package. This includes data that 16667 * will be used to scan and reconcile the package. 16668 */ 16669 private static class PrepareResult { 16670 public final int installReason; 16671 public final String volumeUuid; 16672 public final String installerPackageName; 16673 public final UserHandle user; 16674 public final boolean replace; 16675 public final int scanFlags; 16676 public final int parseFlags; 16677 @Nullable /* The original Package if it is being replaced, otherwise {@code null} */ 16678 public final PackageParser.Package existingPackage; 16679 public final PackageParser.Package packageToScan; 16680 public final boolean clearCodeCache; 16681 public final boolean system; 16682 /* The original package name if it was changed during an update, otherwise {@code null}. */ 16683 @Nullable 16684 public final String renamedPackage; 16685 public final PackageFreezer freezer; 16686 public final PackageSetting originalPs; 16687 public final PackageSetting disabledPs; 16688 public final PackageSetting[] childPackageSettings; 16689 16690 private PrepareResult(int installReason, String volumeUuid, 16691 String installerPackageName, UserHandle user, boolean replace, int scanFlags, 16692 int parseFlags, PackageParser.Package existingPackage, 16693 PackageParser.Package packageToScan, boolean clearCodeCache, boolean system, 16694 String renamedPackage, PackageFreezer freezer, PackageSetting originalPs, 16695 PackageSetting disabledPs, PackageSetting[] childPackageSettings) { 16696 this.installReason = installReason; 16697 this.volumeUuid = volumeUuid; 16698 this.installerPackageName = installerPackageName; 16699 this.user = user; 16700 this.replace = replace; 16701 this.scanFlags = scanFlags; 16702 this.parseFlags = parseFlags; 16703 this.existingPackage = existingPackage; 16704 this.packageToScan = packageToScan; 16705 this.clearCodeCache = clearCodeCache; 16706 this.system = system; 16707 this.renamedPackage = renamedPackage; 16708 this.freezer = freezer; 16709 this.originalPs = originalPs; 16710 this.disabledPs = disabledPs; 16711 this.childPackageSettings = childPackageSettings; 16712 } 16713 } 16714 16715 private static class PrepareFailure extends PackageManagerException { 16716 16717 public String conflictingPackage; 16718 public String conflictingPermission; 16719 16720 PrepareFailure(int error) { 16721 super(error, "Failed to prepare for install."); 16722 } 16723 16724 PrepareFailure(int error, String detailMessage) { 16725 super(error, detailMessage); 16726 } 16727 16728 PrepareFailure(String message, Exception e) { 16729 super(e instanceof PackageParserException 16730 ? ((PackageParserException) e).error 16731 : ((PackageManagerException) e).error, 16732 ExceptionUtils.getCompleteMessage(message, e)); 16733 } 16734 16735 PrepareFailure conflictsWithExistingPermission(String conflictingPermission, 16736 String conflictingPackage) { 16737 this.conflictingPermission = conflictingPermission; 16738 this.conflictingPackage = conflictingPackage; 16739 return this; 16740 } 16741 } 16742 16743 @GuardedBy("mInstallLock") 16744 private PrepareResult preparePackageLI(InstallArgs args, PackageInstalledInfo res) 16745 throws PrepareFailure { 16746 final int installFlags = args.installFlags; 16747 final String installerPackageName = args.installerPackageName; 16748 final String volumeUuid = args.volumeUuid; 16749 final File tmpPackageFile = new File(args.getCodePath()); 16750 final boolean onExternal = args.volumeUuid != null; 16751 final boolean instantApp = ((installFlags & PackageManager.INSTALL_INSTANT_APP) != 0); 16752 final boolean fullApp = ((installFlags & PackageManager.INSTALL_FULL_APP) != 0); 16753 final boolean virtualPreload = 16754 ((installFlags & PackageManager.INSTALL_VIRTUAL_PRELOAD) != 0); 16755 @ScanFlags int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 16756 if (args.move != null) { 16757 // moving a complete application; perform an initial scan on the new install location 16758 scanFlags |= SCAN_INITIAL; 16759 } 16760 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 16761 scanFlags |= SCAN_DONT_KILL_APP; 16762 } 16763 if (instantApp) { 16764 scanFlags |= SCAN_AS_INSTANT_APP; 16765 } 16766 if (fullApp) { 16767 scanFlags |= SCAN_AS_FULL_APP; 16768 } 16769 if (virtualPreload) { 16770 scanFlags |= SCAN_AS_VIRTUAL_PRELOAD; 16771 } 16772 16773 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 16774 16775 // Sanity check 16776 if (instantApp && onExternal) { 16777 Slog.i(TAG, "Incompatible ephemeral install; external=" + onExternal); 16778 throw new PrepareFailure(PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 16779 } 16780 16781 // Retrieve PackageSettings and parse package 16782 @ParseFlags final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 16783 | PackageParser.PARSE_ENFORCE_CODE 16784 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 16785 16786 PackageParser pp = new PackageParser(); 16787 pp.setSeparateProcesses(mSeparateProcesses); 16788 pp.setDisplayMetrics(mMetrics); 16789 pp.setCallback(mPackageParserCallback); 16790 16791 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 16792 final PackageParser.Package pkg; 16793 try { 16794 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 16795 DexMetadataHelper.validatePackageDexMetadata(pkg); 16796 } catch (PackageParserException e) { 16797 throw new PrepareFailure("Failed parse during installPackageLI", e); 16798 } finally { 16799 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 16800 } 16801 16802 // Instant apps have several additional install-time checks. 16803 if (instantApp) { 16804 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.O) { 16805 Slog.w(TAG, 16806 "Instant app package " + pkg.packageName + " does not target at least O"); 16807 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 16808 "Instant app package must target at least O"); 16809 } 16810 if (pkg.mSharedUserId != null) { 16811 Slog.w(TAG, "Instant app package " + pkg.packageName 16812 + " may not declare sharedUserId."); 16813 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 16814 "Instant app package may not declare a sharedUserId"); 16815 } 16816 } 16817 16818 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16819 // Static shared libraries have synthetic package names 16820 renameStaticSharedLibraryPackage(pkg); 16821 16822 // No static shared libs on external storage 16823 if (onExternal) { 16824 Slog.i(TAG, "Static shared libs can only be installed on internal storage."); 16825 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 16826 "Packages declaring static-shared libs cannot be updated"); 16827 } 16828 } 16829 16830 // If we are installing a clustered package add results for the children 16831 if (pkg.childPackages != null) { 16832 synchronized (mPackages) { 16833 final int childCount = pkg.childPackages.size(); 16834 for (int i = 0; i < childCount; i++) { 16835 PackageParser.Package childPkg = pkg.childPackages.get(i); 16836 PackageInstalledInfo childRes = new PackageInstalledInfo(); 16837 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 16838 childRes.pkg = childPkg; 16839 childRes.name = childPkg.packageName; 16840 PackageSetting childPs = mSettings.getPackageLPr(childPkg.packageName); 16841 if (childPs != null) { 16842 childRes.origUsers = childPs.queryInstalledUsers( 16843 sUserManager.getUserIds(), true); 16844 } 16845 if ((mPackages.containsKey(childPkg.packageName))) { 16846 childRes.removedInfo = new PackageRemovedInfo(this); 16847 childRes.removedInfo.removedPackage = childPkg.packageName; 16848 childRes.removedInfo.installerPackageName = childPs.installerPackageName; 16849 } 16850 if (res.addedChildPackages == null) { 16851 res.addedChildPackages = new ArrayMap<>(); 16852 } 16853 res.addedChildPackages.put(childPkg.packageName, childRes); 16854 } 16855 } 16856 } 16857 16858 // If package doesn't declare API override, mark that we have an install 16859 // time CPU ABI override. 16860 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 16861 pkg.cpuAbiOverride = args.abiOverride; 16862 } 16863 16864 String pkgName = res.name = pkg.packageName; 16865 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_TEST_ONLY) != 0) { 16866 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 16867 throw new PrepareFailure(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 16868 } 16869 } 16870 16871 try { 16872 // either use what we've been given or parse directly from the APK 16873 if (args.signingDetails != PackageParser.SigningDetails.UNKNOWN) { 16874 pkg.setSigningDetails(args.signingDetails); 16875 } else { 16876 PackageParser.collectCertificates(pkg, false /* skipVerify */); 16877 } 16878 } catch (PackageParserException e) { 16879 throw new PrepareFailure("Failed collect during installPackageLI", e); 16880 } 16881 16882 if (instantApp && pkg.mSigningDetails.signatureSchemeVersion 16883 < SignatureSchemeVersion.SIGNING_BLOCK_V2) { 16884 Slog.w(TAG, "Instant app package " + pkg.packageName 16885 + " is not signed with at least APK Signature Scheme v2"); 16886 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 16887 "Instant app package must be signed with APK Signature Scheme v2 or greater"); 16888 } 16889 16890 // Get rid of all references to package scan path via parser. 16891 pp = null; 16892 boolean systemApp = false; 16893 boolean replace = false; 16894 synchronized (mPackages) { 16895 // Check if installing already existing package 16896 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 16897 String oldName = mSettings.getRenamedPackageLPr(pkgName); 16898 if (pkg.mOriginalPackages != null 16899 && pkg.mOriginalPackages.contains(oldName) 16900 && mPackages.containsKey(oldName)) { 16901 // This package is derived from an original package, 16902 // and this device has been updating from that original 16903 // name. We must continue using the original name, so 16904 // rename the new package here. 16905 pkg.setPackageName(oldName); 16906 pkgName = pkg.packageName; 16907 replace = true; 16908 if (DEBUG_INSTALL) { 16909 Slog.d(TAG, "Replacing existing renamed package: oldName=" 16910 + oldName + " pkgName=" + pkgName); 16911 } 16912 } else if (mPackages.containsKey(pkgName)) { 16913 // This package, under its official name, already exists 16914 // on the device; we should replace it. 16915 replace = true; 16916 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 16917 } 16918 16919 // Child packages are installed through the parent package 16920 if (pkg.parentPackage != null) { 16921 throw new PrepareFailure( 16922 PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16923 "Package " + pkg.packageName + " is child of package " 16924 + pkg.parentPackage.parentPackage + ". Child packages " 16925 + "can be updated only through the parent package."); 16926 } 16927 16928 if (replace) { 16929 // Prevent apps opting out from runtime permissions 16930 PackageParser.Package oldPackage = mPackages.get(pkgName); 16931 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 16932 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 16933 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 16934 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 16935 throw new PrepareFailure( 16936 PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 16937 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 16938 + " doesn't support runtime permissions but the old" 16939 + " target SDK " + oldTargetSdk + " does."); 16940 } 16941 // Prevent persistent apps from being updated 16942 if (((oldPackage.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0) 16943 && ((installFlags & PackageManager.INSTALL_STAGED) == 0)) { 16944 throw new PrepareFailure(PackageManager.INSTALL_FAILED_INVALID_APK, 16945 "Package " + oldPackage.packageName + " is a persistent app. " 16946 + "Persistent apps are not updateable."); 16947 } 16948 // Prevent installing of child packages 16949 if (oldPackage.parentPackage != null) { 16950 throw new PrepareFailure( 16951 PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 16952 "Package " + pkg.packageName + " is child of package " 16953 + oldPackage.parentPackage + ". Child packages " 16954 + "can be updated only through the parent package."); 16955 } 16956 } 16957 } 16958 16959 PackageSetting ps = mSettings.mPackages.get(pkgName); 16960 if (ps != null) { 16961 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 16962 16963 // Static shared libs have same package with different versions where 16964 // we internally use a synthetic package name to allow multiple versions 16965 // of the same package, therefore we need to compare signatures against 16966 // the package setting for the latest library version. 16967 PackageSetting signatureCheckPs = ps; 16968 if (pkg.applicationInfo.isStaticSharedLibrary()) { 16969 SharedLibraryInfo libraryInfo = getLatestSharedLibraVersionLPr(pkg); 16970 if (libraryInfo != null) { 16971 signatureCheckPs = mSettings.getPackageLPr(libraryInfo.getPackageName()); 16972 } 16973 } 16974 16975 // Quick sanity check that we're signed correctly if updating; 16976 // we'll check this again later when scanning, but we want to 16977 // bail early here before tripping over redefined permissions. 16978 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 16979 if (ksms.shouldCheckUpgradeKeySetLocked(signatureCheckPs, scanFlags)) { 16980 if (!ksms.checkUpgradeKeySetLocked(signatureCheckPs, pkg)) { 16981 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 16982 + pkg.packageName + " upgrade keys do not match the " 16983 + "previously installed version"); 16984 } 16985 } else { 16986 try { 16987 final boolean compareCompat = isCompatSignatureUpdateNeeded(pkg); 16988 final boolean compareRecover = isRecoverSignatureUpdateNeeded(pkg); 16989 // We don't care about disabledPkgSetting on install for now. 16990 final boolean compatMatch = verifySignatures( 16991 signatureCheckPs, null, pkg.mSigningDetails, compareCompat, 16992 compareRecover); 16993 // The new KeySets will be re-added later in the scanning process. 16994 if (compatMatch) { 16995 synchronized (mPackages) { 16996 ksms.removeAppKeySetDataLPw(pkg.packageName); 16997 } 16998 } 16999 } catch (PackageManagerException e) { 17000 throw new PrepareFailure(e.error, e.getMessage()); 17001 } 17002 } 17003 17004 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 17005 systemApp = (ps.pkg.applicationInfo.flags & 17006 ApplicationInfo.FLAG_SYSTEM) != 0; 17007 } 17008 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 17009 } 17010 17011 17012 int N = pkg.permissions.size(); 17013 for (int i = N - 1; i >= 0; i--) { 17014 final PackageParser.Permission perm = pkg.permissions.get(i); 17015 final BasePermission bp = 17016 (BasePermission) mPermissionManager.getPermissionTEMP(perm.info.name); 17017 17018 // Don't allow anyone but the system to define ephemeral permissions. 17019 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTANT) != 0 17020 && !systemApp) { 17021 Slog.w(TAG, "Non-System package " + pkg.packageName 17022 + " attempting to delcare ephemeral permission " 17023 + perm.info.name + "; Removing ephemeral."); 17024 perm.info.protectionLevel &= ~PermissionInfo.PROTECTION_FLAG_INSTANT; 17025 } 17026 17027 // Check whether the newly-scanned package wants to define an already-defined perm 17028 if (bp != null) { 17029 // If the defining package is signed with our cert, it's okay. This 17030 // also includes the "updating the same package" case, of course. 17031 // "updating same package" could also involve key-rotation. 17032 final boolean sigsOk; 17033 final String sourcePackageName = bp.getSourcePackageName(); 17034 final PackageSettingBase sourcePackageSetting = bp.getSourcePackageSetting(); 17035 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17036 if (sourcePackageName.equals(pkg.packageName) 17037 && (ksms.shouldCheckUpgradeKeySetLocked( 17038 sourcePackageSetting, scanFlags))) { 17039 sigsOk = ksms.checkUpgradeKeySetLocked(sourcePackageSetting, pkg); 17040 } else { 17041 17042 // in the event of signing certificate rotation, we need to see if the 17043 // package's certificate has rotated from the current one, or if it is an 17044 // older certificate with which the current is ok with sharing permissions 17045 if (sourcePackageSetting.signatures.mSigningDetails.checkCapability( 17046 pkg.mSigningDetails, 17047 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17048 sigsOk = true; 17049 } else if (pkg.mSigningDetails.checkCapability( 17050 sourcePackageSetting.signatures.mSigningDetails, 17051 PackageParser.SigningDetails.CertCapabilities.PERMISSION)) { 17052 17053 // the scanned package checks out, has signing certificate rotation 17054 // history, and is newer; bring it over 17055 sourcePackageSetting.signatures.mSigningDetails = pkg.mSigningDetails; 17056 sigsOk = true; 17057 } else { 17058 sigsOk = false; 17059 } 17060 } 17061 if (!sigsOk) { 17062 // If the owning package is the system itself, we log but allow 17063 // install to proceed; we fail the install on all other permission 17064 // redefinitions. 17065 if (!sourcePackageName.equals("android")) { 17066 throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 17067 + pkg.packageName 17068 + " attempting to redeclare permission " 17069 + perm.info.name + " already owned by " 17070 + sourcePackageName) 17071 .conflictsWithExistingPermission(perm.info.name, 17072 sourcePackageName); 17073 } else { 17074 Slog.w(TAG, "Package " + pkg.packageName 17075 + " attempting to redeclare system permission " 17076 + perm.info.name + "; ignoring new declaration"); 17077 pkg.permissions.remove(i); 17078 } 17079 } else if (!PLATFORM_PACKAGE_NAME.equals(pkg.packageName)) { 17080 // Prevent apps to change protection level to dangerous from any other 17081 // type as this would allow a privilege escalation where an app adds a 17082 // normal/signature permission in other app's group and later redefines 17083 // it as dangerous leading to the group auto-grant. 17084 if ((perm.info.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE) 17085 == PermissionInfo.PROTECTION_DANGEROUS) { 17086 if (bp != null && !bp.isRuntime()) { 17087 Slog.w(TAG, "Package " + pkg.packageName + " trying to change a " 17088 + "non-runtime permission " + perm.info.name 17089 + " to runtime; keeping old protection level"); 17090 perm.info.protectionLevel = bp.getProtectionLevel(); 17091 } 17092 } 17093 } 17094 } 17095 } 17096 } 17097 17098 if (systemApp) { 17099 if (onExternal) { 17100 // Abort update; system app can't be replaced with app on sdcard 17101 throw new PrepareFailure(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 17102 "Cannot install updates to system apps on sdcard"); 17103 } else if (instantApp) { 17104 // Abort update; system app can't be replaced with an instant app 17105 throw new PrepareFailure(INSTALL_FAILED_INSTANT_APP_INVALID, 17106 "Cannot update a system app with an instant app"); 17107 } 17108 } 17109 17110 if (args.move != null) { 17111 // We did an in-place move, so dex is ready to roll 17112 scanFlags |= SCAN_NO_DEX; 17113 scanFlags |= SCAN_MOVE; 17114 17115 synchronized (mPackages) { 17116 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17117 if (ps == null) { 17118 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 17119 "Missing settings for moved package " + pkgName); 17120 } 17121 17122 // We moved the entire application as-is, so bring over the 17123 // previously derived ABI information. 17124 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 17125 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 17126 } 17127 17128 } else { 17129 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 17130 scanFlags |= SCAN_NO_DEX; 17131 17132 try { 17133 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 17134 args.abiOverride : pkg.cpuAbiOverride); 17135 final boolean extractNativeLibs = !pkg.isLibrary(); 17136 final Pair<PackageAbiHelper.Abis, PackageAbiHelper.NativeLibraryPaths> 17137 derivedAbi = mInjector.getAbiHelper().derivePackageAbi( 17138 pkg, abiOverride, extractNativeLibs); 17139 derivedAbi.first.applyTo(pkg); 17140 derivedAbi.second.applyTo(pkg); 17141 } catch (PackageManagerException pme) { 17142 Slog.e(TAG, "Error deriving application ABI", pme); 17143 throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR, 17144 "Error deriving application ABI"); 17145 } 17146 } 17147 17148 if (!args.doRename(res.returnCode, pkg)) { 17149 throw new PrepareFailure(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 17150 } 17151 17152 try { 17153 setUpFsVerityIfPossible(pkg); 17154 } catch (InstallerException | IOException | DigestException | NoSuchAlgorithmException e) { 17155 throw new PrepareFailure(INSTALL_FAILED_INTERNAL_ERROR, 17156 "Failed to set up verity: " + e); 17157 } 17158 17159 if (!instantApp) { 17160 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 17161 } else { 17162 if (DEBUG_DOMAIN_VERIFICATION) { 17163 Slog.d(TAG, "Not verifying instant app install for app links: " + pkgName); 17164 } 17165 } 17166 final PackageFreezer freezer = 17167 freezePackageForInstall(pkgName, installFlags, "installPackageLI"); 17168 boolean shouldCloseFreezerBeforeReturn = true; 17169 try { 17170 final PackageParser.Package existingPackage; 17171 String renamedPackage = null; 17172 boolean sysPkg = false; 17173 String targetVolumeUuid = volumeUuid; 17174 int targetScanFlags = scanFlags; 17175 int targetParseFlags = parseFlags; 17176 final PackageSetting ps; 17177 final PackageSetting disabledPs; 17178 final PackageSetting[] childPackages; 17179 if (replace) { 17180 targetVolumeUuid = null; 17181 if (pkg.applicationInfo.isStaticSharedLibrary()) { 17182 // Static libs have a synthetic package name containing the version 17183 // and cannot be updated as an update would get a new package name, 17184 // unless this is the exact same version code which is useful for 17185 // development. 17186 PackageParser.Package existingPkg = mPackages.get(pkg.packageName); 17187 if (existingPkg != null 17188 && existingPkg.getLongVersionCode() != pkg.getLongVersionCode()) { 17189 throw new PrepareFailure(INSTALL_FAILED_DUPLICATE_PACKAGE, 17190 "Packages declaring " 17191 + "static-shared libs cannot be updated"); 17192 } 17193 } 17194 17195 final boolean isInstantApp = (scanFlags & SCAN_AS_INSTANT_APP) != 0; 17196 17197 final PackageParser.Package oldPackage; 17198 final String pkgName11 = pkg.packageName; 17199 final int[] allUsers; 17200 final int[] installedUsers; 17201 17202 synchronized (mPackages) { 17203 oldPackage = mPackages.get(pkgName11); 17204 existingPackage = oldPackage; 17205 if (DEBUG_INSTALL) { 17206 Slog.d(TAG, 17207 "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 17208 } 17209 17210 ps = mSettings.mPackages.get(pkgName11); 17211 disabledPs = mSettings.getDisabledSystemPkgLPr(ps); 17212 17213 // verify signatures are valid 17214 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 17215 if (ksms.shouldCheckUpgradeKeySetLocked(ps, scanFlags)) { 17216 if (!ksms.checkUpgradeKeySetLocked(ps, pkg)) { 17217 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17218 "New package not signed by keys specified by upgrade-keysets: " 17219 + pkgName11); 17220 } 17221 } else { 17222 // default to original signature matching 17223 if (!pkg.mSigningDetails.checkCapability(oldPackage.mSigningDetails, 17224 SigningDetails.CertCapabilities.INSTALLED_DATA) 17225 && !oldPackage.mSigningDetails.checkCapability( 17226 pkg.mSigningDetails, 17227 SigningDetails.CertCapabilities.ROLLBACK)) { 17228 throw new PrepareFailure(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 17229 "New package has a different signature: " + pkgName11); 17230 } 17231 } 17232 17233 // don't allow a system upgrade unless the upgrade hash matches 17234 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystem()) { 17235 final byte[] digestBytes; 17236 try { 17237 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 17238 updateDigest(digest, new File(pkg.baseCodePath)); 17239 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 17240 for (String path : pkg.splitCodePaths) { 17241 updateDigest(digest, new File(path)); 17242 } 17243 } 17244 digestBytes = digest.digest(); 17245 } catch (NoSuchAlgorithmException | IOException e) { 17246 throw new PrepareFailure(INSTALL_FAILED_INVALID_APK, 17247 "Could not compute hash: " + pkgName11); 17248 } 17249 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 17250 throw new PrepareFailure(INSTALL_FAILED_INVALID_APK, 17251 "New package fails restrict-update check: " + pkgName11); 17252 } 17253 // retain upgrade restriction 17254 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 17255 } 17256 17257 // Check for shared user id changes 17258 String invalidPackageName = 17259 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 17260 if (invalidPackageName != null) { 17261 throw new PrepareFailure(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 17262 "Package " + invalidPackageName + " tried to change user " 17263 + oldPackage.mSharedUserId); 17264 } 17265 17266 // In case of rollback, remember per-user/profile install state 17267 allUsers = sUserManager.getUserIds(); 17268 installedUsers = ps.queryInstalledUsers(allUsers, true); 17269 17270 17271 // don't allow an upgrade from full to ephemeral 17272 if (isInstantApp) { 17273 if (args.user == null || args.user.getIdentifier() == UserHandle.USER_ALL) { 17274 for (int currentUser : allUsers) { 17275 if (!ps.getInstantApp(currentUser)) { 17276 // can't downgrade from full to instant 17277 Slog.w(TAG, 17278 "Can't replace full app with instant app: " + pkgName11 17279 + " for user: " + currentUser); 17280 throw new PrepareFailure( 17281 PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17282 } 17283 } 17284 } else if (!ps.getInstantApp(args.user.getIdentifier())) { 17285 // can't downgrade from full to instant 17286 Slog.w(TAG, "Can't replace full app with instant app: " + pkgName11 17287 + " for user: " + args.user.getIdentifier()); 17288 throw new PrepareFailure( 17289 PackageManager.INSTALL_FAILED_INSTANT_APP_INVALID); 17290 } 17291 } 17292 } 17293 17294 // Update what is removed 17295 res.removedInfo = new PackageRemovedInfo(this); 17296 res.removedInfo.uid = oldPackage.applicationInfo.uid; 17297 res.removedInfo.removedPackage = oldPackage.packageName; 17298 res.removedInfo.installerPackageName = ps.installerPackageName; 17299 res.removedInfo.isStaticSharedLib = pkg.staticSharedLibName != null; 17300 res.removedInfo.isUpdate = true; 17301 res.removedInfo.origUsers = installedUsers; 17302 res.removedInfo.installReasons = new SparseArray<>(installedUsers.length); 17303 for (int i = 0; i < installedUsers.length; i++) { 17304 final int userId = installedUsers[i]; 17305 res.removedInfo.installReasons.put(userId, ps.getInstallReason(userId)); 17306 } 17307 17308 childPackages = mSettings.getChildSettingsLPr(ps); 17309 if (childPackages != null) { 17310 for (PackageSetting childPs : childPackages) { 17311 boolean childPackageUpdated = false; 17312 PackageParser.Package childPkg = (childPs == null) ? null : childPs.pkg; 17313 if (res.addedChildPackages != null) { 17314 PackageInstalledInfo childRes = res.addedChildPackages.get( 17315 childPkg.packageName); 17316 if (childRes != null) { 17317 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 17318 childRes.removedInfo.removedPackage = childPkg.packageName; 17319 if (childPs != null) { 17320 childRes.removedInfo.installerPackageName = 17321 childPs.installerPackageName; 17322 } 17323 childRes.removedInfo.isUpdate = true; 17324 childRes.removedInfo.installReasons = 17325 res.removedInfo.installReasons; 17326 childPackageUpdated = true; 17327 } 17328 } 17329 if (!childPackageUpdated) { 17330 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(this); 17331 childRemovedRes.removedPackage = childPkg.packageName; 17332 if (childPs != null) { 17333 childRemovedRes.installerPackageName = childPs.installerPackageName; 17334 } 17335 childRemovedRes.isUpdate = false; 17336 childRemovedRes.dataRemoved = true; 17337 synchronized (mPackages) { 17338 if (childPs != null) { 17339 childRemovedRes.origUsers = childPs.queryInstalledUsers( 17340 allUsers, 17341 true); 17342 } 17343 } 17344 if (res.removedInfo.removedChildPackages == null) { 17345 res.removedInfo.removedChildPackages = new ArrayMap<>(); 17346 } 17347 res.removedInfo.removedChildPackages.put(childPkg.packageName, 17348 childRemovedRes); 17349 } 17350 } 17351 } 17352 17353 17354 sysPkg = (isSystemApp(oldPackage)); 17355 if (sysPkg) { 17356 // Set the system/privileged/oem/vendor/product flags as needed 17357 final boolean privileged = isPrivilegedApp(oldPackage); 17358 final boolean oem = isOemApp(oldPackage); 17359 final boolean vendor = isVendorApp(oldPackage); 17360 final boolean product = isProductApp(oldPackage); 17361 final boolean odm = isOdmApp(oldPackage); 17362 final @ParseFlags int systemParseFlags = parseFlags; 17363 final @ScanFlags int systemScanFlags = scanFlags 17364 | SCAN_AS_SYSTEM 17365 | (privileged ? SCAN_AS_PRIVILEGED : 0) 17366 | (oem ? SCAN_AS_OEM : 0) 17367 | (vendor ? SCAN_AS_VENDOR : 0) 17368 | (product ? SCAN_AS_PRODUCT : 0) 17369 | (odm ? SCAN_AS_ODM : 0); 17370 17371 if (DEBUG_INSTALL) { 17372 Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 17373 + ", old=" + oldPackage); 17374 } 17375 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 17376 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 17377 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 17378 targetParseFlags = systemParseFlags; 17379 targetScanFlags = systemScanFlags; 17380 } else { // non system replace 17381 replace = true; 17382 if (DEBUG_INSTALL) { 17383 Slog.d(TAG, 17384 "replaceNonSystemPackageLI: new=" + pkg + ", old=" 17385 + oldPackage); 17386 } 17387 17388 String pkgName1 = oldPackage.packageName; 17389 boolean deletedPkg = true; 17390 boolean addedPkg = false; 17391 boolean updatedSettings = false; 17392 17393 final long origUpdateTime = (pkg.mExtras != null) 17394 ? ((PackageSetting) pkg.mExtras).lastUpdateTime : 0; 17395 17396 } 17397 } else { // new package install 17398 ps = null; 17399 childPackages = null; 17400 disabledPs = null; 17401 replace = false; 17402 existingPackage = null; 17403 // Remember this for later, in case we need to rollback this install 17404 String pkgName1 = pkg.packageName; 17405 17406 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 17407 17408 // TODO(patb): MOVE TO RECONCILE 17409 synchronized (mPackages) { 17410 renamedPackage = mSettings.getRenamedPackageLPr(pkgName1); 17411 if (renamedPackage != null) { 17412 // A package with the same name is already installed, though 17413 // it has been renamed to an older name. The package we 17414 // are trying to install should be installed as an update to 17415 // the existing one, but that has not been requested, so bail. 17416 throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS, 17417 "Attempt to re-install " + pkgName1 17418 + " without first uninstalling package running as " 17419 + renamedPackage); 17420 } 17421 if (mPackages.containsKey(pkgName1)) { 17422 // Don't allow installation over an existing package with the same name. 17423 throw new PrepareFailure(INSTALL_FAILED_ALREADY_EXISTS, 17424 "Attempt to re-install " + pkgName1 17425 + " without first uninstalling."); 17426 } 17427 } 17428 } 17429 // we're passing the freezer back to be closed in a later phase of install 17430 shouldCloseFreezerBeforeReturn = false; 17431 17432 return new PrepareResult(args.installReason, targetVolumeUuid, installerPackageName, 17433 args.user, replace, targetScanFlags, targetParseFlags, existingPackage, pkg, 17434 replace /* clearCodeCache */, sysPkg, renamedPackage, freezer, 17435 ps, disabledPs, childPackages); 17436 } finally { 17437 if (shouldCloseFreezerBeforeReturn) { 17438 freezer.close(); 17439 } 17440 } 17441 } 17442 17443 /** 17444 * Set up fs-verity for the given package if possible. This requires a feature flag of system 17445 * property to be enabled only if the kernel supports fs-verity. 17446 * 17447 * <p>When the feature flag is set to legacy mode, only APK is supported (with some experimental 17448 * kernel patches). In normal mode, all file format can be supported. 17449 */ 17450 private void setUpFsVerityIfPossible(PackageParser.Package pkg) throws InstallerException, 17451 PrepareFailure, IOException, DigestException, NoSuchAlgorithmException { 17452 final boolean standardMode = PackageManagerServiceUtils.isApkVerityEnabled(); 17453 final boolean legacyMode = PackageManagerServiceUtils.isLegacyApkVerityEnabled(); 17454 if (!standardMode && !legacyMode) { 17455 return; 17456 } 17457 17458 // Collect files we care for fs-verity setup. 17459 ArrayMap<String, String> fsverityCandidates = new ArrayMap<>(); 17460 if (legacyMode) { 17461 synchronized (mPackages) { 17462 final PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 17463 if (ps != null && ps.isPrivileged()) { 17464 fsverityCandidates.put(pkg.baseCodePath, null); 17465 if (pkg.splitCodePaths != null) { 17466 for (String splitPath : pkg.splitCodePaths) { 17467 fsverityCandidates.put(splitPath, null); 17468 } 17469 } 17470 } 17471 } 17472 } else { 17473 // NB: These files will become only accessible if the signing key is loaded in kernel's 17474 // .fs-verity keyring. 17475 fsverityCandidates.put(pkg.baseCodePath, 17476 VerityUtils.getFsveritySignatureFilePath(pkg.baseCodePath)); 17477 17478 final String dmPath = DexMetadataHelper.buildDexMetadataPathForApk(pkg.baseCodePath); 17479 if (new File(dmPath).exists()) { 17480 fsverityCandidates.put(dmPath, VerityUtils.getFsveritySignatureFilePath(dmPath)); 17481 } 17482 17483 if (pkg.splitCodePaths != null) { 17484 for (String path : pkg.splitCodePaths) { 17485 fsverityCandidates.put(path, VerityUtils.getFsveritySignatureFilePath(path)); 17486 17487 final String splitDmPath = DexMetadataHelper.buildDexMetadataPathForApk(path); 17488 if (new File(splitDmPath).exists()) { 17489 fsverityCandidates.put(splitDmPath, 17490 VerityUtils.getFsveritySignatureFilePath(splitDmPath)); 17491 } 17492 } 17493 } 17494 } 17495 17496 for (Map.Entry<String, String> entry : fsverityCandidates.entrySet()) { 17497 final String filePath = entry.getKey(); 17498 final String signaturePath = entry.getValue(); 17499 17500 if (!legacyMode) { 17501 // fs-verity is optional for now. Only set up if signature is provided. 17502 if (new File(signaturePath).exists() && !VerityUtils.hasFsverity(filePath)) { 17503 try { 17504 VerityUtils.setUpFsverity(filePath, signaturePath); 17505 } catch (IOException e) { 17506 throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE, 17507 "Failed to enable fs-verity: " + e); 17508 } 17509 } 17510 continue; 17511 } 17512 17513 // In legacy mode, fs-verity can only be enabled by process with CAP_SYS_ADMIN. 17514 final VerityUtils.SetupResult result = VerityUtils.generateApkVeritySetupData(filePath); 17515 if (result.isOk()) { 17516 if (Build.IS_DEBUGGABLE) Slog.i(TAG, "Enabling verity to " + filePath); 17517 final FileDescriptor fd = result.getUnownedFileDescriptor(); 17518 try { 17519 final byte[] rootHash = VerityUtils.generateApkVerityRootHash(filePath); 17520 try { 17521 // A file may already have fs-verity, e.g. when reused during a split 17522 // install. If the measurement succeeds, no need to attempt to set up. 17523 mInstaller.assertFsverityRootHashMatches(filePath, rootHash); 17524 } catch (InstallerException e) { 17525 mInstaller.installApkVerity(filePath, fd, result.getContentSize()); 17526 mInstaller.assertFsverityRootHashMatches(filePath, rootHash); 17527 } 17528 } finally { 17529 IoUtils.closeQuietly(fd); 17530 } 17531 } else if (result.isFailed()) { 17532 throw new PrepareFailure(PackageManager.INSTALL_FAILED_BAD_SIGNATURE, 17533 "Failed to generate verity"); 17534 } 17535 } 17536 } 17537 17538 private void startIntentFilterVerifications(int userId, boolean replacing, 17539 PackageParser.Package pkg) { 17540 if (mIntentFilterVerifierComponent == null) { 17541 Slog.w(TAG, "No IntentFilter verification will not be done as " 17542 + "there is no IntentFilterVerifier available!"); 17543 return; 17544 } 17545 17546 final int verifierUid = getPackageUid( 17547 mIntentFilterVerifierComponent.getPackageName(), 17548 MATCH_DEBUG_TRIAGED_MISSING, 17549 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 17550 17551 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17552 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 17553 mHandler.sendMessage(msg); 17554 17555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 17556 for (int i = 0; i < childCount; i++) { 17557 PackageParser.Package childPkg = pkg.childPackages.get(i); 17558 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 17559 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 17560 mHandler.sendMessage(msg); 17561 } 17562 } 17563 17564 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 17565 PackageParser.Package pkg) { 17566 int size = pkg.activities.size(); 17567 if (size == 0) { 17568 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17569 "No activity, so no need to verify any IntentFilter!"); 17570 return; 17571 } 17572 17573 final boolean hasDomainURLs = hasDomainURLs(pkg); 17574 if (!hasDomainURLs) { 17575 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17576 "No domain URLs, so no need to verify any IntentFilter!"); 17577 return; 17578 } 17579 17580 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 17581 + " if any IntentFilter from the " + size 17582 + " Activities needs verification ..."); 17583 17584 int count = 0; 17585 final String packageName = pkg.packageName; 17586 17587 synchronized (mPackages) { 17588 // If this is a new install and we see that we've already run verification for this 17589 // package, we have nothing to do: it means the state was restored from backup. 17590 if (!replacing) { 17591 IntentFilterVerificationInfo ivi = 17592 mSettings.getIntentFilterVerificationLPr(packageName); 17593 if (ivi != null) { 17594 if (DEBUG_DOMAIN_VERIFICATION) { 17595 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 17596 + ivi.getStatusString()); 17597 } 17598 return; 17599 } 17600 } 17601 17602 // If any filters need to be verified, then all need to be. 17603 boolean needToVerify = false; 17604 for (PackageParser.Activity a : pkg.activities) { 17605 for (ActivityIntentInfo filter : a.intents) { 17606 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 17607 if (DEBUG_DOMAIN_VERIFICATION) { 17608 Slog.d(TAG, 17609 "Intent filter needs verification, so processing all filters"); 17610 } 17611 needToVerify = true; 17612 break; 17613 } 17614 } 17615 } 17616 17617 if (needToVerify) { 17618 final int verificationId = mIntentFilterVerificationToken++; 17619 for (PackageParser.Activity a : pkg.activities) { 17620 for (ActivityIntentInfo filter : a.intents) { 17621 // Run verification against hosts mentioned in any web-nav intent filter, 17622 // even if the filter matches non-web schemes as well 17623 if (filter.handlesWebUris(false) && needsNetworkVerificationLPr(filter)) { 17624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 17625 "Verification needed for IntentFilter:" + filter.toString()); 17626 mIntentFilterVerifier.addOneIntentFilterVerification( 17627 verifierUid, userId, verificationId, filter, packageName); 17628 count++; 17629 } 17630 } 17631 } 17632 } 17633 } 17634 17635 if (count > 0) { 17636 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 17637 + " IntentFilter verification" + (count > 1 ? "s" : "") 17638 + " for userId:" + userId); 17639 mIntentFilterVerifier.startVerifications(userId); 17640 } else { 17641 if (DEBUG_DOMAIN_VERIFICATION) { 17642 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 17643 } 17644 } 17645 } 17646 17647 @GuardedBy("mPackages") 17648 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 17649 final ComponentName cn = filter.activity.getComponentName(); 17650 final String packageName = cn.getPackageName(); 17651 17652 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 17653 packageName); 17654 if (ivi == null) { 17655 return true; 17656 } 17657 int status = ivi.getStatus(); 17658 switch (status) { 17659 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 17660 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS: 17661 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 17662 return true; 17663 17664 default: 17665 // Nothing to do 17666 return false; 17667 } 17668 } 17669 17670 private static boolean isExternal(PackageParser.Package pkg) { 17671 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17672 } 17673 17674 private static boolean isExternal(PackageSetting ps) { 17675 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 17676 } 17677 17678 static boolean isSystemApp(PackageParser.Package pkg) { 17679 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 17680 } 17681 17682 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 17683 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 17684 } 17685 17686 private static boolean isOemApp(PackageParser.Package pkg) { 17687 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_OEM) != 0; 17688 } 17689 17690 private static boolean isVendorApp(PackageParser.Package pkg) { 17691 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_VENDOR) != 0; 17692 } 17693 17694 private static boolean isProductApp(PackageParser.Package pkg) { 17695 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRODUCT) != 0; 17696 } 17697 17698 private static boolean isSystemExtApp(PackageParser.Package pkg) { 17699 return (pkg.applicationInfo.privateFlags 17700 & ApplicationInfo.PRIVATE_FLAG_SYSTEM_EXT) != 0; 17701 } 17702 17703 private static boolean isOdmApp(PackageParser.Package pkg) { 17704 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_ODM) != 0; 17705 } 17706 17707 private static boolean hasDomainURLs(PackageParser.Package pkg) { 17708 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 17709 } 17710 17711 private static boolean isSystemApp(PackageSetting ps) { 17712 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 17713 } 17714 17715 private static boolean isUpdatedSystemApp(PackageSetting ps) { 17716 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 17717 } 17718 17719 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 17720 if (isExternal(pkg)) { 17721 if (TextUtils.isEmpty(pkg.volumeUuid)) { 17722 return mSettings.getExternalVersion(); 17723 } else { 17724 return mSettings.findOrCreateVersion(pkg.volumeUuid); 17725 } 17726 } else { 17727 return mSettings.getInternalVersion(); 17728 } 17729 } 17730 17731 private void deleteTempPackageFiles() { 17732 final FilenameFilter filter = 17733 (dir, name) -> name.startsWith("vmdl") && name.endsWith(".tmp"); 17734 } 17735 17736 @Override 17737 public void deletePackageAsUser(String packageName, int versionCode, 17738 IPackageDeleteObserver observer, int userId, int flags) { 17739 deletePackageVersioned(new VersionedPackage(packageName, versionCode), 17740 new LegacyPackageDeleteObserver(observer).getBinder(), userId, flags); 17741 } 17742 17743 @Override 17744 public void deletePackageVersioned(VersionedPackage versionedPackage, 17745 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 17746 final int callingUid = Binder.getCallingUid(); 17747 mContext.enforceCallingOrSelfPermission( 17748 android.Manifest.permission.DELETE_PACKAGES, null); 17749 final boolean canViewInstantApps = canViewInstantApps(callingUid, userId); 17750 Preconditions.checkNotNull(versionedPackage); 17751 Preconditions.checkNotNull(observer); 17752 Preconditions.checkArgumentInRange(versionedPackage.getLongVersionCode(), 17753 PackageManager.VERSION_CODE_HIGHEST, 17754 Long.MAX_VALUE, "versionCode must be >= -1"); 17755 17756 final String packageName = versionedPackage.getPackageName(); 17757 final long versionCode = versionedPackage.getLongVersionCode(); 17758 final String internalPackageName; 17759 synchronized (mPackages) { 17760 // Normalize package name to handle renamed packages and static libs 17761 internalPackageName = resolveInternalPackageNameLPr(packageName, versionCode); 17762 } 17763 17764 final int uid = Binder.getCallingUid(); 17765 if (!isOrphaned(internalPackageName) 17766 && !isCallerAllowedToSilentlyUninstall(uid, internalPackageName)) { 17767 mHandler.post(() -> { 17768 try { 17769 final Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE); 17770 intent.setData(Uri.fromParts(PACKAGE_SCHEME, packageName, null)); 17771 intent.putExtra(PackageInstaller.EXTRA_CALLBACK, observer.asBinder()); 17772 observer.onUserActionRequired(intent); 17773 } catch (RemoteException re) { 17774 } 17775 }); 17776 return; 17777 } 17778 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 17779 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{userId}; 17780 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 17781 mContext.enforceCallingOrSelfPermission( 17782 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 17783 "deletePackage for user " + userId); 17784 } 17785 17786 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 17787 mHandler.post(() -> { 17788 try { 17789 observer.onPackageDeleted(packageName, 17790 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 17791 } catch (RemoteException re) { 17792 } 17793 }); 17794 return; 17795 } 17796 17797 if (!deleteAllUsers && getBlockUninstallForUser(internalPackageName, userId)) { 17798 mHandler.post(() -> { 17799 try { 17800 observer.onPackageDeleted(packageName, 17801 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 17802 } catch (RemoteException re) { 17803 } 17804 }); 17805 return; 17806 } 17807 17808 if (DEBUG_REMOVE) { 17809 Slog.d(TAG, "deletePackageAsUser: pkg=" + internalPackageName + " user=" + userId 17810 + " deleteAllUsers: " + deleteAllUsers + " version=" 17811 + (versionCode == PackageManager.VERSION_CODE_HIGHEST 17812 ? "VERSION_CODE_HIGHEST" : versionCode)); 17813 } 17814 // Queue up an async operation since the package deletion may take a little while. 17815 mHandler.post(() -> { 17816 int returnCode; 17817 final PackageSetting ps = mSettings.mPackages.get(internalPackageName); 17818 boolean doDeletePackage = true; 17819 if (ps != null) { 17820 final boolean targetIsInstantApp = 17821 ps.getInstantApp(UserHandle.getUserId(callingUid)); 17822 doDeletePackage = !targetIsInstantApp 17823 || canViewInstantApps; 17824 } 17825 if (doDeletePackage) { 17826 if (!deleteAllUsers) { 17827 returnCode = deletePackageX(internalPackageName, versionCode, 17828 userId, deleteFlags); 17829 } else { 17830 int[] blockUninstallUserIds = getBlockUninstallForUsers( 17831 internalPackageName, users); 17832 // If nobody is blocking uninstall, proceed with delete for all users 17833 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 17834 returnCode = deletePackageX(internalPackageName, versionCode, 17835 userId, deleteFlags); 17836 } else { 17837 // Otherwise uninstall individually for users with blockUninstalls=false 17838 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 17839 for (int userId1 : users) { 17840 if (!ArrayUtils.contains(blockUninstallUserIds, userId1)) { 17841 returnCode = deletePackageX(internalPackageName, versionCode, 17842 userId1, userFlags); 17843 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 17844 Slog.w(TAG, "Package delete failed for user " + userId1 17845 + ", returnCode " + returnCode); 17846 } 17847 } 17848 } 17849 // The app has only been marked uninstalled for certain users. 17850 // We still need to report that delete was blocked 17851 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 17852 } 17853 } 17854 } else { 17855 returnCode = PackageManager.DELETE_FAILED_INTERNAL_ERROR; 17856 } 17857 try { 17858 observer.onPackageDeleted(packageName, returnCode, null); 17859 } catch (RemoteException e) { 17860 Log.i(TAG, "Observer no longer exists."); 17861 } //end catch 17862 }); 17863 } 17864 17865 private String resolveExternalPackageNameLPr(PackageParser.Package pkg) { 17866 if (pkg.staticSharedLibName != null) { 17867 return pkg.manifestPackageName; 17868 } 17869 return pkg.packageName; 17870 } 17871 17872 @GuardedBy("mPackages") 17873 private String resolveInternalPackageNameLPr(String packageName, long versionCode) { 17874 // Handle renamed packages 17875 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 17876 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 17877 17878 // Is this a static library? 17879 LongSparseArray<SharedLibraryInfo> versionedLib = 17880 mStaticLibsByDeclaringPackage.get(packageName); 17881 if (versionedLib == null || versionedLib.size() <= 0) { 17882 return packageName; 17883 } 17884 17885 // Figure out which lib versions the caller can see 17886 LongSparseLongArray versionsCallerCanSee = null; 17887 final int callingAppId = UserHandle.getAppId(Binder.getCallingUid()); 17888 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.SHELL_UID 17889 && callingAppId != Process.ROOT_UID) { 17890 versionsCallerCanSee = new LongSparseLongArray(); 17891 String libName = versionedLib.valueAt(0).getName(); 17892 String[] uidPackages = getPackagesForUid(Binder.getCallingUid()); 17893 if (uidPackages != null) { 17894 for (String uidPackage : uidPackages) { 17895 PackageSetting ps = mSettings.getPackageLPr(uidPackage); 17896 final int libIdx = ArrayUtils.indexOf(ps.usesStaticLibraries, libName); 17897 if (libIdx >= 0) { 17898 final long libVersion = ps.usesStaticLibrariesVersions[libIdx]; 17899 versionsCallerCanSee.append(libVersion, libVersion); 17900 } 17901 } 17902 } 17903 } 17904 17905 // Caller can see nothing - done 17906 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 17907 return packageName; 17908 } 17909 17910 // Find the version the caller can see and the app version code 17911 SharedLibraryInfo highestVersion = null; 17912 final int versionCount = versionedLib.size(); 17913 for (int i = 0; i < versionCount; i++) { 17914 SharedLibraryInfo libraryInfo = versionedLib.valueAt(i); 17915 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 17916 libraryInfo.getLongVersion()) < 0) { 17917 continue; 17918 } 17919 final long libVersionCode = libraryInfo.getDeclaringPackage().getLongVersionCode(); 17920 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 17921 if (libVersionCode == versionCode) { 17922 return libraryInfo.getPackageName(); 17923 } 17924 } else if (highestVersion == null) { 17925 highestVersion = libraryInfo; 17926 } else if (libVersionCode > highestVersion 17927 .getDeclaringPackage().getLongVersionCode()) { 17928 highestVersion = libraryInfo; 17929 } 17930 } 17931 17932 if (highestVersion != null) { 17933 return highestVersion.getPackageName(); 17934 } 17935 17936 return packageName; 17937 } 17938 17939 boolean isCallerVerifier(int callingUid) { 17940 final int callingUserId = UserHandle.getUserId(callingUid); 17941 return mRequiredVerifierPackage != null && 17942 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId); 17943 } 17944 17945 private boolean isCallerAllowedToSilentlyUninstall(int callingUid, String pkgName) { 17946 if (callingUid == Process.SHELL_UID || callingUid == Process.ROOT_UID 17947 || UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17948 return true; 17949 } 17950 final int callingUserId = UserHandle.getUserId(callingUid); 17951 // If the caller installed the pkgName, then allow it to silently uninstall. 17952 if (callingUid == getPackageUid(getInstallerPackageName(pkgName), 0, callingUserId)) { 17953 return true; 17954 } 17955 17956 // Allow package verifier to silently uninstall. 17957 if (mRequiredVerifierPackage != null && 17958 callingUid == getPackageUid(mRequiredVerifierPackage, 0, callingUserId)) { 17959 return true; 17960 } 17961 17962 // Allow package uninstaller to silently uninstall. 17963 if (mRequiredUninstallerPackage != null && 17964 callingUid == getPackageUid(mRequiredUninstallerPackage, 0, callingUserId)) { 17965 return true; 17966 } 17967 17968 // Allow storage manager to silently uninstall. 17969 if (mStorageManagerPackage != null && 17970 callingUid == getPackageUid(mStorageManagerPackage, 0, callingUserId)) { 17971 return true; 17972 } 17973 17974 // Allow caller having MANAGE_PROFILE_AND_DEVICE_OWNERS permission to silently 17975 // uninstall for device owner provisioning. 17976 if (checkUidPermission(MANAGE_PROFILE_AND_DEVICE_OWNERS, callingUid) 17977 == PERMISSION_GRANTED) { 17978 return true; 17979 } 17980 17981 return false; 17982 } 17983 17984 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 17985 int[] result = EMPTY_INT_ARRAY; 17986 for (int userId : userIds) { 17987 if (getBlockUninstallForUser(packageName, userId)) { 17988 result = ArrayUtils.appendInt(result, userId); 17989 } 17990 } 17991 return result; 17992 } 17993 17994 @Override 17995 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 17996 final int callingUid = Binder.getCallingUid(); 17997 if (checkUidPermission(android.Manifest.permission.MANAGE_USERS, callingUid) 17998 != PERMISSION_GRANTED) { 17999 EventLog.writeEvent(0x534e4554, "128599183", -1, ""); 18000 throw new SecurityException(android.Manifest.permission.MANAGE_USERS 18001 + " permission is required to call this API"); 18002 } 18003 if (getInstantAppPackageName(callingUid) != null 18004 && !isCallerSameApp(packageName, callingUid)) { 18005 return false; 18006 } 18007 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 18008 } 18009 18010 private boolean isPackageDeviceAdmin(String packageName, int userId) { 18011 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 18012 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 18013 try { 18014 if (dpm != null) { 18015 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 18016 /* callingUserOnly =*/ false); 18017 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 18018 : deviceOwnerComponentName.getPackageName(); 18019 // Does the package contains the device owner? 18020 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 18021 // this check is probably not needed, since DO should be registered as a device 18022 // admin on some user too. (Original bug for this: b/17657954) 18023 if (packageName.equals(deviceOwnerPackageName)) { 18024 return true; 18025 } 18026 // Does it contain a device admin for any user? 18027 int[] users; 18028 if (userId == UserHandle.USER_ALL) { 18029 users = sUserManager.getUserIds(); 18030 } else { 18031 users = new int[]{userId}; 18032 } 18033 for (int i = 0; i < users.length; ++i) { 18034 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 18035 return true; 18036 } 18037 } 18038 } 18039 } catch (RemoteException e) { 18040 } 18041 return false; 18042 } 18043 18044 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 18045 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 18046 } 18047 18048 /** 18049 * This method is an internal method that could be get invoked either 18050 * to delete an installed package or to clean up a failed installation. 18051 * After deleting an installed package, a broadcast is sent to notify any 18052 * listeners that the package has been removed. For cleaning up a failed 18053 * installation, the broadcast is not necessary since the package's 18054 * installation wouldn't have sent the initial broadcast either 18055 * The key steps in deleting a package are 18056 * deleting the package information in internal structures like mPackages, 18057 * deleting the packages base directories through installd 18058 * updating mSettings to reflect current status 18059 * persisting settings for later use 18060 * sending a broadcast if necessary 18061 */ 18062 int deletePackageX(String packageName, long versionCode, int userId, int deleteFlags) { 18063 final PackageRemovedInfo info = new PackageRemovedInfo(this); 18064 final boolean res; 18065 18066 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 18067 ? UserHandle.USER_ALL : userId; 18068 18069 if (isPackageDeviceAdmin(packageName, removeUser)) { 18070 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 18071 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 18072 } 18073 18074 final PackageSetting uninstalledPs; 18075 final PackageSetting disabledSystemPs; 18076 final PackageParser.Package pkg; 18077 18078 // for the uninstall-updates case and restricted profiles, remember the per- 18079 // user handle installed state 18080 int[] allUsers; 18081 /** enabled state of the uninstalled application */ 18082 final int origEnabledState; 18083 synchronized (mPackages) { 18084 uninstalledPs = mSettings.mPackages.get(packageName); 18085 if (uninstalledPs == null) { 18086 Slog.w(TAG, "Not removing non-existent package " + packageName); 18087 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18088 } 18089 18090 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 18091 && uninstalledPs.versionCode != versionCode) { 18092 Slog.w(TAG, "Not removing package " + packageName + " with versionCode " 18093 + uninstalledPs.versionCode + " != " + versionCode); 18094 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18095 } 18096 18097 disabledSystemPs = mSettings.getDisabledSystemPkgLPr(packageName); 18098 // Save the enabled state before we delete the package. When deleting a stub 18099 // application we always set the enabled state to 'disabled'. 18100 origEnabledState = uninstalledPs == null 18101 ? COMPONENT_ENABLED_STATE_DEFAULT : uninstalledPs.getEnabled(userId); 18102 // Static shared libs can be declared by any package, so let us not 18103 // allow removing a package if it provides a lib others depend on. 18104 pkg = mPackages.get(packageName); 18105 18106 allUsers = sUserManager.getUserIds(); 18107 18108 if (pkg != null && pkg.staticSharedLibName != null) { 18109 SharedLibraryInfo libraryInfo = getSharedLibraryInfoLPr(pkg.staticSharedLibName, 18110 pkg.staticSharedLibVersion); 18111 if (libraryInfo != null) { 18112 for (int currUserId : allUsers) { 18113 if (removeUser != UserHandle.USER_ALL && removeUser != currUserId) { 18114 continue; 18115 } 18116 List<VersionedPackage> libClientPackages = getPackagesUsingSharedLibraryLPr( 18117 libraryInfo, MATCH_KNOWN_PACKAGES, currUserId); 18118 if (!ArrayUtils.isEmpty(libClientPackages)) { 18119 Slog.w(TAG, "Not removing package " + pkg.manifestPackageName 18120 + " hosting lib " + libraryInfo.getName() + " version " 18121 + libraryInfo.getLongVersion() + " used by " + libClientPackages 18122 + " for user " + currUserId); 18123 return PackageManager.DELETE_FAILED_USED_SHARED_LIBRARY; 18124 } 18125 } 18126 } 18127 } 18128 18129 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 18130 } 18131 18132 final int freezeUser; 18133 if (isUpdatedSystemApp(uninstalledPs) 18134 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 18135 // We're downgrading a system app, which will apply to all users, so 18136 // freeze them all during the downgrade 18137 freezeUser = UserHandle.USER_ALL; 18138 } else { 18139 freezeUser = removeUser; 18140 } 18141 18142 synchronized (mInstallLock) { 18143 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 18144 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 18145 deleteFlags, "deletePackageX")) { 18146 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 18147 deleteFlags | PackageManager.DELETE_CHATTY, info, true, null); 18148 } 18149 synchronized (mPackages) { 18150 if (res) { 18151 if (pkg != null) { 18152 mInstantAppRegistry.onPackageUninstalledLPw(pkg, info.removedUsers); 18153 } 18154 updateSequenceNumberLP(uninstalledPs, info.removedUsers); 18155 updateInstantAppInstallerLocked(packageName); 18156 } 18157 } 18158 } 18159 18160 if (res) { 18161 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 18162 info.sendPackageRemovedBroadcasts(killApp); 18163 info.sendSystemPackageUpdatedBroadcasts(); 18164 info.sendSystemPackageAppearedBroadcasts(); 18165 } 18166 // Force a gc here. 18167 Runtime.getRuntime().gc(); 18168 // Delete the resources here after sending the broadcast to let 18169 // other processes clean up before deleting resources. 18170 synchronized (mInstallLock) { 18171 if (info.args != null) { 18172 info.args.doPostDeleteLI(true); 18173 } 18174 final PackageParser.Package stubPkg = 18175 (disabledSystemPs == null) ? null : disabledSystemPs.pkg; 18176 if (stubPkg != null && stubPkg.isStub) { 18177 synchronized (mPackages) { 18178 // restore the enabled state of the stub; the state is overwritten when 18179 // the stub is uninstalled 18180 final PackageSetting stubPs = mSettings.mPackages.get(stubPkg.packageName); 18181 if (stubPs != null) { 18182 stubPs.setEnabled(origEnabledState, userId, "android"); 18183 } 18184 } 18185 if (origEnabledState == COMPONENT_ENABLED_STATE_DEFAULT 18186 || origEnabledState == COMPONENT_ENABLED_STATE_ENABLED) { 18187 if (DEBUG_COMPRESSION) { 18188 Slog.i(TAG, "Enabling system stub after removal; pkg: " 18189 + stubPkg.packageName); 18190 } 18191 enableCompressedPackage(stubPkg); 18192 } 18193 } 18194 } 18195 18196 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 18197 } 18198 18199 static class PackageRemovedInfo { 18200 final PackageSender packageSender; 18201 String removedPackage; 18202 String installerPackageName; 18203 int uid = -1; 18204 int removedAppId = -1; 18205 int[] origUsers; 18206 int[] removedUsers = null; 18207 int[] broadcastUsers = null; 18208 int[] instantUserIds = null; 18209 SparseArray<Integer> installReasons; 18210 boolean isRemovedPackageSystemUpdate = false; 18211 boolean isUpdate; 18212 boolean dataRemoved; 18213 boolean removedForAllUsers; 18214 boolean isStaticSharedLib; 18215 // Clean up resources deleted packages. 18216 InstallArgs args = null; 18217 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 18218 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 18219 18220 PackageRemovedInfo(PackageSender packageSender) { 18221 this.packageSender = packageSender; 18222 } 18223 18224 void sendPackageRemovedBroadcasts(boolean killApp) { 18225 sendPackageRemovedBroadcastInternal(killApp); 18226 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 18227 for (int i = 0; i < childCount; i++) { 18228 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18229 childInfo.sendPackageRemovedBroadcastInternal(killApp); 18230 } 18231 } 18232 18233 void sendSystemPackageUpdatedBroadcasts() { 18234 if (isRemovedPackageSystemUpdate) { 18235 sendSystemPackageUpdatedBroadcastsInternal(); 18236 final int childCount = (removedChildPackages != null) 18237 ? removedChildPackages.size() : 0; 18238 for (int i = 0; i < childCount; i++) { 18239 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 18240 if (childInfo.isRemovedPackageSystemUpdate) { 18241 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 18242 } 18243 } 18244 } 18245 } 18246 18247 void sendSystemPackageAppearedBroadcasts() { 18248 final int packageCount = (appearedChildPackages != null) 18249 ? appearedChildPackages.size() : 0; 18250 for (int i = 0; i < packageCount; i++) { 18251 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 18252 packageSender.sendPackageAddedForNewUsers(installedInfo.name, 18253 true /*sendBootCompleted*/, false /*startReceiver*/, 18254 UserHandle.getAppId(installedInfo.uid), installedInfo.newUsers, null); 18255 } 18256 } 18257 18258 private void sendSystemPackageUpdatedBroadcastsInternal() { 18259 Bundle extras = new Bundle(2); 18260 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 18261 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18262 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18263 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18264 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18265 removedPackage, extras, 0, null /*targetPackage*/, null, null, null); 18266 packageSender.sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 18267 null, null, 0, removedPackage, null, null, null); 18268 if (installerPackageName != null) { 18269 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 18270 removedPackage, extras, 0 /*flags*/, 18271 installerPackageName, null, null, null); 18272 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 18273 removedPackage, extras, 0 /*flags*/, 18274 installerPackageName, null, null, null); 18275 } 18276 } 18277 18278 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 18279 // Don't send static shared library removal broadcasts as these 18280 // libs are visible only the the apps that depend on them an one 18281 // cannot remove the library if it has a dependency. 18282 if (isStaticSharedLib) { 18283 return; 18284 } 18285 Bundle extras = new Bundle(2); 18286 final int removedUid = removedAppId >= 0 ? removedAppId : uid; 18287 extras.putInt(Intent.EXTRA_UID, removedUid); 18288 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 18289 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 18290 if (isUpdate || isRemovedPackageSystemUpdate) { 18291 extras.putBoolean(Intent.EXTRA_REPLACING, true); 18292 } 18293 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 18294 if (removedPackage != null) { 18295 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18296 removedPackage, extras, 0, null /*targetPackage*/, null, 18297 broadcastUsers, instantUserIds); 18298 if (installerPackageName != null) { 18299 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, 18300 removedPackage, extras, 0 /*flags*/, 18301 installerPackageName, null, broadcastUsers, instantUserIds); 18302 } 18303 if (dataRemoved && !isRemovedPackageSystemUpdate) { 18304 packageSender.sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 18305 removedPackage, extras, 18306 Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18307 null, null, broadcastUsers, instantUserIds); 18308 packageSender.notifyPackageRemoved(removedPackage, removedUid); 18309 } 18310 } 18311 if (removedAppId >= 0) { 18312 // If a system app's updates are uninstalled the UID is not actually removed. Some 18313 // services need to know the package name affected. 18314 if (extras.getBoolean(Intent.EXTRA_REPLACING, false)) { 18315 extras.putString(Intent.EXTRA_PACKAGE_NAME, removedPackage); 18316 } 18317 18318 packageSender.sendPackageBroadcast(Intent.ACTION_UID_REMOVED, 18319 null, extras, Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND, 18320 null, null, broadcastUsers, instantUserIds); 18321 } 18322 } 18323 18324 void populateUsers(int[] userIds, PackageSetting deletedPackageSetting) { 18325 removedUsers = userIds; 18326 if (removedUsers == null) { 18327 broadcastUsers = null; 18328 return; 18329 } 18330 18331 broadcastUsers = EMPTY_INT_ARRAY; 18332 instantUserIds = EMPTY_INT_ARRAY; 18333 for (int i = userIds.length - 1; i >= 0; --i) { 18334 final int userId = userIds[i]; 18335 if (deletedPackageSetting.getInstantApp(userId)) { 18336 instantUserIds = ArrayUtils.appendInt(instantUserIds, userId); 18337 } else { 18338 broadcastUsers = ArrayUtils.appendInt(broadcastUsers, userId); 18339 } 18340 } 18341 } 18342 } 18343 18344 /* 18345 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 18346 * flag is not set, the data directory is removed as well. 18347 * make sure this flag is set for partially installed apps. If not its meaningless to 18348 * delete a partially installed application. 18349 */ 18350 private void removePackageDataLIF(final PackageSetting deletedPs, int[] allUserHandles, 18351 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 18352 String packageName = deletedPs.name; 18353 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + deletedPs); 18354 // Retrieve object to delete permissions for shared user later on 18355 final PackageParser.Package deletedPkg = deletedPs.pkg; 18356 if (outInfo != null) { 18357 outInfo.removedPackage = packageName; 18358 outInfo.installerPackageName = deletedPs.installerPackageName; 18359 outInfo.isStaticSharedLib = deletedPkg != null 18360 && deletedPkg.staticSharedLibName != null; 18361 outInfo.populateUsers(deletedPs == null ? null 18362 : deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true), deletedPs); 18363 } 18364 18365 removePackageLI(deletedPs.name, (flags & PackageManager.DELETE_CHATTY) != 0); 18366 18367 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18368 final PackageParser.Package resolvedPkg; 18369 if (deletedPkg != null) { 18370 resolvedPkg = deletedPkg; 18371 } else { 18372 // We don't have a parsed package when it lives on an ejected 18373 // adopted storage device, so fake something together 18374 resolvedPkg = new PackageParser.Package(deletedPs.name); 18375 resolvedPkg.setVolumeUuid(deletedPs.volumeUuid); 18376 } 18377 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 18378 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 18379 destroyAppProfilesLIF(resolvedPkg); 18380 if (outInfo != null) { 18381 outInfo.dataRemoved = true; 18382 } 18383 } 18384 18385 int removedAppId = -1; 18386 18387 // writer 18388 boolean installedStateChanged = false; 18389 if (deletedPs != null) { 18390 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 18391 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 18392 synchronized (mPackages) { 18393 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 18394 clearDefaultBrowserIfNeeded(packageName); 18395 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 18396 removedAppId = mSettings.removePackageLPw(packageName); 18397 if (outInfo != null) { 18398 outInfo.removedAppId = removedAppId; 18399 } 18400 mPermissionManager.updatePermissions( 18401 deletedPs.name, null, false, mPackages.values(), mPermissionCallback); 18402 if (deletedPs.sharedUser != null) { 18403 // Remove permissions associated with package. Since runtime 18404 // permissions are per user we have to kill the removed package 18405 // or packages running under the shared user of the removed 18406 // package if revoking the permissions requested only by the removed 18407 // package is successful and this causes a change in gids. 18408 boolean shouldKill = false; 18409 for (int userId : UserManagerService.getInstance().getUserIds()) { 18410 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 18411 userId); 18412 shouldKill |= userIdToKill == UserHandle.USER_ALL 18413 || userIdToKill >= UserHandle.USER_SYSTEM; 18414 } 18415 // If gids changed, kill all affected packages. 18416 if (shouldKill) { 18417 mHandler.post(() -> { 18418 // This has to happen with no lock held. 18419 killApplication(deletedPs.name, deletedPs.appId, 18420 KILL_APP_REASON_GIDS_CHANGED); 18421 }); 18422 } 18423 } 18424 clearPackagePreferredActivitiesLPw( 18425 deletedPs.name, changedUsers, UserHandle.USER_ALL); 18426 } 18427 if (changedUsers.size() > 0) { 18428 updateDefaultHomeNotLocked(changedUsers); 18429 postPreferredActivityChangedBroadcast(UserHandle.USER_ALL); 18430 } 18431 } 18432 // make sure to preserve per-user disabled state if this removal was just 18433 // a downgrade of a system app to the factory package 18434 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 18435 if (DEBUG_REMOVE) { 18436 Slog.d(TAG, "Propagating install state across downgrade"); 18437 } 18438 for (int userId : allUserHandles) { 18439 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 18440 if (DEBUG_REMOVE) { 18441 Slog.d(TAG, " user " + userId + " => " + installed); 18442 } 18443 if (installed != deletedPs.getInstalled(userId)) { 18444 installedStateChanged = true; 18445 } 18446 deletedPs.setInstalled(installed, userId); 18447 } 18448 } 18449 } 18450 synchronized (mPackages) { 18451 // can downgrade to reader 18452 if (writeSettings) { 18453 // Save settings now 18454 mSettings.writeLPr(); 18455 } 18456 if (installedStateChanged) { 18457 mSettings.writeKernelMappingLPr(deletedPs); 18458 } 18459 } 18460 if (removedAppId != -1) { 18461 // A user ID was deleted here. Go through all users and remove it 18462 // from KeyStore. 18463 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, removedAppId); 18464 } 18465 } 18466 18467 private static @Nullable SystemPartition resolveApexToSystemPartition( 18468 ApexManager.ActiveApexInfo apexInfo) { 18469 for (int i = 0, size = SYSTEM_PARTITIONS.size(); i < size; i++) { 18470 SystemPartition sp = SYSTEM_PARTITIONS.get(i); 18471 if (apexInfo.preinstalledApexPath.getAbsolutePath().startsWith( 18472 sp.folder.getAbsolutePath())) { 18473 return new SystemPartition(apexInfo.apexDirectory, sp.scanFlag, 18474 false /* hasOverlays */); 18475 } 18476 } 18477 return null; 18478 } 18479 18480 /* 18481 * Tries to delete system package. 18482 */ 18483 private void deleteSystemPackageLIF(DeletePackageAction action, PackageSetting deletedPs, 18484 int[] allUserHandles, int flags, @Nullable PackageRemovedInfo outInfo, 18485 boolean writeSettings) 18486 throws SystemDeleteException { 18487 final boolean applyUserRestrictions = 18488 (allUserHandles != null) && outInfo != null && (outInfo.origUsers != null); 18489 final PackageParser.Package deletedPkg = deletedPs.pkg; 18490 // Confirm if the system package has been updated 18491 // An updated system app can be deleted. This will also have to restore 18492 // the system pkg from system partition 18493 // reader 18494 final PackageSetting disabledPs = action.disabledPs; 18495 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 18496 + " disabledPs=" + disabledPs); 18497 Slog.d(TAG, "Deleting system pkg from data partition"); 18498 18499 if (DEBUG_REMOVE) { 18500 if (applyUserRestrictions) { 18501 Slog.d(TAG, "Remembering install states:"); 18502 for (int userId : allUserHandles) { 18503 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 18504 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 18505 } 18506 } 18507 } 18508 18509 if (outInfo != null) { 18510 // Delete the updated package 18511 outInfo.isRemovedPackageSystemUpdate = true; 18512 if (outInfo.removedChildPackages != null) { 18513 final int childCount = (deletedPs.childPackageNames != null) 18514 ? deletedPs.childPackageNames.size() : 0; 18515 for (int i = 0; i < childCount; i++) { 18516 String childPackageName = deletedPs.childPackageNames.get(i); 18517 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 18518 .contains(childPackageName)) { 18519 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18520 childPackageName); 18521 if (childInfo != null) { 18522 childInfo.isRemovedPackageSystemUpdate = true; 18523 } 18524 } 18525 } 18526 } 18527 } 18528 18529 if (disabledPs.versionCode < deletedPs.versionCode) { 18530 // Delete data for downgrades 18531 flags &= ~PackageManager.DELETE_KEEP_DATA; 18532 } else { 18533 // Preserve data by setting flag 18534 flags |= PackageManager.DELETE_KEEP_DATA; 18535 } 18536 18537 deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 18538 outInfo, writeSettings, disabledPs.pkg); 18539 18540 // writer 18541 synchronized (mPackages) { 18542 // NOTE: The system package always needs to be enabled; even if it's for 18543 // a compressed stub. If we don't, installing the system package fails 18544 // during scan [scanning checks the disabled packages]. We will reverse 18545 // this later, after we've "installed" the stub. 18546 // Reinstate the old system package 18547 enableSystemPackageLPw(disabledPs.pkg); 18548 // Remove any native libraries from the upgraded package. 18549 removeNativeBinariesLI(deletedPs); 18550 } 18551 18552 // Install the system package 18553 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 18554 try { 18555 installPackageFromSystemLIF(disabledPs.codePathString, allUserHandles, 18556 outInfo == null ? null : outInfo.origUsers, deletedPs.getPermissionsState(), 18557 writeSettings); 18558 } catch (PackageManagerException e) { 18559 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 18560 + e.getMessage()); 18561 // TODO(patb): can we avoid this; throw would come from scan... 18562 throw new SystemDeleteException(e); 18563 } finally { 18564 if (disabledPs.pkg.isStub) { 18565 // We've re-installed the stub; make sure it's disabled here. If package was 18566 // originally enabled, we'll install the compressed version of the application 18567 // and re-enable it afterward. 18568 final PackageSetting stubPs = mSettings.mPackages.get(deletedPkg.packageName); 18569 if (stubPs != null) { 18570 stubPs.setEnabled( 18571 COMPONENT_ENABLED_STATE_DISABLED, UserHandle.USER_SYSTEM, "android"); 18572 } 18573 } 18574 } 18575 } 18576 18577 /** 18578 * Installs a package that's already on the system partition. 18579 */ 18580 private PackageParser.Package installPackageFromSystemLIF(@NonNull String codePathString, 18581 @Nullable int[] allUserHandles, @Nullable int[] origUserHandles, 18582 @Nullable PermissionsState origPermissionState, boolean writeSettings) 18583 throws PackageManagerException { 18584 @ParseFlags int parseFlags = 18585 mDefParseFlags 18586 | PackageParser.PARSE_MUST_BE_APK 18587 | PackageParser.PARSE_IS_SYSTEM_DIR; 18588 @ScanFlags int scanFlags = SCAN_AS_SYSTEM; 18589 for (int i = 0, size = mDirsToScanAsSystem.size(); i < size; i++) { 18590 SystemPartition partition = mDirsToScanAsSystem.get(i); 18591 if (partition.containsPath(codePathString)) { 18592 scanFlags |= partition.scanFlag; 18593 if (partition.containsPrivPath(codePathString)) { 18594 scanFlags |= SCAN_AS_PRIVILEGED; 18595 } 18596 break; 18597 } 18598 } 18599 18600 final File codePath = new File(codePathString); 18601 final PackageParser.Package pkg = 18602 scanPackageTracedLI(codePath, parseFlags, scanFlags, 0 /*currentTime*/, null); 18603 18604 try { 18605 // update shared libraries for the newly re-installed system package 18606 updateSharedLibrariesLocked(pkg, null, Collections.unmodifiableMap(mPackages)); 18607 } catch (PackageManagerException e) { 18608 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 18609 } 18610 18611 prepareAppDataAfterInstallLIF(pkg); 18612 18613 // writer 18614 synchronized (mPackages) { 18615 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 18616 18617 // Propagate the permissions state as we do not want to drop on the floor 18618 // runtime permissions. The update permissions method below will take 18619 // care of removing obsolete permissions and grant install permissions. 18620 if (origPermissionState != null) { 18621 ps.getPermissionsState().copyFrom(origPermissionState); 18622 } 18623 mPermissionManager.updatePermissions(pkg.packageName, pkg, true, mPackages.values(), 18624 mPermissionCallback); 18625 18626 final boolean applyUserRestrictions 18627 = (allUserHandles != null) && (origUserHandles != null); 18628 if (applyUserRestrictions) { 18629 boolean installedStateChanged = false; 18630 if (DEBUG_REMOVE) { 18631 Slog.d(TAG, "Propagating install state across reinstall"); 18632 } 18633 for (int userId : allUserHandles) { 18634 final boolean installed = ArrayUtils.contains(origUserHandles, userId); 18635 if (DEBUG_REMOVE) { 18636 Slog.d(TAG, " user " + userId + " => " + installed); 18637 } 18638 if (installed != ps.getInstalled(userId)) { 18639 installedStateChanged = true; 18640 } 18641 ps.setInstalled(installed, userId); 18642 18643 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 18644 } 18645 // Regardless of writeSettings we need to ensure that this restriction 18646 // state propagation is persisted 18647 mSettings.writeAllUsersPackageRestrictionsLPr(); 18648 if (installedStateChanged) { 18649 mSettings.writeKernelMappingLPr(ps); 18650 } 18651 } 18652 // can downgrade to reader here 18653 if (writeSettings) { 18654 mSettings.writeLPr(); 18655 } 18656 } 18657 return pkg; 18658 } 18659 18660 private void deleteInstalledPackageLIF(PackageSetting ps, 18661 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 18662 PackageRemovedInfo outInfo, boolean writeSettings, 18663 PackageParser.Package replacingPackage) { 18664 synchronized (mPackages) { 18665 if (outInfo != null) { 18666 outInfo.uid = ps.appId; 18667 } 18668 18669 if (outInfo != null && outInfo.removedChildPackages != null) { 18670 final int childCount = (ps.childPackageNames != null) 18671 ? ps.childPackageNames.size() : 0; 18672 for (int i = 0; i < childCount; i++) { 18673 String childPackageName = ps.childPackageNames.get(i); 18674 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 18675 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 18676 childPackageName); 18677 if (childInfo != null) { 18678 childInfo.uid = childPs.appId; 18679 } 18680 } 18681 } 18682 } 18683 18684 // Delete package data from internal structures and also remove data if flag is set 18685 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 18686 18687 // Delete the child packages data 18688 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18689 for (int i = 0; i < childCount; i++) { 18690 PackageSetting childPs; 18691 synchronized (mPackages) { 18692 childPs = mSettings.getPackageLPr(ps.childPackageNames.get(i)); 18693 } 18694 if (childPs != null) { 18695 PackageRemovedInfo childOutInfo = (outInfo != null 18696 && outInfo.removedChildPackages != null) 18697 ? outInfo.removedChildPackages.get(childPs.name) : null; 18698 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 18699 && (replacingPackage != null 18700 && !replacingPackage.hasChildPackage(childPs.name)) 18701 ? flags & ~DELETE_KEEP_DATA : flags; 18702 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 18703 deleteFlags, writeSettings); 18704 } 18705 } 18706 18707 // Delete application code and resources only for parent packages 18708 if (ps.parentPackageName == null) { 18709 if (deleteCodeAndResources && (outInfo != null)) { 18710 outInfo.args = createInstallArgsForExisting( 18711 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 18712 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 18713 } 18714 } 18715 } 18716 18717 @Override 18718 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 18719 int userId) { 18720 mContext.enforceCallingOrSelfPermission( 18721 android.Manifest.permission.DELETE_PACKAGES, null); 18722 synchronized (mPackages) { 18723 // Cannot block uninstall of static shared libs as they are 18724 // considered a part of the using app (emulating static linking). 18725 // Also static libs are installed always on internal storage. 18726 PackageParser.Package pkg = mPackages.get(packageName); 18727 if (pkg != null && pkg.staticSharedLibName != null) { 18728 Slog.w(TAG, "Cannot block uninstall of package: " + packageName 18729 + " providing static shared library: " + pkg.staticSharedLibName); 18730 return false; 18731 } 18732 mSettings.setBlockUninstallLPw(userId, packageName, blockUninstall); 18733 mSettings.writePackageRestrictionsLPr(userId); 18734 } 18735 return true; 18736 } 18737 18738 @Override 18739 public boolean getBlockUninstallForUser(String packageName, int userId) { 18740 synchronized (mPackages) { 18741 final PackageSetting ps = mSettings.mPackages.get(packageName); 18742 if (ps == null || filterAppAccessLPr(ps, Binder.getCallingUid(), userId)) { 18743 return false; 18744 } 18745 return mSettings.getBlockUninstallLPr(userId, packageName); 18746 } 18747 } 18748 18749 @Override 18750 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 18751 enforceSystemOrRoot("setRequiredForSystemUser can only be run by the system or root"); 18752 synchronized (mPackages) { 18753 PackageSetting ps = mSettings.mPackages.get(packageName); 18754 if (ps == null) { 18755 Log.w(TAG, "Package doesn't exist: " + packageName); 18756 return false; 18757 } 18758 if (systemUserApp) { 18759 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18760 } else { 18761 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 18762 } 18763 mSettings.writeLPr(); 18764 } 18765 return true; 18766 } 18767 18768 private static class DeletePackageAction { 18769 public final PackageSetting deletingPs; 18770 public final PackageSetting disabledPs; 18771 public final PackageRemovedInfo outInfo; 18772 public final int flags; 18773 public final UserHandle user; 18774 18775 private DeletePackageAction(PackageSetting deletingPs, PackageSetting disabledPs, 18776 PackageRemovedInfo outInfo, int flags, UserHandle user) { 18777 this.deletingPs = deletingPs; 18778 this.disabledPs = disabledPs; 18779 this.outInfo = outInfo; 18780 this.flags = flags; 18781 this.user = user; 18782 } 18783 } 18784 18785 /** 18786 * @return a {@link DeletePackageAction} if the provided package and related state may be 18787 * deleted, {@code null} otherwise. 18788 */ 18789 @Nullable 18790 @GuardedBy("mPackages") 18791 private static DeletePackageAction mayDeletePackageLocked( 18792 PackageRemovedInfo outInfo, PackageSetting ps, @Nullable PackageSetting disabledPs, 18793 @Nullable PackageSetting[] children, int flags, UserHandle user) { 18794 if (ps == null) { 18795 return null; 18796 } 18797 if (isSystemApp(ps)) { 18798 if (ps.parentPackageName != null) { 18799 Slog.w(TAG, "Attempt to delete child system package " + ps.pkg.packageName); 18800 return null; 18801 } 18802 18803 final boolean deleteSystem = (flags & PackageManager.DELETE_SYSTEM_APP) != 0; 18804 final boolean deleteAllUsers = 18805 user == null || user.getIdentifier() == UserHandle.USER_ALL; 18806 if ((!deleteSystem || deleteAllUsers) && disabledPs == null) { 18807 Slog.w(TAG, "Attempt to delete unknown system package " + ps.pkg.packageName); 18808 return null; 18809 } 18810 // Confirmed if the system package has been updated 18811 // An updated system app can be deleted. This will also have to restore 18812 // the system pkg from system partition reader 18813 } 18814 final int parentReferenceCount = 18815 (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 18816 final int childCount = children != null ? children.length : 0; 18817 if (childCount != parentReferenceCount) { 18818 return null; 18819 } 18820 if (childCount != 0 && outInfo != null && outInfo.removedChildPackages != null) { 18821 for (PackageSetting child : children) { 18822 if (child == null || !ps.childPackageNames.contains(child.name)) { 18823 return null; 18824 } 18825 } 18826 } 18827 return new DeletePackageAction(ps, disabledPs, outInfo, flags, user); 18828 } 18829 18830 /* 18831 * This method handles package deletion in general 18832 */ 18833 private boolean deletePackageLIF(@NonNull String packageName, UserHandle user, 18834 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 18835 PackageRemovedInfo outInfo, boolean writeSettings, 18836 PackageParser.Package replacingPackage) { 18837 final DeletePackageAction action; 18838 synchronized (mPackages) { 18839 final PackageSetting ps = mSettings.mPackages.get(packageName); 18840 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps); 18841 PackageSetting[] children = mSettings.getChildSettingsLPr(ps); 18842 action = mayDeletePackageLocked(outInfo, ps, disabledPs, children, flags, user); 18843 } 18844 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 18845 if (null == action) { 18846 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: action was null"); 18847 return false; 18848 } 18849 18850 18851 try { 18852 executeDeletePackageLIF(action, packageName, deleteCodeAndResources, 18853 allUserHandles, writeSettings, replacingPackage); 18854 } catch (SystemDeleteException e) { 18855 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: system deletion failure", e); 18856 return false; 18857 } 18858 return true; 18859 } 18860 18861 private static class SystemDeleteException extends Exception { 18862 public final PackageManagerException reason; 18863 18864 private SystemDeleteException(PackageManagerException reason) { 18865 this.reason = reason; 18866 } 18867 } 18868 18869 /** Deletes a package. Only throws when install of a disabled package fails. */ 18870 private void executeDeletePackageLIF(DeletePackageAction action, 18871 String packageName, boolean deleteCodeAndResources, 18872 int[] allUserHandles, boolean writeSettings, 18873 PackageParser.Package replacingPackage) throws SystemDeleteException { 18874 final PackageSetting ps = action.deletingPs; 18875 final PackageRemovedInfo outInfo = action.outInfo; 18876 final UserHandle user = action.user; 18877 final int flags = action.flags; 18878 final boolean systemApp = isSystemApp(ps); 18879 18880 if (ps.parentPackageName != null 18881 && (!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 18882 if (DEBUG_REMOVE) { 18883 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 18884 + ((user == null) ? UserHandle.USER_ALL : user)); 18885 } 18886 final int removedUserId = (user != null) ? user.getIdentifier() 18887 : UserHandle.USER_ALL; 18888 18889 clearPackageStateForUserLIF(ps, removedUserId, outInfo, flags); 18890 synchronized (mPackages) { 18891 markPackageUninstalledForUserLPw(ps, user); 18892 scheduleWritePackageRestrictionsLocked(user); 18893 } 18894 return; 18895 } 18896 18897 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 18898 if (ps.getPermissionsState().hasPermission(Manifest.permission.SUSPEND_APPS, userId)) { 18899 unsuspendForSuspendingPackage(packageName, userId); 18900 } 18901 if ((!systemApp || (flags & PackageManager.DELETE_SYSTEM_APP) != 0) 18902 && userId != UserHandle.USER_ALL) { 18903 // The caller is asking that the package only be deleted for a single 18904 // user. To do this, we just mark its uninstalled state and delete 18905 // its data. If this is a system app, we only allow this to happen if 18906 // they have set the special DELETE_SYSTEM_APP which requests different 18907 // semantics than normal for uninstalling system apps. 18908 final boolean clearPackageStateAndReturn; 18909 synchronized (mPackages) { 18910 markPackageUninstalledForUserLPw(ps, user); 18911 if (!systemApp) { 18912 // Do not uninstall the APK if an app should be cached 18913 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 18914 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 18915 // Other users still have this package installed, so all 18916 // we need to do is clear this user's data and save that 18917 // it is uninstalled. 18918 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 18919 clearPackageStateAndReturn = true; 18920 } else { 18921 // We need to set it back to 'installed' so the uninstall 18922 // broadcasts will be sent correctly. 18923 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 18924 ps.setInstalled(true, userId); 18925 mSettings.writeKernelMappingLPr(ps); 18926 clearPackageStateAndReturn = false; 18927 } 18928 } else { 18929 // This is a system app, so we assume that the 18930 // other users still have this package installed, so all 18931 // we need to do is clear this user's data and save that 18932 // it is uninstalled. 18933 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 18934 clearPackageStateAndReturn = true; 18935 } 18936 } 18937 if (clearPackageStateAndReturn) { 18938 clearPackageStateForUserLIF(ps, userId, outInfo, flags); 18939 synchronized (mPackages) { 18940 scheduleWritePackageRestrictionsLocked(user); 18941 } 18942 return; 18943 } 18944 } 18945 18946 // If we are deleting a composite package for all users, keep track 18947 // of result for each child. 18948 if (ps.childPackageNames != null && outInfo != null) { 18949 synchronized (mPackages) { 18950 final int childCount = ps.childPackageNames.size(); 18951 outInfo.removedChildPackages = new ArrayMap<>(childCount); 18952 for (int i = 0; i < childCount; i++) { 18953 String childPackageName = ps.childPackageNames.get(i); 18954 PackageRemovedInfo childInfo = new PackageRemovedInfo(this); 18955 childInfo.removedPackage = childPackageName; 18956 childInfo.installerPackageName = ps.installerPackageName; 18957 outInfo.removedChildPackages.put(childPackageName, childInfo); 18958 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 18959 if (childPs != null) { 18960 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 18961 } 18962 } 18963 } 18964 } 18965 18966 // TODO(b/109941548): break reasons for ret = false out into mayDelete method 18967 if (systemApp) { 18968 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 18969 // When an updated system application is deleted we delete the existing resources 18970 // as well and fall back to existing code in system partition 18971 deleteSystemPackageLIF(action, ps, allUserHandles, flags, outInfo, writeSettings); 18972 } else { 18973 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 18974 deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 18975 outInfo, writeSettings, replacingPackage); 18976 } 18977 18978 // Take a note whether we deleted the package for all users 18979 if (outInfo != null) { 18980 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 18981 if (outInfo.removedChildPackages != null) { 18982 synchronized (mPackages) { 18983 final int childCount = outInfo.removedChildPackages.size(); 18984 for (int i = 0; i < childCount; i++) { 18985 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 18986 if (childInfo != null) { 18987 childInfo.removedForAllUsers = mPackages.get( 18988 childInfo.removedPackage) == null; 18989 } 18990 } 18991 } 18992 } 18993 // If we uninstalled an update to a system app there may be some 18994 // child packages that appeared as they are declared in the system 18995 // app but were not declared in the update. 18996 if (systemApp) { 18997 synchronized (mPackages) { 18998 PackageSetting updatedPs = mSettings.getPackageLPr(ps.name); 18999 final int childCount = (updatedPs.childPackageNames != null) 19000 ? updatedPs.childPackageNames.size() : 0; 19001 for (int i = 0; i < childCount; i++) { 19002 String childPackageName = updatedPs.childPackageNames.get(i); 19003 if (outInfo.removedChildPackages == null 19004 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 19005 PackageSetting childPs = mSettings.getPackageLPr(childPackageName); 19006 if (childPs == null) { 19007 continue; 19008 } 19009 PackageInstalledInfo installRes = new PackageInstalledInfo(); 19010 installRes.name = childPackageName; 19011 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 19012 installRes.pkg = mPackages.get(childPackageName); 19013 installRes.uid = childPs.pkg.applicationInfo.uid; 19014 if (outInfo.appearedChildPackages == null) { 19015 outInfo.appearedChildPackages = new ArrayMap<>(); 19016 } 19017 outInfo.appearedChildPackages.put(childPackageName, installRes); 19018 } 19019 } 19020 } 19021 } 19022 } 19023 } 19024 19025 @GuardedBy("mPackages") 19026 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 19027 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 19028 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 19029 for (int nextUserId : userIds) { 19030 if (DEBUG_REMOVE) { 19031 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 19032 } 19033 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 19034 false /*installed*/, 19035 true /*stopped*/, 19036 true /*notLaunched*/, 19037 false /*hidden*/, 19038 0 /*distractionFlags*/, 19039 false /*suspended*/, 19040 null /*suspendingPackage*/, 19041 null /*dialogInfo*/, 19042 null /*suspendedAppExtras*/, 19043 null /*suspendedLauncherExtras*/, 19044 false /*instantApp*/, 19045 false /*virtualPreload*/, 19046 null /*lastDisableAppCaller*/, 19047 null /*enabledComponents*/, 19048 null /*disabledComponents*/, 19049 ps.readUserState(nextUserId).domainVerificationStatus, 19050 0, PackageManager.INSTALL_REASON_UNKNOWN, 19051 null /*harmfulAppWarning*/); 19052 } 19053 mSettings.writeKernelMappingLPr(ps); 19054 } 19055 19056 private void clearPackageStateForUserLIF(PackageSetting ps, int userId, 19057 PackageRemovedInfo outInfo, int flags) { 19058 final PackageParser.Package pkg; 19059 synchronized (mPackages) { 19060 pkg = mPackages.get(ps.name); 19061 } 19062 19063 destroyAppProfilesLIF(pkg); 19064 19065 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 19066 : new int[] {userId}; 19067 for (int nextUserId : userIds) { 19068 if (DEBUG_REMOVE) { 19069 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 19070 + nextUserId); 19071 } 19072 19073 destroyAppDataLIF(pkg, nextUserId, 19074 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 19075 clearDefaultBrowserIfNeededForUser(ps.name, nextUserId); 19076 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 19077 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 19078 clearPackagePreferredActivitiesLPw(ps.name, changedUsers, nextUserId); 19079 if (changedUsers.size() > 0) { 19080 updateDefaultHomeNotLocked(changedUsers); 19081 postPreferredActivityChangedBroadcast(nextUserId); 19082 synchronized (mPackages) { 19083 scheduleWritePackageRestrictionsLocked(nextUserId); 19084 } 19085 } 19086 synchronized (mPackages) { 19087 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 19088 } 19089 // Also delete contributed media, when requested 19090 if ((flags & PackageManager.DELETE_CONTRIBUTED_MEDIA) != 0) { 19091 try { 19092 MediaStore.deleteContributedMedia(mContext, ps.name, UserHandle.of(nextUserId)); 19093 } catch (IOException e) { 19094 Slog.w(TAG, "Failed to delete contributed media for " + ps.name, e); 19095 } 19096 } 19097 } 19098 19099 if (outInfo != null) { 19100 outInfo.removedPackage = ps.name; 19101 outInfo.installerPackageName = ps.installerPackageName; 19102 outInfo.isStaticSharedLib = pkg != null && pkg.staticSharedLibName != null; 19103 outInfo.removedAppId = ps.appId; 19104 outInfo.removedUsers = userIds; 19105 outInfo.broadcastUsers = userIds; 19106 } 19107 } 19108 19109 @Override 19110 public void clearApplicationProfileData(String packageName) { 19111 enforceSystemOrRoot("Only the system can clear all profile data"); 19112 19113 final PackageParser.Package pkg; 19114 synchronized (mPackages) { 19115 pkg = mPackages.get(packageName); 19116 } 19117 19118 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 19119 synchronized (mInstallLock) { 19120 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 19121 } 19122 } 19123 } 19124 19125 @Override 19126 public void clearApplicationUserData(final String packageName, 19127 final IPackageDataObserver observer, final int userId) { 19128 mContext.enforceCallingOrSelfPermission( 19129 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 19130 19131 final int callingUid = Binder.getCallingUid(); 19132 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19133 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 19134 19135 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19136 final boolean filterApp = (ps != null && filterAppAccessLPr(ps, callingUid, userId)); 19137 if (!filterApp && mProtectedPackages.isPackageDataProtected(userId, packageName)) { 19138 throw new SecurityException("Cannot clear data for a protected package: " 19139 + packageName); 19140 } 19141 // Queue up an async operation since the package deletion may take a little while. 19142 mHandler.post(new Runnable() { 19143 public void run() { 19144 mHandler.removeCallbacks(this); 19145 final boolean succeeded; 19146 if (!filterApp) { 19147 try (PackageFreezer freezer = freezePackage(packageName, 19148 "clearApplicationUserData")) { 19149 synchronized (mInstallLock) { 19150 succeeded = clearApplicationUserDataLIF(packageName, userId); 19151 } 19152 synchronized (mPackages) { 19153 mInstantAppRegistry.deleteInstantApplicationMetadataLPw( 19154 packageName, userId); 19155 } 19156 } 19157 if (succeeded) { 19158 // invoke DeviceStorageMonitor's update method to clear any notifications 19159 DeviceStorageMonitorInternal dsm = LocalServices 19160 .getService(DeviceStorageMonitorInternal.class); 19161 if (dsm != null) { 19162 dsm.checkMemory(); 19163 } 19164 if (checkPermission(Manifest.permission.SUSPEND_APPS, packageName, userId) 19165 == PERMISSION_GRANTED) { 19166 unsuspendForSuspendingPackage(packageName, userId); 19167 } 19168 } 19169 } else { 19170 succeeded = false; 19171 } 19172 if (observer != null) { 19173 try { 19174 observer.onRemoveCompleted(packageName, succeeded); 19175 } catch (RemoteException e) { 19176 Log.i(TAG, "Observer no longer exists."); 19177 } 19178 } //end if observer 19179 } //end run 19180 }); 19181 } 19182 19183 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 19184 if (packageName == null) { 19185 Slog.w(TAG, "Attempt to delete null packageName."); 19186 return false; 19187 } 19188 19189 // Try finding details about the requested package 19190 PackageParser.Package pkg; 19191 synchronized (mPackages) { 19192 pkg = mPackages.get(packageName); 19193 if (pkg == null) { 19194 final PackageSetting ps = mSettings.mPackages.get(packageName); 19195 if (ps != null) { 19196 pkg = ps.pkg; 19197 } 19198 } 19199 19200 if (pkg == null) { 19201 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 19202 return false; 19203 } 19204 19205 PackageSetting ps = (PackageSetting) pkg.mExtras; 19206 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19207 } 19208 19209 clearAppDataLIF(pkg, userId, 19210 FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL); 19211 19212 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19213 removeKeystoreDataIfNeeded(userId, appId); 19214 19215 UserManagerInternal umInternal = getUserManagerInternal(); 19216 final int flags; 19217 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 19218 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19219 } else if (umInternal.isUserRunning(userId)) { 19220 flags = StorageManager.FLAG_STORAGE_DE; 19221 } else { 19222 flags = 0; 19223 } 19224 prepareAppDataContentsLIF(pkg, userId, flags); 19225 19226 return true; 19227 } 19228 19229 /** 19230 * Reverts user permission state changes (permissions and flags) in 19231 * all packages for a given user. 19232 * 19233 * @param userId The device user for which to do a reset. 19234 */ 19235 @GuardedBy("mPackages") 19236 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 19237 final int packageCount = mPackages.size(); 19238 for (int i = 0; i < packageCount; i++) { 19239 PackageParser.Package pkg = mPackages.valueAt(i); 19240 PackageSetting ps = (PackageSetting) pkg.mExtras; 19241 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 19242 } 19243 } 19244 19245 private void resetNetworkPolicies(int userId) { 19246 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 19247 } 19248 19249 /** 19250 * Reverts user permission state changes (permissions and flags). 19251 * 19252 * @param ps The package for which to reset. 19253 * @param userId The device user for which to do a reset. 19254 */ 19255 @GuardedBy("mPackages") 19256 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 19257 final PackageSetting ps, final int userId) { 19258 if (ps.pkg == null) { 19259 return; 19260 } 19261 19262 final String packageName = ps.pkg.packageName; 19263 19264 // These are flags that can change base on user actions. 19265 final int userSettableMask = FLAG_PERMISSION_USER_SET 19266 | FLAG_PERMISSION_USER_FIXED 19267 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 19268 | FLAG_PERMISSION_REVIEW_REQUIRED; 19269 19270 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 19271 | FLAG_PERMISSION_POLICY_FIXED; 19272 19273 // Delay and combine non-async permission callbacks 19274 final boolean[] permissionRemoved = new boolean[1]; 19275 final ArraySet<Long> revokedPermissions = new ArraySet<>(); 19276 final SparseBooleanArray updatedUsers = new SparseBooleanArray(); 19277 19278 PermissionCallback delayingPermCallback = new PermissionCallback() { 19279 public void onGidsChanged(int appId, int userId) { 19280 mPermissionCallback.onGidsChanged(appId, userId); 19281 } 19282 19283 public void onPermissionChanged() { 19284 mPermissionCallback.onPermissionChanged(); 19285 } 19286 19287 public void onPermissionGranted(int uid, int userId) { 19288 mPermissionCallback.onPermissionGranted(uid, userId); 19289 } 19290 19291 public void onInstallPermissionGranted() { 19292 mPermissionCallback.onInstallPermissionGranted(); 19293 } 19294 19295 public void onPermissionRevoked(int uid, int userId) { 19296 revokedPermissions.add(IntPair.of(uid, userId)); 19297 19298 updatedUsers.put(userId, true); 19299 } 19300 19301 public void onInstallPermissionRevoked() { 19302 mPermissionCallback.onInstallPermissionRevoked(); 19303 } 19304 19305 public void onPermissionUpdated(int[] updatedUserIds, boolean sync) { 19306 for (int userId : updatedUserIds) { 19307 if (sync) { 19308 updatedUsers.put(userId, true); 19309 } else { 19310 // Don't override sync=true by sync=false 19311 if (!updatedUsers.get(userId)) { 19312 updatedUsers.put(userId, false); 19313 } 19314 } 19315 } 19316 } 19317 19318 public void onPermissionRemoved() { 19319 permissionRemoved[0] = true; 19320 } 19321 19322 public void onInstallPermissionUpdated() { 19323 mPermissionCallback.onInstallPermissionUpdated(); 19324 } 19325 }; 19326 19327 final AppOpsManager appOpsManager = mContext.getSystemService(AppOpsManager.class); 19328 final int uid = UserHandle.getUid(userId, ps.pkg.applicationInfo.uid); 19329 19330 final int permissionCount = ps.pkg.requestedPermissions.size(); 19331 for (int i = 0; i < permissionCount; i++) { 19332 final String permName = ps.pkg.requestedPermissions.get(i); 19333 final BasePermission bp = 19334 (BasePermission) mPermissionManager.getPermissionTEMP(permName); 19335 if (bp == null) { 19336 continue; 19337 } 19338 19339 if (bp.isRemoved()) { 19340 continue; 19341 } 19342 19343 // If shared user we just reset the state to which only this app contributed. 19344 if (ps.sharedUser != null) { 19345 boolean used = false; 19346 final int packageCount = ps.sharedUser.packages.size(); 19347 for (int j = 0; j < packageCount; j++) { 19348 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 19349 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 19350 && pkg.pkg.requestedPermissions.contains(permName)) { 19351 used = true; 19352 break; 19353 } 19354 } 19355 if (used) { 19356 continue; 19357 } 19358 } 19359 19360 final int oldFlags = mPermissionManager.getPermissionFlags(permName, packageName, 19361 Process.SYSTEM_UID, userId); 19362 19363 // Always clear the user settable flags. 19364 // If permission review is enabled and this is a legacy app, mark the 19365 // permission as requiring a review as this is the initial state. 19366 int flags = 0; 19367 if (ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M && bp.isRuntime()) { 19368 flags |= FLAG_PERMISSION_REVIEW_REQUIRED | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 19369 } 19370 19371 mPermissionManager.updatePermissionFlags(permName, packageName, 19372 userSettableMask, flags, Process.SYSTEM_UID, userId, false, 19373 delayingPermCallback); 19374 19375 // Below is only runtime permission handling. 19376 if (!bp.isRuntime()) { 19377 continue; 19378 } 19379 19380 // Never clobber system or policy. 19381 if ((oldFlags & policyOrSystemFlags) != 0) { 19382 continue; 19383 } 19384 19385 // If this permission was granted by default, make sure it is. 19386 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 19387 mPermissionManager.grantRuntimePermission(permName, packageName, false, 19388 Process.SYSTEM_UID, userId, delayingPermCallback); 19389 // Allow app op later as we are holding mPackages 19390 // PermissionPolicyService will handle the app op for foreground/background 19391 // permissions. 19392 String appOp = AppOpsManager.permissionToOp(permName); 19393 if (appOp != null) { 19394 mHandler.post(() -> appOpsManager.setUidMode(appOp, uid, 19395 AppOpsManager.MODE_ALLOWED)); 19396 } 19397 // If permission review is enabled the permissions for a legacy apps 19398 // are represented as constantly granted runtime ones, so don't revoke. 19399 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 19400 // Otherwise, reset the permission. 19401 mPermissionManager.revokeRuntimePermission(permName, packageName, false, userId, 19402 delayingPermCallback); 19403 } 19404 } 19405 19406 // Execute delayed callbacks 19407 if (permissionRemoved[0]) { 19408 mPermissionCallback.onPermissionRemoved(); 19409 } 19410 19411 // Slight variation on the code in mPermissionCallback.onPermissionRevoked() as we cannot 19412 // kill uid while holding mPackages-lock 19413 if (!revokedPermissions.isEmpty()) { 19414 int numRevokedPermissions = revokedPermissions.size(); 19415 for (int i = 0; i < numRevokedPermissions; i++) { 19416 int revocationUID = IntPair.first(revokedPermissions.valueAt(i)); 19417 int revocationUserId = IntPair.second(revokedPermissions.valueAt(i)); 19418 19419 mOnPermissionChangeListeners.onPermissionsChanged(revocationUID); 19420 19421 // Kill app later as we are holding mPackages 19422 mHandler.post(() -> killUid(UserHandle.getAppId(revocationUID), revocationUserId, 19423 KILL_APP_REASON_PERMISSIONS_REVOKED)); 19424 } 19425 } 19426 19427 int numUpdatedUsers = updatedUsers.size(); 19428 for (int i = 0; i < numUpdatedUsers; i++) { 19429 mSettings.writeRuntimePermissionsForUserLPr(updatedUsers.keyAt(i), 19430 updatedUsers.valueAt(i)); 19431 } 19432 } 19433 19434 /** 19435 * Remove entries from the keystore daemon. Will only remove it if the 19436 * {@code appId} is valid. 19437 */ 19438 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 19439 if (appId < 0) { 19440 return; 19441 } 19442 19443 final KeyStore keyStore = KeyStore.getInstance(); 19444 if (keyStore != null) { 19445 if (userId == UserHandle.USER_ALL) { 19446 for (final int individual : sUserManager.getUserIds()) { 19447 keyStore.clearUid(UserHandle.getUid(individual, appId)); 19448 } 19449 } else { 19450 keyStore.clearUid(UserHandle.getUid(userId, appId)); 19451 } 19452 } else { 19453 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 19454 } 19455 } 19456 19457 @Override 19458 public void deleteApplicationCacheFiles(final String packageName, 19459 final IPackageDataObserver observer) { 19460 final int userId = UserHandle.getCallingUserId(); 19461 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 19462 } 19463 19464 @Override 19465 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 19466 final IPackageDataObserver observer) { 19467 final int callingUid = Binder.getCallingUid(); 19468 if (mContext.checkCallingOrSelfPermission( 19469 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES) 19470 != PackageManager.PERMISSION_GRANTED) { 19471 // If the caller has the old delete cache permission, silently ignore. Else throw. 19472 if (mContext.checkCallingOrSelfPermission( 19473 android.Manifest.permission.DELETE_CACHE_FILES) 19474 == PackageManager.PERMISSION_GRANTED) { 19475 Slog.w(TAG, "Calling uid " + callingUid + " does not have " + 19476 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES + 19477 ", silently ignoring"); 19478 return; 19479 } 19480 mContext.enforceCallingOrSelfPermission( 19481 android.Manifest.permission.INTERNAL_DELETE_CACHE_FILES, null); 19482 } 19483 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19484 /* requireFullPermission= */ true, /* checkShell= */ false, 19485 "delete application cache files"); 19486 final int hasAccessInstantApps = mContext.checkCallingOrSelfPermission( 19487 android.Manifest.permission.ACCESS_INSTANT_APPS); 19488 19489 final PackageParser.Package pkg; 19490 synchronized (mPackages) { 19491 pkg = mPackages.get(packageName); 19492 } 19493 19494 // Queue up an async operation since the package deletion may take a little while. 19495 mHandler.post(() -> { 19496 final PackageSetting ps = pkg == null ? null : (PackageSetting) pkg.mExtras; 19497 boolean doClearData = true; 19498 if (ps != null) { 19499 final boolean targetIsInstantApp = 19500 ps.getInstantApp(UserHandle.getUserId(callingUid)); 19501 doClearData = !targetIsInstantApp 19502 || hasAccessInstantApps == PackageManager.PERMISSION_GRANTED; 19503 } 19504 if (doClearData) { 19505 synchronized (mInstallLock) { 19506 final int flags = FLAG_STORAGE_DE | FLAG_STORAGE_CE | FLAG_STORAGE_EXTERNAL; 19507 // We're only clearing cache files, so we don't care if the 19508 // app is unfrozen and still able to run 19509 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 19510 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19511 } 19512 } 19513 if (observer != null) { 19514 try { 19515 observer.onRemoveCompleted(packageName, true); 19516 } catch (RemoteException e) { 19517 Log.i(TAG, "Observer no longer exists."); 19518 } 19519 } 19520 }); 19521 } 19522 19523 @Override 19524 public void getPackageSizeInfo(final String packageName, int userHandle, 19525 final IPackageStatsObserver observer) { 19526 throw new UnsupportedOperationException( 19527 "Shame on you for calling the hidden API getPackageSizeInfo(). Shame!"); 19528 } 19529 19530 @GuardedBy("mInstallLock") 19531 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 19532 final PackageSetting ps; 19533 synchronized (mPackages) { 19534 ps = mSettings.mPackages.get(packageName); 19535 if (ps == null) { 19536 Slog.w(TAG, "Failed to find settings for " + packageName); 19537 return false; 19538 } 19539 } 19540 19541 final String[] packageNames = { packageName }; 19542 final long[] ceDataInodes = { ps.getCeDataInode(userId) }; 19543 final String[] codePaths = { ps.codePathString }; 19544 19545 try { 19546 mInstaller.getAppSize(ps.volumeUuid, packageNames, userId, 0, 19547 ps.appId, ceDataInodes, codePaths, stats); 19548 19549 // For now, ignore code size of packages on system partition 19550 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 19551 stats.codeSize = 0; 19552 } 19553 19554 // External clients expect these to be tracked separately 19555 stats.dataSize -= stats.cacheSize; 19556 19557 } catch (InstallerException e) { 19558 Slog.w(TAG, String.valueOf(e)); 19559 return false; 19560 } 19561 19562 return true; 19563 } 19564 19565 @GuardedBy("mPackages") 19566 private int getUidTargetSdkVersionLockedLPr(int uid) { 19567 final int appId = UserHandle.getAppId(uid); 19568 final Object obj = mSettings.getSettingLPr(appId); 19569 if (obj instanceof SharedUserSetting) { 19570 final SharedUserSetting sus = (SharedUserSetting) obj; 19571 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 19572 final Iterator<PackageSetting> it = sus.packages.iterator(); 19573 while (it.hasNext()) { 19574 final PackageSetting ps = it.next(); 19575 if (ps.pkg != null) { 19576 int v = ps.pkg.applicationInfo.targetSdkVersion; 19577 if (v < vers) vers = v; 19578 } 19579 } 19580 return vers; 19581 } else if (obj instanceof PackageSetting) { 19582 final PackageSetting ps = (PackageSetting) obj; 19583 if (ps.pkg != null) { 19584 return ps.pkg.applicationInfo.targetSdkVersion; 19585 } 19586 } 19587 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19588 } 19589 19590 @GuardedBy("mPackages") 19591 private int getPackageTargetSdkVersionLockedLPr(String packageName) { 19592 final PackageParser.Package p = mPackages.get(packageName); 19593 if (p != null) { 19594 return p.applicationInfo.targetSdkVersion; 19595 } 19596 return Build.VERSION_CODES.CUR_DEVELOPMENT; 19597 } 19598 19599 @Override 19600 public void addPreferredActivity(IntentFilter filter, int match, 19601 ComponentName[] set, ComponentName activity, int userId) { 19602 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19603 "Adding preferred"); 19604 } 19605 19606 private void addPreferredActivityInternal(IntentFilter filter, int match, 19607 ComponentName[] set, ComponentName activity, boolean always, int userId, 19608 String opname) { 19609 // writer 19610 int callingUid = Binder.getCallingUid(); 19611 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19612 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 19613 if (mContext.checkCallingOrSelfPermission( 19614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19615 != PackageManager.PERMISSION_GRANTED) { 19616 if (getUidTargetSdkVersionLockedLPr(callingUid) 19617 < Build.VERSION_CODES.FROYO) { 19618 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 19619 + callingUid); 19620 return; 19621 } 19622 mContext.enforceCallingOrSelfPermission( 19623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19624 } 19625 if (filter.countActions() == 0) { 19626 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19627 return; 19628 } 19629 if (DEBUG_PREFERRED) { 19630 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 19631 + userId + ":"); 19632 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19633 } 19634 synchronized (mPackages) { 19635 final PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 19636 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 19637 scheduleWritePackageRestrictionsLocked(userId); 19638 } 19639 if (!updateDefaultHomeNotLocked(userId)) { 19640 postPreferredActivityChangedBroadcast(userId); 19641 } 19642 } 19643 19644 private void postPreferredActivityChangedBroadcast(int userId) { 19645 mHandler.post(() -> { 19646 final IActivityManager am = ActivityManager.getService(); 19647 if (am == null) { 19648 return; 19649 } 19650 19651 final Intent intent = new Intent(Intent.ACTION_PREFERRED_ACTIVITY_CHANGED); 19652 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId); 19653 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT); 19654 try { 19655 am.broadcastIntent(null, intent, null, null, 19656 0, null, null, null, android.app.AppOpsManager.OP_NONE, 19657 null, false, false, userId); 19658 } catch (RemoteException e) { 19659 } 19660 }); 19661 } 19662 19663 @Override 19664 public void replacePreferredActivity(IntentFilter filter, int match, 19665 ComponentName[] set, ComponentName activity, int userId) { 19666 if (filter.countActions() != 1) { 19667 throw new IllegalArgumentException( 19668 "replacePreferredActivity expects filter to have only 1 action."); 19669 } 19670 if (filter.countDataAuthorities() != 0 19671 || filter.countDataPaths() != 0 19672 || filter.countDataSchemes() > 1 19673 || filter.countDataTypes() != 0) { 19674 throw new IllegalArgumentException( 19675 "replacePreferredActivity expects filter to have no data authorities, " + 19676 "paths, or types; and at most one scheme."); 19677 } 19678 19679 final int callingUid = Binder.getCallingUid(); 19680 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 19681 true /* requireFullPermission */, false /* checkShell */, 19682 "replace preferred activity"); 19683 if (mContext.checkCallingOrSelfPermission( 19684 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19685 != PackageManager.PERMISSION_GRANTED) { 19686 synchronized (mPackages) { 19687 if (getUidTargetSdkVersionLockedLPr(callingUid) 19688 < Build.VERSION_CODES.FROYO) { 19689 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 19690 + Binder.getCallingUid()); 19691 return; 19692 } 19693 } 19694 mContext.enforceCallingOrSelfPermission( 19695 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19696 } 19697 19698 synchronized (mPackages) { 19699 final PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19700 if (pir != null) { 19701 // Get all of the existing entries that exactly match this filter. 19702 final ArrayList<PreferredActivity> existing = pir.findFilters(filter); 19703 if (existing != null && existing.size() == 1) { 19704 final PreferredActivity cur = existing.get(0); 19705 if (DEBUG_PREFERRED) { 19706 Slog.i(TAG, "Checking replace of preferred:"); 19707 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19708 if (!cur.mPref.mAlways) { 19709 Slog.i(TAG, " -- CUR; not mAlways!"); 19710 } else { 19711 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 19712 Slog.i(TAG, " -- CUR: mSet=" 19713 + Arrays.toString(cur.mPref.mSetComponents)); 19714 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 19715 Slog.i(TAG, " -- NEW: mMatch=" 19716 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 19717 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 19718 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 19719 } 19720 } 19721 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 19722 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 19723 && cur.mPref.sameSet(set)) { 19724 // Setting the preferred activity to what it happens to be already 19725 if (DEBUG_PREFERRED) { 19726 Slog.i(TAG, "Replacing with same preferred activity " 19727 + cur.mPref.mShortComponent + " for user " 19728 + userId + ":"); 19729 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19730 } 19731 return; 19732 } 19733 } 19734 if (existing != null) { 19735 if (DEBUG_PREFERRED) { 19736 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 19737 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19738 } 19739 for (int i = existing.size() - 1; i >= 0; --i) { 19740 final PreferredActivity pa = existing.get(i); 19741 if (DEBUG_PREFERRED) { 19742 Slog.i(TAG, "Removing existing preferred activity " 19743 + pa.mPref.mComponent + ":"); 19744 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 19745 } 19746 pir.removeFilter(pa); 19747 } 19748 } 19749 } 19750 } 19751 addPreferredActivityInternal(filter, match, set, activity, true, userId, 19752 "Replacing preferred"); 19753 } 19754 19755 @Override 19756 public void clearPackagePreferredActivities(String packageName) { 19757 final int callingUid = Binder.getCallingUid(); 19758 if (getInstantAppPackageName(callingUid) != null) { 19759 return; 19760 } 19761 // writer 19762 synchronized (mPackages) { 19763 PackageParser.Package pkg = mPackages.get(packageName); 19764 if (pkg == null || !isCallerSameApp(packageName, callingUid)) { 19765 if (mContext.checkCallingOrSelfPermission( 19766 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 19767 != PackageManager.PERMISSION_GRANTED) { 19768 if (getUidTargetSdkVersionLockedLPr(callingUid) 19769 < Build.VERSION_CODES.FROYO) { 19770 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 19771 + callingUid); 19772 return; 19773 } 19774 mContext.enforceCallingOrSelfPermission( 19775 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19776 } 19777 } 19778 final PackageSetting ps = mSettings.getPackageLPr(packageName); 19779 if (ps != null 19780 && filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 19781 return; 19782 } 19783 } 19784 int callingUserId = UserHandle.getCallingUserId(); 19785 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 19786 clearPackagePreferredActivitiesLPw(packageName, changedUsers, callingUserId); 19787 if (changedUsers.size() > 0) { 19788 updateDefaultHomeNotLocked(changedUsers); 19789 postPreferredActivityChangedBroadcast(callingUserId); 19790 synchronized (mPackages) { 19791 scheduleWritePackageRestrictionsLocked(callingUserId); 19792 } 19793 } 19794 } 19795 19796 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19797 @GuardedBy("mPackages") 19798 private void clearPackagePreferredActivitiesLPw(String packageName, 19799 @NonNull SparseBooleanArray outUserChanged, int userId) { 19800 ArrayList<PreferredActivity> removed = null; 19801 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 19802 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 19803 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 19804 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 19805 continue; 19806 } 19807 Iterator<PreferredActivity> it = pir.filterIterator(); 19808 while (it.hasNext()) { 19809 PreferredActivity pa = it.next(); 19810 // Mark entry for removal only if it matches the package name 19811 // and the entry is of type "always". 19812 if (packageName == null || 19813 (pa.mPref.mComponent.getPackageName().equals(packageName) 19814 && pa.mPref.mAlways)) { 19815 if (removed == null) { 19816 removed = new ArrayList<>(); 19817 } 19818 removed.add(pa); 19819 } 19820 } 19821 if (removed != null) { 19822 for (int j=0; j<removed.size(); j++) { 19823 PreferredActivity pa = removed.get(j); 19824 pir.removeFilter(pa); 19825 } 19826 outUserChanged.put(thisUserId, true); 19827 } 19828 } 19829 } 19830 19831 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19832 @GuardedBy("mPackages") 19833 private void clearIntentFilterVerificationsLPw(int userId) { 19834 final int packageCount = mPackages.size(); 19835 for (int i = 0; i < packageCount; i++) { 19836 PackageParser.Package pkg = mPackages.valueAt(i); 19837 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 19838 } 19839 } 19840 19841 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 19842 @GuardedBy("mPackages") 19843 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 19844 if (userId == UserHandle.USER_ALL) { 19845 if (mSettings.removeIntentFilterVerificationLPw(packageName, 19846 sUserManager.getUserIds())) { 19847 for (int oneUserId : sUserManager.getUserIds()) { 19848 scheduleWritePackageRestrictionsLocked(oneUserId); 19849 } 19850 } 19851 } else { 19852 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 19853 scheduleWritePackageRestrictionsLocked(userId); 19854 } 19855 } 19856 } 19857 19858 /** Clears state for all users, and touches intent filter verification policy */ 19859 void clearDefaultBrowserIfNeeded(String packageName) { 19860 for (int oneUserId : sUserManager.getUserIds()) { 19861 clearDefaultBrowserIfNeededForUser(packageName, oneUserId); 19862 } 19863 } 19864 19865 private void clearDefaultBrowserIfNeededForUser(String packageName, int userId) { 19866 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 19867 if (!TextUtils.isEmpty(defaultBrowserPackageName)) { 19868 if (packageName.equals(defaultBrowserPackageName)) { 19869 setDefaultBrowserPackageName(null, userId); 19870 } 19871 } 19872 } 19873 19874 @Override 19875 public void resetApplicationPreferences(int userId) { 19876 mContext.enforceCallingOrSelfPermission( 19877 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 19878 final long identity = Binder.clearCallingIdentity(); 19879 // writer 19880 try { 19881 final SparseBooleanArray changedUsers = new SparseBooleanArray(); 19882 clearPackagePreferredActivitiesLPw(null, changedUsers, userId); 19883 if (changedUsers.size() > 0) { 19884 postPreferredActivityChangedBroadcast(userId); 19885 } 19886 synchronized (mPackages) { 19887 mSettings.applyDefaultPreferredAppsLPw(userId); 19888 clearIntentFilterVerificationsLPw(userId); 19889 primeDomainVerificationsLPw(userId); 19890 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 19891 } 19892 updateDefaultHomeNotLocked(userId); 19893 // TODO: We have to reset the default SMS and Phone. This requires 19894 // significant refactoring to keep all default apps in the package 19895 // manager (cleaner but more work) or have the services provide 19896 // callbacks to the package manager to request a default app reset. 19897 setDefaultBrowserPackageName(null, userId); 19898 resetNetworkPolicies(userId); 19899 synchronized (mPackages) { 19900 scheduleWritePackageRestrictionsLocked(userId); 19901 } 19902 } finally { 19903 Binder.restoreCallingIdentity(identity); 19904 } 19905 } 19906 19907 @Override 19908 public int getPreferredActivities(List<IntentFilter> outFilters, 19909 List<ComponentName> outActivities, String packageName) { 19910 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 19911 return 0; 19912 } 19913 int num = 0; 19914 final int userId = UserHandle.getCallingUserId(); 19915 // reader 19916 synchronized (mPackages) { 19917 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 19918 if (pir != null) { 19919 final Iterator<PreferredActivity> it = pir.filterIterator(); 19920 while (it.hasNext()) { 19921 final PreferredActivity pa = it.next(); 19922 if (packageName == null 19923 || (pa.mPref.mComponent.getPackageName().equals(packageName) 19924 && pa.mPref.mAlways)) { 19925 if (outFilters != null) { 19926 outFilters.add(new IntentFilter(pa)); 19927 } 19928 if (outActivities != null) { 19929 outActivities.add(pa.mPref.mComponent); 19930 } 19931 } 19932 } 19933 } 19934 } 19935 19936 return num; 19937 } 19938 19939 @Override 19940 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 19941 int userId) { 19942 int callingUid = Binder.getCallingUid(); 19943 if (callingUid != Process.SYSTEM_UID) { 19944 throw new SecurityException( 19945 "addPersistentPreferredActivity can only be run by the system"); 19946 } 19947 if (filter.countActions() == 0) { 19948 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 19949 return; 19950 } 19951 if (DEBUG_PREFERRED) { 19952 Slog.i(TAG, "Adding persistent preferred activity " + activity 19953 + " for user " + userId + ":"); 19954 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 19955 } 19956 synchronized (mPackages) { 19957 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 19958 new PersistentPreferredActivity(filter, activity)); 19959 scheduleWritePackageRestrictionsLocked(userId); 19960 } 19961 updateDefaultHomeNotLocked(userId); 19962 postPreferredActivityChangedBroadcast(userId); 19963 } 19964 19965 @Override 19966 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 19967 int callingUid = Binder.getCallingUid(); 19968 if (callingUid != Process.SYSTEM_UID) { 19969 throw new SecurityException( 19970 "clearPackagePersistentPreferredActivities can only be run by the system"); 19971 } 19972 ArrayList<PersistentPreferredActivity> removed = null; 19973 boolean changed = false; 19974 synchronized (mPackages) { 19975 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 19976 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 19977 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 19978 .valueAt(i); 19979 if (userId != thisUserId) { 19980 continue; 19981 } 19982 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 19983 while (it.hasNext()) { 19984 PersistentPreferredActivity ppa = it.next(); 19985 // Mark entry for removal only if it matches the package name. 19986 if (ppa.mComponent.getPackageName().equals(packageName)) { 19987 if (removed == null) { 19988 removed = new ArrayList<>(); 19989 } 19990 removed.add(ppa); 19991 } 19992 } 19993 if (removed != null) { 19994 for (int j=0; j<removed.size(); j++) { 19995 PersistentPreferredActivity ppa = removed.get(j); 19996 ppir.removeFilter(ppa); 19997 } 19998 changed = true; 19999 } 20000 } 20001 } 20002 if (changed) { 20003 updateDefaultHomeNotLocked(userId); 20004 postPreferredActivityChangedBroadcast(userId); 20005 synchronized (mPackages) { 20006 scheduleWritePackageRestrictionsLocked(userId); 20007 } 20008 } 20009 } 20010 20011 /** 20012 * Common machinery for picking apart a restored XML blob and passing 20013 * it to a caller-supplied functor to be applied to the running system. 20014 */ 20015 private void restoreFromXml(XmlPullParser parser, int userId, 20016 String expectedStartTag, BlobXmlRestorer functor) 20017 throws IOException, XmlPullParserException { 20018 int type; 20019 while ((type = parser.next()) != XmlPullParser.START_TAG 20020 && type != XmlPullParser.END_DOCUMENT) { 20021 } 20022 if (type != XmlPullParser.START_TAG) { 20023 // oops didn't find a start tag?! 20024 if (DEBUG_BACKUP) { 20025 Slog.e(TAG, "Didn't find start tag during restore"); 20026 } 20027 return; 20028 } 20029 // this is supposed to be TAG_PREFERRED_BACKUP 20030 if (!expectedStartTag.equals(parser.getName())) { 20031 if (DEBUG_BACKUP) { 20032 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 20033 } 20034 return; 20035 } 20036 20037 // skip interfering stuff, then we're aligned with the backing implementation 20038 while ((type = parser.next()) == XmlPullParser.TEXT) { } 20039 functor.apply(parser, userId); 20040 } 20041 20042 private interface BlobXmlRestorer { 20043 void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 20044 } 20045 20046 /** 20047 * Non-Binder method, support for the backup/restore mechanism: write the 20048 * full set of preferred activities in its canonical XML format. Returns the 20049 * XML output as a byte array, or null if there is none. 20050 */ 20051 @Override 20052 public byte[] getPreferredActivityBackup(int userId) { 20053 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20054 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 20055 } 20056 20057 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20058 try { 20059 final XmlSerializer serializer = new FastXmlSerializer(); 20060 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20061 serializer.startDocument(null, true); 20062 serializer.startTag(null, TAG_PREFERRED_BACKUP); 20063 20064 synchronized (mPackages) { 20065 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 20066 } 20067 20068 serializer.endTag(null, TAG_PREFERRED_BACKUP); 20069 serializer.endDocument(); 20070 serializer.flush(); 20071 } catch (Exception e) { 20072 if (DEBUG_BACKUP) { 20073 Slog.e(TAG, "Unable to write preferred activities for backup", e); 20074 } 20075 return null; 20076 } 20077 20078 return dataStream.toByteArray(); 20079 } 20080 20081 @Override 20082 public void restorePreferredActivities(byte[] backup, int userId) { 20083 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20084 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20085 } 20086 20087 try { 20088 final XmlPullParser parser = Xml.newPullParser(); 20089 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20090 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 20091 (readParser, readUserId) -> { 20092 synchronized (mPackages) { 20093 mSettings.readPreferredActivitiesLPw(readParser, readUserId); 20094 } 20095 updateDefaultHomeNotLocked(readUserId); 20096 }); 20097 } catch (Exception e) { 20098 if (DEBUG_BACKUP) { 20099 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20100 } 20101 } 20102 } 20103 20104 /** 20105 * Non-Binder method, support for the backup/restore mechanism: write the 20106 * default browser (etc) settings in its canonical XML format. Returns the default 20107 * browser XML representation as a byte array, or null if there is none. 20108 */ 20109 @Override 20110 public byte[] getDefaultAppsBackup(int userId) { 20111 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20112 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 20113 } 20114 20115 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20116 try { 20117 final XmlSerializer serializer = new FastXmlSerializer(); 20118 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20119 serializer.startDocument(null, true); 20120 serializer.startTag(null, TAG_DEFAULT_APPS); 20121 20122 synchronized (mPackages) { 20123 mSettings.writeDefaultAppsLPr(serializer, userId); 20124 } 20125 20126 serializer.endTag(null, TAG_DEFAULT_APPS); 20127 serializer.endDocument(); 20128 serializer.flush(); 20129 } catch (Exception e) { 20130 if (DEBUG_BACKUP) { 20131 Slog.e(TAG, "Unable to write default apps for backup", e); 20132 } 20133 return null; 20134 } 20135 20136 return dataStream.toByteArray(); 20137 } 20138 20139 @Override 20140 public void restoreDefaultApps(byte[] backup, int userId) { 20141 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20142 throw new SecurityException("Only the system may call restoreDefaultApps()"); 20143 } 20144 20145 try { 20146 final XmlPullParser parser = Xml.newPullParser(); 20147 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20148 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 20149 (parser1, userId1) -> { 20150 String defaultBrowser; 20151 synchronized (mPackages) { 20152 mSettings.readDefaultAppsLPw(parser1, userId1); 20153 defaultBrowser = mSettings.removeDefaultBrowserPackageNameLPw(userId1); 20154 } 20155 if (defaultBrowser != null) { 20156 PackageManagerInternal.DefaultBrowserProvider provider; 20157 synchronized (mPackages) { 20158 provider = mDefaultBrowserProvider; 20159 } 20160 provider.setDefaultBrowser(defaultBrowser, userId1); 20161 } 20162 }); 20163 } catch (Exception e) { 20164 if (DEBUG_BACKUP) { 20165 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 20166 } 20167 } 20168 } 20169 20170 @Override 20171 public byte[] getIntentFilterVerificationBackup(int userId) { 20172 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20173 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 20174 } 20175 20176 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 20177 try { 20178 final XmlSerializer serializer = new FastXmlSerializer(); 20179 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 20180 serializer.startDocument(null, true); 20181 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 20182 20183 synchronized (mPackages) { 20184 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 20185 } 20186 20187 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 20188 serializer.endDocument(); 20189 serializer.flush(); 20190 } catch (Exception e) { 20191 if (DEBUG_BACKUP) { 20192 Slog.e(TAG, "Unable to write default apps for backup", e); 20193 } 20194 return null; 20195 } 20196 20197 return dataStream.toByteArray(); 20198 } 20199 20200 @Override 20201 public void restoreIntentFilterVerification(byte[] backup, int userId) { 20202 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 20203 throw new SecurityException("Only the system may call restorePreferredActivities()"); 20204 } 20205 20206 try { 20207 final XmlPullParser parser = Xml.newPullParser(); 20208 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 20209 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 20210 (parser1, userId1) -> { 20211 synchronized (mPackages) { 20212 mSettings.readAllDomainVerificationsLPr(parser1, userId1); 20213 mSettings.writeLPr(); 20214 } 20215 }); 20216 } catch (Exception e) { 20217 if (DEBUG_BACKUP) { 20218 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 20219 } 20220 } 20221 } 20222 20223 @Override 20224 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 20225 int sourceUserId, int targetUserId, int flags) { 20226 mContext.enforceCallingOrSelfPermission( 20227 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20228 int callingUid = Binder.getCallingUid(); 20229 enforceOwnerRights(ownerPackage, callingUid); 20230 PackageManagerServiceUtils.enforceShellRestriction( 20231 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20232 if (intentFilter.countActions() == 0) { 20233 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 20234 return; 20235 } 20236 synchronized (mPackages) { 20237 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 20238 ownerPackage, targetUserId, flags); 20239 CrossProfileIntentResolver resolver = 20240 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20241 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 20242 // We have all those whose filter is equal. Now checking if the rest is equal as well. 20243 if (existing != null) { 20244 int size = existing.size(); 20245 for (int i = 0; i < size; i++) { 20246 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 20247 return; 20248 } 20249 } 20250 } 20251 resolver.addFilter(newFilter); 20252 scheduleWritePackageRestrictionsLocked(sourceUserId); 20253 } 20254 } 20255 20256 @Override 20257 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 20258 mContext.enforceCallingOrSelfPermission( 20259 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 20260 final int callingUid = Binder.getCallingUid(); 20261 enforceOwnerRights(ownerPackage, callingUid); 20262 PackageManagerServiceUtils.enforceShellRestriction( 20263 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 20264 synchronized (mPackages) { 20265 CrossProfileIntentResolver resolver = 20266 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 20267 ArraySet<CrossProfileIntentFilter> set = 20268 new ArraySet<>(resolver.filterSet()); 20269 for (CrossProfileIntentFilter filter : set) { 20270 if (filter.getOwnerPackage().equals(ownerPackage)) { 20271 resolver.removeFilter(filter); 20272 } 20273 } 20274 scheduleWritePackageRestrictionsLocked(sourceUserId); 20275 } 20276 } 20277 20278 // Enforcing that callingUid is owning pkg on userId 20279 private void enforceOwnerRights(String pkg, int callingUid) { 20280 // The system owns everything. 20281 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 20282 return; 20283 } 20284 final int callingUserId = UserHandle.getUserId(callingUid); 20285 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 20286 if (pi == null) { 20287 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 20288 + callingUserId); 20289 } 20290 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 20291 throw new SecurityException("Calling uid " + callingUid 20292 + " does not own package " + pkg); 20293 } 20294 } 20295 20296 @Override 20297 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 20298 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20299 return null; 20300 } 20301 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 20302 } 20303 20304 /** 20305 * Send a {@code PackageInstaller.ACTION_SESSION_UPDATED} broadcast intent, containing 20306 * the {@code sessionInfo} in the extra field {@code PackageInstaller.EXTRA_SESSION}. 20307 */ 20308 public void sendSessionUpdatedBroadcast(PackageInstaller.SessionInfo sessionInfo, 20309 int userId) { 20310 if (TextUtils.isEmpty(sessionInfo.installerPackageName)) { 20311 return; 20312 } 20313 Intent sessionUpdatedIntent = new Intent(PackageInstaller.ACTION_SESSION_UPDATED) 20314 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20315 .setPackage(sessionInfo.installerPackageName); 20316 mContext.sendBroadcastAsUser(sessionUpdatedIntent, UserHandle.of(userId)); 20317 } 20318 20319 public void sendSessionCommitBroadcast(PackageInstaller.SessionInfo sessionInfo, int userId) { 20320 UserManagerService ums = UserManagerService.getInstance(); 20321 if (ums != null && !sessionInfo.isStaged()) { 20322 final UserInfo parent = ums.getProfileParent(userId); 20323 final int launcherUid = (parent != null) ? parent.id : userId; 20324 final ComponentName launcherComponent = getDefaultHomeActivity(launcherUid); 20325 if (launcherComponent != null) { 20326 Intent launcherIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20327 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20328 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20329 .setPackage(launcherComponent.getPackageName()); 20330 mContext.sendBroadcastAsUser(launcherIntent, UserHandle.of(launcherUid)); 20331 } 20332 // TODO(b/122900055) Change/Remove this and replace with new permission role. 20333 if (mAppPredictionServicePackage != null) { 20334 Intent predictorIntent = new Intent(PackageInstaller.ACTION_SESSION_COMMITTED) 20335 .putExtra(PackageInstaller.EXTRA_SESSION, sessionInfo) 20336 .putExtra(Intent.EXTRA_USER, UserHandle.of(userId)) 20337 .setPackage(mAppPredictionServicePackage); 20338 mContext.sendBroadcastAsUser(predictorIntent, UserHandle.of(launcherUid)); 20339 } 20340 } 20341 } 20342 20343 /** 20344 * Report the 'Home' activity which is currently set as "always use this one". If non is set 20345 * then reports the most likely home activity or null if there are more than one. 20346 */ 20347 private ComponentName getDefaultHomeActivity(int userId) { 20348 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 20349 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 20350 if (cn != null) { 20351 return cn; 20352 } 20353 20354 // Find the launcher with the highest priority and return that component if there are no 20355 // other home activity with the same priority. 20356 int lastPriority = Integer.MIN_VALUE; 20357 ComponentName lastComponent = null; 20358 final int size = allHomeCandidates.size(); 20359 for (int i = 0; i < size; i++) { 20360 final ResolveInfo ri = allHomeCandidates.get(i); 20361 if (ri.priority > lastPriority) { 20362 lastComponent = ri.activityInfo.getComponentName(); 20363 lastPriority = ri.priority; 20364 } else if (ri.priority == lastPriority) { 20365 // Two components found with same priority. 20366 lastComponent = null; 20367 } 20368 } 20369 return lastComponent; 20370 } 20371 20372 private Intent getHomeIntent() { 20373 Intent intent = new Intent(Intent.ACTION_MAIN); 20374 intent.addCategory(Intent.CATEGORY_HOME); 20375 intent.addCategory(Intent.CATEGORY_DEFAULT); 20376 return intent; 20377 } 20378 20379 private IntentFilter getHomeFilter() { 20380 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 20381 filter.addCategory(Intent.CATEGORY_HOME); 20382 filter.addCategory(Intent.CATEGORY_DEFAULT); 20383 return filter; 20384 } 20385 20386 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20387 int userId) { 20388 Intent intent = getHomeIntent(); 20389 List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null, 20390 PackageManager.GET_META_DATA, userId); 20391 allHomeCandidates.clear(); 20392 if (resolveInfos == null) { 20393 return null; 20394 } 20395 allHomeCandidates.addAll(resolveInfos); 20396 20397 PackageManagerInternal.DefaultHomeProvider provider; 20398 synchronized (mPackages) { 20399 provider = mDefaultHomeProvider; 20400 } 20401 if (provider == null) { 20402 Slog.e(TAG, "mDefaultHomeProvider is null"); 20403 return null; 20404 } 20405 String packageName = provider.getDefaultHome(userId); 20406 if (packageName == null) { 20407 return null; 20408 } 20409 int resolveInfosSize = resolveInfos.size(); 20410 for (int i = 0; i < resolveInfosSize; i++) { 20411 ResolveInfo resolveInfo = resolveInfos.get(i); 20412 20413 if (resolveInfo.activityInfo != null && TextUtils.equals( 20414 resolveInfo.activityInfo.packageName, packageName)) { 20415 return new ComponentName(resolveInfo.activityInfo.packageName, 20416 resolveInfo.activityInfo.name); 20417 } 20418 } 20419 return null; 20420 } 20421 20422 /** <b>must not hold {@link #mPackages}</b> */ 20423 private void updateDefaultHomeNotLocked(SparseBooleanArray userIds) { 20424 if (Thread.holdsLock(mPackages)) { 20425 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 20426 + " is holding mPackages", new Throwable()); 20427 } 20428 for (int i = userIds.size() - 1; i >= 0; --i) { 20429 final int userId = userIds.keyAt(i); 20430 updateDefaultHomeNotLocked(userId); 20431 } 20432 } 20433 20434 /** 20435 * <b>must not hold {@link #mPackages}</b> 20436 * 20437 * @return Whether the ACTION_PREFERRED_ACTIVITY_CHANGED broadcast has been scheduled. 20438 */ 20439 private boolean updateDefaultHomeNotLocked(int userId) { 20440 if (Thread.holdsLock(mPackages)) { 20441 Slog.wtf(TAG, "Calling thread " + Thread.currentThread().getName() 20442 + " is holding mPackages", new Throwable()); 20443 } 20444 if (!mSystemReady) { 20445 // We might get called before system is ready because of package changes etc, but 20446 // finding preferred activity depends on settings provider, so we ignore the update 20447 // before that. 20448 return false; 20449 } 20450 final Intent intent = getHomeIntent(); 20451 final List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null, 20452 PackageManager.GET_META_DATA, userId); 20453 final ResolveInfo preferredResolveInfo = findPreferredActivityNotLocked( 20454 intent, null, 0, resolveInfos, 0, true, false, false, userId); 20455 final String packageName = preferredResolveInfo != null 20456 && preferredResolveInfo.activityInfo != null 20457 ? preferredResolveInfo.activityInfo.packageName : null; 20458 final PackageManagerInternal.DefaultHomeProvider provider; 20459 synchronized (mPackages) { 20460 provider = mDefaultHomeProvider; 20461 } 20462 if (provider == null) { 20463 Slog.e(TAG, "Default home provider has not been set"); 20464 return false; 20465 } 20466 final String currentPackageName = provider.getDefaultHome(userId); 20467 if (TextUtils.equals(currentPackageName, packageName)) { 20468 return false; 20469 } 20470 final String[] callingPackages = getPackagesForUid(Binder.getCallingUid()); 20471 if (callingPackages != null && ArrayUtils.contains(callingPackages, 20472 mRequiredPermissionControllerPackage)) { 20473 // PermissionController manages default home directly. 20474 return false; 20475 } 20476 provider.setDefaultHomeAsync(packageName, userId, (successful) -> { 20477 if (successful) { 20478 postPreferredActivityChangedBroadcast(userId); 20479 } 20480 }); 20481 return true; 20482 } 20483 20484 @Override 20485 public void setHomeActivity(ComponentName comp, int userId) { 20486 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20487 return; 20488 } 20489 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 20490 getHomeActivitiesAsUser(homeActivities, userId); 20491 20492 boolean found = false; 20493 20494 final int size = homeActivities.size(); 20495 final ComponentName[] set = new ComponentName[size]; 20496 for (int i = 0; i < size; i++) { 20497 final ResolveInfo candidate = homeActivities.get(i); 20498 final ActivityInfo info = candidate.activityInfo; 20499 final ComponentName activityName = new ComponentName(info.packageName, info.name); 20500 set[i] = activityName; 20501 if (!found && activityName.equals(comp)) { 20502 found = true; 20503 } 20504 } 20505 if (!found) { 20506 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 20507 + userId); 20508 } 20509 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 20510 set, comp, userId); 20511 } 20512 20513 private @Nullable String getSetupWizardPackageName() { 20514 final Intent intent = new Intent(Intent.ACTION_MAIN); 20515 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 20516 20517 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20518 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20519 | MATCH_DISABLED_COMPONENTS, 20520 UserHandle.myUserId()); 20521 if (matches.size() == 1) { 20522 return matches.get(0).getComponentInfo().packageName; 20523 } else { 20524 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 20525 + ": matches=" + matches); 20526 return null; 20527 } 20528 } 20529 20530 private @Nullable String getStorageManagerPackageName() { 20531 final Intent intent = new Intent(StorageManager.ACTION_MANAGE_STORAGE); 20532 20533 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 20534 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20535 | MATCH_DISABLED_COMPONENTS, 20536 UserHandle.myUserId()); 20537 if (matches.size() == 1) { 20538 return matches.get(0).getComponentInfo().packageName; 20539 } else { 20540 Slog.e(TAG, "There should probably be exactly one storage manager; found " 20541 + matches.size() + ": matches=" + matches); 20542 return null; 20543 } 20544 } 20545 20546 @Override 20547 public String getSystemTextClassifierPackageName() { 20548 return ensureSystemPackageName(mContext.getString( 20549 R.string.config_defaultTextClassifierPackage)); 20550 } 20551 20552 @Override 20553 public @Nullable String getAttentionServicePackageName() { 20554 final String flattenedComponentName = 20555 mContext.getString(R.string.config_defaultAttentionService); 20556 if (flattenedComponentName != null) { 20557 ComponentName componentName = ComponentName.unflattenFromString(flattenedComponentName); 20558 if (componentName != null && componentName.getPackageName() != null) { 20559 return ensureSystemPackageName(componentName.getPackageName()); 20560 } 20561 } 20562 return null; 20563 } 20564 20565 private @Nullable String getDocumenterPackageName() { 20566 final Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT); 20567 intent.addCategory(Intent.CATEGORY_OPENABLE); 20568 intent.setType("*/*"); 20569 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 20570 20571 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, resolvedType, 20572 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 20573 | MATCH_DISABLED_COMPONENTS, 20574 UserHandle.myUserId()); 20575 if (matches.size() == 1) { 20576 return matches.get(0).getComponentInfo().packageName; 20577 } else { 20578 Slog.e(TAG, "There should probably be exactly one documenter; found " 20579 + matches.size() + ": matches=" + matches); 20580 return null; 20581 } 20582 } 20583 20584 @Nullable 20585 private String getDeviceConfiguratorPackageName() { 20586 return ensureSystemPackageName(mContext.getString( 20587 R.string.config_deviceConfiguratorPackageName)); 20588 } 20589 20590 @Override 20591 public String getWellbeingPackageName() { 20592 return ensureSystemPackageName(mContext.getString(R.string.config_defaultWellbeingPackage)); 20593 } 20594 20595 @Override 20596 public String getAppPredictionServicePackageName() { 20597 String flattenedAppPredictionServiceComponentName = 20598 mContext.getString(R.string.config_defaultAppPredictionService); 20599 if (flattenedAppPredictionServiceComponentName == null) { 20600 return null; 20601 } 20602 ComponentName appPredictionServiceComponentName = 20603 ComponentName.unflattenFromString(flattenedAppPredictionServiceComponentName); 20604 if (appPredictionServiceComponentName == null) { 20605 return null; 20606 } 20607 return ensureSystemPackageName(appPredictionServiceComponentName.getPackageName()); 20608 } 20609 20610 @Override 20611 public String getSystemCaptionsServicePackageName() { 20612 String flattenedSystemCaptionsServiceComponentName = 20613 mContext.getString(R.string.config_defaultSystemCaptionsService); 20614 20615 if (TextUtils.isEmpty(flattenedSystemCaptionsServiceComponentName)) { 20616 return null; 20617 } 20618 20619 ComponentName systemCaptionsServiceComponentName = 20620 ComponentName.unflattenFromString(flattenedSystemCaptionsServiceComponentName); 20621 if (systemCaptionsServiceComponentName == null) { 20622 return null; 20623 } 20624 return ensureSystemPackageName(systemCaptionsServiceComponentName.getPackageName()); 20625 } 20626 20627 public String getIncidentReportApproverPackageName() { 20628 return ensureSystemPackageName(mContext.getString( 20629 R.string.config_incidentReportApproverPackage)); 20630 } 20631 20632 @Nullable 20633 private String ensureSystemPackageName(@Nullable String packageName) { 20634 if (packageName == null) { 20635 return null; 20636 } 20637 long token = Binder.clearCallingIdentity(); 20638 try { 20639 if (getPackageInfo(packageName, MATCH_FACTORY_ONLY, UserHandle.USER_SYSTEM) == null) { 20640 PackageInfo packageInfo = getPackageInfo(packageName, 0, UserHandle.USER_SYSTEM); 20641 if (packageInfo != null) { 20642 EventLog.writeEvent(0x534e4554, "145981139", packageInfo.applicationInfo.uid, 20643 ""); 20644 } 20645 return null; 20646 } 20647 } finally { 20648 Binder.restoreCallingIdentity(token); 20649 } 20650 return packageName; 20651 } 20652 20653 @Override 20654 public String[] getTelephonyPackageNames() { 20655 String names = mContext.getString(R.string.config_telephonyPackages); 20656 String[] telephonyPackageNames = null; 20657 if (!TextUtils.isEmpty(names)) { 20658 telephonyPackageNames = names.trim().split(","); 20659 } 20660 return telephonyPackageNames; 20661 } 20662 20663 @Override 20664 public void setApplicationEnabledSetting(String appPackageName, 20665 int newState, int flags, int userId, String callingPackage) { 20666 if (!sUserManager.exists(userId)) return; 20667 if (callingPackage == null) { 20668 callingPackage = Integer.toString(Binder.getCallingUid()); 20669 } 20670 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 20671 } 20672 20673 @Override 20674 public void setUpdateAvailable(String packageName, boolean updateAvailable) { 20675 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 20676 synchronized (mPackages) { 20677 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 20678 if (pkgSetting != null) { 20679 pkgSetting.setUpdateAvailable(updateAvailable); 20680 } 20681 } 20682 } 20683 20684 @Override 20685 public void setComponentEnabledSetting(ComponentName componentName, 20686 int newState, int flags, int userId) { 20687 if (!sUserManager.exists(userId)) return; 20688 setEnabledSetting(componentName.getPackageName(), 20689 componentName.getClassName(), newState, flags, userId, null); 20690 } 20691 20692 private void setEnabledSetting(final String packageName, String className, int newState, 20693 final int flags, int userId, String callingPackage) { 20694 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 20695 || newState == COMPONENT_ENABLED_STATE_ENABLED 20696 || newState == COMPONENT_ENABLED_STATE_DISABLED 20697 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20698 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 20699 throw new IllegalArgumentException("Invalid new component state: " 20700 + newState); 20701 } 20702 PackageSetting pkgSetting; 20703 final int callingUid = Binder.getCallingUid(); 20704 final int permission; 20705 if (callingUid == Process.SYSTEM_UID) { 20706 permission = PackageManager.PERMISSION_GRANTED; 20707 } else { 20708 permission = mContext.checkCallingOrSelfPermission( 20709 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20710 } 20711 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20712 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 20713 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20714 boolean sendNow = false; 20715 boolean isApp = (className == null); 20716 final boolean isCallerInstantApp = (getInstantAppPackageName(callingUid) != null); 20717 String componentName = isApp ? packageName : className; 20718 ArrayList<String> components; 20719 20720 // reader 20721 synchronized (mPackages) { 20722 pkgSetting = mSettings.mPackages.get(packageName); 20723 if (pkgSetting == null) { 20724 if (!isCallerInstantApp) { 20725 if (className == null) { 20726 throw new IllegalArgumentException("Unknown package: " + packageName); 20727 } 20728 throw new IllegalArgumentException( 20729 "Unknown component: " + packageName + "/" + className); 20730 } else { 20731 // throw SecurityException to prevent leaking package information 20732 throw new SecurityException( 20733 "Attempt to change component state; " 20734 + "pid=" + Binder.getCallingPid() 20735 + ", uid=" + callingUid 20736 + (className == null 20737 ? ", package=" + packageName 20738 : ", component=" + packageName + "/" + className)); 20739 } 20740 } 20741 } 20742 20743 // Limit who can change which apps 20744 if (!UserHandle.isSameApp(callingUid, pkgSetting.appId)) { 20745 // Don't allow apps that don't have permission to modify other apps 20746 if (!allowedByPermission 20747 || filterAppAccessLPr(pkgSetting, callingUid, userId)) { 20748 throw new SecurityException( 20749 "Attempt to change component state; " 20750 + "pid=" + Binder.getCallingPid() 20751 + ", uid=" + callingUid 20752 + (className == null 20753 ? ", package=" + packageName 20754 : ", component=" + packageName + "/" + className)); 20755 } 20756 // Don't allow changing protected packages. 20757 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 20758 throw new SecurityException("Cannot disable a protected package: " + packageName); 20759 } 20760 } 20761 // Only allow apps with CHANGE_COMPONENT_ENABLED_STATE permission to change hidden 20762 // app details activity 20763 if (PackageManager.APP_DETAILS_ACTIVITY_CLASS_NAME.equals(className) 20764 && !allowedByPermission) { 20765 throw new SecurityException("Cannot disable a system-generated component"); 20766 } 20767 20768 synchronized (mPackages) { 20769 if (callingUid == Process.SHELL_UID 20770 && (pkgSetting.pkgFlags & ApplicationInfo.FLAG_TEST_ONLY) == 0) { 20771 // Shell can only change whole packages between ENABLED and DISABLED_USER states 20772 // unless it is a test package. 20773 int oldState = pkgSetting.getEnabled(userId); 20774 if (className == null 20775 && 20776 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 20777 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 20778 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 20779 && 20780 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 20781 || newState == COMPONENT_ENABLED_STATE_DEFAULT 20782 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 20783 // ok 20784 } else { 20785 throw new SecurityException( 20786 "Shell cannot change component state for " + packageName + "/" 20787 + className + " to " + newState); 20788 } 20789 } 20790 } 20791 if (className == null) { 20792 // We're dealing with an application/package level state change 20793 synchronized (mPackages) { 20794 if (pkgSetting.getEnabled(userId) == newState) { 20795 // Nothing to do 20796 return; 20797 } 20798 } 20799 // If we're enabling a system stub, there's a little more work to do. 20800 // Prior to enabling the package, we need to decompress the APK(s) to the 20801 // data partition and then replace the version on the system partition. 20802 final PackageParser.Package deletedPkg = pkgSetting.pkg; 20803 final boolean isSystemStub = deletedPkg.isStub 20804 && deletedPkg.isSystem(); 20805 if (isSystemStub 20806 && (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20807 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED)) { 20808 if (!enableCompressedPackage(deletedPkg)) { 20809 return; 20810 } 20811 } 20812 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 20813 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 20814 // Don't care about who enables an app. 20815 callingPackage = null; 20816 } 20817 synchronized (mPackages) { 20818 pkgSetting.setEnabled(newState, userId, callingPackage); 20819 } 20820 } else { 20821 synchronized (mPackages) { 20822 // We're dealing with a component level state change 20823 // First, verify that this is a valid class name. 20824 PackageParser.Package pkg = pkgSetting.pkg; 20825 if (pkg == null || !pkg.hasComponentClassName(className)) { 20826 if (pkg != null && 20827 pkg.applicationInfo.targetSdkVersion >= 20828 Build.VERSION_CODES.JELLY_BEAN) { 20829 throw new IllegalArgumentException("Component class " + className 20830 + " does not exist in " + packageName); 20831 } else { 20832 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 20833 + className + " does not exist in " + packageName); 20834 } 20835 } 20836 switch (newState) { 20837 case COMPONENT_ENABLED_STATE_ENABLED: 20838 if (!pkgSetting.enableComponentLPw(className, userId)) { 20839 return; 20840 } 20841 break; 20842 case COMPONENT_ENABLED_STATE_DISABLED: 20843 if (!pkgSetting.disableComponentLPw(className, userId)) { 20844 return; 20845 } 20846 break; 20847 case COMPONENT_ENABLED_STATE_DEFAULT: 20848 if (!pkgSetting.restoreComponentLPw(className, userId)) { 20849 return; 20850 } 20851 break; 20852 default: 20853 Slog.e(TAG, "Invalid new component state: " + newState); 20854 return; 20855 } 20856 } 20857 } 20858 synchronized (mPackages) { 20859 scheduleWritePackageRestrictionsLocked(userId); 20860 updateSequenceNumberLP(pkgSetting, new int[] { userId }); 20861 final long callingId = Binder.clearCallingIdentity(); 20862 try { 20863 updateInstantAppInstallerLocked(packageName); 20864 } finally { 20865 Binder.restoreCallingIdentity(callingId); 20866 } 20867 components = mPendingBroadcasts.get(userId, packageName); 20868 final boolean newPackage = components == null; 20869 if (newPackage) { 20870 components = new ArrayList<>(); 20871 } 20872 if (!components.contains(componentName)) { 20873 components.add(componentName); 20874 } 20875 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 20876 sendNow = true; 20877 // Purge entry from pending broadcast list if another one exists already 20878 // since we are sending one right away. 20879 mPendingBroadcasts.remove(userId, packageName); 20880 } else { 20881 if (newPackage) { 20882 mPendingBroadcasts.put(userId, packageName, components); 20883 } 20884 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 20885 // Schedule a message - if it has been a "reasonably long time" since the 20886 // service started, send the broadcast with a delay of one second to avoid 20887 // delayed reactions from the receiver, else keep the default ten second delay 20888 // to avoid extreme thrashing on service startup. 20889 final long broadcastDelay = SystemClock.uptimeMillis() > mServiceStartWithDelay 20890 ? BROADCAST_DELAY 20891 : BROADCAST_DELAY_DURING_STARTUP; 20892 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, broadcastDelay); 20893 } 20894 } 20895 } 20896 20897 long callingId = Binder.clearCallingIdentity(); 20898 try { 20899 if (sendNow) { 20900 int packageUid = UserHandle.getUid(userId, pkgSetting.appId); 20901 sendPackageChangedBroadcast(packageName, 20902 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 20903 } 20904 } finally { 20905 Binder.restoreCallingIdentity(callingId); 20906 } 20907 } 20908 20909 @Override 20910 public void flushPackageRestrictionsAsUser(int userId) { 20911 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 20912 return; 20913 } 20914 if (!sUserManager.exists(userId)) { 20915 return; 20916 } 20917 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 20918 false /* checkShell */, "flushPackageRestrictions"); 20919 synchronized (mPackages) { 20920 mSettings.writePackageRestrictionsLPr(userId); 20921 mDirtyUsers.remove(userId); 20922 if (mDirtyUsers.isEmpty()) { 20923 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 20924 } 20925 } 20926 } 20927 20928 private void sendPackageChangedBroadcast(String packageName, 20929 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 20930 if (DEBUG_INSTALL) 20931 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 20932 + componentNames); 20933 Bundle extras = new Bundle(4); 20934 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 20935 String nameList[] = new String[componentNames.size()]; 20936 componentNames.toArray(nameList); 20937 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 20938 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 20939 extras.putInt(Intent.EXTRA_UID, packageUid); 20940 // If this is not reporting a change of the overall package, then only send it 20941 // to registered receivers. We don't want to launch a swath of apps for every 20942 // little component state change. 20943 final int flags = !componentNames.contains(packageName) 20944 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 20945 final int userId = UserHandle.getUserId(packageUid); 20946 final boolean isInstantApp = isInstantApp(packageName, userId); 20947 final int[] userIds = isInstantApp ? EMPTY_INT_ARRAY : new int[] { userId }; 20948 final int[] instantUserIds = isInstantApp ? new int[] { userId } : EMPTY_INT_ARRAY; 20949 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 20950 userIds, instantUserIds); 20951 } 20952 20953 @Override 20954 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 20955 if (!sUserManager.exists(userId)) return; 20956 final int callingUid = Binder.getCallingUid(); 20957 if (getInstantAppPackageName(callingUid) != null) { 20958 return; 20959 } 20960 final int permission = mContext.checkCallingOrSelfPermission( 20961 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 20962 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 20963 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 20964 true /* requireFullPermission */, true /* checkShell */, "stop package"); 20965 // writer 20966 synchronized (mPackages) { 20967 final PackageSetting ps = mSettings.mPackages.get(packageName); 20968 if (!filterAppAccessLPr(ps, callingUid, userId) 20969 && mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 20970 allowedByPermission, callingUid, userId)) { 20971 scheduleWritePackageRestrictionsLocked(userId); 20972 } 20973 } 20974 } 20975 20976 @Override 20977 public String getInstallerPackageName(String packageName) { 20978 final int callingUid = Binder.getCallingUid(); 20979 synchronized (mPackages) { 20980 final PackageSetting ps = mSettings.mPackages.get(packageName); 20981 if (filterAppAccessLPr(ps, callingUid, UserHandle.getUserId(callingUid))) { 20982 return null; 20983 } 20984 // InstallerPackageName for Apex is not stored in PackageManager 20985 if (ps == null && mApexManager.isApexPackage(packageName)) { 20986 return null; 20987 } 20988 return mSettings.getInstallerPackageNameLPr(packageName); 20989 } 20990 } 20991 20992 public boolean isOrphaned(String packageName) { 20993 // reader 20994 synchronized (mPackages) { 20995 if (!mPackages.containsKey(packageName)) { 20996 return false; 20997 } 20998 return mSettings.isOrphaned(packageName); 20999 } 21000 } 21001 21002 @Override 21003 public int getApplicationEnabledSetting(String packageName, int userId) { 21004 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21005 int callingUid = Binder.getCallingUid(); 21006 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21007 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 21008 // reader 21009 synchronized (mPackages) { 21010 if (filterAppAccessLPr(mSettings.getPackageLPr(packageName), callingUid, userId)) { 21011 return COMPONENT_ENABLED_STATE_DISABLED; 21012 } 21013 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 21014 } 21015 } 21016 21017 @Override 21018 public int getComponentEnabledSetting(@NonNull ComponentName component, int userId) { 21019 if (component == null) return COMPONENT_ENABLED_STATE_DEFAULT; 21020 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 21021 int callingUid = Binder.getCallingUid(); 21022 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 21023 false /*requireFullPermission*/, false /*checkShell*/, "getComponentEnabled"); 21024 synchronized (mPackages) { 21025 if (filterAppAccessLPr(mSettings.getPackageLPr(component.getPackageName()), callingUid, 21026 component, TYPE_UNKNOWN, userId)) { 21027 return COMPONENT_ENABLED_STATE_DISABLED; 21028 } 21029 return mSettings.getComponentEnabledSettingLPr(component, userId); 21030 } 21031 } 21032 21033 @Override 21034 public void enterSafeMode() { 21035 enforceSystemOrRoot("Only the system can request entering safe mode"); 21036 21037 if (!mSystemReady) { 21038 mSafeMode = true; 21039 } 21040 } 21041 21042 @Override 21043 public void systemReady() { 21044 enforceSystemOrRoot("Only the system can claim the system is ready"); 21045 21046 mSystemReady = true; 21047 final ContentResolver resolver = mContext.getContentResolver(); 21048 ContentObserver co = new ContentObserver(mHandler) { 21049 @Override 21050 public void onChange(boolean selfChange) { 21051 final boolean ephemeralFeatureDisabled = 21052 Global.getInt(resolver, Global.ENABLE_EPHEMERAL_FEATURE, 1) == 0; 21053 for (int userId : UserManagerService.getInstance().getUserIds()) { 21054 final boolean instantAppsDisabledForUser = 21055 ephemeralFeatureDisabled || Secure.getIntForUser(resolver, 21056 Secure.INSTANT_APPS_ENABLED, 1, userId) == 0; 21057 mWebInstantAppsDisabled.put(userId, instantAppsDisabledForUser); 21058 } 21059 } 21060 }; 21061 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Global 21062 .getUriFor(Global.ENABLE_EPHEMERAL_FEATURE), 21063 false, co, UserHandle.USER_ALL); 21064 mContext.getContentResolver().registerContentObserver(android.provider.Settings.Secure 21065 .getUriFor(Secure.INSTANT_APPS_ENABLED), false, co, UserHandle.USER_ALL); 21066 co.onChange(true); 21067 21068 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 21069 // disabled after already being started. 21070 CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, 21071 UserHandle.USER_SYSTEM, mContext); 21072 21073 disableSkuSpecificApps(); 21074 21075 // Read the compatibilty setting when the system is ready. 21076 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 21077 mContext.getContentResolver(), 21078 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 21079 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 21080 21081 if (DEBUG_SETTINGS) { 21082 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 21083 } 21084 21085 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 21086 21087 synchronized (mPackages) { 21088 // Verify that all of the preferred activity components actually 21089 // exist. It is possible for applications to be updated and at 21090 // that point remove a previously declared activity component that 21091 // had been set as a preferred activity. We try to clean this up 21092 // the next time we encounter that preferred activity, but it is 21093 // possible for the user flow to never be able to return to that 21094 // situation so here we do a sanity check to make sure we haven't 21095 // left any junk around. 21096 ArrayList<PreferredActivity> removed = new ArrayList<>(); 21097 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21098 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21099 removed.clear(); 21100 for (PreferredActivity pa : pir.filterSet()) { 21101 if (!mComponentResolver.isActivityDefined(pa.mPref.mComponent)) { 21102 removed.add(pa); 21103 } 21104 } 21105 if (removed.size() > 0) { 21106 for (int r=0; r<removed.size(); r++) { 21107 PreferredActivity pa = removed.get(r); 21108 Slog.w(TAG, "Removing dangling preferred activity: " 21109 + pa.mPref.mComponent); 21110 pir.removeFilter(pa); 21111 } 21112 mSettings.writePackageRestrictionsLPr( 21113 mSettings.mPreferredActivities.keyAt(i)); 21114 } 21115 } 21116 21117 for (int userId : UserManagerService.getInstance().getUserIds()) { 21118 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 21119 grantPermissionsUserIds = ArrayUtils.appendInt( 21120 grantPermissionsUserIds, userId); 21121 } 21122 } 21123 } 21124 21125 sUserManager.systemReady(); 21126 // If we upgraded grant all default permissions before kicking off. 21127 for (int userId : grantPermissionsUserIds) { 21128 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 21129 } 21130 21131 if (grantPermissionsUserIds == EMPTY_INT_ARRAY) { 21132 // If we did not grant default permissions, we preload from this the 21133 // default permission exceptions lazily to ensure we don't hit the 21134 // disk on a new user creation. 21135 mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions(); 21136 } 21137 21138 // Now that we've scanned all packages, and granted any default 21139 // permissions, ensure permissions are updated. Beware of dragons if you 21140 // try optimizing this. 21141 synchronized (mPackages) { 21142 mPermissionManager.updateAllPermissions( 21143 StorageManager.UUID_PRIVATE_INTERNAL, false, mPackages.values(), 21144 mPermissionCallback); 21145 21146 final PermissionPolicyInternal permissionPolicyInternal = 21147 LocalServices.getService(PermissionPolicyInternal.class); 21148 permissionPolicyInternal.setOnInitializedCallback(userId -> { 21149 // The SDK updated case is already handled when we run during the ctor. 21150 synchronized (mPackages) { 21151 mPermissionManager.updateAllPermissions( 21152 StorageManager.UUID_PRIVATE_INTERNAL, false /*sdkUpdated*/, 21153 mPackages.values(), mPermissionCallback); 21154 } 21155 }); 21156 } 21157 21158 // Watch for external volumes that come and go over time 21159 final StorageManager storage = mContext.getSystemService(StorageManager.class); 21160 storage.registerListener(mStorageListener); 21161 21162 mInstallerService.systemReady(); 21163 mApexManager.systemReady(); 21164 mPackageDexOptimizer.systemReady(); 21165 21166 getStorageManagerInternal().addExternalStoragePolicy( 21167 new StorageManagerInternal.ExternalStorageMountPolicy() { 21168 @Override 21169 public int getMountMode(int uid, String packageName) { 21170 if (Process.isIsolated(uid)) { 21171 return Zygote.MOUNT_EXTERNAL_NONE; 21172 } 21173 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21174 return Zygote.MOUNT_EXTERNAL_DEFAULT; 21175 } 21176 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 21177 return Zygote.MOUNT_EXTERNAL_READ; 21178 } 21179 return Zygote.MOUNT_EXTERNAL_WRITE; 21180 } 21181 21182 @Override 21183 public boolean hasExternalStorage(int uid, String packageName) { 21184 return true; 21185 } 21186 }); 21187 21188 // Now that we're mostly running, clean up stale users and apps 21189 sUserManager.reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 21190 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 21191 21192 mPermissionManager.systemReady(); 21193 21194 if (mInstantAppResolverConnection != null) { 21195 mContext.registerReceiver(new BroadcastReceiver() { 21196 @Override 21197 public void onReceive(Context context, Intent intent) { 21198 mInstantAppResolverConnection.optimisticBind(); 21199 mContext.unregisterReceiver(this); 21200 } 21201 }, new IntentFilter(Intent.ACTION_BOOT_COMPLETED)); 21202 } 21203 21204 mModuleInfoProvider.systemReady(); 21205 21206 // Installer service might attempt to install some packages that have been staged for 21207 // installation on reboot. Make sure this is the last component to be call since the 21208 // installation might require other components to be ready. 21209 mInstallerService.restoreAndApplyStagedSessionIfNeeded(); 21210 } 21211 21212 public void waitForAppDataPrepared() { 21213 if (mPrepareAppDataFuture == null) { 21214 return; 21215 } 21216 ConcurrentUtils.waitForFutureNoInterrupt(mPrepareAppDataFuture, "wait for prepareAppData"); 21217 mPrepareAppDataFuture = null; 21218 } 21219 21220 @Override 21221 public boolean isSafeMode() { 21222 // allow instant applications 21223 return mSafeMode; 21224 } 21225 21226 @Override 21227 public boolean hasSystemUidErrors() { 21228 // allow instant applications 21229 return mHasSystemUidErrors; 21230 } 21231 21232 static String arrayToString(int[] array) { 21233 StringBuilder stringBuilder = new StringBuilder(128); 21234 stringBuilder.append('['); 21235 if (array != null) { 21236 for (int i=0; i<array.length; i++) { 21237 if (i > 0) stringBuilder.append(", "); 21238 stringBuilder.append(array[i]); 21239 } 21240 } 21241 stringBuilder.append(']'); 21242 return stringBuilder.toString(); 21243 } 21244 21245 @Override 21246 public void onShellCommand(FileDescriptor in, FileDescriptor out, 21247 FileDescriptor err, String[] args, ShellCallback callback, 21248 ResultReceiver resultReceiver) { 21249 (new PackageManagerShellCommand(this)).exec( 21250 this, in, out, err, args, callback, resultReceiver); 21251 } 21252 21253 @SuppressWarnings("resource") 21254 @Override 21255 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 21256 if (!DumpUtils.checkDumpAndUsageStatsPermission(mContext, TAG, pw)) return; 21257 21258 DumpState dumpState = new DumpState(); 21259 boolean fullPreferred = false; 21260 boolean checkin = false; 21261 21262 String packageName = null; 21263 ArraySet<String> permissionNames = null; 21264 21265 int opti = 0; 21266 while (opti < args.length) { 21267 String opt = args[opti]; 21268 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 21269 break; 21270 } 21271 opti++; 21272 21273 if ("-a".equals(opt)) { 21274 // Right now we only know how to print all. 21275 } else if ("-h".equals(opt)) { 21276 pw.println("Package manager dump options:"); 21277 pw.println(" [-h] [-f] [--checkin] [--all-components] [cmd] ..."); 21278 pw.println(" --checkin: dump for a checkin"); 21279 pw.println(" -f: print details of intent filters"); 21280 pw.println(" -h: print this help"); 21281 pw.println(" --all-components: include all component names in package dump"); 21282 pw.println(" cmd may be one of:"); 21283 pw.println(" apex: list active APEXes and APEX session state"); 21284 pw.println(" l[ibraries]: list known shared libraries"); 21285 pw.println(" f[eatures]: list device features"); 21286 pw.println(" k[eysets]: print known keysets"); 21287 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 21288 pw.println(" perm[issions]: dump permissions"); 21289 pw.println(" permission [name ...]: dump declaration and use of given permission"); 21290 pw.println(" pref[erred]: print preferred package settings"); 21291 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 21292 pw.println(" prov[iders]: dump content providers"); 21293 pw.println(" p[ackages]: dump installed packages"); 21294 pw.println(" s[hared-users]: dump shared user IDs"); 21295 pw.println(" m[essages]: print collected runtime messages"); 21296 pw.println(" v[erifiers]: print package verifier info"); 21297 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 21298 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 21299 pw.println(" version: print database version info"); 21300 pw.println(" write: write current settings now"); 21301 pw.println(" installs: details about install sessions"); 21302 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 21303 pw.println(" dexopt: dump dexopt state"); 21304 pw.println(" compiler-stats: dump compiler statistics"); 21305 pw.println(" service-permissions: dump permissions required by services"); 21306 pw.println(" <package.name>: info about given package"); 21307 return; 21308 } else if ("--checkin".equals(opt)) { 21309 checkin = true; 21310 } else if ("--all-components".equals(opt)) { 21311 dumpState.setOptionEnabled(DumpState.OPTION_DUMP_ALL_COMPONENTS); 21312 } else if ("-f".equals(opt)) { 21313 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21314 } else if ("--proto".equals(opt)) { 21315 dumpProto(fd); 21316 return; 21317 } else { 21318 pw.println("Unknown argument: " + opt + "; use -h for help"); 21319 } 21320 } 21321 21322 // Is the caller requesting to dump a particular piece of data? 21323 if (opti < args.length) { 21324 String cmd = args[opti]; 21325 opti++; 21326 // Is this a package name? 21327 if ("android".equals(cmd) || cmd.contains(".")) { 21328 packageName = cmd; 21329 // When dumping a single package, we always dump all of its 21330 // filter information since the amount of data will be reasonable. 21331 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 21332 } else if ("check-permission".equals(cmd)) { 21333 if (opti >= args.length) { 21334 pw.println("Error: check-permission missing permission argument"); 21335 return; 21336 } 21337 String perm = args[opti]; 21338 opti++; 21339 if (opti >= args.length) { 21340 pw.println("Error: check-permission missing package argument"); 21341 return; 21342 } 21343 21344 String pkg = args[opti]; 21345 opti++; 21346 int user = UserHandle.getUserId(Binder.getCallingUid()); 21347 if (opti < args.length) { 21348 try { 21349 user = Integer.parseInt(args[opti]); 21350 } catch (NumberFormatException e) { 21351 pw.println("Error: check-permission user argument is not a number: " 21352 + args[opti]); 21353 return; 21354 } 21355 } 21356 21357 // Normalize package name to handle renamed packages and static libs 21358 pkg = resolveInternalPackageNameLPr(pkg, PackageManager.VERSION_CODE_HIGHEST); 21359 21360 pw.println(checkPermission(perm, pkg, user)); 21361 return; 21362 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 21363 dumpState.setDump(DumpState.DUMP_LIBS); 21364 } else if ("f".equals(cmd) || "features".equals(cmd)) { 21365 dumpState.setDump(DumpState.DUMP_FEATURES); 21366 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 21367 if (opti >= args.length) { 21368 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 21369 | DumpState.DUMP_SERVICE_RESOLVERS 21370 | DumpState.DUMP_RECEIVER_RESOLVERS 21371 | DumpState.DUMP_CONTENT_RESOLVERS); 21372 } else { 21373 while (opti < args.length) { 21374 String name = args[opti]; 21375 if ("a".equals(name) || "activity".equals(name)) { 21376 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 21377 } else if ("s".equals(name) || "service".equals(name)) { 21378 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 21379 } else if ("r".equals(name) || "receiver".equals(name)) { 21380 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 21381 } else if ("c".equals(name) || "content".equals(name)) { 21382 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 21383 } else { 21384 pw.println("Error: unknown resolver table type: " + name); 21385 return; 21386 } 21387 opti++; 21388 } 21389 } 21390 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 21391 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 21392 } else if ("permission".equals(cmd)) { 21393 if (opti >= args.length) { 21394 pw.println("Error: permission requires permission name"); 21395 return; 21396 } 21397 permissionNames = new ArraySet<>(); 21398 while (opti < args.length) { 21399 permissionNames.add(args[opti]); 21400 opti++; 21401 } 21402 dumpState.setDump(DumpState.DUMP_PERMISSIONS 21403 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 21404 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 21405 dumpState.setDump(DumpState.DUMP_PREFERRED); 21406 } else if ("preferred-xml".equals(cmd)) { 21407 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 21408 if (opti < args.length && "--full".equals(args[opti])) { 21409 fullPreferred = true; 21410 opti++; 21411 } 21412 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 21413 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 21414 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 21415 dumpState.setDump(DumpState.DUMP_PACKAGES); 21416 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 21417 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 21418 if (opti < args.length && "noperm".equals(args[opti])) { 21419 dumpState.setOptionEnabled(DumpState.OPTION_SKIP_PERMISSIONS); 21420 } 21421 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 21422 dumpState.setDump(DumpState.DUMP_PROVIDERS); 21423 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 21424 dumpState.setDump(DumpState.DUMP_MESSAGES); 21425 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 21426 dumpState.setDump(DumpState.DUMP_VERIFIERS); 21427 } else if ("i".equals(cmd) || "ifv".equals(cmd) 21428 || "intent-filter-verifiers".equals(cmd)) { 21429 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 21430 } else if ("version".equals(cmd)) { 21431 dumpState.setDump(DumpState.DUMP_VERSION); 21432 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 21433 dumpState.setDump(DumpState.DUMP_KEYSETS); 21434 } else if ("installs".equals(cmd)) { 21435 dumpState.setDump(DumpState.DUMP_INSTALLS); 21436 } else if ("frozen".equals(cmd)) { 21437 dumpState.setDump(DumpState.DUMP_FROZEN); 21438 } else if ("volumes".equals(cmd)) { 21439 dumpState.setDump(DumpState.DUMP_VOLUMES); 21440 } else if ("dexopt".equals(cmd)) { 21441 dumpState.setDump(DumpState.DUMP_DEXOPT); 21442 } else if ("compiler-stats".equals(cmd)) { 21443 dumpState.setDump(DumpState.DUMP_COMPILER_STATS); 21444 } else if ("changes".equals(cmd)) { 21445 dumpState.setDump(DumpState.DUMP_CHANGES); 21446 } else if ("service-permissions".equals(cmd)) { 21447 dumpState.setDump(DumpState.DUMP_SERVICE_PERMISSIONS); 21448 } else if ("write".equals(cmd)) { 21449 synchronized (mPackages) { 21450 mSettings.writeLPr(); 21451 pw.println("Settings written."); 21452 return; 21453 } 21454 } 21455 } 21456 21457 if (checkin) { 21458 pw.println("vers,1"); 21459 } 21460 21461 // reader 21462 synchronized (mPackages) { 21463 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 21464 if (!checkin) { 21465 if (dumpState.onTitlePrinted()) 21466 pw.println(); 21467 pw.println("Database versions:"); 21468 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 21469 } 21470 } 21471 21472 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 21473 if (!checkin) { 21474 if (dumpState.onTitlePrinted()) 21475 pw.println(); 21476 pw.println("Verifiers:"); 21477 pw.print(" Required: "); 21478 pw.print(mRequiredVerifierPackage); 21479 pw.print(" (uid="); 21480 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21481 UserHandle.USER_SYSTEM)); 21482 pw.println(")"); 21483 } else if (mRequiredVerifierPackage != null) { 21484 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 21485 pw.print(","); 21486 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 21487 UserHandle.USER_SYSTEM)); 21488 } 21489 } 21490 21491 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 21492 packageName == null) { 21493 if (mIntentFilterVerifierComponent != null) { 21494 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21495 if (!checkin) { 21496 if (dumpState.onTitlePrinted()) 21497 pw.println(); 21498 pw.println("Intent Filter Verifier:"); 21499 pw.print(" Using: "); 21500 pw.print(verifierPackageName); 21501 pw.print(" (uid="); 21502 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21503 UserHandle.USER_SYSTEM)); 21504 pw.println(")"); 21505 } else if (verifierPackageName != null) { 21506 pw.print("ifv,"); pw.print(verifierPackageName); 21507 pw.print(","); 21508 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 21509 UserHandle.USER_SYSTEM)); 21510 } 21511 } else { 21512 pw.println(); 21513 pw.println("No Intent Filter Verifier available!"); 21514 } 21515 } 21516 21517 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 21518 boolean printedHeader = false; 21519 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 21520 while (it.hasNext()) { 21521 String libName = it.next(); 21522 LongSparseArray<SharedLibraryInfo> versionedLib 21523 = mSharedLibraries.get(libName); 21524 if (versionedLib == null) { 21525 continue; 21526 } 21527 final int versionCount = versionedLib.size(); 21528 for (int i = 0; i < versionCount; i++) { 21529 SharedLibraryInfo libraryInfo = versionedLib.valueAt(i); 21530 if (!checkin) { 21531 if (!printedHeader) { 21532 if (dumpState.onTitlePrinted()) 21533 pw.println(); 21534 pw.println("Libraries:"); 21535 printedHeader = true; 21536 } 21537 pw.print(" "); 21538 } else { 21539 pw.print("lib,"); 21540 } 21541 pw.print(libraryInfo.getName()); 21542 if (libraryInfo.isStatic()) { 21543 pw.print(" version=" + libraryInfo.getLongVersion()); 21544 } 21545 if (!checkin) { 21546 pw.print(" -> "); 21547 } 21548 if (libraryInfo.getPath() != null) { 21549 pw.print(" (jar) "); 21550 pw.print(libraryInfo.getPath()); 21551 } else { 21552 pw.print(" (apk) "); 21553 pw.print(libraryInfo.getPackageName()); 21554 } 21555 pw.println(); 21556 } 21557 } 21558 } 21559 21560 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 21561 if (dumpState.onTitlePrinted()) 21562 pw.println(); 21563 if (!checkin) { 21564 pw.println("Features:"); 21565 } 21566 21567 synchronized (mAvailableFeatures) { 21568 for (FeatureInfo feat : mAvailableFeatures.values()) { 21569 if (checkin) { 21570 pw.print("feat,"); 21571 pw.print(feat.name); 21572 pw.print(","); 21573 pw.println(feat.version); 21574 } else { 21575 pw.print(" "); 21576 pw.print(feat.name); 21577 if (feat.version > 0) { 21578 pw.print(" version="); 21579 pw.print(feat.version); 21580 } 21581 pw.println(); 21582 } 21583 } 21584 } 21585 } 21586 21587 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 21588 mComponentResolver.dumpActivityResolvers(pw, dumpState, packageName); 21589 } 21590 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 21591 mComponentResolver.dumpReceiverResolvers(pw, dumpState, packageName); 21592 } 21593 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 21594 mComponentResolver.dumpServiceResolvers(pw, dumpState, packageName); 21595 } 21596 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 21597 mComponentResolver.dumpProviderResolvers(pw, dumpState, packageName); 21598 } 21599 21600 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 21601 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 21602 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 21603 int user = mSettings.mPreferredActivities.keyAt(i); 21604 if (pir.dump(pw, 21605 dumpState.getTitlePrinted() 21606 ? "\nPreferred Activities User " + user + ":" 21607 : "Preferred Activities User " + user + ":", " ", 21608 packageName, true, false)) { 21609 dumpState.setTitlePrinted(true); 21610 } 21611 } 21612 } 21613 21614 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 21615 pw.flush(); 21616 FileOutputStream fout = new FileOutputStream(fd); 21617 BufferedOutputStream str = new BufferedOutputStream(fout); 21618 XmlSerializer serializer = new FastXmlSerializer(); 21619 try { 21620 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 21621 serializer.startDocument(null, true); 21622 serializer.setFeature( 21623 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 21624 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 21625 serializer.endDocument(); 21626 serializer.flush(); 21627 } catch (IllegalArgumentException e) { 21628 pw.println("Failed writing: " + e); 21629 } catch (IllegalStateException e) { 21630 pw.println("Failed writing: " + e); 21631 } catch (IOException e) { 21632 pw.println("Failed writing: " + e); 21633 } 21634 } 21635 21636 if (!checkin 21637 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 21638 && packageName == null) { 21639 pw.println(); 21640 int count = mSettings.mPackages.size(); 21641 if (count == 0) { 21642 pw.println("No applications!"); 21643 pw.println(); 21644 } else { 21645 final String prefix = " "; 21646 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 21647 if (allPackageSettings.size() == 0) { 21648 pw.println("No domain preferred apps!"); 21649 pw.println(); 21650 } else { 21651 pw.println("App verification status:"); 21652 pw.println(); 21653 count = 0; 21654 for (PackageSetting ps : allPackageSettings) { 21655 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 21656 if (ivi == null || ivi.getPackageName() == null) continue; 21657 pw.println(prefix + "Package: " + ivi.getPackageName()); 21658 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 21659 pw.println(prefix + "Status: " + ivi.getStatusString()); 21660 pw.println(); 21661 count++; 21662 } 21663 if (count == 0) { 21664 pw.println(prefix + "No app verification established."); 21665 pw.println(); 21666 } 21667 for (int userId : sUserManager.getUserIds()) { 21668 pw.println("App linkages for user " + userId + ":"); 21669 pw.println(); 21670 count = 0; 21671 for (PackageSetting ps : allPackageSettings) { 21672 final long status = ps.getDomainVerificationStatusForUser(userId); 21673 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED 21674 && !DEBUG_DOMAIN_VERIFICATION) { 21675 continue; 21676 } 21677 pw.println(prefix + "Package: " + ps.name); 21678 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 21679 String statusStr = IntentFilterVerificationInfo. 21680 getStatusStringFromValue(status); 21681 pw.println(prefix + "Status: " + statusStr); 21682 pw.println(); 21683 count++; 21684 } 21685 if (count == 0) { 21686 pw.println(prefix + "No configured app linkages."); 21687 pw.println(); 21688 } 21689 } 21690 } 21691 } 21692 } 21693 21694 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 21695 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 21696 } 21697 21698 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 21699 mComponentResolver.dumpContentProviders(pw, dumpState, packageName); 21700 } 21701 21702 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 21703 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 21704 } 21705 21706 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 21707 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 21708 21709 boolean systemUserPackagesBlacklistSupported = 21710 isSystemUserPackagesBlacklistSupported(); 21711 pw.println("isSystemUserPackagesBlacklistSupported: " 21712 + systemUserPackagesBlacklistSupported); 21713 if (systemUserPackagesBlacklistSupported) { 21714 SystemConfig sysconfig = SystemConfig.getInstance(); 21715 dumpPackagesList(pw, " ", "whitelist", 21716 sysconfig.getSystemUserWhitelistedApps()); 21717 dumpPackagesList(pw, " ", "blacklist", 21718 sysconfig.getSystemUserBlacklistedApps()); 21719 } 21720 } 21721 21722 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 21723 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 21724 } 21725 21726 if (dumpState.isDumping(DumpState.DUMP_CHANGES)) { 21727 if (dumpState.onTitlePrinted()) pw.println(); 21728 pw.println("Package Changes:"); 21729 pw.print(" Sequence number="); pw.println(mChangedPackagesSequenceNumber); 21730 final int K = mChangedPackages.size(); 21731 for (int i = 0; i < K; i++) { 21732 final SparseArray<String> changes = mChangedPackages.valueAt(i); 21733 pw.print(" User "); pw.print(mChangedPackages.keyAt(i)); pw.println(":"); 21734 final int N = changes.size(); 21735 if (N == 0) { 21736 pw.print(" "); pw.println("No packages changed"); 21737 } else { 21738 for (int j = 0; j < N; j++) { 21739 final String pkgName = changes.valueAt(j); 21740 final int sequenceNumber = changes.keyAt(j); 21741 pw.print(" "); 21742 pw.print("seq="); 21743 pw.print(sequenceNumber); 21744 pw.print(", package="); 21745 pw.println(pkgName); 21746 } 21747 } 21748 } 21749 } 21750 21751 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 21752 // XXX should handle packageName != null by dumping only install data that 21753 // the given package is involved with. 21754 if (dumpState.onTitlePrinted()) pw.println(); 21755 21756 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21757 ipw.println(); 21758 ipw.println("Frozen packages:"); 21759 ipw.increaseIndent(); 21760 if (mFrozenPackages.size() == 0) { 21761 ipw.println("(none)"); 21762 } else { 21763 for (int i = 0; i < mFrozenPackages.size(); i++) { 21764 ipw.println(mFrozenPackages.valueAt(i)); 21765 } 21766 } 21767 ipw.decreaseIndent(); 21768 } 21769 21770 if (!checkin && dumpState.isDumping(DumpState.DUMP_VOLUMES) && packageName == null) { 21771 if (dumpState.onTitlePrinted()) pw.println(); 21772 21773 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 21774 ipw.println(); 21775 ipw.println("Loaded volumes:"); 21776 ipw.increaseIndent(); 21777 if (mLoadedVolumes.size() == 0) { 21778 ipw.println("(none)"); 21779 } else { 21780 for (int i = 0; i < mLoadedVolumes.size(); i++) { 21781 ipw.println(mLoadedVolumes.valueAt(i)); 21782 } 21783 } 21784 ipw.decreaseIndent(); 21785 } 21786 21787 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_PERMISSIONS) 21788 && packageName == null) { 21789 mComponentResolver.dumpServicePermissions(pw, dumpState, packageName); 21790 } 21791 21792 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 21793 if (dumpState.onTitlePrinted()) pw.println(); 21794 dumpDexoptStateLPr(pw, packageName); 21795 } 21796 21797 if (!checkin && dumpState.isDumping(DumpState.DUMP_COMPILER_STATS)) { 21798 if (dumpState.onTitlePrinted()) pw.println(); 21799 dumpCompilerStatsLPr(pw, packageName); 21800 } 21801 21802 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 21803 if (dumpState.onTitlePrinted()) pw.println(); 21804 mSettings.dumpReadMessagesLPr(pw, dumpState); 21805 21806 pw.println(); 21807 pw.println("Package warning messages:"); 21808 dumpCriticalInfo(pw, null); 21809 } 21810 21811 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 21812 dumpCriticalInfo(pw, "msg,"); 21813 } 21814 } 21815 21816 // PackageInstaller should be called outside of mPackages lock 21817 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 21818 // XXX should handle packageName != null by dumping only install data that 21819 // the given package is involved with. 21820 if (dumpState.onTitlePrinted()) pw.println(); 21821 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 21822 } 21823 21824 if (!checkin && dumpState.isDumping(DumpState.DUMP_APEX)) { 21825 mApexManager.dump(pw, packageName); 21826 } 21827 } 21828 21829 private void dumpPackagesList(PrintWriter pw, String prefix, String name, 21830 ArraySet<String> list) { 21831 pw.print(prefix); pw.print(name); pw.print(": "); 21832 int size = list.size(); 21833 if (size == 0) { 21834 pw.println("empty"); 21835 return; 21836 } 21837 pw.print(size); pw.println(" packages"); 21838 String prefix2 = prefix + " "; 21839 for (int i = 0; i < size; i++) { 21840 pw.print(prefix2); pw.println(list.valueAt(i)); 21841 } 21842 } 21843 21844 //TODO: b/111402650 21845 private void disableSkuSpecificApps() { 21846 String apkList[] = mContext.getResources().getStringArray( 21847 R.array.config_disableApksUnlessMatchedSku_apk_list); 21848 String skuArray[] = mContext.getResources().getStringArray( 21849 R.array.config_disableApkUnlessMatchedSku_skus_list); 21850 if (ArrayUtils.isEmpty(apkList)) { 21851 return; 21852 } 21853 String sku = SystemProperties.get("ro.boot.hardware.sku"); 21854 if (!TextUtils.isEmpty(sku) && ArrayUtils.contains(skuArray, sku)) { 21855 return; 21856 } 21857 for (String packageName : apkList) { 21858 setSystemAppHiddenUntilInstalled(packageName, true); 21859 for (UserInfo user : sUserManager.getUsers(false)) { 21860 setSystemAppInstallState(packageName, false, user.id); 21861 } 21862 } 21863 } 21864 21865 private void dumpProto(FileDescriptor fd) { 21866 final ProtoOutputStream proto = new ProtoOutputStream(fd); 21867 21868 synchronized (mPackages) { 21869 final long requiredVerifierPackageToken = 21870 proto.start(PackageServiceDumpProto.REQUIRED_VERIFIER_PACKAGE); 21871 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, mRequiredVerifierPackage); 21872 proto.write( 21873 PackageServiceDumpProto.PackageShortProto.UID, 21874 getPackageUid( 21875 mRequiredVerifierPackage, 21876 MATCH_DEBUG_TRIAGED_MISSING, 21877 UserHandle.USER_SYSTEM)); 21878 proto.end(requiredVerifierPackageToken); 21879 21880 if (mIntentFilterVerifierComponent != null) { 21881 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 21882 final long verifierPackageToken = 21883 proto.start(PackageServiceDumpProto.VERIFIER_PACKAGE); 21884 proto.write(PackageServiceDumpProto.PackageShortProto.NAME, verifierPackageName); 21885 proto.write( 21886 PackageServiceDumpProto.PackageShortProto.UID, 21887 getPackageUid( 21888 verifierPackageName, 21889 MATCH_DEBUG_TRIAGED_MISSING, 21890 UserHandle.USER_SYSTEM)); 21891 proto.end(verifierPackageToken); 21892 } 21893 21894 dumpSharedLibrariesProto(proto); 21895 dumpFeaturesProto(proto); 21896 mSettings.dumpPackagesProto(proto); 21897 mSettings.dumpSharedUsersProto(proto); 21898 dumpCriticalInfo(proto); 21899 } 21900 proto.flush(); 21901 } 21902 21903 private void dumpFeaturesProto(ProtoOutputStream proto) { 21904 synchronized (mAvailableFeatures) { 21905 final int count = mAvailableFeatures.size(); 21906 for (int i = 0; i < count; i++) { 21907 mAvailableFeatures.valueAt(i).writeToProto(proto, PackageServiceDumpProto.FEATURES); 21908 } 21909 } 21910 } 21911 21912 private void dumpSharedLibrariesProto(ProtoOutputStream proto) { 21913 final int count = mSharedLibraries.size(); 21914 for (int i = 0; i < count; i++) { 21915 final String libName = mSharedLibraries.keyAt(i); 21916 LongSparseArray<SharedLibraryInfo> versionedLib = mSharedLibraries.get(libName); 21917 if (versionedLib == null) { 21918 continue; 21919 } 21920 final int versionCount = versionedLib.size(); 21921 for (int j = 0; j < versionCount; j++) { 21922 final SharedLibraryInfo libraryInfo = versionedLib.valueAt(j); 21923 final long sharedLibraryToken = 21924 proto.start(PackageServiceDumpProto.SHARED_LIBRARIES); 21925 proto.write(PackageServiceDumpProto.SharedLibraryProto.NAME, libraryInfo.getName()); 21926 final boolean isJar = (libraryInfo.getPath() != null); 21927 proto.write(PackageServiceDumpProto.SharedLibraryProto.IS_JAR, isJar); 21928 if (isJar) { 21929 proto.write(PackageServiceDumpProto.SharedLibraryProto.PATH, 21930 libraryInfo.getPath()); 21931 } else { 21932 proto.write(PackageServiceDumpProto.SharedLibraryProto.APK, 21933 libraryInfo.getPackageName()); 21934 } 21935 proto.end(sharedLibraryToken); 21936 } 21937 } 21938 } 21939 21940 @GuardedBy("mPackages") 21941 @SuppressWarnings("resource") 21942 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 21943 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21944 ipw.println(); 21945 ipw.println("Dexopt state:"); 21946 ipw.increaseIndent(); 21947 Collection<PackageParser.Package> packages; 21948 if (packageName != null) { 21949 PackageParser.Package targetPackage = mPackages.get(packageName); 21950 if (targetPackage != null) { 21951 packages = Collections.singletonList(targetPackage); 21952 } else { 21953 ipw.println("Unable to find package: " + packageName); 21954 return; 21955 } 21956 } else { 21957 packages = mPackages.values(); 21958 } 21959 21960 for (PackageParser.Package pkg : packages) { 21961 ipw.println("[" + pkg.packageName + "]"); 21962 ipw.increaseIndent(); 21963 mPackageDexOptimizer.dumpDexoptState(ipw, pkg, 21964 mDexManager.getPackageUseInfoOrDefault(pkg.packageName)); 21965 ipw.decreaseIndent(); 21966 } 21967 } 21968 21969 @GuardedBy("mPackages") 21970 @SuppressWarnings("resource") 21971 private void dumpCompilerStatsLPr(PrintWriter pw, String packageName) { 21972 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 21973 ipw.println(); 21974 ipw.println("Compiler stats:"); 21975 ipw.increaseIndent(); 21976 Collection<PackageParser.Package> packages; 21977 if (packageName != null) { 21978 PackageParser.Package targetPackage = mPackages.get(packageName); 21979 if (targetPackage != null) { 21980 packages = Collections.singletonList(targetPackage); 21981 } else { 21982 ipw.println("Unable to find package: " + packageName); 21983 return; 21984 } 21985 } else { 21986 packages = mPackages.values(); 21987 } 21988 21989 for (PackageParser.Package pkg : packages) { 21990 ipw.println("[" + pkg.packageName + "]"); 21991 ipw.increaseIndent(); 21992 21993 CompilerStats.PackageStats stats = getCompilerPackageStats(pkg.packageName); 21994 if (stats == null) { 21995 ipw.println("(No recorded stats)"); 21996 } else { 21997 stats.dump(ipw); 21998 } 21999 ipw.decreaseIndent(); 22000 } 22001 } 22002 22003 private String dumpDomainString(String packageName) { 22004 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 22005 .getList(); 22006 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 22007 22008 ArraySet<String> result = new ArraySet<>(); 22009 if (iviList.size() > 0) { 22010 for (IntentFilterVerificationInfo ivi : iviList) { 22011 result.addAll(ivi.getDomains()); 22012 } 22013 } 22014 if (filters != null && filters.size() > 0) { 22015 for (IntentFilter filter : filters) { 22016 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 22017 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 22018 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 22019 result.addAll(filter.getHostsList()); 22020 } 22021 } 22022 } 22023 22024 StringBuilder sb = new StringBuilder(result.size() * 16); 22025 for (String domain : result) { 22026 if (sb.length() > 0) sb.append(" "); 22027 sb.append(domain); 22028 } 22029 return sb.toString(); 22030 } 22031 22032 // ------- apps on sdcard specific code ------- 22033 static final boolean DEBUG_SD_INSTALL = false; 22034 22035 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 22036 22037 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 22038 22039 private boolean mMediaMounted = false; 22040 22041 static String getEncryptKey() { 22042 try { 22043 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 22044 SD_ENCRYPTION_KEYSTORE_NAME); 22045 if (sdEncKey == null) { 22046 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 22047 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 22048 if (sdEncKey == null) { 22049 Slog.e(TAG, "Failed to create encryption keys"); 22050 return null; 22051 } 22052 } 22053 return sdEncKey; 22054 } catch (NoSuchAlgorithmException nsae) { 22055 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 22056 return null; 22057 } catch (IOException ioe) { 22058 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 22059 return null; 22060 } 22061 } 22062 22063 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22064 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 22065 final int size = infos.size(); 22066 final String[] packageNames = new String[size]; 22067 final int[] packageUids = new int[size]; 22068 for (int i = 0; i < size; i++) { 22069 final ApplicationInfo info = infos.get(i); 22070 packageNames[i] = info.packageName; 22071 packageUids[i] = info.uid; 22072 } 22073 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 22074 finishedReceiver); 22075 } 22076 22077 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22078 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22079 sendResourcesChangedBroadcast(mediaStatus, replacing, 22080 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 22081 } 22082 22083 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 22084 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 22085 int size = pkgList.length; 22086 if (size > 0) { 22087 // Send broadcasts here 22088 Bundle extras = new Bundle(); 22089 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 22090 if (uidArr != null) { 22091 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 22092 } 22093 if (replacing) { 22094 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 22095 } 22096 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 22097 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 22098 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null, null); 22099 } 22100 } 22101 22102 private void loadPrivatePackages(final VolumeInfo vol) { 22103 mHandler.post(() -> loadPrivatePackagesInner(vol)); 22104 } 22105 22106 private void loadPrivatePackagesInner(VolumeInfo vol) { 22107 final String volumeUuid = vol.fsUuid; 22108 if (TextUtils.isEmpty(volumeUuid)) { 22109 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 22110 return; 22111 } 22112 22113 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 22114 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 22115 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 22116 22117 final VersionInfo ver; 22118 final List<PackageSetting> packages; 22119 synchronized (mPackages) { 22120 ver = mSettings.findOrCreateVersion(volumeUuid); 22121 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22122 } 22123 22124 for (PackageSetting ps : packages) { 22125 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 22126 synchronized (mInstallLock) { 22127 final PackageParser.Package pkg; 22128 try { 22129 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 22130 loaded.add(pkg.applicationInfo); 22131 22132 } catch (PackageManagerException e) { 22133 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 22134 } 22135 22136 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 22137 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, FLAG_STORAGE_DE | FLAG_STORAGE_CE 22138 | FLAG_STORAGE_EXTERNAL | Installer.FLAG_CLEAR_CODE_CACHE_ONLY 22139 | Installer.FLAG_CLEAR_APP_DATA_KEEP_ART_PROFILES); 22140 } 22141 } 22142 } 22143 22144 // Reconcile app data for all started/unlocked users 22145 final StorageManager sm = mContext.getSystemService(StorageManager.class); 22146 final UserManager um = mContext.getSystemService(UserManager.class); 22147 UserManagerInternal umInternal = getUserManagerInternal(); 22148 for (UserInfo user : um.getUsers()) { 22149 final int flags; 22150 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22151 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22152 } else if (umInternal.isUserRunning(user.id)) { 22153 flags = StorageManager.FLAG_STORAGE_DE; 22154 } else { 22155 continue; 22156 } 22157 22158 try { 22159 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 22160 synchronized (mInstallLock) { 22161 reconcileAppsDataLI(volumeUuid, user.id, flags, true /* migrateAppData */); 22162 } 22163 } catch (IllegalStateException e) { 22164 // Device was probably ejected, and we'll process that event momentarily 22165 Slog.w(TAG, "Failed to prepare storage: " + e); 22166 } 22167 } 22168 22169 synchronized (mPackages) { 22170 final boolean sdkUpdated = (ver.sdkVersion != mSdkVersion); 22171 if (sdkUpdated) { 22172 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 22173 + mSdkVersion + "; regranting permissions for " + volumeUuid); 22174 } 22175 mPermissionManager.updateAllPermissions(volumeUuid, sdkUpdated, mPackages.values(), 22176 mPermissionCallback); 22177 22178 // Yay, everything is now upgraded 22179 ver.forceCurrent(); 22180 22181 mSettings.writeLPr(); 22182 } 22183 22184 for (PackageFreezer freezer : freezers) { 22185 freezer.close(); 22186 } 22187 22188 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 22189 sendResourcesChangedBroadcast(true, false, loaded, null); 22190 mLoadedVolumes.add(vol.getId()); 22191 } 22192 22193 private void unloadPrivatePackages(final VolumeInfo vol) { 22194 mHandler.post(() -> unloadPrivatePackagesInner(vol)); 22195 } 22196 22197 private void unloadPrivatePackagesInner(VolumeInfo vol) { 22198 final String volumeUuid = vol.fsUuid; 22199 if (TextUtils.isEmpty(volumeUuid)) { 22200 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 22201 return; 22202 } 22203 22204 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 22205 synchronized (mInstallLock) { 22206 synchronized (mPackages) { 22207 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 22208 for (PackageSetting ps : packages) { 22209 if (ps.pkg == null) continue; 22210 22211 final ApplicationInfo info = ps.pkg.applicationInfo; 22212 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 22213 final PackageRemovedInfo outInfo = new PackageRemovedInfo(this); 22214 22215 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 22216 "unloadPrivatePackagesInner")) { 22217 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 22218 false, null)) { 22219 unloaded.add(info); 22220 } else { 22221 Slog.w(TAG, "Failed to unload " + ps.codePath); 22222 } 22223 } 22224 22225 // Try very hard to release any references to this package 22226 // so we don't risk the system server being killed due to 22227 // open FDs 22228 AttributeCache.instance().removePackage(ps.name); 22229 } 22230 22231 mSettings.writeLPr(); 22232 } 22233 } 22234 22235 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 22236 sendResourcesChangedBroadcast(false, false, unloaded, null); 22237 mLoadedVolumes.remove(vol.getId()); 22238 22239 // Try very hard to release any references to this path so we don't risk 22240 // the system server being killed due to open FDs 22241 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 22242 22243 for (int i = 0; i < 3; i++) { 22244 System.gc(); 22245 System.runFinalization(); 22246 } 22247 } 22248 22249 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 22250 throws PackageManagerException { 22251 synchronized (mPackages) { 22252 // Normalize package name to handle renamed packages 22253 packageName = normalizePackageNameLPr(packageName); 22254 22255 final PackageSetting ps = mSettings.mPackages.get(packageName); 22256 if (ps == null) { 22257 throw new PackageManagerException("Package " + packageName + " is unknown"); 22258 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 22259 throw new PackageManagerException( 22260 "Package " + packageName + " found on unknown volume " + volumeUuid 22261 + "; expected volume " + ps.volumeUuid); 22262 } else if (!ps.getInstalled(userId)) { 22263 throw new PackageManagerException( 22264 "Package " + packageName + " not installed for user " + userId); 22265 } 22266 } 22267 } 22268 22269 private List<String> collectAbsoluteCodePaths() { 22270 synchronized (mPackages) { 22271 List<String> codePaths = new ArrayList<>(); 22272 final int packageCount = mSettings.mPackages.size(); 22273 for (int i = 0; i < packageCount; i++) { 22274 final PackageSetting ps = mSettings.mPackages.valueAt(i); 22275 codePaths.add(ps.codePath.getAbsolutePath()); 22276 } 22277 return codePaths; 22278 } 22279 } 22280 22281 /** 22282 * Examine all apps present on given mounted volume, and destroy apps that 22283 * aren't expected, either due to uninstallation or reinstallation on 22284 * another volume. 22285 */ 22286 private void reconcileApps(String volumeUuid) { 22287 List<String> absoluteCodePaths = collectAbsoluteCodePaths(); 22288 List<File> filesToDelete = null; 22289 22290 final File[] files = FileUtils.listFilesOrEmpty( 22291 Environment.getDataAppDirectory(volumeUuid)); 22292 for (File file : files) { 22293 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 22294 && !PackageInstallerService.isStageName(file.getName()); 22295 if (!isPackage) { 22296 // Ignore entries which are not packages 22297 continue; 22298 } 22299 22300 String absolutePath = file.getAbsolutePath(); 22301 22302 boolean pathValid = false; 22303 final int absoluteCodePathCount = absoluteCodePaths.size(); 22304 for (int i = 0; i < absoluteCodePathCount; i++) { 22305 String absoluteCodePath = absoluteCodePaths.get(i); 22306 if (absolutePath.startsWith(absoluteCodePath)) { 22307 pathValid = true; 22308 break; 22309 } 22310 } 22311 22312 if (!pathValid) { 22313 if (filesToDelete == null) { 22314 filesToDelete = new ArrayList<>(); 22315 } 22316 filesToDelete.add(file); 22317 } 22318 } 22319 22320 if (filesToDelete != null) { 22321 final int fileToDeleteCount = filesToDelete.size(); 22322 for (int i = 0; i < fileToDeleteCount; i++) { 22323 File fileToDelete = filesToDelete.get(i); 22324 logCriticalInfo(Log.WARN, "Destroying orphaned" + fileToDelete); 22325 synchronized (mInstallLock) { 22326 removeCodePathLI(fileToDelete); 22327 } 22328 } 22329 } 22330 } 22331 22332 /** 22333 * Reconcile all app data for the given user. 22334 * <p> 22335 * Verifies that directories exist and that ownership and labeling is 22336 * correct for all installed apps on all mounted volumes. 22337 */ 22338 void reconcileAppsData(int userId, int flags, boolean migrateAppsData) { 22339 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22340 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 22341 final String volumeUuid = vol.getFsUuid(); 22342 synchronized (mInstallLock) { 22343 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppsData); 22344 } 22345 } 22346 } 22347 22348 @GuardedBy("mInstallLock") 22349 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22350 boolean migrateAppData) { 22351 reconcileAppsDataLI(volumeUuid, userId, flags, migrateAppData, false /* onlyCoreApps */); 22352 } 22353 22354 /** 22355 * Reconcile all app data on given mounted volume. 22356 * <p> 22357 * Destroys app data that isn't expected, either due to uninstallation or 22358 * reinstallation on another volume. 22359 * <p> 22360 * Verifies that directories exist and that ownership and labeling is 22361 * correct for all installed apps. 22362 * @return list of skipped non-core packages (if {@code onlyCoreApps} is true) 22363 */ 22364 @GuardedBy("mInstallLock") 22365 private List<String> reconcileAppsDataLI(String volumeUuid, int userId, int flags, 22366 boolean migrateAppData, boolean onlyCoreApps) { 22367 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 22368 + Integer.toHexString(flags) + " migrateAppData=" + migrateAppData); 22369 List<String> result = onlyCoreApps ? new ArrayList<>() : null; 22370 22371 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 22372 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 22373 22374 // First look for stale data that doesn't belong, and check if things 22375 // have changed since we did our last restorecon 22376 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22377 if (StorageManager.isFileEncryptedNativeOrEmulated() 22378 && !StorageManager.isUserKeyUnlocked(userId)) { 22379 throw new RuntimeException( 22380 "Yikes, someone asked us to reconcile CE storage while " + userId 22381 + " was still locked; this would have caused massive data loss!"); 22382 } 22383 22384 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 22385 for (File file : files) { 22386 final String packageName = file.getName(); 22387 try { 22388 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22389 } catch (PackageManagerException e) { 22390 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22391 try { 22392 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22393 StorageManager.FLAG_STORAGE_CE, 0); 22394 } catch (InstallerException e2) { 22395 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22396 } 22397 } 22398 } 22399 } 22400 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 22401 final File[] files = FileUtils.listFilesOrEmpty(deDir); 22402 for (File file : files) { 22403 final String packageName = file.getName(); 22404 try { 22405 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 22406 } catch (PackageManagerException e) { 22407 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 22408 try { 22409 mInstaller.destroyAppData(volumeUuid, packageName, userId, 22410 StorageManager.FLAG_STORAGE_DE, 0); 22411 } catch (InstallerException e2) { 22412 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 22413 } 22414 } 22415 } 22416 } 22417 22418 // Ensure that data directories are ready to roll for all packages 22419 // installed for this volume and user 22420 final List<PackageSetting> packages; 22421 synchronized (mPackages) { 22422 packages = mSettings.getVolumePackagesLPr(volumeUuid); 22423 } 22424 int preparedCount = 0; 22425 for (PackageSetting ps : packages) { 22426 final String packageName = ps.name; 22427 if (ps.pkg == null) { 22428 Slog.w(TAG, "Odd, missing scanned package " + packageName); 22429 // TODO: might be due to legacy ASEC apps; we should circle back 22430 // and reconcile again once they're scanned 22431 continue; 22432 } 22433 // Skip non-core apps if requested 22434 if (onlyCoreApps && !ps.pkg.coreApp) { 22435 result.add(packageName); 22436 continue; 22437 } 22438 22439 if (ps.getInstalled(userId)) { 22440 prepareAppDataAndMigrateLIF(ps.pkg, userId, flags, migrateAppData); 22441 preparedCount++; 22442 } 22443 } 22444 22445 Slog.v(TAG, "reconcileAppsData finished " + preparedCount + " packages"); 22446 return result; 22447 } 22448 22449 /** 22450 * Prepare app data for the given app just after it was installed or 22451 * upgraded. This method carefully only touches users that it's installed 22452 * for, and it forces a restorecon to handle any seinfo changes. 22453 * <p> 22454 * Verifies that directories exist and that ownership and labeling is 22455 * correct for all installed apps. If there is an ownership mismatch, it 22456 * will try recovering system apps by wiping data; third-party app data is 22457 * left intact. 22458 * <p> 22459 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 22460 */ 22461 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 22462 final PackageSetting ps; 22463 synchronized (mPackages) { 22464 ps = mSettings.mPackages.get(pkg.packageName); 22465 mSettings.writeKernelMappingLPr(ps); 22466 } 22467 22468 final UserManagerService um = sUserManager; 22469 UserManagerInternal umInternal = getUserManagerInternal(); 22470 for (UserInfo user : um.getUsers(false /* excludeDying */)) { 22471 final int flags; 22472 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 22473 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 22474 } else if (umInternal.isUserRunning(user.id)) { 22475 flags = StorageManager.FLAG_STORAGE_DE; 22476 } else { 22477 continue; 22478 } 22479 22480 if (ps.getInstalled(user.id)) { 22481 // TODO: when user data is locked, mark that we're still dirty 22482 prepareAppDataLIF(pkg, user.id, flags); 22483 } 22484 } 22485 } 22486 22487 /** 22488 * Prepare app data for the given app. 22489 * <p> 22490 * Verifies that directories exist and that ownership and labeling is 22491 * correct for all installed apps. If there is an ownership mismatch, this 22492 * will try recovering system apps by wiping data; third-party app data is 22493 * left intact. 22494 */ 22495 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 22496 if (pkg == null) { 22497 Slog.wtf(TAG, "Package was null!", new Throwable()); 22498 return; 22499 } 22500 prepareAppDataLeafLIF(pkg, userId, flags); 22501 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22502 for (int i = 0; i < childCount; i++) { 22503 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 22504 } 22505 } 22506 22507 private void prepareAppDataAndMigrateLIF(PackageParser.Package pkg, int userId, int flags, 22508 boolean maybeMigrateAppData) { 22509 prepareAppDataLIF(pkg, userId, flags); 22510 22511 if (maybeMigrateAppData && maybeMigrateAppDataLIF(pkg, userId)) { 22512 // We may have just shuffled around app data directories, so 22513 // prepare them one more time 22514 prepareAppDataLIF(pkg, userId, flags); 22515 } 22516 } 22517 22518 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22519 if (DEBUG_APP_DATA) { 22520 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 22521 + Integer.toHexString(flags)); 22522 } 22523 22524 final PackageSetting ps; 22525 synchronized (mPackages) { 22526 ps = mSettings.mPackages.get(pkg.packageName); 22527 } 22528 final String volumeUuid = pkg.volumeUuid; 22529 final String packageName = pkg.packageName; 22530 22531 ApplicationInfo app = (ps == null) 22532 ? pkg.applicationInfo 22533 : PackageParser.generateApplicationInfo(pkg, 0, ps.readUserState(userId), userId); 22534 if (app == null) { 22535 app = pkg.applicationInfo; 22536 } 22537 22538 final int appId = UserHandle.getAppId(app.uid); 22539 22540 Preconditions.checkNotNull(app.seInfo); 22541 22542 final String seInfo = app.seInfo + (app.seInfoUser != null ? app.seInfoUser : ""); 22543 long ceDataInode = -1; 22544 try { 22545 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22546 appId, seInfo, app.targetSdkVersion); 22547 } catch (InstallerException e) { 22548 if (app.isSystemApp()) { 22549 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 22550 + ", but trying to recover: " + e); 22551 destroyAppDataLeafLIF(pkg, userId, flags); 22552 try { 22553 ceDataInode = mInstaller.createAppData(volumeUuid, packageName, userId, flags, 22554 appId, seInfo, app.targetSdkVersion); 22555 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 22556 } catch (InstallerException e2) { 22557 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 22558 } 22559 } else { 22560 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 22561 } 22562 } 22563 // Prepare the application profiles only for upgrades and first boot (so that we don't 22564 // repeat the same operation at each boot). 22565 // We only have to cover the upgrade and first boot here because for app installs we 22566 // prepare the profiles before invoking dexopt (in installPackageLI). 22567 // 22568 // We also have to cover non system users because we do not call the usual install package 22569 // methods for them. 22570 // 22571 // NOTE: in order to speed up first boot time we only create the current profile and do not 22572 // update the content of the reference profile. A system image should already be configured 22573 // with the right profile keys and the profiles for the speed-profile prebuilds should 22574 // already be copied. That's done in #performDexOptUpgrade. 22575 // 22576 // TODO(calin, mathieuc): We should use .dm files for prebuilds profiles instead of 22577 // manually copying them in #performDexOptUpgrade. When we do that we should have a more 22578 // granular check here and only update the existing profiles. 22579 if (mIsUpgrade || mFirstBoot || (userId != UserHandle.USER_SYSTEM)) { 22580 mArtManagerService.prepareAppProfiles(pkg, userId, 22581 /* updateReferenceProfileContent= */ false); 22582 } 22583 22584 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && ceDataInode != -1) { 22585 // TODO: mark this structure as dirty so we persist it! 22586 synchronized (mPackages) { 22587 if (ps != null) { 22588 ps.setCeDataInode(ceDataInode, userId); 22589 } 22590 } 22591 } 22592 22593 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22594 } 22595 22596 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 22597 if (pkg == null) { 22598 Slog.wtf(TAG, "Package was null!", new Throwable()); 22599 return; 22600 } 22601 prepareAppDataContentsLeafLIF(pkg, userId, flags); 22602 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 22603 for (int i = 0; i < childCount; i++) { 22604 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 22605 } 22606 } 22607 22608 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 22609 final String volumeUuid = pkg.volumeUuid; 22610 final String packageName = pkg.packageName; 22611 final ApplicationInfo app = pkg.applicationInfo; 22612 22613 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 22614 // Create a native library symlink only if we have native libraries 22615 // and if the native libraries are 32 bit libraries. We do not provide 22616 // this symlink for 64 bit libraries. 22617 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 22618 final String nativeLibPath = app.nativeLibraryDir; 22619 try { 22620 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 22621 nativeLibPath, userId); 22622 } catch (InstallerException e) { 22623 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 22624 } 22625 } 22626 } 22627 } 22628 22629 /** 22630 * For system apps on non-FBE devices, this method migrates any existing 22631 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 22632 * requested by the app. 22633 */ 22634 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 22635 if (pkg.isSystem() && !StorageManager.isFileEncryptedNativeOrEmulated() 22636 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 22637 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 22638 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 22639 try { 22640 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 22641 storageTarget); 22642 } catch (InstallerException e) { 22643 logCriticalInfo(Log.WARN, 22644 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 22645 } 22646 return true; 22647 } else { 22648 return false; 22649 } 22650 } 22651 22652 public PackageFreezer freezePackage(String packageName, String killReason) { 22653 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 22654 } 22655 22656 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 22657 return new PackageFreezer(packageName, userId, killReason); 22658 } 22659 22660 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 22661 String killReason) { 22662 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 22663 } 22664 22665 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 22666 String killReason) { 22667 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 22668 return new PackageFreezer(); 22669 } else { 22670 return freezePackage(packageName, userId, killReason); 22671 } 22672 } 22673 22674 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 22675 String killReason) { 22676 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 22677 } 22678 22679 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 22680 String killReason) { 22681 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 22682 return new PackageFreezer(); 22683 } else { 22684 return freezePackage(packageName, userId, killReason); 22685 } 22686 } 22687 22688 /** 22689 * Class that freezes and kills the given package upon creation, and 22690 * unfreezes it upon closing. This is typically used when doing surgery on 22691 * app code/data to prevent the app from running while you're working. 22692 */ 22693 private class PackageFreezer implements AutoCloseable { 22694 private final String mPackageName; 22695 private final PackageFreezer[] mChildren; 22696 22697 private final boolean mWeFroze; 22698 22699 private final AtomicBoolean mClosed = new AtomicBoolean(); 22700 private final CloseGuard mCloseGuard = CloseGuard.get(); 22701 22702 /** 22703 * Create and return a stub freezer that doesn't actually do anything, 22704 * typically used when someone requested 22705 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 22706 * {@link PackageManager#DELETE_DONT_KILL_APP}. 22707 */ 22708 public PackageFreezer() { 22709 mPackageName = null; 22710 mChildren = null; 22711 mWeFroze = false; 22712 mCloseGuard.open("close"); 22713 } 22714 22715 public PackageFreezer(String packageName, int userId, String killReason) { 22716 synchronized (mPackages) { 22717 mPackageName = packageName; 22718 mWeFroze = mFrozenPackages.add(mPackageName); 22719 22720 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 22721 if (ps != null) { 22722 killApplication(ps.name, ps.appId, userId, killReason); 22723 } 22724 22725 final PackageParser.Package p = mPackages.get(packageName); 22726 if (p != null && p.childPackages != null) { 22727 final int N = p.childPackages.size(); 22728 mChildren = new PackageFreezer[N]; 22729 for (int i = 0; i < N; i++) { 22730 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 22731 userId, killReason); 22732 } 22733 } else { 22734 mChildren = null; 22735 } 22736 } 22737 mCloseGuard.open("close"); 22738 } 22739 22740 @Override 22741 protected void finalize() throws Throwable { 22742 try { 22743 mCloseGuard.warnIfOpen(); 22744 close(); 22745 } finally { 22746 super.finalize(); 22747 } 22748 } 22749 22750 @Override 22751 public void close() { 22752 mCloseGuard.close(); 22753 if (mClosed.compareAndSet(false, true)) { 22754 synchronized (mPackages) { 22755 if (mWeFroze) { 22756 mFrozenPackages.remove(mPackageName); 22757 } 22758 22759 if (mChildren != null) { 22760 for (PackageFreezer freezer : mChildren) { 22761 freezer.close(); 22762 } 22763 } 22764 } 22765 } 22766 } 22767 } 22768 22769 /** 22770 * Verify that given package is currently frozen. 22771 */ 22772 private void checkPackageFrozen(String packageName) { 22773 synchronized (mPackages) { 22774 if (!mFrozenPackages.contains(packageName)) { 22775 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 22776 } 22777 } 22778 } 22779 22780 @Override 22781 public int movePackage(final String packageName, final String volumeUuid) { 22782 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 22783 22784 final int callingUid = Binder.getCallingUid(); 22785 final UserHandle user = new UserHandle(UserHandle.getUserId(callingUid)); 22786 final int moveId = mNextMoveId.getAndIncrement(); 22787 mHandler.post(() -> { 22788 try { 22789 movePackageInternal(packageName, volumeUuid, moveId, callingUid, user); 22790 } catch (PackageManagerException e) { 22791 Slog.w(TAG, "Failed to move " + packageName, e); 22792 mMoveCallbacks.notifyStatusChanged(moveId, e.error); 22793 } 22794 }); 22795 return moveId; 22796 } 22797 22798 private void movePackageInternal(final String packageName, final String volumeUuid, 22799 final int moveId, final int callingUid, UserHandle user) 22800 throws PackageManagerException { 22801 final StorageManager storage = mContext.getSystemService(StorageManager.class); 22802 final PackageManager pm = mContext.getPackageManager(); 22803 22804 final String currentVolumeUuid; 22805 final File codeFile; 22806 final String installerPackageName; 22807 final String packageAbiOverride; 22808 final int appId; 22809 final String seinfo; 22810 final String label; 22811 final int targetSdkVersion; 22812 final PackageFreezer freezer; 22813 final int[] installedUserIds; 22814 final boolean isCurrentLocationExternal; 22815 22816 // reader 22817 synchronized (mPackages) { 22818 final PackageParser.Package pkg = mPackages.get(packageName); 22819 final PackageSetting ps = mSettings.mPackages.get(packageName); 22820 if (pkg == null 22821 || ps == null 22822 || filterAppAccessLPr(ps, callingUid, user.getIdentifier())) { 22823 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 22824 } 22825 if (pkg.applicationInfo.isSystemApp()) { 22826 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 22827 "Cannot move system application"); 22828 } 22829 22830 final boolean isInternalStorage = VolumeInfo.ID_PRIVATE_INTERNAL.equals(volumeUuid); 22831 final boolean allow3rdPartyOnInternal = mContext.getResources().getBoolean( 22832 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal); 22833 if (isInternalStorage && !allow3rdPartyOnInternal) { 22834 throw new PackageManagerException(MOVE_FAILED_3RD_PARTY_NOT_ALLOWED_ON_INTERNAL, 22835 "3rd party apps are not allowed on internal storage"); 22836 } 22837 22838 currentVolumeUuid = ps.volumeUuid; 22839 22840 final File probe = new File(pkg.codePath); 22841 final File probeOat = new File(probe, "oat"); 22842 if (!probe.isDirectory() || !probeOat.isDirectory()) { 22843 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22844 "Move only supported for modern cluster style installs"); 22845 } 22846 22847 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 22848 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22849 "Package already moved to " + volumeUuid); 22850 } 22851 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 22852 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 22853 "Device admin cannot be moved"); 22854 } 22855 22856 if (mFrozenPackages.contains(packageName)) { 22857 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 22858 "Failed to move already frozen package"); 22859 } 22860 22861 isCurrentLocationExternal = isExternal(pkg); 22862 codeFile = new File(pkg.codePath); 22863 installerPackageName = ps.installerPackageName; 22864 packageAbiOverride = ps.cpuAbiOverrideString; 22865 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 22866 seinfo = pkg.applicationInfo.seInfo; 22867 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 22868 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 22869 freezer = freezePackage(packageName, "movePackageInternal"); 22870 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 22871 } 22872 22873 final Bundle extras = new Bundle(); 22874 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 22875 extras.putString(Intent.EXTRA_TITLE, label); 22876 mMoveCallbacks.notifyCreated(moveId, extras); 22877 22878 int installFlags; 22879 final boolean moveCompleteApp; 22880 final File measurePath; 22881 22882 installFlags = INSTALL_INTERNAL; 22883 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 22884 moveCompleteApp = true; 22885 measurePath = Environment.getDataAppDirectory(volumeUuid); 22886 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 22887 moveCompleteApp = false; 22888 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 22889 } else { 22890 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 22891 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 22892 || !volume.isMountedWritable()) { 22893 freezer.close(); 22894 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22895 "Move location not mounted private volume"); 22896 } 22897 22898 moveCompleteApp = true; 22899 measurePath = Environment.getDataAppDirectory(volumeUuid); 22900 } 22901 22902 // If we're moving app data around, we need all the users unlocked 22903 if (moveCompleteApp) { 22904 for (int userId : installedUserIds) { 22905 if (StorageManager.isFileEncryptedNativeOrEmulated() 22906 && !StorageManager.isUserKeyUnlocked(userId)) { 22907 throw new PackageManagerException(MOVE_FAILED_LOCKED_USER, 22908 "User " + userId + " must be unlocked"); 22909 } 22910 } 22911 } 22912 22913 final PackageStats stats = new PackageStats(null, -1); 22914 synchronized (mInstaller) { 22915 for (int userId : installedUserIds) { 22916 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 22917 freezer.close(); 22918 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22919 "Failed to measure package size"); 22920 } 22921 } 22922 } 22923 22924 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 22925 + stats.dataSize); 22926 22927 final long startFreeBytes = measurePath.getUsableSpace(); 22928 final long sizeBytes; 22929 if (moveCompleteApp) { 22930 sizeBytes = stats.codeSize + stats.dataSize; 22931 } else { 22932 sizeBytes = stats.codeSize; 22933 } 22934 22935 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 22936 freezer.close(); 22937 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 22938 "Not enough free space to move"); 22939 } 22940 22941 mMoveCallbacks.notifyStatusChanged(moveId, 10); 22942 22943 final CountDownLatch installedLatch = new CountDownLatch(1); 22944 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 22945 @Override 22946 public void onUserActionRequired(Intent intent) throws RemoteException { 22947 throw new IllegalStateException(); 22948 } 22949 22950 @Override 22951 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 22952 Bundle extras) throws RemoteException { 22953 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 22954 + PackageManager.installStatusToString(returnCode, msg)); 22955 22956 installedLatch.countDown(); 22957 freezer.close(); 22958 22959 final int status = PackageManager.installStatusToPublicStatus(returnCode); 22960 switch (status) { 22961 case PackageInstaller.STATUS_SUCCESS: 22962 mMoveCallbacks.notifyStatusChanged(moveId, 22963 PackageManager.MOVE_SUCCEEDED); 22964 logAppMovedStorage(packageName, isCurrentLocationExternal); 22965 break; 22966 case PackageInstaller.STATUS_FAILURE_STORAGE: 22967 mMoveCallbacks.notifyStatusChanged(moveId, 22968 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 22969 break; 22970 default: 22971 mMoveCallbacks.notifyStatusChanged(moveId, 22972 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 22973 break; 22974 } 22975 } 22976 }; 22977 22978 final MoveInfo move; 22979 if (moveCompleteApp) { 22980 // Kick off a thread to report progress estimates 22981 new Thread(() -> { 22982 while (true) { 22983 try { 22984 if (installedLatch.await(1, TimeUnit.SECONDS)) { 22985 break; 22986 } 22987 } catch (InterruptedException ignored) { 22988 } 22989 22990 final long deltaFreeBytes = startFreeBytes - measurePath.getUsableSpace(); 22991 final int progress = 10 + (int) MathUtils.constrain( 22992 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 22993 mMoveCallbacks.notifyStatusChanged(moveId, progress); 22994 } 22995 }).start(); 22996 22997 final String dataAppName = codeFile.getName(); 22998 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 22999 dataAppName, appId, seinfo, targetSdkVersion); 23000 } else { 23001 move = null; 23002 } 23003 23004 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 23005 23006 final Message msg = mHandler.obtainMessage(INIT_COPY); 23007 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 23008 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 23009 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 23010 packageAbiOverride, null /*grantedPermissions*/, 23011 null /*whitelistedRestrictedPermissions*/, PackageParser.SigningDetails.UNKNOWN, 23012 PackageManager.INSTALL_REASON_UNKNOWN, PackageManager.VERSION_CODE_HIGHEST); 23013 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 23014 msg.obj = params; 23015 23016 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 23017 System.identityHashCode(msg.obj)); 23018 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 23019 System.identityHashCode(msg.obj)); 23020 23021 mHandler.sendMessage(msg); 23022 } 23023 23024 /** 23025 * Logs that an app has been moved from internal to external storage and vice versa. 23026 * @param packageName The package that was moved. 23027 */ 23028 private void logAppMovedStorage(String packageName, boolean isPreviousLocationExternal) { 23029 final PackageParser.Package pkg; 23030 synchronized (mPackages) { 23031 pkg = mPackages.get(packageName); 23032 } 23033 if (pkg == null) { 23034 return; 23035 } 23036 23037 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23038 VolumeInfo volume = storage.findVolumeByUuid(pkg.applicationInfo.storageUuid.toString()); 23039 int packageExternalStorageType = getPackageExternalStorageType(volume, isExternal(pkg)); 23040 23041 if (!isPreviousLocationExternal && isExternal(pkg)) { 23042 // Move from internal to external storage. 23043 StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType, 23044 StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_EXTERNAL, 23045 packageName); 23046 } else if (isPreviousLocationExternal && !isExternal(pkg)) { 23047 // Move from external to internal storage. 23048 StatsLog.write(StatsLog.APP_MOVED_STORAGE_REPORTED, packageExternalStorageType, 23049 StatsLog.APP_MOVED_STORAGE_REPORTED__MOVE_TYPE__TO_INTERNAL, 23050 packageName); 23051 } 23052 } 23053 23054 @Override 23055 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 23056 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 23057 23058 final int realMoveId = mNextMoveId.getAndIncrement(); 23059 final Bundle extras = new Bundle(); 23060 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 23061 mMoveCallbacks.notifyCreated(realMoveId, extras); 23062 23063 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 23064 @Override 23065 public void onCreated(int moveId, Bundle extras) { 23066 // Ignored 23067 } 23068 23069 @Override 23070 public void onStatusChanged(int moveId, int status, long estMillis) { 23071 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 23072 } 23073 }; 23074 23075 final StorageManager storage = mContext.getSystemService(StorageManager.class); 23076 storage.setPrimaryStorageUuid(volumeUuid, callback); 23077 return realMoveId; 23078 } 23079 23080 @Override 23081 public int getMoveStatus(int moveId) { 23082 mContext.enforceCallingOrSelfPermission( 23083 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23084 return mMoveCallbacks.mLastStatus.get(moveId); 23085 } 23086 23087 @Override 23088 public void registerMoveCallback(IPackageMoveObserver callback) { 23089 mContext.enforceCallingOrSelfPermission( 23090 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23091 mMoveCallbacks.register(callback); 23092 } 23093 23094 @Override 23095 public void unregisterMoveCallback(IPackageMoveObserver callback) { 23096 mContext.enforceCallingOrSelfPermission( 23097 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 23098 mMoveCallbacks.unregister(callback); 23099 } 23100 23101 @Override 23102 public boolean setInstallLocation(int loc) { 23103 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 23104 null); 23105 if (getInstallLocation() == loc) { 23106 return true; 23107 } 23108 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 23109 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 23110 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 23111 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 23112 return true; 23113 } 23114 return false; 23115 } 23116 23117 @Override 23118 public int getInstallLocation() { 23119 // allow instant app access 23120 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 23121 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 23122 PackageHelper.APP_INSTALL_AUTO); 23123 } 23124 23125 /** Called by UserManagerService */ 23126 void cleanUpUser(UserManagerService userManager, int userHandle) { 23127 synchronized (mPackages) { 23128 mDirtyUsers.remove(userHandle); 23129 mUserNeedsBadging.delete(userHandle); 23130 mSettings.removeUserLPw(userHandle); 23131 mPendingBroadcasts.remove(userHandle); 23132 mInstantAppRegistry.onUserRemovedLPw(userHandle); 23133 removeUnusedPackagesLPw(userManager, userHandle); 23134 } 23135 } 23136 23137 /** 23138 * We're removing userHandle and would like to remove any downloaded packages 23139 * that are no longer in use by any other user. 23140 * @param userHandle the user being removed 23141 */ 23142 @GuardedBy("mPackages") 23143 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 23144 final boolean DEBUG_CLEAN_APKS = false; 23145 int [] users = userManager.getUserIds(); 23146 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 23147 while (psit.hasNext()) { 23148 PackageSetting ps = psit.next(); 23149 if (ps.pkg == null) { 23150 continue; 23151 } 23152 final String packageName = ps.pkg.packageName; 23153 // Skip over if system app or static shared library 23154 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0 23155 || !TextUtils.isEmpty(ps.pkg.staticSharedLibName)) { 23156 continue; 23157 } 23158 if (DEBUG_CLEAN_APKS) { 23159 Slog.i(TAG, "Checking package " + packageName); 23160 } 23161 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 23162 if (keep) { 23163 if (DEBUG_CLEAN_APKS) { 23164 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 23165 } 23166 } else { 23167 for (int i = 0; i < users.length; i++) { 23168 if (users[i] != userHandle && ps.getInstalled(users[i])) { 23169 keep = true; 23170 if (DEBUG_CLEAN_APKS) { 23171 Slog.i(TAG, " Keeping package " + packageName + " for user " 23172 + users[i]); 23173 } 23174 break; 23175 } 23176 } 23177 } 23178 if (!keep) { 23179 if (DEBUG_CLEAN_APKS) { 23180 Slog.i(TAG, " Removing package " + packageName); 23181 } 23182 //end run 23183 mHandler.post(() -> { 23184 if (!mBlockDeleteOnUserRemoveForTest.block(30000 /* 30 seconds*/)) { 23185 mBlockDeleteOnUserRemoveForTest.open(); 23186 } 23187 deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23188 userHandle, 0); 23189 }); 23190 } 23191 } 23192 } 23193 23194 /** Called by UserManagerService */ 23195 void createNewUser(int userId, String[] disallowedPackages) { 23196 synchronized (mInstallLock) { 23197 mSettings.createNewUserLI(this, mInstaller, userId, disallowedPackages); 23198 } 23199 synchronized (mPackages) { 23200 scheduleWritePackageRestrictionsLocked(userId); 23201 scheduleWritePackageListLocked(userId); 23202 primeDomainVerificationsLPw(userId); 23203 } 23204 } 23205 23206 void onNewUserCreated(final int userId) { 23207 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 23208 synchronized(mPackages) { 23209 // NOTE: This adds UPDATE_PERMISSIONS_REPLACE_PKG 23210 mPermissionManager.updateAllPermissions( 23211 StorageManager.UUID_PRIVATE_INTERNAL, true, mPackages.values(), 23212 mPermissionCallback); 23213 } 23214 } 23215 23216 boolean readPermissionStateForUser(@UserIdInt int userId) { 23217 synchronized (mPackages) { 23218 mSettings.readPermissionStateForUserSyncLPr(userId); 23219 return mSettings.areDefaultRuntimePermissionsGrantedLPr(userId); 23220 } 23221 } 23222 23223 @Override 23224 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 23225 mContext.enforceCallingOrSelfPermission( 23226 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 23227 "Only package verification agents can read the verifier device identity"); 23228 23229 synchronized (mPackages) { 23230 return mSettings.getVerifierDeviceIdentityLPw(); 23231 } 23232 } 23233 23234 @Override 23235 public void setPermissionEnforced(String permission, boolean enforced) { 23236 // TODO: Now that we no longer change GID for storage, this should to away. 23237 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 23238 "setPermissionEnforced"); 23239 if (READ_EXTERNAL_STORAGE.equals(permission)) { 23240 synchronized (mPackages) { 23241 if (mSettings.mReadExternalStorageEnforced == null 23242 || mSettings.mReadExternalStorageEnforced != enforced) { 23243 mSettings.mReadExternalStorageEnforced = 23244 enforced ? Boolean.TRUE : Boolean.FALSE; 23245 mSettings.writeLPr(); 23246 } 23247 } 23248 // kill any non-foreground processes so we restart them and 23249 // grant/revoke the GID. 23250 final IActivityManager am = ActivityManager.getService(); 23251 if (am != null) { 23252 final long token = Binder.clearCallingIdentity(); 23253 try { 23254 am.killProcessesBelowForeground("setPermissionEnforcement"); 23255 } catch (RemoteException e) { 23256 } finally { 23257 Binder.restoreCallingIdentity(token); 23258 } 23259 } 23260 } else { 23261 throw new IllegalArgumentException("No selective enforcement for " + permission); 23262 } 23263 } 23264 23265 @Override 23266 @Deprecated 23267 public boolean isPermissionEnforced(String permission) { 23268 // allow instant applications 23269 return true; 23270 } 23271 23272 @Override 23273 public boolean isStorageLow() { 23274 // allow instant applications 23275 final long token = Binder.clearCallingIdentity(); 23276 try { 23277 final DeviceStorageMonitorInternal 23278 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 23279 if (dsm != null) { 23280 return dsm.isMemoryLow(); 23281 } else { 23282 return false; 23283 } 23284 } finally { 23285 Binder.restoreCallingIdentity(token); 23286 } 23287 } 23288 23289 @Override 23290 public IPackageInstaller getPackageInstaller() { 23291 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 23292 return null; 23293 } 23294 return mInstallerService; 23295 } 23296 23297 @Override 23298 public IArtManager getArtManager() { 23299 return mArtManagerService; 23300 } 23301 23302 private boolean userNeedsBadging(int userId) { 23303 int index = mUserNeedsBadging.indexOfKey(userId); 23304 if (index < 0) { 23305 final UserInfo userInfo; 23306 final long token = Binder.clearCallingIdentity(); 23307 try { 23308 userInfo = sUserManager.getUserInfo(userId); 23309 } finally { 23310 Binder.restoreCallingIdentity(token); 23311 } 23312 final boolean b; 23313 if (userInfo != null && userInfo.isManagedProfile()) { 23314 b = true; 23315 } else { 23316 b = false; 23317 } 23318 mUserNeedsBadging.put(userId, b); 23319 return b; 23320 } 23321 return mUserNeedsBadging.valueAt(index); 23322 } 23323 23324 @Override 23325 public KeySet getKeySetByAlias(String packageName, String alias) { 23326 if (packageName == null || alias == null) { 23327 return null; 23328 } 23329 synchronized(mPackages) { 23330 final PackageParser.Package pkg = mPackages.get(packageName); 23331 if (pkg == null) { 23332 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23333 throw new IllegalArgumentException("Unknown package: " + packageName); 23334 } 23335 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23336 if (filterAppAccessLPr(ps, Binder.getCallingUid(), UserHandle.getCallingUserId())) { 23337 Slog.w(TAG, "KeySet requested for filtered package: " + packageName); 23338 throw new IllegalArgumentException("Unknown package: " + packageName); 23339 } 23340 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23341 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 23342 } 23343 } 23344 23345 @Override 23346 public KeySet getSigningKeySet(String packageName) { 23347 if (packageName == null) { 23348 return null; 23349 } 23350 synchronized(mPackages) { 23351 final int callingUid = Binder.getCallingUid(); 23352 final int callingUserId = UserHandle.getUserId(callingUid); 23353 final PackageParser.Package pkg = mPackages.get(packageName); 23354 if (pkg == null) { 23355 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23356 throw new IllegalArgumentException("Unknown package: " + packageName); 23357 } 23358 final PackageSetting ps = (PackageSetting) pkg.mExtras; 23359 if (filterAppAccessLPr(ps, callingUid, callingUserId)) { 23360 // filter and pretend the package doesn't exist 23361 Slog.w(TAG, "KeySet requested for filtered package: " + packageName 23362 + ", uid:" + callingUid); 23363 throw new IllegalArgumentException("Unknown package: " + packageName); 23364 } 23365 if (pkg.applicationInfo.uid != callingUid 23366 && Process.SYSTEM_UID != callingUid) { 23367 throw new SecurityException("May not access signing KeySet of other apps."); 23368 } 23369 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23370 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 23371 } 23372 } 23373 23374 @Override 23375 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 23376 final int callingUid = Binder.getCallingUid(); 23377 if (getInstantAppPackageName(callingUid) != null) { 23378 return false; 23379 } 23380 if (packageName == null || ks == null) { 23381 return false; 23382 } 23383 synchronized(mPackages) { 23384 final PackageParser.Package pkg = mPackages.get(packageName); 23385 if (pkg == null 23386 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23387 UserHandle.getUserId(callingUid))) { 23388 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23389 throw new IllegalArgumentException("Unknown package: " + packageName); 23390 } 23391 IBinder ksh = ks.getToken(); 23392 if (ksh instanceof KeySetHandle) { 23393 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23394 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 23395 } 23396 return false; 23397 } 23398 } 23399 23400 @Override 23401 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 23402 final int callingUid = Binder.getCallingUid(); 23403 if (getInstantAppPackageName(callingUid) != null) { 23404 return false; 23405 } 23406 if (packageName == null || ks == null) { 23407 return false; 23408 } 23409 synchronized(mPackages) { 23410 final PackageParser.Package pkg = mPackages.get(packageName); 23411 if (pkg == null 23412 || filterAppAccessLPr((PackageSetting) pkg.mExtras, callingUid, 23413 UserHandle.getUserId(callingUid))) { 23414 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 23415 throw new IllegalArgumentException("Unknown package: " + packageName); 23416 } 23417 IBinder ksh = ks.getToken(); 23418 if (ksh instanceof KeySetHandle) { 23419 final KeySetManagerService ksms = mSettings.mKeySetManagerService; 23420 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 23421 } 23422 return false; 23423 } 23424 } 23425 23426 @GuardedBy("mPackages") 23427 private void deletePackageIfUnusedLPr(final String packageName) { 23428 PackageSetting ps = mSettings.mPackages.get(packageName); 23429 if (ps == null) { 23430 return; 23431 } 23432 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 23433 // TODO Implement atomic delete if package is unused 23434 // It is currently possible that the package will be deleted even if it is installed 23435 // after this method returns. 23436 mHandler.post(() -> deletePackageX(packageName, PackageManager.VERSION_CODE_HIGHEST, 23437 0, PackageManager.DELETE_ALL_USERS)); 23438 } 23439 } 23440 23441 /** 23442 * Check and throw if the given before/after packages would be considered a 23443 * downgrade. 23444 */ 23445 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 23446 throws PackageManagerException { 23447 if (after.getLongVersionCode() < before.getLongVersionCode()) { 23448 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23449 "Update version code " + after.versionCode + " is older than current " 23450 + before.getLongVersionCode()); 23451 } else if (after.getLongVersionCode() == before.getLongVersionCode()) { 23452 if (after.baseRevisionCode < before.baseRevisionCode) { 23453 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23454 "Update base revision code " + after.baseRevisionCode 23455 + " is older than current " + before.baseRevisionCode); 23456 } 23457 23458 if (!ArrayUtils.isEmpty(after.splitNames)) { 23459 for (int i = 0; i < after.splitNames.length; i++) { 23460 final String splitName = after.splitNames[i]; 23461 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 23462 if (j != -1) { 23463 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 23464 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 23465 "Update split " + splitName + " revision code " 23466 + after.splitRevisionCodes[i] + " is older than current " 23467 + before.splitRevisionCodes[j]); 23468 } 23469 } 23470 } 23471 } 23472 } 23473 } 23474 23475 private static class MoveCallbacks extends Handler { 23476 private static final int MSG_CREATED = 1; 23477 private static final int MSG_STATUS_CHANGED = 2; 23478 23479 private final RemoteCallbackList<IPackageMoveObserver> 23480 mCallbacks = new RemoteCallbackList<>(); 23481 23482 private final SparseIntArray mLastStatus = new SparseIntArray(); 23483 23484 public MoveCallbacks(Looper looper) { 23485 super(looper); 23486 } 23487 23488 public void register(IPackageMoveObserver callback) { 23489 mCallbacks.register(callback); 23490 } 23491 23492 public void unregister(IPackageMoveObserver callback) { 23493 mCallbacks.unregister(callback); 23494 } 23495 23496 @Override 23497 public void handleMessage(Message msg) { 23498 final SomeArgs args = (SomeArgs) msg.obj; 23499 final int n = mCallbacks.beginBroadcast(); 23500 for (int i = 0; i < n; i++) { 23501 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 23502 try { 23503 invokeCallback(callback, msg.what, args); 23504 } catch (RemoteException ignored) { 23505 } 23506 } 23507 mCallbacks.finishBroadcast(); 23508 args.recycle(); 23509 } 23510 23511 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 23512 throws RemoteException { 23513 switch (what) { 23514 case MSG_CREATED: { 23515 callback.onCreated(args.argi1, (Bundle) args.arg2); 23516 break; 23517 } 23518 case MSG_STATUS_CHANGED: { 23519 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 23520 break; 23521 } 23522 } 23523 } 23524 23525 private void notifyCreated(int moveId, Bundle extras) { 23526 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 23527 23528 final SomeArgs args = SomeArgs.obtain(); 23529 args.argi1 = moveId; 23530 args.arg2 = extras; 23531 obtainMessage(MSG_CREATED, args).sendToTarget(); 23532 } 23533 23534 private void notifyStatusChanged(int moveId, int status) { 23535 notifyStatusChanged(moveId, status, -1); 23536 } 23537 23538 private void notifyStatusChanged(int moveId, int status, long estMillis) { 23539 Slog.v(TAG, "Move " + moveId + " status " + status); 23540 23541 final SomeArgs args = SomeArgs.obtain(); 23542 args.argi1 = moveId; 23543 args.argi2 = status; 23544 args.arg3 = estMillis; 23545 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 23546 23547 synchronized (mLastStatus) { 23548 mLastStatus.put(moveId, status); 23549 } 23550 } 23551 } 23552 23553 private final static class OnPermissionChangeListeners extends Handler { 23554 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 23555 23556 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 23557 new RemoteCallbackList<>(); 23558 23559 public OnPermissionChangeListeners(Looper looper) { 23560 super(looper); 23561 } 23562 23563 @Override 23564 public void handleMessage(Message msg) { 23565 switch (msg.what) { 23566 case MSG_ON_PERMISSIONS_CHANGED: { 23567 final int uid = msg.arg1; 23568 handleOnPermissionsChanged(uid); 23569 } break; 23570 } 23571 } 23572 23573 public void addListenerLocked(IOnPermissionsChangeListener listener) { 23574 mPermissionListeners.register(listener); 23575 23576 } 23577 23578 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 23579 mPermissionListeners.unregister(listener); 23580 } 23581 23582 public void onPermissionsChanged(int uid) { 23583 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 23584 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 23585 } 23586 } 23587 23588 private void handleOnPermissionsChanged(int uid) { 23589 final int count = mPermissionListeners.beginBroadcast(); 23590 try { 23591 for (int i = 0; i < count; i++) { 23592 IOnPermissionsChangeListener callback = mPermissionListeners 23593 .getBroadcastItem(i); 23594 try { 23595 callback.onPermissionsChanged(uid); 23596 } catch (RemoteException e) { 23597 Log.e(TAG, "Permission listener is dead", e); 23598 } 23599 } 23600 } finally { 23601 mPermissionListeners.finishBroadcast(); 23602 } 23603 } 23604 } 23605 23606 private class PackageManagerNative extends IPackageManagerNative.Stub { 23607 @Override 23608 public String[] getNamesForUids(int[] uids) throws RemoteException { 23609 final String[] results = PackageManagerService.this.getNamesForUids(uids); 23610 // massage results so they can be parsed by the native binder 23611 for (int i = results.length - 1; i >= 0; --i) { 23612 if (results[i] == null) { 23613 results[i] = ""; 23614 } 23615 } 23616 return results; 23617 } 23618 23619 // NB: this differentiates between preloads and sideloads 23620 @Override 23621 public String getInstallerForPackage(String packageName) throws RemoteException { 23622 final String installerName = getInstallerPackageName(packageName); 23623 if (!TextUtils.isEmpty(installerName)) { 23624 return installerName; 23625 } 23626 // differentiate between preload and sideload 23627 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23628 ApplicationInfo appInfo = getApplicationInfo(packageName, 23629 /*flags*/ 0, 23630 /*userId*/ callingUser); 23631 if (appInfo != null && (appInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 23632 return "preload"; 23633 } 23634 return ""; 23635 } 23636 23637 @Override 23638 public long getVersionCodeForPackage(String packageName) throws RemoteException { 23639 try { 23640 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23641 PackageInfo pInfo = getPackageInfo(packageName, 0, callingUser); 23642 if (pInfo != null) { 23643 return pInfo.getLongVersionCode(); 23644 } 23645 } catch (Exception e) { 23646 } 23647 return 0; 23648 } 23649 23650 @Override 23651 public int getTargetSdkVersionForPackage(String packageName) 23652 throws RemoteException { 23653 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23654 ApplicationInfo info = getApplicationInfo(packageName, 0, callingUser); 23655 if (info == null) { 23656 throw new RemoteException( 23657 "Couldn't get ApplicationInfo for package " + packageName); 23658 } 23659 return info.targetSdkVersion; 23660 } 23661 23662 @Override 23663 public boolean[] isAudioPlaybackCaptureAllowed(String[] packageNames) 23664 throws RemoteException { 23665 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23666 boolean[] results = new boolean[packageNames.length]; 23667 for (int i = results.length - 1; i >= 0; --i) { 23668 ApplicationInfo appInfo = getApplicationInfo(packageNames[i], 0, callingUser); 23669 results[i] = appInfo == null ? false : appInfo.isAudioPlaybackCaptureAllowed(); 23670 } 23671 return results; 23672 } 23673 23674 @Override 23675 public int getLocationFlags(String packageName) throws RemoteException { 23676 int callingUser = UserHandle.getUserId(Binder.getCallingUid()); 23677 ApplicationInfo appInfo = getApplicationInfo(packageName, 23678 /*flags*/ 0, 23679 /*userId*/ callingUser); 23680 if (appInfo == null) { 23681 throw new RemoteException( 23682 "Couldn't get ApplicationInfo for package " + packageName); 23683 } 23684 return ((appInfo.isSystemApp() ? IPackageManagerNative.LOCATION_SYSTEM : 0) 23685 | (appInfo.isVendor() ? IPackageManagerNative.LOCATION_VENDOR : 0) 23686 | (appInfo.isProduct() ? IPackageManagerNative.LOCATION_PRODUCT : 0)); 23687 } 23688 23689 @Override 23690 public String getModuleMetadataPackageName() throws RemoteException { 23691 return PackageManagerService.this.mModuleInfoProvider.getPackageName(); 23692 } 23693 } 23694 23695 private class PackageManagerInternalImpl extends PackageManagerInternal { 23696 @Override 23697 public void updatePermissionFlagsTEMP(String permName, String packageName, int flagMask, 23698 int flagValues, int userId) { 23699 PackageManagerService.this.updatePermissionFlags( 23700 permName, packageName, flagMask, flagValues, true, userId); 23701 } 23702 23703 @Override 23704 public List<ApplicationInfo> getInstalledApplications(int flags, int userId, 23705 int callingUid) { 23706 return PackageManagerService.this.getInstalledApplicationsListInternal(flags, userId, 23707 callingUid); 23708 } 23709 23710 23711 @Override 23712 public boolean isPlatformSigned(String packageName) { 23713 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 23714 if (packageSetting == null) { 23715 return false; 23716 } 23717 PackageParser.Package pkg = packageSetting.pkg; 23718 if (pkg == null) { 23719 // May happen if package in on a removable sd card 23720 return false; 23721 } 23722 return pkg.mSigningDetails.hasAncestorOrSelf(mPlatformPackage.mSigningDetails) 23723 || mPlatformPackage.mSigningDetails.checkCapability(pkg.mSigningDetails, 23724 PackageParser.SigningDetails.CertCapabilities.PERMISSION); 23725 } 23726 23727 @Override 23728 public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) { 23729 SigningDetails sd = getSigningDetails(packageName); 23730 if (sd == null) { 23731 return false; 23732 } 23733 return sd.hasSha256Certificate(restoringFromSigHash, 23734 SigningDetails.CertCapabilities.INSTALLED_DATA); 23735 } 23736 23737 @Override 23738 public boolean isDataRestoreSafe(Signature restoringFromSig, String packageName) { 23739 SigningDetails sd = getSigningDetails(packageName); 23740 if (sd == null) { 23741 return false; 23742 } 23743 return sd.hasCertificate(restoringFromSig, 23744 SigningDetails.CertCapabilities.INSTALLED_DATA); 23745 } 23746 23747 @Override 23748 public boolean hasSignatureCapability(int serverUid, int clientUid, 23749 @SigningDetails.CertCapabilities int capability) { 23750 SigningDetails serverSigningDetails = getSigningDetails(serverUid); 23751 SigningDetails clientSigningDetails = getSigningDetails(clientUid); 23752 return serverSigningDetails.checkCapability(clientSigningDetails, capability) 23753 || clientSigningDetails.hasAncestorOrSelf(serverSigningDetails); 23754 23755 } 23756 23757 private SigningDetails getSigningDetails(@NonNull String packageName) { 23758 synchronized (mPackages) { 23759 PackageParser.Package p = mPackages.get(packageName); 23760 if (p == null) { 23761 return null; 23762 } 23763 return p.mSigningDetails; 23764 } 23765 } 23766 23767 private SigningDetails getSigningDetails(int uid) { 23768 synchronized (mPackages) { 23769 final int appId = UserHandle.getAppId(uid); 23770 final Object obj = mSettings.getSettingLPr(appId); 23771 if (obj != null) { 23772 if (obj instanceof SharedUserSetting) { 23773 return ((SharedUserSetting) obj).signatures.mSigningDetails; 23774 } else if (obj instanceof PackageSetting) { 23775 final PackageSetting ps = (PackageSetting) obj; 23776 return ps.signatures.mSigningDetails; 23777 } 23778 } 23779 return SigningDetails.UNKNOWN; 23780 } 23781 } 23782 23783 @Override 23784 public int getPermissionFlagsTEMP(String permName, String packageName, int userId) { 23785 return PackageManagerService.this.getPermissionFlags(permName, packageName, userId); 23786 } 23787 23788 @Override 23789 public boolean isInstantApp(String packageName, int userId) { 23790 return PackageManagerService.this.isInstantApp(packageName, userId); 23791 } 23792 23793 @Override 23794 public String getInstantAppPackageName(int uid) { 23795 return PackageManagerService.this.getInstantAppPackageName(uid); 23796 } 23797 23798 @Override 23799 public boolean filterAppAccess(PackageParser.Package pkg, int callingUid, int userId) { 23800 synchronized (mPackages) { 23801 return PackageManagerService.this.filterAppAccessLPr( 23802 (PackageSetting) pkg.mExtras, callingUid, userId); 23803 } 23804 } 23805 23806 @Override 23807 public PackageParser.Package getPackage(String packageName) { 23808 synchronized (mPackages) { 23809 packageName = resolveInternalPackageNameLPr( 23810 packageName, PackageManager.VERSION_CODE_HIGHEST); 23811 return mPackages.get(packageName); 23812 } 23813 } 23814 23815 @Override 23816 public PackageList getPackageList(PackageListObserver observer) { 23817 synchronized (mPackages) { 23818 final int N = mPackages.size(); 23819 final ArrayList<String> list = new ArrayList<>(N); 23820 for (int i = 0; i < N; i++) { 23821 list.add(mPackages.keyAt(i)); 23822 } 23823 final PackageList packageList = new PackageList(list, observer); 23824 if (observer != null) { 23825 mPackageListObservers.add(packageList); 23826 } 23827 return packageList; 23828 } 23829 } 23830 23831 @Override 23832 public void removePackageListObserver(PackageListObserver observer) { 23833 synchronized (mPackages) { 23834 mPackageListObservers.remove(observer); 23835 } 23836 } 23837 23838 @Override 23839 public PackageParser.Package getDisabledSystemPackage(String packageName) { 23840 synchronized (mPackages) { 23841 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 23842 return (ps != null) ? ps.pkg : null; 23843 } 23844 } 23845 23846 @Override 23847 public @Nullable String getDisabledSystemPackageName(@NonNull String packageName) { 23848 PackageParser.Package pkg = getDisabledSystemPackage(packageName); 23849 return pkg == null ? null : pkg.packageName; 23850 } 23851 23852 @Override 23853 public @NonNull String[] getKnownPackageNames(int knownPackage, int userId) { 23854 switch(knownPackage) { 23855 case PackageManagerInternal.PACKAGE_BROWSER: 23856 return new String[]{getDefaultBrowserPackageName(userId)}; 23857 case PackageManagerInternal.PACKAGE_INSTALLER: 23858 return new String[]{mRequiredInstallerPackage}; 23859 case PackageManagerInternal.PACKAGE_SETUP_WIZARD: 23860 return new String[]{mSetupWizardPackage}; 23861 case PackageManagerInternal.PACKAGE_SYSTEM: 23862 return new String[]{"android"}; 23863 case PackageManagerInternal.PACKAGE_VERIFIER: 23864 return new String[]{mRequiredVerifierPackage}; 23865 case PackageManagerInternal.PACKAGE_SYSTEM_TEXT_CLASSIFIER: 23866 return new String[]{mSystemTextClassifierPackage}; 23867 case PackageManagerInternal.PACKAGE_PERMISSION_CONTROLLER: 23868 return new String[]{mRequiredPermissionControllerPackage}; 23869 case PackageManagerInternal.PACKAGE_WELLBEING: 23870 return new String[]{mWellbeingPackage}; 23871 case PackageManagerInternal.PACKAGE_DOCUMENTER: 23872 return new String[]{mDocumenterPackage}; 23873 case PackageManagerInternal.PACKAGE_CONFIGURATOR: 23874 return new String[]{mConfiguratorPackage}; 23875 case PackageManagerInternal.PACKAGE_INCIDENT_REPORT_APPROVER: 23876 return new String[]{mIncidentReportApproverPackage}; 23877 case PackageManagerInternal.PACKAGE_APP_PREDICTOR: 23878 return new String[]{mAppPredictionServicePackage}; 23879 case PackageManagerInternal.PACKAGE_TELEPHONY: 23880 return mTelephonyPackages; 23881 } 23882 return ArrayUtils.emptyArray(String.class); 23883 } 23884 23885 @Override 23886 public boolean isResolveActivityComponent(ComponentInfo component) { 23887 return mResolveActivity.packageName.equals(component.packageName) 23888 && mResolveActivity.name.equals(component.name); 23889 } 23890 23891 @Override 23892 public void setLocationPackagesProvider(PackagesProvider provider) { 23893 mDefaultPermissionPolicy.setLocationPackagesProvider(provider); 23894 } 23895 23896 @Override 23897 public void setLocationExtraPackagesProvider(PackagesProvider provider) { 23898 mDefaultPermissionPolicy.setLocationExtraPackagesProvider(provider); 23899 } 23900 23901 @Override 23902 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 23903 mDefaultPermissionPolicy.setVoiceInteractionPackagesProvider(provider); 23904 } 23905 23906 @Override 23907 public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) { 23908 mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider); 23909 } 23910 23911 @Override 23912 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 23913 mDefaultPermissionPolicy.setSyncAdapterPackagesProvider(provider); 23914 } 23915 23916 @Override 23917 public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) { 23918 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultUseOpenWifiApp( 23919 packageName, userId); 23920 } 23921 23922 @Override 23923 public void setKeepUninstalledPackages(final List<String> packageList) { 23924 Preconditions.checkNotNull(packageList); 23925 List<String> removedFromList = null; 23926 synchronized (mPackages) { 23927 if (mKeepUninstalledPackages != null) { 23928 final int packagesCount = mKeepUninstalledPackages.size(); 23929 for (int i = 0; i < packagesCount; i++) { 23930 String oldPackage = mKeepUninstalledPackages.get(i); 23931 if (packageList != null && packageList.contains(oldPackage)) { 23932 continue; 23933 } 23934 if (removedFromList == null) { 23935 removedFromList = new ArrayList<>(); 23936 } 23937 removedFromList.add(oldPackage); 23938 } 23939 } 23940 mKeepUninstalledPackages = new ArrayList<>(packageList); 23941 if (removedFromList != null) { 23942 final int removedCount = removedFromList.size(); 23943 for (int i = 0; i < removedCount; i++) { 23944 deletePackageIfUnusedLPr(removedFromList.get(i)); 23945 } 23946 } 23947 } 23948 } 23949 23950 @Override 23951 public boolean isPermissionsReviewRequired(String packageName, int userId) { 23952 synchronized (mPackages) { 23953 final PackageParser.Package pkg = mPackages.get(packageName); 23954 if (pkg == null) { 23955 return false; 23956 } 23957 23958 return mPermissionManager.isPermissionsReviewRequired(pkg, userId); 23959 } 23960 } 23961 23962 @Override 23963 public PackageInfo getPackageInfo( 23964 String packageName, int flags, int filterCallingUid, int userId) { 23965 return PackageManagerService.this 23966 .getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 23967 flags, filterCallingUid, userId); 23968 } 23969 23970 @Override 23971 public Bundle getSuspendedPackageLauncherExtras(String packageName, int userId) { 23972 synchronized (mPackages) { 23973 final PackageSetting ps = mSettings.mPackages.get(packageName); 23974 PersistableBundle launcherExtras = null; 23975 if (ps != null) { 23976 launcherExtras = ps.readUserState(userId).suspendedLauncherExtras; 23977 } 23978 return (launcherExtras != null) ? new Bundle(launcherExtras.deepCopy()) : null; 23979 } 23980 } 23981 23982 @Override 23983 public boolean isPackageSuspended(String packageName, int userId) { 23984 synchronized (mPackages) { 23985 final PackageSetting ps = mSettings.mPackages.get(packageName); 23986 return (ps != null) ? ps.getSuspended(userId) : false; 23987 } 23988 } 23989 23990 @Override 23991 public String getSuspendingPackage(String suspendedPackage, int userId) { 23992 synchronized (mPackages) { 23993 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 23994 return (ps != null) ? ps.readUserState(userId).suspendingPackage : null; 23995 } 23996 } 23997 23998 @Override 23999 public SuspendDialogInfo getSuspendedDialogInfo(String suspendedPackage, int userId) { 24000 synchronized (mPackages) { 24001 final PackageSetting ps = mSettings.mPackages.get(suspendedPackage); 24002 return (ps != null) ? ps.readUserState(userId).dialogInfo : null; 24003 } 24004 } 24005 24006 @Override 24007 public int getDistractingPackageRestrictions(String packageName, int userId) { 24008 synchronized (mPackages) { 24009 final PackageSetting ps = mSettings.mPackages.get(packageName); 24010 return (ps != null) ? ps.getDistractionFlags(userId) : RESTRICTION_NONE; 24011 } 24012 } 24013 24014 @Override 24015 public int getPackageUid(String packageName, int flags, int userId) { 24016 return PackageManagerService.this 24017 .getPackageUid(packageName, flags, userId); 24018 } 24019 24020 @Override 24021 public ApplicationInfo getApplicationInfo( 24022 String packageName, int flags, int filterCallingUid, int userId) { 24023 return PackageManagerService.this 24024 .getApplicationInfoInternal(packageName, flags, filterCallingUid, userId); 24025 } 24026 24027 @Override 24028 public ActivityInfo getActivityInfo( 24029 ComponentName component, int flags, int filterCallingUid, int userId) { 24030 return PackageManagerService.this 24031 .getActivityInfoInternal(component, flags, filterCallingUid, userId); 24032 } 24033 24034 @Override 24035 public List<ResolveInfo> queryIntentActivities( 24036 Intent intent, int flags, int filterCallingUid, int userId) { 24037 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24038 return queryIntentActivities(intent, resolvedType, flags, filterCallingUid, userId); 24039 } 24040 24041 @Override 24042 public List<ResolveInfo> queryIntentActivities( 24043 Intent intent, String resolvedType, int flags, int filterCallingUid, int userId) { 24044 return PackageManagerService.this 24045 .queryIntentActivitiesInternal(intent, resolvedType, flags, filterCallingUid, 24046 userId, false /*resolveForStart*/, true /*allowDynamicSplits*/); 24047 } 24048 24049 @Override 24050 public List<ResolveInfo> queryIntentServices( 24051 Intent intent, int flags, int callingUid, int userId) { 24052 final String resolvedType = intent.resolveTypeIfNeeded(mContext.getContentResolver()); 24053 return PackageManagerService.this 24054 .queryIntentServicesInternal(intent, resolvedType, flags, userId, callingUid, 24055 false); 24056 } 24057 24058 @Override 24059 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 24060 int userId) { 24061 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 24062 } 24063 24064 @Override 24065 public ComponentName getDefaultHomeActivity(int userId) { 24066 return PackageManagerService.this.getDefaultHomeActivity(userId); 24067 } 24068 24069 @Override 24070 public void setDeviceAndProfileOwnerPackages( 24071 int deviceOwnerUserId, String deviceOwnerPackage, 24072 SparseArray<String> profileOwnerPackages) { 24073 mProtectedPackages.setDeviceAndProfileOwnerPackages( 24074 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 24075 24076 final ArraySet<Integer> usersWithPoOrDo = new ArraySet<>(); 24077 if (deviceOwnerPackage != null) { 24078 usersWithPoOrDo.add(deviceOwnerUserId); 24079 } 24080 final int sz = profileOwnerPackages.size(); 24081 for (int i = 0; i < sz; i++) { 24082 if (profileOwnerPackages.valueAt(i) != null) { 24083 usersWithPoOrDo.add(profileOwnerPackages.keyAt(i)); 24084 } 24085 } 24086 unsuspendForNonSystemSuspendingPackages(usersWithPoOrDo); 24087 } 24088 24089 @Override 24090 public boolean isPackageDataProtected(int userId, String packageName) { 24091 return mProtectedPackages.isPackageDataProtected(userId, packageName); 24092 } 24093 24094 @Override 24095 public boolean isPackageStateProtected(String packageName, int userId) { 24096 return mProtectedPackages.isPackageStateProtected(userId, packageName); 24097 } 24098 24099 @Override 24100 public boolean isPackageEphemeral(int userId, String packageName) { 24101 synchronized (mPackages) { 24102 final PackageSetting ps = mSettings.mPackages.get(packageName); 24103 return ps != null ? ps.getInstantApp(userId) : false; 24104 } 24105 } 24106 24107 @Override 24108 public boolean wasPackageEverLaunched(String packageName, int userId) { 24109 synchronized (mPackages) { 24110 return mSettings.wasPackageEverLaunchedLPr(packageName, userId); 24111 } 24112 } 24113 24114 @Override 24115 public boolean isEnabledAndMatches(ComponentInfo info, int flags, int userId) { 24116 synchronized (mPackages) { 24117 return mSettings.isEnabledAndMatchLPr(info, flags, userId); 24118 } 24119 } 24120 24121 @Override 24122 public boolean userNeedsBadging(int userId) { 24123 synchronized (mPackages) { 24124 return PackageManagerService.this.userNeedsBadging(userId); 24125 } 24126 } 24127 24128 @Override 24129 public void grantRuntimePermission(String packageName, String permName, int userId, 24130 boolean overridePolicy) { 24131 PackageManagerService.this.mPermissionManager.grantRuntimePermission( 24132 permName, packageName, overridePolicy, getCallingUid(), userId, 24133 mPermissionCallback); 24134 } 24135 24136 @Override 24137 public void revokeRuntimePermission(String packageName, String permName, int userId, 24138 boolean overridePolicy) { 24139 mPermissionManager.revokeRuntimePermission( 24140 permName, packageName, overridePolicy, userId, 24141 mPermissionCallback); 24142 } 24143 24144 @Override 24145 public String getNameForUid(int uid) { 24146 return PackageManagerService.this.getNameForUid(uid); 24147 } 24148 24149 @Override 24150 public void requestInstantAppResolutionPhaseTwo(AuxiliaryResolveInfo responseObj, 24151 Intent origIntent, String resolvedType, String callingPackage, 24152 Bundle verificationBundle, int userId) { 24153 PackageManagerService.this.requestInstantAppResolutionPhaseTwo( 24154 responseObj, origIntent, resolvedType, callingPackage, verificationBundle, 24155 userId); 24156 } 24157 24158 @Override 24159 public void grantEphemeralAccess(int userId, Intent intent, 24160 int targetAppId, int ephemeralAppId) { 24161 synchronized (mPackages) { 24162 mInstantAppRegistry.grantInstantAccessLPw(userId, intent, 24163 targetAppId, ephemeralAppId); 24164 } 24165 } 24166 24167 @Override 24168 public boolean isInstantAppInstallerComponent(ComponentName component) { 24169 synchronized (mPackages) { 24170 return mInstantAppInstallerActivity != null 24171 && mInstantAppInstallerActivity.getComponentName().equals(component); 24172 } 24173 } 24174 24175 @Override 24176 public void pruneInstantApps() { 24177 mInstantAppRegistry.pruneInstantApps(); 24178 } 24179 24180 @Override 24181 public String getSetupWizardPackageName() { 24182 return mSetupWizardPackage; 24183 } 24184 24185 public void setExternalSourcesPolicy(ExternalSourcesPolicy policy) { 24186 if (policy != null) { 24187 mExternalSourcesPolicy = policy; 24188 } 24189 } 24190 24191 @Override 24192 public boolean isPackagePersistent(String packageName) { 24193 synchronized (mPackages) { 24194 PackageParser.Package pkg = mPackages.get(packageName); 24195 return pkg != null 24196 ? ((pkg.applicationInfo.flags&(ApplicationInfo.FLAG_SYSTEM 24197 | ApplicationInfo.FLAG_PERSISTENT)) == 24198 (ApplicationInfo.FLAG_SYSTEM | ApplicationInfo.FLAG_PERSISTENT)) 24199 : false; 24200 } 24201 } 24202 24203 @Override 24204 public boolean isLegacySystemApp(PackageParser.Package pkg) { 24205 synchronized (mPackages) { 24206 final PackageSetting ps = (PackageSetting) pkg.mExtras; 24207 return mPromoteSystemApps 24208 && ps.isSystem() 24209 && mExistingSystemPackages.contains(ps.name); 24210 } 24211 } 24212 24213 @Override 24214 public List<PackageInfo> getOverlayPackages(int userId) { 24215 final ArrayList<PackageInfo> overlayPackages = new ArrayList<PackageInfo>(); 24216 synchronized (mPackages) { 24217 for (PackageParser.Package p : mPackages.values()) { 24218 if (p.mOverlayTarget != null) { 24219 PackageInfo pkg = generatePackageInfo((PackageSetting)p.mExtras, 0, userId); 24220 if (pkg != null) { 24221 overlayPackages.add(pkg); 24222 } 24223 } 24224 } 24225 } 24226 return overlayPackages; 24227 } 24228 24229 @Override 24230 public List<String> getTargetPackageNames(int userId) { 24231 List<String> targetPackages = new ArrayList<>(); 24232 synchronized (mPackages) { 24233 for (PackageParser.Package p : mPackages.values()) { 24234 if (p.mOverlayTarget == null) { 24235 targetPackages.add(p.packageName); 24236 } 24237 } 24238 } 24239 return targetPackages; 24240 } 24241 24242 @Override 24243 public boolean setEnabledOverlayPackages(int userId, @NonNull String targetPackageName, 24244 @Nullable List<String> overlayPackageNames) { 24245 synchronized (mPackages) { 24246 if (targetPackageName == null || mPackages.get(targetPackageName) == null) { 24247 Slog.e(TAG, "failed to find package " + targetPackageName); 24248 return false; 24249 } 24250 ArrayList<String> overlayPaths = null; 24251 if (overlayPackageNames != null && overlayPackageNames.size() > 0) { 24252 final int N = overlayPackageNames.size(); 24253 overlayPaths = new ArrayList<>(N); 24254 for (int i = 0; i < N; i++) { 24255 final String packageName = overlayPackageNames.get(i); 24256 final PackageParser.Package pkg = mPackages.get(packageName); 24257 if (pkg == null) { 24258 Slog.e(TAG, "failed to find package " + packageName); 24259 return false; 24260 } 24261 overlayPaths.add(pkg.baseCodePath); 24262 } 24263 } 24264 24265 final PackageSetting ps = mSettings.mPackages.get(targetPackageName); 24266 ps.setOverlayPaths(overlayPaths, userId); 24267 return true; 24268 } 24269 } 24270 24271 @Override 24272 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 24273 int flags, int userId, boolean resolveForStart, int filterCallingUid) { 24274 return resolveIntentInternal( 24275 intent, resolvedType, flags, userId, resolveForStart, filterCallingUid); 24276 } 24277 24278 @Override 24279 public ResolveInfo resolveService(Intent intent, String resolvedType, 24280 int flags, int userId, int callingUid) { 24281 return resolveServiceInternal(intent, resolvedType, flags, userId, callingUid); 24282 } 24283 24284 @Override 24285 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 24286 return PackageManagerService.this.resolveContentProviderInternal( 24287 name, flags, userId); 24288 } 24289 24290 @Override 24291 public void addIsolatedUid(int isolatedUid, int ownerUid) { 24292 synchronized (mPackages) { 24293 mIsolatedOwners.put(isolatedUid, ownerUid); 24294 } 24295 } 24296 24297 @Override 24298 public void removeIsolatedUid(int isolatedUid) { 24299 synchronized (mPackages) { 24300 mIsolatedOwners.delete(isolatedUid); 24301 } 24302 } 24303 24304 @Override 24305 public int getUidTargetSdkVersion(int uid) { 24306 synchronized (mPackages) { 24307 return getUidTargetSdkVersionLockedLPr(uid); 24308 } 24309 } 24310 24311 @Override 24312 public int getPackageTargetSdkVersion(String packageName) { 24313 synchronized (mPackages) { 24314 return getPackageTargetSdkVersionLockedLPr(packageName); 24315 } 24316 } 24317 24318 @Override 24319 public boolean canAccessInstantApps(int callingUid, int userId) { 24320 return PackageManagerService.this.canViewInstantApps(callingUid, userId); 24321 } 24322 24323 @Override 24324 public boolean canAccessComponent(int callingUid, ComponentName component, int userId) { 24325 synchronized (mPackages) { 24326 final PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 24327 return ps != null && !PackageManagerService.this.filterAppAccessLPr( 24328 ps, callingUid, component, TYPE_UNKNOWN, userId); 24329 } 24330 } 24331 24332 @Override 24333 public boolean hasInstantApplicationMetadata(String packageName, int userId) { 24334 synchronized (mPackages) { 24335 return mInstantAppRegistry.hasInstantApplicationMetadataLPr(packageName, userId); 24336 } 24337 } 24338 24339 @Override 24340 public void notifyPackageUse(String packageName, int reason) { 24341 synchronized (mPackages) { 24342 PackageManagerService.this.notifyPackageUseLocked(packageName, reason); 24343 } 24344 } 24345 24346 @Override 24347 public CheckPermissionDelegate getCheckPermissionDelegate() { 24348 synchronized (mPackages) { 24349 return PackageManagerService.this.getCheckPermissionDelegateLocked(); 24350 } 24351 } 24352 24353 @Override 24354 public void setCheckPermissionDelegate(CheckPermissionDelegate delegate) { 24355 synchronized (mPackages) { 24356 PackageManagerService.this.setCheckPermissionDelegateLocked(delegate); 24357 } 24358 } 24359 24360 @Override 24361 public SparseArray<String> getAppsWithSharedUserIds() { 24362 synchronized (mPackages) { 24363 return getAppsWithSharedUserIdsLocked(); 24364 } 24365 } 24366 24367 @Override 24368 public String getSharedUserIdForPackage(String packageName) { 24369 synchronized (mPackages) { 24370 return getSharedUserIdForPackageLocked(packageName); 24371 } 24372 } 24373 24374 @Override 24375 public String[] getPackagesForSharedUserId(String sharedUserId, int userId) { 24376 synchronized (mPackages) { 24377 return getPackagesForSharedUserIdLocked(sharedUserId, userId); 24378 } 24379 } 24380 24381 @Override 24382 public boolean isOnlyCoreApps() { 24383 return PackageManagerService.this.isOnlyCoreApps(); 24384 } 24385 24386 @Override 24387 public void freeStorage(String volumeUuid, long bytes, int storageFlags) 24388 throws IOException { 24389 PackageManagerService.this.freeStorage(volumeUuid, bytes, storageFlags); 24390 } 24391 24392 @Override 24393 public void forEachPackage(Consumer<PackageParser.Package> actionLocked) { 24394 PackageManagerService.this.forEachPackage(actionLocked); 24395 } 24396 24397 @Override 24398 public void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked, 24399 @UserIdInt int userId) { 24400 PackageManagerService.this.forEachInstalledPackage(actionLocked, userId); 24401 } 24402 24403 @Override 24404 public ArraySet<String> getEnabledComponents(String packageName, int userId) { 24405 synchronized (mPackages) { 24406 PackageSetting setting = mSettings.getPackageLPr(packageName); 24407 if (setting == null) { 24408 return new ArraySet<>(); 24409 } 24410 return setting.getEnabledComponents(userId); 24411 } 24412 } 24413 24414 @Override 24415 public ArraySet<String> getDisabledComponents(String packageName, int userId) { 24416 synchronized (mPackages) { 24417 PackageSetting setting = mSettings.getPackageLPr(packageName); 24418 if (setting == null) { 24419 return new ArraySet<>(); 24420 } 24421 return setting.getDisabledComponents(userId); 24422 } 24423 } 24424 24425 @Override 24426 public @PackageManager.EnabledState int getApplicationEnabledState( 24427 String packageName, int userId) { 24428 synchronized (mPackages) { 24429 PackageSetting setting = mSettings.getPackageLPr(packageName); 24430 if (setting == null) { 24431 return COMPONENT_ENABLED_STATE_DEFAULT; 24432 } 24433 return setting.getEnabled(userId); 24434 } 24435 } 24436 24437 @Override 24438 public void setEnableRollbackCode(int token, int enableRollbackCode) { 24439 PackageManagerService.this.setEnableRollbackCode(token, enableRollbackCode); 24440 } 24441 24442 /** 24443 * Ask the package manager to compile layouts in the given package. 24444 */ 24445 @Override 24446 public boolean compileLayouts(String packageName) { 24447 PackageParser.Package pkg; 24448 synchronized (mPackages) { 24449 pkg = mPackages.get(packageName); 24450 if (pkg == null) { 24451 return false; 24452 } 24453 } 24454 return mArtManagerService.compileLayouts(pkg); 24455 } 24456 24457 @Override 24458 public void finishPackageInstall(int token, boolean didLaunch) { 24459 PackageManagerService.this.finishPackageInstall(token, didLaunch); 24460 } 24461 24462 @Nullable 24463 @Override 24464 public String removeLegacyDefaultBrowserPackageName(int userId) { 24465 synchronized (mPackages) { 24466 return mSettings.removeDefaultBrowserPackageNameLPw(userId); 24467 } 24468 } 24469 24470 @Override 24471 public void setDefaultBrowserProvider(@NonNull DefaultBrowserProvider provider) { 24472 synchronized (mPackages) { 24473 mDefaultBrowserProvider = provider; 24474 } 24475 } 24476 24477 @Override 24478 public void setDefaultDialerProvider(@NonNull DefaultDialerProvider provider) { 24479 synchronized (mPackages) { 24480 mDefaultDialerProvider = provider; 24481 } 24482 } 24483 24484 @Override 24485 public void setDefaultHomeProvider(@NonNull DefaultHomeProvider provider) { 24486 synchronized (mPackages) { 24487 mDefaultHomeProvider = provider; 24488 } 24489 } 24490 24491 @Override 24492 public boolean isApexPackage(String packageName) { 24493 return PackageManagerService.this.mApexManager.isApexPackage(packageName); 24494 } 24495 24496 @Override 24497 public void uninstallApex(String packageName, long versionCode, int userId, 24498 IntentSender intentSender) { 24499 final int callerUid = Binder.getCallingUid(); 24500 if (callerUid != Process.ROOT_UID && callerUid != Process.SHELL_UID) { 24501 throw new SecurityException("Not allowed to uninstall apexes"); 24502 } 24503 PackageInstallerService.PackageDeleteObserverAdapter adapter = 24504 new PackageInstallerService.PackageDeleteObserverAdapter( 24505 PackageManagerService.this.mContext, intentSender, packageName, 24506 false, userId); 24507 if (userId != UserHandle.USER_ALL) { 24508 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 24509 "Can't uninstall an apex for a single user"); 24510 return; 24511 } 24512 final ApexManager am = PackageManagerService.this.mApexManager; 24513 PackageInfo activePackage = am.getPackageInfo(packageName, 24514 ApexManager.MATCH_ACTIVE_PACKAGE); 24515 if (activePackage == null) { 24516 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 24517 packageName + " is not an apex package"); 24518 return; 24519 } 24520 if (versionCode != PackageManager.VERSION_CODE_HIGHEST 24521 && activePackage.getLongVersionCode() != versionCode) { 24522 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 24523 "Active version " + activePackage.getLongVersionCode() 24524 + " is not equal to " + versionCode + "]"); 24525 return; 24526 } 24527 if (!am.uninstallApex(activePackage.applicationInfo.sourceDir)) { 24528 adapter.onPackageDeleted(packageName, PackageManager.DELETE_FAILED_ABORTED, 24529 "Failed to uninstall apex " + packageName); 24530 } else { 24531 adapter.onPackageDeleted(packageName, PackageManager.DELETE_SUCCEEDED, 24532 null); 24533 } 24534 } 24535 24536 @Override 24537 public boolean wereDefaultPermissionsGrantedSinceBoot(int userId) { 24538 synchronized (mPackages) { 24539 return mDefaultPermissionPolicy.wereDefaultPermissionsGrantedSinceBoot(userId); 24540 } 24541 } 24542 24543 @Override 24544 public void setRuntimePermissionsFingerPrint(@NonNull String fingerPrint, 24545 @UserIdInt int userId) { 24546 synchronized (mPackages) { 24547 mSettings.setRuntimePermissionsFingerPrintLPr(fingerPrint, userId); 24548 } 24549 } 24550 24551 @Override 24552 public void migrateLegacyObbData() { 24553 try { 24554 mInstaller.migrateLegacyObbData(); 24555 } catch (Exception e) { 24556 Slog.wtf(TAG, e); 24557 } 24558 } 24559 24560 @Override 24561 public void notifyingOnNextUserRemovalForTest() { 24562 mBlockDeleteOnUserRemoveForTest.close(); 24563 } 24564 24565 @Override 24566 public void userRemovedForTest() { 24567 mBlockDeleteOnUserRemoveForTest.open(); 24568 } 24569 } 24570 24571 @GuardedBy("mPackages") 24572 private SparseArray<String> getAppsWithSharedUserIdsLocked() { 24573 final SparseArray<String> sharedUserIds = new SparseArray<>(); 24574 synchronized (mPackages) { 24575 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 24576 sharedUserIds.put(UserHandle.getAppId(setting.userId), setting.name); 24577 } 24578 } 24579 return sharedUserIds; 24580 } 24581 24582 @GuardedBy("mPackages") 24583 private String getSharedUserIdForPackageLocked(String packageName) { 24584 final PackageSetting ps = mSettings.mPackages.get(packageName); 24585 return (ps != null && ps.isSharedUser()) ? ps.sharedUser.name : null; 24586 } 24587 24588 @GuardedBy("mPackages") 24589 private String[] getPackagesForSharedUserIdLocked(String sharedUserId, int userId) { 24590 try { 24591 final SharedUserSetting sus = mSettings.getSharedUserLPw( 24592 sharedUserId, 0, 0, false); 24593 if (sus == null) { 24594 return EmptyArray.STRING; 24595 } 24596 String[] res = new String[sus.packages.size()]; 24597 final Iterator<PackageSetting> it = sus.packages.iterator(); 24598 int i = 0; 24599 while (it.hasNext()) { 24600 PackageSetting ps = it.next(); 24601 if (ps.getInstalled(userId)) { 24602 res[i++] = ps.name; 24603 } else { 24604 res = ArrayUtils.removeElement(String.class, res, res[i]); 24605 } 24606 } 24607 return res; 24608 } catch (PackageManagerException e) { 24609 // Should not happen 24610 } 24611 return EmptyArray.STRING; 24612 } 24613 24614 @Override 24615 public int getRuntimePermissionsVersion(@UserIdInt int userId) { 24616 Preconditions.checkArgumentNonnegative(userId); 24617 mContext.enforceCallingOrSelfPermission( 24618 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 24619 "setRuntimePermissionVersion"); 24620 synchronized (mPackages) { 24621 return mSettings.getDefaultRuntimePermissionsVersionLPr(userId); 24622 } 24623 } 24624 24625 @Override 24626 public void setRuntimePermissionsVersion(int version, @UserIdInt int userId) { 24627 Preconditions.checkArgumentNonnegative(version); 24628 Preconditions.checkArgumentNonnegative(userId); 24629 mContext.enforceCallingOrSelfPermission( 24630 Manifest.permission.ADJUST_RUNTIME_PERMISSIONS_POLICY, 24631 "setRuntimePermissionVersion"); 24632 synchronized (mPackages) { 24633 mSettings.setDefaultRuntimePermissionsVersionLPr(version, userId); 24634 } 24635 } 24636 24637 @Override 24638 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 24639 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 24640 synchronized (mPackages) { 24641 final long identity = Binder.clearCallingIdentity(); 24642 try { 24643 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierApps( 24644 packageNames, userId); 24645 } finally { 24646 Binder.restoreCallingIdentity(identity); 24647 } 24648 } 24649 } 24650 24651 @Override 24652 public void grantDefaultPermissionsToEnabledImsServices(String[] packageNames, int userId) { 24653 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledImsServices"); 24654 synchronized (mPackages) { 24655 final long identity = Binder.clearCallingIdentity(); 24656 try { 24657 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledImsServices( 24658 packageNames, userId); 24659 } finally { 24660 Binder.restoreCallingIdentity(identity); 24661 } 24662 } 24663 } 24664 24665 @Override 24666 public void grantDefaultPermissionsToEnabledTelephonyDataServices( 24667 String[] packageNames, int userId) { 24668 enforceSystemOrPhoneCaller("grantDefaultPermissionsToEnabledTelephonyDataServices"); 24669 synchronized (mPackages) { 24670 Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy. 24671 grantDefaultPermissionsToEnabledTelephonyDataServices( 24672 packageNames, userId)); 24673 } 24674 } 24675 24676 @Override 24677 public void revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24678 String[] packageNames, int userId) { 24679 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromDisabledTelephonyDataServices"); 24680 synchronized (mPackages) { 24681 Binder.withCleanCallingIdentity( () -> mDefaultPermissionPolicy. 24682 revokeDefaultPermissionsFromDisabledTelephonyDataServices( 24683 packageNames, userId)); 24684 } 24685 } 24686 24687 @Override 24688 public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) { 24689 enforceSystemOrPhoneCaller("grantDefaultPermissionsToActiveLuiApp"); 24690 synchronized (mPackages) { 24691 final long identity = Binder.clearCallingIdentity(); 24692 try { 24693 mDefaultPermissionPolicy.grantDefaultPermissionsToActiveLuiApp( 24694 packageName, userId); 24695 } finally { 24696 Binder.restoreCallingIdentity(identity); 24697 } 24698 } 24699 } 24700 24701 @Override 24702 public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) { 24703 enforceSystemOrPhoneCaller("revokeDefaultPermissionsFromLuiApps"); 24704 synchronized (mPackages) { 24705 final long identity = Binder.clearCallingIdentity(); 24706 try { 24707 mDefaultPermissionPolicy.revokeDefaultPermissionsFromLuiApps(packageNames, userId); 24708 } finally { 24709 Binder.restoreCallingIdentity(identity); 24710 } 24711 } 24712 } 24713 24714 void forEachPackage(Consumer<PackageParser.Package> actionLocked) { 24715 synchronized (mPackages) { 24716 int numPackages = mPackages.size(); 24717 for (int i = 0; i < numPackages; i++) { 24718 actionLocked.accept(mPackages.valueAt(i)); 24719 } 24720 } 24721 } 24722 24723 void forEachInstalledPackage(@NonNull Consumer<PackageParser.Package> actionLocked, 24724 @UserIdInt int userId) { 24725 synchronized (mPackages) { 24726 int numPackages = mPackages.size(); 24727 for (int i = 0; i < numPackages; i++) { 24728 PackageParser.Package pkg = mPackages.valueAt(i); 24729 PackageSetting setting = mSettings.getPackageLPr(pkg.packageName); 24730 if (setting == null || !setting.getInstalled(userId)) { 24731 continue; 24732 } 24733 actionLocked.accept(pkg); 24734 } 24735 } 24736 } 24737 24738 private static void enforceSystemOrPhoneCaller(String tag) { 24739 int callingUid = Binder.getCallingUid(); 24740 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 24741 throw new SecurityException( 24742 "Cannot call " + tag + " from UID " + callingUid); 24743 } 24744 } 24745 24746 boolean isHistoricalPackageUsageAvailable() { 24747 return mPackageUsage.isHistoricalPackageUsageAvailable(); 24748 } 24749 24750 /** 24751 * Return a <b>copy</b> of the collection of packages known to the package manager. 24752 * @return A copy of the values of mPackages. 24753 */ 24754 Collection<PackageParser.Package> getPackages() { 24755 synchronized (mPackages) { 24756 return new ArrayList<>(mPackages.values()); 24757 } 24758 } 24759 24760 /** 24761 * Logs process start information (including base APK hash) to the security log. 24762 * @hide 24763 */ 24764 @Override 24765 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 24766 String apkFile, int pid) { 24767 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24768 return; 24769 } 24770 if (!SecurityLog.isLoggingEnabled()) { 24771 return; 24772 } 24773 Bundle data = new Bundle(); 24774 data.putLong("startTimestamp", System.currentTimeMillis()); 24775 data.putString("processName", processName); 24776 data.putInt("uid", uid); 24777 data.putString("seinfo", seinfo); 24778 data.putString("apkFile", apkFile); 24779 data.putInt("pid", pid); 24780 Message msg = mProcessLoggingHandler.obtainMessage( 24781 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 24782 msg.setData(data); 24783 mProcessLoggingHandler.sendMessage(msg); 24784 } 24785 24786 public CompilerStats.PackageStats getCompilerPackageStats(String pkgName) { 24787 return mCompilerStats.getPackageStats(pkgName); 24788 } 24789 24790 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(PackageParser.Package pkg) { 24791 return getOrCreateCompilerPackageStats(pkg.packageName); 24792 } 24793 24794 public CompilerStats.PackageStats getOrCreateCompilerPackageStats(String pkgName) { 24795 return mCompilerStats.getOrCreatePackageStats(pkgName); 24796 } 24797 24798 public void deleteCompilerPackageStats(String pkgName) { 24799 mCompilerStats.deletePackageStats(pkgName); 24800 } 24801 24802 @Override 24803 public int getInstallReason(String packageName, int userId) { 24804 final int callingUid = Binder.getCallingUid(); 24805 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24806 true /* requireFullPermission */, false /* checkShell */, 24807 "get install reason"); 24808 synchronized (mPackages) { 24809 final PackageSetting ps = mSettings.mPackages.get(packageName); 24810 if (filterAppAccessLPr(ps, callingUid, userId)) { 24811 return PackageManager.INSTALL_REASON_UNKNOWN; 24812 } 24813 if (ps != null) { 24814 return ps.getInstallReason(userId); 24815 } 24816 } 24817 return PackageManager.INSTALL_REASON_UNKNOWN; 24818 } 24819 24820 @Override 24821 public boolean canRequestPackageInstalls(String packageName, int userId) { 24822 return canRequestPackageInstallsInternal(packageName, 0, userId, 24823 true /* throwIfPermNotDeclared*/); 24824 } 24825 24826 private boolean canRequestPackageInstallsInternal(String packageName, int flags, int userId, 24827 boolean throwIfPermNotDeclared) { 24828 int callingUid = Binder.getCallingUid(); 24829 int uid = getPackageUid(packageName, 0, userId); 24830 if (callingUid != uid && callingUid != Process.ROOT_UID 24831 && callingUid != Process.SYSTEM_UID) { 24832 throw new SecurityException( 24833 "Caller uid " + callingUid + " does not own package " + packageName); 24834 } 24835 ApplicationInfo info = getApplicationInfo(packageName, flags, userId); 24836 if (info == null) { 24837 return false; 24838 } 24839 if (info.targetSdkVersion < Build.VERSION_CODES.O) { 24840 return false; 24841 } 24842 if (isInstantApp(packageName, userId)) { 24843 return false; 24844 } 24845 String appOpPermission = Manifest.permission.REQUEST_INSTALL_PACKAGES; 24846 String[] packagesDeclaringPermission = getAppOpPermissionPackages(appOpPermission); 24847 if (!ArrayUtils.contains(packagesDeclaringPermission, packageName)) { 24848 if (throwIfPermNotDeclared) { 24849 throw new SecurityException("Need to declare " + appOpPermission 24850 + " to call this api"); 24851 } else { 24852 Slog.e(TAG, "Need to declare " + appOpPermission + " to call this api"); 24853 return false; 24854 } 24855 } 24856 if (sUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId) 24857 || sUserManager.hasUserRestriction( 24858 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, userId)) { 24859 return false; 24860 } 24861 if (mExternalSourcesPolicy != null) { 24862 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 24863 return isTrusted == PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 24864 } 24865 return false; 24866 } 24867 24868 @Override 24869 public ComponentName getInstantAppResolverSettingsComponent() { 24870 return mInstantAppResolverSettingsComponent; 24871 } 24872 24873 @Override 24874 public ComponentName getInstantAppInstallerComponent() { 24875 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 24876 return null; 24877 } 24878 return mInstantAppInstallerActivity == null 24879 ? null : mInstantAppInstallerActivity.getComponentName(); 24880 } 24881 24882 @Override 24883 public String getInstantAppAndroidId(String packageName, int userId) { 24884 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.ACCESS_INSTANT_APPS, 24885 "getInstantAppAndroidId"); 24886 mPermissionManager.enforceCrossUserPermission(Binder.getCallingUid(), userId, 24887 true /* requireFullPermission */, false /* checkShell */, 24888 "getInstantAppAndroidId"); 24889 // Make sure the target is an Instant App. 24890 if (!isInstantApp(packageName, userId)) { 24891 return null; 24892 } 24893 synchronized (mPackages) { 24894 return mInstantAppRegistry.getInstantAppAndroidIdLPw(packageName, userId); 24895 } 24896 } 24897 24898 boolean canHaveOatDir(String packageName) { 24899 synchronized (mPackages) { 24900 PackageParser.Package p = mPackages.get(packageName); 24901 if (p == null) { 24902 return false; 24903 } 24904 return p.canHaveOatDir(); 24905 } 24906 } 24907 24908 private String getOatDir(PackageParser.Package pkg) { 24909 if (!pkg.canHaveOatDir()) { 24910 return null; 24911 } 24912 File codePath = new File(pkg.codePath); 24913 if (codePath.isDirectory()) { 24914 return PackageDexOptimizer.getOatDir(codePath).getAbsolutePath(); 24915 } 24916 return null; 24917 } 24918 24919 void deleteOatArtifactsOfPackage(String packageName) { 24920 final String[] instructionSets; 24921 final List<String> codePaths; 24922 final String oatDir; 24923 final PackageParser.Package pkg; 24924 synchronized (mPackages) { 24925 pkg = mPackages.get(packageName); 24926 } 24927 instructionSets = getAppDexInstructionSets(pkg.applicationInfo); 24928 codePaths = pkg.getAllCodePaths(); 24929 oatDir = getOatDir(pkg); 24930 24931 for (String codePath : codePaths) { 24932 for (String isa : instructionSets) { 24933 try { 24934 mInstaller.deleteOdex(codePath, isa, oatDir); 24935 } catch (InstallerException e) { 24936 Log.e(TAG, "Failed deleting oat files for " + codePath, e); 24937 } 24938 } 24939 } 24940 } 24941 24942 Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 24943 Set<String> unusedPackages = new HashSet<>(); 24944 long currentTimeInMillis = System.currentTimeMillis(); 24945 synchronized (mPackages) { 24946 for (PackageParser.Package pkg : mPackages.values()) { 24947 PackageSetting ps = mSettings.mPackages.get(pkg.packageName); 24948 if (ps == null) { 24949 continue; 24950 } 24951 PackageDexUsage.PackageUseInfo packageUseInfo = 24952 getDexManager().getPackageUseInfoOrDefault(pkg.packageName); 24953 if (PackageManagerServiceUtils 24954 .isUnusedSinceTimeInMillis(ps.firstInstallTime, currentTimeInMillis, 24955 downgradeTimeThresholdMillis, packageUseInfo, 24956 pkg.getLatestPackageUseTimeInMills(), 24957 pkg.getLatestForegroundPackageUseTimeInMills())) { 24958 unusedPackages.add(pkg.packageName); 24959 } 24960 } 24961 } 24962 return unusedPackages; 24963 } 24964 24965 @Override 24966 public void setHarmfulAppWarning(@NonNull String packageName, @Nullable CharSequence warning, 24967 int userId) { 24968 final int callingUid = Binder.getCallingUid(); 24969 final int callingAppId = UserHandle.getAppId(callingUid); 24970 24971 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24972 true /*requireFullPermission*/, true /*checkShell*/, "setHarmfulAppInfo"); 24973 24974 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24975 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24976 throw new SecurityException("Caller must have the " 24977 + SET_HARMFUL_APP_WARNINGS + " permission."); 24978 } 24979 24980 synchronized(mPackages) { 24981 mSettings.setHarmfulAppWarningLPw(packageName, warning, userId); 24982 scheduleWritePackageRestrictionsLocked(userId); 24983 } 24984 } 24985 24986 @Nullable 24987 @Override 24988 public CharSequence getHarmfulAppWarning(@NonNull String packageName, int userId) { 24989 final int callingUid = Binder.getCallingUid(); 24990 final int callingAppId = UserHandle.getAppId(callingUid); 24991 24992 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 24993 true /*requireFullPermission*/, true /*checkShell*/, "getHarmfulAppInfo"); 24994 24995 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID && 24996 checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 24997 throw new SecurityException("Caller must have the " 24998 + SET_HARMFUL_APP_WARNINGS + " permission."); 24999 } 25000 25001 synchronized(mPackages) { 25002 return mSettings.getHarmfulAppWarningLPr(packageName, userId); 25003 } 25004 } 25005 25006 @Override 25007 public boolean isPackageStateProtected(@NonNull String packageName, @UserIdInt int userId) { 25008 final int callingUid = Binder.getCallingUid(); 25009 final int callingAppId = UserHandle.getAppId(callingUid); 25010 25011 mPermissionManager.enforceCrossUserPermission(callingUid, userId, 25012 false /*requireFullPermission*/, true /*checkShell*/, "isPackageStateProtected"); 25013 25014 if (callingAppId != Process.SYSTEM_UID && callingAppId != Process.ROOT_UID 25015 && checkUidPermission(MANAGE_DEVICE_ADMINS, callingUid) != PERMISSION_GRANTED) { 25016 throw new SecurityException("Caller must have the " 25017 + MANAGE_DEVICE_ADMINS + " permission."); 25018 } 25019 25020 return mProtectedPackages.isPackageStateProtected(userId, packageName); 25021 } 25022 25023 @Override 25024 public void sendDeviceCustomizationReadyBroadcast() { 25025 mContext.enforceCallingPermission(Manifest.permission.SEND_DEVICE_CUSTOMIZATION_READY, 25026 "sendDeviceCustomizationReadyBroadcast"); 25027 25028 final long ident = Binder.clearCallingIdentity(); 25029 try { 25030 final Intent intent = new Intent(Intent.ACTION_DEVICE_CUSTOMIZATION_READY); 25031 intent.setFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND); 25032 final IActivityManager am = ActivityManager.getService(); 25033 final String[] requiredPermissions = { 25034 Manifest.permission.RECEIVE_DEVICE_CUSTOMIZATION_READY, 25035 }; 25036 try { 25037 am.broadcastIntent(null, intent, null, null, 0, null, null, requiredPermissions, 25038 android.app.AppOpsManager.OP_NONE, null, false, false, UserHandle.USER_ALL); 25039 } catch (RemoteException e) { 25040 throw e.rethrowFromSystemServer(); 25041 } 25042 } finally { 25043 Binder.restoreCallingIdentity(ident); 25044 } 25045 } 25046 25047 static class ActiveInstallSession { 25048 private final String mPackageName; 25049 private final File mStagedDir; 25050 private final IPackageInstallObserver2 mObserver; 25051 private final PackageInstaller.SessionParams mSessionParams; 25052 private final String mInstallerPackageName; 25053 private final int mInstallerUid; 25054 private final UserHandle mUser; 25055 private final SigningDetails mSigningDetails; 25056 25057 ActiveInstallSession(String packageName, File stagedDir, IPackageInstallObserver2 observer, 25058 PackageInstaller.SessionParams sessionParams, String installerPackageName, 25059 int installerUid, UserHandle user, SigningDetails signingDetails) { 25060 mPackageName = packageName; 25061 mStagedDir = stagedDir; 25062 mObserver = observer; 25063 mSessionParams = sessionParams; 25064 mInstallerPackageName = installerPackageName; 25065 mInstallerUid = installerUid; 25066 mUser = user; 25067 mSigningDetails = signingDetails; 25068 } 25069 25070 public String getPackageName() { 25071 return mPackageName; 25072 } 25073 25074 public File getStagedDir() { 25075 return mStagedDir; 25076 } 25077 25078 public IPackageInstallObserver2 getObserver() { 25079 return mObserver; 25080 } 25081 25082 public PackageInstaller.SessionParams getSessionParams() { 25083 return mSessionParams; 25084 } 25085 25086 public String getInstallerPackageName() { 25087 return mInstallerPackageName; 25088 } 25089 25090 public int getInstallerUid() { 25091 return mInstallerUid; 25092 } 25093 25094 public UserHandle getUser() { 25095 return mUser; 25096 } 25097 25098 public SigningDetails getSigningDetails() { 25099 return mSigningDetails; 25100 } 25101 } 25102 } 25103 25104 interface PackageSender { 25105 /** 25106 * @param userIds User IDs where the action occurred on a full application 25107 * @param instantUserIds User IDs where the action occurred on an instant application 25108 */ 25109 void sendPackageBroadcast(final String action, final String pkg, 25110 final Bundle extras, final int flags, final String targetPkg, 25111 final IIntentReceiver finishedReceiver, final int[] userIds, int[] instantUserIds); 25112 void sendPackageAddedForNewUsers(String packageName, boolean sendBootCompleted, 25113 boolean includeStopped, int appId, int[] userIds, int[] instantUserIds); 25114 void notifyPackageAdded(String packageName, int uid); 25115 void notifyPackageChanged(String packageName, int uid); 25116 void notifyPackageRemoved(String packageName, int uid); 25117 } 25118