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