1 /* 2 * Copyright (C) 2021 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.REQUEST_DELETE_PACKAGES; 22 import static android.Manifest.permission.SET_HARMFUL_APP_WARNINGS; 23 import static android.content.ContentProvider.isAuthorityRedirectedForCloneProfile; 24 import static android.content.Intent.ACTION_MAIN; 25 import static android.content.Intent.CATEGORY_DEFAULT; 26 import static android.content.Intent.CATEGORY_HOME; 27 import static android.content.pm.PackageManager.CERT_INPUT_RAW_X509; 28 import static android.content.pm.PackageManager.CERT_INPUT_SHA256; 29 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 30 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 31 import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 32 import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 33 import static android.content.pm.PackageManager.MATCH_ANY_USER; 34 import static android.content.pm.PackageManager.MATCH_APEX; 35 import static android.content.pm.PackageManager.MATCH_ARCHIVED_PACKAGES; 36 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 37 import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 38 import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 39 import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 40 import static android.content.pm.PackageManager.MATCH_KNOWN_PACKAGES; 41 import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 42 import static android.content.pm.PackageManager.PERMISSION_GRANTED; 43 import static android.content.pm.PackageManager.TYPE_ACTIVITY; 44 import static android.content.pm.PackageManager.TYPE_PROVIDER; 45 import static android.content.pm.PackageManager.TYPE_RECEIVER; 46 import static android.content.pm.PackageManager.TYPE_SERVICE; 47 import static android.content.pm.PackageManager.TYPE_UNKNOWN; 48 import static android.os.Process.INVALID_UID; 49 import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 50 51 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 52 import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 53 import static com.android.server.pm.PackageManagerService.DEBUG_INSTALL; 54 import static com.android.server.pm.PackageManagerService.DEBUG_INSTANT; 55 import static com.android.server.pm.PackageManagerService.DEBUG_PACKAGE_INFO; 56 import static com.android.server.pm.PackageManagerService.DEBUG_PREFERRED; 57 import static com.android.server.pm.PackageManagerService.EMPTY_INT_ARRAY; 58 import static com.android.server.pm.PackageManagerService.HIDE_EPHEMERAL_APIS; 59 import static com.android.server.pm.PackageManagerService.TAG; 60 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatureArrays; 61 import static com.android.server.pm.PackageManagerServiceUtils.compareSignatures; 62 import static com.android.server.pm.PackageManagerServiceUtils.isSystemOrRootOrShell; 63 import static com.android.server.pm.parsing.PackageInfoUtils.getDeprecatedSignatures; 64 import static com.android.server.pm.resolution.ComponentResolver.RESOLVE_PRIORITY_SORTER; 65 66 import android.Manifest; 67 import android.annotation.NonNull; 68 import android.annotation.Nullable; 69 import android.annotation.UserIdInt; 70 import android.app.ActivityManager; 71 import android.app.admin.DevicePolicyManagerInternal; 72 import android.companion.virtual.VirtualDeviceManager; 73 import android.content.ComponentName; 74 import android.content.Context; 75 import android.content.Intent; 76 import android.content.IntentFilter; 77 import android.content.PermissionChecker; 78 import android.content.pm.ActivityInfo; 79 import android.content.pm.ApplicationInfo; 80 import android.content.pm.AuxiliaryResolveInfo; 81 import android.content.pm.ComponentInfo; 82 import android.content.pm.Flags; 83 import android.content.pm.InstallSourceInfo; 84 import android.content.pm.InstantAppRequest; 85 import android.content.pm.InstantAppResolveInfo; 86 import android.content.pm.InstrumentationInfo; 87 import android.content.pm.KeySet; 88 import android.content.pm.PackageInfo; 89 import android.content.pm.PackageManager; 90 import android.content.pm.PackageManagerInternal; 91 import android.content.pm.ParceledListSlice; 92 import android.content.pm.ProcessInfo; 93 import android.content.pm.ProviderInfo; 94 import android.content.pm.ResolveInfo; 95 import android.content.pm.ServiceInfo; 96 import android.content.pm.SharedLibraryInfo; 97 import android.content.pm.Signature; 98 import android.content.pm.SigningDetails; 99 import android.content.pm.SigningInfo; 100 import android.content.pm.UserInfo; 101 import android.content.pm.UserPackage; 102 import android.content.pm.VersionedPackage; 103 import android.os.Binder; 104 import android.os.Build; 105 import android.os.IBinder; 106 import android.os.ParcelableException; 107 import android.os.PatternMatcher; 108 import android.os.Process; 109 import android.os.Trace; 110 import android.os.UserHandle; 111 import android.os.UserManager; 112 import android.os.storage.StorageManager; 113 import android.provider.ContactsContract; 114 import android.text.TextUtils; 115 import android.util.ArrayMap; 116 import android.util.ArraySet; 117 import android.util.Log; 118 import android.util.LogPrinter; 119 import android.util.LongSparseLongArray; 120 import android.util.MathUtils; 121 import android.util.Pair; 122 import android.util.PrintWriterPrinter; 123 import android.util.Slog; 124 import android.util.SparseArray; 125 import android.util.Xml; 126 import android.util.proto.ProtoOutputStream; 127 128 import com.android.internal.annotations.VisibleForTesting; 129 import com.android.internal.pm.pkg.component.ParsedActivity; 130 import com.android.internal.pm.pkg.component.ParsedInstrumentation; 131 import com.android.internal.pm.pkg.component.ParsedIntentInfo; 132 import com.android.internal.pm.pkg.component.ParsedMainComponent; 133 import com.android.internal.pm.pkg.component.ParsedProvider; 134 import com.android.internal.pm.pkg.component.ParsedService; 135 import com.android.internal.util.ArrayUtils; 136 import com.android.internal.util.CollectionUtils; 137 import com.android.internal.util.IndentingPrintWriter; 138 import com.android.internal.util.Preconditions; 139 import com.android.modules.utils.TypedXmlSerializer; 140 import com.android.server.ondeviceintelligence.OnDeviceIntelligenceManagerInternal; 141 import com.android.server.pm.dex.DexManager; 142 import com.android.server.pm.dex.PackageDexUsage; 143 import com.android.server.pm.parsing.PackageInfoUtils; 144 import com.android.server.pm.parsing.pkg.AndroidPackageUtils; 145 import com.android.server.pm.permission.PermissionManagerServiceInternal; 146 import com.android.server.pm.pkg.AndroidPackage; 147 import com.android.server.pm.pkg.PackageState; 148 import com.android.server.pm.pkg.PackageStateInternal; 149 import com.android.server.pm.pkg.PackageStateUtils; 150 import com.android.server.pm.pkg.PackageUserStateInternal; 151 import com.android.server.pm.pkg.PackageUserStateUtils; 152 import com.android.server.pm.pkg.SharedUserApi; 153 import com.android.server.pm.resolution.ComponentResolverApi; 154 import com.android.server.pm.verify.domain.DomainVerificationManagerInternal; 155 import com.android.server.uri.UriGrantsManagerInternal; 156 import com.android.server.utils.WatchedArrayMap; 157 import com.android.server.utils.WatchedLongSparseArray; 158 import com.android.server.utils.WatchedSparseBooleanArray; 159 import com.android.server.utils.WatchedSparseIntArray; 160 import com.android.server.wm.ActivityTaskManagerInternal; 161 162 import libcore.util.EmptyArray; 163 164 import java.io.BufferedOutputStream; 165 import java.io.FileDescriptor; 166 import java.io.FileOutputStream; 167 import java.io.IOException; 168 import java.io.PrintWriter; 169 import java.nio.charset.StandardCharsets; 170 import java.util.ArrayList; 171 import java.util.Arrays; 172 import java.util.Collection; 173 import java.util.Collections; 174 import java.util.Comparator; 175 import java.util.List; 176 import java.util.Objects; 177 import java.util.Set; 178 import java.util.UUID; 179 180 /** 181 * This class contains the implementation of the Computer functions. It 182 * is entirely self-contained - it has no implicit access to 183 * PackageManagerService. 184 */ 185 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PRIVATE) 186 public class ComputerEngine implements Computer { 187 188 // TODO: Move this to its own interface implemented by the pm.Settings implementation 189 protected class Settings { 190 191 @NonNull 192 private final com.android.server.pm.Settings mSettings; 193 getPackages()194 public ArrayMap<String, ? extends PackageStateInternal> getPackages() { 195 return mSettings.getPackagesLocked().untrackedStorage(); 196 } 197 getDisabledSystemPackages()198 public ArrayMap<String, ? extends PackageStateInternal> getDisabledSystemPackages() { 199 return mSettings.getDisabledSystemPackagesLocked().untrackedStorage(); 200 } 201 Settings(@onNull com.android.server.pm.Settings settings)202 public Settings(@NonNull com.android.server.pm.Settings settings) { 203 mSettings = settings; 204 } 205 206 @Nullable getPackage(@onNull String packageName)207 public PackageStateInternal getPackage(@NonNull String packageName) { 208 return mSettings.getPackageLPr(packageName); 209 } 210 211 @Nullable getDisabledSystemPkg(@onNull String packageName)212 public PackageStateInternal getDisabledSystemPkg(@NonNull String packageName) { 213 return mSettings.getDisabledSystemPkgLPr(packageName); 214 } 215 isEnabledAndMatch(ComponentInfo componentInfo, int flags, int userId)216 public boolean isEnabledAndMatch(ComponentInfo componentInfo, int flags, int userId) { 217 PackageStateInternal pkgState = getPackage(componentInfo.packageName); 218 if (pkgState == null) { 219 return false; 220 } 221 222 return PackageUserStateUtils.isMatch(pkgState.getUserStateOrDefault(userId), 223 componentInfo, flags); 224 } 225 226 @VisibleForTesting(visibility = VisibleForTesting.Visibility.PACKAGE) isEnabledAndMatch(AndroidPackage pkg, ParsedMainComponent component, long flags, int userId)227 public boolean isEnabledAndMatch(AndroidPackage pkg, ParsedMainComponent component, 228 long flags, int userId) { 229 PackageStateInternal pkgState = getPackage(component.getPackageName()); 230 if (pkgState == null) { 231 return false; 232 } 233 234 return PackageUserStateUtils.isMatch(pkgState.getUserStateOrDefault(userId), 235 pkgState.isSystem(), pkg.isEnabled(), component, flags); 236 } 237 238 @Nullable getCrossProfileIntentResolver(@serIdInt int userId)239 public CrossProfileIntentResolver getCrossProfileIntentResolver(@UserIdInt int userId) { 240 return mSettings.getCrossProfileIntentResolver(userId); 241 } 242 243 // TODO: Find replacement 244 @Nullable getSettingBase(int appId)245 public SettingBase getSettingBase(int appId) { 246 return mSettings.getSettingLPr(appId); 247 } 248 249 @Nullable getRenamedPackageLPr(String packageName)250 public String getRenamedPackageLPr(String packageName) { 251 return mSettings.getRenamedPackageLPr(packageName); 252 } 253 254 @Nullable getPersistentPreferredActivities( @serIdInt int userId)255 public PersistentPreferredIntentResolver getPersistentPreferredActivities( 256 @UserIdInt int userId) { 257 return mSettings.getPersistentPreferredActivities(userId); 258 } 259 dumpVersionLPr(@onNull IndentingPrintWriter indentingPrintWriter)260 public void dumpVersionLPr(@NonNull IndentingPrintWriter indentingPrintWriter) { 261 mSettings.dumpVersionLPr(indentingPrintWriter); 262 } 263 dumpPreferred(PrintWriter pw, DumpState dumpState, String packageName)264 public void dumpPreferred(PrintWriter pw, DumpState dumpState, String packageName) { 265 mSettings.dumpPreferred(pw, dumpState, packageName); 266 } 267 268 // TODO: Move to separate utility writePreferredActivitiesLPr(@onNull TypedXmlSerializer serializer, int userId, boolean full)269 public void writePreferredActivitiesLPr(@NonNull TypedXmlSerializer serializer, int userId, 270 boolean full) throws IllegalArgumentException, IllegalStateException, IOException { 271 mSettings.writePreferredActivitiesLPr(serializer, userId, full); 272 } 273 getPreferredActivities(@serIdInt int userId)274 public PreferredIntentResolver getPreferredActivities(@UserIdInt int userId) { 275 return mSettings.getPreferredActivities(userId); 276 } 277 278 @Nullable getSharedUserFromId(String name)279 public SharedUserSetting getSharedUserFromId(String name) { 280 try { 281 return mSettings.getSharedUserLPw(name, 0, 0, false /*create*/); 282 } catch (PackageManagerException ignored) { 283 // This is impossible do to create being false 284 throw new RuntimeException(ignored); 285 } 286 } 287 getBlockUninstall(@serIdInt int userId, @NonNull String packageName)288 public boolean getBlockUninstall(@UserIdInt int userId, @NonNull String packageName) { 289 return mSettings.getBlockUninstallLPr(userId, packageName); 290 } 291 292 @PackageManager.EnabledState getApplicationEnabledSetting(@onNull String packageName, @UserIdInt int userId)293 public int getApplicationEnabledSetting(@NonNull String packageName, 294 @UserIdInt int userId) throws PackageManager.NameNotFoundException { 295 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 296 } 297 298 @PackageManager.EnabledState getComponentEnabledSetting(@onNull ComponentName component, @UserIdInt int userId)299 public int getComponentEnabledSetting(@NonNull ComponentName component, 300 @UserIdInt int userId) throws PackageManager.NameNotFoundException { 301 return mSettings.getComponentEnabledSettingLPr(component, userId); 302 } 303 304 @NonNull getKeySetManagerService()305 public KeySetManagerService getKeySetManagerService() { 306 return mSettings.getKeySetManagerService(); 307 } 308 309 @NonNull getSharedUsers()310 ArrayMap<String, ? extends SharedUserApi> getSharedUsers() { 311 return mSettings.getSharedUsersLocked().untrackedStorage(); 312 } 313 314 @Nullable getSharedUserFromPackageName(String packageName)315 public SharedUserApi getSharedUserFromPackageName(String packageName) { 316 return mSettings.getSharedUserSettingLPr(packageName); 317 } 318 319 @Nullable getSharedUserFromAppId(int sharedUserAppId)320 public SharedUserApi getSharedUserFromAppId(int sharedUserAppId) { 321 return (SharedUserSetting) mSettings.getSettingLPr(sharedUserAppId); 322 } 323 324 @NonNull getSharedUserPackages(int sharedUserAppId)325 public ArraySet<PackageStateInternal> getSharedUserPackages(int sharedUserAppId) { 326 final ArraySet<PackageStateInternal> res = new ArraySet<>(); 327 final SharedUserSetting sharedUserSetting = 328 (SharedUserSetting) mSettings.getSettingLPr(sharedUserAppId); 329 if (sharedUserSetting != null) { 330 final ArraySet<? extends PackageStateInternal> sharedUserPackages = 331 sharedUserSetting.getPackageStates(); 332 for (PackageStateInternal ps : sharedUserPackages) { 333 res.add(ps); 334 } 335 } 336 return res; 337 } 338 dumpPackagesProto(ProtoOutputStream proto)339 public void dumpPackagesProto(ProtoOutputStream proto) { 340 mSettings.dumpPackagesProto(proto); 341 } 342 dumpPermissions(PrintWriter pw, String packageName, ArraySet<String> permissionNames, DumpState dumpState)343 public void dumpPermissions(PrintWriter pw, String packageName, 344 ArraySet<String> permissionNames, DumpState dumpState) { 345 mSettings.dumpPermissions(pw, packageName, permissionNames, dumpState); 346 } 347 dumpPackages(PrintWriter pw, String packageName, ArraySet<String> permissionNames, DumpState dumpState, boolean checkin)348 public void dumpPackages(PrintWriter pw, String packageName, 349 ArraySet<String> permissionNames, DumpState dumpState, boolean checkin) { 350 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 351 } 352 dumpKeySet(PrintWriter pw, String packageName, DumpState dumpState)353 public void dumpKeySet(PrintWriter pw, String packageName, DumpState dumpState) { 354 mSettings.getKeySetManagerService().dumpLPr(pw, packageName, dumpState); 355 } 356 dumpSharedUsers(PrintWriter pw, String packageName, ArraySet<String> permissionNames, DumpState dumpState, boolean checkin)357 public void dumpSharedUsers(PrintWriter pw, String packageName, 358 ArraySet<String> permissionNames, DumpState dumpState, boolean checkin) { 359 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 360 } 361 dumpReadMessages(PrintWriter pw, DumpState dumpState)362 public void dumpReadMessages(PrintWriter pw, DumpState dumpState) { 363 mSettings.dumpReadMessages(pw, dumpState); 364 } 365 dumpSharedUsersProto(ProtoOutputStream proto)366 public void dumpSharedUsersProto(ProtoOutputStream proto) { 367 mSettings.dumpSharedUsersProto(proto); 368 } 369 getVolumePackages( @onNull String volumeUuid)370 public List<? extends PackageStateInternal> getVolumePackages( 371 @NonNull String volumeUuid) { 372 return mSettings.getVolumePackagesLPr(volumeUuid); 373 } 374 } 375 376 private static final Comparator<ProviderInfo> sProviderInitOrderSorter = (p1, p2) -> { 377 final int v1 = p1.initOrder; 378 final int v2 = p2.initOrder; 379 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 380 }; 381 382 private final int mVersion; 383 384 // The administrative use counter. 385 private int mUsed = 0; 386 387 // Cached attributes. The names in this class are the same as the 388 // names in PackageManagerService; see that class for documentation. 389 protected final Settings mSettings; 390 private final WatchedSparseIntArray mIsolatedOwners; 391 private final WatchedArrayMap<String, AndroidPackage> mPackages; 392 private final WatchedArrayMap<ComponentName, ParsedInstrumentation> 393 mInstrumentation; 394 private final SharedLibrariesRead mSharedLibraries; 395 private final ComponentName mLocalResolveComponentName; 396 private final ActivityInfo mResolveActivity; 397 private final WatchedSparseBooleanArray mWebInstantAppsDisabled; 398 private final ActivityInfo mLocalInstantAppInstallerActivity; 399 private final ResolveInfo mInstantAppInstallerInfo; 400 private final InstantAppRegistry mInstantAppRegistry; 401 private final ApplicationInfo mLocalAndroidApplication; 402 private final AppsFilterSnapshot mAppsFilter; 403 private final WatchedArrayMap<String, Integer> mFrozenPackages; 404 405 // Immutable service attribute 406 private final String mAppPredictionServicePackage; 407 408 // The following are not cloned since changes to these have never 409 // been guarded by the PMS lock. 410 private final Context mContext; 411 private final UserManagerService mUserManager; 412 private final PermissionManagerServiceInternal mPermissionManager; 413 private final ApexManager mApexManager; 414 private final PackageManagerServiceInjector mInjector; 415 private final ComponentResolverApi mComponentResolver; 416 private final InstantAppResolverConnection mInstantAppResolverConnection; 417 private final DefaultAppProvider mDefaultAppProvider; 418 private final DomainVerificationManagerInternal mDomainVerificationManager; 419 private final PackageDexOptimizer mPackageDexOptimizer; 420 private final DexManager mDexManager; 421 private final CompilerStats mCompilerStats; 422 private final PackageManagerInternal.ExternalSourcesPolicy mExternalSourcesPolicy; 423 private final CrossProfileIntentResolverEngine mCrossProfileIntentResolverEngine; 424 425 // PackageManagerService attributes that are primitives are referenced through the 426 // pms object directly. Primitives are the only attributes so referenced. 427 protected final PackageManagerService mService; safeMode()428 private boolean safeMode() { 429 return mService.getSafeMode(); 430 } resolveComponentName()431 protected ComponentName resolveComponentName() { 432 return mLocalResolveComponentName; 433 } instantAppInstallerActivity()434 protected ActivityInfo instantAppInstallerActivity() { 435 return mLocalInstantAppInstallerActivity; 436 } androidApplication()437 protected ApplicationInfo androidApplication() { 438 return mLocalAndroidApplication; 439 } 440 ComputerEngine(PackageManagerService.Snapshot args, int version)441 ComputerEngine(PackageManagerService.Snapshot args, int version) { 442 mVersion = version; 443 mSettings = new Settings(args.settings); 444 mIsolatedOwners = args.isolatedOwners; 445 mPackages = args.packages; 446 mSharedLibraries = args.sharedLibraries; 447 mInstrumentation = args.instrumentation; 448 mWebInstantAppsDisabled = args.webInstantAppsDisabled; 449 mLocalResolveComponentName = args.resolveComponentName; 450 mResolveActivity = args.resolveActivity; 451 mLocalInstantAppInstallerActivity = args.instantAppInstallerActivity; 452 mInstantAppInstallerInfo = args.instantAppInstallerInfo; 453 mInstantAppRegistry = args.instantAppRegistry; 454 mLocalAndroidApplication = args.androidApplication; 455 mAppsFilter = args.appsFilter; 456 mFrozenPackages = args.frozenPackages; 457 mComponentResolver = args.componentResolver; 458 459 mAppPredictionServicePackage = args.appPredictionServicePackage; 460 461 // The following are not cached copies. Instead they are 462 // references to outside services. 463 mPermissionManager = args.service.mPermissionManager; 464 mUserManager = args.service.mUserManager; 465 mContext = args.service.mContext; 466 mInjector = args.service.mInjector; 467 mApexManager = args.service.mApexManager; 468 mInstantAppResolverConnection = args.service.mInstantAppResolverConnection; 469 mDefaultAppProvider = args.service.getDefaultAppProvider(); 470 mDomainVerificationManager = args.service.mDomainVerificationManager; 471 mPackageDexOptimizer = args.service.mPackageDexOptimizer; 472 mDexManager = args.service.getDexManager(); 473 mCompilerStats = args.service.mCompilerStats; 474 mExternalSourcesPolicy = args.service.mExternalSourcesPolicy; 475 mCrossProfileIntentResolverEngine = new CrossProfileIntentResolverEngine( 476 mUserManager, mDomainVerificationManager, mDefaultAppProvider, mContext); 477 478 // Used to reference PMS attributes that are primitives and which are not 479 // updated under control of the PMS lock. 480 mService = args.service; 481 } 482 483 @Override getVersion()484 public int getVersion() { 485 return mVersion; 486 } 487 488 /** 489 * Record that the snapshot was used. 490 */ use()491 public final Computer use() { 492 mUsed++; 493 return this; 494 } 495 496 /** 497 * Return the usage counter. 498 */ getUsed()499 public final int getUsed() { 500 return mUsed; 501 } 502 queryIntentActivitiesInternal( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, @PackageManagerInternal.PrivateResolveFlags long privateResolveFlags, int filterCallingUid, int callingPid, int userId, boolean resolveForStart, boolean allowDynamicSplits)503 public final @NonNull List<ResolveInfo> queryIntentActivitiesInternal( 504 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 505 @PackageManagerInternal.PrivateResolveFlags long privateResolveFlags, 506 int filterCallingUid, int callingPid, int userId, boolean resolveForStart, 507 boolean allowDynamicSplits) { 508 if (!mUserManager.exists(userId)) return Collections.emptyList(); 509 510 // Allow to match activities of quarantined packages. 511 flags |= PackageManager.MATCH_QUARANTINED_COMPONENTS; 512 513 final String instantAppPkgName = getInstantAppPackageName(filterCallingUid); 514 enforceCrossUserPermission(Binder.getCallingUid(), userId, 515 false /* requireFullPermission */, false /* checkShell */, 516 "query intent activities"); 517 final String pkgName = intent.getPackage(); 518 Intent originalIntent = null; 519 ComponentName comp = intent.getComponent(); 520 if (comp == null) { 521 if (intent.getSelector() != null) { 522 originalIntent = intent; 523 intent = intent.getSelector(); 524 comp = intent.getComponent(); 525 } 526 } 527 528 flags = updateFlagsForResolve(flags, userId, filterCallingUid, resolveForStart, 529 comp != null || pkgName != null /*onlyExposedExplicitly*/, 530 isImplicitImageCaptureIntentAndNotSetByDpc(intent, userId, resolvedType, 531 flags)); 532 533 var args = new SaferIntentUtils.IntentArgs(intent, resolvedType, 534 false /* isReceiver */, resolveForStart, filterCallingUid, callingPid); 535 args.platformCompat = mInjector.getCompatibility(); 536 args.snapshot = this; 537 538 List<ResolveInfo> list = Collections.emptyList(); 539 boolean skipPostResolution = false; 540 if (comp != null) { 541 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 542 if (ai != null) { 543 // When specifying an explicit component, we prevent the activity from being 544 // used when either 1) the calling package is normal and the activity is within 545 // an ephemeral application or 2) the calling package is ephemeral and the 546 // activity is not visible to ephemeral applications. 547 final boolean matchInstantApp = 548 (flags & PackageManager.MATCH_INSTANT) != 0; 549 final boolean matchVisibleToInstantAppOnly = 550 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 551 final boolean matchExplicitlyVisibleOnly = 552 (flags & PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY) != 0; 553 final boolean isCallerInstantApp = 554 instantAppPkgName != null; 555 final boolean isTargetSameInstantApp = 556 comp.getPackageName().equals(instantAppPkgName); 557 final boolean isTargetInstantApp = 558 (ai.applicationInfo.privateFlags 559 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 560 final boolean isTargetVisibleToInstantApp = 561 (ai.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 562 final boolean isTargetExplicitlyVisibleToInstantApp = 563 isTargetVisibleToInstantApp 564 && (ai.flags & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) 565 == 0; 566 final boolean isTargetHiddenFromInstantApp = 567 !isTargetVisibleToInstantApp 568 || (matchExplicitlyVisibleOnly 569 && !isTargetExplicitlyVisibleToInstantApp); 570 final boolean blockInstantResolution = 571 !isTargetSameInstantApp 572 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 573 || (matchVisibleToInstantAppOnly && isCallerInstantApp 574 && isTargetHiddenFromInstantApp)); 575 final boolean resolveForStartNonExported = resolveForStart 576 && !ai.exported 577 && !isCallerSameApp(pkgName, filterCallingUid); 578 final boolean blockNormalResolution = 579 (!resolveForStart || resolveForStartNonExported) 580 && !isTargetInstantApp 581 && !isCallerInstantApp 582 && shouldFilterApplication( 583 getPackageStateInternal(ai.applicationInfo.packageName, 584 Process.SYSTEM_UID), filterCallingUid, userId); 585 if (!blockInstantResolution && !blockNormalResolution) { 586 final ResolveInfo ri = new ResolveInfo(); 587 ri.activityInfo = ai; 588 ri.userHandle = UserHandle.of(userId); 589 list = new ArrayList<>(1); 590 list.add(ri); 591 SaferIntentUtils.enforceIntentFilterMatching(args, list); 592 } 593 } 594 } else { 595 QueryIntentActivitiesResult lockedResult = 596 queryIntentActivitiesInternalBody( 597 intent, resolvedType, flags, filterCallingUid, userId, 598 resolveForStart, allowDynamicSplits, pkgName, instantAppPkgName); 599 if (lockedResult.answer != null) { 600 skipPostResolution = true; 601 list = lockedResult.answer; 602 } else { 603 if (lockedResult.addInstant) { 604 String callingPkgName = getInstantAppPackageName(filterCallingUid); 605 boolean isRequesterInstantApp = isInstantApp(callingPkgName, userId); 606 lockedResult.result = maybeAddInstantAppInstaller( 607 lockedResult.result, intent, resolvedType, flags, 608 userId, resolveForStart, isRequesterInstantApp); 609 } 610 if (lockedResult.sortResult) { 611 lockedResult.result.sort(RESOLVE_PRIORITY_SORTER); 612 } 613 list = lockedResult.result; 614 } 615 SaferIntentUtils.blockNullAction(args, list); 616 } 617 618 if (originalIntent != null) { 619 // We also have to ensure all components match the original intent 620 args.intent = originalIntent; 621 SaferIntentUtils.enforceIntentFilterMatching(args, list); 622 } 623 624 return skipPostResolution ? list : applyPostResolutionFilter( 625 list, instantAppPkgName, allowDynamicSplits, filterCallingUid, 626 resolveForStart, userId, intent); 627 } 628 629 @NonNull 630 @Override queryIntentActivitiesInternal(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId)631 public final List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, String resolvedType, 632 @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId) { 633 return queryIntentActivitiesInternal( 634 intent, resolvedType, flags, 0 /*privateResolveFlags*/, filterCallingUid, 635 Process.INVALID_PID, userId, 636 /*resolveForStart*/ false, /*allowDynamicSplits*/ true); 637 } 638 queryIntentActivitiesInternal(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId)639 public final @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 640 String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId) { 641 return queryIntentActivitiesInternal( 642 intent, resolvedType, flags, 0 /*privateResolveFlags*/, 643 Binder.getCallingUid(), Process.INVALID_PID, userId, 644 /*resolveForStart*/ false, /*allowDynamicSplits*/ true); 645 } 646 queryIntentServicesInternal( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid, int callingPid, boolean includeInstantApps, boolean resolveForStart)647 public final @NonNull List<ResolveInfo> queryIntentServicesInternal( 648 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 649 int userId, int callingUid, int callingPid, 650 boolean includeInstantApps, boolean resolveForStart) { 651 if (!mUserManager.exists(userId)) return Collections.emptyList(); 652 enforceCrossUserOrProfilePermission(callingUid, 653 userId, 654 false /*requireFullPermission*/, 655 false /*checkShell*/, 656 "query intent receivers"); 657 final String instantAppPkgName = getInstantAppPackageName(callingUid); 658 flags = updateFlagsForResolve(flags, userId, callingUid, includeInstantApps, 659 false /* isImplicitImageCaptureIntentAndNotSetByDpc */); 660 661 var args = new SaferIntentUtils.IntentArgs(intent, resolvedType, 662 false /* isReceiver */, resolveForStart, callingUid, callingPid); 663 args.platformCompat = mInjector.getCompatibility(); 664 args.snapshot = this; 665 666 Intent originalIntent = null; 667 ComponentName comp = intent.getComponent(); 668 if (comp == null) { 669 if (intent.getSelector() != null) { 670 originalIntent = intent; 671 intent = intent.getSelector(); 672 comp = intent.getComponent(); 673 } 674 } 675 List<ResolveInfo> list = Collections.emptyList(); 676 if (comp != null) { 677 final ServiceInfo si = getServiceInfo(comp, flags, userId); 678 if (si != null) { 679 // When specifying an explicit component, we prevent the service from being 680 // used when either 1) the service is in an instant application and the 681 // caller is not the same instant application or 2) the calling package is 682 // ephemeral and the activity is not visible to ephemeral applications. 683 final boolean matchInstantApp = 684 (flags & PackageManager.MATCH_INSTANT) != 0; 685 final boolean matchVisibleToInstantAppOnly = 686 (flags & PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY) != 0; 687 final boolean isCallerInstantApp = 688 instantAppPkgName != null; 689 final boolean isTargetSameInstantApp = 690 comp.getPackageName().equals(instantAppPkgName); 691 final boolean isTargetInstantApp = 692 (si.applicationInfo.privateFlags 693 & ApplicationInfo.PRIVATE_FLAG_INSTANT) != 0; 694 final boolean isTargetHiddenFromInstantApp = 695 (si.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) == 0; 696 final boolean blockInstantResolution = 697 !isTargetSameInstantApp 698 && ((!matchInstantApp && !isCallerInstantApp && isTargetInstantApp) 699 || (matchVisibleToInstantAppOnly && isCallerInstantApp 700 && isTargetHiddenFromInstantApp)); 701 702 final boolean blockNormalResolution = !isTargetInstantApp && !isCallerInstantApp 703 && shouldFilterApplication( 704 getPackageStateInternal(si.applicationInfo.packageName, 705 Process.SYSTEM_UID), callingUid, userId); 706 if (!blockInstantResolution && !blockNormalResolution) { 707 final ResolveInfo ri = new ResolveInfo(); 708 ri.serviceInfo = si; 709 list = new ArrayList<>(1); 710 list.add(ri); 711 SaferIntentUtils.enforceIntentFilterMatching(args, list); 712 } 713 } 714 } else { 715 list = queryIntentServicesInternalBody(intent, resolvedType, flags, 716 userId, callingUid, instantAppPkgName); 717 SaferIntentUtils.blockNullAction(args, list); 718 } 719 720 if (originalIntent != null) { 721 // We also have to ensure all components match the original intent 722 args.intent = originalIntent; 723 SaferIntentUtils.enforceIntentFilterMatching(args, list); 724 } 725 726 return list; 727 } 728 queryIntentServicesInternalBody(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid, String instantAppPkgName)729 protected @NonNull List<ResolveInfo> queryIntentServicesInternalBody(Intent intent, 730 String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, 731 int callingUid, String instantAppPkgName) { 732 // reader 733 String pkgName = intent.getPackage(); 734 if (pkgName == null) { 735 final List<ResolveInfo> resolveInfos = mComponentResolver.queryServices(this, intent, 736 resolvedType, flags, userId); 737 if (resolveInfos == null) { 738 return Collections.emptyList(); 739 } 740 return applyPostServiceResolutionFilter( 741 resolveInfos, instantAppPkgName, userId, callingUid); 742 } 743 final AndroidPackage pkg = mPackages.get(pkgName); 744 if (pkg != null) { 745 final List<ResolveInfo> resolveInfos = mComponentResolver.queryServices(this, intent, 746 resolvedType, flags, pkg.getServices(), 747 userId); 748 if (resolveInfos == null) { 749 return Collections.emptyList(); 750 } 751 return applyPostServiceResolutionFilter( 752 resolveInfos, instantAppPkgName, userId, callingUid); 753 } 754 return Collections.emptyList(); 755 } 756 queryIntentActivitiesInternalBody( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId, boolean resolveForStart, boolean allowDynamicSplits, String pkgName, String instantAppPkgName)757 public @NonNull QueryIntentActivitiesResult queryIntentActivitiesInternalBody( 758 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 759 int filterCallingUid, int userId, boolean resolveForStart, boolean allowDynamicSplits, 760 String pkgName, String instantAppPkgName) { 761 // reader 762 boolean sortResult = false; 763 boolean addInstant = false; 764 List<ResolveInfo> result = new ArrayList<>(); 765 // crossProfileResults will hold resolve infos from resolution across profiles. 766 List<CrossProfileDomainInfo> crossProfileResults = new ArrayList<>(); 767 if (pkgName == null) { 768 if (!mCrossProfileIntentResolverEngine.shouldSkipCurrentProfile(this, intent, 769 resolvedType, userId)) { 770 771 final List<ResolveInfo> queryResult = mComponentResolver.queryActivities(this, 772 intent, resolvedType, flags, userId); 773 // If the user doesn't exist, the queryResult is null 774 if (queryResult != null) { 775 /* 776 Check for results in the current profile only if there is no 777 {@link CrossProfileIntentFilter} for user with flag 778 {@link PackageManager.SKIP_CURRENT_PROFILE} set. 779 */ 780 result.addAll(filterIfNotSystemUser(queryResult, userId)); 781 } 782 } 783 addInstant = isInstantAppResolutionAllowed(intent, result, userId, 784 false /*skipPackageCheck*/, flags); 785 786 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 787 788 /* 789 Calling {@link com.android.server.pm.CrossProfileIntentResolverEngine#resolveIntent} to 790 get list of {@link CrossProfileDomainInfo} which have {@link ResolveInfo}s from linked 791 profiles. 792 */ 793 crossProfileResults = mCrossProfileIntentResolverEngine.resolveIntent(this, intent, 794 resolvedType, userId, flags, pkgName, hasNonNegativePriorityResult, 795 resolveForStart, mSettings::getPackage); 796 if (intent.hasWebURI() || !crossProfileResults.isEmpty()) sortResult = true; 797 } else { 798 final PackageStateInternal setting = 799 getPackageStateInternal(pkgName, Process.SYSTEM_UID); 800 801 if (setting != null && setting.getAndroidPackage() != null && (resolveForStart 802 || !shouldFilterApplication(setting, filterCallingUid, userId))) { 803 final List<ResolveInfo> queryResult = mComponentResolver.queryActivities(this, 804 intent, resolvedType, flags, setting.getAndroidPackage().getActivities(), 805 userId); 806 // If the user doesn't exist, the queryResult is null 807 if (queryResult != null) { 808 result.addAll(filterIfNotSystemUser(queryResult, userId)); 809 } 810 } 811 if (result == null || result.size() == 0) { 812 // the caller wants to resolve for a particular package; however, there 813 // were no installed results, so, try to find an ephemeral result 814 addInstant = isInstantAppResolutionAllowed(intent, null /*result*/, userId, 815 true /*skipPackageCheck*/, flags); 816 } 817 /* 818 Calling {@link com.android.server.pm.CrossProfileIntentResolverEngine#resolveIntent} to 819 get list of {@link CrossProfileDomainInfo} which have {@link ResolveInfo}s from linked 820 profiles. 821 */ 822 crossProfileResults = mCrossProfileIntentResolverEngine.resolveIntent(this, intent, 823 resolvedType, userId, flags, pkgName, false, 824 resolveForStart, mSettings::getPackage); 825 } 826 827 /* 828 Calling {@link com.android.server.pm. 829 CrossProfileIntentResolverEngine#combineFilterAndCreateQueryAcitivitesResponse} to 830 combine results from current and cross profiles. This also filters any resolve info 831 based on domain preference(if required). 832 */ 833 return mCrossProfileIntentResolverEngine 834 .combineFilterAndCreateQueryActivitiesResponse(this, intent, resolvedType, 835 instantAppPkgName, pkgName, allowDynamicSplits, flags, userId, 836 filterCallingUid, resolveForStart, result, crossProfileResults, 837 areWebInstantAppsDisabled(userId), addInstant, sortResult, 838 mSettings::getPackage); 839 } 840 841 /** 842 * Returns the activity component that can handle install failures. 843 * <p>By default, the instant application installer handles failures. However, an 844 * application may want to handle failures on its own. Applications do this by 845 * creating an activity with an intent filter that handles the action 846 * {@link Intent#ACTION_INSTALL_FAILURE}. 847 */ findInstallFailureActivity( String packageName, int filterCallingUid, int userId)848 private @Nullable ComponentName findInstallFailureActivity( 849 String packageName, int filterCallingUid, int userId) { 850 final Intent failureActivityIntent = new Intent(Intent.ACTION_INSTALL_FAILURE); 851 failureActivityIntent.setPackage(packageName); 852 // IMPORTANT: disallow dynamic splits to avoid an infinite loop 853 final List<ResolveInfo> result = queryIntentActivitiesInternal( 854 failureActivityIntent, null /*resolvedType*/, 0 /*flags*/, 855 0 /*privateResolveFlags*/, filterCallingUid, Process.INVALID_PID, userId, 856 /*resolveForStart*/ false, /*allowDynamicSplits*/ false); 857 final int numResults = result.size(); 858 if (numResults > 0) { 859 for (int i = 0; i < numResults; i++) { 860 final ResolveInfo info = result.get(i); 861 if (info.activityInfo.splitName != null) { 862 continue; 863 } 864 return new ComponentName(packageName, info.activityInfo.name); 865 } 866 } 867 return null; 868 } 869 getActivityInfo(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int userId)870 public final ActivityInfo getActivityInfo(ComponentName component, 871 @PackageManager.ResolveInfoFlagsBits long flags, int userId) { 872 return getActivityInfoInternal(component, flags, Binder.getCallingUid(), userId); 873 } 874 875 /** 876 * Similar to {@link Computer#getActivityInfo(android.content.ComponentName, long, int)} but 877 * only visible as internal service. This method bypass INTERACT_ACROSS_USERS or 878 * INTERACT_ACROSS_USERS_FULL permission checks and only to be used for intent resolution across 879 * chained cross profiles 880 * @param component application's component 881 * @param flags resolve info flags 882 * @param userId user id where activity resides 883 * @return ActivityInfo corresponding to requested component. 884 */ getActivityInfoCrossProfile(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int userId)885 public final ActivityInfo getActivityInfoCrossProfile(ComponentName component, 886 @PackageManager.ResolveInfoFlagsBits long flags, int userId) { 887 if (!mUserManager.exists(userId)) return null; 888 flags = updateFlagsForComponent(flags, userId); 889 890 return getActivityInfoInternalBody(component, flags, Binder.getCallingUid(), userId); 891 } 892 893 /** 894 * Important: The provided filterCallingUid is used exclusively to filter out activities 895 * that can be seen based on user state. It's typically the original caller uid prior 896 * to clearing. Because it can only be provided by trusted code, its value can be 897 * trusted and will be used as-is; unlike userId which will be validated by this method. 898 */ getActivityInfoInternal(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId)899 public final ActivityInfo getActivityInfoInternal(ComponentName component, 900 @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId) { 901 if (!mUserManager.exists(userId)) return null; 902 flags = updateFlagsForComponent(flags, userId); 903 904 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 905 enforceCrossUserPermission(Binder.getCallingUid(), userId, 906 false /* requireFullPermission */, false /* checkShell */, 907 "get activity info"); 908 } 909 910 return getActivityInfoInternalBody(component, flags, filterCallingUid, userId); 911 } 912 getActivityInfoInternalBody(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId)913 protected ActivityInfo getActivityInfoInternalBody(ComponentName component, 914 @PackageManager.ResolveInfoFlagsBits long flags, int filterCallingUid, int userId) { 915 ParsedActivity a = mComponentResolver.getActivity(component); 916 917 // Allow to match activities of quarantined packages. 918 flags |= PackageManager.MATCH_QUARANTINED_COMPONENTS; 919 920 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 921 922 AndroidPackage pkg = a == null ? null : mPackages.get(a.getPackageName()); 923 if (pkg != null && mSettings.isEnabledAndMatch(pkg, a, flags, userId)) { 924 PackageStateInternal ps = mSettings.getPackage(component.getPackageName()); 925 if (ps == null) return null; 926 if (shouldFilterApplication( 927 ps, filterCallingUid, component, TYPE_ACTIVITY, userId)) { 928 return null; 929 } 930 return PackageInfoUtils.generateActivityInfo(pkg, 931 a, flags, ps.getUserStateOrDefault(userId), userId, ps); 932 } 933 if (resolveComponentName().equals(component)) { 934 return PackageInfoUtils.generateDelegateActivityInfo(mResolveActivity, 935 flags, PackageUserStateInternal.DEFAULT, userId); 936 } 937 return null; 938 } 939 getPackage(String packageName)940 public AndroidPackage getPackage(String packageName) { 941 packageName = resolveInternalPackageName( 942 packageName, PackageManager.VERSION_CODE_HIGHEST); 943 return mPackages.get(packageName); 944 } 945 getPackage(int uid)946 public AndroidPackage getPackage(int uid) { 947 final String[] packageNames = getPackagesForUidInternal(uid, Process.SYSTEM_UID); 948 AndroidPackage pkg = null; 949 final int numPackages = packageNames == null ? 0 : packageNames.length; 950 for (int i = 0; pkg == null && i < numPackages; i++) { 951 pkg = mPackages.get(packageNames[i]); 952 } 953 return pkg; 954 } 955 generateApplicationInfoFromSettings(String packageName, long flags, int filterCallingUid, int userId)956 public final ApplicationInfo generateApplicationInfoFromSettings(String packageName, 957 long flags, int filterCallingUid, int userId) { 958 if (!mUserManager.exists(userId)) return null; 959 PackageStateInternal ps = mSettings.getPackage(packageName); 960 if (ps != null) { 961 if (filterSharedLibPackage(ps, filterCallingUid, userId, flags)) { 962 return null; 963 } 964 if (shouldFilterApplication(ps, filterCallingUid, userId)) { 965 return null; 966 } 967 if (ps.getAndroidPackage() == null) { 968 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 969 if (pInfo != null) { 970 return pInfo.applicationInfo; 971 } 972 return null; 973 } 974 ApplicationInfo ai = PackageInfoUtils.generateApplicationInfo(ps.getPkg(), 975 flags, ps.getUserStateOrDefault(userId), userId, ps); 976 if (ai != null) { 977 ai.packageName = resolveExternalPackageName(ps.getPkg()); 978 } 979 return ai; 980 } 981 return null; 982 } 983 getApplicationInfo(String packageName, @PackageManager.ApplicationInfoFlagsBits long flags, int userId)984 public final ApplicationInfo getApplicationInfo(String packageName, 985 @PackageManager.ApplicationInfoFlagsBits long flags, int userId) { 986 return getApplicationInfoInternal(packageName, flags, Binder.getCallingUid(), userId); 987 } 988 989 /** 990 * Important: The provided filterCallingUid is used exclusively to filter out applications 991 * that can be seen based on user state. It's typically the original caller uid prior 992 * to clearing. Because it can only be provided by trusted code, its value can be 993 * trusted and will be used as-is; unlike userId which will be validated by this method. 994 */ getApplicationInfoInternal(String packageName, @PackageManager.ApplicationInfoFlagsBits long flags, int filterCallingUid, int userId)995 public final ApplicationInfo getApplicationInfoInternal(String packageName, 996 @PackageManager.ApplicationInfoFlagsBits long flags, 997 int filterCallingUid, int userId) { 998 if (!mUserManager.exists(userId)) return null; 999 flags = updateFlagsForApplication(flags, userId); 1000 1001 if (!isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId)) { 1002 enforceCrossUserPermission(Binder.getCallingUid(), userId, 1003 false /* requireFullPermission */, false /* checkShell */, 1004 "get application info"); 1005 } 1006 1007 return getApplicationInfoInternalBody(packageName, flags, filterCallingUid, userId); 1008 } 1009 getApplicationInfoInternalBody(String packageName, @PackageManager.ApplicationInfoFlagsBits long flags, int filterCallingUid, int userId)1010 protected ApplicationInfo getApplicationInfoInternalBody(String packageName, 1011 @PackageManager.ApplicationInfoFlagsBits long flags, 1012 int filterCallingUid, int userId) { 1013 // writer 1014 // Normalize package name to handle renamed packages and static libs 1015 packageName = resolveInternalPackageName(packageName, 1016 PackageManager.VERSION_CODE_HIGHEST); 1017 1018 AndroidPackage p = mPackages.get(packageName); 1019 if (DEBUG_PACKAGE_INFO) { 1020 Log.v( 1021 TAG, "getApplicationInfo " + packageName 1022 + ": " + p); 1023 } 1024 final boolean matchApex = (flags & MATCH_APEX) != 0; 1025 if (p != null) { 1026 PackageStateInternal ps = mSettings.getPackage(packageName); 1027 if (ps == null) return null; 1028 if (!matchApex && p.isApex()) { 1029 return null; 1030 } 1031 if (filterSharedLibPackage(ps, filterCallingUid, userId, flags)) { 1032 return null; 1033 } 1034 if (shouldFilterApplication(ps, filterCallingUid, userId)) { 1035 return null; 1036 } 1037 // Note: isEnabledLP() does not apply here - always return info 1038 ApplicationInfo ai = PackageInfoUtils.generateApplicationInfo( 1039 p, flags, ps.getUserStateOrDefault(userId), userId, ps); 1040 if (ai != null) { 1041 ai.packageName = resolveExternalPackageName(p); 1042 } 1043 return ai; 1044 } 1045 if ("android".equals(packageName) || "system".equals(packageName)) { 1046 return androidApplication(); 1047 } 1048 if ((flags & (MATCH_KNOWN_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0) { 1049 // Already generates the external package name 1050 return generateApplicationInfoFromSettings(packageName, 1051 flags, filterCallingUid, userId); 1052 } 1053 return null; 1054 } 1055 1056 /** 1057 * Report the 'Home' activity which is currently set as "always use this one". If non is set 1058 * then reports the most likely home activity or null if there are more than one. 1059 */ getDefaultHomeActivity(int userId)1060 public final ComponentName getDefaultHomeActivity(int userId) { 1061 List<ResolveInfo> allHomeCandidates = new ArrayList<>(); 1062 ComponentName cn = getHomeActivitiesAsUser(allHomeCandidates, userId); 1063 if (cn != null) { 1064 return cn; 1065 } 1066 // TODO: This should not happen since there should always be a default package set for 1067 // ROLE_HOME in RoleManager. Continue with a warning log for now. 1068 Slog.w(TAG, "Default package for ROLE_HOME is not set in RoleManager"); 1069 1070 // Find the launcher with the highest priority and return that component if there are no 1071 // other home activity with the same priority. 1072 int lastPriority = Integer.MIN_VALUE; 1073 ComponentName lastComponent = null; 1074 final int size = allHomeCandidates.size(); 1075 for (int i = 0; i < size; i++) { 1076 final ResolveInfo ri = allHomeCandidates.get(i); 1077 if (ri.priority > lastPriority) { 1078 lastComponent = ri.activityInfo.getComponentName(); 1079 lastPriority = ri.priority; 1080 } else if (ri.priority == lastPriority) { 1081 // Two components found with same priority. 1082 lastComponent = null; 1083 } 1084 } 1085 return lastComponent; 1086 } 1087 getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, int userId)1088 public final ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 1089 int userId) { 1090 Intent intent = getHomeIntent(); 1091 List<ResolveInfo> resolveInfos = queryIntentActivitiesInternal(intent, null, 1092 PackageManager.GET_META_DATA, userId); 1093 allHomeCandidates.clear(); 1094 if (resolveInfos == null) { 1095 return null; 1096 } 1097 allHomeCandidates.addAll(resolveInfos); 1098 1099 String packageName = mDefaultAppProvider.getDefaultHome(userId); 1100 if (packageName == null) { 1101 // Role changes are not and cannot be atomic because its implementation lives inside 1102 // a system app, so when the home role changes, there is a window when the previous 1103 // role holder is removed and the new role holder is granted the preferred activity, 1104 // but hasn't become the role holder yet. However, this case may be easily hit 1105 // because the preferred activity change triggers a broadcast and receivers may try 1106 // to get the default home activity there. So we need to fix it for this time 1107 // window, and an easy workaround is to fallback to the current preferred activity. 1108 final int appId = UserHandle.getAppId(Binder.getCallingUid()); 1109 final boolean filtered = appId >= Process.FIRST_APPLICATION_UID; 1110 PackageManagerService.FindPreferredActivityBodyResult result = 1111 findPreferredActivityInternal(intent, null, 0, resolveInfos, true, false, 1112 false, userId, filtered); 1113 ResolveInfo preferredResolveInfo = result.mPreferredResolveInfo; 1114 if (preferredResolveInfo != null && preferredResolveInfo.activityInfo != null) { 1115 packageName = preferredResolveInfo.activityInfo.packageName; 1116 } 1117 } 1118 if (packageName == null) { 1119 return null; 1120 } 1121 1122 int resolveInfosSize = resolveInfos.size(); 1123 for (int i = 0; i < resolveInfosSize; i++) { 1124 ResolveInfo resolveInfo = resolveInfos.get(i); 1125 1126 if (resolveInfo.activityInfo != null && TextUtils.equals( 1127 resolveInfo.activityInfo.packageName, packageName)) { 1128 return new ComponentName(resolveInfo.activityInfo.packageName, 1129 resolveInfo.activityInfo.name); 1130 } 1131 } 1132 return null; 1133 } 1134 getCrossProfileDomainPreferredLpr(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int sourceUserId, int parentUserId)1135 public final CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 1136 String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int sourceUserId, 1137 int parentUserId) { 1138 if (!mUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 1139 sourceUserId)) { 1140 return null; 1141 } 1142 List<ResolveInfo> resultTargetUser = mComponentResolver.queryActivities(this, intent, 1143 resolvedType, flags, parentUserId); 1144 1145 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 1146 return null; 1147 } 1148 CrossProfileDomainInfo result = null; 1149 int size = resultTargetUser.size(); 1150 for (int i = 0; i < size; i++) { 1151 ResolveInfo riTargetUser = resultTargetUser.get(i); 1152 // Intent filter verification is only for filters that specify a host. So don't 1153 //return 1154 // those that handle all web uris. 1155 if (riTargetUser.handleAllWebDataURI) { 1156 continue; 1157 } 1158 String packageName = riTargetUser.activityInfo.packageName; 1159 PackageStateInternal ps = mSettings.getPackage(packageName); 1160 if (ps == null) { 1161 continue; 1162 } 1163 1164 int approvalLevel = mDomainVerificationManager 1165 .approvalLevelForDomain(ps, intent, flags, parentUserId); 1166 1167 if (result == null) { 1168 result = new CrossProfileDomainInfo(createForwardingResolveInfoUnchecked( 1169 new WatchedIntentFilter(), sourceUserId, parentUserId), approvalLevel, 1170 parentUserId); 1171 } else { 1172 result.mHighestApprovalLevel = 1173 Math.max(approvalLevel, result.mHighestApprovalLevel); 1174 } 1175 } 1176 if (result != null && result.mHighestApprovalLevel 1177 <= DomainVerificationManagerInternal.APPROVAL_LEVEL_NONE) { 1178 return null; 1179 } 1180 return result; 1181 } 1182 getHomeIntent()1183 public final Intent getHomeIntent() { 1184 Intent intent = new Intent(Intent.ACTION_MAIN); 1185 intent.addCategory(Intent.CATEGORY_HOME); 1186 intent.addCategory(Intent.CATEGORY_DEFAULT); 1187 return intent; 1188 } 1189 getMatchingCrossProfileIntentFilters( Intent intent, String resolvedType, int userId)1190 public final List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters( 1191 Intent intent, String resolvedType, int userId) { 1192 CrossProfileIntentResolver resolver = mSettings.getCrossProfileIntentResolver(userId); 1193 if (resolver != null) { 1194 return resolver.queryIntent(this, intent, resolvedType, false /*defaultOnly*/, 1195 userId); 1196 } 1197 return null; 1198 } 1199 1200 /** 1201 * Filters out ephemeral activities. 1202 * <p>When resolving for an ephemeral app, only activities that 1) are defined in the 1203 * ephemeral app or 2) marked with {@code visibleToEphemeral} are returned. 1204 * 1205 * @param resolveInfos The pre-filtered list of resolved activities 1206 * @param ephemeralPkgName The ephemeral package name. If {@code null}, no filtering 1207 * is performed. 1208 * @param intent 1209 * @return A filtered list of resolved activities. 1210 */ applyPostResolutionFilter( @onNull List<ResolveInfo> resolveInfos, String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, boolean resolveForStart, int userId, Intent intent)1211 public final List<ResolveInfo> applyPostResolutionFilter( 1212 @NonNull List<ResolveInfo> resolveInfos, 1213 String ephemeralPkgName, boolean allowDynamicSplits, int filterCallingUid, 1214 boolean resolveForStart, int userId, Intent intent) { 1215 final boolean blockInstant = intent.isWebIntent() && areWebInstantAppsDisabled(userId); 1216 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 1217 final ResolveInfo info = resolveInfos.get(i); 1218 // remove locally resolved instant app web results when disabled 1219 if (info.isInstantAppAvailable && blockInstant) { 1220 resolveInfos.remove(i); 1221 continue; 1222 } 1223 // allow activities that are defined in the provided package 1224 if (allowDynamicSplits 1225 && info.activityInfo != null 1226 && info.activityInfo.splitName != null 1227 && !ArrayUtils.contains(info.activityInfo.applicationInfo.splitNames, 1228 info.activityInfo.splitName)) { 1229 if (instantAppInstallerActivity() == null) { 1230 if (DEBUG_INSTALL) { 1231 Slog.v(TAG, "No installer - not adding it to the ResolveInfo list"); 1232 } 1233 resolveInfos.remove(i); 1234 continue; 1235 } 1236 if (blockInstant && isInstantAppInternal( 1237 info.activityInfo.packageName, userId, Process.SYSTEM_UID)) { 1238 resolveInfos.remove(i); 1239 continue; 1240 } 1241 // requested activity is defined in a split that hasn't been installed yet. 1242 // add the installer to the resolve list 1243 if (DEBUG_INSTALL) { 1244 Slog.v(TAG, "Adding installer to the ResolveInfo list"); 1245 } 1246 final ResolveInfo installerInfo = new ResolveInfo( 1247 mInstantAppInstallerInfo); 1248 final ComponentName installFailureActivity = findInstallFailureActivity( 1249 info.activityInfo.packageName, filterCallingUid, userId); 1250 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 1251 installFailureActivity, 1252 info.activityInfo.packageName, 1253 info.activityInfo.applicationInfo.longVersionCode, 1254 info.activityInfo.splitName); 1255 // add a non-generic filter 1256 installerInfo.filter = new IntentFilter(); 1257 1258 // This resolve info may appear in the chooser UI, so let us make it 1259 // look as the one it replaces as far as the user is concerned which 1260 // requires loading the correct label and icon for the resolve info. 1261 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 1262 installerInfo.labelRes = info.resolveLabelResId(); 1263 installerInfo.icon = info.resolveIconResId(); 1264 installerInfo.isInstantAppAvailable = true; 1265 resolveInfos.set(i, installerInfo); 1266 continue; 1267 } 1268 if (ephemeralPkgName == null) { 1269 // caller is a full app 1270 SettingBase callingSetting = 1271 mSettings.getSettingBase(UserHandle.getAppId(filterCallingUid)); 1272 PackageStateInternal resolvedSetting = 1273 getPackageStateInternal(info.activityInfo.packageName, 0); 1274 if (resolveForStart 1275 || !mAppsFilter.shouldFilterApplication(this, 1276 filterCallingUid, callingSetting, resolvedSetting, userId)) { 1277 continue; 1278 } 1279 } else if (ephemeralPkgName.equals(info.activityInfo.packageName)) { 1280 // caller is same app; don't need to apply any other filtering 1281 continue; 1282 } else if (resolveForStart 1283 && (intent.isWebIntent() 1284 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) != 0) 1285 && intent.getPackage() == null 1286 && intent.getComponent() == null) { 1287 // ephemeral apps can launch other ephemeral apps indirectly 1288 continue; 1289 } else if (((info.activityInfo.flags & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) 1290 != 0) 1291 && !info.activityInfo.applicationInfo.isInstantApp()) { 1292 // allow activities that have been explicitly exposed to ephemeral apps 1293 continue; 1294 } 1295 resolveInfos.remove(i); 1296 } 1297 return resolveInfos; 1298 } 1299 applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, String instantAppPkgName, @UserIdInt int userId, int filterCallingUid)1300 private List<ResolveInfo> applyPostServiceResolutionFilter(List<ResolveInfo> resolveInfos, 1301 String instantAppPkgName, @UserIdInt int userId, int filterCallingUid) { 1302 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 1303 final ResolveInfo info = resolveInfos.get(i); 1304 if (instantAppPkgName == null) { 1305 SettingBase callingSetting = 1306 mSettings.getSettingBase(UserHandle.getAppId(filterCallingUid)); 1307 PackageStateInternal resolvedSetting = 1308 getPackageStateInternal(info.serviceInfo.packageName, 0); 1309 if (!mAppsFilter.shouldFilterApplication(this, 1310 filterCallingUid, callingSetting, resolvedSetting, userId)) { 1311 continue; 1312 } 1313 } 1314 final boolean isEphemeralApp = info.serviceInfo.applicationInfo.isInstantApp(); 1315 // allow services that are defined in the provided package 1316 if (isEphemeralApp && instantAppPkgName.equals(info.serviceInfo.packageName)) { 1317 if (info.serviceInfo.splitName != null 1318 && !ArrayUtils.contains(info.serviceInfo.applicationInfo.splitNames, 1319 info.serviceInfo.splitName)) { 1320 if (instantAppInstallerActivity() == null) { 1321 if (DEBUG_INSTANT) { 1322 Slog.v(TAG, "No installer - not adding it to the ResolveInfo" 1323 + "list"); 1324 } 1325 resolveInfos.remove(i); 1326 continue; 1327 } 1328 // requested service is defined in a split that hasn't been installed yet. 1329 // add the installer to the resolve list 1330 if (DEBUG_INSTANT) { 1331 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 1332 } 1333 final ResolveInfo installerInfo = new ResolveInfo( 1334 mInstantAppInstallerInfo); 1335 installerInfo.auxiliaryInfo = new AuxiliaryResolveInfo( 1336 null /* installFailureActivity */, 1337 info.serviceInfo.packageName, 1338 info.serviceInfo.applicationInfo.longVersionCode, 1339 info.serviceInfo.splitName); 1340 // add a non-generic filter 1341 installerInfo.filter = new IntentFilter(); 1342 // load resources from the correct package 1343 installerInfo.resolvePackageName = info.getComponentInfo().packageName; 1344 resolveInfos.set(i, installerInfo); 1345 } 1346 continue; 1347 } 1348 // allow services that have been explicitly exposed to ephemeral apps 1349 if (!isEphemeralApp 1350 && ((info.serviceInfo.flags & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) 1351 != 0)) { 1352 continue; 1353 } 1354 resolveInfos.remove(i); 1355 } 1356 return resolveInfos; 1357 } 1358 1359 /** 1360 * Filter out activities with systemUserOnly flag set, when current user is not System. 1361 * 1362 * @return filtered list 1363 */ filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId)1364 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, 1365 int userId) { 1366 if (userId == UserHandle.USER_SYSTEM) { 1367 return resolveInfos; 1368 } 1369 1370 for (int i = CollectionUtils.size(resolveInfos) - 1; i >= 0; i--) { 1371 ResolveInfo info = resolveInfos.get(i); 1372 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 1373 resolveInfos.remove(i); 1374 } 1375 } 1376 return resolveInfos; 1377 } 1378 maybeAddInstantAppInstaller(List<ResolveInfo> result, Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, int userId, boolean resolveForStart, boolean isRequesterInstantApp)1379 private List<ResolveInfo> maybeAddInstantAppInstaller(List<ResolveInfo> result, 1380 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 1381 int userId, boolean resolveForStart, boolean isRequesterInstantApp) { 1382 // first, check to see if we've got an instant app already installed 1383 final boolean alreadyResolvedLocally = (flags & PackageManager.MATCH_INSTANT) != 0; 1384 ResolveInfo localInstantApp = null; 1385 boolean blockResolution = false; 1386 if (!alreadyResolvedLocally) { 1387 final List<ResolveInfo> instantApps = mComponentResolver.queryActivities(this, 1388 intent, 1389 resolvedType, 1390 flags 1391 | PackageManager.GET_RESOLVED_FILTER 1392 | PackageManager.MATCH_INSTANT 1393 | PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY, 1394 userId); 1395 for (int i = instantApps.size() - 1; i >= 0; --i) { 1396 final ResolveInfo info = instantApps.get(i); 1397 final String packageName = info.activityInfo.packageName; 1398 final PackageStateInternal ps = mSettings.getPackage(packageName); 1399 if (ps.getUserStateOrDefault(userId).isInstantApp()) { 1400 if (PackageManagerServiceUtils.hasAnyDomainApproval( 1401 mDomainVerificationManager, ps, intent, flags, userId)) { 1402 if (DEBUG_INSTANT) { 1403 Slog.v(TAG, "Instant app approved for intent; pkg: " 1404 + packageName); 1405 } 1406 localInstantApp = info; 1407 } else { 1408 if (DEBUG_INSTANT) { 1409 Slog.v(TAG, "Instant app not approved for intent; pkg: " 1410 + packageName); 1411 } 1412 blockResolution = true; 1413 } 1414 break; 1415 } 1416 } 1417 } 1418 // no app installed, let's see if one's available 1419 AuxiliaryResolveInfo auxiliaryResponse = null; 1420 if (!blockResolution) { 1421 if (localInstantApp == null) { 1422 // we don't have an instant app locally, resolve externally 1423 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 1424 String token = UUID.randomUUID().toString(); 1425 InstantAppResolveInfo.InstantAppDigest digest = 1426 InstantAppResolver.parseDigest(intent); 1427 final InstantAppRequest requestObject = 1428 new InstantAppRequest(null /*responseObj*/, 1429 intent /*origIntent*/, resolvedType, null /*callingPackage*/, 1430 null /*callingFeatureId*/, isRequesterInstantApp, userId, 1431 null /*verificationBundle*/, resolveForStart, 1432 digest.getDigestPrefixSecure(), token); 1433 auxiliaryResponse = InstantAppResolver.doInstantAppResolutionPhaseOne(this, 1434 mUserManager, mInstantAppResolverConnection, requestObject); 1435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1436 } else { 1437 // we have an instant application locally, but, we can't admit that since 1438 // callers shouldn't be able to determine prior browsing. create a placeholder 1439 // auxiliary response so the downstream code behaves as if there's an 1440 // instant application available externally. when it comes time to start 1441 // the instant application, we'll do the right thing. 1442 final ApplicationInfo ai = localInstantApp.activityInfo.applicationInfo; 1443 auxiliaryResponse = new AuxiliaryResolveInfo(null /* failureActivity */, 1444 ai.packageName, ai.longVersionCode, 1445 null /* splitName */); 1446 } 1447 } 1448 if (intent.isWebIntent() && auxiliaryResponse == null) { 1449 return result; 1450 } 1451 final PackageStateInternal ps = 1452 mSettings.getPackage(instantAppInstallerActivity().packageName); 1453 if (ps == null || !PackageUserStateUtils.isEnabled(ps.getUserStateOrDefault(userId), 1454 instantAppInstallerActivity(), 0)) { 1455 return result; 1456 } 1457 final ResolveInfo ephemeralInstaller = new ResolveInfo(mInstantAppInstallerInfo); 1458 ephemeralInstaller.activityInfo = PackageInfoUtils.generateDelegateActivityInfo( 1459 instantAppInstallerActivity(), 0 /*flags*/, 1460 ps.getUserStateOrDefault(userId), userId); 1461 ephemeralInstaller.match = IntentFilter.MATCH_CATEGORY_SCHEME_SPECIFIC_PART 1462 | IntentFilter.MATCH_ADJUSTMENT_NORMAL; 1463 // add a non-generic filter 1464 ephemeralInstaller.filter = new IntentFilter(); 1465 if (intent.getAction() != null) { 1466 ephemeralInstaller.filter.addAction(intent.getAction()); 1467 } 1468 if (intent.getData() != null && intent.getData().getPath() != null) { 1469 ephemeralInstaller.filter.addDataPath( 1470 intent.getData().getPath(), PatternMatcher.PATTERN_LITERAL); 1471 } 1472 ephemeralInstaller.isInstantAppAvailable = true; 1473 // make sure this resolver is the default 1474 ephemeralInstaller.isDefault = true; 1475 ephemeralInstaller.auxiliaryInfo = auxiliaryResponse; 1476 if (DEBUG_INSTANT) { 1477 Slog.v(TAG, "Adding ephemeral installer to the ResolveInfo list"); 1478 } 1479 1480 result.add(ephemeralInstaller); 1481 return result; 1482 } 1483 generatePackageInfo(PackageStateInternal ps, @PackageManager.PackageInfoFlagsBits long flags, int userId)1484 public final PackageInfo generatePackageInfo(PackageStateInternal ps, 1485 @PackageManager.PackageInfoFlagsBits long flags, int userId) { 1486 if (!mUserManager.exists(userId)) return null; 1487 if (ps == null) { 1488 return null; 1489 } 1490 final int callingUid = Binder.getCallingUid(); 1491 // Filter out ephemeral app metadata: 1492 // * The system/shell/root can see metadata for any app 1493 // * An installed app can see metadata for 1) other installed apps 1494 // and 2) ephemeral apps that have explicitly interacted with it 1495 // * Ephemeral apps can only see their own data and exposed installed apps 1496 // * Holding a signature permission allows seeing instant apps 1497 if (shouldFilterApplication(ps, callingUid, userId)) { 1498 return null; 1499 } 1500 1501 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0 1502 && ps.isSystem()) { 1503 flags |= MATCH_ANY_USER; 1504 } 1505 1506 final PackageUserStateInternal state = ps.getUserStateOrDefault(userId); 1507 AndroidPackage p = ps.getPkg(); 1508 if (p != null) { 1509 // Compute GIDs only if requested 1510 final int[] gids = (flags & PackageManager.GET_GIDS) == 0 ? EMPTY_INT_ARRAY 1511 : mPermissionManager.getGidsForUid(UserHandle.getUid(userId, ps.getAppId())); 1512 // Compute installed permissions only if requested 1513 final Set<String> installedPermissions = ((flags & PackageManager.GET_PERMISSIONS) == 0 1514 || ArrayUtils.isEmpty(p.getPermissions())) ? Collections.emptySet() 1515 : mPermissionManager.getInstalledPermissions(ps.getPackageName()); 1516 // Compute granted permissions only if package has requested permissions 1517 final Set<String> grantedPermissions = ((flags & PackageManager.GET_PERMISSIONS) == 0 1518 || ArrayUtils.isEmpty(p.getRequestedPermissions())) ? Collections.emptySet() 1519 : mPermissionManager.getGrantedPermissions(ps.getPackageName(), userId); 1520 1521 PackageInfo packageInfo = PackageInfoUtils.generate(p, gids, flags, 1522 state.getFirstInstallTimeMillis(), ps.getLastUpdateTime(), installedPermissions, 1523 grantedPermissions, state, userId, ps); 1524 1525 if (packageInfo == null) { 1526 return null; 1527 } 1528 1529 packageInfo.packageName = packageInfo.applicationInfo.packageName = 1530 resolveExternalPackageName(p); 1531 1532 if (Flags.provideInfoOfApkInApex()) { 1533 final String apexModuleName = ps.getApexModuleName(); 1534 if (apexModuleName != null) { 1535 packageInfo.setApexPackageName( 1536 mApexManager.getActivePackageNameForApexModuleName(apexModuleName)); 1537 } 1538 } 1539 return packageInfo; 1540 } else if ((flags & (MATCH_UNINSTALLED_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0 1541 && PackageUserStateUtils.isAvailable(state, flags)) { 1542 PackageInfo pi = new PackageInfo(); 1543 pi.packageName = ps.getPackageName(); 1544 pi.setLongVersionCode(ps.getVersionCode()); 1545 SharedUserApi sharedUser = mSettings.getSharedUserFromPackageName(pi.packageName); 1546 pi.sharedUserId = (sharedUser != null) ? sharedUser.getName() : null; 1547 pi.firstInstallTime = state.getFirstInstallTimeMillis(); 1548 pi.lastUpdateTime = ps.getLastUpdateTime(); 1549 1550 ApplicationInfo ai = new ApplicationInfo(); 1551 ai.packageName = ps.getPackageName(); 1552 ai.uid = UserHandle.getUid(userId, ps.getAppId()); 1553 ai.primaryCpuAbi = ps.getPrimaryCpuAbiLegacy(); 1554 ai.secondaryCpuAbi = ps.getSecondaryCpuAbiLegacy(); 1555 ai.volumeUuid = ps.getVolumeUuid(); 1556 ai.storageUuid = StorageManager.convert(ai.volumeUuid); 1557 ai.setVersionCode(ps.getVersionCode()); 1558 ai.targetSdkVersion = ps.getTargetSdkVersion(); 1559 ai.flags = ps.getFlags(); 1560 ai.privateFlags = ps.getPrivateFlags(); 1561 pi.applicationInfo = PackageInfoUtils.generateDelegateApplicationInfo( 1562 ai, flags, state, userId); 1563 pi.signingInfo = ps.getSigningInfo(); 1564 pi.signatures = getDeprecatedSignatures(pi.signingInfo.getSigningDetails(), flags); 1565 if (state.getArchiveState() != null) { 1566 pi.setArchiveTimeMillis(state.getArchiveState().getArchiveTimeMillis()); 1567 } 1568 1569 if (DEBUG_PACKAGE_INFO) { 1570 Log.v(TAG, "ps.pkg is n/a for [" 1571 + ps.getPackageName() + "]. Provides a minimum info."); 1572 } 1573 return pi; 1574 } else { 1575 return null; 1576 } 1577 } 1578 getPackageInfo(String packageName, @PackageManager.PackageInfoFlagsBits long flags, int userId)1579 public final PackageInfo getPackageInfo(String packageName, 1580 @PackageManager.PackageInfoFlagsBits long flags, int userId) { 1581 return getPackageInfoInternal(packageName, PackageManager.VERSION_CODE_HIGHEST, 1582 flags, Binder.getCallingUid(), userId); 1583 } 1584 1585 /** 1586 * Important: The provided filterCallingUid is used exclusively to filter out packages 1587 * that can be seen based on user state. It's typically the original caller uid prior 1588 * to clearing. Because it can only be provided by trusted code, its value can be 1589 * trusted and will be used as-is; unlike userId which will be validated by this method. 1590 */ getPackageInfoInternal(String packageName, long versionCode, long flags, int filterCallingUid, int userId)1591 public final PackageInfo getPackageInfoInternal(String packageName, long versionCode, 1592 long flags, int filterCallingUid, int userId) { 1593 if (!mUserManager.exists(userId)) return null; 1594 flags = updateFlagsForPackage(flags, userId); 1595 enforceCrossUserPermission(Binder.getCallingUid(), userId, 1596 false /* requireFullPermission */, false /* checkShell */, "get package info"); 1597 1598 return getPackageInfoInternalBody(packageName, versionCode, flags, filterCallingUid, 1599 userId); 1600 } 1601 getPackageInfoInternalBody(String packageName, long versionCode, long flags, int filterCallingUid, int userId)1602 protected PackageInfo getPackageInfoInternalBody(String packageName, long versionCode, 1603 long flags, int filterCallingUid, int userId) { 1604 // reader 1605 // Normalize package name to handle renamed packages and static libs 1606 packageName = resolveInternalPackageName(packageName, versionCode); 1607 1608 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 1609 final boolean matchApex = (flags & MATCH_APEX) != 0; 1610 if (matchFactoryOnly) { 1611 // Instant app filtering for APEX modules is ignored 1612 final PackageStateInternal ps = mSettings.getDisabledSystemPkg(packageName); 1613 if (ps != null) { 1614 if (!matchApex && ps.getPkg() != null && ps.getPkg().isApex()) { 1615 return null; 1616 } 1617 if (filterSharedLibPackage(ps, filterCallingUid, userId, flags)) { 1618 return null; 1619 } 1620 if (shouldFilterApplication(ps, filterCallingUid, userId)) { 1621 return null; 1622 } 1623 return generatePackageInfo(ps, flags, userId); 1624 } 1625 } 1626 1627 AndroidPackage p = mPackages.get(packageName); 1628 var packageState = mSettings.getPackage(packageName); 1629 if (matchFactoryOnly && p != null && !packageState.isSystem()) { 1630 return null; 1631 } 1632 if (DEBUG_PACKAGE_INFO) { 1633 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 1634 } 1635 if (p != null) { 1636 final PackageStateInternal ps = getPackageStateInternal(p.getPackageName()); 1637 if (!matchApex && p.isApex()) { 1638 return null; 1639 } 1640 if (filterSharedLibPackage(ps, filterCallingUid, userId, flags)) { 1641 return null; 1642 } 1643 if (ps != null && shouldFilterApplication(ps, filterCallingUid, userId)) { 1644 return null; 1645 } 1646 1647 return generatePackageInfo(ps, flags, userId); 1648 } 1649 if (!matchFactoryOnly && (flags & (MATCH_KNOWN_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0) { 1650 final PackageStateInternal ps = mSettings.getPackage(packageName); 1651 if (ps == null) return null; 1652 if (filterSharedLibPackage(ps, filterCallingUid, userId, flags)) { 1653 return null; 1654 } 1655 if (shouldFilterApplication(ps, filterCallingUid, userId)) { 1656 return null; 1657 } 1658 return generatePackageInfo(ps, flags, userId); 1659 } 1660 return null; 1661 } 1662 1663 @Override getAllAvailablePackageNames()1664 public String[] getAllAvailablePackageNames() { 1665 return mPackages.keySet().toArray(new String[0]); 1666 } 1667 1668 @Nullable getPackageStateInternal(String packageName)1669 public final PackageStateInternal getPackageStateInternal(String packageName) { 1670 return getPackageStateInternal(packageName, Binder.getCallingUid()); 1671 } 1672 getPackageStateInternal(String packageName, int callingUid)1673 public PackageStateInternal getPackageStateInternal(String packageName, 1674 int callingUid) { 1675 packageName = resolveInternalPackageNameInternalLocked( 1676 packageName, PackageManager.VERSION_CODE_HIGHEST, callingUid); 1677 return mSettings.getPackage(packageName); 1678 } 1679 1680 @Override getPackageStateFiltered(@onNull String packageName, int callingUid, @UserIdInt int userId)1681 public PackageStateInternal getPackageStateFiltered(@NonNull String packageName, 1682 int callingUid, @UserIdInt int userId) { 1683 packageName = resolveInternalPackageNameInternalLocked( 1684 packageName, PackageManager.VERSION_CODE_HIGHEST, callingUid); 1685 var packageState = mSettings.getPackage(packageName); 1686 if (shouldFilterApplication(packageState, callingUid, userId)) { 1687 return null; 1688 } else { 1689 return packageState; 1690 } 1691 } 1692 getInstalledPackages(long flags, int userId)1693 public final ParceledListSlice<PackageInfo> getInstalledPackages(long flags, int userId) { 1694 final int callingUid = Binder.getCallingUid(); 1695 if (getInstantAppPackageName(callingUid) != null) { 1696 return ParceledListSlice.emptyList(); 1697 } 1698 if (!mUserManager.exists(userId)) return ParceledListSlice.emptyList(); 1699 flags = updateFlagsForPackage(flags, userId); 1700 1701 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 1702 false /* checkShell */, "get installed packages"); 1703 1704 return getInstalledPackagesBody(flags, userId, callingUid); 1705 } 1706 getInstalledPackagesBody(long flags, int userId, int callingUid)1707 protected ParceledListSlice<PackageInfo> getInstalledPackagesBody(long flags, int userId, 1708 int callingUid) { 1709 // writer 1710 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 1711 final boolean listApex = (flags & MATCH_APEX) != 0; 1712 final boolean listFactory = (flags & MATCH_FACTORY_ONLY) != 0; 1713 // Only list archived apps, not fully uninstalled ones. Other entries are unaffected. 1714 final boolean listArchivedOnly = !listUninstalled && (flags & MATCH_ARCHIVED_PACKAGES) != 0; 1715 1716 ArrayList<PackageInfo> list; 1717 if (listUninstalled || listArchivedOnly) { 1718 list = new ArrayList<>(mSettings.getPackages().size()); 1719 for (PackageStateInternal ps : mSettings.getPackages().values()) { 1720 if (listFactory) { 1721 if (!ps.isSystem()) { 1722 continue; 1723 } 1724 PackageStateInternal psDisabled = 1725 mSettings.getDisabledSystemPkg(ps.getPackageName()); 1726 if (psDisabled != null) { 1727 ps = psDisabled; 1728 } 1729 } 1730 if (!listApex && ps.getPkg() != null && ps.getPkg().isApex()) { 1731 continue; 1732 } 1733 PackageUserStateInternal userState = ps.getUserStateOrDefault(userId); 1734 if (listArchivedOnly && !userState.isInstalled() 1735 && userState.getArchiveState() == null) { 1736 continue; 1737 } 1738 if (filterSharedLibPackage(ps, callingUid, userId, flags)) { 1739 continue; 1740 } 1741 if (shouldFilterApplication(ps, callingUid, userId)) { 1742 continue; 1743 } 1744 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 1745 if (pi != null) { 1746 list.add(pi); 1747 } 1748 } 1749 } else { 1750 list = new ArrayList<>(mPackages.size()); 1751 for (AndroidPackage p : mPackages.values()) { 1752 PackageStateInternal ps = getPackageStateInternal(p.getPackageName()); 1753 if (listFactory) { 1754 if (!ps.isSystem()) { 1755 continue; 1756 } 1757 PackageStateInternal psDisabled = 1758 ps == null ? null : mSettings.getDisabledSystemPkg(ps.getPackageName()); 1759 if (psDisabled != null) { 1760 ps = psDisabled; 1761 } 1762 } 1763 if (!listApex && p.isApex()) { 1764 continue; 1765 } 1766 if (filterSharedLibPackage(ps, callingUid, userId, flags)) { 1767 continue; 1768 } 1769 if (shouldFilterApplication(ps, callingUid, userId)) { 1770 continue; 1771 } 1772 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 1773 if (pi != null) { 1774 list.add(pi); 1775 } 1776 } 1777 } 1778 return new ParceledListSlice<>(list); 1779 } 1780 createForwardingResolveInfoUnchecked(WatchedIntentFilter filter, int sourceUserId, int targetUserId)1781 public final ResolveInfo createForwardingResolveInfoUnchecked(WatchedIntentFilter filter, 1782 int sourceUserId, int targetUserId) { 1783 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 1784 final long ident = Binder.clearCallingIdentity(); 1785 boolean targetIsProfile; 1786 try { 1787 targetIsProfile = mUserManager.getUserInfo(targetUserId).isManagedProfile(); 1788 } finally { 1789 Binder.restoreCallingIdentity(ident); 1790 } 1791 String className; 1792 if (targetIsProfile) { 1793 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 1794 } else { 1795 className = FORWARD_INTENT_TO_PARENT; 1796 } 1797 ComponentName forwardingActivityComponentName = new ComponentName( 1798 androidApplication().packageName, className); 1799 ActivityInfo forwardingActivityInfo = 1800 getActivityInfoCrossProfile(forwardingActivityComponentName, 0, 1801 sourceUserId); 1802 if (!targetIsProfile) { 1803 forwardingActivityInfo.showUserIcon = targetUserId; 1804 forwardingResolveInfo.noResourceId = true; 1805 } 1806 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 1807 forwardingResolveInfo.priority = 0; 1808 forwardingResolveInfo.preferredOrder = 0; 1809 forwardingResolveInfo.match = 0; 1810 forwardingResolveInfo.isDefault = true; 1811 forwardingResolveInfo.filter = new IntentFilter(filter.getIntentFilter()); 1812 forwardingResolveInfo.targetUserId = targetUserId; 1813 forwardingResolveInfo.userHandle = UserHandle.of(sourceUserId); 1814 return forwardingResolveInfo; 1815 } 1816 getServiceInfo(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int userId)1817 public final ServiceInfo getServiceInfo(ComponentName component, 1818 @PackageManager.ResolveInfoFlagsBits long flags, int userId) { 1819 if (!mUserManager.exists(userId)) return null; 1820 final int callingUid = Binder.getCallingUid(); 1821 flags = updateFlagsForComponent(flags, userId); 1822 enforceCrossUserOrProfilePermission(callingUid, userId, 1823 false /* requireFullPermission */, 1824 false /* checkShell */, "get service info"); 1825 return getServiceInfoBody(component, flags, userId, callingUid); 1826 } 1827 getServiceInfoBody(ComponentName component, @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid)1828 protected ServiceInfo getServiceInfoBody(ComponentName component, 1829 @PackageManager.ResolveInfoFlagsBits long flags, int userId, int callingUid) { 1830 ParsedService s = mComponentResolver.getService(component); 1831 if (DEBUG_PACKAGE_INFO) { 1832 Log.v( 1833 TAG, "getServiceInfo " + component + ": " + s); 1834 } 1835 if (s == null) { 1836 return null; 1837 } 1838 1839 AndroidPackage pkg = mPackages.get(s.getPackageName()); 1840 if (mSettings.isEnabledAndMatch(pkg, s, flags, userId)) { 1841 PackageStateInternal ps = mSettings.getPackage(component.getPackageName()); 1842 if (ps == null) return null; 1843 if (shouldFilterApplication( 1844 ps, callingUid, component, TYPE_SERVICE, userId)) { 1845 return null; 1846 } 1847 return PackageInfoUtils.generateServiceInfo(pkg, 1848 s, flags, ps.getUserStateOrDefault(userId), userId, ps); 1849 } 1850 return null; 1851 } 1852 1853 @Nullable getSharedLibraryInfo(String name, long version)1854 public final SharedLibraryInfo getSharedLibraryInfo(String name, long version) { 1855 return mSharedLibraries.getSharedLibraryInfo(name, version); 1856 } 1857 1858 /** 1859 * Returns the package name of the calling Uid if it's an instant app. If it isn't 1860 * instant, returns {@code null}. 1861 */ getInstantAppPackageName(int callingUid)1862 public String getInstantAppPackageName(int callingUid) { 1863 // If the caller is an isolated app use the owner's uid for the lookup. 1864 if (Process.isIsolated(callingUid)) { 1865 callingUid = getIsolatedOwner(callingUid); 1866 } 1867 final int appId = UserHandle.getAppId(callingUid); 1868 final Object obj = mSettings.getSettingBase(appId); 1869 if (obj instanceof PackageStateInternal) { 1870 final PackageStateInternal ps = (PackageStateInternal) obj; 1871 final boolean isInstantApp = ps.getUserStateOrDefault(UserHandle.getUserId(callingUid)) 1872 .isInstantApp(); 1873 return isInstantApp ? ps.getPkg().getPackageName() : null; 1874 } 1875 return null; 1876 } 1877 1878 /** 1879 * Finds the owner for the provided isolated UID. Throws IllegalStateException if no such 1880 * isolated UID is found. 1881 */ getIsolatedOwner(int isolatedUid)1882 private int getIsolatedOwner(int isolatedUid) { 1883 final int ownerUid = mIsolatedOwners.get(isolatedUid, -1); 1884 if (ownerUid == -1) { 1885 throw new IllegalStateException( 1886 "No owner UID found for isolated UID " + isolatedUid); 1887 } 1888 return ownerUid; 1889 } 1890 resolveExternalPackageName(AndroidPackage pkg)1891 public final String resolveExternalPackageName(AndroidPackage pkg) { 1892 if (pkg.getStaticSharedLibraryName() != null) { 1893 return pkg.getManifestPackageName(); 1894 } 1895 return pkg.getPackageName(); 1896 } 1897 resolveInternalPackageNameInternalLocked( String packageName, long versionCode, int callingUid)1898 private String resolveInternalPackageNameInternalLocked( 1899 String packageName, long versionCode, int callingUid) { 1900 // Handle renamed packages 1901 String normalizedPackageName = mSettings.getRenamedPackageLPr(packageName); 1902 packageName = normalizedPackageName != null ? normalizedPackageName : packageName; 1903 1904 // Is this a static library? 1905 WatchedLongSparseArray<SharedLibraryInfo> versionedLib = 1906 mSharedLibraries.getStaticLibraryInfos(packageName); 1907 if (versionedLib == null || versionedLib.size() <= 0) { 1908 return packageName; 1909 } 1910 1911 // Figure out which lib versions the caller can see 1912 LongSparseLongArray versionsCallerCanSee = null; 1913 final int callingAppId = UserHandle.getAppId(callingUid); 1914 if (!PackageManagerServiceUtils.isSystemOrRootOrShell(callingAppId)) { 1915 versionsCallerCanSee = new LongSparseLongArray(); 1916 String libName = versionedLib.valueAt(0).getName(); 1917 String[] uidPackages = getPackagesForUidInternal(callingUid, callingUid); 1918 if (uidPackages != null) { 1919 for (String uidPackage : uidPackages) { 1920 PackageStateInternal ps = mSettings.getPackage(uidPackage); 1921 final int libIdx = ArrayUtils.indexOf(ps.getUsesStaticLibraries(), libName); 1922 if (libIdx >= 0) { 1923 final long libVersion = ps.getUsesStaticLibrariesVersions()[libIdx]; 1924 versionsCallerCanSee.append(libVersion, libVersion); 1925 } 1926 } 1927 } 1928 } 1929 1930 // Caller can see nothing - done 1931 if (versionsCallerCanSee != null && versionsCallerCanSee.size() <= 0) { 1932 return packageName; 1933 } 1934 1935 // Find the version the caller can see and the app version code 1936 SharedLibraryInfo highestVersion = null; 1937 final int versionCount = versionedLib.size(); 1938 for (int i = 0; i < versionCount; i++) { 1939 SharedLibraryInfo libraryInfo = versionedLib.valueAt(i); 1940 if (versionsCallerCanSee != null && versionsCallerCanSee.indexOfKey( 1941 libraryInfo.getLongVersion()) < 0) { 1942 continue; 1943 } 1944 final long libVersionCode = libraryInfo.getDeclaringPackage().getLongVersionCode(); 1945 if (versionCode != PackageManager.VERSION_CODE_HIGHEST) { 1946 if (libVersionCode == versionCode) { 1947 return libraryInfo.getPackageName(); 1948 } 1949 } else if (highestVersion == null) { 1950 highestVersion = libraryInfo; 1951 } else if (libVersionCode > highestVersion 1952 .getDeclaringPackage().getLongVersionCode()) { 1953 highestVersion = libraryInfo; 1954 } 1955 } 1956 1957 if (highestVersion != null) { 1958 return highestVersion.getPackageName(); 1959 } 1960 1961 return packageName; 1962 } 1963 resolveInternalPackageName(String packageName, long versionCode)1964 public final String resolveInternalPackageName(String packageName, long versionCode) { 1965 final int callingUid = Binder.getCallingUid(); 1966 return resolveInternalPackageNameInternalLocked(packageName, versionCode, 1967 callingUid); 1968 } 1969 1970 /** 1971 * <em>IMPORTANT:</em> Not all packages returned by this method may be known 1972 * to the system. There are two conditions in which this may occur: 1973 * <ol> 1974 * <li>The package is on adoptable storage and the device has been removed</li> 1975 * <li>The package is being removed and the internal structures are partially updated</li> 1976 * </ol> 1977 * The second is an artifact of the current data structures and should be fixed. See 1978 * b/111075456 for one such instance. 1979 * This binder API is cached. If the algorithm in this method changes, 1980 * or if the underlying objecs (as returned by getSettingLPr()) change 1981 * then the logic that invalidates the cache must be revisited. See 1982 * calls to invalidateGetPackagesForUidCache() to locate the points at 1983 * which the cache is invalidated. 1984 */ getPackagesForUid(int uid)1985 public final String[] getPackagesForUid(int uid) { 1986 return getPackagesForUidInternal(uid, Binder.getCallingUid()); 1987 } 1988 getPackagesForUidInternal(int uid, int callingUid)1989 private String[] getPackagesForUidInternal(int uid, int callingUid) { 1990 final boolean isCallerInstantApp = getInstantAppPackageName(callingUid) != null; 1991 final int userId = UserHandle.getUserId(uid); 1992 if (Process.isSdkSandboxUid(uid)) { 1993 uid = getBaseSdkSandboxUid(); 1994 } 1995 final int appId = UserHandle.getAppId(uid); 1996 return getPackagesForUidInternalBody(callingUid, userId, appId, isCallerInstantApp); 1997 } 1998 getPackagesForUidInternalBody(int callingUid, int userId, int appId, boolean isCallerInstantApp)1999 protected String[] getPackagesForUidInternalBody(int callingUid, int userId, int appId, 2000 boolean isCallerInstantApp) { 2001 // reader 2002 final Object obj = mSettings.getSettingBase(appId); 2003 if (obj instanceof SharedUserSetting) { 2004 if (isCallerInstantApp) { 2005 return null; 2006 } 2007 final SharedUserSetting sus = (SharedUserSetting) obj; 2008 final ArraySet<PackageStateInternal> packageStates = 2009 (ArraySet<PackageStateInternal>) sus.getPackageStates(); 2010 final int n = packageStates.size(); 2011 String[] res = new String[n]; 2012 int i = 0; 2013 for (int index = 0; index < n; index++) { 2014 final PackageStateInternal ps = packageStates.valueAt(index); 2015 if (ps.getUserStateOrDefault(userId).isInstalled() 2016 && !shouldFilterApplication(ps, callingUid, userId)) { 2017 res[i++] = ps.getPackageName(); 2018 } 2019 } 2020 return ArrayUtils.trimToSize(res, i); 2021 } else if (obj instanceof PackageStateInternal) { 2022 final PackageStateInternal ps = (PackageStateInternal) obj; 2023 if (ps.getUserStateOrDefault(userId).isInstalled() 2024 && !shouldFilterApplication(ps, callingUid, userId)) { 2025 return new String[]{ps.getPackageName()}; 2026 } 2027 } 2028 return null; 2029 } 2030 getProfileParent(int userId)2031 public final UserInfo getProfileParent(int userId) { 2032 final long identity = Binder.clearCallingIdentity(); 2033 try { 2034 return mUserManager.getProfileParent(userId); 2035 } finally { 2036 Binder.restoreCallingIdentity(identity); 2037 } 2038 } 2039 2040 /** 2041 * Returns whether or not instant apps have been disabled remotely. 2042 */ areWebInstantAppsDisabled(int userId)2043 private boolean areWebInstantAppsDisabled(int userId) { 2044 return mWebInstantAppsDisabled.get(userId); 2045 } 2046 2047 /** 2048 * Returns whether or not a full application can see an instant application. 2049 * <p> 2050 * Currently, there are four cases in which this can occur: 2051 * <ol> 2052 * <li>The calling application is a "special" process. Special processes 2053 * are those with a UID < {@link Process#FIRST_APPLICATION_UID}.</li> 2054 * <li>The calling application has the permission 2055 * {@link android.Manifest.permission#ACCESS_INSTANT_APPS}.</li> 2056 * <li>The calling application is the default launcher on the 2057 * system partition.</li> 2058 * <li>The calling application is the default app prediction service.</li> 2059 * </ol> 2060 */ canViewInstantApps(int callingUid, int userId)2061 public final boolean canViewInstantApps(int callingUid, int userId) { 2062 if (callingUid < Process.FIRST_APPLICATION_UID) { 2063 return true; 2064 } 2065 if (mContext.checkCallingOrSelfPermission( 2066 android.Manifest.permission.ACCESS_INSTANT_APPS) == PERMISSION_GRANTED) { 2067 return true; 2068 } 2069 if (mContext.checkCallingOrSelfPermission( 2070 android.Manifest.permission.VIEW_INSTANT_APPS) == PERMISSION_GRANTED) { 2071 final ComponentName homeComponent = getDefaultHomeActivity(userId); 2072 if (homeComponent != null 2073 && isCallerSameApp(homeComponent.getPackageName(), callingUid)) { 2074 return true; 2075 } 2076 // TODO(b/122900055) Change/Remove this and replace with new permission role. 2077 return mAppPredictionServicePackage != null 2078 && isCallerSameApp(mAppPredictionServicePackage, callingUid); 2079 } 2080 return false; 2081 } 2082 filterStaticSharedLibPackage(@ullable PackageStateInternal ps, int uid, int userId, @PackageManager.ComponentInfoFlagsBits long flags)2083 private boolean filterStaticSharedLibPackage(@Nullable PackageStateInternal ps, int uid, 2084 int userId, @PackageManager.ComponentInfoFlagsBits long flags) { 2085 // Callers can access only the static shared libs they depend on, otherwise they need to 2086 // explicitly ask for the static shared libraries given the caller is allowed to access 2087 // all static libs. 2088 if ((flags & PackageManager.MATCH_STATIC_SHARED_AND_SDK_LIBRARIES) != 0) { 2089 // System/shell/root get to see all static libs 2090 final int appId = UserHandle.getAppId(uid); 2091 if (PackageManagerServiceUtils.isSystemOrRootOrShell(appId)) { 2092 return false; 2093 } 2094 // Installer gets to see all static libs. 2095 if (PackageManager.PERMISSION_GRANTED 2096 == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) { 2097 return false; 2098 } 2099 } 2100 2101 // No package means no static lib as it is always on internal storage 2102 if (ps == null || ps.getPkg() == null || !ps.getPkg().isStaticSharedLibrary()) { 2103 return false; 2104 } 2105 2106 final SharedLibraryInfo libraryInfo = getSharedLibraryInfo( 2107 ps.getPkg().getStaticSharedLibraryName(), 2108 ps.getPkg().getStaticSharedLibraryVersion()); 2109 if (libraryInfo == null) { 2110 return false; 2111 } 2112 2113 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 2114 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 2115 if (uidPackageNames == null) { 2116 return true; 2117 } 2118 2119 for (String uidPackageName : uidPackageNames) { 2120 if (ps.getPackageName().equals(uidPackageName)) { 2121 return false; 2122 } 2123 PackageStateInternal uidPs = mSettings.getPackage(uidPackageName); 2124 if (uidPs != null) { 2125 final int index = ArrayUtils.indexOf(uidPs.getUsesStaticLibraries(), 2126 libraryInfo.getName()); 2127 if (index < 0) { 2128 continue; 2129 } 2130 if (uidPs.getPkg().getUsesStaticLibrariesVersions()[index] 2131 == libraryInfo.getLongVersion()) { 2132 return false; 2133 } 2134 } 2135 } 2136 return true; 2137 } 2138 filterSdkLibPackage(@ullable PackageStateInternal ps, int uid, int userId, @PackageManager.ComponentInfoFlagsBits long flags)2139 private boolean filterSdkLibPackage(@Nullable PackageStateInternal ps, int uid, 2140 int userId, @PackageManager.ComponentInfoFlagsBits long flags) { 2141 // Callers can access only the SDK libs they depend on, otherwise they need to 2142 // explicitly ask for the SDKs given the caller is allowed to access 2143 // all shared libs. 2144 if ((flags & PackageManager.MATCH_STATIC_SHARED_AND_SDK_LIBRARIES) != 0) { 2145 // System/shell/root get to see all SDK libs. 2146 final int appId = UserHandle.getAppId(uid); 2147 if (PackageManagerServiceUtils.isSystemOrRootOrShell(appId)) { 2148 return false; 2149 } 2150 // Installer gets to see all SDK libs. 2151 if (PackageManager.PERMISSION_GRANTED 2152 == checkUidPermission(Manifest.permission.INSTALL_PACKAGES, uid)) { 2153 return false; 2154 } 2155 } 2156 2157 // No package means no static lib as it is always on internal storage 2158 if (ps == null || ps.getPkg() == null || !ps.getPkg().isSdkLibrary()) { 2159 return false; 2160 } 2161 2162 final SharedLibraryInfo libraryInfo = getSharedLibraryInfo( 2163 ps.getPkg().getSdkLibraryName(), ps.getPkg().getSdkLibVersionMajor()); 2164 if (libraryInfo == null) { 2165 return false; 2166 } 2167 2168 final int resolvedUid = UserHandle.getUid(userId, UserHandle.getAppId(uid)); 2169 final String[] uidPackageNames = getPackagesForUid(resolvedUid); 2170 if (uidPackageNames == null) { 2171 return true; 2172 } 2173 2174 for (String uidPackageName : uidPackageNames) { 2175 if (ps.getPackageName().equals(uidPackageName)) { 2176 return false; 2177 } 2178 PackageStateInternal uidPs = mSettings.getPackage(uidPackageName); 2179 if (uidPs != null) { 2180 final int index = ArrayUtils.indexOf(uidPs.getUsesSdkLibraries(), 2181 libraryInfo.getName()); 2182 if (index < 0) { 2183 continue; 2184 } 2185 if (uidPs.getPkg().getUsesSdkLibrariesVersionsMajor()[index] 2186 == libraryInfo.getLongVersion()) { 2187 return false; 2188 } 2189 } 2190 } 2191 return true; 2192 } 2193 2194 @Override filterSharedLibPackage(@ullable PackageStateInternal ps, int uid, int userId, @PackageManager.ComponentInfoFlagsBits long flags)2195 public final boolean filterSharedLibPackage(@Nullable PackageStateInternal ps, int uid, 2196 int userId, @PackageManager.ComponentInfoFlagsBits long flags) { 2197 return filterStaticSharedLibPackage(ps, uid, userId, flags) || filterSdkLibPackage(ps, uid, 2198 userId, flags); 2199 } 2200 hasCrossUserPermission( int callingUid, int callingUserId, int userId, boolean requireFullPermission, boolean requirePermissionWhenSameUser)2201 private boolean hasCrossUserPermission( 2202 int callingUid, int callingUserId, int userId, boolean requireFullPermission, 2203 boolean requirePermissionWhenSameUser) { 2204 if (!requirePermissionWhenSameUser && userId == callingUserId) { 2205 return true; 2206 } 2207 if (PackageManagerServiceUtils.isSystemOrRoot(callingUid)) { 2208 return true; 2209 } 2210 boolean permissionGranted = requireFullPermission ? hasPermission( 2211 Manifest.permission.INTERACT_ACROSS_USERS_FULL) 2212 : (hasPermission( 2213 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL) 2214 || hasPermission(Manifest.permission.INTERACT_ACROSS_USERS)); 2215 if (!permissionGranted) { 2216 if (Process.isIsolatedUid(callingUid) && isKnownIsolatedComputeApp(callingUid)) { 2217 return checkIsolatedOwnerHasPermission(callingUid, requireFullPermission); 2218 } 2219 } 2220 return permissionGranted; 2221 } 2222 2223 /** 2224 * @param resolveInfos list of resolve infos in descending priority order 2225 * @return if the list contains a resolve info with non-negative priority 2226 */ hasNonNegativePriority(List<ResolveInfo> resolveInfos)2227 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 2228 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 2229 } 2230 hasPermission(String permission)2231 private boolean hasPermission(String permission) { 2232 return mContext.checkCallingOrSelfPermission(permission) 2233 == PackageManager.PERMISSION_GRANTED; 2234 } 2235 hasPermission(String permission, int uid)2236 private boolean hasPermission(String permission, int uid) { 2237 return mContext.checkPermission(permission, Process.INVALID_PID, uid) 2238 == PackageManager.PERMISSION_GRANTED; 2239 } 2240 2241 /** 2242 * Since isolated process cannot hold permissions, we check the permissions on the owner app 2243 * for known isolated_compute_app cases because they belong to the same package. 2244 */ checkIsolatedOwnerHasPermission(int callingUid, boolean requireFullPermission)2245 private boolean checkIsolatedOwnerHasPermission(int callingUid, boolean requireFullPermission) { 2246 int ownerUid = getIsolatedOwner(callingUid); 2247 if (requireFullPermission) { 2248 return hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL, ownerUid); 2249 } 2250 return hasPermission(Manifest.permission.INTERACT_ACROSS_USERS_FULL, ownerUid) 2251 || hasPermission(Manifest.permission.INTERACT_ACROSS_USERS, ownerUid); 2252 } 2253 isCallerSameApp(String packageName, int uid)2254 public final boolean isCallerSameApp(String packageName, int uid) { 2255 return isCallerSameApp(packageName, uid, false /* resolveIsolatedUid */); 2256 } 2257 2258 @Override isCallerSameApp(String packageName, int uid, boolean resolveIsolatedUid)2259 public final boolean isCallerSameApp(String packageName, int uid, boolean resolveIsolatedUid) { 2260 if (Process.isSdkSandboxUid(uid)) { 2261 return (packageName != null 2262 && packageName.equals(mService.getSdkSandboxPackageName())); 2263 } 2264 AndroidPackage pkg = mPackages.get(packageName); 2265 if (resolveIsolatedUid && Process.isIsolated(uid)) { 2266 uid = getIsolatedOwner(uid); 2267 } 2268 return pkg != null 2269 && UserHandle.getAppId(uid) == pkg.getUid(); 2270 } 2271 isCallerFromManagedUserOrProfile(@serIdInt int userId)2272 private boolean isCallerFromManagedUserOrProfile(@UserIdInt int userId) { 2273 final var dpmi = mInjector.getLocalService(DevicePolicyManagerInternal.class); 2274 return dpmi != null && dpmi.isUserOrganizationManaged(userId); 2275 } 2276 isComponentVisibleToInstantApp(@ullable ComponentName component)2277 public final boolean isComponentVisibleToInstantApp(@Nullable ComponentName component) { 2278 if (isComponentVisibleToInstantApp(component, TYPE_ACTIVITY)) { 2279 return true; 2280 } 2281 if (isComponentVisibleToInstantApp(component, TYPE_SERVICE)) { 2282 return true; 2283 } 2284 return isComponentVisibleToInstantApp(component, TYPE_PROVIDER); 2285 } 2286 isComponentVisibleToInstantApp( @ullable ComponentName component, @PackageManager.ComponentType int type)2287 public final boolean isComponentVisibleToInstantApp( 2288 @Nullable ComponentName component, @PackageManager.ComponentType int type) { 2289 if (type == TYPE_ACTIVITY) { 2290 final ParsedActivity activity = mComponentResolver.getActivity(component); 2291 if (activity == null) { 2292 return false; 2293 } 2294 final boolean visibleToInstantApp = 2295 (activity.getFlags() & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 2296 final boolean explicitlyVisibleToInstantApp = 2297 (activity.getFlags() & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) 2298 == 0; 2299 return visibleToInstantApp && explicitlyVisibleToInstantApp; 2300 } else if (type == TYPE_RECEIVER) { 2301 final ParsedActivity activity = mComponentResolver.getReceiver(component); 2302 if (activity == null) { 2303 return false; 2304 } 2305 final boolean visibleToInstantApp = 2306 (activity.getFlags() & ActivityInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 2307 final boolean explicitlyVisibleToInstantApp = 2308 (activity.getFlags() & ActivityInfo.FLAG_IMPLICITLY_VISIBLE_TO_INSTANT_APP) 2309 == 0; 2310 return visibleToInstantApp && !explicitlyVisibleToInstantApp; 2311 } else if (type == TYPE_SERVICE) { 2312 final ParsedService service = mComponentResolver.getService(component); 2313 return service != null 2314 && (service.getFlags() & ServiceInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 2315 } else if (type == TYPE_PROVIDER) { 2316 final ParsedProvider provider = mComponentResolver.getProvider(component); 2317 return provider != null 2318 && (provider.getFlags() & ProviderInfo.FLAG_VISIBLE_TO_INSTANT_APP) != 0; 2319 } else if (type == TYPE_UNKNOWN) { 2320 return isComponentVisibleToInstantApp(component); 2321 } 2322 return false; 2323 } 2324 2325 /** 2326 * From Android R, 2327 * camera intents have to match system apps. The only exception to this is if 2328 * the DPC has set the camera persistent preferred activity. This case was introduced 2329 * because it is important that the DPC has the ability to set both system and non-system 2330 * camera persistent preferred activities. 2331 * 2332 * @return {@code true} if the intent is a camera intent and the persistent preferred 2333 * activity was not set by the DPC. 2334 */ isImplicitImageCaptureIntentAndNotSetByDpc(Intent intent, int userId, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags)2335 public final boolean isImplicitImageCaptureIntentAndNotSetByDpc(Intent intent, 2336 int userId, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags) { 2337 return intent.isImplicitImageCaptureIntent() && !isPersistentPreferredActivitySetByDpm( 2338 intent, userId, resolvedType, flags); 2339 } 2340 isInstantApp(String packageName, int userId)2341 public final boolean isInstantApp(String packageName, int userId) { 2342 final int callingUid = Binder.getCallingUid(); 2343 enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 2344 false /* checkShell */, "isInstantApp"); 2345 2346 return isInstantAppInternal(packageName, userId, callingUid); 2347 } 2348 isInstantAppInternal(String packageName, @UserIdInt int userId, int callingUid)2349 public final boolean isInstantAppInternal(String packageName, @UserIdInt int userId, 2350 int callingUid) { 2351 if (HIDE_EPHEMERAL_APIS) { 2352 return false; 2353 } 2354 return isInstantAppInternalBody(packageName, userId, callingUid); 2355 } 2356 isInstantAppInternalBody(String packageName, @UserIdInt int userId, int callingUid)2357 protected boolean isInstantAppInternalBody(String packageName, @UserIdInt int userId, 2358 int callingUid) { 2359 if (Process.isIsolated(callingUid)) { 2360 callingUid = getIsolatedOwner(callingUid); 2361 } 2362 final PackageStateInternal ps = mSettings.getPackage(packageName); 2363 final boolean returnAllowed = 2364 ps != null 2365 && (isCallerSameApp(packageName, callingUid) 2366 || canViewInstantApps(callingUid, userId) 2367 || mInstantAppRegistry.isInstantAccessGranted( 2368 userId, UserHandle.getAppId(callingUid), ps.getAppId())); 2369 if (returnAllowed) { 2370 return ps.getUserStateOrDefault(userId).isInstantApp(); 2371 } 2372 return false; 2373 } 2374 isInstantAppResolutionAllowed( Intent intent, List<ResolveInfo> resolvedActivities, int userId, boolean skipPackageCheck, @PackageManager.ResolveInfoFlagsBits long flags)2375 private boolean isInstantAppResolutionAllowed( 2376 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 2377 boolean skipPackageCheck, @PackageManager.ResolveInfoFlagsBits long flags) { 2378 if (mInstantAppResolverConnection == null) { 2379 return false; 2380 } 2381 if (instantAppInstallerActivity() == null) { 2382 return false; 2383 } 2384 if (intent.getComponent() != null) { 2385 return false; 2386 } 2387 if ((intent.getFlags() & Intent.FLAG_IGNORE_EPHEMERAL) != 0) { 2388 return false; 2389 } 2390 if ((intent.getFlags() & Intent.FLAG_ACTIVITY_REQUIRE_NON_BROWSER) != 0) { 2391 return false; 2392 } 2393 if (!skipPackageCheck && intent.getPackage() != null) { 2394 return false; 2395 } 2396 if (!intent.isWebIntent()) { 2397 // for non web intents, we should not resolve externally if an app already exists to 2398 // handle it or if the caller didn't explicitly request it. 2399 if ((resolvedActivities != null && resolvedActivities.size() != 0) 2400 || (intent.getFlags() & Intent.FLAG_ACTIVITY_MATCH_EXTERNAL) == 0) { 2401 return false; 2402 } 2403 } else { 2404 if (intent.getData() == null || TextUtils.isEmpty(intent.getData().getHost())) { 2405 return false; 2406 } else if (areWebInstantAppsDisabled(userId)) { 2407 return false; 2408 } 2409 } 2410 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 2411 // Or if there's already an ephemeral app installed that handles the action 2412 return isInstantAppResolutionAllowedBody(intent, resolvedActivities, userId, 2413 skipPackageCheck, flags); 2414 } 2415 2416 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 2417 // Or if there's already an ephemeral app installed that handles the action isInstantAppResolutionAllowedBody( Intent intent, List<ResolveInfo> resolvedActivities, int userId, boolean skipPackageCheck, @PackageManager.ResolveInfoFlagsBits long flags)2418 protected boolean isInstantAppResolutionAllowedBody( 2419 Intent intent, List<ResolveInfo> resolvedActivities, int userId, 2420 boolean skipPackageCheck, @PackageManager.ResolveInfoFlagsBits long flags) { 2421 final int count = (resolvedActivities == null ? 0 : resolvedActivities.size()); 2422 var debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 2423 if (debug) { 2424 Slog.d(TAG, "Checking if instant app resolution allowed, resolvedActivities = " 2425 + resolvedActivities); 2426 } 2427 for (int n = 0; n < count; n++) { 2428 final ResolveInfo info = resolvedActivities.get(n); 2429 final String packageName = info.activityInfo.packageName; 2430 final PackageStateInternal ps = mSettings.getPackage(packageName); 2431 if (ps != null) { 2432 // only check domain verification status if the app is not a browser 2433 if (!info.handleAllWebDataURI) { 2434 if (PackageManagerServiceUtils.hasAnyDomainApproval( 2435 mDomainVerificationManager, ps, intent, flags, userId)) { 2436 if (DEBUG_INSTANT) { 2437 Slog.v(TAG, "DENY instant app;" + " pkg: " + packageName 2438 + ", approved"); 2439 } 2440 return false; 2441 } 2442 } 2443 if (ps.getUserStateOrDefault(userId).isInstantApp()) { 2444 if (DEBUG_INSTANT) { 2445 Slog.v(TAG, "DENY instant app installed;" 2446 + " pkg: " + packageName); 2447 } 2448 return false; 2449 } 2450 } else if (debug) { 2451 Slog.d(TAG, "Could not find package " + packageName); 2452 } 2453 } 2454 // We've exhausted all ways to deny ephemeral application; let the system look for them. 2455 return true; 2456 } 2457 isPersistentPreferredActivitySetByDpm(Intent intent, int userId, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags)2458 private boolean isPersistentPreferredActivitySetByDpm(Intent intent, int userId, 2459 String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags) { 2460 PersistentPreferredIntentResolver ppir = 2461 mSettings.getPersistentPreferredActivities(userId); 2462 //TODO(b/158003772): Remove double query 2463 List<PersistentPreferredActivity> pprefs = ppir != null 2464 ? ppir.queryIntent(this, intent, resolvedType, 2465 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 2466 userId) 2467 : new ArrayList<>(); 2468 for (PersistentPreferredActivity ppa : pprefs) { 2469 if (ppa.mIsSetByDpm) { 2470 return true; 2471 } 2472 } 2473 return false; 2474 } 2475 isRecentsAccessingChildProfiles(int callingUid, int targetUserId)2476 private boolean isRecentsAccessingChildProfiles(int callingUid, int targetUserId) { 2477 if (!mInjector.getLocalService(ActivityTaskManagerInternal.class) 2478 .isCallerRecents(callingUid)) { 2479 return false; 2480 } 2481 final long token = Binder.clearCallingIdentity(); 2482 try { 2483 final int callingUserId = UserHandle.getUserId(callingUid); 2484 if (ActivityManager.getCurrentUser() != callingUserId) { 2485 return false; 2486 } 2487 return mUserManager.isSameProfileGroup(callingUserId, targetUserId); 2488 } finally { 2489 Binder.restoreCallingIdentity(token); 2490 } 2491 } 2492 isSameProfileGroup(@serIdInt int callerUserId, @UserIdInt int userId)2493 public final boolean isSameProfileGroup(@UserIdInt int callerUserId, 2494 @UserIdInt int userId) { 2495 final long identity = Binder.clearCallingIdentity(); 2496 try { 2497 return UserManagerService.getInstance().isSameProfileGroup(callerUserId, userId); 2498 } finally { 2499 Binder.restoreCallingIdentity(identity); 2500 } 2501 } 2502 2503 /** 2504 * Returns whether or not access to the application should be filtered. 2505 * <p> 2506 * Access may be limited based upon whether the calling or target applications 2507 * are instant applications. 2508 * 2509 * @see #canViewInstantApps(int, int) 2510 */ shouldFilterApplication(@ullable PackageStateInternal ps, int callingUid, @Nullable ComponentName component, @PackageManager.ComponentType int componentType, int userId, boolean filterUninstall, boolean filterArchived)2511 public final boolean shouldFilterApplication(@Nullable PackageStateInternal ps, 2512 int callingUid, @Nullable ComponentName component, 2513 @PackageManager.ComponentType int componentType, int userId, boolean filterUninstall, 2514 boolean filterArchived) { 2515 if (Process.isSdkSandboxUid(callingUid)) { 2516 int clientAppUid = Process.getAppUidForSdkSandboxUid(callingUid); 2517 // SDK sandbox should be able to see it's client app 2518 if (ps != null && clientAppUid == UserHandle.getUid(userId, ps.getAppId())) { 2519 return false; 2520 } 2521 } 2522 // if we're in an isolated process, get the real calling UID 2523 if (Process.isIsolated(callingUid)) { 2524 callingUid = getIsolatedOwner(callingUid); 2525 } 2526 final String instantAppPkgName = getInstantAppPackageName(callingUid); 2527 final boolean callerIsInstantApp = instantAppPkgName != null; 2528 final boolean packageArchivedForUser = ps != null && PackageArchiver.isArchived( 2529 ps.getUserStateOrDefault(userId)); 2530 // Don't treat hiddenUntilInstalled as an uninstalled state, phone app needs to access 2531 // these hidden application details to customize carrier apps. Also, allowing the system 2532 // caller accessing to application across users. 2533 if (ps == null 2534 || (filterUninstall 2535 && !isSystemOrRootOrShell(callingUid) 2536 && !ps.isHiddenUntilInstalled() 2537 && !ps.getUserStateOrDefault(userId).isInstalled() 2538 // Archived packages behave like uninstalled packages. So if filterUninstall is 2539 // set to true, we dismiss filtering some uninstalled package only if it is 2540 // archived and filterArchived is set as false. 2541 && (!packageArchivedForUser || filterArchived))) { 2542 // If caller is instant app or sdk sandbox and ps is null, pretend the application 2543 // exists, but, needs to be filtered 2544 return (callerIsInstantApp || filterUninstall || Process.isSdkSandboxUid(callingUid)); 2545 } 2546 // if the target and caller are the same application, don't filter 2547 if (isCallerSameApp(ps.getPackageName(), callingUid)) { 2548 return false; 2549 } 2550 if (callerIsInstantApp) { 2551 // both caller and target are both instant, but, different applications, filter 2552 if (ps.getUserStateOrDefault(userId).isInstantApp()) { 2553 return true; 2554 } 2555 // request for a specific component; if it hasn't been explicitly exposed through 2556 // property or instrumentation target, filter 2557 if (component != null) { 2558 final ParsedInstrumentation instrumentation = 2559 mInstrumentation.get(component); 2560 if (instrumentation != null 2561 && isCallerSameApp(instrumentation.getTargetPackage(), callingUid)) { 2562 return false; 2563 } 2564 return !isComponentVisibleToInstantApp(component, componentType); 2565 } 2566 // request for application; if no components have been explicitly exposed, filter 2567 return !ps.getPkg().isVisibleToInstantApps(); 2568 } 2569 if (ps.getUserStateOrDefault(userId).isInstantApp()) { 2570 // caller can see all components of all instant applications, don't filter 2571 if (canViewInstantApps(callingUid, userId)) { 2572 return false; 2573 } 2574 // request for a specific instant application component, filter 2575 if (component != null) { 2576 return true; 2577 } 2578 // request for an instant application; if the caller hasn't been granted access, 2579 //filter 2580 return !mInstantAppRegistry.isInstantAccessGranted( 2581 userId, UserHandle.getAppId(callingUid), ps.getAppId()); 2582 } 2583 int appId = UserHandle.getAppId(callingUid); 2584 final SettingBase callingPs = mSettings.getSettingBase(appId); 2585 return mAppsFilter.shouldFilterApplication(this, callingUid, callingPs, ps, userId); 2586 } 2587 2588 /** 2589 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2590 * boolean) 2591 */ shouldFilterApplication(@ullable PackageStateInternal ps, int callingUid, @Nullable ComponentName component, @PackageManager.ComponentType int componentType, int userId, boolean filterUninstall)2592 public final boolean shouldFilterApplication(@Nullable PackageStateInternal ps, 2593 int callingUid, @Nullable ComponentName component, 2594 @PackageManager.ComponentType int componentType, int userId, boolean filterUninstall) { 2595 return shouldFilterApplication( 2596 ps, callingUid, component, componentType, userId, filterUninstall, 2597 true /* filterArchived */); 2598 } 2599 2600 /** 2601 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2602 * boolean) 2603 */ shouldFilterApplication(@ullable PackageStateInternal ps, int callingUid, @Nullable ComponentName component, @PackageManager.ComponentType int componentType, int userId)2604 public final boolean shouldFilterApplication(@Nullable PackageStateInternal ps, 2605 int callingUid, @Nullable ComponentName component, 2606 @PackageManager.ComponentType int componentType, int userId) { 2607 return shouldFilterApplication( 2608 ps, callingUid, component, componentType, userId, false /* filterUninstall */); 2609 } 2610 2611 /** 2612 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2613 * boolean) 2614 */ shouldFilterApplication( @ullable PackageStateInternal ps, int callingUid, int userId)2615 public final boolean shouldFilterApplication( 2616 @Nullable PackageStateInternal ps, int callingUid, int userId) { 2617 return shouldFilterApplication( 2618 ps, callingUid, null, TYPE_UNKNOWN, userId, false /* filterUninstall */); 2619 } 2620 2621 /** 2622 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2623 * boolean) 2624 */ shouldFilterApplication(@onNull SharedUserSetting sus, int callingUid, int userId)2625 public final boolean shouldFilterApplication(@NonNull SharedUserSetting sus, 2626 int callingUid, int userId) { 2627 boolean filterApp = true; 2628 final ArraySet<PackageStateInternal> packageStates = 2629 (ArraySet<PackageStateInternal>) sus.getPackageStates(); 2630 for (int index = packageStates.size() - 1; index >= 0 && filterApp; index--) { 2631 filterApp &= shouldFilterApplication(packageStates.valueAt(index), callingUid, 2632 null /* component */, TYPE_UNKNOWN, userId, false /* filterUninstall */); 2633 } 2634 return filterApp; 2635 } 2636 2637 /** 2638 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2639 * boolean) 2640 */ shouldFilterApplicationIncludingUninstalled( @ullable PackageStateInternal ps, int callingUid, int userId)2641 public final boolean shouldFilterApplicationIncludingUninstalled( 2642 @Nullable PackageStateInternal ps, int callingUid, int userId) { 2643 return shouldFilterApplication( 2644 ps, callingUid, null, TYPE_UNKNOWN, userId, true /* filterUninstall */); 2645 } 2646 2647 /** 2648 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2649 * boolean) 2650 */ shouldFilterApplicationIncludingUninstalledNotArchived( @ullable PackageStateInternal ps, int callingUid, int userId)2651 public final boolean shouldFilterApplicationIncludingUninstalledNotArchived( 2652 @Nullable PackageStateInternal ps, int callingUid, int userId) { 2653 return shouldFilterApplication( 2654 ps, callingUid, null, TYPE_UNKNOWN, userId, true /* filterUninstall */, 2655 false /* filterArchived */); 2656 } 2657 2658 /** 2659 * @see #shouldFilterApplication(PackageStateInternal, int, ComponentName, int, int, boolean, 2660 * boolean) 2661 */ shouldFilterApplicationIncludingUninstalled( @onNull SharedUserSetting sus, int callingUid, int userId)2662 public final boolean shouldFilterApplicationIncludingUninstalled( 2663 @NonNull SharedUserSetting sus, int callingUid, int userId) { 2664 if (shouldFilterApplication(sus, callingUid, userId)) { 2665 return true; 2666 } 2667 if (isSystemOrRootOrShell(callingUid)) { 2668 return false; 2669 } 2670 final ArraySet<PackageStateInternal> packageStates = 2671 (ArraySet<PackageStateInternal>) sus.getPackageStates(); 2672 for (int index = 0; index < packageStates.size(); index++) { 2673 final PackageStateInternal ps = packageStates.valueAt(index); 2674 if (ps.getUserStateOrDefault(userId).isInstalled() || ps.isHiddenUntilInstalled()) { 2675 return false; 2676 } 2677 } 2678 // Filter it, all packages with the same shared uid are uninstalled. 2679 return true; 2680 } 2681 2682 /** 2683 * Verification statuses are ordered from the worse to the best, except for 2684 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 2685 */ bestDomainVerificationStatus(int status1, int status2)2686 private int bestDomainVerificationStatus(int status1, int status2) { 2687 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 2688 return status2; 2689 } 2690 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 2691 return status1; 2692 } 2693 return (int) MathUtils.max(status1, status2); 2694 } 2695 2696 // NOTE: Can't remove without a major refactor. Keep around for now. checkUidPermission(String permName, int uid)2697 public final int checkUidPermission(String permName, int uid) { 2698 return mPermissionManager.checkUidPermission(uid, permName, Context.DEVICE_ID_DEFAULT); 2699 } 2700 getPackageUidInternal(String packageName, @PackageManager.PackageInfoFlagsBits long flags, int userId, int callingUid)2701 public int getPackageUidInternal(String packageName, 2702 @PackageManager.PackageInfoFlagsBits long flags, int userId, int callingUid) { 2703 // reader 2704 var packageState = mSettings.getPackage(packageName); 2705 final AndroidPackage p = mPackages.get(packageName); 2706 if (p != null && AndroidPackageUtils.isMatchForSystemOnly(packageState, flags)) { 2707 final PackageStateInternal ps = getPackageStateInternal(p.getPackageName(), callingUid); 2708 if (ps != null && ps.getUserStateOrDefault(userId).isInstalled() 2709 && !shouldFilterApplication(ps, callingUid, userId)) { 2710 return UserHandle.getUid(userId, p.getUid()); 2711 } 2712 } 2713 if ((flags & (MATCH_KNOWN_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0) { 2714 final PackageStateInternal ps = mSettings.getPackage(packageName); 2715 if (ps != null && PackageStateUtils.isMatch(ps, flags) 2716 && !shouldFilterApplication(ps, callingUid, userId)) { 2717 return UserHandle.getUid(userId, ps.getAppId()); 2718 } 2719 } 2720 2721 return INVALID_UID; 2722 } 2723 2724 /** 2725 * Update given flags based on encryption status of current user. 2726 */ updateFlags(long flags, int userId)2727 private long updateFlags(long flags, int userId) { 2728 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 2729 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 2730 // Caller expressed an explicit opinion about what encryption 2731 // aware/unaware components they want to see, so fall through and 2732 // give them what they want 2733 } else { 2734 final UserManagerInternal umInternal = mInjector.getUserManagerInternal(); 2735 // Caller expressed no opinion, so match based on user state 2736 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 2737 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 2738 } else { 2739 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 2740 } 2741 } 2742 return flags; 2743 } 2744 2745 /** 2746 * Update given flags when being used to request {@link ApplicationInfo}. 2747 */ updateFlagsForApplication(long flags, int userId)2748 public final long updateFlagsForApplication(long flags, int userId) { 2749 return updateFlagsForPackage(flags, userId); 2750 } 2751 2752 /** 2753 * Update given flags when being used to request {@link ComponentInfo}. 2754 */ updateFlagsForComponent(long flags, int userId)2755 public final long updateFlagsForComponent(long flags, int userId) { 2756 return updateFlags(flags, userId); 2757 } 2758 2759 /** 2760 * Update given flags when being used to request {@link PackageInfo}. 2761 */ updateFlagsForPackage(long flags, int userId)2762 public final long updateFlagsForPackage(long flags, int userId) { 2763 final boolean isCallerSystemUser = UserHandle.getCallingUserId() 2764 == UserHandle.USER_SYSTEM; 2765 if ((flags & PackageManager.MATCH_ANY_USER) != 0) { 2766 // require the permission to be held; the calling uid and given user id referring 2767 // to the same user is not sufficient 2768 enforceCrossUserPermission(Binder.getCallingUid(), userId, false, false, 2769 !isRecentsAccessingChildProfiles(Binder.getCallingUid(), userId), 2770 "MATCH_ANY_USER flag requires INTERACT_ACROSS_USERS permission"); 2771 } else if ((flags & PackageManager.MATCH_UNINSTALLED_PACKAGES) != 0 2772 && isCallerSystemUser 2773 && mUserManager.hasProfile(UserHandle.USER_SYSTEM)) { 2774 // If the caller wants all packages and has a profile associated with it, 2775 // then match all users. This is to make sure that launchers that need to access 2776 //work 2777 // profile apps don't start breaking. TODO: Remove this hack when launchers stop 2778 //using 2779 // MATCH_UNINSTALLED_PACKAGES to query apps in other profiles. b/31000380 2780 flags |= PackageManager.MATCH_ANY_USER; 2781 } 2782 return updateFlags(flags, userId); 2783 } 2784 2785 /** 2786 * Update given flags when being used to request {@link ResolveInfo}. 2787 * <p>Instant apps are resolved specially, depending upon context. Minimally, 2788 * {@code}flags{@code} must have the {@link PackageManager#MATCH_INSTANT} 2789 * flag set. However, this flag is only honoured in three circumstances: 2790 * <ul> 2791 * <li>when called from a system process</li> 2792 * <li>when the caller holds the permission {@code 2793 * android.permission.ACCESS_INSTANT_APPS}</li> 2794 * <li>when resolution occurs to start an activity with a {@code android.intent.action.VIEW} 2795 * action and a {@code android.intent.category.BROWSABLE} category</li> 2796 * </ul> 2797 */ updateFlagsForResolve(long flags, int userId, int callingUid, boolean wantInstantApps, boolean isImplicitImageCaptureIntentAndNotSetByDpc)2798 public final long updateFlagsForResolve(long flags, int userId, int callingUid, 2799 boolean wantInstantApps, boolean isImplicitImageCaptureIntentAndNotSetByDpc) { 2800 return updateFlagsForResolve(flags, userId, callingUid, 2801 wantInstantApps, false /*onlyExposedExplicitly*/, 2802 isImplicitImageCaptureIntentAndNotSetByDpc); 2803 } 2804 updateFlagsForResolve(long flags, int userId, int callingUid, boolean wantInstantApps, boolean onlyExposedExplicitly, boolean isImplicitImageCaptureIntentAndNotSetByDpc)2805 public final long updateFlagsForResolve(long flags, int userId, int callingUid, 2806 boolean wantInstantApps, boolean onlyExposedExplicitly, 2807 boolean isImplicitImageCaptureIntentAndNotSetByDpc) { 2808 // Safe mode means we shouldn't match any third-party components 2809 if (safeMode() || isImplicitImageCaptureIntentAndNotSetByDpc) { 2810 flags |= PackageManager.MATCH_SYSTEM_ONLY; 2811 } 2812 if (getInstantAppPackageName(callingUid) != null) { 2813 // But, ephemeral apps see both ephemeral and exposed, non-ephemeral components 2814 if (onlyExposedExplicitly) { 2815 flags |= PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY; 2816 } 2817 flags |= PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY; 2818 flags |= PackageManager.MATCH_INSTANT; 2819 } else { 2820 final boolean wantMatchInstant = (flags & PackageManager.MATCH_INSTANT) != 0; 2821 final boolean allowMatchInstant = wantInstantApps 2822 || (wantMatchInstant && canViewInstantApps(callingUid, userId)); 2823 flags &= ~(PackageManager.MATCH_VISIBLE_TO_INSTANT_APP_ONLY 2824 | PackageManager.MATCH_EXPLICITLY_VISIBLE_ONLY); 2825 if (!allowMatchInstant) { 2826 flags &= ~PackageManager.MATCH_INSTANT; 2827 } 2828 } 2829 return updateFlagsForComponent(flags, userId); 2830 } 2831 2832 /** 2833 * Checks if the request is from the system or an app that has the appropriate cross-user 2834 * permissions defined as follows: 2835 * <ul> 2836 * <li>INTERACT_ACROSS_USERS_FULL if {@code requireFullPermission} is true.</li> 2837 * <li>INTERACT_ACROSS_USERS if the given {@code userId} is in a different profile group 2838 * to the caller.</li> 2839 * <li>Otherwise, 2840 * INTERACT_ACROSS_PROFILES if the given {@code userId} is in the same profile 2841 * group as the caller.</li> 2842 * </ul> 2843 * 2844 * @param checkShell whether to prevent shell from access if there's a debugging restriction 2845 * @param message the message to log on security exception 2846 */ enforceCrossUserOrProfilePermission(int callingUid, @UserIdInt int userId, boolean requireFullPermission, boolean checkShell, String message)2847 public final void enforceCrossUserOrProfilePermission(int callingUid, @UserIdInt int userId, 2848 boolean requireFullPermission, boolean checkShell, String message) { 2849 if (userId < 0) { 2850 throw new IllegalArgumentException("Invalid userId " + userId); 2851 } 2852 if (checkShell) { 2853 PackageManagerServiceUtils.enforceShellRestriction( 2854 mInjector.getUserManagerInternal(), 2855 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2856 } 2857 final int callingUserId = UserHandle.getUserId(callingUid); 2858 if (hasCrossUserPermission(callingUid, callingUserId, userId, requireFullPermission, 2859 /*requirePermissionWhenSameUser= */ false)) { 2860 return; 2861 } 2862 final boolean isSameProfileGroup = isSameProfileGroup(callingUserId, userId); 2863 if (isSameProfileGroup && PermissionChecker.checkPermissionForPreflight( 2864 mContext, 2865 android.Manifest.permission.INTERACT_ACROSS_PROFILES, 2866 PermissionChecker.PID_UNKNOWN, 2867 callingUid, 2868 getPackage(callingUid).getPackageName()) 2869 == PermissionChecker.PERMISSION_GRANTED) { 2870 return; 2871 } 2872 String errorMessage = buildInvalidCrossUserOrProfilePermissionMessage( 2873 callingUid, userId, message, requireFullPermission, isSameProfileGroup); 2874 Slog.w(TAG, errorMessage); 2875 throw new SecurityException(errorMessage); 2876 } 2877 buildInvalidCrossUserOrProfilePermissionMessage(int callingUid, @UserIdInt int userId, String message, boolean requireFullPermission, boolean isSameProfileGroup)2878 private static String buildInvalidCrossUserOrProfilePermissionMessage(int callingUid, 2879 @UserIdInt int userId, String message, boolean requireFullPermission, 2880 boolean isSameProfileGroup) { 2881 StringBuilder builder = new StringBuilder(); 2882 if (message != null) { 2883 builder.append(message); 2884 builder.append(": "); 2885 } 2886 builder.append("UID "); 2887 builder.append(callingUid); 2888 builder.append(" requires "); 2889 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 2890 if (!requireFullPermission) { 2891 builder.append(" or "); 2892 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS); 2893 if (isSameProfileGroup) { 2894 builder.append(" or "); 2895 builder.append(android.Manifest.permission.INTERACT_ACROSS_PROFILES); 2896 } 2897 } 2898 builder.append(" to access user "); 2899 builder.append(userId); 2900 builder.append("."); 2901 return builder.toString(); 2902 } 2903 2904 /** 2905 * Enforces the request is from the system or an app that has INTERACT_ACROSS_USERS 2906 * or INTERACT_ACROSS_USERS_FULL permissions, if the {@code userId} is not for the caller. 2907 * 2908 * @param checkShell whether to prevent shell from access if there's a debugging restriction 2909 * @param message the message to log on security exception 2910 */ enforceCrossUserPermission(int callingUid, @UserIdInt int userId, boolean requireFullPermission, boolean checkShell, String message)2911 public final void enforceCrossUserPermission(int callingUid, @UserIdInt int userId, 2912 boolean requireFullPermission, boolean checkShell, String message) { 2913 enforceCrossUserPermission(callingUid, userId, requireFullPermission, checkShell, false, 2914 message); 2915 } 2916 2917 /** 2918 * Enforces the request is from the system or an app that has INTERACT_ACROSS_USERS 2919 * or INTERACT_ACROSS_USERS_FULL permissions, if the {@code userId} is not for the caller. 2920 * 2921 * @param checkShell whether to prevent shell from access if there's a debugging restriction 2922 * @param requirePermissionWhenSameUser When {@code true}, still require the cross user 2923 * permission to be held even if the callingUid and 2924 * userId 2925 * reference the same user. 2926 * @param message the message to log on security exception 2927 */ enforceCrossUserPermission(int callingUid, @UserIdInt int userId, boolean requireFullPermission, boolean checkShell, boolean requirePermissionWhenSameUser, String message)2928 public final void enforceCrossUserPermission(int callingUid, @UserIdInt int userId, 2929 boolean requireFullPermission, boolean checkShell, 2930 boolean requirePermissionWhenSameUser, String message) { 2931 if (userId < 0) { 2932 throw new IllegalArgumentException("Invalid userId " + userId); 2933 } 2934 if (checkShell) { 2935 PackageManagerServiceUtils.enforceShellRestriction( 2936 mInjector.getUserManagerInternal(), 2937 UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 2938 } 2939 final int callingUserId = UserHandle.getUserId(callingUid); 2940 if (hasCrossUserPermission( 2941 callingUid, callingUserId, userId, requireFullPermission, 2942 requirePermissionWhenSameUser)) { 2943 return; 2944 } 2945 String errorMessage = buildInvalidCrossUserPermissionMessage( 2946 callingUid, userId, message, requireFullPermission); 2947 Slog.w(TAG, errorMessage); 2948 throw new SecurityException(errorMessage); 2949 } 2950 buildInvalidCrossUserPermissionMessage(int callingUid, @UserIdInt int userId, String message, boolean requireFullPermission)2951 private static String buildInvalidCrossUserPermissionMessage(int callingUid, 2952 @UserIdInt int userId, String message, boolean requireFullPermission) { 2953 StringBuilder builder = new StringBuilder(); 2954 if (message != null) { 2955 builder.append(message); 2956 builder.append(": "); 2957 } 2958 builder.append("UID "); 2959 builder.append(callingUid); 2960 builder.append(" requires "); 2961 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS_FULL); 2962 if (!requireFullPermission) { 2963 builder.append(" or "); 2964 builder.append(android.Manifest.permission.INTERACT_ACROSS_USERS); 2965 } 2966 builder.append(" to access user "); 2967 builder.append(userId); 2968 builder.append("."); 2969 return builder.toString(); 2970 } 2971 getSigningDetails(@onNull String packageName)2972 public SigningDetails getSigningDetails(@NonNull String packageName) { 2973 AndroidPackage p = mPackages.get(packageName); 2974 if (p == null) { 2975 return null; 2976 } 2977 return p.getSigningDetails(); 2978 } 2979 getSigningDetails(int uid)2980 public SigningDetails getSigningDetails(int uid) { 2981 final int appId = UserHandle.getAppId(uid); 2982 final Object obj = mSettings.getSettingBase(appId); 2983 if (obj != null) { 2984 if (obj instanceof SharedUserSetting) { 2985 return ((SharedUserSetting) obj).signatures.mSigningDetails; 2986 } else if (obj instanceof PackageStateInternal) { 2987 final PackageStateInternal ps = (PackageStateInternal) obj; 2988 return ps.getSigningDetails(); 2989 } 2990 } 2991 return SigningDetails.UNKNOWN; 2992 } 2993 filterAppAccess(AndroidPackage pkg, int callingUid, int userId)2994 public boolean filterAppAccess(AndroidPackage pkg, int callingUid, int userId) { 2995 PackageStateInternal ps = getPackageStateInternal(pkg.getPackageName()); 2996 return shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId); 2997 } 2998 filterAppAccess(String packageName, int callingUid, int userId, boolean filterUninstalled)2999 public boolean filterAppAccess(String packageName, int callingUid, int userId, 3000 boolean filterUninstalled) { 3001 PackageStateInternal ps = getPackageStateInternal(packageName); 3002 return shouldFilterApplication( 3003 ps, callingUid, null /* component */, TYPE_UNKNOWN, userId, filterUninstalled); 3004 } 3005 filterAppAccess(int uid, int callingUid)3006 public boolean filterAppAccess(int uid, int callingUid) { 3007 if (Process.isSdkSandboxUid(uid)) { 3008 // Sdk sandbox instance should be able to see itself. 3009 if (callingUid == uid) { 3010 return false; 3011 } 3012 final int clientAppUid = Process.getAppUidForSdkSandboxUid(uid); 3013 // Client app of this sdk sandbox process should be able to see it. 3014 if (clientAppUid == uid) { 3015 return false; 3016 } 3017 // Nobody else should be able to see the sdk sandbox process. 3018 return true; 3019 } 3020 final int userId = UserHandle.getUserId(uid); 3021 final int appId = UserHandle.getAppId(uid); 3022 final Object setting = mSettings.getSettingBase(appId); 3023 if (setting == null) { 3024 return true; 3025 } 3026 if (setting instanceof SharedUserSetting) { 3027 return shouldFilterApplicationIncludingUninstalled( 3028 (SharedUserSetting) setting, callingUid, userId); 3029 } else if (setting instanceof PackageStateInternal) { 3030 return shouldFilterApplicationIncludingUninstalled( 3031 (PackageStateInternal) setting, callingUid, userId); 3032 } 3033 return true; 3034 } 3035 dump(int type, FileDescriptor fd, PrintWriter pw, DumpState dumpState)3036 public void dump(int type, FileDescriptor fd, PrintWriter pw, DumpState dumpState) { 3037 final String packageName = dumpState.getTargetPackageName(); 3038 final PackageStateInternal setting = mSettings.getPackage(packageName); 3039 final boolean checkin = dumpState.isCheckIn(); 3040 3041 // Return if the package doesn't exist. 3042 if (packageName != null && setting == null && !isApexPackage(packageName)) { 3043 return; 3044 } 3045 3046 switch (type) { 3047 case DumpState.DUMP_VERSION: 3048 { 3049 if (dumpState.onTitlePrinted()) { 3050 pw.println(); 3051 } 3052 pw.println("Database versions:"); 3053 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 3054 break; 3055 } 3056 3057 case DumpState.DUMP_LIBS: 3058 mSharedLibraries.dump(pw, dumpState); 3059 break; 3060 3061 case DumpState.DUMP_PREFERRED: 3062 mSettings.dumpPreferred(pw, dumpState, packageName); 3063 break; 3064 3065 case DumpState.DUMP_PREFERRED_XML: 3066 { 3067 pw.flush(); 3068 FileOutputStream fout = new FileOutputStream(fd); 3069 BufferedOutputStream str = new BufferedOutputStream(fout); 3070 TypedXmlSerializer serializer = Xml.newFastSerializer(); 3071 try { 3072 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 3073 serializer.startDocument(null, true); 3074 serializer.setFeature( 3075 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 3076 mSettings.writePreferredActivitiesLPr(serializer, 0, 3077 dumpState.isFullPreferred()); 3078 serializer.endDocument(); 3079 serializer.flush(); 3080 } catch (IllegalArgumentException e) { 3081 pw.println("Failed writing: " + e); 3082 } catch (IllegalStateException e) { 3083 pw.println("Failed writing: " + e); 3084 } catch (IOException e) { 3085 pw.println("Failed writing: " + e); 3086 } 3087 break; 3088 } 3089 3090 case DumpState.DUMP_QUERIES: 3091 { 3092 final Integer filteringAppId = setting == null ? null : setting.getAppId(); 3093 mAppsFilter.dumpQueries( 3094 pw, filteringAppId, dumpState, mUserManager.getUserIds(), 3095 this::getPackagesForUidInternalBody); 3096 break; 3097 } 3098 3099 case DumpState.DUMP_DOMAIN_PREFERRED: 3100 { 3101 final android.util.IndentingPrintWriter writer = 3102 new android.util.IndentingPrintWriter(pw); 3103 if (dumpState.onTitlePrinted()) { 3104 pw.println(); 3105 } 3106 writer.println("Domain verification status:"); 3107 writer.increaseIndent(); 3108 try { 3109 mDomainVerificationManager.printState(this, writer, packageName, 3110 UserHandle.USER_ALL); 3111 } catch (Exception e) { 3112 pw.println("Failure printing domain verification information"); 3113 Slog.e(TAG, "Failure printing domain verification information", e); 3114 } 3115 writer.decreaseIndent(); 3116 break; 3117 } 3118 3119 case DumpState.DUMP_DEXOPT: 3120 { 3121 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 3122 if (dumpState.onTitlePrinted()) { 3123 pw.println(); 3124 } 3125 ipw.println("Dexopt state:"); 3126 ipw.increaseIndent(); 3127 DexOptHelper.dumpDexoptState(ipw, packageName); 3128 ipw.decreaseIndent(); 3129 break; 3130 } 3131 3132 case DumpState.DUMP_COMPILER_STATS: 3133 { 3134 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " "); 3135 if (dumpState.onTitlePrinted()) { 3136 pw.println(); 3137 } 3138 ipw.println("Compiler stats:"); 3139 ipw.increaseIndent(); 3140 Collection<? extends PackageStateInternal> pkgSettings; 3141 if (setting != null) { 3142 pkgSettings = Collections.singletonList(setting); 3143 } else { 3144 pkgSettings = mSettings.getPackages().values(); 3145 } 3146 3147 for (PackageStateInternal pkgSetting : pkgSettings) { 3148 final AndroidPackage pkg = pkgSetting.getPkg(); 3149 if (pkg == null) { 3150 continue; 3151 } 3152 final String pkgName = pkg.getPackageName(); 3153 ipw.println("[" + pkgName + "]"); 3154 ipw.increaseIndent(); 3155 3156 final CompilerStats.PackageStats stats = 3157 mCompilerStats.getPackageStats(pkgName); 3158 if (stats == null) { 3159 ipw.println("(No recorded stats)"); 3160 } else { 3161 stats.dump(ipw); 3162 } 3163 ipw.decreaseIndent(); 3164 } 3165 break; 3166 } 3167 3168 case DumpState.DUMP_MESSAGES: { 3169 mSettings.dumpReadMessages(pw, dumpState); 3170 break; 3171 } 3172 3173 case DumpState.DUMP_FROZEN: { 3174 // XXX should handle packageName != null by dumping only install data that 3175 // the given package is involved with. 3176 if (dumpState.onTitlePrinted()) { 3177 pw.println(); 3178 } 3179 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 3180 ipw.println(); 3181 ipw.println("Frozen packages:"); 3182 ipw.increaseIndent(); 3183 if (mFrozenPackages.size() == 0) { 3184 ipw.println("(none)"); 3185 } else { 3186 for (int i = 0; i < mFrozenPackages.size(); i++) { 3187 ipw.print("package="); 3188 ipw.print(mFrozenPackages.keyAt(i)); 3189 ipw.print(", refCounts="); 3190 ipw.println(mFrozenPackages.valueAt(i)); 3191 } 3192 } 3193 ipw.decreaseIndent(); 3194 break; 3195 } 3196 3197 case DumpState.DUMP_APEX: { 3198 if (packageName == null || isApexPackage(packageName)) { 3199 mApexManager.dump(pw); 3200 dumpApex(pw, packageName); 3201 } 3202 break; 3203 } 3204 } // switch 3205 } 3206 generateApexPackageInfo(@onNull List<PackageStateInternal> activePackages, @NonNull List<PackageStateInternal> inactivePackages, @NonNull List<PackageStateInternal> factoryActivePackages, @NonNull List<PackageStateInternal> factoryInactivePackages)3207 private void generateApexPackageInfo(@NonNull List<PackageStateInternal> activePackages, 3208 @NonNull List<PackageStateInternal> inactivePackages, 3209 @NonNull List<PackageStateInternal> factoryActivePackages, 3210 @NonNull List<PackageStateInternal> factoryInactivePackages) { 3211 for (AndroidPackage p : mPackages.values()) { 3212 final String packageName = p.getPackageName(); 3213 PackageStateInternal ps = mSettings.getPackage(packageName); 3214 if (!p.isApex() || ps == null) { 3215 continue; 3216 } 3217 activePackages.add(ps); 3218 if (!ps.isUpdatedSystemApp()) { 3219 factoryActivePackages.add(ps); 3220 } else { 3221 PackageStateInternal psDisabled = mSettings.getDisabledSystemPkg(packageName); 3222 factoryInactivePackages.add(psDisabled); 3223 inactivePackages.add(psDisabled); 3224 } 3225 } 3226 } 3227 dumpApex(PrintWriter pw, String packageName)3228 private void dumpApex(PrintWriter pw, String packageName) { 3229 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 3230 List<PackageStateInternal> activePackages = new ArrayList<>(); 3231 List<PackageStateInternal> inactivePackages = new ArrayList<>(); 3232 List<PackageStateInternal> factoryActivePackages = new ArrayList<>(); 3233 List<PackageStateInternal> factoryInactivePackages = new ArrayList<>(); 3234 generateApexPackageInfo(activePackages, inactivePackages, factoryActivePackages, 3235 factoryInactivePackages); 3236 ipw.println("Active APEX packages:"); 3237 dumpApexPackageStates(activePackages, true, packageName, ipw); 3238 ipw.println("Inactive APEX packages:"); 3239 dumpApexPackageStates(inactivePackages, false, packageName, ipw); 3240 ipw.println("Factory APEX packages:"); 3241 dumpApexPackageStates(factoryActivePackages, true, packageName, ipw); 3242 dumpApexPackageStates(factoryInactivePackages, false, packageName, ipw); 3243 } 3244 3245 3246 /** 3247 * Dump information about the packages contained in a particular cache 3248 * @param packageStates the states to print information about. 3249 * @param packageName a {@link String} containing a package name, or {@code null}. If set, 3250 * only information about that specific package will be dumped. 3251 * @param ipw the {@link IndentingPrintWriter} object to send information to. 3252 */ dumpApexPackageStates(List<PackageStateInternal> packageStates, boolean isActive, @Nullable String packageName, IndentingPrintWriter ipw)3253 private static void dumpApexPackageStates(List<PackageStateInternal> packageStates, 3254 boolean isActive, @Nullable String packageName, IndentingPrintWriter ipw) { 3255 ipw.println(); 3256 ipw.increaseIndent(); 3257 for (int i = 0, size = packageStates.size(); i < size; i++) { 3258 final var packageState = packageStates.get(i); 3259 var pkg = packageState.getPkg(); 3260 if (packageName != null && !packageName.equals(pkg.getPackageName())) { 3261 continue; 3262 } 3263 ipw.println(pkg.getPackageName()); 3264 ipw.increaseIndent(); 3265 ipw.println("Version: " + pkg.getLongVersionCode()); 3266 ipw.println("Path: " + pkg.getBaseApkPath()); 3267 ipw.println("IsActive: " + isActive); 3268 ipw.println("IsFactory: " + !packageState.isUpdatedSystemApp()); 3269 ipw.println("ApplicationInfo: "); 3270 ipw.increaseIndent(); 3271 // TODO: Dump the package manually 3272 AndroidPackageUtils.generateAppInfoWithoutState(pkg) 3273 .dump(new PrintWriterPrinter(ipw), ""); 3274 ipw.decreaseIndent(); 3275 ipw.decreaseIndent(); 3276 } 3277 ipw.decreaseIndent(); 3278 ipw.println(); 3279 } 3280 3281 // The body of findPreferredActivity. findPreferredActivityBody( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, List<ResolveInfo> query, boolean always, boolean removeMatches, boolean debug, int userId, boolean queryMayBeFiltered, int callingUid, boolean isDeviceProvisioned)3282 protected PackageManagerService.FindPreferredActivityBodyResult findPreferredActivityBody( 3283 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 3284 List<ResolveInfo> query, boolean always, 3285 boolean removeMatches, boolean debug, int userId, boolean queryMayBeFiltered, 3286 int callingUid, boolean isDeviceProvisioned) { 3287 PackageManagerService.FindPreferredActivityBodyResult 3288 result = new PackageManagerService.FindPreferredActivityBodyResult(); 3289 3290 flags = updateFlagsForResolve( 3291 flags, userId, callingUid, false /*includeInstantApps*/, 3292 isImplicitImageCaptureIntentAndNotSetByDpc(intent, userId, 3293 resolvedType, flags)); 3294 intent = PackageManagerServiceUtils.updateIntentForResolve(intent); 3295 3296 // Try to find a matching persistent preferred activity. 3297 result.mPreferredResolveInfo = findPersistentPreferredActivity(intent, 3298 resolvedType, flags, query, debug, userId); 3299 3300 // If a persistent preferred activity matched, use it. 3301 if (result.mPreferredResolveInfo != null) { 3302 return result; 3303 } 3304 3305 PreferredIntentResolver pir = mSettings.getPreferredActivities(userId); 3306 // Get the list of preferred activities that handle the intent 3307 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 3308 List<PreferredActivity> prefs = pir != null 3309 ? pir.queryIntent(this, intent, resolvedType, 3310 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 3311 userId) 3312 : null; 3313 if (prefs != null && prefs.size() > 0) { 3314 3315 // First figure out how good the original match set is. 3316 // We will only allow preferred activities that came 3317 // from the same match quality. 3318 int match = 0; 3319 3320 if (DEBUG_PREFERRED || debug) { 3321 Slog.v(TAG, "Figuring out best match..."); 3322 } 3323 3324 final int n = query.size(); 3325 for (int j = 0; j < n; j++) { 3326 final ResolveInfo ri = query.get(j); 3327 if (DEBUG_PREFERRED || debug) { 3328 Slog.v(TAG, "Match for " + ri.activityInfo 3329 + ": 0x" + Integer.toHexString(ri.match)); 3330 } 3331 if (ri.match > match) { 3332 match = ri.match; 3333 } 3334 } 3335 3336 if (DEBUG_PREFERRED || debug) { 3337 Slog.v(TAG, "Best match: 0x" + Integer.toHexString(match)); 3338 } 3339 match &= IntentFilter.MATCH_CATEGORY_MASK; 3340 final int m = prefs.size(); 3341 for (int i = 0; i < m; i++) { 3342 final PreferredActivity pa = prefs.get(i); 3343 if (DEBUG_PREFERRED || debug) { 3344 Slog.v(TAG, "Checking PreferredActivity ds=" 3345 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 3346 + "\n component=" + pa.mPref.mComponent); 3347 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3348 } 3349 if (pa.mPref.mMatch != match) { 3350 if (DEBUG_PREFERRED || debug) { 3351 Slog.v(TAG, "Skipping bad match " 3352 + Integer.toHexString(pa.mPref.mMatch)); 3353 } 3354 continue; 3355 } 3356 // If it's not an "always" type preferred activity and that's what we're 3357 // looking for, skip it. 3358 if (always && !pa.mPref.mAlways) { 3359 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 3360 continue; 3361 } 3362 final ActivityInfo ai = getActivityInfo( 3363 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 3364 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 3365 userId); 3366 if (DEBUG_PREFERRED || debug) { 3367 Slog.v(TAG, "Found preferred activity:"); 3368 if (ai != null) { 3369 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3370 } else { 3371 Slog.v(TAG, " null"); 3372 } 3373 } 3374 final boolean excludeSetupWizardHomeActivity = isHomeIntent(intent) 3375 && !isDeviceProvisioned; 3376 final boolean allowSetMutation = !excludeSetupWizardHomeActivity 3377 && !queryMayBeFiltered; 3378 if (ai == null) { 3379 // Do not remove launcher's preferred activity during SetupWizard 3380 // due to it may not install yet 3381 if (!allowSetMutation) { 3382 continue; 3383 } 3384 3385 // This previously registered preferred activity 3386 // component is no longer known. Most likely an update 3387 // to the app was installed and in the new version this 3388 // component no longer exists. Clean it up by removing 3389 // it from the preferred activities list, and skip it. 3390 Slog.w(TAG, "Removing dangling preferred activity: " 3391 + pa.mPref.mComponent); 3392 pir.removeFilter(pa); 3393 result.mChanged = true; 3394 continue; 3395 } 3396 for (int j = 0; j < n; j++) { 3397 final ResolveInfo ri = query.get(j); 3398 if (!ri.activityInfo.applicationInfo.packageName 3399 .equals(ai.applicationInfo.packageName)) { 3400 continue; 3401 } 3402 if (!ri.activityInfo.name.equals(ai.name)) { 3403 continue; 3404 } 3405 3406 if (removeMatches && allowSetMutation) { 3407 pir.removeFilter(pa); 3408 result.mChanged = true; 3409 if (DEBUG_PREFERRED) { 3410 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 3411 } 3412 break; 3413 } 3414 3415 // Okay we found a previously set preferred or last chosen app. 3416 // If the result set is different from when this 3417 // was created, and is not a subset of the preferred set, we need to 3418 // clear it and re-ask the user their preference, if we're looking for 3419 // an "always" type entry. 3420 3421 if (always 3422 && !pa.mPref.sameSet(query, excludeSetupWizardHomeActivity, userId)) { 3423 if (pa.mPref.isSuperset(query, excludeSetupWizardHomeActivity)) { 3424 if (allowSetMutation) { 3425 // some components of the set are no longer present in 3426 // the query, but the preferred activity can still be reused 3427 if (DEBUG_PREFERRED) { 3428 Slog.i(TAG, "Result set changed, but PreferredActivity" 3429 + " is still valid as only non-preferred" 3430 + " components were removed for " + intent 3431 + " type " + resolvedType); 3432 } 3433 // remove obsolete components and re-add the up-to-date 3434 // filter 3435 PreferredActivity freshPa = new PreferredActivity(pa, 3436 pa.mPref.mMatch, 3437 pa.mPref.discardObsoleteComponents(query), 3438 pa.mPref.mComponent, 3439 pa.mPref.mAlways); 3440 pir.removeFilter(pa); 3441 pir.addFilter(this, freshPa); 3442 result.mChanged = true; 3443 } else { 3444 if (DEBUG_PREFERRED) { 3445 Slog.i(TAG, "Do not remove preferred activity"); 3446 } 3447 } 3448 } else { 3449 final boolean isHomeActivity = ACTION_MAIN.equals(intent.getAction()) 3450 && intent.hasCategory(CATEGORY_HOME); 3451 if (!Flags.improveHomeAppBehavior() || !isHomeActivity) { 3452 // Don't reset the preferred activity just for the home intent, we 3453 // should respect the default home app even though there any new 3454 // home activity is enabled. 3455 if (allowSetMutation) { 3456 Slog.i(TAG, 3457 "Result set changed, dropping preferred activity " 3458 + "for " + intent + " type " 3459 + resolvedType); 3460 if (DEBUG_PREFERRED) { 3461 Slog.v(TAG, 3462 "Removing preferred activity since set changed " 3463 + pa.mPref.mComponent); 3464 } 3465 pir.removeFilter(pa); 3466 // Re-add the filter as a "last chosen" entry (!always) 3467 PreferredActivity lastChosen = new PreferredActivity( 3468 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, 3469 false); 3470 pir.addFilter(this, lastChosen); 3471 result.mChanged = true; 3472 } 3473 result.mPreferredResolveInfo = null; 3474 return result; 3475 } 3476 } 3477 } 3478 3479 // Yay! Either the set matched or we're looking for the last chosen 3480 if (DEBUG_PREFERRED || debug) { 3481 Slog.v(TAG, "Returning preferred activity: " 3482 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3483 } 3484 result.mPreferredResolveInfo = ri; 3485 return result; 3486 } 3487 } 3488 } 3489 return result; 3490 } 3491 isHomeIntent(Intent intent)3492 private static boolean isHomeIntent(Intent intent) { 3493 return ACTION_MAIN.equals(intent.getAction()) 3494 && intent.hasCategory(CATEGORY_HOME) 3495 && intent.hasCategory(CATEGORY_DEFAULT); 3496 } 3497 findPreferredActivityInternal( Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, List<ResolveInfo> query, boolean always, boolean removeMatches, boolean debug, int userId, boolean queryMayBeFiltered)3498 public final PackageManagerService.FindPreferredActivityBodyResult findPreferredActivityInternal( 3499 Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 3500 List<ResolveInfo> query, boolean always, 3501 boolean removeMatches, boolean debug, int userId, boolean queryMayBeFiltered) { 3502 3503 final int callingUid = Binder.getCallingUid(); 3504 // Do NOT hold the packages lock; this calls up into the settings provider which 3505 // could cause a deadlock. 3506 final boolean isDeviceProvisioned = 3507 android.provider.Settings.Global.getInt(mContext.getContentResolver(), 3508 android.provider.Settings.Global.DEVICE_PROVISIONED, 0) == 1; 3509 // Find the preferred activity - the lock is held inside the method. 3510 return findPreferredActivityBody( 3511 intent, resolvedType, flags, query, always, removeMatches, debug, 3512 userId, queryMayBeFiltered, callingUid, isDeviceProvisioned); 3513 } 3514 findPersistentPreferredActivity(Intent intent, String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, List<ResolveInfo> query, boolean debug, int userId)3515 public final ResolveInfo findPersistentPreferredActivity(Intent intent, 3516 String resolvedType, @PackageManager.ResolveInfoFlagsBits long flags, 3517 List<ResolveInfo> query, boolean debug, int userId) { 3518 final int n = query.size(); 3519 PersistentPreferredIntentResolver ppir = 3520 mSettings.getPersistentPreferredActivities(userId); 3521 // Get the list of persistent preferred activities that handle the intent 3522 if (DEBUG_PREFERRED || debug) { 3523 Slog.v(TAG, "Looking for persistent preferred activities..."); 3524 } 3525 List<PersistentPreferredActivity> pprefs = ppir != null 3526 ? ppir.queryIntent(this, intent, resolvedType, 3527 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, 3528 userId) 3529 : null; 3530 if (pprefs != null && pprefs.size() > 0) { 3531 final int m = pprefs.size(); 3532 for (int i = 0; i < m; i++) { 3533 final PersistentPreferredActivity ppa = pprefs.get(i); 3534 if (DEBUG_PREFERRED || debug) { 3535 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 3536 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 3537 + "\n component=" + ppa.mComponent); 3538 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3539 } 3540 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 3541 flags | MATCH_DISABLED_COMPONENTS, userId); 3542 if (DEBUG_PREFERRED || debug) { 3543 Slog.v(TAG, "Found persistent preferred activity:"); 3544 if (ai != null) { 3545 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 3546 } else { 3547 Slog.v(TAG, " null"); 3548 } 3549 } 3550 if (ai == null) { 3551 // This previously registered persistent preferred activity 3552 // component is no longer known. Ignore it and do NOT remove it. 3553 continue; 3554 } 3555 for (int j = 0; j < n; j++) { 3556 final ResolveInfo ri = query.get(j); 3557 if (!ri.activityInfo.applicationInfo.packageName 3558 .equals(ai.applicationInfo.packageName)) { 3559 continue; 3560 } 3561 if (!ri.activityInfo.name.equals(ai.name)) { 3562 continue; 3563 } 3564 // Found a persistent preference that can handle the intent. 3565 if (DEBUG_PREFERRED || debug) { 3566 Slog.v(TAG, "Returning persistent preferred activity: " 3567 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 3568 } 3569 return ri; 3570 } 3571 } 3572 } 3573 return null; 3574 } 3575 3576 @Override getPreferredActivities(int userId)3577 public PreferredIntentResolver getPreferredActivities(int userId) { 3578 return mSettings.getPreferredActivities(userId); 3579 } 3580 3581 @NonNull 3582 @Override getPackageStates()3583 public ArrayMap<String, ? extends PackageStateInternal> getPackageStates() { 3584 return mSettings.getPackages(); 3585 } 3586 3587 @NonNull 3588 @Override getDisabledSystemPackageStates()3589 public ArrayMap<String, ? extends PackageStateInternal> getDisabledSystemPackageStates() { 3590 return mSettings.getDisabledSystemPackages(); 3591 } 3592 3593 @Nullable 3594 @Override getRenamedPackage(@onNull String packageName)3595 public String getRenamedPackage(@NonNull String packageName) { 3596 return mSettings.getRenamedPackageLPr(packageName); 3597 } 3598 3599 @NonNull 3600 @Override 3601 public WatchedArrayMap<String, WatchedLongSparseArray<SharedLibraryInfo>> getSharedLibraries()3602 getSharedLibraries() { 3603 return mSharedLibraries.getAll(); 3604 } 3605 3606 @NonNull 3607 @Override getNotifyPackagesForReplacedReceived(@onNull String[] packages)3608 public ArraySet<String> getNotifyPackagesForReplacedReceived(@NonNull String[] packages) { 3609 final int callingUid = Binder.getCallingUid(); 3610 final int callingUserId = UserHandle.getUserId(callingUid); 3611 3612 ArraySet<String> packagesToNotify = new ArraySet<>(); 3613 for (String packageName : packages) { 3614 final PackageStateInternal packageState = getPackageStateInternal(packageName); 3615 if (!shouldFilterApplication(packageState, callingUid, callingUserId)) { 3616 packagesToNotify.add(packageName); 3617 } 3618 } 3619 3620 return packagesToNotify; 3621 } 3622 3623 @PackageManagerService.PackageStartability 3624 @Override getPackageStartability(boolean safeMode, @NonNull String packageName, int callingUid, @UserIdInt int userId)3625 public int getPackageStartability(boolean safeMode, @NonNull String packageName, int callingUid, 3626 @UserIdInt int userId) { 3627 final boolean ceStorageUnlocked = StorageManager.isCeStorageUnlocked(userId); 3628 final PackageStateInternal ps = getPackageStateInternal(packageName); 3629 if (ps == null || shouldFilterApplication(ps, callingUid, userId) 3630 || !ps.getUserStateOrDefault(userId).isInstalled()) { 3631 return PackageManagerService.PACKAGE_STARTABILITY_NOT_FOUND; 3632 } 3633 3634 if (safeMode && !ps.isSystem()) { 3635 return PackageManagerService.PACKAGE_STARTABILITY_NOT_SYSTEM; 3636 } 3637 3638 if (mFrozenPackages.containsKey(packageName)) { 3639 return PackageManagerService.PACKAGE_STARTABILITY_FROZEN; 3640 } 3641 3642 if (!ceStorageUnlocked && !AndroidPackageUtils.isEncryptionAware(ps.getPkg())) { 3643 return PackageManagerService.PACKAGE_STARTABILITY_DIRECT_BOOT_UNSUPPORTED; 3644 } 3645 return PackageManagerService.PACKAGE_STARTABILITY_OK; 3646 } 3647 3648 @Override isPackageAvailable(String packageName, int userId)3649 public boolean isPackageAvailable(String packageName, int userId) { 3650 if (!mUserManager.exists(userId)) return false; 3651 final int callingUid = Binder.getCallingUid(); 3652 enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 3653 false /*checkShell*/, "is package available"); 3654 3655 final PackageStateInternal ps = getPackageStateInternal(packageName); 3656 if (ps != null && ps.getPkg() != null) { 3657 if (shouldFilterApplication(ps, callingUid, userId)) { 3658 return false; 3659 } 3660 final PackageUserStateInternal state = ps.getUserStateOrDefault(userId); 3661 if (state != null) { 3662 return PackageUserStateUtils.isAvailable(state, 0); 3663 } 3664 } 3665 return false; 3666 } 3667 3668 @Override isApexPackage(String packageName)3669 public boolean isApexPackage(String packageName) { 3670 final AndroidPackage pkg = mPackages.get(packageName); 3671 return pkg != null && pkg.isApex(); 3672 } 3673 3674 @Override currentToCanonicalPackageNames(String[] names)3675 public String[] currentToCanonicalPackageNames(String[] names) { 3676 final int callingUid = Binder.getCallingUid(); 3677 if (getInstantAppPackageName(callingUid) != null) { 3678 return names; 3679 } 3680 final String[] out = new String[names.length]; 3681 final int callingUserId = UserHandle.getUserId(callingUid); 3682 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3683 for (int i=names.length-1; i>=0; i--) { 3684 final PackageStateInternal ps = getPackageStateInternal(names[i]); 3685 boolean translateName = false; 3686 if (ps != null && ps.getRealName() != null) { 3687 final boolean targetIsInstantApp = ps.getUserStateOrDefault(callingUserId) 3688 .isInstantApp(); 3689 translateName = !targetIsInstantApp 3690 || canViewInstantApps 3691 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3692 UserHandle.getAppId(callingUid), ps.getAppId()); 3693 } 3694 out[i] = translateName ? ps.getRealName() : names[i]; 3695 } 3696 return out; 3697 } 3698 3699 @Override canonicalToCurrentPackageNames(String[] names)3700 public String[] canonicalToCurrentPackageNames(String[] names) { 3701 final int callingUid = Binder.getCallingUid(); 3702 if (getInstantAppPackageName(callingUid) != null) { 3703 return names; 3704 } 3705 final String[] out = new String[names.length]; 3706 final int callingUserId = UserHandle.getUserId(callingUid); 3707 final boolean canViewInstantApps = canViewInstantApps(callingUid, callingUserId); 3708 for (int i=names.length-1; i>=0; i--) { 3709 final String cur = getRenamedPackage(names[i]); 3710 boolean translateName = false; 3711 if (cur != null) { 3712 final PackageStateInternal ps = getPackageStateInternal(names[i]); 3713 final boolean targetIsInstantApp = 3714 ps != null && ps.getUserStateOrDefault(callingUserId).isInstantApp(); 3715 translateName = !targetIsInstantApp 3716 || canViewInstantApps 3717 || mInstantAppRegistry.isInstantAccessGranted(callingUserId, 3718 UserHandle.getAppId(callingUid), ps.getAppId()); 3719 } 3720 out[i] = translateName ? cur : names[i]; 3721 } 3722 return out; 3723 } 3724 3725 @Override getPackageGids(@onNull String packageName, @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId)3726 public int[] getPackageGids(@NonNull String packageName, 3727 @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId) { 3728 if (!mUserManager.exists(userId)) return null; 3729 final int callingUid = Binder.getCallingUid(); 3730 flags = updateFlagsForPackage(flags, userId); 3731 enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 3732 false /*checkShell*/, "getPackageGids"); 3733 3734 final PackageStateInternal ps = getPackageStateInternal(packageName); 3735 if (ps == null) { 3736 return null; 3737 } 3738 if (ps.getPkg() != null 3739 && AndroidPackageUtils.isMatchForSystemOnly(ps, flags)) { 3740 if (ps.getUserStateOrDefault(userId).isInstalled() 3741 && !shouldFilterApplication(ps, callingUid, userId)) { 3742 return mPermissionManager.getGidsForUid(UserHandle.getUid(userId, 3743 ps.getAppId())); 3744 } 3745 } 3746 if ((flags & (MATCH_KNOWN_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0) { 3747 if (PackageStateUtils.isMatch(ps, flags) 3748 && !shouldFilterApplication(ps, callingUid, userId)) { 3749 return mPermissionManager.getGidsForUid( 3750 UserHandle.getUid(userId, ps.getAppId())); 3751 } 3752 } 3753 3754 return null; 3755 } 3756 3757 @Override getTargetSdkVersion(@onNull String packageName)3758 public int getTargetSdkVersion(@NonNull String packageName) { 3759 final PackageStateInternal ps = getPackageStateInternal(packageName); 3760 if (ps == null || ps.getPkg() == null) { 3761 return -1; 3762 } 3763 if (shouldFilterApplicationIncludingUninstalled(ps, Binder.getCallingUid(), 3764 UserHandle.getCallingUserId())) { 3765 return -1; 3766 } 3767 return ps.getPkg().getTargetSdkVersion(); 3768 } 3769 3770 @Override activitySupportsIntentAsUser(@onNull ComponentName resolveComponentName, @NonNull ComponentName component, @NonNull Intent intent, String resolvedType, int userId)3771 public boolean activitySupportsIntentAsUser(@NonNull ComponentName resolveComponentName, 3772 @NonNull ComponentName component, @NonNull Intent intent, String resolvedType, 3773 int userId) { 3774 final int callingUid = Binder.getCallingUid(); 3775 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 3776 false /* checkShell */, "activitySupportsIntentAsUser"); 3777 if (component.equals(resolveComponentName)) { 3778 // The resolver supports EVERYTHING! 3779 return true; 3780 } 3781 ParsedActivity a = mComponentResolver.getActivity(component); 3782 if (a == null) { 3783 return false; 3784 } 3785 final PackageStateInternal ps = getPackageStateInternal(component.getPackageName()); 3786 if (ps == null) { 3787 return false; 3788 } 3789 if (shouldFilterApplication( 3790 ps, callingUid, component, TYPE_ACTIVITY, userId, true /* filterUninstall */)) { 3791 return false; 3792 } 3793 for (int i=0; i< a.getIntents().size(); i++) { 3794 if (a.getIntents().get(i).getIntentFilter() 3795 .match(intent.getAction(), resolvedType, intent.getScheme(), 3796 intent.getData(), intent.getCategories(), TAG) >= 0) { 3797 return true; 3798 } 3799 } 3800 return false; 3801 } 3802 3803 @Nullable 3804 @Override getReceiverInfo(@onNull ComponentName component, @PackageManager.ComponentInfoFlagsBits long flags, @UserIdInt int userId)3805 public ActivityInfo getReceiverInfo(@NonNull ComponentName component, 3806 @PackageManager.ComponentInfoFlagsBits long flags, @UserIdInt int userId) { 3807 if (!mUserManager.exists(userId)) return null; 3808 final int callingUid = Binder.getCallingUid(); 3809 flags = updateFlagsForComponent(flags, userId); 3810 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 3811 false /* checkShell */, "get receiver info"); 3812 3813 ParsedActivity a = mComponentResolver.getReceiver(component); 3814 if (DEBUG_PACKAGE_INFO) Log.v( 3815 TAG, "getReceiverInfo " + component + ": " + a); 3816 3817 if (a == null) { 3818 return null; 3819 } 3820 3821 final PackageStateInternal ps = getPackageStateInternal(a.getPackageName()); 3822 if (ps == null || ps.getPkg() == null) { 3823 return null; 3824 } 3825 3826 if (PackageStateUtils.isEnabledAndMatches(ps, a, flags, userId)) { 3827 if (shouldFilterApplication(ps, callingUid, component, TYPE_RECEIVER, userId)) { 3828 return null; 3829 } 3830 return PackageInfoUtils.generateActivityInfo(ps.getPkg(), 3831 a, flags, ps.getUserStateOrDefault(userId), userId, ps); 3832 } 3833 return null; 3834 } 3835 3836 @Nullable 3837 @Override getSharedLibraries(@onNull String packageName, @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId)3838 public ParceledListSlice<SharedLibraryInfo> getSharedLibraries(@NonNull String packageName, 3839 @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId) { 3840 if (!mUserManager.exists(userId)) return null; 3841 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 3842 final int callingUid = Binder.getCallingUid(); 3843 if (getInstantAppPackageName(callingUid) != null) { 3844 return null; 3845 } 3846 3847 flags = updateFlagsForPackage(flags, userId); 3848 3849 final boolean canSeeStaticAndSdkLibraries = 3850 mContext.checkCallingOrSelfPermission(INSTALL_PACKAGES) 3851 == PERMISSION_GRANTED 3852 || mContext.checkCallingOrSelfPermission(DELETE_PACKAGES) 3853 == PERMISSION_GRANTED 3854 || canRequestPackageInstalls(packageName, callingUid, userId, 3855 false /* throwIfPermNotDeclared*/) 3856 || mContext.checkCallingOrSelfPermission(REQUEST_DELETE_PACKAGES) 3857 == PERMISSION_GRANTED 3858 || mContext.checkCallingOrSelfPermission( 3859 Manifest.permission.ACCESS_SHARED_LIBRARIES) == PERMISSION_GRANTED; 3860 3861 final WatchedArrayMap<String, WatchedLongSparseArray<SharedLibraryInfo>> sharedLibraries = 3862 getSharedLibraries(); 3863 List<SharedLibraryInfo> result = null; 3864 final int libCount = sharedLibraries.size(); 3865 for (int i = 0; i < libCount; i++) { 3866 WatchedLongSparseArray<SharedLibraryInfo> versionedLib = sharedLibraries.valueAt(i); 3867 if (versionedLib == null) { 3868 continue; 3869 } 3870 3871 final int versionCount = versionedLib.size(); 3872 for (int j = 0; j < versionCount; j++) { 3873 SharedLibraryInfo libInfo = versionedLib.valueAt(j); 3874 if (!canSeeStaticAndSdkLibraries && (libInfo.isStatic() || libInfo.isSdk())) { 3875 break; 3876 } 3877 final long identity = Binder.clearCallingIdentity(); 3878 final VersionedPackage declaringPackage = libInfo.getDeclaringPackage(); 3879 try { 3880 PackageInfo packageInfo = getPackageInfoInternal( 3881 declaringPackage.getPackageName(), 3882 declaringPackage.getLongVersionCode(), 3883 flags | PackageManager.MATCH_STATIC_SHARED_AND_SDK_LIBRARIES, 3884 Binder.getCallingUid(), userId); 3885 if (packageInfo == null) { 3886 continue; 3887 } 3888 } finally { 3889 Binder.restoreCallingIdentity(identity); 3890 } 3891 SharedLibraryInfo resLibInfo = new SharedLibraryInfo(libInfo.getPath(), 3892 libInfo.getPackageName(), libInfo.getAllCodePaths(), 3893 libInfo.getName(), libInfo.getLongVersion(), 3894 libInfo.getType(), declaringPackage, 3895 (libInfo.getDependencies() == null 3896 ? null 3897 : new ArrayList<>(libInfo.getDependencies())), 3898 libInfo.isNative(), 3899 getPackagesUsingSharedLibrary(libInfo, flags, callingUid, userId)); 3900 if (result == null) { 3901 result = new ArrayList<>(); 3902 } 3903 result.add(resLibInfo); 3904 } 3905 } 3906 3907 return result != null ? new ParceledListSlice<>(result) : null; 3908 } 3909 3910 @Override canRequestPackageInstalls(@onNull String packageName, int callingUid, int userId, boolean throwIfPermNotDeclared)3911 public boolean canRequestPackageInstalls(@NonNull String packageName, int callingUid, 3912 int userId, boolean throwIfPermNotDeclared) { 3913 int uid = getPackageUidInternal(packageName, 0, userId, callingUid); 3914 if (callingUid != uid && !PackageManagerServiceUtils.isSystemOrRoot(callingUid)) { 3915 throw new SecurityException( 3916 "Caller uid " + callingUid + " does not own package " + packageName); 3917 } 3918 if (isInstantAppInternal(packageName, userId, Process.SYSTEM_UID)) { 3919 return false; 3920 } 3921 final AndroidPackage pkg = mPackages.get(packageName); 3922 if (pkg == null) { 3923 return false; 3924 } 3925 if (pkg.getTargetSdkVersion() < Build.VERSION_CODES.O) { 3926 return false; 3927 } 3928 if (!pkg.getRequestedPermissions().contains( 3929 android.Manifest.permission.REQUEST_INSTALL_PACKAGES)) { 3930 final String message = "Need to declare " 3931 + android.Manifest.permission.REQUEST_INSTALL_PACKAGES 3932 + " to call this api"; 3933 if (throwIfPermNotDeclared) { 3934 throw new SecurityException(message); 3935 } else { 3936 Slog.e(TAG, message); 3937 return false; 3938 } 3939 } 3940 3941 return !isInstallDisabledForPackage(packageName, uid, userId); 3942 } 3943 3944 /** 3945 * Returns true if the system or user is explicitly preventing an otherwise valid installer to 3946 * complete an install. This includes checks like unknown sources and user restrictions. 3947 */ 3948 @Override isInstallDisabledForPackage(@onNull String packageName, int uid, @UserIdInt int userId)3949 public final boolean isInstallDisabledForPackage(@NonNull String packageName, int uid, 3950 @UserIdInt int userId) { 3951 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES, userId) 3952 || mUserManager.hasUserRestriction( 3953 UserManager.DISALLOW_INSTALL_UNKNOWN_SOURCES_GLOBALLY, userId)) { 3954 return true; 3955 } 3956 if (mExternalSourcesPolicy != null) { 3957 int isTrusted = mExternalSourcesPolicy.getPackageTrustedToInstallApps(packageName, uid); 3958 return isTrusted != PackageManagerInternal.ExternalSourcesPolicy.USER_TRUSTED; 3959 } 3960 return false; 3961 } 3962 3963 3964 @Override getPackagesUsingSharedLibrary( @onNull SharedLibraryInfo libInfo, @PackageManager.PackageInfoFlagsBits long flags, int callingUid, @UserIdInt int userId)3965 public Pair<List<VersionedPackage>, List<Boolean>> getPackagesUsingSharedLibrary( 3966 @NonNull SharedLibraryInfo libInfo, @PackageManager.PackageInfoFlagsBits long flags, 3967 int callingUid, @UserIdInt int userId) { 3968 List<VersionedPackage> versionedPackages = null; 3969 final ArrayMap<String, ? extends PackageStateInternal> packageStates = getPackageStates(); 3970 final int packageCount = packageStates.size(); 3971 List<Boolean> usesLibsOptional = null; 3972 for (int i = 0; i < packageCount; i++) { 3973 PackageStateInternal ps = packageStates.valueAt(i); 3974 if (ps == null) { 3975 continue; 3976 } 3977 3978 if (!PackageUserStateUtils.isAvailable(ps.getUserStateOrDefault(userId), flags)) { 3979 continue; 3980 } 3981 3982 final String libName = libInfo.getName(); 3983 if (libInfo.isStatic() || libInfo.isSdk()) { 3984 final String[] libs = 3985 libInfo.isStatic() ? ps.getUsesStaticLibraries() : ps.getUsesSdkLibraries(); 3986 final long[] libsVersions = libInfo.isStatic() ? ps.getUsesStaticLibrariesVersions() 3987 : ps.getUsesSdkLibrariesVersionsMajor(); 3988 final boolean[] libsOptional = libInfo.isSdk() 3989 ? ps.getUsesSdkLibrariesOptional() : null; 3990 3991 final int libIdx = ArrayUtils.indexOf(libs, libName); 3992 if (libIdx < 0) { 3993 continue; 3994 } 3995 if (libsVersions[libIdx] != libInfo.getLongVersion()) { 3996 // Not expected StaticLib/SdkLib version 3997 continue; 3998 } 3999 if (shouldFilterApplication(ps, callingUid, userId)) { 4000 continue; 4001 } 4002 if (versionedPackages == null) { 4003 versionedPackages = new ArrayList<>(); 4004 } 4005 if (usesLibsOptional == null) { 4006 usesLibsOptional = new ArrayList<>(); 4007 } 4008 // If the dependent is a static shared lib, use the public package name 4009 String dependentPackageName = ps.getPackageName(); 4010 if (ps.getPkg() != null && ps.getPkg().isStaticSharedLibrary()) { 4011 dependentPackageName = ps.getPkg().getManifestPackageName(); 4012 } 4013 versionedPackages.add(new VersionedPackage(dependentPackageName, 4014 ps.getVersionCode())); 4015 usesLibsOptional.add(libsOptional != null && libsOptional[libIdx]); 4016 } else if (ps.getPkg() != null) { 4017 if (ArrayUtils.contains(ps.getPkg().getUsesLibraries(), libName) 4018 || ArrayUtils.contains(ps.getPkg().getUsesOptionalLibraries(), libName)) { 4019 if (shouldFilterApplication(ps, callingUid, userId)) { 4020 continue; 4021 } 4022 if (versionedPackages == null) { 4023 versionedPackages = new ArrayList<>(); 4024 } 4025 versionedPackages.add(new VersionedPackage(ps.getPackageName(), 4026 ps.getVersionCode())); 4027 } 4028 } 4029 } 4030 4031 return new Pair<>(versionedPackages, usesLibsOptional); 4032 } 4033 4034 @Nullable 4035 @Override getDeclaredSharedLibraries( @onNull String packageName, @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId)4036 public ParceledListSlice<SharedLibraryInfo> getDeclaredSharedLibraries( 4037 @NonNull String packageName, @PackageManager.PackageInfoFlagsBits long flags, 4038 @UserIdInt int userId) { 4039 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_SHARED_LIBRARIES, 4040 "getDeclaredSharedLibraries"); 4041 int callingUid = Binder.getCallingUid(); 4042 enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 4043 false /* checkShell */, "getDeclaredSharedLibraries"); 4044 4045 Preconditions.checkNotNull(packageName, "packageName cannot be null"); 4046 Preconditions.checkArgumentNonnegative(userId, "userId must be >= 0"); 4047 if (!mUserManager.exists(userId)) { 4048 return null; 4049 } 4050 4051 if (getInstantAppPackageName(callingUid) != null) { 4052 return null; 4053 } 4054 4055 final WatchedArrayMap<String, WatchedLongSparseArray<SharedLibraryInfo>> sharedLibraries = 4056 getSharedLibraries(); 4057 List<SharedLibraryInfo> result = null; 4058 4059 int libraryCount = sharedLibraries.size(); 4060 for (int i = 0; i < libraryCount; i++) { 4061 WatchedLongSparseArray<SharedLibraryInfo> versionedLibrary = 4062 sharedLibraries.valueAt(i); 4063 if (versionedLibrary == null) { 4064 continue; 4065 } 4066 4067 int versionCount = versionedLibrary.size(); 4068 for (int j = 0; j < versionCount; j++) { 4069 SharedLibraryInfo libraryInfo = versionedLibrary.valueAt(j); 4070 4071 VersionedPackage declaringPackage = libraryInfo.getDeclaringPackage(); 4072 if (!Objects.equals(declaringPackage.getPackageName(), packageName)) { 4073 continue; 4074 } 4075 4076 final long identity = Binder.clearCallingIdentity(); 4077 try { 4078 PackageInfo packageInfo = getPackageInfoInternal( 4079 declaringPackage.getPackageName(), 4080 declaringPackage.getLongVersionCode(), 4081 flags | PackageManager.MATCH_STATIC_SHARED_AND_SDK_LIBRARIES, 4082 Binder.getCallingUid(), userId); 4083 if (packageInfo == null) { 4084 continue; 4085 } 4086 } finally { 4087 Binder.restoreCallingIdentity(identity); 4088 } 4089 4090 var usingSharedLibraryPair = 4091 getPackagesUsingSharedLibrary(libraryInfo, flags, callingUid, userId); 4092 SharedLibraryInfo resultLibraryInfo = new SharedLibraryInfo( 4093 libraryInfo.getPath(), libraryInfo.getPackageName(), 4094 libraryInfo.getAllCodePaths(), libraryInfo.getName(), 4095 libraryInfo.getLongVersion(), libraryInfo.getType(), 4096 libraryInfo.getDeclaringPackage(), 4097 usingSharedLibraryPair.first, 4098 libraryInfo.getDependencies() == null 4099 ? null : new ArrayList<>(libraryInfo.getDependencies()), 4100 libraryInfo.isNative()); 4101 4102 if (result == null) { 4103 result = new ArrayList<>(); 4104 } 4105 result.add(resultLibraryInfo); 4106 } 4107 } 4108 4109 return result != null ? new ParceledListSlice<>(result) : null; 4110 } 4111 4112 @Nullable 4113 @Override getProviderInfo(@onNull ComponentName component, @PackageManager.ComponentInfoFlagsBits long flags, @UserIdInt int userId)4114 public ProviderInfo getProviderInfo(@NonNull ComponentName component, 4115 @PackageManager.ComponentInfoFlagsBits long flags, @UserIdInt int userId) { 4116 if (!mUserManager.exists(userId)) return null; 4117 final int callingUid = Binder.getCallingUid(); 4118 flags = updateFlagsForComponent(flags, userId); 4119 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4120 false /* checkShell */, "get provider info"); 4121 ParsedProvider p = mComponentResolver.getProvider(component); 4122 if (DEBUG_PACKAGE_INFO) Log.v( 4123 TAG, "getProviderInfo " + component + ": " + p); 4124 if (p == null) { 4125 return null; 4126 } 4127 4128 final PackageStateInternal ps = getPackageStateInternal(p.getPackageName()); 4129 if (ps == null || ps.getPkg() == null) { 4130 return null; 4131 } 4132 4133 if (PackageStateUtils.isEnabledAndMatches(ps, p, flags, userId)) { 4134 if (shouldFilterApplication( 4135 ps, callingUid, component, TYPE_PROVIDER, userId)) { 4136 return null; 4137 } 4138 PackageUserStateInternal state = ps.getUserStateOrDefault(userId); 4139 final ApplicationInfo appInfo = 4140 PackageInfoUtils.generateApplicationInfo(ps.getPkg(), flags, state, userId, ps); 4141 if (appInfo == null) { 4142 return null; 4143 } 4144 return PackageInfoUtils.generateProviderInfo(ps.getPkg(), p, flags, state, appInfo, 4145 userId, ps); 4146 } 4147 return null; 4148 } 4149 4150 @Override getSystemSharedLibraryNamesAndPaths()4151 public ArrayMap<String, String> getSystemSharedLibraryNamesAndPaths() { 4152 // allow instant applications 4153 final WatchedArrayMap<String, WatchedLongSparseArray<SharedLibraryInfo>> sharedLibraries = 4154 getSharedLibraries(); 4155 final ArrayMap<String, String> libs = new ArrayMap<>(); 4156 final int libCount = sharedLibraries.size(); 4157 for (int i = 0; i < libCount; i++) { 4158 WatchedLongSparseArray<SharedLibraryInfo> versionedLib = sharedLibraries.valueAt(i); 4159 if (versionedLib == null) { 4160 continue; 4161 } 4162 final int versionCount = versionedLib.size(); 4163 for (int j = 0; j < versionCount; j++) { 4164 SharedLibraryInfo libraryInfo = versionedLib.valueAt(j); 4165 if (!libraryInfo.isStatic()) { 4166 libs.put(libraryInfo.getName(), libraryInfo.getPath()); 4167 break; 4168 } 4169 final PackageStateInternal ps = 4170 getPackageStateInternal(libraryInfo.getPackageName()); 4171 if (ps != null && !filterSharedLibPackage(ps, Binder.getCallingUid(), 4172 UserHandle.getUserId(Binder.getCallingUid()), 4173 PackageManager.MATCH_STATIC_SHARED_AND_SDK_LIBRARIES)) { 4174 libs.put(libraryInfo.getName(), libraryInfo.getPath()); 4175 break; 4176 } 4177 } 4178 } 4179 return libs; 4180 } 4181 4182 @Override getPackageStateForInstalledAndFiltered(@onNull String packageName, int callingUid, @UserIdInt int userId)4183 public PackageStateInternal getPackageStateForInstalledAndFiltered(@NonNull String packageName, 4184 int callingUid, @UserIdInt int userId) { 4185 final PackageStateInternal packageState = getPackageStateInternal(packageName); 4186 if (packageState == null 4187 || shouldFilterApplicationIncludingUninstalled(packageState, callingUid, userId)) { 4188 return null; 4189 } 4190 return packageState; 4191 } 4192 4193 @Override checkSignatures(@onNull String pkg1, @NonNull String pkg2, int userId)4194 public int checkSignatures(@NonNull String pkg1, @NonNull String pkg2, int userId) { 4195 final int callingUid = Binder.getCallingUid(); 4196 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4197 false /* checkShell */, "checkSignatures"); 4198 4199 final AndroidPackage p1 = mPackages.get(pkg1); 4200 final AndroidPackage p2 = mPackages.get(pkg2); 4201 final PackageStateInternal ps1 = 4202 p1 == null ? null : getPackageStateInternal(p1.getPackageName()); 4203 final PackageStateInternal ps2 = 4204 p2 == null ? null : getPackageStateInternal(p2.getPackageName()); 4205 if (p1 == null || ps1 == null || p2 == null || ps2 == null) { 4206 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4207 } 4208 if (shouldFilterApplicationIncludingUninstalled(ps1, callingUid, userId) 4209 || shouldFilterApplicationIncludingUninstalled(ps2, callingUid, userId)) { 4210 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4211 } 4212 return checkSignaturesInternal(p1.getSigningDetails(), p2.getSigningDetails()); 4213 } 4214 4215 @Override checkUidSignatures(int uid1, int uid2)4216 public int checkUidSignatures(int uid1, int uid2) { 4217 final int callingUid = Binder.getCallingUid(); 4218 final int callingUserId = UserHandle.getUserId(callingUid); 4219 final SigningDetails p1SigningDetails = 4220 getSigningDetailsAndFilterAccess(uid1, callingUid, callingUserId); 4221 final SigningDetails p2SigningDetails = 4222 getSigningDetailsAndFilterAccess(uid2, callingUid, callingUserId); 4223 if (p1SigningDetails == null || p2SigningDetails == null) { 4224 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4225 } 4226 return checkSignaturesInternal(p1SigningDetails, p2SigningDetails); 4227 } 4228 4229 @Override checkUidSignaturesForAllUsers(int uid1, int uid2)4230 public int checkUidSignaturesForAllUsers(int uid1, int uid2) { 4231 final int callingUid = Binder.getCallingUid(); 4232 final int userId1 = UserHandle.getUserId(uid1); 4233 final int userId2 = UserHandle.getUserId(uid2); 4234 enforceCrossUserPermission(callingUid, userId1, false /* requireFullPermission */, 4235 false /* checkShell */, "checkUidSignaturesForAllUsers"); 4236 enforceCrossUserPermission(callingUid, userId2, false /* requireFullPermission */, 4237 false /* checkShell */, "checkUidSignaturesForAllUsers"); 4238 final SigningDetails p1SigningDetails = 4239 getSigningDetailsAndFilterAccess(uid1, callingUid, userId1); 4240 final SigningDetails p2SigningDetails = 4241 getSigningDetailsAndFilterAccess(uid2, callingUid, userId2); 4242 if (p1SigningDetails == null || p2SigningDetails == null) { 4243 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4244 } 4245 return checkSignaturesInternal(p1SigningDetails, p2SigningDetails); 4246 } 4247 getSigningDetailsAndFilterAccess(int uid, int callingUid, int userId)4248 private SigningDetails getSigningDetailsAndFilterAccess(int uid, int callingUid, int userId) { 4249 // Map to base uids. 4250 final int appId = UserHandle.getAppId(uid); 4251 final Object obj = mSettings.getSettingBase(appId); 4252 if (obj == null) { 4253 return null; 4254 } 4255 if (obj instanceof SharedUserSetting) { 4256 final SharedUserSetting sus = (SharedUserSetting) obj; 4257 if (shouldFilterApplicationIncludingUninstalled(sus, callingUid, userId)) { 4258 return null; 4259 } 4260 return sus.signatures.mSigningDetails; 4261 } else if (obj instanceof PackageSetting) { 4262 final PackageSetting ps = (PackageSetting) obj; 4263 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 4264 return null; 4265 } 4266 return ps.getSigningDetails(); 4267 } 4268 return null; 4269 } 4270 checkSignaturesInternal(SigningDetails p1SigningDetails, SigningDetails p2SigningDetails)4271 private int checkSignaturesInternal(SigningDetails p1SigningDetails, 4272 SigningDetails p2SigningDetails) { 4273 if (p1SigningDetails == null) { 4274 return p2SigningDetails == null 4275 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4276 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4277 } 4278 if (p2SigningDetails == null) { 4279 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4280 } 4281 int result = compareSignatures(p1SigningDetails, p2SigningDetails); 4282 if (result == PackageManager.SIGNATURE_MATCH) { 4283 return result; 4284 } 4285 // To support backwards compatibility with clients of this API expecting pre-key 4286 // rotation results if either of the packages has a signing lineage the oldest signer 4287 // in the lineage is used for signature verification. 4288 if (p1SigningDetails.hasPastSigningCertificates() 4289 || p2SigningDetails.hasPastSigningCertificates()) { 4290 Signature[] p1Signatures = p1SigningDetails.hasPastSigningCertificates() 4291 ? new Signature[]{p1SigningDetails.getPastSigningCertificates()[0]} 4292 : p1SigningDetails.getSignatures(); 4293 Signature[] p2Signatures = p2SigningDetails.hasPastSigningCertificates() 4294 ? new Signature[]{p2SigningDetails.getPastSigningCertificates()[0]} 4295 : p2SigningDetails.getSignatures(); 4296 result = compareSignatureArrays(p1Signatures, p2Signatures); 4297 } 4298 return result; 4299 } 4300 4301 @Override hasSigningCertificate(@onNull String packageName, @NonNull byte[] certificate, @PackageManager.CertificateInputType int type)4302 public boolean hasSigningCertificate(@NonNull String packageName, @NonNull byte[] certificate, 4303 @PackageManager.CertificateInputType int type) { 4304 final AndroidPackage p = mPackages.get(packageName); 4305 if (p == null) { 4306 return false; 4307 } 4308 final int callingUid = Binder.getCallingUid(); 4309 final int callingUserId = UserHandle.getUserId(callingUid); 4310 final PackageStateInternal ps = getPackageStateInternal(p.getPackageName()); 4311 if (ps == null 4312 || shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 4313 return false; 4314 } 4315 switch (type) { 4316 case CERT_INPUT_RAW_X509: 4317 return p.getSigningDetails().hasCertificate(certificate); 4318 case CERT_INPUT_SHA256: 4319 return p.getSigningDetails().hasSha256Certificate(certificate); 4320 default: 4321 return false; 4322 } 4323 } 4324 4325 @Override hasUidSigningCertificate(int uid, @NonNull byte[] certificate, @PackageManager.CertificateInputType int type)4326 public boolean hasUidSigningCertificate(int uid, @NonNull byte[] certificate, 4327 @PackageManager.CertificateInputType int type) { 4328 final int callingUid = Binder.getCallingUid(); 4329 final int callingUserId = UserHandle.getUserId(callingUid); 4330 final SigningDetails signingDetails = 4331 getSigningDetailsAndFilterAccess(uid, callingUid, callingUserId); 4332 if (signingDetails == null) { 4333 return false; 4334 } 4335 switch (type) { 4336 case CERT_INPUT_RAW_X509: 4337 return signingDetails.hasCertificate(certificate); 4338 case CERT_INPUT_SHA256: 4339 return signingDetails.hasSha256Certificate(certificate); 4340 default: 4341 return false; 4342 } 4343 } 4344 4345 @Override getAllPackages()4346 public List<String> getAllPackages() { 4347 PackageManagerServiceUtils.enforceSystemOrRootOrShell( 4348 "getAllPackages is limited to privileged callers"); 4349 final int callingUid = Binder.getCallingUid(); 4350 final int callingUserId = UserHandle.getUserId(callingUid); 4351 if (canViewInstantApps(callingUid, callingUserId)) { 4352 return new ArrayList<>(mPackages.keySet()); 4353 } 4354 final String instantAppPkgName = getInstantAppPackageName(callingUid); 4355 final List<String> result = new ArrayList<>(); 4356 if (instantAppPkgName != null) { 4357 // caller is an instant application; filter unexposed applications 4358 for (AndroidPackage pkg : mPackages.values()) { 4359 if (!pkg.isVisibleToInstantApps()) { 4360 continue; 4361 } 4362 result.add(pkg.getPackageName()); 4363 } 4364 } else { 4365 // caller is a normal application; filter instant applications 4366 for (AndroidPackage pkg : mPackages.values()) { 4367 final PackageStateInternal ps = getPackageStateInternal(pkg.getPackageName()); 4368 if (ps != null 4369 && ps.getUserStateOrDefault(callingUserId).isInstantApp() 4370 && !mInstantAppRegistry.isInstantAccessGranted(callingUserId, 4371 UserHandle.getAppId(callingUid), ps.getAppId())) { 4372 continue; 4373 } 4374 result.add(pkg.getPackageName()); 4375 } 4376 } 4377 return result; 4378 } 4379 4380 @Nullable 4381 @Override getNameForUid(int uid)4382 public String getNameForUid(int uid) { 4383 final int callingUid = Binder.getCallingUid(); 4384 if (getInstantAppPackageName(callingUid) != null) { 4385 return null; 4386 } 4387 if (Process.isSdkSandboxUid(uid)) { 4388 uid = getBaseSdkSandboxUid(); 4389 } 4390 final int callingUserId = UserHandle.getUserId(callingUid); 4391 if (isKnownIsolatedComputeApp(uid)) { 4392 try { 4393 uid = getIsolatedOwner(uid); 4394 } catch (IllegalStateException e) { 4395 // If the owner uid doesn't exist, just use the current uid 4396 Slog.wtf(TAG, "Expected isolated uid " + uid + " to have an owner", e); 4397 } 4398 } 4399 final int appId = UserHandle.getAppId(uid); 4400 final Object obj = mSettings.getSettingBase(appId); 4401 if (obj instanceof SharedUserSetting) { 4402 final SharedUserSetting sus = (SharedUserSetting) obj; 4403 if (shouldFilterApplicationIncludingUninstalled(sus, callingUid, callingUserId)) { 4404 return null; 4405 } 4406 return sus.name + ":" + sus.mAppId; 4407 } else if (obj instanceof PackageSetting) { 4408 final PackageSetting ps = (PackageSetting) obj; 4409 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 4410 return null; 4411 } 4412 return ps.getPackageName(); 4413 } 4414 return null; 4415 } 4416 4417 @Nullable 4418 @Override getNamesForUids(int[] uids)4419 public String[] getNamesForUids(int[] uids) { 4420 if (uids == null || uids.length == 0) { 4421 return null; 4422 } 4423 final int callingUid = Binder.getCallingUid(); 4424 if (getInstantAppPackageName(callingUid) != null) { 4425 return null; 4426 } 4427 final int callingUserId = UserHandle.getUserId(callingUid); 4428 final String[] names = new String[uids.length]; 4429 for (int i = uids.length - 1; i >= 0; i--) { 4430 int uid = uids[i]; 4431 if (Process.isSdkSandboxUid(uid)) { 4432 uid = getBaseSdkSandboxUid(); 4433 } 4434 if (isKnownIsolatedComputeApp(uid)) { 4435 try { 4436 uid = getIsolatedOwner(uid); 4437 } catch (IllegalStateException e) { 4438 // If the owner uid doesn't exist, just use the current uid 4439 Slog.wtf(TAG, "Expected isolated uid " + uid + " to have an owner", e); 4440 } 4441 } 4442 final int appId = UserHandle.getAppId(uid); 4443 final Object obj = mSettings.getSettingBase(appId); 4444 if (obj instanceof SharedUserSetting) { 4445 final SharedUserSetting sus = (SharedUserSetting) obj; 4446 if (shouldFilterApplicationIncludingUninstalled(sus, callingUid, callingUserId)) { 4447 names[i] = null; 4448 } else { 4449 names[i] = "shared:" + sus.name; 4450 } 4451 } else if (obj instanceof PackageSetting) { 4452 final PackageSetting ps = (PackageSetting) obj; 4453 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 4454 names[i] = null; 4455 } else { 4456 names[i] = ps.getPackageName(); 4457 } 4458 } else { 4459 names[i] = null; 4460 } 4461 } 4462 return names; 4463 } 4464 4465 @Override getUidForSharedUser(@onNull String sharedUserName)4466 public int getUidForSharedUser(@NonNull String sharedUserName) { 4467 if (sharedUserName == null) { 4468 return INVALID_UID; 4469 } 4470 final int callingUid = Binder.getCallingUid(); 4471 if (getInstantAppPackageName(callingUid) != null) { 4472 return INVALID_UID; 4473 } 4474 final SharedUserSetting suid = mSettings.getSharedUserFromId(sharedUserName); 4475 if (suid != null && !shouldFilterApplicationIncludingUninstalled(suid, callingUid, 4476 UserHandle.getUserId(callingUid))) { 4477 return suid.mAppId; 4478 } 4479 return INVALID_UID; 4480 } 4481 4482 @Override getFlagsForUid(int uid)4483 public int getFlagsForUid(int uid) { 4484 final int callingUid = Binder.getCallingUid(); 4485 if (getInstantAppPackageName(callingUid) != null) { 4486 return 0; 4487 } 4488 if (Process.isSdkSandboxUid(uid)) { 4489 uid = getBaseSdkSandboxUid(); 4490 } 4491 final int callingUserId = UserHandle.getUserId(callingUid); 4492 final int appId = UserHandle.getAppId(uid); 4493 final Object obj = mSettings.getSettingBase(appId); 4494 if (obj instanceof SharedUserSetting) { 4495 final SharedUserSetting sus = (SharedUserSetting) obj; 4496 if (shouldFilterApplicationIncludingUninstalled(sus, callingUid, callingUserId)) { 4497 return 0; 4498 } 4499 return sus.getFlags(); 4500 } else if (obj instanceof PackageSetting) { 4501 final PackageSetting ps = (PackageSetting) obj; 4502 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 4503 return 0; 4504 } 4505 return ps.getFlags(); 4506 } 4507 return 0; 4508 } 4509 4510 @Override getPrivateFlagsForUid(int uid)4511 public int getPrivateFlagsForUid(int uid) { 4512 final int callingUid = Binder.getCallingUid(); 4513 if (getInstantAppPackageName(callingUid) != null) { 4514 return 0; 4515 } 4516 if (Process.isSdkSandboxUid(uid)) { 4517 uid = getBaseSdkSandboxUid(); 4518 } 4519 final int callingUserId = UserHandle.getUserId(callingUid); 4520 final int appId = UserHandle.getAppId(uid); 4521 final Object obj = mSettings.getSettingBase(appId); 4522 if (obj instanceof SharedUserSetting) { 4523 final SharedUserSetting sus = (SharedUserSetting) obj; 4524 if (shouldFilterApplicationIncludingUninstalled(sus, callingUid, callingUserId)) { 4525 return 0; 4526 } 4527 return sus.getPrivateFlags(); 4528 } else if (obj instanceof PackageSetting) { 4529 final PackageSetting ps = (PackageSetting) obj; 4530 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 4531 return 0; 4532 } 4533 return ps.getPrivateFlags(); 4534 } 4535 return 0; 4536 } 4537 4538 @Override isUidPrivileged(int uid)4539 public boolean isUidPrivileged(int uid) { 4540 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4541 return false; 4542 } 4543 if (Process.isSdkSandboxUid(uid)) { 4544 uid = getBaseSdkSandboxUid(); 4545 } 4546 final int appId = UserHandle.getAppId(uid); 4547 final Object obj = mSettings.getSettingBase(appId); 4548 if (obj instanceof SharedUserSetting) { 4549 final SharedUserSetting sus = (SharedUserSetting) obj; 4550 final ArraySet<PackageStateInternal> packageStates = 4551 (ArraySet<PackageStateInternal>) sus.getPackageStates(); 4552 final int numPackages = packageStates.size(); 4553 for (int index = 0; index < numPackages; index++) { 4554 final PackageStateInternal ps = packageStates.valueAt(index); 4555 if (ps.isPrivileged()) { 4556 return true; 4557 } 4558 } 4559 } else if (obj instanceof PackageSetting) { 4560 final PackageSetting ps = (PackageSetting) obj; 4561 return ps.isPrivileged(); 4562 } 4563 return false; 4564 } 4565 4566 // NOTE: Can't remove due to unsupported app usage 4567 @NonNull 4568 @Override getAppOpPermissionPackages(@onNull String permissionName, int userId)4569 public String[] getAppOpPermissionPackages(@NonNull String permissionName, int userId) { 4570 final int callingUid = Binder.getCallingUid(); 4571 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4572 false /* checkShell */, "getAppOpPermissionPackages"); 4573 if (permissionName == null || getInstantAppPackageName(callingUid) != null 4574 || !mUserManager.exists(userId)) { 4575 return EmptyArray.STRING; 4576 } 4577 4578 final ArraySet<String> packageNames = new ArraySet( 4579 mPermissionManager.getAppOpPermissionPackages(permissionName)); 4580 for (int i = packageNames.size() - 1; i >= 0; i--) { 4581 final String packageName = packageNames.valueAt(i); 4582 if (!shouldFilterApplicationIncludingUninstalled( 4583 mSettings.getPackage(packageName), callingUid, userId)) { 4584 continue; 4585 } 4586 packageNames.removeAt(i); 4587 } 4588 return packageNames.toArray(new String[packageNames.size()]); 4589 } 4590 4591 @NonNull 4592 @Override getPackagesHoldingPermissions( @onNull String[] permissions, @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId)4593 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 4594 @NonNull String[] permissions, @PackageManager.PackageInfoFlagsBits long flags, 4595 @UserIdInt int userId) { 4596 if (!mUserManager.exists(userId)) return ParceledListSlice.emptyList(); 4597 flags = updateFlagsForPackage(flags, userId); 4598 enforceCrossUserPermission(Binder.getCallingUid(), userId, true /* requireFullPermission */, 4599 false /* checkShell */, "get packages holding permissions"); 4600 final boolean listUninstalled = 4601 (flags & (MATCH_KNOWN_PACKAGES | MATCH_ARCHIVED_PACKAGES)) != 0; 4602 4603 ArrayList<PackageInfo> list = new ArrayList<>(); 4604 boolean[] tmpBools = new boolean[permissions.length]; 4605 for (PackageStateInternal ps : getPackageStates().values()) { 4606 if (ps.getPkg() == null && !listUninstalled) { 4607 continue; 4608 } 4609 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 4610 } 4611 4612 return new ParceledListSlice<>(list); 4613 } 4614 addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageStateInternal ps, String[] permissions, boolean[] tmp, @PackageManager.PackageInfoFlagsBits long flags, int userId)4615 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageStateInternal ps, 4616 String[] permissions, boolean[] tmp, @PackageManager.PackageInfoFlagsBits long flags, 4617 int userId) { 4618 int numMatch = 0; 4619 for (int i=0; i<permissions.length; i++) { 4620 final String permission = permissions[i]; 4621 if (mPermissionManager.checkPermission(ps.getPackageName(), permission, 4622 VirtualDeviceManager.PERSISTENT_DEVICE_ID_DEFAULT, userId) 4623 == PERMISSION_GRANTED) { 4624 tmp[i] = true; 4625 numMatch++; 4626 } else { 4627 tmp[i] = false; 4628 } 4629 } 4630 if (numMatch == 0) { 4631 return; 4632 } 4633 final PackageInfo pi = generatePackageInfo(ps, flags, userId); 4634 4635 // The above might return null in cases of uninstalled apps or install-state 4636 // skew across users/profiles. 4637 if (pi != null) { 4638 if ((flags & PackageManager.GET_PERMISSIONS) == 0) { 4639 if (numMatch == permissions.length) { 4640 pi.requestedPermissions = permissions; 4641 } else { 4642 pi.requestedPermissions = new String[numMatch]; 4643 numMatch = 0; 4644 for (int i=0; i<permissions.length; i++) { 4645 if (tmp[i]) { 4646 pi.requestedPermissions[numMatch] = permissions[i]; 4647 numMatch++; 4648 } 4649 } 4650 } 4651 } 4652 list.add(pi); 4653 } 4654 } 4655 4656 @NonNull 4657 @Override getInstalledApplications( @ackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId, int callingUid, boolean forceAllowCrossUser)4658 public List<ApplicationInfo> getInstalledApplications( 4659 @PackageManager.ApplicationInfoFlagsBits long flags, @UserIdInt int userId, 4660 int callingUid, boolean forceAllowCrossUser) { 4661 if (getInstantAppPackageName(callingUid) != null) { 4662 return Collections.emptyList(); 4663 } 4664 if (!mUserManager.exists(userId)) return Collections.emptyList(); 4665 flags = updateFlagsForApplication(flags, userId); 4666 final boolean listUninstalled = (flags & MATCH_KNOWN_PACKAGES) != 0; 4667 final boolean listApex = (flags & MATCH_APEX) != 0; 4668 final boolean listArchivedOnly = !listUninstalled && (flags & MATCH_ARCHIVED_PACKAGES) != 0; 4669 4670 if (!forceAllowCrossUser) { 4671 enforceCrossUserPermission( 4672 callingUid, 4673 userId, 4674 false /* requireFullPermission */, 4675 false /* checkShell */, 4676 "get installed application info"); 4677 } 4678 4679 ArrayList<ApplicationInfo> list; 4680 final ArrayMap<String, ? extends PackageStateInternal> packageStates = 4681 getPackageStates(); 4682 if (listUninstalled || listArchivedOnly) { 4683 list = new ArrayList<>(packageStates.size()); 4684 for (PackageStateInternal ps : packageStates.values()) { 4685 ApplicationInfo ai; 4686 long effectiveFlags = flags; 4687 if (ps.isSystem()) { 4688 effectiveFlags |= PackageManager.MATCH_ANY_USER; 4689 } 4690 if (ps.getPkg() != null) { 4691 if (!listApex && ps.getPkg().isApex()) { 4692 continue; 4693 } 4694 PackageUserStateInternal userState = ps.getUserStateOrDefault(userId); 4695 if (listArchivedOnly && !userState.isInstalled() 4696 && userState.getArchiveState() == null) { 4697 continue; 4698 } 4699 if (filterSharedLibPackage(ps, callingUid, userId, flags)) { 4700 continue; 4701 } 4702 if (shouldFilterApplication(ps, callingUid, userId)) { 4703 continue; 4704 } 4705 ai = PackageInfoUtils.generateApplicationInfo(ps.getPkg(), effectiveFlags, 4706 ps.getUserStateOrDefault(userId), userId, ps); 4707 if (ai != null) { 4708 ai.packageName = resolveExternalPackageName(ps.getPkg()); 4709 } 4710 } else { 4711 // Shared lib filtering done in generateApplicationInfoFromSettingsLPw 4712 // and already converts to externally visible package name 4713 ai = generateApplicationInfoFromSettings(ps.getPackageName(), 4714 effectiveFlags, callingUid, userId); 4715 } 4716 if (ai != null) { 4717 list.add(ai); 4718 } 4719 } 4720 } else { 4721 list = new ArrayList<>(mPackages.size()); 4722 for (PackageStateInternal packageState : packageStates.values()) { 4723 final AndroidPackage pkg = packageState.getPkg(); 4724 if (pkg == null) { 4725 continue; 4726 } 4727 if (!listApex && pkg.isApex()) { 4728 continue; 4729 } 4730 if (filterSharedLibPackage(packageState, Binder.getCallingUid(), userId, flags)) { 4731 continue; 4732 } 4733 if (shouldFilterApplication(packageState, callingUid, userId)) { 4734 continue; 4735 } 4736 ApplicationInfo ai = PackageInfoUtils.generateApplicationInfo(pkg, flags, 4737 packageState.getUserStateOrDefault(userId), userId, packageState); 4738 if (ai != null) { 4739 ai.packageName = resolveExternalPackageName(pkg); 4740 list.add(ai); 4741 } 4742 } 4743 } 4744 4745 return list; 4746 } 4747 4748 @Nullable 4749 @Override resolveContentProvider(@onNull String name, @PackageManager.ResolveInfoFlagsBits long flags, @UserIdInt int userId, int callingUid)4750 public ProviderInfo resolveContentProvider(@NonNull String name, 4751 @PackageManager.ResolveInfoFlagsBits long flags, @UserIdInt int userId, 4752 int callingUid) { 4753 if (!mUserManager.exists(userId)) return null; 4754 flags = updateFlagsForComponent(flags, userId); 4755 final ProviderInfo providerInfo = mComponentResolver.queryProvider(this, name, flags, 4756 userId); 4757 boolean checkedGrants = false; 4758 if (providerInfo != null) { 4759 // Looking for cross-user grants before enforcing the typical cross-users permissions 4760 if (userId != UserHandle.getUserId(callingUid)) { 4761 final UriGrantsManagerInternal ugmInternal = 4762 mInjector.getLocalService(UriGrantsManagerInternal.class); 4763 checkedGrants = 4764 ugmInternal.checkAuthorityGrants(callingUid, providerInfo, userId, true); 4765 } 4766 } 4767 if (!checkedGrants) { 4768 boolean enforceCrossUser = true; 4769 4770 if (isAuthorityRedirectedForCloneProfile(name)) { 4771 final UserManagerInternal umInternal = mInjector.getUserManagerInternal(); 4772 4773 UserInfo userInfo = umInternal.getUserInfo(UserHandle.getUserId(callingUid)); 4774 if (userInfo != null && userInfo.isCloneProfile() 4775 && userInfo.profileGroupId == userId) { 4776 enforceCrossUser = false; 4777 } 4778 } 4779 4780 if (enforceCrossUser) { 4781 enforceCrossUserPermission(callingUid, userId, false, false, 4782 "resolveContentProvider"); 4783 } 4784 } 4785 4786 if (providerInfo == null) { 4787 return null; 4788 } 4789 final PackageStateInternal packageState = getPackageStateInternal( 4790 providerInfo.packageName); 4791 if (!PackageStateUtils.isEnabledAndMatches(packageState, providerInfo, flags, userId)) { 4792 return null; 4793 } 4794 final ComponentName component = 4795 new ComponentName(providerInfo.packageName, providerInfo.name); 4796 if (shouldFilterApplication(packageState, callingUid, component, TYPE_PROVIDER, userId)) { 4797 return null; 4798 } 4799 return providerInfo; 4800 } 4801 4802 @Nullable 4803 @Override getGrantImplicitAccessProviderInfo(int recipientUid, @NonNull String visibleAuthority)4804 public ProviderInfo getGrantImplicitAccessProviderInfo(int recipientUid, 4805 @NonNull String visibleAuthority) { 4806 final int callingUid = Binder.getCallingUid(); 4807 final int recipientUserId = UserHandle.getUserId(recipientUid); 4808 // This API is exposed temporarily to only the contacts provider. (b/158688602) 4809 ProviderInfo contactsProvider = resolveContentProvider( 4810 ContactsContract.AUTHORITY, 0, UserHandle.getUserId(callingUid), callingUid); 4811 if (contactsProvider == null || contactsProvider.applicationInfo == null 4812 || !UserHandle.isSameApp(contactsProvider.applicationInfo.uid, callingUid)) { 4813 throw new SecurityException( 4814 callingUid + " is not allow to call grantImplicitAccess"); 4815 } 4816 final long token = Binder.clearCallingIdentity(); 4817 try { 4818 return resolveContentProvider(visibleAuthority, 0 /*flags*/, recipientUserId, 4819 callingUid); 4820 } finally { 4821 Binder.restoreCallingIdentity(token); 4822 } 4823 } 4824 4825 @Deprecated querySyncProviders(boolean safeMode, @NonNull List<String> outNames, @NonNull List<ProviderInfo> outInfo)4826 public void querySyncProviders(boolean safeMode, @NonNull List<String> outNames, 4827 @NonNull List<ProviderInfo> outInfo) { 4828 if (getInstantAppPackageName(Binder.getCallingUid()) != null) { 4829 return; 4830 } 4831 final List<String> names = new ArrayList<>(); 4832 final List<ProviderInfo> infos = new ArrayList<>(); 4833 final int callingUserId = UserHandle.getCallingUserId(); 4834 mComponentResolver.querySyncProviders(this, names, infos, safeMode, callingUserId); 4835 for (int i = infos.size() - 1; i >= 0; i--) { 4836 final ProviderInfo providerInfo = infos.get(i); 4837 final PackageStateInternal ps = mSettings.getPackage(providerInfo.packageName); 4838 final ComponentName component = 4839 new ComponentName(providerInfo.packageName, providerInfo.name); 4840 if (!shouldFilterApplication(ps, Binder.getCallingUid(), component, 4841 TYPE_PROVIDER, callingUserId)) { 4842 continue; 4843 } 4844 infos.remove(i); 4845 names.remove(i); 4846 } 4847 if (!names.isEmpty()) { 4848 outNames.addAll(names); 4849 } 4850 if (!infos.isEmpty()) { 4851 outInfo.addAll(infos); 4852 } 4853 } 4854 4855 @NonNull 4856 @Override queryContentProviders(@ullable String processName, int uid, @PackageManager.ComponentInfoFlagsBits long flags, @Nullable String metaDataKey)4857 public ParceledListSlice<ProviderInfo> queryContentProviders(@Nullable String processName, 4858 int uid, @PackageManager.ComponentInfoFlagsBits long flags, 4859 @Nullable String metaDataKey) { 4860 final int callingUid = Binder.getCallingUid(); 4861 final int userId = processName != null ? UserHandle.getUserId(uid) 4862 : UserHandle.getCallingUserId(); 4863 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4864 false /* checkShell */, "queryContentProviders"); 4865 if (!mUserManager.exists(userId)) return ParceledListSlice.emptyList(); 4866 flags = updateFlagsForComponent(flags, userId); 4867 ArrayList<ProviderInfo> finalList = null; 4868 final List<ProviderInfo> matchList = mComponentResolver.queryProviders(this, processName, 4869 metaDataKey, uid, flags, userId); 4870 final int listSize = (matchList == null ? 0 : matchList.size()); 4871 for (int i = 0; i < listSize; i++) { 4872 final ProviderInfo providerInfo = matchList.get(i); 4873 if (!PackageStateUtils.isEnabledAndMatches( 4874 mSettings.getPackage(providerInfo.packageName), providerInfo, 4875 flags, userId)) { 4876 continue; 4877 } 4878 final PackageStateInternal ps = mSettings.getPackage(providerInfo.packageName); 4879 final ComponentName component = 4880 new ComponentName(providerInfo.packageName, providerInfo.name); 4881 if (shouldFilterApplication( 4882 ps, callingUid, component, TYPE_PROVIDER, userId)) { 4883 continue; 4884 } 4885 if (finalList == null) { 4886 finalList = new ArrayList<>(listSize - i); 4887 } 4888 finalList.add(providerInfo); 4889 } 4890 4891 if (finalList != null) { 4892 finalList.sort(sProviderInitOrderSorter); 4893 return new ParceledListSlice<>(finalList); 4894 } 4895 4896 return ParceledListSlice.emptyList(); 4897 } 4898 4899 @Nullable 4900 @Override getInstrumentationInfoAsUser(@onNull ComponentName component, int flags, int userId)4901 public InstrumentationInfo getInstrumentationInfoAsUser(@NonNull ComponentName component, 4902 int flags, int userId) { 4903 final int callingUid = Binder.getCallingUid(); 4904 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4905 false /* checkShell */, "getInstrumentationInfoAsUser"); 4906 if (!mUserManager.exists(userId)) return null; 4907 String packageName = component.getPackageName(); 4908 final PackageStateInternal ps = mSettings.getPackage(packageName); 4909 AndroidPackage pkg = mPackages.get(packageName); 4910 if (ps == null || pkg == null) return null; 4911 if (shouldFilterApplication( 4912 ps, callingUid, component, TYPE_UNKNOWN, userId)) { 4913 return null; 4914 } 4915 final ParsedInstrumentation i = mInstrumentation.get(component); 4916 final PackageUserStateInternal state = ps.getUserStateOrDefault(userId); 4917 return PackageInfoUtils.generateInstrumentationInfo(i, pkg, flags, state, userId, ps); 4918 } 4919 4920 @NonNull 4921 @Override queryInstrumentationAsUser( @onNull String targetPackage, int flags, int userId)4922 public ParceledListSlice<InstrumentationInfo> queryInstrumentationAsUser( 4923 @NonNull String targetPackage, int flags, int userId) { 4924 final int callingUid = Binder.getCallingUid(); 4925 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 4926 false /* checkShell */, "queryInstrumentationAsUser"); 4927 if (!mUserManager.exists(userId)) return ParceledListSlice.emptyList(); 4928 ArrayList<InstrumentationInfo> finalList = new ArrayList<>(); 4929 4930 final int numInstrumentations = mInstrumentation.size(); 4931 for (int index = 0; index < numInstrumentations; index++) { 4932 final ParsedInstrumentation p = mInstrumentation.valueAt(index); 4933 if (targetPackage == null 4934 || targetPackage.equals(p.getTargetPackage())) { 4935 String packageName = p.getPackageName(); 4936 AndroidPackage pkg = mPackages.get(packageName); 4937 PackageStateInternal pkgSetting = getPackageStateInternal(packageName); 4938 if (pkg == null || pkgSetting == null 4939 || shouldFilterApplication(pkgSetting, callingUid, userId)) { 4940 continue; 4941 } 4942 final PackageUserStateInternal state = pkgSetting.getUserStateOrDefault(userId); 4943 InstrumentationInfo ii = PackageInfoUtils.generateInstrumentationInfo(p, 4944 pkg, flags, state, userId, pkgSetting); 4945 if (ii != null) { 4946 finalList.add(ii); 4947 } 4948 } 4949 } 4950 4951 return new ParceledListSlice<>(finalList); 4952 } 4953 4954 @NonNull 4955 @Override findSharedNonSystemLibraries( @onNull PackageStateInternal pkgSetting)4956 public List<PackageStateInternal> findSharedNonSystemLibraries( 4957 @NonNull PackageStateInternal pkgSetting) { 4958 List<SharedLibraryInfo> deps = SharedLibraryUtils.findSharedLibraries(pkgSetting); 4959 if (!deps.isEmpty()) { 4960 List<PackageStateInternal> retValue = new ArrayList<>(); 4961 for (SharedLibraryInfo info : deps) { 4962 PackageStateInternal depPackageSetting = 4963 getPackageStateInternal(info.getPackageName()); 4964 if (depPackageSetting != null && depPackageSetting.getPkg() != null) { 4965 retValue.add(depPackageSetting); 4966 } 4967 } 4968 return retValue; 4969 } else { 4970 return Collections.emptyList(); 4971 } 4972 } 4973 4974 /** 4975 * Returns true if application is not found or there was an error. Otherwise it returns 4976 * the hidden state of the package for the given user. 4977 */ 4978 @Override getApplicationHiddenSettingAsUser(@onNull String packageName, @UserIdInt int userId)4979 public boolean getApplicationHiddenSettingAsUser(@NonNull String packageName, 4980 @UserIdInt int userId) { 4981 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 4982 final int callingUid = Binder.getCallingUid(); 4983 enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 4984 false /* checkShell */, "getApplicationHidden for user " + userId); 4985 final long callingId = Binder.clearCallingIdentity(); 4986 try { 4987 PackageStateInternal ps = mSettings.getPackage(packageName); 4988 if (ps == null) { 4989 return true; 4990 } 4991 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 4992 return true; 4993 } 4994 return ps.getUserStateOrDefault(userId).isHidden(); 4995 } finally { 4996 Binder.restoreCallingIdentity(callingId); 4997 } 4998 } 4999 getUserStateOrDefaultForUser(@onNull String packageName, int userId)5000 private PackageUserStateInternal getUserStateOrDefaultForUser(@NonNull String packageName, 5001 int userId) throws PackageManager.NameNotFoundException { 5002 final int callingUid = Binder.getCallingUid(); 5003 enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 5004 false /* checkShell */, "when asking about packages for user " + userId); 5005 final PackageStateInternal ps = mSettings.getPackage(packageName); 5006 if (ps == null || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5007 throw new PackageManager.NameNotFoundException(packageName); 5008 } 5009 return ps.getUserStateOrDefault(userId); 5010 } 5011 5012 @Override isPackageSuspendedForUser(@onNull String packageName, int userId)5013 public boolean isPackageSuspendedForUser(@NonNull String packageName, int userId) 5014 throws PackageManager.NameNotFoundException { 5015 return getUserStateOrDefaultForUser(packageName, userId).isSuspended(); 5016 } 5017 5018 @Override isPackageQuarantinedForUser(@onNull String packageName, @UserIdInt int userId)5019 public boolean isPackageQuarantinedForUser(@NonNull String packageName, @UserIdInt int userId) 5020 throws PackageManager.NameNotFoundException { 5021 return getUserStateOrDefaultForUser(packageName, userId).isQuarantined(); 5022 } 5023 5024 @Override isPackageStoppedForUser(@onNull String packageName, @UserIdInt int userId)5025 public boolean isPackageStoppedForUser(@NonNull String packageName, @UserIdInt int userId) 5026 throws PackageManager.NameNotFoundException { 5027 return getUserStateOrDefaultForUser(packageName, userId).isStopped(); 5028 } 5029 5030 @Override isSuspendingAnyPackages(@onNull String suspendingPackage, @UserIdInt int suspendingUserId, int targetUserId)5031 public boolean isSuspendingAnyPackages(@NonNull String suspendingPackage, 5032 @UserIdInt int suspendingUserId, int targetUserId) { 5033 final UserPackage suspender = UserPackage.of(suspendingUserId, suspendingPackage); 5034 for (final PackageStateInternal packageState : getPackageStates().values()) { 5035 final PackageUserStateInternal state = 5036 packageState.getUserStateOrDefault(targetUserId); 5037 if (state.getSuspendParams() != null 5038 && state.getSuspendParams().containsKey(suspender)) { 5039 return true; 5040 } 5041 } 5042 return false; 5043 } 5044 5045 @NonNull 5046 @Override getAllIntentFilters(@onNull String packageName)5047 public ParceledListSlice<IntentFilter> getAllIntentFilters(@NonNull String packageName) { 5048 if (TextUtils.isEmpty(packageName)) { 5049 return ParceledListSlice.emptyList(); 5050 } 5051 final int callingUid = Binder.getCallingUid(); 5052 final int callingUserId = UserHandle.getUserId(callingUid); 5053 final PackageStateInternal ps = getPackageStateInternal(packageName); 5054 final AndroidPackage pkg = ps == null ? null : ps.getPkg(); 5055 if (pkg == null || ArrayUtils.isEmpty(pkg.getActivities())) { 5056 return ParceledListSlice.emptyList(); 5057 } 5058 if (shouldFilterApplicationIncludingUninstalled(ps, callingUid, callingUserId)) { 5059 return ParceledListSlice.emptyList(); 5060 } 5061 final int count = ArrayUtils.size(pkg.getActivities()); 5062 ArrayList<IntentFilter> result = new ArrayList<>(); 5063 for (int n=0; n<count; n++) { 5064 ParsedActivity activity = pkg.getActivities().get(n); 5065 List<ParsedIntentInfo> intentInfos = activity.getIntents(); 5066 for (int index = 0; index < intentInfos.size(); index++) { 5067 result.add(new IntentFilter(intentInfos.get(index).getIntentFilter())); 5068 } 5069 } 5070 return new ParceledListSlice<>(result); 5071 } 5072 5073 @Override getBlockUninstallForUser(@onNull String packageName, @UserIdInt int userId)5074 public boolean getBlockUninstallForUser(@NonNull String packageName, @UserIdInt int userId) { 5075 final PackageStateInternal ps = mSettings.getPackage(packageName); 5076 final int callingUid = Binder.getCallingUid(); 5077 if (ps == null || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5078 return false; 5079 } 5080 return mSettings.getBlockUninstall(userId, packageName); 5081 } 5082 5083 @Nullable 5084 @Override getInstallerPackageName(@onNull String packageName, @UserIdInt int userId)5085 public String getInstallerPackageName(@NonNull String packageName, @UserIdInt int userId) { 5086 final int callingUid = Binder.getCallingUid(); 5087 final InstallSource installSource = getInstallSource(packageName, callingUid, userId); 5088 if (installSource == null) { 5089 throw new IllegalArgumentException("Unknown package: " + packageName); 5090 } 5091 String installerPackageName = installSource.mInstallerPackageName; 5092 if (installerPackageName != null) { 5093 final PackageStateInternal ps = mSettings.getPackage(installerPackageName); 5094 if (ps == null || shouldFilterApplicationIncludingUninstalledNotArchived(ps, callingUid, 5095 UserHandle.getUserId(callingUid))) { 5096 installerPackageName = null; 5097 } 5098 } 5099 return installerPackageName; 5100 } 5101 5102 @Nullable getInstallSource(@onNull String packageName, int callingUid, int userId)5103 private InstallSource getInstallSource(@NonNull String packageName, int callingUid, 5104 int userId) { 5105 final PackageStateInternal ps = mSettings.getPackage(packageName); 5106 5107 // Installer info for Apex is not stored in PackageManager 5108 if (isApexPackage(packageName)) { 5109 return InstallSource.EMPTY; 5110 } 5111 5112 if (ps == null || shouldFilterApplicationIncludingUninstalledNotArchived(ps, callingUid, 5113 userId)) { 5114 return null; 5115 } 5116 5117 return ps.getInstallSource(); 5118 } 5119 5120 @Override 5121 @Nullable getInstallSourceInfo(@onNull String packageName, @UserIdInt int userId)5122 public InstallSourceInfo getInstallSourceInfo(@NonNull String packageName, 5123 @UserIdInt int userId) { 5124 final int callingUid = Binder.getCallingUid(); 5125 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 5126 false /* checkShell */, "getInstallSourceInfo"); 5127 5128 String installerPackageName; 5129 String initiatingPackageName; 5130 String originatingPackageName; 5131 String updateOwnerPackageName; 5132 5133 final InstallSource installSource = getInstallSource(packageName, callingUid, userId); 5134 if (installSource == null) { 5135 return null; 5136 } 5137 5138 installerPackageName = installSource.mInstallerPackageName; 5139 if (installerPackageName != null) { 5140 final PackageStateInternal ps = mSettings.getPackage(installerPackageName); 5141 if (ps == null 5142 || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5143 installerPackageName = null; 5144 } 5145 } 5146 5147 updateOwnerPackageName = installSource.mUpdateOwnerPackageName; 5148 if (updateOwnerPackageName != null) { 5149 final PackageStateInternal ps = mSettings.getPackage(updateOwnerPackageName); 5150 final boolean isCallerSystemOrUpdateOwner = callingUid == Process.SYSTEM_UID 5151 || isCallerSameApp(updateOwnerPackageName, callingUid); 5152 // Except for package visibility filtering, we also hide update owner if the installer 5153 // is in the managed user or profile. As we don't enforce the update ownership for the 5154 // managed user and profile, knowing there's an update owner is meaningless in that 5155 // user unless the installer is the owner. 5156 if (ps == null 5157 || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId) 5158 || (!isCallerSystemOrUpdateOwner && isCallerFromManagedUserOrProfile(userId))) { 5159 updateOwnerPackageName = null; 5160 } 5161 } 5162 5163 if (installSource.mIsInitiatingPackageUninstalled) { 5164 // We can't check visibility in the usual way, since the initiating package is no 5165 // longer present. So we apply simpler rules to whether to expose the info: 5166 // 1. Instant apps can't see it. 5167 // 2. Otherwise only the installed app itself can see it. 5168 final boolean isInstantApp = getInstantAppPackageName(callingUid) != null; 5169 if (!isInstantApp && isCallerSameApp(packageName, callingUid)) { 5170 initiatingPackageName = installSource.mInitiatingPackageName; 5171 } else { 5172 initiatingPackageName = null; 5173 } 5174 } else { 5175 if (Objects.equals(installSource.mInitiatingPackageName, 5176 installSource.mInstallerPackageName)) { 5177 // The installer and initiator will often be the same, and when they are 5178 // we can skip doing the same check again. 5179 initiatingPackageName = installerPackageName; 5180 } else { 5181 initiatingPackageName = installSource.mInitiatingPackageName; 5182 final PackageStateInternal ps = mSettings.getPackage(initiatingPackageName); 5183 if (ps == null 5184 || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5185 initiatingPackageName = null; 5186 } 5187 } 5188 } 5189 5190 originatingPackageName = installSource.mOriginatingPackageName; 5191 if (originatingPackageName != null) { 5192 final PackageStateInternal ps = mSettings.getPackage(originatingPackageName); 5193 if (ps == null 5194 || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5195 originatingPackageName = null; 5196 } 5197 } 5198 5199 // Remaining work can safely be done outside the lock. (Note that installSource is 5200 // immutable so it's ok to carry on reading from it.) 5201 5202 if (originatingPackageName != null && mContext.checkCallingOrSelfPermission( 5203 Manifest.permission.INSTALL_PACKAGES) != PackageManager.PERMISSION_GRANTED) { 5204 originatingPackageName = null; 5205 } 5206 5207 // If you can see the initiatingPackageName, and we have valid signing info for it, 5208 // then we let you see that too. 5209 final SigningInfo initiatingPackageSigningInfo; 5210 final PackageSignatures signatures = installSource.mInitiatingPackageSignatures; 5211 if (initiatingPackageName != null && signatures != null 5212 && signatures.mSigningDetails != SigningDetails.UNKNOWN) { 5213 initiatingPackageSigningInfo = new SigningInfo(signatures.mSigningDetails); 5214 } else { 5215 initiatingPackageSigningInfo = null; 5216 } 5217 5218 return new InstallSourceInfo(initiatingPackageName, initiatingPackageSigningInfo, 5219 originatingPackageName, installerPackageName, updateOwnerPackageName, 5220 installSource.mPackageSource); 5221 } 5222 5223 @PackageManager.EnabledState 5224 @Override getApplicationEnabledSetting(@onNull String packageName, @UserIdInt int userId)5225 public int getApplicationEnabledSetting(@NonNull String packageName, @UserIdInt int userId) { 5226 if (!mUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 5227 int callingUid = Binder.getCallingUid(); 5228 enforceCrossUserPermission(callingUid, userId, false /* requireFullPermission */, 5229 false /* checkShell */, "get enabled"); 5230 try { 5231 if (shouldFilterApplicationIncludingUninstalled( 5232 mSettings.getPackage(packageName), callingUid, userId)) { 5233 throw new PackageManager.NameNotFoundException(packageName); 5234 } 5235 return mSettings.getApplicationEnabledSetting(packageName, userId); 5236 } catch (PackageManager.NameNotFoundException e) { 5237 throw new IllegalArgumentException("Unknown package: " + packageName); 5238 } 5239 } 5240 5241 @PackageManager.EnabledState 5242 @Override getComponentEnabledSetting(@onNull ComponentName component, int callingUid, @UserIdInt int userId)5243 public int getComponentEnabledSetting(@NonNull ComponentName component, int callingUid, 5244 @UserIdInt int userId) { 5245 enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 5246 false /*checkShell*/, "getComponentEnabled"); 5247 return getComponentEnabledSettingInternal(component, callingUid, userId); 5248 } 5249 5250 @PackageManager.EnabledState 5251 @Override getComponentEnabledSettingInternal(@onNull ComponentName component, int callingUid, @UserIdInt int userId)5252 public int getComponentEnabledSettingInternal(@NonNull ComponentName component, int callingUid, 5253 @UserIdInt int userId) { 5254 if (component == null) return COMPONENT_ENABLED_STATE_DEFAULT; 5255 if (!mUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 5256 5257 try { 5258 if (shouldFilterApplication( 5259 mSettings.getPackage(component.getPackageName()), callingUid, 5260 component, TYPE_UNKNOWN, userId, true /* filterUninstall */)) { 5261 throw new PackageManager.NameNotFoundException(component.getPackageName()); 5262 } 5263 return mSettings.getComponentEnabledSetting(component, userId); 5264 } catch (PackageManager.NameNotFoundException e) { 5265 throw new IllegalArgumentException("Unknown component: " + component); 5266 } 5267 } 5268 5269 @Override isComponentEffectivelyEnabled(@onNull ComponentInfo componentInfo, @NonNull UserHandle userHandle)5270 public boolean isComponentEffectivelyEnabled(@NonNull ComponentInfo componentInfo, 5271 @NonNull UserHandle userHandle) { 5272 try { 5273 String packageName = componentInfo.packageName; 5274 int userId = userHandle.getIdentifier(); 5275 int appEnabledSetting = 5276 mSettings.getApplicationEnabledSetting(packageName, userId); 5277 if (appEnabledSetting == COMPONENT_ENABLED_STATE_DEFAULT) { 5278 if (!componentInfo.applicationInfo.enabled) { 5279 return false; 5280 } 5281 } else if (appEnabledSetting != COMPONENT_ENABLED_STATE_ENABLED) { 5282 return false; 5283 } 5284 5285 int componentEnabledSetting = mSettings.getComponentEnabledSetting( 5286 componentInfo.getComponentName(), userId); 5287 if (componentEnabledSetting == COMPONENT_ENABLED_STATE_DEFAULT) { 5288 return componentInfo.isEnabled(); 5289 } else return componentEnabledSetting == COMPONENT_ENABLED_STATE_ENABLED; 5290 } catch (PackageManager.NameNotFoundException ignored) { 5291 return false; 5292 } 5293 } 5294 5295 @Override isApplicationEffectivelyEnabled(@onNull String packageName, @NonNull UserHandle userHandle)5296 public boolean isApplicationEffectivelyEnabled(@NonNull String packageName, 5297 @NonNull UserHandle userHandle) { 5298 try { 5299 int appEnabledSetting = mSettings.getApplicationEnabledSetting(packageName, 5300 userHandle.getIdentifier()); 5301 if (appEnabledSetting == COMPONENT_ENABLED_STATE_DEFAULT) { 5302 final AndroidPackage pkg = getPackage(packageName); 5303 if (pkg == null) { 5304 // Should not happen because getApplicationEnabledSetting would have thrown 5305 return false; 5306 } 5307 return pkg.isEnabled(); 5308 } else { 5309 return appEnabledSetting == COMPONENT_ENABLED_STATE_ENABLED; 5310 } 5311 } catch (PackageManager.NameNotFoundException ignored) { 5312 return false; 5313 } 5314 } 5315 5316 @Nullable 5317 @Override getKeySetByAlias(@onNull String packageName, @NonNull String alias)5318 public KeySet getKeySetByAlias(@NonNull String packageName, @NonNull String alias) { 5319 if (packageName == null || alias == null) { 5320 return null; 5321 } 5322 final int callingUid = Binder.getCallingUid(); 5323 final int callingUserId = UserHandle.getUserId(callingUid); 5324 final AndroidPackage pkg = mPackages.get(packageName); 5325 if (pkg == null || shouldFilterApplicationIncludingUninstalled( 5326 getPackageStateInternal(pkg.getPackageName()), callingUid, callingUserId)) { 5327 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 5328 throw new IllegalArgumentException("Unknown package: " + packageName); 5329 } 5330 final KeySetManagerService ksms = mSettings.getKeySetManagerService(); 5331 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 5332 } 5333 5334 @Nullable 5335 @Override getSigningKeySet(@onNull String packageName)5336 public KeySet getSigningKeySet(@NonNull String packageName) { 5337 if (packageName == null) { 5338 return null; 5339 } 5340 final int callingUid = Binder.getCallingUid(); 5341 final int callingUserId = UserHandle.getUserId(callingUid); 5342 final AndroidPackage pkg = mPackages.get(packageName); 5343 if (pkg == null || shouldFilterApplicationIncludingUninstalled( 5344 getPackageStateInternal(pkg.getPackageName()), callingUid, callingUserId)) { 5345 Slog.w(TAG, "KeySet requested for unknown package: " + packageName 5346 + ", uid:" + callingUid); 5347 throw new IllegalArgumentException("Unknown package: " + packageName); 5348 } 5349 if (pkg.getUid() != callingUid 5350 && Process.SYSTEM_UID != callingUid) { 5351 throw new SecurityException("May not access signing KeySet of other apps."); 5352 } 5353 final KeySetManagerService ksms = mSettings.getKeySetManagerService(); 5354 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 5355 } 5356 5357 @Override isPackageSignedByKeySet(@onNull String packageName, @NonNull KeySet ks)5358 public boolean isPackageSignedByKeySet(@NonNull String packageName, @NonNull KeySet ks) { 5359 final int callingUid = Binder.getCallingUid(); 5360 if (getInstantAppPackageName(callingUid) != null) { 5361 return false; 5362 } 5363 if (packageName == null || ks == null) { 5364 return false; 5365 } 5366 final AndroidPackage pkg = mPackages.get(packageName); 5367 final int callingUserId = UserHandle.getUserId(callingUid); 5368 if (pkg == null 5369 || shouldFilterApplicationIncludingUninstalled( 5370 getPackageStateInternal(pkg.getPackageName()), callingUid, callingUserId)) { 5371 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 5372 throw new IllegalArgumentException("Unknown package: " + packageName); 5373 } 5374 IBinder ksh = ks.getToken(); 5375 if (ksh instanceof KeySetHandle) { 5376 final KeySetManagerService ksms = mSettings.getKeySetManagerService(); 5377 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 5378 } 5379 return false; 5380 } 5381 5382 @Override isPackageSignedByKeySetExactly(@onNull String packageName, @NonNull KeySet ks)5383 public boolean isPackageSignedByKeySetExactly(@NonNull String packageName, @NonNull KeySet ks) { 5384 final int callingUid = Binder.getCallingUid(); 5385 if (getInstantAppPackageName(callingUid) != null) { 5386 return false; 5387 } 5388 if (packageName == null || ks == null) { 5389 return false; 5390 } 5391 final AndroidPackage pkg = mPackages.get(packageName); 5392 final int callingUserId = UserHandle.getUserId(callingUid); 5393 if (pkg == null 5394 || shouldFilterApplicationIncludingUninstalled( 5395 getPackageStateInternal(pkg.getPackageName()), callingUid, callingUserId)) { 5396 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 5397 throw new IllegalArgumentException("Unknown package: " + packageName); 5398 } 5399 IBinder ksh = ks.getToken(); 5400 if (ksh instanceof KeySetHandle) { 5401 final KeySetManagerService ksms = mSettings.getKeySetManagerService(); 5402 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 5403 } 5404 return false; 5405 } 5406 5407 @Nullable 5408 @Override getVisibilityAllowLists(@onNull String packageName, @UserIdInt int[] userIds)5409 public SparseArray<int[]> getVisibilityAllowLists(@NonNull String packageName, 5410 @UserIdInt int[] userIds) { 5411 final PackageStateInternal ps = 5412 getPackageStateInternal(packageName, Process.SYSTEM_UID); 5413 if (ps == null) { 5414 return null; 5415 } 5416 return mAppsFilter.getVisibilityAllowList(this, ps, userIds, getPackageStates()); 5417 } 5418 5419 @Nullable 5420 @Override getVisibilityAllowList(@onNull String packageName, @UserIdInt int userId)5421 public int[] getVisibilityAllowList(@NonNull String packageName, @UserIdInt int userId) { 5422 final SparseArray<int[]> visibilityAllowList = getVisibilityAllowLists(packageName, 5423 new int[]{userId}); 5424 return visibilityAllowList != null ? visibilityAllowList.get(userId) : null; 5425 } 5426 5427 @Override canQueryPackage(int callingUid, @Nullable String targetPackageName)5428 public boolean canQueryPackage(int callingUid, @Nullable String targetPackageName) { 5429 // Since getSettingLPr returns null for ROOT_UID, add an extra check for it here. 5430 if (callingUid == Process.ROOT_UID || targetPackageName == null) { 5431 return true; 5432 } 5433 final Object setting = mSettings.getSettingBase(UserHandle.getAppId(callingUid)); 5434 if (setting == null) { 5435 return false; 5436 } 5437 5438 final int userId = UserHandle.getUserId(callingUid); 5439 final int targetAppId = UserHandle.getAppId( 5440 getPackageUid(targetPackageName, 0 /* flags */, userId)); 5441 // For update or already installed case, leverage the existing visibility rule. 5442 if (targetAppId != INVALID_UID) { 5443 final Object targetSetting = mSettings.getSettingBase(targetAppId); 5444 if (targetSetting instanceof PackageSetting) { 5445 return !shouldFilterApplication( 5446 (PackageSetting) targetSetting, callingUid, userId); 5447 } else { 5448 return !shouldFilterApplication( 5449 (SharedUserSetting) targetSetting, callingUid, userId); 5450 } 5451 } 5452 5453 // For new installing case, check if caller declares <queries> element with the 5454 // target package name or has proper permission. 5455 if (setting instanceof PackageSetting) { 5456 final AndroidPackage pkg = ((PackageSetting) setting).getPkg(); 5457 return pkg != null && mAppsFilter.canQueryPackage(pkg, targetPackageName); 5458 } else { 5459 final ArraySet<PackageStateInternal> callingSharedPkgSettings = 5460 (ArraySet<PackageStateInternal>) 5461 ((SharedUserSetting) setting).getPackageStates(); 5462 for (int i = callingSharedPkgSettings.size() - 1; i >= 0; i--) { 5463 final AndroidPackage pkg = callingSharedPkgSettings.valueAt(i).getPkg(); 5464 if (pkg != null && mAppsFilter.canQueryPackage(pkg, targetPackageName)) { 5465 return true; 5466 } 5467 } 5468 return false; 5469 } 5470 } 5471 5472 @Override getPackageUid(@onNull String packageName, @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId)5473 public int getPackageUid(@NonNull String packageName, 5474 @PackageManager.PackageInfoFlagsBits long flags, @UserIdInt int userId) { 5475 if (!mUserManager.exists(userId)) return -1; 5476 final int callingUid = Binder.getCallingUid(); 5477 flags = updateFlagsForPackage(flags, userId); 5478 enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 5479 false /*checkShell*/, "getPackageUid"); 5480 return getPackageUidInternal(packageName, flags, userId, callingUid); 5481 } 5482 5483 @Override canAccessComponent(int callingUid, @NonNull ComponentName component, @UserIdInt int userId)5484 public boolean canAccessComponent(int callingUid, @NonNull ComponentName component, 5485 @UserIdInt int userId) { 5486 final PackageStateInternal packageState = 5487 getPackageStateInternal(component.getPackageName()); 5488 return packageState != null && !shouldFilterApplication(packageState, callingUid, 5489 component, TYPE_UNKNOWN, userId, true /* filterUninstall */); 5490 } 5491 5492 @Override isCallerInstallerOfRecord(@onNull AndroidPackage pkg, int callingUid)5493 public boolean isCallerInstallerOfRecord(@NonNull AndroidPackage pkg, int callingUid) { 5494 if (pkg == null) { 5495 return false; 5496 } 5497 final PackageStateInternal packageState = getPackageStateInternal(pkg.getPackageName()); 5498 if (packageState == null) { 5499 return false; 5500 } 5501 5502 final PackageStateInternal installerPackageState = getPackageStateInternal( 5503 packageState.getInstallSource().mInstallerPackageName); 5504 return installerPackageState != null 5505 && UserHandle.isSameApp(installerPackageState.getAppId(), callingUid); 5506 } 5507 5508 @PackageManager.InstallReason 5509 @Override getInstallReason(@onNull String packageName, @UserIdInt int userId)5510 public int getInstallReason(@NonNull String packageName, @UserIdInt int userId) { 5511 final int callingUid = Binder.getCallingUid(); 5512 enforceCrossUserPermission(callingUid, userId, true /* requireFullPermission */, 5513 false /* checkShell */, "get install reason"); 5514 final PackageStateInternal ps = mSettings.getPackage(packageName); 5515 if (ps == null || shouldFilterApplicationIncludingUninstalled(ps, callingUid, userId)) { 5516 return PackageManager.INSTALL_REASON_UNKNOWN; 5517 } 5518 return ps.getUserStateOrDefault(userId).getInstallReason(); 5519 } 5520 5521 @Override 5522 @NonNull canPackageQuery(@onNull String sourcePackageName, @NonNull String[] targetPackageNames, @UserIdInt int userId)5523 public boolean[] canPackageQuery(@NonNull String sourcePackageName, 5524 @NonNull String[] targetPackageNames, @UserIdInt int userId) { 5525 final int targetSize = targetPackageNames.length; 5526 final boolean[] results = new boolean[targetSize]; 5527 if (!mUserManager.exists(userId)) { 5528 return results; 5529 } 5530 final int callingUid = Binder.getCallingUid(); 5531 enforceCrossUserPermission(callingUid, userId, false /*requireFullPermission*/, 5532 false /*checkShell*/, "can package query"); 5533 5534 final PackageStateInternal sourceSetting = getPackageStateInternal(sourcePackageName); 5535 final PackageStateInternal[] targetSettings = new PackageStateInternal[targetSize]; 5536 // Throw exception if the caller without the visibility of source package 5537 boolean throwException = 5538 (sourceSetting == null || shouldFilterApplicationIncludingUninstalled( 5539 sourceSetting, callingUid, userId)); 5540 for (int i = 0; !throwException && i < targetSize; i++) { 5541 targetSettings[i] = getPackageStateInternal(targetPackageNames[i]); 5542 // Throw exception if the caller without the visibility of target package 5543 throwException = 5544 (targetSettings[i] == null || shouldFilterApplicationIncludingUninstalled( 5545 targetSettings[i], callingUid, userId)); 5546 } 5547 if (throwException) { 5548 throw new ParcelableException(new PackageManager.NameNotFoundException("Package(s) " 5549 + sourcePackageName + " and/or " + Arrays.toString(targetPackageNames) 5550 + " not found.")); 5551 } 5552 5553 final int sourcePackageUid = UserHandle.getUid(userId, sourceSetting.getAppId()); 5554 for (int i = 0; i < targetSize; i++) { 5555 results[i] = !shouldFilterApplication(targetSettings[i], sourcePackageUid, userId); 5556 } 5557 return results; 5558 } 5559 5560 /* 5561 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5562 */ 5563 @Override canForwardTo(@onNull Intent intent, @Nullable String resolvedType, @UserIdInt int sourceUserId, @UserIdInt int targetUserId)5564 public boolean canForwardTo(@NonNull Intent intent, @Nullable String resolvedType, 5565 @UserIdInt int sourceUserId, @UserIdInt int targetUserId) { 5566 mContext.enforceCallingOrSelfPermission( 5567 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5568 if (mCrossProfileIntentResolverEngine.canReachTo(this, intent, resolvedType, 5569 sourceUserId, targetUserId)) { 5570 return true; 5571 } 5572 if (intent.hasWebURI()) { 5573 // cross-profile app linking works only towards the parent. 5574 final int callingUid = Binder.getCallingUid(); 5575 final UserInfo parent = getProfileParent(sourceUserId); 5576 if (parent == null) { 5577 return false; 5578 } 5579 long flags = updateFlagsForResolve(0, parent.id, callingUid, 5580 false /*includeInstantApps*/, 5581 isImplicitImageCaptureIntentAndNotSetByDpc(intent, parent.id, 5582 resolvedType, 0)); 5583 flags |= PackageManager.MATCH_DEFAULT_ONLY; 5584 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5585 intent, resolvedType, flags, sourceUserId, parent.id); 5586 return xpDomainInfo != null; 5587 } 5588 return false; 5589 } 5590 5591 @NonNull 5592 @Override getPersistentApplications(boolean safeMode, int flags)5593 public List<ApplicationInfo> getPersistentApplications(boolean safeMode, int flags) { 5594 final ArrayList<ApplicationInfo> finalList = new ArrayList<>(); 5595 5596 final int numPackages = mPackages.size(); 5597 final int userId = UserHandle.getCallingUserId(); 5598 for (int index = 0; index < numPackages; index++) { 5599 final AndroidPackage p = mPackages.valueAt(index); 5600 var packageState = mSettings.getPackage(p.getPackageName()); 5601 5602 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 5603 && !p.isDirectBootAware(); 5604 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 5605 && p.isDirectBootAware(); 5606 5607 if (p.isPersistent() 5608 && (!safeMode || packageState.isSystem()) 5609 && (matchesUnaware || matchesAware)) { 5610 PackageStateInternal ps = mSettings.getPackage(p.getPackageName()); 5611 if (ps != null) { 5612 ApplicationInfo ai = PackageInfoUtils.generateApplicationInfo(p, flags, 5613 ps.getUserStateOrDefault(userId), userId, ps); 5614 if (ai != null) { 5615 finalList.add(ai); 5616 } 5617 } 5618 } 5619 } 5620 5621 return finalList; 5622 } 5623 5624 @NonNull 5625 @Override getAppsWithSharedUserIds()5626 public SparseArray<String> getAppsWithSharedUserIds() { 5627 final SparseArray<String> sharedUserIds = new SparseArray<>(); 5628 for (SharedUserApi sharedUser : mSettings.getSharedUsers().values()) { 5629 sharedUserIds.put(UserHandle.getAppId(sharedUser.getAppId()), sharedUser.getName()); 5630 } 5631 return sharedUserIds; 5632 } 5633 5634 @NonNull 5635 @Override getSharedUserPackagesForPackage(@onNull String packageName, @UserIdInt int userId)5636 public String[] getSharedUserPackagesForPackage(@NonNull String packageName, 5637 @UserIdInt int userId) { 5638 final PackageStateInternal packageSetting = mSettings.getPackage(packageName); 5639 if (packageSetting == null || mSettings.getSharedUserFromPackageName(packageName) == null) { 5640 return EmptyArray.STRING; 5641 } 5642 5643 ArraySet<? extends PackageStateInternal> packages = 5644 mSettings.getSharedUserFromPackageName(packageName).getPackageStates(); 5645 final int numPackages = packages.size(); 5646 String[] res = new String[numPackages]; 5647 int i = 0; 5648 for (int index = 0; index < numPackages; index++) { 5649 final PackageStateInternal ps = packages.valueAt(index); 5650 if (ps.getUserStateOrDefault(userId).isInstalled()) { 5651 res[i++] = ps.getPackageName(); 5652 } 5653 } 5654 res = ArrayUtils.trimToSize(res, i); 5655 return res != null ? res : EmptyArray.STRING; 5656 } 5657 5658 5659 @NonNull 5660 @Override getUnusedPackages(long downgradeTimeThresholdMillis)5661 public Set<String> getUnusedPackages(long downgradeTimeThresholdMillis) { 5662 Set<String> unusedPackages = new ArraySet<>(); 5663 long currentTimeInMillis = System.currentTimeMillis(); 5664 final ArrayMap<String, ? extends PackageStateInternal> packageStates = 5665 mSettings.getPackages(); 5666 for (int index = 0; index < packageStates.size(); index++) { 5667 final PackageStateInternal packageState = packageStates.valueAt(index); 5668 if (packageState.getPkg() == null) { 5669 continue; 5670 } 5671 PackageDexUsage.PackageUseInfo packageUseInfo = 5672 mDexManager.getPackageUseInfoOrDefault(packageState.getPackageName()); 5673 if (PackageManagerServiceUtils.isUnusedSinceTimeInMillis( 5674 PackageStateUtils.getEarliestFirstInstallTime(packageState.getUserStates()), 5675 currentTimeInMillis, downgradeTimeThresholdMillis, packageUseInfo, 5676 packageState.getTransientState().getLatestPackageUseTimeInMills(), 5677 packageState.getTransientState().getLatestForegroundPackageUseTimeInMills())) { 5678 unusedPackages.add(packageState.getPackageName()); 5679 } 5680 } 5681 return unusedPackages; 5682 } 5683 5684 @Nullable 5685 @Override getHarmfulAppWarning(@onNull String packageName, @UserIdInt int userId)5686 public CharSequence getHarmfulAppWarning(@NonNull String packageName, @UserIdInt int userId) { 5687 final int callingUid = Binder.getCallingUid(); 5688 final int callingAppId = UserHandle.getAppId(callingUid); 5689 5690 enforceCrossUserPermission(callingUid, userId, true /*requireFullPermission*/, 5691 true /*checkShell*/, "getHarmfulAppInfo"); 5692 5693 if (!PackageManagerServiceUtils.isSystemOrRoot(callingAppId) 5694 && checkUidPermission(SET_HARMFUL_APP_WARNINGS, callingUid) != PERMISSION_GRANTED) { 5695 throw new SecurityException("Caller must have the " 5696 + SET_HARMFUL_APP_WARNINGS + " permission."); 5697 } 5698 5699 final PackageStateInternal packageState = getPackageStateInternal(packageName); 5700 if (packageState == null) { 5701 throw new IllegalArgumentException("Unknown package: " + packageName); 5702 } 5703 return packageState.getUserStateOrDefault(userId).getHarmfulAppWarning(); 5704 } 5705 5706 /** 5707 * Only keep package names that refer to {@link PackageState#isSystem system} packages. 5708 * 5709 * @param pkgNames The packages to filter 5710 * 5711 * @return The filtered packages 5712 */ 5713 @NonNull 5714 @Override filterOnlySystemPackages(@ullable String... pkgNames)5715 public String[] filterOnlySystemPackages(@Nullable String... pkgNames) { 5716 if (pkgNames == null) { 5717 return ArrayUtils.emptyArray(String.class); 5718 } 5719 5720 ArrayList<String> systemPackageNames = new ArrayList<>(pkgNames.length); 5721 5722 for (String pkgName: pkgNames) { 5723 if (pkgName == null) { 5724 continue; 5725 } 5726 5727 var packageState = getPackageStateInternal(pkgName); 5728 if (packageState == null || packageState.getAndroidPackage() == null) { 5729 Log.w(TAG, "Could not find package " + pkgName); 5730 continue; 5731 } 5732 5733 if (!packageState.isSystem()) { 5734 Log.w(TAG, pkgName + " is not system"); 5735 continue; 5736 } 5737 5738 systemPackageNames.add(pkgName); 5739 } 5740 5741 return systemPackageNames.toArray(new String[]{}); 5742 } 5743 5744 @NonNull 5745 @Override getPackagesForAppId(int appId)5746 public List<AndroidPackage> getPackagesForAppId(int appId) { 5747 final SettingBase settingBase = mSettings.getSettingBase(appId); 5748 if (settingBase instanceof SharedUserSetting) { 5749 final SharedUserSetting sus = (SharedUserSetting) settingBase; 5750 return sus.getPackages(); 5751 } else if (settingBase instanceof PackageSetting) { 5752 final PackageSetting ps = (PackageSetting) settingBase; 5753 final AndroidPackage pkg = ps.getPkg(); 5754 if (pkg != null) { 5755 return Collections.singletonList(pkg); 5756 } else { 5757 return Collections.emptyList(); 5758 } 5759 } else { 5760 return Collections.emptyList(); 5761 } 5762 } 5763 5764 @Override getUidTargetSdkVersion(int uid)5765 public int getUidTargetSdkVersion(int uid) { 5766 if (Process.isSdkSandboxUid(uid)) { 5767 uid = getBaseSdkSandboxUid(); 5768 } 5769 final int appId = UserHandle.getAppId(uid); 5770 final SettingBase settingBase = mSettings.getSettingBase(appId); 5771 if (settingBase instanceof SharedUserSetting) { 5772 final SharedUserSetting sus = (SharedUserSetting) settingBase; 5773 final ArraySet<PackageStateInternal> packageStates = 5774 (ArraySet<PackageStateInternal>) sus.getPackageStates(); 5775 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 5776 final int numPackages = packageStates.size(); 5777 for (int index = 0; index < numPackages; index++) { 5778 final PackageStateInternal ps = packageStates.valueAt(index); 5779 if (ps.getPkg() != null) { 5780 int v = ps.getPkg().getTargetSdkVersion(); 5781 if (v < vers) vers = v; 5782 } 5783 } 5784 return vers; 5785 } else if (settingBase instanceof PackageSetting) { 5786 final PackageSetting ps = (PackageSetting) settingBase; 5787 if (ps.getPkg() != null) { 5788 return ps.getPkg().getTargetSdkVersion(); 5789 } 5790 } 5791 return Build.VERSION_CODES.CUR_DEVELOPMENT; 5792 } 5793 5794 @Nullable 5795 @Override getProcessesForUid(int uid)5796 public ArrayMap<String, ProcessInfo> getProcessesForUid(int uid) { 5797 if (Process.isSdkSandboxUid(uid)) { 5798 uid = getBaseSdkSandboxUid(); 5799 } 5800 final int appId = UserHandle.getAppId(uid); 5801 final SettingBase settingBase = mSettings.getSettingBase(appId); 5802 if (settingBase instanceof SharedUserSetting) { 5803 final SharedUserSetting sus = (SharedUserSetting) settingBase; 5804 return PackageInfoUtils.generateProcessInfo(sus.processes, 0); 5805 } else if (settingBase instanceof PackageSetting) { 5806 final PackageSetting ps = (PackageSetting) settingBase; 5807 final AndroidPackage pkg = ps.getPkg(); 5808 return pkg == null ? null : PackageInfoUtils.generateProcessInfo(pkg.getProcesses(), 0); 5809 } 5810 return null; 5811 } 5812 5813 @Override getBlockUninstall(@serIdInt int userId, @NonNull String packageName)5814 public boolean getBlockUninstall(@UserIdInt int userId, @NonNull String packageName) { 5815 return mSettings.getBlockUninstall(userId, packageName); 5816 } 5817 5818 @Nullable 5819 @Override getPackageOrSharedUser(int appId)5820 public Pair<PackageStateInternal, SharedUserApi> getPackageOrSharedUser(int appId) { 5821 final SettingBase settingBase = mSettings.getSettingBase(appId); 5822 if (settingBase instanceof SharedUserSetting) { 5823 return Pair.create(null, (SharedUserApi) settingBase); 5824 } else if (settingBase instanceof PackageSetting) { 5825 return Pair.create((PackageStateInternal) settingBase, null); 5826 } else { 5827 return null; 5828 } 5829 } 5830 getBaseSdkSandboxUid()5831 private int getBaseSdkSandboxUid() { 5832 return getPackage(mService.getSdkSandboxPackageName()).getUid(); 5833 } 5834 5835 isKnownIsolatedComputeApp(int uid)5836 private boolean isKnownIsolatedComputeApp(int uid) { 5837 if (!Process.isIsolatedUid(uid)) { 5838 return false; 5839 } 5840 final boolean isHotword = 5841 mPermissionManager.getHotwordDetectionServiceProvider() != null 5842 && uid 5843 == mPermissionManager.getHotwordDetectionServiceProvider().getUid(); 5844 if (isHotword) { 5845 return true; 5846 } 5847 OnDeviceIntelligenceManagerInternal onDeviceIntelligenceManagerInternal = 5848 mInjector.getLocalService(OnDeviceIntelligenceManagerInternal.class); 5849 return onDeviceIntelligenceManagerInternal != null 5850 && uid == onDeviceIntelligenceManagerInternal.getInferenceServiceUid(); 5851 } 5852 5853 @Nullable 5854 @Override getSharedUser(int sharedUserAppId)5855 public SharedUserApi getSharedUser(int sharedUserAppId) { 5856 return mSettings.getSharedUserFromAppId(sharedUserAppId); 5857 } 5858 5859 @NonNull 5860 @Override getSharedUserPackages(int sharedUserAppId)5861 public ArraySet<PackageStateInternal> getSharedUserPackages(int sharedUserAppId) { 5862 return mSettings.getSharedUserPackages(sharedUserAppId); 5863 } 5864 5865 @NonNull 5866 @Override getComponentResolver()5867 public ComponentResolverApi getComponentResolver() { 5868 return mComponentResolver; 5869 } 5870 5871 @Nullable 5872 @Override getDisabledSystemPackage(@onNull String packageName)5873 public PackageStateInternal getDisabledSystemPackage(@NonNull String packageName) { 5874 return mSettings.getDisabledSystemPkg(packageName); 5875 } 5876 5877 @Nullable 5878 @Override getInstantAppInstallerInfo()5879 public ResolveInfo getInstantAppInstallerInfo() { 5880 return mInstantAppInstallerInfo; 5881 } 5882 5883 @NonNull 5884 @Override getFrozenPackages()5885 public WatchedArrayMap<String, Integer> getFrozenPackages() { 5886 return mFrozenPackages; 5887 } 5888 5889 @Override checkPackageFrozen(@onNull String packageName)5890 public void checkPackageFrozen(@NonNull String packageName) { 5891 if (!mFrozenPackages.containsKey(packageName)) { 5892 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 5893 } 5894 } 5895 5896 @Nullable 5897 @Override getInstantAppInstallerComponent()5898 public ComponentName getInstantAppInstallerComponent() { 5899 return mLocalInstantAppInstallerActivity == null 5900 ? null : mLocalInstantAppInstallerActivity.getComponentName(); 5901 } 5902 5903 @Override dumpPermissions(@onNull PrintWriter pw, @NonNull String packageName, @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState)5904 public void dumpPermissions(@NonNull PrintWriter pw, @NonNull String packageName, 5905 @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState) { 5906 mSettings.dumpPermissions(pw, packageName, permissionNames, dumpState); 5907 } 5908 5909 @Override dumpPackages(@onNull PrintWriter pw, @NonNull String packageName, @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState, boolean checkin)5910 public void dumpPackages(@NonNull PrintWriter pw, @NonNull String packageName, 5911 @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState, 5912 boolean checkin) { 5913 mSettings.dumpPackages(pw, packageName, permissionNames, dumpState, checkin); 5914 } 5915 5916 @Override dumpKeySet(@onNull PrintWriter pw, @NonNull String packageName, @NonNull DumpState dumpState)5917 public void dumpKeySet(@NonNull PrintWriter pw, @NonNull String packageName, 5918 @NonNull DumpState dumpState) { 5919 mSettings.dumpKeySet(pw, packageName, dumpState); 5920 } 5921 5922 @Override dumpSharedUsers(@onNull PrintWriter pw, @NonNull String packageName, @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState, boolean checkin)5923 public void dumpSharedUsers(@NonNull PrintWriter pw, @NonNull String packageName, 5924 @NonNull ArraySet<String> permissionNames, @NonNull DumpState dumpState, 5925 boolean checkin) { 5926 mSettings.dumpSharedUsers(pw, packageName, permissionNames, dumpState, checkin); 5927 } 5928 5929 @Override dumpSharedUsersProto(@onNull ProtoOutputStream proto)5930 public void dumpSharedUsersProto(@NonNull ProtoOutputStream proto) { 5931 mSettings.dumpSharedUsersProto(proto); 5932 } 5933 5934 @Override dumpPackagesProto(@onNull ProtoOutputStream proto)5935 public void dumpPackagesProto(@NonNull ProtoOutputStream proto) { 5936 mSettings.dumpPackagesProto(proto); 5937 } 5938 5939 @Override dumpSharedLibrariesProto(@onNull ProtoOutputStream proto)5940 public void dumpSharedLibrariesProto(@NonNull ProtoOutputStream proto) { 5941 mSharedLibraries.dumpProto(proto); 5942 } 5943 5944 @NonNull 5945 @Override getVolumePackages(@onNull String volumeUuid)5946 public List<? extends PackageStateInternal> getVolumePackages(@NonNull String volumeUuid) { 5947 return mSettings.getVolumePackages(volumeUuid); 5948 } 5949 5950 @Override 5951 @NonNull getSharedUsers()5952 public ArrayMap<String, ? extends SharedUserApi> getSharedUsers() { 5953 return mSettings.getSharedUsers(); 5954 } 5955 5956 @Override 5957 @NonNull getUserInfos()5958 public UserInfo[] getUserInfos() { 5959 return mInjector.getUserManagerInternal().getUserInfos(); 5960 } 5961 } 5962