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