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