1 /*
2  * Copyright (C) 2010 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 android.app;
18 
19 import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_COLORED;
20 import static android.app.admin.DevicePolicyResources.Drawables.Style.SOLID_NOT_COLORED;
21 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON;
22 import static android.app.admin.DevicePolicyResources.Drawables.WORK_PROFILE_ICON_BADGE;
23 import static android.app.admin.DevicePolicyResources.UNDEFINED;
24 import static android.content.pm.Checksum.TYPE_PARTIAL_MERKLE_ROOT_1M_SHA256;
25 import static android.content.pm.Checksum.TYPE_PARTIAL_MERKLE_ROOT_1M_SHA512;
26 import static android.content.pm.Checksum.TYPE_WHOLE_MD5;
27 import static android.content.pm.Checksum.TYPE_WHOLE_MERKLE_ROOT_4K_SHA256;
28 import static android.content.pm.Checksum.TYPE_WHOLE_SHA1;
29 import static android.content.pm.Checksum.TYPE_WHOLE_SHA256;
30 import static android.content.pm.Checksum.TYPE_WHOLE_SHA512;
31 
32 import android.annotation.CallbackExecutor;
33 import android.annotation.DrawableRes;
34 import android.annotation.NonNull;
35 import android.annotation.Nullable;
36 import android.annotation.StringRes;
37 import android.annotation.UserIdInt;
38 import android.annotation.XmlRes;
39 import android.app.admin.DevicePolicyManager;
40 import android.app.role.RoleManager;
41 import android.compat.annotation.UnsupportedAppUsage;
42 import android.content.ComponentName;
43 import android.content.ContentResolver;
44 import android.content.Context;
45 import android.content.Intent;
46 import android.content.IntentFilter;
47 import android.content.IntentSender;
48 import android.content.pm.ActivityInfo;
49 import android.content.pm.ApkChecksum;
50 import android.content.pm.ApplicationInfo;
51 import android.content.pm.ChangedPackages;
52 import android.content.pm.Checksum;
53 import android.content.pm.ComponentInfo;
54 import android.content.pm.FeatureInfo;
55 import android.content.pm.IOnChecksumsReadyListener;
56 import android.content.pm.IPackageDataObserver;
57 import android.content.pm.IPackageDeleteObserver;
58 import android.content.pm.IPackageManager;
59 import android.content.pm.IPackageMoveObserver;
60 import android.content.pm.IPackageStatsObserver;
61 import android.content.pm.InstallSourceInfo;
62 import android.content.pm.InstantAppInfo;
63 import android.content.pm.InstrumentationInfo;
64 import android.content.pm.IntentFilterVerificationInfo;
65 import android.content.pm.KeySet;
66 import android.content.pm.ModuleInfo;
67 import android.content.pm.PackageInfo;
68 import android.content.pm.PackageInstaller;
69 import android.content.pm.PackageItemInfo;
70 import android.content.pm.PackageManager;
71 import android.content.pm.ParceledListSlice;
72 import android.content.pm.PermissionGroupInfo;
73 import android.content.pm.PermissionInfo;
74 import android.content.pm.ProviderInfo;
75 import android.content.pm.ResolveInfo;
76 import android.content.pm.ServiceInfo;
77 import android.content.pm.SharedLibraryInfo;
78 import android.content.pm.SuspendDialogInfo;
79 import android.content.pm.VerifierDeviceIdentity;
80 import android.content.pm.VersionedPackage;
81 import android.content.pm.dex.ArtManager;
82 import android.content.res.Configuration;
83 import android.content.res.Resources;
84 import android.content.res.XmlResourceParser;
85 import android.graphics.Bitmap;
86 import android.graphics.Canvas;
87 import android.graphics.Rect;
88 import android.graphics.drawable.BitmapDrawable;
89 import android.graphics.drawable.Drawable;
90 import android.graphics.drawable.LayerDrawable;
91 import android.os.Build;
92 import android.os.Bundle;
93 import android.os.Handler;
94 import android.os.Looper;
95 import android.os.Message;
96 import android.os.ParcelFileDescriptor;
97 import android.os.ParcelableException;
98 import android.os.PersistableBundle;
99 import android.os.Process;
100 import android.os.RemoteException;
101 import android.os.StrictMode;
102 import android.os.SystemProperties;
103 import android.os.UserHandle;
104 import android.os.UserManager;
105 import android.os.storage.StorageManager;
106 import android.os.storage.VolumeInfo;
107 import android.permission.PermissionControllerManager;
108 import android.permission.PermissionManager;
109 import android.provider.Settings;
110 import android.system.ErrnoException;
111 import android.system.Os;
112 import android.system.OsConstants;
113 import android.system.StructStat;
114 import android.text.TextUtils;
115 import android.util.ArrayMap;
116 import android.util.ArraySet;
117 import android.util.LauncherIcons;
118 import android.util.Log;
119 
120 import com.android.internal.annotations.GuardedBy;
121 import com.android.internal.annotations.Immutable;
122 import com.android.internal.annotations.VisibleForTesting;
123 import com.android.internal.os.SomeArgs;
124 import com.android.internal.util.UserIcons;
125 
126 import dalvik.system.VMRuntime;
127 
128 import libcore.util.EmptyArray;
129 
130 import java.io.IOException;
131 import java.io.InputStream;
132 import java.lang.ref.WeakReference;
133 import java.security.cert.Certificate;
134 import java.security.cert.CertificateEncodingException;
135 import java.security.cert.X509Certificate;
136 import java.util.ArrayList;
137 import java.util.Arrays;
138 import java.util.Collections;
139 import java.util.Iterator;
140 import java.util.List;
141 import java.util.Objects;
142 import java.util.Set;
143 import java.util.concurrent.Executor;
144 import java.util.function.Consumer;
145 
146 /** @hide */
147 public class ApplicationPackageManager extends PackageManager {
148     private static final String TAG = "ApplicationPackageManager";
149     private static final boolean DEBUG_ICONS = false;
150 
151     private static final int DEFAULT_EPHEMERAL_COOKIE_MAX_SIZE_BYTES = 16384; // 16KB
152 
153     // Default flags to use with PackageManager when no flags are given.
154     private static final int sDefaultFlags = GET_SHARED_LIBRARY_FILES;
155 
156     /** Default set of checksums - includes all available checksums.
157      * @see PackageManager#requestChecksums  */
158     private static final int DEFAULT_CHECKSUMS =
159             TYPE_WHOLE_MERKLE_ROOT_4K_SHA256 | TYPE_WHOLE_MD5 | TYPE_WHOLE_SHA1 | TYPE_WHOLE_SHA256
160                     | TYPE_WHOLE_SHA512 | TYPE_PARTIAL_MERKLE_ROOT_1M_SHA256
161                     | TYPE_PARTIAL_MERKLE_ROOT_1M_SHA512;
162 
163     // Name of the resource which provides background permission button string
164     public static final String APP_PERMISSION_BUTTON_ALLOW_ALWAYS =
165             "app_permission_button_allow_always";
166 
167     // Name of the package which the permission controller's resources are in.
168     public static final String PERMISSION_CONTROLLER_RESOURCE_PACKAGE =
169             "com.android.permissioncontroller";
170 
171     private volatile UserManager mUserManager;
172     private volatile PermissionManager mPermissionManager;
173     private volatile PackageInstaller mInstaller;
174     private volatile ArtManager mArtManager;
175     private volatile DevicePolicyManager mDevicePolicyManager;
176     private volatile String mPermissionsControllerPackageName;
177 
178     @GuardedBy("mDelegates")
179     private final ArrayList<MoveCallbackDelegate> mDelegates = new ArrayList<>();
180 
getUserManager()181     UserManager getUserManager() {
182         if (mUserManager == null) {
183             mUserManager = UserManager.get(mContext);
184         }
185         return mUserManager;
186     }
187 
getDevicePolicyManager()188     DevicePolicyManager getDevicePolicyManager() {
189         if (mDevicePolicyManager == null) {
190             mDevicePolicyManager = mContext.getSystemService(DevicePolicyManager.class);
191         }
192         return mDevicePolicyManager;
193     }
194 
getPermissionManager()195     private PermissionManager getPermissionManager() {
196         if (mPermissionManager == null) {
197             mPermissionManager = mContext.getSystemService(PermissionManager.class);
198         }
199         return mPermissionManager;
200     }
201 
202     @Override
getUserId()203     public int getUserId() {
204         return mContext.getUserId();
205     }
206 
207     @Override
getPackageInfo(String packageName, int flags)208     public PackageInfo getPackageInfo(String packageName, int flags)
209             throws NameNotFoundException {
210         return getPackageInfo(packageName, PackageInfoFlags.of(flags));
211     }
212 
213     @Override
getPackageInfo(String packageName, PackageInfoFlags flags)214     public PackageInfo getPackageInfo(String packageName, PackageInfoFlags flags)
215             throws NameNotFoundException {
216         return getPackageInfoAsUser(packageName, flags, getUserId());
217     }
218 
219     @Override
getPackageInfo(VersionedPackage versionedPackage, int flags)220     public PackageInfo getPackageInfo(VersionedPackage versionedPackage, int flags)
221             throws NameNotFoundException {
222         return getPackageInfo(versionedPackage, PackageInfoFlags.of(flags));
223     }
224 
225     @Override
getPackageInfo(VersionedPackage versionedPackage, PackageInfoFlags flags)226     public PackageInfo getPackageInfo(VersionedPackage versionedPackage, PackageInfoFlags flags)
227             throws NameNotFoundException {
228         final int userId = getUserId();
229         try {
230             PackageInfo pi = mPM.getPackageInfoVersioned(versionedPackage,
231                     updateFlagsForPackage(flags.getValue(), userId), userId);
232             if (pi != null) {
233                 return pi;
234             }
235         } catch (RemoteException e) {
236             throw e.rethrowFromSystemServer();
237         }
238         throw new NameNotFoundException(versionedPackage.toString());
239     }
240 
241     @Override
getPackageInfoAsUser(String packageName, int flags, int userId)242     public PackageInfo getPackageInfoAsUser(String packageName, int flags, int userId)
243             throws NameNotFoundException {
244         return getPackageInfoAsUser(packageName, PackageInfoFlags.of(flags), userId);
245     }
246 
247     @Override
getPackageInfoAsUser(String packageName, PackageInfoFlags flags, int userId)248     public PackageInfo getPackageInfoAsUser(String packageName, PackageInfoFlags flags, int userId)
249             throws NameNotFoundException {
250         PackageInfo pi =
251                 getPackageInfoAsUserCached(
252                         packageName,
253                         updateFlagsForPackage(flags.getValue(), userId),
254                         userId);
255         if (pi == null) {
256             throw new NameNotFoundException(packageName);
257         }
258         return pi;
259     }
260 
261     @Override
currentToCanonicalPackageNames(String[] names)262     public String[] currentToCanonicalPackageNames(String[] names) {
263         try {
264             return mPM.currentToCanonicalPackageNames(names);
265         } catch (RemoteException e) {
266             throw e.rethrowFromSystemServer();
267         }
268     }
269 
270     @Override
canonicalToCurrentPackageNames(String[] names)271     public String[] canonicalToCurrentPackageNames(String[] names) {
272         try {
273             return mPM.canonicalToCurrentPackageNames(names);
274         } catch (RemoteException e) {
275             throw e.rethrowFromSystemServer();
276         }
277     }
278 
279     @Override
getLaunchIntentForPackage(String packageName)280     public Intent getLaunchIntentForPackage(String packageName) {
281         // First see if the package has an INFO activity; the existence of
282         // such an activity is implied to be the desired front-door for the
283         // overall package (such as if it has multiple launcher entries).
284         Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
285         intentToResolve.addCategory(Intent.CATEGORY_INFO);
286         intentToResolve.setPackage(packageName);
287         List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
288 
289         // Otherwise, try to find a main launcher activity.
290         if (ris == null || ris.size() <= 0) {
291             // reuse the intent instance
292             intentToResolve.removeCategory(Intent.CATEGORY_INFO);
293             intentToResolve.addCategory(Intent.CATEGORY_LAUNCHER);
294             intentToResolve.setPackage(packageName);
295             ris = queryIntentActivities(intentToResolve, 0);
296         }
297         if (ris == null || ris.size() <= 0) {
298             return null;
299         }
300         Intent intent = new Intent(intentToResolve);
301         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
302         intent.setClassName(ris.get(0).activityInfo.packageName,
303                 ris.get(0).activityInfo.name);
304         return intent;
305     }
306 
307     @Override
getLeanbackLaunchIntentForPackage(String packageName)308     public Intent getLeanbackLaunchIntentForPackage(String packageName) {
309         return getLaunchIntentForPackageAndCategory(packageName, Intent.CATEGORY_LEANBACK_LAUNCHER);
310     }
311 
312     @Override
getCarLaunchIntentForPackage(String packageName)313     public Intent getCarLaunchIntentForPackage(String packageName) {
314         return getLaunchIntentForPackageAndCategory(packageName, Intent.CATEGORY_CAR_LAUNCHER);
315     }
316 
getLaunchIntentForPackageAndCategory(String packageName, String category)317     private Intent getLaunchIntentForPackageAndCategory(String packageName, String category) {
318         // Try to find a main launcher activity for the given categories.
319         Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
320         intentToResolve.addCategory(category);
321         intentToResolve.setPackage(packageName);
322         List<ResolveInfo> ris = queryIntentActivities(intentToResolve, 0);
323 
324         if (ris == null || ris.size() <= 0) {
325             return null;
326         }
327         Intent intent = new Intent(intentToResolve);
328         intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
329         intent.setClassName(ris.get(0).activityInfo.packageName,
330                 ris.get(0).activityInfo.name);
331         return intent;
332     }
333 
334     @Override
getLaunchIntentSenderForPackage(@onNull String packageName)335     public @NonNull IntentSender getLaunchIntentSenderForPackage(@NonNull String packageName) {
336         try {
337             return mPM.getLaunchIntentSenderForPackage(packageName, mContext.getPackageName(),
338                     mContext.getAttributionTag(), getUserId());
339         } catch (RemoteException e) {
340             throw e.rethrowFromSystemServer();
341         }
342     }
343 
344     @Override
getPackageGids(String packageName)345     public int[] getPackageGids(String packageName) throws NameNotFoundException {
346         return getPackageGids(packageName, 0);
347     }
348 
349     @Override
getPackageGids(String packageName, int flags)350     public int[] getPackageGids(String packageName, int flags)
351             throws NameNotFoundException {
352         return getPackageGids(packageName, PackageInfoFlags.of(flags));
353     }
354 
355     @Override
getPackageGids(String packageName, PackageInfoFlags flags)356     public int[] getPackageGids(String packageName, PackageInfoFlags flags)
357             throws NameNotFoundException {
358         final int userId = getUserId();
359         try {
360             int[] gids = mPM.getPackageGids(packageName,
361                     updateFlagsForPackage(flags.getValue(), userId), userId);
362             if (gids != null) {
363                 return gids;
364             }
365         } catch (RemoteException e) {
366             throw e.rethrowFromSystemServer();
367         }
368 
369         throw new NameNotFoundException(packageName);
370     }
371 
372     @Override
getPackageUid(String packageName, int flags)373     public int getPackageUid(String packageName, int flags) throws NameNotFoundException {
374         return getPackageUid(packageName, PackageInfoFlags.of(flags));
375     }
376 
377     @Override
getPackageUid(String packageName, PackageInfoFlags flags)378     public int getPackageUid(String packageName, PackageInfoFlags flags)
379             throws NameNotFoundException {
380         return getPackageUidAsUser(packageName, flags, getUserId());
381     }
382 
383     @Override
getPackageUidAsUser(String packageName, int userId)384     public int getPackageUidAsUser(String packageName, int userId) throws NameNotFoundException {
385         return getPackageUidAsUser(packageName, 0, userId);
386     }
387 
388     @Override
getPackageUidAsUser(String packageName, int flags, int userId)389     public int getPackageUidAsUser(String packageName, int flags, int userId)
390             throws NameNotFoundException {
391         return getPackageUidAsUser(packageName, PackageInfoFlags.of(flags), userId);
392     }
393 
394     @Override
getPackageUidAsUser(String packageName, PackageInfoFlags flags, int userId)395     public int getPackageUidAsUser(String packageName, PackageInfoFlags flags, int userId)
396             throws NameNotFoundException {
397         try {
398             int uid = mPM.getPackageUid(packageName,
399                     updateFlagsForPackage(flags.getValue(), userId), userId);
400             if (uid >= 0) {
401                 return uid;
402             }
403         } catch (RemoteException e) {
404             throw e.rethrowFromSystemServer();
405         }
406 
407         throw new NameNotFoundException(packageName);
408     }
409 
410     @Override
411     @SuppressWarnings("unchecked")
getAllPermissionGroups(int flags)412     public List<PermissionGroupInfo> getAllPermissionGroups(int flags) {
413         return getPermissionManager().getAllPermissionGroups(flags);
414     }
415 
416     @Override
getPermissionGroupInfo(String groupName, int flags)417     public PermissionGroupInfo getPermissionGroupInfo(String groupName, int flags)
418             throws NameNotFoundException {
419         final PermissionGroupInfo permissionGroupInfo = getPermissionManager()
420                 .getPermissionGroupInfo(groupName, flags);
421         if (permissionGroupInfo == null) {
422             throw new NameNotFoundException(groupName);
423         }
424         return permissionGroupInfo;
425     }
426 
427     @Override
getPermissionInfo(String permName, int flags)428     public PermissionInfo getPermissionInfo(String permName, int flags)
429             throws NameNotFoundException {
430         final PermissionInfo permissionInfo = getPermissionManager().getPermissionInfo(permName,
431                 flags);
432         if (permissionInfo == null) {
433             throw new NameNotFoundException(permName);
434         }
435         return permissionInfo;
436     }
437 
438     @Override
439     @SuppressWarnings("unchecked")
queryPermissionsByGroup(String groupName, int flags)440     public List<PermissionInfo> queryPermissionsByGroup(String groupName, int flags)
441             throws NameNotFoundException {
442         final List<PermissionInfo> permissionInfos = getPermissionManager().queryPermissionsByGroup(
443                 groupName, flags);
444         if (permissionInfos == null) {
445             throw new NameNotFoundException(groupName);
446         }
447         return permissionInfos;
448     }
449 
450     @Override
getPlatformPermissionsForGroup(@onNull String permissionGroupName, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<List<String>> callback)451     public void getPlatformPermissionsForGroup(@NonNull String permissionGroupName,
452             @NonNull @CallbackExecutor Executor executor,
453             @NonNull Consumer<List<String>> callback) {
454         final PermissionControllerManager permissionControllerManager = mContext.getSystemService(
455                 PermissionControllerManager.class);
456         permissionControllerManager.getPlatformPermissionsForGroup(permissionGroupName, executor,
457                 callback);
458     }
459 
460     @Override
getGroupOfPlatformPermission(@onNull String permissionName, @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<String> callback)461     public void getGroupOfPlatformPermission(@NonNull String permissionName,
462             @NonNull @CallbackExecutor Executor executor, @NonNull Consumer<String> callback) {
463         final PermissionControllerManager permissionControllerManager = mContext.getSystemService(
464                 PermissionControllerManager.class);
465         permissionControllerManager.getGroupOfPlatformPermission(permissionName, executor,
466                 callback);
467     }
468 
469     @Override
arePermissionsIndividuallyControlled()470     public boolean arePermissionsIndividuallyControlled() {
471         return mContext.getResources().getBoolean(
472                 com.android.internal.R.bool.config_permissionsIndividuallyControlled);
473     }
474 
475     @Override
isWirelessConsentModeEnabled()476     public boolean isWirelessConsentModeEnabled() {
477         return mContext.getResources().getBoolean(
478                 com.android.internal.R.bool.config_wirelessConsentRequired);
479     }
480 
481     @Override
getApplicationInfo(String packageName, int flags)482     public ApplicationInfo getApplicationInfo(String packageName, int flags)
483             throws NameNotFoundException {
484         return getApplicationInfo(packageName, ApplicationInfoFlags.of(flags));
485     }
486 
487     @Override
getApplicationInfo(String packageName, ApplicationInfoFlags flags)488     public ApplicationInfo getApplicationInfo(String packageName, ApplicationInfoFlags flags)
489             throws NameNotFoundException {
490         return getApplicationInfoAsUser(packageName, flags, getUserId());
491     }
492 
493     @Override
getApplicationInfoAsUser(String packageName, int flags, int userId)494     public ApplicationInfo getApplicationInfoAsUser(String packageName, int flags, int userId)
495             throws NameNotFoundException {
496         return getApplicationInfoAsUser(packageName, ApplicationInfoFlags.of(flags), userId);
497     }
498 
499     @Override
getApplicationInfoAsUser(String packageName, ApplicationInfoFlags flags, int userId)500     public ApplicationInfo getApplicationInfoAsUser(String packageName, ApplicationInfoFlags flags,
501             int userId) throws NameNotFoundException {
502         ApplicationInfo ai = getApplicationInfoAsUserCached(
503                         packageName,
504                         updateFlagsForApplication(flags.getValue(), userId),
505                         userId);
506         if (ai == null) {
507             throw new NameNotFoundException(packageName);
508         }
509         return maybeAdjustApplicationInfo(ai);
510     }
511 
maybeAdjustApplicationInfo(ApplicationInfo info)512     private static ApplicationInfo maybeAdjustApplicationInfo(ApplicationInfo info) {
513         // If we're dealing with a multi-arch application that has both
514         // 32 and 64 bit shared libraries, we might need to choose the secondary
515         // depending on what the current runtime's instruction set is.
516         if (info.primaryCpuAbi != null && info.secondaryCpuAbi != null) {
517             final String runtimeIsa = VMRuntime.getRuntime().vmInstructionSet();
518 
519             // Get the instruction set that the libraries of secondary Abi is supported.
520             // In presence of a native bridge this might be different than the one secondary Abi used.
521             String secondaryIsa = VMRuntime.getInstructionSet(info.secondaryCpuAbi);
522             final String secondaryDexCodeIsa = SystemProperties.get("ro.dalvik.vm.isa." + secondaryIsa);
523             secondaryIsa = secondaryDexCodeIsa.isEmpty() ? secondaryIsa : secondaryDexCodeIsa;
524 
525             // If the runtimeIsa is the same as the primary isa, then we do nothing.
526             // Everything will be set up correctly because info.nativeLibraryDir will
527             // correspond to the right ISA.
528             if (runtimeIsa.equals(secondaryIsa)) {
529                 ApplicationInfo modified = new ApplicationInfo(info);
530                 modified.nativeLibraryDir = info.secondaryNativeLibraryDir;
531                 return modified;
532             }
533         }
534         return info;
535     }
536 
537     @Override
getTargetSdkVersion(@onNull String packageName)538     public int getTargetSdkVersion(@NonNull String packageName) throws NameNotFoundException {
539         try {
540             int version = mPM.getTargetSdkVersion(packageName);
541             if (version != -1) {
542                 return version;
543             }
544         } catch (RemoteException e) {
545             throw e.rethrowFromSystemServer();
546         }
547         throw new PackageManager.NameNotFoundException(packageName);
548     }
549 
550     @Override
getActivityInfo(ComponentName className, int flags)551     public ActivityInfo getActivityInfo(ComponentName className, int flags)
552             throws NameNotFoundException {
553         return getActivityInfo(className, ComponentInfoFlags.of(flags));
554     }
555 
556     @Override
getActivityInfo(ComponentName className, ComponentInfoFlags flags)557     public ActivityInfo getActivityInfo(ComponentName className, ComponentInfoFlags flags)
558             throws NameNotFoundException {
559         final int userId = getUserId();
560         try {
561             ActivityInfo ai = mPM.getActivityInfo(className,
562                     updateFlagsForComponent(flags.getValue(), userId, null), userId);
563             if (ai != null) {
564                 return ai;
565             }
566         } catch (RemoteException e) {
567             throw e.rethrowFromSystemServer();
568         }
569 
570         throw new NameNotFoundException(className.toString());
571     }
572 
573     @Override
getReceiverInfo(ComponentName className, int flags)574     public ActivityInfo getReceiverInfo(ComponentName className, int flags)
575             throws NameNotFoundException {
576         return getReceiverInfo(className, ComponentInfoFlags.of(flags));
577     }
578 
579     @Override
getReceiverInfo(ComponentName className, ComponentInfoFlags flags)580     public ActivityInfo getReceiverInfo(ComponentName className, ComponentInfoFlags flags)
581             throws NameNotFoundException {
582         final int userId = getUserId();
583         try {
584             ActivityInfo ai = mPM.getReceiverInfo(className,
585                     updateFlagsForComponent(flags.getValue(), userId, null), userId);
586             if (ai != null) {
587                 return ai;
588             }
589         } catch (RemoteException e) {
590             throw e.rethrowFromSystemServer();
591         }
592 
593         throw new NameNotFoundException(className.toString());
594     }
595 
596     @Override
getServiceInfo(ComponentName className, int flags)597     public ServiceInfo getServiceInfo(ComponentName className, int flags)
598             throws NameNotFoundException {
599         return getServiceInfo(className, ComponentInfoFlags.of(flags));
600     }
601 
602     @Override
getServiceInfo(ComponentName className, ComponentInfoFlags flags)603     public ServiceInfo getServiceInfo(ComponentName className, ComponentInfoFlags flags)
604             throws NameNotFoundException {
605         final int userId = getUserId();
606         try {
607             ServiceInfo si = mPM.getServiceInfo(className,
608                     updateFlagsForComponent(flags.getValue(), userId, null), userId);
609             if (si != null) {
610                 return si;
611             }
612         } catch (RemoteException e) {
613             throw e.rethrowFromSystemServer();
614         }
615 
616         throw new NameNotFoundException(className.toString());
617     }
618 
619     @Override
getProviderInfo(ComponentName className, int flags)620     public ProviderInfo getProviderInfo(ComponentName className, int flags)
621             throws NameNotFoundException {
622         return getProviderInfo(className, ComponentInfoFlags.of(flags));
623     }
624 
625     @Override
getProviderInfo(ComponentName className, ComponentInfoFlags flags)626     public ProviderInfo getProviderInfo(ComponentName className, ComponentInfoFlags flags)
627             throws NameNotFoundException {
628         final int userId = getUserId();
629         try {
630             ProviderInfo pi = mPM.getProviderInfo(className,
631                     updateFlagsForComponent(flags.getValue(), userId, null), userId);
632             if (pi != null) {
633                 return pi;
634             }
635         } catch (RemoteException e) {
636             throw e.rethrowFromSystemServer();
637         }
638 
639         throw new NameNotFoundException(className.toString());
640     }
641 
642     @Override
getSystemSharedLibraryNames()643     public String[] getSystemSharedLibraryNames() {
644         try {
645             return mPM.getSystemSharedLibraryNames();
646         } catch (RemoteException e) {
647             throw e.rethrowFromSystemServer();
648         }
649     }
650 
651     /** @hide */
652     @Override
getSharedLibraries(int flags)653     public @NonNull List<SharedLibraryInfo> getSharedLibraries(int flags) {
654         return this.getSharedLibraries(PackageInfoFlags.of(flags));
655     }
656 
657     /** @hide
658      * @param flags */
659     @Override
getSharedLibraries(PackageInfoFlags flags)660     public @NonNull List<SharedLibraryInfo> getSharedLibraries(PackageInfoFlags flags) {
661         return getSharedLibrariesAsUser(flags, getUserId());
662     }
663 
664     /** @hide */
665     @Override
getSharedLibrariesAsUser(int flags, int userId)666     public @NonNull List<SharedLibraryInfo> getSharedLibrariesAsUser(int flags, int userId) {
667         return getSharedLibrariesAsUser(PackageInfoFlags.of(flags), userId);
668     }
669 
670     /** @hide */
671     @Override
672     @SuppressWarnings("unchecked")
getSharedLibrariesAsUser(PackageInfoFlags flags, int userId)673     public @NonNull List<SharedLibraryInfo> getSharedLibrariesAsUser(PackageInfoFlags flags,
674             int userId) {
675         try {
676             ParceledListSlice<SharedLibraryInfo> sharedLibs = mPM.getSharedLibraries(
677                     mContext.getOpPackageName(), flags.getValue(), userId);
678             if (sharedLibs == null) {
679                 return Collections.emptyList();
680             }
681             return sharedLibs.getList();
682         } catch (RemoteException e) {
683             throw e.rethrowFromSystemServer();
684         }
685     }
686 
687     @NonNull
688     @Override
getDeclaredSharedLibraries(@onNull String packageName, int flags)689     public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
690             int flags) {
691         return getDeclaredSharedLibraries(packageName, PackageInfoFlags.of(flags));
692     }
693 
694     @NonNull
695     @Override
696     @SuppressWarnings("unchecked")
getDeclaredSharedLibraries(@onNull String packageName, PackageInfoFlags flags)697     public List<SharedLibraryInfo> getDeclaredSharedLibraries(@NonNull String packageName,
698             PackageInfoFlags flags) {
699         try {
700             ParceledListSlice<SharedLibraryInfo> sharedLibraries = mPM.getDeclaredSharedLibraries(
701                     packageName, flags.getValue(), mContext.getUserId());
702             return sharedLibraries != null ? sharedLibraries.getList() : Collections.emptyList();
703         } catch (RemoteException e) {
704             throw e.rethrowFromSystemServer();
705         }
706     }
707 
708     /** @hide */
709     @Override
getServicesSystemSharedLibraryPackageName()710     public @NonNull String getServicesSystemSharedLibraryPackageName() {
711         try {
712             return mPM.getServicesSystemSharedLibraryPackageName();
713         } catch (RemoteException e) {
714             throw e.rethrowFromSystemServer();
715         }
716     }
717 
718     /**
719      * @hide
720      */
getSharedSystemSharedLibraryPackageName()721     public @NonNull String getSharedSystemSharedLibraryPackageName() {
722         try {
723             return mPM.getSharedSystemSharedLibraryPackageName();
724         } catch (RemoteException e) {
725             throw e.rethrowFromSystemServer();
726         }
727     }
728 
729     @Override
getChangedPackages(int sequenceNumber)730     public ChangedPackages getChangedPackages(int sequenceNumber) {
731         try {
732             return mPM.getChangedPackages(sequenceNumber, getUserId());
733         } catch (RemoteException e) {
734             throw e.rethrowFromSystemServer();
735         }
736     }
737 
738     @Override
739     @SuppressWarnings("unchecked")
getSystemAvailableFeatures()740     public FeatureInfo[] getSystemAvailableFeatures() {
741         try {
742             ParceledListSlice<FeatureInfo> parceledList =
743                     mPM.getSystemAvailableFeatures();
744             if (parceledList == null) {
745                 return new FeatureInfo[0];
746             }
747             final List<FeatureInfo> list = parceledList.getList();
748             final FeatureInfo[] res = new FeatureInfo[list.size()];
749             for (int i = 0; i < res.length; i++) {
750                 res[i] = list.get(i);
751             }
752             return res;
753         } catch (RemoteException e) {
754             throw e.rethrowFromSystemServer();
755         }
756     }
757 
758     @Override
hasSystemFeature(String name)759     public boolean hasSystemFeature(String name) {
760         return hasSystemFeature(name, 0);
761     }
762 
763     /**
764      * Identifies a single hasSystemFeature query.
765      */
766     @Immutable
767     private static final class HasSystemFeatureQuery {
768         public final String name;
769         public final int version;
HasSystemFeatureQuery(String n, int v)770         public HasSystemFeatureQuery(String n, int v) {
771             name = n;
772             version = v;
773         }
774         @Override
toString()775         public String toString() {
776             return String.format("HasSystemFeatureQuery(name=\"%s\", version=%d)",
777                     name, version);
778         }
779         @Override
equals(@ullable Object o)780         public boolean equals(@Nullable Object o) {
781             if (o instanceof HasSystemFeatureQuery) {
782                 HasSystemFeatureQuery r = (HasSystemFeatureQuery) o;
783                 return Objects.equals(name, r.name) &&  version == r.version;
784             } else {
785                 return false;
786             }
787         }
788         @Override
hashCode()789         public int hashCode() {
790             return Objects.hashCode(name) * 13 + version;
791         }
792     }
793 
794     // Make this cache relatively large.  There are many system features and
795     // none are ever invalidated.  MPTS tests suggests that the cache should
796     // hold at least 150 entries.
797     private final static PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>
798             mHasSystemFeatureCache =
799             new PropertyInvalidatedCache<HasSystemFeatureQuery, Boolean>(
800                 256, "cache_key.has_system_feature") {
801                 @Override
802                 public Boolean recompute(HasSystemFeatureQuery query) {
803                     try {
804                         return ActivityThread.currentActivityThread().getPackageManager().
805                             hasSystemFeature(query.name, query.version);
806                     } catch (RemoteException e) {
807                         throw e.rethrowFromSystemServer();
808                     }
809                 }
810             };
811 
812     @Override
hasSystemFeature(String name, int version)813     public boolean hasSystemFeature(String name, int version) {
814         return mHasSystemFeatureCache.query(new HasSystemFeatureQuery(name, version));
815     }
816 
817     /** @hide */
disableHasSystemFeatureCache()818     public void disableHasSystemFeatureCache() {
819         mHasSystemFeatureCache.disableLocal();
820     }
821 
822     /** @hide */
invalidateHasSystemFeatureCache()823     public static void invalidateHasSystemFeatureCache() {
824         mHasSystemFeatureCache.invalidateCache();
825     }
826 
827     @Override
checkPermission(String permName, String pkgName)828     public int checkPermission(String permName, String pkgName) {
829         return PermissionManager.checkPackageNamePermission(permName, pkgName, getUserId());
830     }
831 
832     @Override
isPermissionRevokedByPolicy(String permName, String pkgName)833     public boolean isPermissionRevokedByPolicy(String permName, String pkgName) {
834         return getPermissionManager().isPermissionRevokedByPolicy(pkgName, permName);
835     }
836 
837     /**
838      * @hide
839      */
840     @Override
getPermissionControllerPackageName()841     public String getPermissionControllerPackageName() {
842         if (mPermissionsControllerPackageName == null) {
843             try {
844                 mPermissionsControllerPackageName = mPM.getPermissionControllerPackageName();
845             } catch (RemoteException e) {
846                 throw e.rethrowFromSystemServer();
847             }
848         }
849         return mPermissionsControllerPackageName;
850     }
851 
852     /**
853      * @hide
854      */
855     @Override
getSdkSandboxPackageName()856     public String getSdkSandboxPackageName() {
857         try {
858             return mPM.getSdkSandboxPackageName();
859         } catch (RemoteException e) {
860             throw e.rethrowFromSystemServer();
861         }
862     }
863 
864     @Override
addPermission(PermissionInfo info)865     public boolean addPermission(PermissionInfo info) {
866         return getPermissionManager().addPermission(info, false);
867     }
868 
869     @Override
addPermissionAsync(PermissionInfo info)870     public boolean addPermissionAsync(PermissionInfo info) {
871         return getPermissionManager().addPermission(info, true);
872     }
873 
874     @Override
removePermission(String name)875     public void removePermission(String name) {
876         getPermissionManager().removePermission(name);
877     }
878 
879     @Override
grantRuntimePermission(String packageName, String permissionName, UserHandle user)880     public void grantRuntimePermission(String packageName, String permissionName,
881             UserHandle user) {
882         getPermissionManager().grantRuntimePermission(packageName, permissionName, user);
883     }
884 
885     @Override
revokeRuntimePermission(String packageName, String permName, UserHandle user)886     public void revokeRuntimePermission(String packageName, String permName, UserHandle user) {
887         revokeRuntimePermission(packageName, permName, user, null);
888     }
889 
890     @Override
revokeRuntimePermission(String packageName, String permName, UserHandle user, String reason)891     public void revokeRuntimePermission(String packageName, String permName, UserHandle user,
892             String reason) {
893         getPermissionManager().revokeRuntimePermission(packageName, permName, user, reason);
894     }
895 
896     @Override
getPermissionFlags(String permName, String packageName, UserHandle user)897     public int getPermissionFlags(String permName, String packageName, UserHandle user) {
898         return getPermissionManager().getPermissionFlags(packageName, permName, user);
899     }
900 
901     @Override
updatePermissionFlags(String permName, String packageName, int flagMask, int flagValues, UserHandle user)902     public void updatePermissionFlags(String permName, String packageName,
903             int flagMask, int flagValues, UserHandle user) {
904         getPermissionManager().updatePermissionFlags(packageName, permName, flagMask, flagValues,
905                 user);
906     }
907 
908     @Override
getWhitelistedRestrictedPermissions( @onNull String packageName, @PermissionWhitelistFlags int flags)909     public @NonNull Set<String> getWhitelistedRestrictedPermissions(
910             @NonNull String packageName, @PermissionWhitelistFlags int flags) {
911         return getPermissionManager().getAllowlistedRestrictedPermissions(packageName, flags);
912     }
913 
914     @Override
addWhitelistedRestrictedPermission(@onNull String packageName, @NonNull String permName, @PermissionWhitelistFlags int flags)915     public boolean addWhitelistedRestrictedPermission(@NonNull String packageName,
916             @NonNull String permName, @PermissionWhitelistFlags int flags) {
917         return getPermissionManager().addAllowlistedRestrictedPermission(packageName, permName,
918                 flags);
919     }
920 
921     @Override
setAutoRevokeWhitelisted(@onNull String packageName, boolean whitelisted)922     public boolean setAutoRevokeWhitelisted(@NonNull String packageName, boolean whitelisted) {
923         return getPermissionManager().setAutoRevokeExempted(packageName, whitelisted);
924     }
925 
926     @Override
isAutoRevokeWhitelisted(@onNull String packageName)927     public boolean isAutoRevokeWhitelisted(@NonNull String packageName) {
928         return getPermissionManager().isAutoRevokeExempted(packageName);
929     }
930 
931     @Override
removeWhitelistedRestrictedPermission(@onNull String packageName, @NonNull String permName, @PermissionWhitelistFlags int flags)932     public boolean removeWhitelistedRestrictedPermission(@NonNull String packageName,
933             @NonNull String permName, @PermissionWhitelistFlags int flags) {
934         return getPermissionManager().removeAllowlistedRestrictedPermission(packageName, permName,
935                 flags);
936     }
937 
938     @Override
939     @UnsupportedAppUsage
shouldShowRequestPermissionRationale(String permName)940     public boolean shouldShowRequestPermissionRationale(String permName) {
941         return getPermissionManager().shouldShowRequestPermissionRationale(permName);
942     }
943 
944     @Override
getBackgroundPermissionOptionLabel()945     public CharSequence getBackgroundPermissionOptionLabel() {
946         try {
947 
948             String permissionController = getPermissionControllerPackageName();
949             Context context =
950                     mContext.createPackageContext(permissionController, 0);
951 
952             int textId = context.getResources().getIdentifier(APP_PERMISSION_BUTTON_ALLOW_ALWAYS,
953                     "string", PERMISSION_CONTROLLER_RESOURCE_PACKAGE);
954             if (textId != 0) {
955                 return context.getText(textId);
956             }
957         } catch (NameNotFoundException e) {
958             Log.e(TAG, "Permission controller not found.", e);
959         }
960         return "";
961     }
962 
963     @Override
checkSignatures(String pkg1, String pkg2)964     public int checkSignatures(String pkg1, String pkg2) {
965         try {
966             return mPM.checkSignatures(pkg1, pkg2, getUserId());
967         } catch (RemoteException e) {
968             throw e.rethrowFromSystemServer();
969         }
970     }
971 
972     @Override
checkSignatures(int uid1, int uid2)973     public int checkSignatures(int uid1, int uid2) {
974         try {
975             return mPM.checkUidSignatures(uid1, uid2);
976         } catch (RemoteException e) {
977             throw e.rethrowFromSystemServer();
978         }
979     }
980 
981     @Override
hasSigningCertificate( String packageName, byte[] certificate, @CertificateInputType int type)982     public boolean hasSigningCertificate(
983             String packageName, byte[] certificate, @CertificateInputType int type) {
984         try {
985             return mPM.hasSigningCertificate(packageName, certificate, type);
986         } catch (RemoteException e) {
987             throw e.rethrowFromSystemServer();
988         }
989     }
990 
991     @Override
hasSigningCertificate( int uid, byte[] certificate, @CertificateInputType int type)992     public boolean hasSigningCertificate(
993             int uid, byte[] certificate, @CertificateInputType int type) {
994         try {
995             return mPM.hasUidSigningCertificate(uid, certificate, type);
996         } catch (RemoteException e) {
997             throw e.rethrowFromSystemServer();
998         }
999     }
1000 
encodeCertificates(List<Certificate> certs)1001     private static List<byte[]> encodeCertificates(List<Certificate> certs) throws
1002             CertificateEncodingException {
1003         if (certs == null) {
1004             return null;
1005         }
1006         List<byte[]> result = new ArrayList<>(certs.size());
1007         for (Certificate cert : certs) {
1008             if (!(cert instanceof X509Certificate)) {
1009                 throw new CertificateEncodingException("Only X509 certificates supported.");
1010             }
1011             result.add(cert.getEncoded());
1012         }
1013         return result;
1014     }
1015 
1016     @Override
requestChecksums(@onNull String packageName, boolean includeSplits, @Checksum.TypeMask int required, @NonNull List<Certificate> trustedInstallers, @NonNull OnChecksumsReadyListener onChecksumsReadyListener)1017     public void requestChecksums(@NonNull String packageName, boolean includeSplits,
1018             @Checksum.TypeMask int required, @NonNull List<Certificate> trustedInstallers,
1019             @NonNull OnChecksumsReadyListener onChecksumsReadyListener)
1020             throws CertificateEncodingException, NameNotFoundException {
1021         Objects.requireNonNull(packageName);
1022         Objects.requireNonNull(onChecksumsReadyListener);
1023         Objects.requireNonNull(trustedInstallers);
1024         if (trustedInstallers == TRUST_ALL) {
1025             trustedInstallers = null;
1026         } else if (trustedInstallers == TRUST_NONE) {
1027             trustedInstallers = Collections.emptyList();
1028         } else if (trustedInstallers.isEmpty()) {
1029             throw new IllegalArgumentException(
1030                     "trustedInstallers has to be one of TRUST_ALL/TRUST_NONE or a non-empty "
1031                             + "list of certificates.");
1032         }
1033         try {
1034             IOnChecksumsReadyListener onChecksumsReadyListenerDelegate =
1035                     new IOnChecksumsReadyListener.Stub() {
1036                         @Override
1037                         public void onChecksumsReady(List<ApkChecksum> checksums)
1038                                 throws RemoteException {
1039                             onChecksumsReadyListener.onChecksumsReady(checksums);
1040                         }
1041                     };
1042             mPM.requestPackageChecksums(packageName, includeSplits, DEFAULT_CHECKSUMS, required,
1043                     encodeCertificates(trustedInstallers), onChecksumsReadyListenerDelegate,
1044                     getUserId());
1045         } catch (ParcelableException e) {
1046             e.maybeRethrow(PackageManager.NameNotFoundException.class);
1047             throw new RuntimeException(e);
1048         } catch (RemoteException e) {
1049             throw e.rethrowFromSystemServer();
1050         }
1051     }
1052 
1053     /**
1054      * Wrap the cached value in a class that does deep compares on string
1055      * arrays.  The comparison is needed only for the verification mode of
1056      * PropertyInvalidatedCache; this mode is only enabled for debugging.
1057      * The return result is an array of strings but the order in the array
1058      * is not important.  To properly compare two arrays, the arrays are
1059      * sorted before the comparison.
1060      */
1061     private static class GetPackagesForUidResult {
1062         private final String [] mValue;
GetPackagesForUidResult(String []s)1063         GetPackagesForUidResult(String []s) {
1064             mValue = s;
1065         }
value()1066         public String[] value() {
1067             return mValue;
1068         }
1069         @Override
toString()1070         public String toString() {
1071             return Arrays.toString(mValue);
1072         }
1073         @Override
hashCode()1074         public int hashCode() {
1075             return Arrays.hashCode(mValue);
1076         }
1077         /**
1078          * Arrays.sort() throws an NPE if passed a null pointer, so nulls
1079          * are handled first.
1080          */
1081         @Override
equals(@ullable Object o)1082         public boolean equals(@Nullable Object o) {
1083             if (o instanceof GetPackagesForUidResult) {
1084                 String [] r = ((GetPackagesForUidResult) o).mValue;
1085                 String [] l = mValue;
1086                 if ((r == null) != (l == null)) {
1087                     return false;
1088                 } else if (r == null) {
1089                     return true;
1090                 }
1091                 // Both arrays are non-null.  Sort before comparing.
1092                 Arrays.sort(r);
1093                 Arrays.sort(l);
1094                 return Arrays.equals(l, r);
1095             } else {
1096                 return false;
1097             }
1098         }
1099     }
1100 
1101     private static final String CACHE_KEY_PACKAGES_FOR_UID_PROPERTY =
1102             "cache_key.get_packages_for_uid";
1103     private static final PropertyInvalidatedCache<Integer, GetPackagesForUidResult>
1104             mGetPackagesForUidCache =
1105             new PropertyInvalidatedCache<Integer, GetPackagesForUidResult>(
1106                 32, CACHE_KEY_PACKAGES_FOR_UID_PROPERTY) {
1107                 @Override
1108                 public GetPackagesForUidResult recompute(Integer uid) {
1109                     try {
1110                         return new GetPackagesForUidResult(
1111                             ActivityThread.currentActivityThread().
1112                             getPackageManager().getPackagesForUid(uid));
1113                     } catch (RemoteException e) {
1114                         throw e.rethrowFromSystemServer();
1115                     }
1116                 }
1117                 @Override
1118                 public String queryToString(Integer uid) {
1119                     return String.format("uid=%d", uid.intValue());
1120                 }
1121             };
1122 
1123     @Override
getPackagesForUid(int uid)1124     public String[] getPackagesForUid(int uid) {
1125         return mGetPackagesForUidCache.query(uid).value();
1126     }
1127 
1128     /** @hide */
disableGetPackagesForUidCache()1129     public static void disableGetPackagesForUidCache() {
1130         mGetPackagesForUidCache.disableLocal();
1131     }
1132 
1133     /** @hide */
invalidateGetPackagesForUidCache()1134     public static void invalidateGetPackagesForUidCache() {
1135         PropertyInvalidatedCache.invalidateCache(CACHE_KEY_PACKAGES_FOR_UID_PROPERTY);
1136     }
1137 
1138     @Override
getNameForUid(int uid)1139     public String getNameForUid(int uid) {
1140         try {
1141             return mPM.getNameForUid(uid);
1142         } catch (RemoteException e) {
1143             throw e.rethrowFromSystemServer();
1144         }
1145     }
1146 
1147     @Override
getNamesForUids(int[] uids)1148     public String[] getNamesForUids(int[] uids) {
1149         try {
1150             return mPM.getNamesForUids(uids);
1151         } catch (RemoteException e) {
1152             throw e.rethrowFromSystemServer();
1153         }
1154     }
1155 
1156     @Override
getUidForSharedUser(String sharedUserName)1157     public int getUidForSharedUser(String sharedUserName)
1158             throws NameNotFoundException {
1159         try {
1160             int uid = mPM.getUidForSharedUser(sharedUserName);
1161             if (uid != Process.INVALID_UID) {
1162                 return uid;
1163             }
1164         } catch (RemoteException e) {
1165             throw e.rethrowFromSystemServer();
1166         }
1167         throw new NameNotFoundException("No shared userid for user:"+sharedUserName);
1168     }
1169 
1170     @Override
getInstalledModules(int flags)1171     public List<ModuleInfo> getInstalledModules(int flags) {
1172         try {
1173             return mPM.getInstalledModules(flags);
1174         } catch (RemoteException e) {
1175             throw e.rethrowFromSystemServer();
1176         }
1177     }
1178 
1179     @Override
getModuleInfo(String packageName, int flags)1180     public ModuleInfo getModuleInfo(String packageName, int flags) throws NameNotFoundException {
1181         try {
1182             ModuleInfo mi = mPM.getModuleInfo(packageName, flags);
1183             if (mi != null) {
1184                 return mi;
1185             }
1186         } catch (RemoteException e) {
1187             throw e.rethrowFromSystemServer();
1188         }
1189 
1190         throw new NameNotFoundException("No module info for package: " + packageName);
1191     }
1192 
1193     @SuppressWarnings("unchecked")
1194     @Override
getInstalledPackages(int flags)1195     public List<PackageInfo> getInstalledPackages(int flags) {
1196         return getInstalledPackages(PackageInfoFlags.of(flags));
1197     }
1198 
1199     @SuppressWarnings("unchecked")
1200     @Override
getInstalledPackages(PackageInfoFlags flags)1201     public List<PackageInfo> getInstalledPackages(PackageInfoFlags flags) {
1202         return getInstalledPackagesAsUser(flags, getUserId());
1203     }
1204 
1205     /** @hide */
1206     @Override
1207     @SuppressWarnings("unchecked")
getInstalledPackagesAsUser(int flags, int userId)1208     public List<PackageInfo> getInstalledPackagesAsUser(int flags, int userId) {
1209         return getInstalledPackagesAsUser(PackageInfoFlags.of(flags), userId);
1210     }
1211 
1212     /** @hide */
1213     @Override
1214     @SuppressWarnings("unchecked")
getInstalledPackagesAsUser(PackageInfoFlags flags, int userId)1215     public List<PackageInfo> getInstalledPackagesAsUser(PackageInfoFlags flags, int userId) {
1216         try {
1217             ParceledListSlice<PackageInfo> parceledList =
1218                     mPM.getInstalledPackages(updateFlagsForPackage(flags.getValue(), userId),
1219                             userId);
1220             if (parceledList == null) {
1221                 return Collections.emptyList();
1222             }
1223             return parceledList.getList();
1224         } catch (RemoteException e) {
1225             throw e.rethrowFromSystemServer();
1226         }
1227     }
1228 
1229     @Override
1230     @NonNull
getAppMetadata(@onNull String packageName)1231     public PersistableBundle getAppMetadata(@NonNull String packageName)
1232             throws NameNotFoundException {
1233         PersistableBundle appMetadata = null;
1234         ParcelFileDescriptor pfd = null;
1235         try {
1236             pfd = mPM.getAppMetadataFd(packageName, getUserId());
1237         } catch (ParcelableException e) {
1238             e.maybeRethrow(NameNotFoundException.class);
1239             throw new RuntimeException(e);
1240         } catch (RemoteException e) {
1241             throw e.rethrowFromSystemServer();
1242         }
1243         if (pfd != null) {
1244             try (InputStream inputStream = new ParcelFileDescriptor.AutoCloseInputStream(pfd)) {
1245                 appMetadata = PersistableBundle.readFromStream(inputStream);
1246             } catch (IOException e) {
1247                 throw new RuntimeException(e);
1248             }
1249         }
1250 
1251         return appMetadata != null ? appMetadata : new PersistableBundle();
1252     }
1253 
1254     @SuppressWarnings("unchecked")
1255     @Override
getPackagesHoldingPermissions(String[] permissions, int flags)1256     public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions, int flags) {
1257         return this.getPackagesHoldingPermissions(permissions, PackageInfoFlags.of(flags));
1258     }
1259 
1260     @SuppressWarnings("unchecked")
1261     @Override
getPackagesHoldingPermissions(String[] permissions, PackageInfoFlags flags)1262     public List<PackageInfo> getPackagesHoldingPermissions(String[] permissions,
1263             PackageInfoFlags flags) {
1264         final int userId = getUserId();
1265         try {
1266             ParceledListSlice<PackageInfo> parceledList =
1267                     mPM.getPackagesHoldingPermissions(permissions,
1268                             updateFlagsForPackage(flags.getValue(), userId), userId);
1269             if (parceledList == null) {
1270                 return Collections.emptyList();
1271             }
1272             return parceledList.getList();
1273         } catch (RemoteException e) {
1274             throw e.rethrowFromSystemServer();
1275         }
1276     }
1277 
1278     @SuppressWarnings("unchecked")
1279     @Override
getInstalledApplications(int flags)1280     public List<ApplicationInfo> getInstalledApplications(int flags) {
1281         return getInstalledApplicationsAsUser(flags, getUserId());
1282     }
1283 
1284     @Override
getInstalledApplications(ApplicationInfoFlags flags)1285     public List<ApplicationInfo> getInstalledApplications(ApplicationInfoFlags flags) {
1286         return getInstalledApplicationsAsUser(flags, getUserId());
1287     }
1288 
1289     /** @hide */
1290     @SuppressWarnings("unchecked")
1291     @Override
getInstalledApplicationsAsUser(int flags, int userId)1292     public List<ApplicationInfo> getInstalledApplicationsAsUser(int flags, int userId) {
1293         return getInstalledApplicationsAsUser(ApplicationInfoFlags.of(flags), userId);
1294     }
1295 
1296     /** @hide */
1297     @SuppressWarnings("unchecked")
1298     @Override
getInstalledApplicationsAsUser(ApplicationInfoFlags flags, int userId)1299     public List<ApplicationInfo> getInstalledApplicationsAsUser(ApplicationInfoFlags flags,
1300             int userId) {
1301         try {
1302             ParceledListSlice<ApplicationInfo> parceledList =
1303                     mPM.getInstalledApplications(updateFlagsForApplication(
1304                             flags.getValue(), userId), userId);
1305             if (parceledList == null) {
1306                 return Collections.emptyList();
1307             }
1308             return parceledList.getList();
1309         } catch (RemoteException e) {
1310             throw e.rethrowFromSystemServer();
1311         }
1312     }
1313 
1314     /** @hide */
1315     @SuppressWarnings("unchecked")
1316     @Override
getInstantApps()1317     public List<InstantAppInfo> getInstantApps() {
1318         try {
1319             ParceledListSlice<InstantAppInfo> slice = mPM.getInstantApps(getUserId());
1320             if (slice != null) {
1321                 return slice.getList();
1322             }
1323             return Collections.emptyList();
1324         } catch (RemoteException e) {
1325             throw e.rethrowFromSystemServer();
1326         }
1327     }
1328 
1329     /** @hide */
1330     @Override
getInstantAppIcon(String packageName)1331     public Drawable getInstantAppIcon(String packageName) {
1332         try {
1333             Bitmap bitmap = mPM.getInstantAppIcon(packageName, getUserId());
1334             if (bitmap != null) {
1335                 return new BitmapDrawable(null, bitmap);
1336             }
1337             return null;
1338         } catch (RemoteException e) {
1339             throw e.rethrowFromSystemServer();
1340         }
1341     }
1342 
1343     @Override
isInstantApp()1344     public boolean isInstantApp() {
1345         return isInstantApp(mContext.getPackageName());
1346     }
1347 
1348     @Override
isInstantApp(String packageName)1349     public boolean isInstantApp(String packageName) {
1350         try {
1351             return mPM.isInstantApp(packageName, getUserId());
1352         } catch (RemoteException e) {
1353             throw e.rethrowFromSystemServer();
1354         }
1355     }
1356 
getInstantAppCookieMaxBytes()1357     public int getInstantAppCookieMaxBytes() {
1358         return Settings.Global.getInt(mContext.getContentResolver(),
1359                 Settings.Global.EPHEMERAL_COOKIE_MAX_SIZE_BYTES,
1360                 DEFAULT_EPHEMERAL_COOKIE_MAX_SIZE_BYTES);
1361     }
1362 
1363     @Override
getInstantAppCookieMaxSize()1364     public int getInstantAppCookieMaxSize() {
1365         return getInstantAppCookieMaxBytes();
1366     }
1367 
1368     @Override
getInstantAppCookie()1369     public @NonNull byte[] getInstantAppCookie() {
1370         try {
1371             final byte[] cookie = mPM.getInstantAppCookie(mContext.getPackageName(), getUserId());
1372             if (cookie != null) {
1373                 return cookie;
1374             } else {
1375                 return EmptyArray.BYTE;
1376             }
1377         } catch (RemoteException e) {
1378             throw e.rethrowFromSystemServer();
1379         }
1380     }
1381 
1382     @Override
clearInstantAppCookie()1383     public void clearInstantAppCookie() {
1384         updateInstantAppCookie(null);
1385     }
1386 
1387     @Override
updateInstantAppCookie(@onNull byte[] cookie)1388     public void updateInstantAppCookie(@NonNull byte[] cookie) {
1389         if (cookie != null && cookie.length > getInstantAppCookieMaxBytes()) {
1390             throw new IllegalArgumentException("instant cookie longer than "
1391                     + getInstantAppCookieMaxBytes());
1392         }
1393         try {
1394             mPM.setInstantAppCookie(mContext.getPackageName(), cookie, getUserId());
1395         } catch (RemoteException e) {
1396             throw e.rethrowFromSystemServer();
1397         }
1398     }
1399 
1400     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
1401     @Override
setInstantAppCookie(@onNull byte[] cookie)1402     public boolean setInstantAppCookie(@NonNull byte[] cookie) {
1403         try {
1404             return mPM.setInstantAppCookie(mContext.getPackageName(), cookie, getUserId());
1405         } catch (RemoteException e) {
1406             throw e.rethrowFromSystemServer();
1407         }
1408     }
1409 
1410     @Override
resolveActivity(Intent intent, int flags)1411     public ResolveInfo resolveActivity(Intent intent, int flags) {
1412         return resolveActivity(intent, ResolveInfoFlags.of(flags));
1413     }
1414 
1415     @Override
resolveActivity(Intent intent, ResolveInfoFlags flags)1416     public ResolveInfo resolveActivity(Intent intent, ResolveInfoFlags flags) {
1417         return resolveActivityAsUser(intent, flags, getUserId());
1418     }
1419 
1420     @Override
resolveActivityAsUser(Intent intent, int flags, int userId)1421     public ResolveInfo resolveActivityAsUser(Intent intent, int flags, int userId) {
1422         return resolveActivityAsUser(intent, ResolveInfoFlags.of(flags), userId);
1423     }
1424 
1425     @Override
resolveActivityAsUser(Intent intent, ResolveInfoFlags flags, int userId)1426     public ResolveInfo resolveActivityAsUser(Intent intent, ResolveInfoFlags flags, int userId) {
1427         try {
1428             return mPM.resolveIntent(
1429                 intent,
1430                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1431                 updateFlagsForComponent(flags.getValue(), userId, intent),
1432                 userId);
1433         } catch (RemoteException e) {
1434             throw e.rethrowFromSystemServer();
1435         }
1436     }
1437 
1438     @Override
queryIntentActivities(Intent intent, int flags)1439     public List<ResolveInfo> queryIntentActivities(Intent intent, int flags) {
1440         return queryIntentActivities(intent, ResolveInfoFlags.of(flags));
1441     }
1442 
1443     @Override
queryIntentActivities(Intent intent, ResolveInfoFlags flags)1444     public List<ResolveInfo> queryIntentActivities(Intent intent, ResolveInfoFlags flags) {
1445         return queryIntentActivitiesAsUser(intent, flags, getUserId());
1446     }
1447 
1448     /** @hide Same as above but for a specific user */
1449     @Override
queryIntentActivitiesAsUser(Intent intent, int flags, int userId)1450     public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent, int flags, int userId) {
1451         return queryIntentActivitiesAsUser(intent, ResolveInfoFlags.of(flags), userId);
1452     }
1453 
1454     /** @hide Same as above but for a specific user */
1455     @Override
1456     @SuppressWarnings("unchecked")
queryIntentActivitiesAsUser(Intent intent, ResolveInfoFlags flags, int userId)1457     public List<ResolveInfo> queryIntentActivitiesAsUser(Intent intent, ResolveInfoFlags flags,
1458             int userId) {
1459         try {
1460             ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentActivities(
1461                     intent,
1462                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1463                     updateFlagsForComponent(flags.getValue(), userId, intent),
1464                     userId);
1465             if (parceledList == null) {
1466                 return Collections.emptyList();
1467             }
1468             return parceledList.getList();
1469         } catch (RemoteException e) {
1470             throw e.rethrowFromSystemServer();
1471         }
1472     }
1473 
1474     @Override
queryIntentActivityOptions(ComponentName caller, Intent[] specifics, Intent intent, int flags)1475     public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller, Intent[] specifics,
1476             Intent intent, int flags) {
1477         return queryIntentActivityOptions(caller,
1478                 specifics == null ? null : new ArrayList<>(Arrays.asList(specifics)),
1479                 intent, ResolveInfoFlags.of(flags));
1480     }
1481 
1482     @Override
1483     @SuppressWarnings("unchecked")
queryIntentActivityOptions(ComponentName caller, List<Intent> specifics, Intent intent, ResolveInfoFlags flags)1484     public List<ResolveInfo> queryIntentActivityOptions(ComponentName caller,
1485             List<Intent> specifics, Intent intent, ResolveInfoFlags flags) {
1486         final int userId = getUserId();
1487         final ContentResolver resolver = mContext.getContentResolver();
1488 
1489         String[] specificTypes = null;
1490         if (specifics != null) {
1491             final int numSpecifics = specifics.size();
1492             for (int i = 0; i < numSpecifics; i++) {
1493                 Intent sp = specifics.get(i);
1494                 if (sp != null) {
1495                     String t = sp.resolveTypeIfNeeded(resolver);
1496                     if (t != null) {
1497                         if (specificTypes == null) {
1498                             specificTypes = new String[numSpecifics];
1499                         }
1500                         specificTypes[i] = t;
1501                     }
1502                 }
1503             }
1504         }
1505 
1506         try {
1507             ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentActivityOptions(
1508                     caller,
1509                     specifics == null ? null : specifics.toArray(new Intent[0]),
1510                     specificTypes,
1511                     intent,
1512                     intent.resolveTypeIfNeeded(resolver),
1513                     updateFlagsForComponent(flags.getValue(), userId, intent),
1514                     userId);
1515             if (parceledList == null) {
1516                 return Collections.emptyList();
1517             }
1518             return parceledList.getList();
1519         } catch (RemoteException e) {
1520             throw e.rethrowFromSystemServer();
1521         }
1522     }
1523 
1524     /**
1525      * @hide
1526      */
1527     @Override
queryBroadcastReceiversAsUser(Intent intent, int flags, int userId)1528     public List<ResolveInfo> queryBroadcastReceiversAsUser(Intent intent, int flags, int userId) {
1529         return queryBroadcastReceiversAsUser(intent, ResolveInfoFlags.of(flags), userId);
1530     }
1531 
1532     /**
1533      * @hide
1534      */
1535     @Override
1536     @SuppressWarnings("unchecked")
queryBroadcastReceiversAsUser(Intent intent, ResolveInfoFlags flags, int userId)1537     public List<ResolveInfo> queryBroadcastReceiversAsUser(Intent intent, ResolveInfoFlags flags,
1538             int userId) {
1539         try {
1540             ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentReceivers(
1541                     intent,
1542                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1543                     updateFlagsForComponent(flags.getValue(), userId, intent),
1544                     userId);
1545             if (parceledList == null) {
1546                 return Collections.emptyList();
1547             }
1548             return parceledList.getList();
1549         } catch (RemoteException e) {
1550             throw e.rethrowFromSystemServer();
1551         }
1552     }
1553 
1554     @Override
queryBroadcastReceivers(Intent intent, int flags)1555     public List<ResolveInfo> queryBroadcastReceivers(Intent intent, int flags) {
1556         return queryBroadcastReceivers(intent, ResolveInfoFlags.of(flags));
1557     }
1558 
1559     @Override
queryBroadcastReceivers(Intent intent, ResolveInfoFlags flags)1560     public List<ResolveInfo> queryBroadcastReceivers(Intent intent, ResolveInfoFlags flags) {
1561         return queryBroadcastReceiversAsUser(intent, flags, getUserId());
1562     }
1563 
1564     @Override
resolveServiceAsUser(Intent intent, int flags, @UserIdInt int userId)1565     public ResolveInfo resolveServiceAsUser(Intent intent, int flags, @UserIdInt int userId) {
1566         return resolveServiceAsUser(intent, ResolveInfoFlags.of(flags), userId);
1567     }
1568 
1569     @Override
resolveServiceAsUser(Intent intent, ResolveInfoFlags flags, @UserIdInt int userId)1570     public ResolveInfo resolveServiceAsUser(Intent intent, ResolveInfoFlags flags,
1571             @UserIdInt int userId) {
1572         try {
1573             return mPM.resolveService(
1574                 intent,
1575                 intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1576                 updateFlagsForComponent(flags.getValue(), userId, intent),
1577                 userId);
1578         } catch (RemoteException e) {
1579             throw e.rethrowFromSystemServer();
1580         }
1581     }
1582 
1583     @Override
resolveService(Intent intent, int flags)1584     public ResolveInfo resolveService(Intent intent, int flags) {
1585         return resolveService(intent, ResolveInfoFlags.of(flags));
1586     }
1587 
1588     @Override
resolveService(Intent intent, ResolveInfoFlags flags)1589     public ResolveInfo resolveService(Intent intent, ResolveInfoFlags flags) {
1590         return resolveServiceAsUser(intent, flags, getUserId());
1591     }
1592 
1593     @Override
queryIntentServicesAsUser(Intent intent, int flags, int userId)1594     public List<ResolveInfo> queryIntentServicesAsUser(Intent intent, int flags, int userId) {
1595         return queryIntentServicesAsUser(intent, ResolveInfoFlags.of(flags), userId);
1596     }
1597 
1598     @Override
1599     @SuppressWarnings("unchecked")
queryIntentServicesAsUser(Intent intent, ResolveInfoFlags flags, int userId)1600     public List<ResolveInfo> queryIntentServicesAsUser(Intent intent, ResolveInfoFlags flags,
1601             int userId) {
1602         try {
1603             ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentServices(
1604                     intent,
1605                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1606                     updateFlagsForComponent(flags.getValue(), userId, intent),
1607                     userId);
1608             if (parceledList == null) {
1609                 return Collections.emptyList();
1610             }
1611             return parceledList.getList();
1612         } catch (RemoteException e) {
1613             throw e.rethrowFromSystemServer();
1614         }
1615     }
1616 
1617     @Override
queryIntentServices(Intent intent, int flags)1618     public List<ResolveInfo> queryIntentServices(Intent intent, int flags) {
1619         return queryIntentServices(intent, ResolveInfoFlags.of(flags));
1620     }
1621 
1622     @Override
queryIntentServices(Intent intent, ResolveInfoFlags flags)1623     public List<ResolveInfo> queryIntentServices(Intent intent, ResolveInfoFlags flags) {
1624         return queryIntentServicesAsUser(intent, flags, getUserId());
1625     }
1626 
1627     @Override
queryIntentContentProvidersAsUser( Intent intent, int flags, int userId)1628     public List<ResolveInfo> queryIntentContentProvidersAsUser(
1629             Intent intent, int flags, int userId) {
1630         return queryIntentContentProvidersAsUser(intent, ResolveInfoFlags.of(flags), userId);
1631     }
1632 
1633     @Override
1634     @SuppressWarnings("unchecked")
queryIntentContentProvidersAsUser( Intent intent, ResolveInfoFlags flags, int userId)1635     public List<ResolveInfo> queryIntentContentProvidersAsUser(
1636             Intent intent, ResolveInfoFlags flags, int userId) {
1637         try {
1638             ParceledListSlice<ResolveInfo> parceledList = mPM.queryIntentContentProviders(
1639                     intent,
1640                     intent.resolveTypeIfNeeded(mContext.getContentResolver()),
1641                     updateFlagsForComponent(flags.getValue(), userId, intent),
1642                     userId);
1643             if (parceledList == null) {
1644                 return Collections.emptyList();
1645             }
1646             return parceledList.getList();
1647         } catch (RemoteException e) {
1648             throw e.rethrowFromSystemServer();
1649         }
1650     }
1651 
1652     @Override
queryIntentContentProviders(Intent intent, int flags)1653     public List<ResolveInfo> queryIntentContentProviders(Intent intent, int flags) {
1654         return queryIntentContentProviders(intent, ResolveInfoFlags.of(flags));
1655     }
1656 
1657     @Override
queryIntentContentProviders(Intent intent, ResolveInfoFlags flags)1658     public List<ResolveInfo> queryIntentContentProviders(Intent intent, ResolveInfoFlags flags) {
1659         return queryIntentContentProvidersAsUser(intent, flags, getUserId());
1660     }
1661 
1662     @Override
resolveContentProvider(String name, int flags)1663     public ProviderInfo resolveContentProvider(String name, int flags) {
1664         return resolveContentProvider(name, ComponentInfoFlags.of(flags));
1665     }
1666 
1667     @Override
resolveContentProvider(String name, ComponentInfoFlags flags)1668     public ProviderInfo resolveContentProvider(String name, ComponentInfoFlags flags) {
1669         return resolveContentProviderAsUser(name, flags, getUserId());
1670     }
1671 
1672     /** @hide **/
1673     @Override
resolveContentProviderAsUser(String name, int flags, int userId)1674     public ProviderInfo resolveContentProviderAsUser(String name, int flags, int userId) {
1675         return resolveContentProviderAsUser(name, ComponentInfoFlags.of(flags), userId);
1676     }
1677 
1678     /** @hide **/
1679     @Override
resolveContentProviderAsUser(String name, ComponentInfoFlags flags, int userId)1680     public ProviderInfo resolveContentProviderAsUser(String name, ComponentInfoFlags flags,
1681             int userId) {
1682         try {
1683             return mPM.resolveContentProvider(name,
1684                     updateFlagsForComponent(flags.getValue(), userId, null), userId);
1685         } catch (RemoteException e) {
1686             throw e.rethrowFromSystemServer();
1687         }
1688     }
1689 
1690     @Override
queryContentProviders(String processName, int uid, int flags)1691     public List<ProviderInfo> queryContentProviders(String processName, int uid, int flags) {
1692         return queryContentProviders(processName, uid, ComponentInfoFlags.of(flags));
1693     }
1694 
1695     @Override
queryContentProviders(String processName, int uid, ComponentInfoFlags flags)1696     public List<ProviderInfo> queryContentProviders(String processName, int uid,
1697             ComponentInfoFlags flags) {
1698         return queryContentProviders(processName, uid, flags, null);
1699     }
1700 
1701     @Override
queryContentProviders(String processName, int uid, int flags, String metaDataKey)1702     public List<ProviderInfo> queryContentProviders(String processName,
1703             int uid, int flags, String metaDataKey) {
1704         return queryContentProviders(processName, uid, ComponentInfoFlags.of(flags), metaDataKey);
1705     }
1706 
1707     @Override
1708     @SuppressWarnings("unchecked")
queryContentProviders(String processName, int uid, ComponentInfoFlags flags, String metaDataKey)1709     public List<ProviderInfo> queryContentProviders(String processName,
1710             int uid, ComponentInfoFlags flags, String metaDataKey) {
1711         try {
1712             ParceledListSlice<ProviderInfo> slice = mPM.queryContentProviders(processName, uid,
1713                     updateFlagsForComponent(flags.getValue(), UserHandle.getUserId(uid),
1714                             null), metaDataKey);
1715             return slice != null ? slice.getList() : Collections.emptyList();
1716         } catch (RemoteException e) {
1717             throw e.rethrowFromSystemServer();
1718         }
1719     }
1720 
1721     @Override
getInstrumentationInfo( ComponentName className, int flags)1722     public InstrumentationInfo getInstrumentationInfo(
1723         ComponentName className, int flags)
1724             throws NameNotFoundException {
1725         try {
1726             InstrumentationInfo ii = mPM.getInstrumentationInfoAsUser(
1727                     className, flags, getUserId());
1728             if (ii != null) {
1729                 return ii;
1730             }
1731         } catch (RemoteException e) {
1732             throw e.rethrowFromSystemServer();
1733         }
1734 
1735         throw new NameNotFoundException(className.toString());
1736     }
1737 
1738     @Override
1739     @SuppressWarnings("unchecked")
queryInstrumentation( String targetPackage, int flags)1740     public List<InstrumentationInfo> queryInstrumentation(
1741         String targetPackage, int flags) {
1742         try {
1743             ParceledListSlice<InstrumentationInfo> parceledList =
1744                     mPM.queryInstrumentationAsUser(targetPackage, flags, getUserId());
1745             if (parceledList == null) {
1746                 return Collections.emptyList();
1747             }
1748             return parceledList.getList();
1749         } catch (RemoteException e) {
1750             throw e.rethrowFromSystemServer();
1751         }
1752     }
1753 
1754     @Nullable
1755     @Override
getDrawable(String packageName, @DrawableRes int resId, @Nullable ApplicationInfo appInfo)1756     public Drawable getDrawable(String packageName, @DrawableRes int resId,
1757             @Nullable ApplicationInfo appInfo) {
1758         final ResourceName name = new ResourceName(packageName, resId);
1759         final Drawable cachedIcon = getCachedIcon(name);
1760         if (cachedIcon != null) {
1761             return cachedIcon;
1762         }
1763 
1764         if (appInfo == null) {
1765             try {
1766                 appInfo = getApplicationInfo(packageName, sDefaultFlags);
1767             } catch (NameNotFoundException e) {
1768                 return null;
1769             }
1770         }
1771 
1772         if (resId != 0) {
1773             try {
1774                 final Resources r = getResourcesForApplication(appInfo);
1775                 final Drawable dr = r.getDrawable(resId, null);
1776                 if (dr != null) {
1777                     putCachedIcon(name, dr);
1778                 }
1779 
1780                 if (false) {
1781                     RuntimeException e = new RuntimeException("here");
1782                     e.fillInStackTrace();
1783                     Log.w(TAG, "Getting drawable 0x" + Integer.toHexString(resId)
1784                                     + " from package " + packageName
1785                                     + ": app scale=" + r.getCompatibilityInfo().applicationScale
1786                                     + ", caller scale=" + mContext.getResources()
1787                                     .getCompatibilityInfo().applicationScale,
1788                             e);
1789                 }
1790                 if (DEBUG_ICONS) {
1791                     Log.v(TAG, "Getting drawable 0x"
1792                             + Integer.toHexString(resId) + " from " + r
1793                             + ": " + dr);
1794                 }
1795                 return dr;
1796             } catch (NameNotFoundException e) {
1797                 Log.w("PackageManager", "Failure retrieving resources for "
1798                         + appInfo.packageName);
1799             } catch (Resources.NotFoundException e) {
1800                 Log.w("PackageManager", "Failure retrieving resources for "
1801                         + appInfo.packageName + ": " + e.getMessage());
1802             } catch (Exception e) {
1803                 // If an exception was thrown, fall through to return
1804                 // default icon.
1805                 Log.w("PackageManager", "Failure retrieving icon 0x"
1806                         + Integer.toHexString(resId) + " in package "
1807                         + packageName, e);
1808             }
1809         }
1810 
1811         return null;
1812     }
1813 
getActivityIcon(ComponentName activityName)1814     @Override public Drawable getActivityIcon(ComponentName activityName)
1815             throws NameNotFoundException {
1816         return getActivityInfo(activityName, sDefaultFlags).loadIcon(this);
1817     }
1818 
getActivityIcon(Intent intent)1819     @Override public Drawable getActivityIcon(Intent intent)
1820             throws NameNotFoundException {
1821         if (intent.getComponent() != null) {
1822             return getActivityIcon(intent.getComponent());
1823         }
1824 
1825         ResolveInfo info = resolveActivity(intent, MATCH_DEFAULT_ONLY);
1826         if (info != null) {
1827             return info.activityInfo.loadIcon(this);
1828         }
1829 
1830         throw new NameNotFoundException(intent.toUri(0));
1831     }
1832 
getDefaultActivityIcon()1833     @Override public Drawable getDefaultActivityIcon() {
1834         return mContext.getDrawable(com.android.internal.R.drawable.sym_def_app_icon);
1835     }
1836 
getApplicationIcon(ApplicationInfo info)1837     @Override public Drawable getApplicationIcon(ApplicationInfo info) {
1838         return info.loadIcon(this);
1839     }
1840 
getApplicationIcon(String packageName)1841     @Override public Drawable getApplicationIcon(String packageName)
1842             throws NameNotFoundException {
1843         return getApplicationIcon(getApplicationInfo(packageName, sDefaultFlags));
1844     }
1845 
1846     @Override
getActivityBanner(ComponentName activityName)1847     public Drawable getActivityBanner(ComponentName activityName)
1848             throws NameNotFoundException {
1849         return getActivityInfo(activityName, sDefaultFlags).loadBanner(this);
1850     }
1851 
1852     @Override
getActivityBanner(Intent intent)1853     public Drawable getActivityBanner(Intent intent)
1854             throws NameNotFoundException {
1855         if (intent.getComponent() != null) {
1856             return getActivityBanner(intent.getComponent());
1857         }
1858 
1859         ResolveInfo info = resolveActivity(
1860                 intent, MATCH_DEFAULT_ONLY);
1861         if (info != null) {
1862             return info.activityInfo.loadBanner(this);
1863         }
1864 
1865         throw new NameNotFoundException(intent.toUri(0));
1866     }
1867 
1868     @Override
getApplicationBanner(ApplicationInfo info)1869     public Drawable getApplicationBanner(ApplicationInfo info) {
1870         return info.loadBanner(this);
1871     }
1872 
1873     @Override
getApplicationBanner(String packageName)1874     public Drawable getApplicationBanner(String packageName)
1875             throws NameNotFoundException {
1876         return getApplicationBanner(getApplicationInfo(packageName, sDefaultFlags));
1877     }
1878 
1879     @Override
getActivityLogo(ComponentName activityName)1880     public Drawable getActivityLogo(ComponentName activityName)
1881             throws NameNotFoundException {
1882         return getActivityInfo(activityName, sDefaultFlags).loadLogo(this);
1883     }
1884 
1885     @Override
getActivityLogo(Intent intent)1886     public Drawable getActivityLogo(Intent intent)
1887             throws NameNotFoundException {
1888         if (intent.getComponent() != null) {
1889             return getActivityLogo(intent.getComponent());
1890         }
1891 
1892         ResolveInfo info = resolveActivity(intent, MATCH_DEFAULT_ONLY);
1893         if (info != null) {
1894             return info.activityInfo.loadLogo(this);
1895         }
1896 
1897         throw new NameNotFoundException(intent.toUri(0));
1898     }
1899 
1900     @Override
getApplicationLogo(ApplicationInfo info)1901     public Drawable getApplicationLogo(ApplicationInfo info) {
1902         return info.loadLogo(this);
1903     }
1904 
1905     @Override
getApplicationLogo(String packageName)1906     public Drawable getApplicationLogo(String packageName)
1907             throws NameNotFoundException {
1908         return getApplicationLogo(getApplicationInfo(packageName, sDefaultFlags));
1909     }
1910 
1911     @Override
getUserBadgedIcon(Drawable icon, UserHandle user)1912     public Drawable getUserBadgedIcon(Drawable icon, UserHandle user) {
1913         if (!hasUserBadge(user.getIdentifier())) {
1914             return icon;
1915         }
1916 
1917         final Drawable badgeForeground = getDevicePolicyManager().getResources().getDrawable(
1918                 getUpdatableUserIconBadgeId(user),
1919                 SOLID_COLORED,
1920                 () -> getDefaultUserIconBadge(user));
1921 
1922         Drawable badge = new LauncherIcons(mContext).getBadgeDrawable(
1923                 badgeForeground,
1924                 getUserBadgeColor(user, false));
1925         return getBadgedDrawable(icon, badge, null, true);
1926     }
1927 
getUpdatableUserIconBadgeId(UserHandle user)1928     private String getUpdatableUserIconBadgeId(UserHandle user) {
1929         return getUserManager().isManagedProfile(user.getIdentifier())
1930                 ? WORK_PROFILE_ICON_BADGE : UNDEFINED;
1931     }
1932 
getDefaultUserIconBadge(UserHandle user)1933     private Drawable getDefaultUserIconBadge(UserHandle user) {
1934         return mContext.getDrawable(getUserManager().getUserIconBadgeResId(user.getIdentifier()));
1935     }
1936 
1937     @Override
getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user, Rect badgeLocation, int badgeDensity)1938     public Drawable getUserBadgedDrawableForDensity(Drawable drawable, UserHandle user,
1939             Rect badgeLocation, int badgeDensity) {
1940         Drawable badgeDrawable = getUserBadgeForDensity(user, badgeDensity);
1941         if (badgeDrawable == null) {
1942             return drawable;
1943         }
1944         return getBadgedDrawable(drawable, badgeDrawable, badgeLocation, true);
1945     }
1946 
1947     /**
1948      * Returns the color of the user's actual badge (not the badge's shadow).
1949      * @param checkTheme whether to check the theme to determine the badge color. This should be
1950      *                   true if the background is determined by the theme. Otherwise, if
1951      *                   checkTheme is false, returns the color assuming a light background.
1952      */
getUserBadgeColor(UserHandle user, boolean checkTheme)1953     private int getUserBadgeColor(UserHandle user, boolean checkTheme) {
1954         if (checkTheme && mContext.getResources().getConfiguration().isNightModeActive()) {
1955             return getUserManager().getUserBadgeDarkColor(user.getIdentifier());
1956         }
1957         return getUserManager().getUserBadgeColor(user.getIdentifier());
1958     }
1959 
1960     @Override
getUserBadgeForDensity(UserHandle user, int density)1961     public Drawable getUserBadgeForDensity(UserHandle user, int density) {
1962         // This is part of the shadow, not the main color, and is not actually corp-specific.
1963         Drawable badgeColor = getProfileIconForDensity(user,
1964                 com.android.internal.R.drawable.ic_corp_badge_color, density);
1965         if (badgeColor == null) {
1966             return null;
1967         }
1968 
1969         final Drawable badgeForeground = getDevicePolicyManager().getResources()
1970                 .getDrawableForDensity(
1971                         getUpdatableUserBadgeId(user),
1972                         SOLID_COLORED,
1973                         density,
1974                         () -> getDefaultUserBadgeForDensity(user, density));
1975 
1976         badgeForeground.setTint(getUserBadgeColor(user, false));
1977         Drawable badge = new LayerDrawable(new Drawable[] {badgeColor, badgeForeground });
1978         return badge;
1979     }
1980 
getUpdatableUserBadgeId(UserHandle user)1981     private String getUpdatableUserBadgeId(UserHandle user) {
1982         return getUserManager().isManagedProfile(user.getIdentifier())
1983                 ? WORK_PROFILE_ICON : UNDEFINED;
1984     }
1985 
getDefaultUserBadgeForDensity(UserHandle user, int density)1986     private Drawable getDefaultUserBadgeForDensity(UserHandle user, int density) {
1987         return getDrawableForDensity(
1988                 getUserManager().getUserBadgeResId(user.getIdentifier()), density);
1989     }
1990 
1991     /**
1992      * Returns the badge color based on whether device has dark theme enabled or not.
1993      */
1994     @Override
getUserBadgeForDensityNoBackground(UserHandle user, int density)1995     public Drawable getUserBadgeForDensityNoBackground(UserHandle user, int density) {
1996         if (!hasUserBadge(user.getIdentifier())) {
1997             return null;
1998         }
1999 
2000         final Drawable badge = getDevicePolicyManager().getResources().getDrawableForDensity(
2001                 getUpdatableUserBadgeId(user),
2002                 SOLID_NOT_COLORED,
2003                 density,
2004                 () -> getDefaultUserBadgeNoBackgroundForDensity(user, density));
2005 
2006         if (badge != null) {
2007             badge.setTint(getUserBadgeColor(user, true));
2008         }
2009         return badge;
2010     }
2011 
getDefaultUserBadgeNoBackgroundForDensity(UserHandle user, int density)2012     private Drawable getDefaultUserBadgeNoBackgroundForDensity(UserHandle user, int density) {
2013         return getDrawableForDensity(
2014                 getUserManager().getUserBadgeNoBackgroundResId(user.getIdentifier()), density);
2015     }
2016 
getDrawableForDensity(int drawableId, int density)2017     private Drawable getDrawableForDensity(int drawableId, int density) {
2018         if (density <= 0) {
2019             density = mContext.getResources().getDisplayMetrics().densityDpi;
2020         }
2021         return mContext.getResources().getDrawableForDensity(drawableId, density);
2022     }
2023 
getProfileIconForDensity(UserHandle user, int drawableId, int density)2024     private Drawable getProfileIconForDensity(UserHandle user, int drawableId, int density) {
2025         if (hasUserBadge(user.getIdentifier())) {
2026             return getDrawableForDensity(drawableId, density);
2027         }
2028         return null;
2029     }
2030 
2031     @Override
getUserBadgedLabel(CharSequence label, UserHandle user)2032     public CharSequence getUserBadgedLabel(CharSequence label, UserHandle user) {
2033         return getUserManager().getBadgedLabelForUser(label, user);
2034     }
2035 
2036     @Override
getResourcesForActivity(ComponentName activityName)2037     public Resources getResourcesForActivity(ComponentName activityName)
2038             throws NameNotFoundException {
2039         return getResourcesForApplication(
2040             getActivityInfo(activityName, sDefaultFlags).applicationInfo);
2041     }
2042 
2043     @Override
getResourcesForApplication(@onNull ApplicationInfo app)2044     public Resources getResourcesForApplication(@NonNull ApplicationInfo app)
2045             throws NameNotFoundException {
2046         return getResourcesForApplication(app, null);
2047     }
2048 
2049     @Override
getResourcesForApplication(@onNull ApplicationInfo app, @Nullable Configuration configuration)2050     public Resources getResourcesForApplication(@NonNull ApplicationInfo app,
2051             @Nullable Configuration configuration) throws NameNotFoundException {
2052         if (app.packageName.equals("system")) {
2053             Context sysuiContext = mContext.mMainThread.getSystemUiContext();
2054             if (configuration != null) {
2055                 sysuiContext = sysuiContext.createConfigurationContext(configuration);
2056             }
2057             return sysuiContext.getResources();
2058         }
2059         final boolean sameUid = (app.uid == Process.myUid());
2060         final Resources r = mContext.mMainThread.getTopLevelResources(
2061                 sameUid ? app.sourceDir : app.publicSourceDir,
2062                 sameUid ? app.splitSourceDirs : app.splitPublicSourceDirs,
2063                 app.resourceDirs, app.overlayPaths, app.sharedLibraryFiles,
2064                 mContext.mPackageInfo, configuration);
2065         if (r != null) {
2066             return r;
2067         }
2068         throw new NameNotFoundException("Unable to open " + app.publicSourceDir);
2069     }
2070 
2071     @Override
getResourcesForApplication(String appPackageName)2072     public Resources getResourcesForApplication(String appPackageName)
2073             throws NameNotFoundException {
2074         return getResourcesForApplication(
2075             getApplicationInfo(appPackageName, sDefaultFlags));
2076     }
2077 
2078     /** @hide */
2079     @Override
getResourcesForApplicationAsUser(String appPackageName, int userId)2080     public Resources getResourcesForApplicationAsUser(String appPackageName, int userId)
2081             throws NameNotFoundException {
2082         if (userId < 0) {
2083             throw new IllegalArgumentException(
2084                     "Call does not support special user #" + userId);
2085         }
2086         if ("system".equals(appPackageName)) {
2087             return mContext.mMainThread.getSystemUiContext().getResources();
2088         }
2089         try {
2090             ApplicationInfo ai = mPM.getApplicationInfo(appPackageName, sDefaultFlags, userId);
2091             if (ai != null) {
2092                 return getResourcesForApplication(ai);
2093             }
2094         } catch (RemoteException e) {
2095             throw e.rethrowFromSystemServer();
2096         }
2097         throw new NameNotFoundException("Package " + appPackageName + " doesn't exist");
2098     }
2099 
2100     volatile int mCachedSafeMode = -1;
2101 
2102     @Override
isSafeMode()2103     public boolean isSafeMode() {
2104         try {
2105             if (mCachedSafeMode < 0) {
2106                 mCachedSafeMode = mPM.isSafeMode() ? 1 : 0;
2107             }
2108             return mCachedSafeMode != 0;
2109         } catch (RemoteException e) {
2110             throw e.rethrowFromSystemServer();
2111         }
2112     }
2113 
2114     @Override
addOnPermissionsChangeListener(OnPermissionsChangedListener listener)2115     public void addOnPermissionsChangeListener(OnPermissionsChangedListener listener) {
2116         getPermissionManager().addOnPermissionsChangeListener(listener);
2117     }
2118 
2119     @Override
removeOnPermissionsChangeListener(OnPermissionsChangedListener listener)2120     public void removeOnPermissionsChangeListener(OnPermissionsChangedListener listener) {
2121         getPermissionManager().removeOnPermissionsChangeListener(listener);
2122     }
2123 
2124     @UnsupportedAppUsage
configurationChanged()2125     static void configurationChanged() {
2126         synchronized (sSync) {
2127             sIconCache.clear();
2128             sStringCache.clear();
2129         }
2130     }
2131 
2132     @UnsupportedAppUsage
ApplicationPackageManager(ContextImpl context, IPackageManager pm)2133     protected ApplicationPackageManager(ContextImpl context, IPackageManager pm) {
2134         mContext = context;
2135         mPM = pm;
2136     }
2137 
2138     /**
2139      * Update given flags when being used to request {@link PackageInfo}.
2140      */
updateFlagsForPackage(long flags, int userId)2141     private long updateFlagsForPackage(long flags, int userId) {
2142         if ((flags & (GET_ACTIVITIES | GET_RECEIVERS | GET_SERVICES | GET_PROVIDERS)) != 0) {
2143             // Caller is asking for component details, so they'd better be
2144             // asking for specific Direct Boot matching behavior
2145             if ((flags & (MATCH_DIRECT_BOOT_UNAWARE
2146                     | MATCH_DIRECT_BOOT_AWARE
2147                     | MATCH_DIRECT_BOOT_AUTO)) == 0) {
2148                 onImplicitDirectBoot(userId);
2149             }
2150         }
2151         return flags;
2152     }
2153 
2154     /**
2155      * Update given flags when being used to request {@link ApplicationInfo}.
2156      */
updateFlagsForApplication(long flags, int userId)2157     private long updateFlagsForApplication(long flags, int userId) {
2158         return updateFlagsForPackage(flags, userId);
2159     }
2160 
2161     /**
2162      * Update given flags when being used to request {@link ComponentInfo}.
2163      */
updateFlagsForComponent(@omponentInfoFlagsBits long flags, int userId, Intent intent)2164     private long updateFlagsForComponent(@ComponentInfoFlagsBits long flags, int userId,
2165             Intent intent) {
2166         if (intent != null) {
2167             if ((intent.getFlags() & Intent.FLAG_DIRECT_BOOT_AUTO) != 0) {
2168                 flags |= MATCH_DIRECT_BOOT_AUTO;
2169             }
2170         }
2171 
2172         // Caller is asking for component details, so they'd better be
2173         // asking for specific Direct Boot matching behavior
2174         if ((flags & (MATCH_DIRECT_BOOT_UNAWARE
2175                 | MATCH_DIRECT_BOOT_AWARE
2176                 | MATCH_DIRECT_BOOT_AUTO)) == 0) {
2177             onImplicitDirectBoot(userId);
2178         }
2179         return flags;
2180     }
2181 
onImplicitDirectBoot(int userId)2182     private void onImplicitDirectBoot(int userId) {
2183         // Only report if someone is relying on implicit behavior while the user
2184         // is locked; code running when unlocked is going to see both aware and
2185         // unaware components.
2186         if (StrictMode.vmImplicitDirectBootEnabled()) {
2187             // We can cache the unlocked state for the userId we're running as,
2188             // since any relocking of that user will always result in our
2189             // process being killed to release any CE FDs we're holding onto.
2190             if (userId == UserHandle.myUserId()) {
2191                 if (mUserUnlocked) {
2192                     return;
2193                 } else if (mContext.getSystemService(UserManager.class)
2194                         .isUserUnlockingOrUnlocked(userId)) {
2195                     mUserUnlocked = true;
2196                 } else {
2197                     StrictMode.onImplicitDirectBoot();
2198                 }
2199             } else if (!mContext.getSystemService(UserManager.class)
2200                     .isUserUnlockingOrUnlocked(userId)) {
2201                 StrictMode.onImplicitDirectBoot();
2202             }
2203         }
2204     }
2205 
2206     @Nullable
getCachedIcon(@onNull ResourceName name)2207     private Drawable getCachedIcon(@NonNull ResourceName name) {
2208         synchronized (sSync) {
2209             final WeakReference<Drawable.ConstantState> wr = sIconCache.get(name);
2210             if (DEBUG_ICONS) Log.v(TAG, "Get cached weak drawable ref for "
2211                                    + name + ": " + wr);
2212             if (wr != null) {   // we have the activity
2213                 final Drawable.ConstantState state = wr.get();
2214                 if (state != null) {
2215                     if (DEBUG_ICONS) {
2216                         Log.v(TAG, "Get cached drawable state for " + name + ": " + state);
2217                     }
2218                     // Note: It's okay here to not use the newDrawable(Resources) variant
2219                     //       of the API. The ConstantState comes from a drawable that was
2220                     //       originally created by passing the proper app Resources instance
2221                     //       which means the state should already contain the proper
2222                     //       resources specific information (like density.) See
2223                     //       BitmapDrawable.BitmapState for instance.
2224                     return state.newDrawable();
2225                 }
2226                 // our entry has been purged
2227                 sIconCache.remove(name);
2228             }
2229         }
2230         return null;
2231     }
2232 
putCachedIcon(@onNull ResourceName name, @NonNull Drawable dr)2233     private void putCachedIcon(@NonNull ResourceName name, @NonNull Drawable dr) {
2234         synchronized (sSync) {
2235             sIconCache.put(name, new WeakReference<>(dr.getConstantState()));
2236             if (DEBUG_ICONS) Log.v(TAG, "Added cached drawable state for " + name + ": " + dr);
2237         }
2238     }
2239 
handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo)2240     static void handlePackageBroadcast(int cmd, String[] pkgList, boolean hasPkgInfo) {
2241         boolean immediateGc = false;
2242         if (cmd == ApplicationThreadConstants.EXTERNAL_STORAGE_UNAVAILABLE) {
2243             immediateGc = true;
2244         }
2245         if (pkgList != null && (pkgList.length > 0)) {
2246             boolean needCleanup = false;
2247             for (String ssp : pkgList) {
2248                 synchronized (sSync) {
2249                     for (int i=sIconCache.size()-1; i>=0; i--) {
2250                         ResourceName nm = sIconCache.keyAt(i);
2251                         if (nm.packageName.equals(ssp)) {
2252                             //Log.i(TAG, "Removing cached drawable for " + nm);
2253                             sIconCache.removeAt(i);
2254                             needCleanup = true;
2255                         }
2256                     }
2257                     for (int i=sStringCache.size()-1; i>=0; i--) {
2258                         ResourceName nm = sStringCache.keyAt(i);
2259                         if (nm.packageName.equals(ssp)) {
2260                             //Log.i(TAG, "Removing cached string for " + nm);
2261                             sStringCache.removeAt(i);
2262                             needCleanup = true;
2263                         }
2264                     }
2265                 }
2266             }
2267             if (needCleanup || hasPkgInfo) {
2268                 if (immediateGc) {
2269                     // Schedule an immediate gc.
2270                     Runtime.getRuntime().gc();
2271                 } else {
2272                     ActivityThread.currentActivityThread().scheduleGcIdler();
2273                 }
2274             }
2275         }
2276     }
2277 
2278     private static final class ResourceName {
2279         final String packageName;
2280         final int iconId;
2281 
ResourceName(String _packageName, int _iconId)2282         ResourceName(String _packageName, int _iconId) {
2283             packageName = _packageName;
2284             iconId = _iconId;
2285         }
2286 
ResourceName(ApplicationInfo aInfo, int _iconId)2287         ResourceName(ApplicationInfo aInfo, int _iconId) {
2288             this(aInfo.packageName, _iconId);
2289         }
2290 
ResourceName(ComponentInfo cInfo, int _iconId)2291         ResourceName(ComponentInfo cInfo, int _iconId) {
2292             this(cInfo.applicationInfo.packageName, _iconId);
2293         }
2294 
ResourceName(ResolveInfo rInfo, int _iconId)2295         ResourceName(ResolveInfo rInfo, int _iconId) {
2296             this(rInfo.activityInfo.applicationInfo.packageName, _iconId);
2297         }
2298 
2299         @Override
equals(@ullable Object o)2300         public boolean equals(@Nullable Object o) {
2301             if (this == o) return true;
2302             if (o == null || getClass() != o.getClass()) return false;
2303 
2304             ResourceName that = (ResourceName) o;
2305 
2306             if (iconId != that.iconId) return false;
2307             return !(packageName != null ?
2308                      !packageName.equals(that.packageName) : that.packageName != null);
2309 
2310         }
2311 
2312         @Override
hashCode()2313         public int hashCode() {
2314             int result;
2315             result = packageName.hashCode();
2316             result = 31 * result + iconId;
2317             return result;
2318         }
2319 
2320         @Override
toString()2321         public String toString() {
2322             return "{ResourceName " + packageName + " / " + iconId + "}";
2323         }
2324     }
2325 
getCachedString(ResourceName name)2326     private CharSequence getCachedString(ResourceName name) {
2327         synchronized (sSync) {
2328             WeakReference<CharSequence> wr = sStringCache.get(name);
2329             if (wr != null) {   // we have the activity
2330                 CharSequence cs = wr.get();
2331                 if (cs != null) {
2332                     return cs;
2333                 }
2334                 // our entry has been purged
2335                 sStringCache.remove(name);
2336             }
2337         }
2338         return null;
2339     }
2340 
putCachedString(ResourceName name, CharSequence cs)2341     private void putCachedString(ResourceName name, CharSequence cs) {
2342         synchronized (sSync) {
2343             sStringCache.put(name, new WeakReference<CharSequence>(cs));
2344         }
2345     }
2346 
2347     @Override
getText(String packageName, @StringRes int resid, ApplicationInfo appInfo)2348     public CharSequence getText(String packageName, @StringRes int resid,
2349                                 ApplicationInfo appInfo) {
2350         ResourceName name = new ResourceName(packageName, resid);
2351         CharSequence text = getCachedString(name);
2352         if (text != null) {
2353             return text;
2354         }
2355         if (appInfo == null) {
2356             try {
2357                 appInfo = getApplicationInfo(packageName, sDefaultFlags);
2358             } catch (NameNotFoundException e) {
2359                 return null;
2360             }
2361         }
2362         try {
2363             Resources r = getResourcesForApplication(appInfo);
2364             text = r.getText(resid);
2365             putCachedString(name, text);
2366             return text;
2367         } catch (NameNotFoundException e) {
2368             Log.w("PackageManager", "Failure retrieving resources for "
2369                   + appInfo.packageName);
2370         } catch (RuntimeException e) {
2371             // If an exception was thrown, fall through to return
2372             // default icon.
2373             Log.w("PackageManager", "Failure retrieving text 0x"
2374                   + Integer.toHexString(resid) + " in package "
2375                   + packageName, e);
2376         }
2377         return null;
2378     }
2379 
2380     @Override
getXml(String packageName, @XmlRes int resid, ApplicationInfo appInfo)2381     public XmlResourceParser getXml(String packageName, @XmlRes int resid,
2382                                     ApplicationInfo appInfo) {
2383         if (appInfo == null) {
2384             try {
2385                 appInfo = getApplicationInfo(packageName, sDefaultFlags);
2386             } catch (NameNotFoundException e) {
2387                 return null;
2388             }
2389         }
2390         try {
2391             Resources r = getResourcesForApplication(appInfo);
2392             return r.getXml(resid);
2393         } catch (RuntimeException e) {
2394             // If an exception was thrown, fall through to return
2395             // default icon.
2396             Log.w("PackageManager", "Failure retrieving xml 0x"
2397                   + Integer.toHexString(resid) + " in package "
2398                   + packageName, e);
2399         } catch (NameNotFoundException e) {
2400             Log.w("PackageManager", "Failure retrieving resources for "
2401                   + appInfo.packageName);
2402         }
2403         return null;
2404     }
2405 
2406     @Override
getApplicationLabel(ApplicationInfo info)2407     public CharSequence getApplicationLabel(ApplicationInfo info) {
2408         return info.loadLabel(this);
2409     }
2410 
2411     @Override
installExistingPackage(String packageName)2412     public int installExistingPackage(String packageName) throws NameNotFoundException {
2413         return installExistingPackage(packageName, INSTALL_REASON_UNKNOWN);
2414     }
2415 
2416     @Override
installExistingPackage(String packageName, int installReason)2417     public int installExistingPackage(String packageName, int installReason)
2418             throws NameNotFoundException {
2419         return installExistingPackageAsUser(packageName, installReason, getUserId());
2420     }
2421 
2422     @Override
installExistingPackageAsUser(String packageName, int userId)2423     public int installExistingPackageAsUser(String packageName, int userId)
2424             throws NameNotFoundException {
2425         return installExistingPackageAsUser(packageName, INSTALL_REASON_UNKNOWN,
2426                 userId);
2427     }
2428 
installExistingPackageAsUser(String packageName, int installReason, int userId)2429     private int installExistingPackageAsUser(String packageName, int installReason, int userId)
2430             throws NameNotFoundException {
2431         try {
2432             int res = mPM.installExistingPackageAsUser(packageName, userId,
2433                     INSTALL_ALL_WHITELIST_RESTRICTED_PERMISSIONS, installReason, null);
2434             if (res == INSTALL_FAILED_INVALID_URI) {
2435                 throw new NameNotFoundException("Package " + packageName + " doesn't exist");
2436             }
2437             return res;
2438         } catch (RemoteException e) {
2439             throw e.rethrowFromSystemServer();
2440         }
2441     }
2442 
2443     @Override
verifyPendingInstall(int id, int response)2444     public void verifyPendingInstall(int id, int response) {
2445         try {
2446             mPM.verifyPendingInstall(id, response);
2447         } catch (RemoteException e) {
2448             throw e.rethrowFromSystemServer();
2449         }
2450     }
2451 
2452     @Override
extendVerificationTimeout(int id, int verificationCodeAtTimeout, long millisecondsToDelay)2453     public void extendVerificationTimeout(int id, int verificationCodeAtTimeout,
2454             long millisecondsToDelay) {
2455         try {
2456             mPM.extendVerificationTimeout(id, verificationCodeAtTimeout, millisecondsToDelay);
2457         } catch (RemoteException e) {
2458             throw e.rethrowFromSystemServer();
2459         }
2460     }
2461 
2462     @Override
verifyIntentFilter(int id, int verificationCode, List<String> failedDomains)2463     public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) {
2464         try {
2465             mPM.verifyIntentFilter(id, verificationCode, failedDomains);
2466         } catch (RemoteException e) {
2467             throw e.rethrowFromSystemServer();
2468         }
2469     }
2470 
2471     @Override
getIntentVerificationStatusAsUser(String packageName, int userId)2472     public int getIntentVerificationStatusAsUser(String packageName, int userId) {
2473         try {
2474             return mPM.getIntentVerificationStatus(packageName, userId);
2475         } catch (RemoteException e) {
2476             throw e.rethrowFromSystemServer();
2477         }
2478     }
2479 
2480     @Override
updateIntentVerificationStatusAsUser(String packageName, int status, int userId)2481     public boolean updateIntentVerificationStatusAsUser(String packageName, int status, int userId) {
2482         try {
2483             return mPM.updateIntentVerificationStatus(packageName, status, userId);
2484         } catch (RemoteException e) {
2485             throw e.rethrowFromSystemServer();
2486         }
2487     }
2488 
2489     @Override
2490     @SuppressWarnings("unchecked")
getIntentFilterVerifications(String packageName)2491     public List<IntentFilterVerificationInfo> getIntentFilterVerifications(String packageName) {
2492         try {
2493             ParceledListSlice<IntentFilterVerificationInfo> parceledList =
2494                     mPM.getIntentFilterVerifications(packageName);
2495             if (parceledList == null) {
2496                 return Collections.emptyList();
2497             }
2498             return parceledList.getList();
2499         } catch (RemoteException e) {
2500             throw e.rethrowFromSystemServer();
2501         }
2502     }
2503 
2504     @Override
2505     @SuppressWarnings("unchecked")
getAllIntentFilters(String packageName)2506     public List<IntentFilter> getAllIntentFilters(String packageName) {
2507         try {
2508             ParceledListSlice<IntentFilter> parceledList =
2509                     mPM.getAllIntentFilters(packageName);
2510             if (parceledList == null) {
2511                 return Collections.emptyList();
2512             }
2513             return parceledList.getList();
2514         } catch (RemoteException e) {
2515             throw e.rethrowFromSystemServer();
2516         }
2517     }
2518 
2519     @Override
getDefaultBrowserPackageNameAsUser(int userId)2520     public String getDefaultBrowserPackageNameAsUser(int userId) {
2521         RoleManager roleManager = mContext.getSystemService(RoleManager.class);
2522         return roleManager.getBrowserRoleHolder(userId);
2523     }
2524 
2525     @Override
setDefaultBrowserPackageNameAsUser(String packageName, int userId)2526     public boolean setDefaultBrowserPackageNameAsUser(String packageName, int userId) {
2527         RoleManager roleManager = mContext.getSystemService(RoleManager.class);
2528         return roleManager.setBrowserRoleHolder(packageName, userId);
2529     }
2530 
2531     @Override
setInstallerPackageName(String targetPackage, String installerPackageName)2532     public void setInstallerPackageName(String targetPackage,
2533             String installerPackageName) {
2534         try {
2535             mPM.setInstallerPackageName(targetPackage, installerPackageName);
2536         } catch (RemoteException e) {
2537             throw e.rethrowFromSystemServer();
2538         }
2539     }
2540 
2541     @Override
setUpdateAvailable(String packageName, boolean updateAvailable)2542     public void setUpdateAvailable(String packageName, boolean updateAvailable) {
2543         try {
2544             mPM.setUpdateAvailable(packageName, updateAvailable);
2545         } catch (RemoteException e) {
2546             throw e.rethrowFromSystemServer();
2547         }
2548     }
2549 
2550     @Override
getInstallerPackageName(String packageName)2551     public String getInstallerPackageName(String packageName) {
2552         try {
2553             return mPM.getInstallerPackageName(packageName);
2554         } catch (RemoteException e) {
2555             throw e.rethrowFromSystemServer();
2556         }
2557     }
2558 
2559     @Override
2560     @NonNull
getInstallSourceInfo(String packageName)2561     public InstallSourceInfo getInstallSourceInfo(String packageName) throws NameNotFoundException {
2562         final InstallSourceInfo installSourceInfo;
2563         try {
2564             installSourceInfo = mPM.getInstallSourceInfo(packageName, getUserId());
2565         } catch (RemoteException e) {
2566             throw e.rethrowFromSystemServer();
2567         }
2568         if (installSourceInfo == null) {
2569             throw new NameNotFoundException(packageName);
2570         }
2571         return installSourceInfo;
2572     }
2573 
2574     @Override
getMoveStatus(int moveId)2575     public int getMoveStatus(int moveId) {
2576         try {
2577             return mPM.getMoveStatus(moveId);
2578         } catch (RemoteException e) {
2579             throw e.rethrowFromSystemServer();
2580         }
2581     }
2582 
2583     @Override
registerMoveCallback(MoveCallback callback, Handler handler)2584     public void registerMoveCallback(MoveCallback callback, Handler handler) {
2585         synchronized (mDelegates) {
2586             final MoveCallbackDelegate delegate = new MoveCallbackDelegate(callback,
2587                     handler.getLooper());
2588             try {
2589                 mPM.registerMoveCallback(delegate);
2590             } catch (RemoteException e) {
2591                 throw e.rethrowFromSystemServer();
2592             }
2593             mDelegates.add(delegate);
2594         }
2595     }
2596 
2597     @Override
unregisterMoveCallback(MoveCallback callback)2598     public void unregisterMoveCallback(MoveCallback callback) {
2599         synchronized (mDelegates) {
2600             for (Iterator<MoveCallbackDelegate> i = mDelegates.iterator(); i.hasNext();) {
2601                 final MoveCallbackDelegate delegate = i.next();
2602                 if (delegate.mCallback == callback) {
2603                     try {
2604                         mPM.unregisterMoveCallback(delegate);
2605                     } catch (RemoteException e) {
2606                         throw e.rethrowFromSystemServer();
2607                     }
2608                     i.remove();
2609                 }
2610             }
2611         }
2612     }
2613 
2614     @Override
movePackage(String packageName, VolumeInfo vol)2615     public int movePackage(String packageName, VolumeInfo vol) {
2616         try {
2617             final String volumeUuid;
2618             if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
2619                 volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
2620             } else if (vol.isPrimaryPhysical()) {
2621                 volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
2622             } else {
2623                 volumeUuid = Objects.requireNonNull(vol.fsUuid);
2624             }
2625 
2626             return mPM.movePackage(packageName, volumeUuid);
2627         } catch (RemoteException e) {
2628             throw e.rethrowFromSystemServer();
2629         }
2630     }
2631 
2632     @Override
2633     @UnsupportedAppUsage(maxTargetSdk = Build.VERSION_CODES.R, trackingBug = 170729553)
getPackageCurrentVolume(ApplicationInfo app)2634     public @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app) {
2635         final StorageManager storage = mContext.getSystemService(StorageManager.class);
2636         return getPackageCurrentVolume(app, storage);
2637     }
2638 
2639     @VisibleForTesting
getPackageCurrentVolume(ApplicationInfo app, StorageManager storage)2640     protected @Nullable VolumeInfo getPackageCurrentVolume(ApplicationInfo app,
2641             StorageManager storage) {
2642         if (app.isInternal()) {
2643             return storage.findVolumeById(VolumeInfo.ID_PRIVATE_INTERNAL);
2644         } else {
2645             return storage.findVolumeByUuid(app.volumeUuid);
2646         }
2647     }
2648 
2649     @Override
getPackageCandidateVolumes(ApplicationInfo app)2650     public @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app) {
2651         final StorageManager storageManager = mContext.getSystemService(StorageManager.class);
2652         return getPackageCandidateVolumes(app, storageManager, mPM);
2653     }
2654 
2655     @VisibleForTesting
getPackageCandidateVolumes(ApplicationInfo app, StorageManager storageManager, IPackageManager pm)2656     protected @NonNull List<VolumeInfo> getPackageCandidateVolumes(ApplicationInfo app,
2657             StorageManager storageManager, IPackageManager pm) {
2658         final VolumeInfo currentVol = getPackageCurrentVolume(app, storageManager);
2659         final List<VolumeInfo> vols = storageManager.getVolumes();
2660         final List<VolumeInfo> candidates = new ArrayList<>();
2661         for (VolumeInfo vol : vols) {
2662             if (Objects.equals(vol, currentVol)
2663                     || isPackageCandidateVolume(mContext, app, vol, pm)) {
2664                 candidates.add(vol);
2665             }
2666         }
2667         return candidates;
2668     }
2669 
2670     @VisibleForTesting
isForceAllowOnExternal(Context context)2671     protected boolean isForceAllowOnExternal(Context context) {
2672         return Settings.Global.getInt(
2673                 context.getContentResolver(), Settings.Global.FORCE_ALLOW_ON_EXTERNAL, 0) != 0;
2674     }
2675 
2676     @VisibleForTesting
isAllow3rdPartyOnInternal(Context context)2677     protected boolean isAllow3rdPartyOnInternal(Context context) {
2678         return context.getResources().getBoolean(
2679                 com.android.internal.R.bool.config_allow3rdPartyAppOnInternal);
2680     }
2681 
isPackageCandidateVolume( ContextImpl context, ApplicationInfo app, VolumeInfo vol, IPackageManager pm)2682     private boolean isPackageCandidateVolume(
2683             ContextImpl context, ApplicationInfo app, VolumeInfo vol, IPackageManager pm) {
2684         final boolean forceAllowOnExternal = isForceAllowOnExternal(context);
2685 
2686         if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
2687             return app.isSystemApp() || isAllow3rdPartyOnInternal(context);
2688         }
2689 
2690         // System apps and apps demanding internal storage can't be moved
2691         // anywhere else
2692         if (app.isSystemApp()) {
2693             return false;
2694         }
2695         if (!forceAllowOnExternal
2696                 && (app.installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY
2697                         || app.installLocation == PackageInfo.INSTALL_LOCATION_UNSPECIFIED)) {
2698             return false;
2699         }
2700 
2701         // Gotta be able to write there
2702         if (!vol.isMountedWritable()) {
2703             return false;
2704         }
2705 
2706         // Moving into an ASEC on public primary is only option internal
2707         if (vol.isPrimaryPhysical()) {
2708             return app.isInternal();
2709         }
2710 
2711         // Some apps can't be moved. (e.g. device admins)
2712         try {
2713             if (pm.isPackageDeviceAdminOnAnyUser(app.packageName)) {
2714                 return false;
2715             }
2716         } catch (RemoteException e) {
2717             throw e.rethrowFromSystemServer();
2718         }
2719 
2720         // Otherwise we can move to any private volume
2721         return (vol.getType() == VolumeInfo.TYPE_PRIVATE);
2722     }
2723 
2724     @Override
movePrimaryStorage(VolumeInfo vol)2725     public int movePrimaryStorage(VolumeInfo vol) {
2726         try {
2727             final String volumeUuid;
2728             if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.id)) {
2729                 volumeUuid = StorageManager.UUID_PRIVATE_INTERNAL;
2730             } else if (vol.isPrimaryPhysical()) {
2731                 volumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
2732             } else {
2733                 volumeUuid = Objects.requireNonNull(vol.fsUuid);
2734             }
2735 
2736             return mPM.movePrimaryStorage(volumeUuid);
2737         } catch (RemoteException e) {
2738             throw e.rethrowFromSystemServer();
2739         }
2740     }
2741 
2742     @Override
getPrimaryStorageCurrentVolume()2743     public @Nullable VolumeInfo getPrimaryStorageCurrentVolume() {
2744         final StorageManager storage = mContext.getSystemService(StorageManager.class);
2745         final String volumeUuid = storage.getPrimaryStorageUuid();
2746         return storage.findVolumeByQualifiedUuid(volumeUuid);
2747     }
2748 
2749     @Override
getPrimaryStorageCandidateVolumes()2750     public @NonNull List<VolumeInfo> getPrimaryStorageCandidateVolumes() {
2751         final StorageManager storage = mContext.getSystemService(StorageManager.class);
2752         final VolumeInfo currentVol = getPrimaryStorageCurrentVolume();
2753         final List<VolumeInfo> vols = storage.getVolumes();
2754         final List<VolumeInfo> candidates = new ArrayList<>();
2755         if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL,
2756                 storage.getPrimaryStorageUuid()) && currentVol != null) {
2757             // TODO: support moving primary physical to emulated volume
2758             candidates.add(currentVol);
2759         } else {
2760             for (VolumeInfo vol : vols) {
2761                 if (Objects.equals(vol, currentVol) || isPrimaryStorageCandidateVolume(vol)) {
2762                     candidates.add(vol);
2763                 }
2764             }
2765         }
2766         return candidates;
2767     }
2768 
isPrimaryStorageCandidateVolume(VolumeInfo vol)2769     private static boolean isPrimaryStorageCandidateVolume(VolumeInfo vol) {
2770         // Private internal is always an option
2771         if (VolumeInfo.ID_PRIVATE_INTERNAL.equals(vol.getId())) {
2772             return true;
2773         }
2774 
2775         // Gotta be able to write there
2776         if (!vol.isMountedWritable()) {
2777             return false;
2778         }
2779 
2780         // We can move to any private volume
2781         return (vol.getType() == VolumeInfo.TYPE_PRIVATE);
2782     }
2783 
2784     @Override
2785     @UnsupportedAppUsage
deletePackage(String packageName, IPackageDeleteObserver observer, int flags)2786     public void deletePackage(String packageName, IPackageDeleteObserver observer, int flags) {
2787         deletePackageAsUser(packageName, observer, flags, getUserId());
2788     }
2789 
2790     @Override
deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int flags, int userId)2791     public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer,
2792             int flags, int userId) {
2793         try {
2794             mPM.deletePackageAsUser(packageName, VERSION_CODE_HIGHEST,
2795                     observer, userId, flags);
2796         } catch (RemoteException e) {
2797             throw e.rethrowFromSystemServer();
2798         }
2799     }
2800 
2801     @Override
clearApplicationUserData(String packageName, IPackageDataObserver observer)2802     public void clearApplicationUserData(String packageName,
2803                                          IPackageDataObserver observer) {
2804         try {
2805             mPM.clearApplicationUserData(packageName, observer, getUserId());
2806         } catch (RemoteException e) {
2807             throw e.rethrowFromSystemServer();
2808         }
2809     }
2810     @Override
deleteApplicationCacheFiles(String packageName, IPackageDataObserver observer)2811     public void deleteApplicationCacheFiles(String packageName,
2812                                             IPackageDataObserver observer) {
2813         try {
2814             mPM.deleteApplicationCacheFiles(packageName, observer);
2815         } catch (RemoteException e) {
2816             throw e.rethrowFromSystemServer();
2817         }
2818     }
2819 
2820     @Override
deleteApplicationCacheFilesAsUser(String packageName, int userId, IPackageDataObserver observer)2821     public void deleteApplicationCacheFilesAsUser(String packageName, int userId,
2822             IPackageDataObserver observer) {
2823         try {
2824             mPM.deleteApplicationCacheFilesAsUser(packageName, userId, observer);
2825         } catch (RemoteException e) {
2826             throw e.rethrowFromSystemServer();
2827         }
2828     }
2829 
2830     @Override
freeStorageAndNotify(String volumeUuid, long idealStorageSize, IPackageDataObserver observer)2831     public void freeStorageAndNotify(String volumeUuid, long idealStorageSize,
2832             IPackageDataObserver observer) {
2833         try {
2834             mPM.freeStorageAndNotify(volumeUuid, idealStorageSize, 0, observer);
2835         } catch (RemoteException e) {
2836             throw e.rethrowFromSystemServer();
2837         }
2838     }
2839 
2840     @Override
freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi)2841     public void freeStorage(String volumeUuid, long freeStorageSize, IntentSender pi) {
2842         try {
2843             mPM.freeStorage(volumeUuid, freeStorageSize, 0, pi);
2844         } catch (RemoteException e) {
2845             throw e.rethrowFromSystemServer();
2846         }
2847     }
2848 
2849     @Override
setDistractingPackageRestrictions(String[] packages, int distractionFlags)2850     public String[] setDistractingPackageRestrictions(String[] packages, int distractionFlags) {
2851         try {
2852             return mPM.setDistractingPackageRestrictionsAsUser(packages, distractionFlags,
2853                     mContext.getUserId());
2854         } catch (RemoteException e) {
2855             throw e.rethrowFromSystemServer();
2856         }
2857     }
2858 
2859     @Override
setPackagesSuspended(String[] packageNames, boolean suspended, PersistableBundle appExtras, PersistableBundle launcherExtras, String dialogMessage)2860     public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
2861             PersistableBundle appExtras, PersistableBundle launcherExtras,
2862             String dialogMessage) {
2863         final SuspendDialogInfo dialogInfo = !TextUtils.isEmpty(dialogMessage)
2864                 ? new SuspendDialogInfo.Builder().setMessage(dialogMessage).build()
2865                 : null;
2866         return setPackagesSuspended(packageNames, suspended, appExtras, launcherExtras, dialogInfo);
2867     }
2868 
2869     @Override
setPackagesSuspended(String[] packageNames, boolean suspended, PersistableBundle appExtras, PersistableBundle launcherExtras, SuspendDialogInfo dialogInfo)2870     public String[] setPackagesSuspended(String[] packageNames, boolean suspended,
2871             PersistableBundle appExtras, PersistableBundle launcherExtras,
2872             SuspendDialogInfo dialogInfo) {
2873         try {
2874             return mPM.setPackagesSuspendedAsUser(packageNames, suspended, appExtras,
2875                     launcherExtras, dialogInfo, mContext.getOpPackageName(),
2876                     getUserId());
2877         } catch (RemoteException e) {
2878             throw e.rethrowFromSystemServer();
2879         }
2880     }
2881 
2882     @Override
getUnsuspendablePackages(String[] packageNames)2883     public String[] getUnsuspendablePackages(String[] packageNames) {
2884         try {
2885             return mPM.getUnsuspendablePackagesForUser(packageNames, mContext.getUserId());
2886         } catch (RemoteException e) {
2887             throw e.rethrowFromSystemServer();
2888         }
2889     }
2890 
2891     @Override
getSuspendedPackageAppExtras()2892     public Bundle getSuspendedPackageAppExtras() {
2893         try {
2894             return mPM.getSuspendedPackageAppExtras(mContext.getOpPackageName(), getUserId());
2895         } catch (RemoteException e) {
2896             throw e.rethrowFromSystemServer();
2897         }
2898     }
2899 
2900     @Override
isPackageSuspendedForUser(String packageName, int userId)2901     public boolean isPackageSuspendedForUser(String packageName, int userId) {
2902         try {
2903             return mPM.isPackageSuspendedForUser(packageName, userId);
2904         } catch (RemoteException e) {
2905             throw e.rethrowFromSystemServer();
2906         }
2907     }
2908 
2909     /** @hide */
2910     @Override
isPackageSuspended(String packageName)2911     public boolean isPackageSuspended(String packageName) throws NameNotFoundException {
2912         try {
2913             return isPackageSuspendedForUser(packageName, getUserId());
2914         } catch (IllegalArgumentException ie) {
2915             throw new NameNotFoundException(packageName);
2916         }
2917     }
2918 
2919     @Override
isPackageSuspended()2920     public boolean isPackageSuspended() {
2921         return isPackageSuspendedForUser(mContext.getOpPackageName(), getUserId());
2922     }
2923 
2924     /** @hide */
2925     @Override
setApplicationCategoryHint(String packageName, int categoryHint)2926     public void setApplicationCategoryHint(String packageName, int categoryHint) {
2927         try {
2928             mPM.setApplicationCategoryHint(packageName, categoryHint,
2929                     mContext.getOpPackageName());
2930         } catch (RemoteException e) {
2931             throw e.rethrowFromSystemServer();
2932         }
2933     }
2934 
2935     @Override
2936     @UnsupportedAppUsage
getPackageSizeInfoAsUser(String packageName, int userHandle, IPackageStatsObserver observer)2937     public void getPackageSizeInfoAsUser(String packageName, int userHandle,
2938             IPackageStatsObserver observer) {
2939         final String msg = "Shame on you for calling the hidden API "
2940                 + "getPackageSizeInfoAsUser(). Shame!";
2941         if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.O) {
2942             throw new UnsupportedOperationException(msg);
2943         } else if (observer != null) {
2944             Log.d(TAG, msg);
2945             try {
2946                 observer.onGetStatsCompleted(null, false);
2947             } catch (RemoteException ignored) {
2948             }
2949         }
2950     }
2951 
2952     @Override
addPackageToPreferred(String packageName)2953     public void addPackageToPreferred(String packageName) {
2954         Log.w(TAG, "addPackageToPreferred() is a no-op");
2955     }
2956 
2957     @Override
removePackageFromPreferred(String packageName)2958     public void removePackageFromPreferred(String packageName) {
2959         Log.w(TAG, "removePackageFromPreferred() is a no-op");
2960     }
2961 
2962     @Override
getPreferredPackages(int flags)2963     public List<PackageInfo> getPreferredPackages(int flags) {
2964         Log.w(TAG, "getPreferredPackages() is a no-op");
2965         return Collections.emptyList();
2966     }
2967 
2968     @Override
addPreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity)2969     public void addPreferredActivity(IntentFilter filter,
2970                                      int match, ComponentName[] set, ComponentName activity) {
2971         try {
2972             mPM.addPreferredActivity(filter, match, set, activity, getUserId(), false);
2973         } catch (RemoteException e) {
2974             throw e.rethrowFromSystemServer();
2975         }
2976     }
2977 
2978     @Override
addPreferredActivityAsUser(IntentFilter filter, int match, ComponentName[] set, ComponentName activity, int userId)2979     public void addPreferredActivityAsUser(IntentFilter filter, int match,
2980             ComponentName[] set, ComponentName activity, int userId) {
2981         try {
2982             mPM.addPreferredActivity(filter, match, set, activity, userId, false);
2983         } catch (RemoteException e) {
2984             throw e.rethrowFromSystemServer();
2985         }
2986     }
2987 
2988     @Override
replacePreferredActivity(IntentFilter filter, int match, ComponentName[] set, ComponentName activity)2989     public void replacePreferredActivity(IntentFilter filter,
2990                                          int match, ComponentName[] set, ComponentName activity) {
2991         try {
2992             mPM.replacePreferredActivity(filter, match, set, activity, getUserId());
2993         } catch (RemoteException e) {
2994             throw e.rethrowFromSystemServer();
2995         }
2996     }
2997 
2998     @Override
replacePreferredActivityAsUser(IntentFilter filter, int match, ComponentName[] set, ComponentName activity, int userId)2999     public void replacePreferredActivityAsUser(IntentFilter filter,
3000                                          int match, ComponentName[] set, ComponentName activity,
3001                                          int userId) {
3002         try {
3003             mPM.replacePreferredActivity(filter, match, set, activity, userId);
3004         } catch (RemoteException e) {
3005             throw e.rethrowFromSystemServer();
3006         }
3007     }
3008 
3009     @Override
clearPackagePreferredActivities(String packageName)3010     public void clearPackagePreferredActivities(String packageName) {
3011         try {
3012             mPM.clearPackagePreferredActivities(packageName);
3013         } catch (RemoteException e) {
3014             throw e.rethrowFromSystemServer();
3015         }
3016     }
3017 
3018     @Override
addUniquePreferredActivity(@onNull IntentFilter filter, int match, @Nullable ComponentName[] set, @NonNull ComponentName activity)3019     public void addUniquePreferredActivity(@NonNull IntentFilter filter, int match,
3020             @Nullable ComponentName[] set, @NonNull ComponentName activity) {
3021         try {
3022             mPM.addPreferredActivity(filter, match, set, activity, getUserId(), true);
3023         } catch (RemoteException e) {
3024             throw e.rethrowFromSystemServer();
3025         }
3026     }
3027 
3028     @Override
getPreferredActivities(List<IntentFilter> outFilters, List<ComponentName> outActivities, String packageName)3029     public int getPreferredActivities(List<IntentFilter> outFilters,
3030                                       List<ComponentName> outActivities, String packageName) {
3031         try {
3032             return mPM.getPreferredActivities(outFilters, outActivities, packageName);
3033         } catch (RemoteException e) {
3034             throw e.rethrowFromSystemServer();
3035         }
3036     }
3037 
3038     @Override
getHomeActivities(List<ResolveInfo> outActivities)3039     public ComponentName getHomeActivities(List<ResolveInfo> outActivities) {
3040         try {
3041             return mPM.getHomeActivities(outActivities);
3042         } catch (RemoteException e) {
3043             throw e.rethrowFromSystemServer();
3044         }
3045     }
3046 
3047     @Override
setSyntheticAppDetailsActivityEnabled(String packageName, boolean enabled)3048     public void setSyntheticAppDetailsActivityEnabled(String packageName, boolean enabled) {
3049         try {
3050             ComponentName componentName = new ComponentName(packageName,
3051                     APP_DETAILS_ACTIVITY_CLASS_NAME);
3052             mPM.setComponentEnabledSetting(componentName, enabled
3053                     ? COMPONENT_ENABLED_STATE_DEFAULT
3054                     : COMPONENT_ENABLED_STATE_DISABLED,
3055                     DONT_KILL_APP, getUserId(), mContext.getOpPackageName());
3056         } catch (RemoteException e) {
3057             throw e.rethrowFromSystemServer();
3058         }
3059     }
3060 
3061     @Override
getSyntheticAppDetailsActivityEnabled(String packageName)3062     public boolean getSyntheticAppDetailsActivityEnabled(String packageName) {
3063         try {
3064             ComponentName componentName = new ComponentName(packageName,
3065                     APP_DETAILS_ACTIVITY_CLASS_NAME);
3066             int state = mPM.getComponentEnabledSetting(componentName, getUserId());
3067             return state == COMPONENT_ENABLED_STATE_ENABLED
3068                     || state == COMPONENT_ENABLED_STATE_DEFAULT;
3069         } catch (RemoteException e) {
3070             throw e.rethrowFromSystemServer();
3071         }
3072     }
3073 
3074     @Override
setComponentEnabledSetting(ComponentName componentName, int newState, int flags)3075     public void setComponentEnabledSetting(ComponentName componentName,
3076                                            int newState, int flags) {
3077         try {
3078             mPM.setComponentEnabledSetting(componentName, newState, flags, getUserId(),
3079                     mContext.getOpPackageName());
3080         } catch (RemoteException e) {
3081             throw e.rethrowFromSystemServer();
3082         }
3083     }
3084 
3085     @Override
setComponentEnabledSettings(List<ComponentEnabledSetting> settings)3086     public void setComponentEnabledSettings(List<ComponentEnabledSetting> settings) {
3087         try {
3088             mPM.setComponentEnabledSettings(settings, getUserId(), mContext.getOpPackageName());
3089         } catch (RemoteException e) {
3090             throw e.rethrowFromSystemServer();
3091         }
3092     }
3093 
3094     @Override
getComponentEnabledSetting(ComponentName componentName)3095     public int getComponentEnabledSetting(ComponentName componentName) {
3096         try {
3097             return mPM.getComponentEnabledSetting(componentName, getUserId());
3098         } catch (RemoteException e) {
3099             throw e.rethrowFromSystemServer();
3100         }
3101     }
3102 
3103     @Override
setApplicationEnabledSetting(String packageName, int newState, int flags)3104     public void setApplicationEnabledSetting(String packageName,
3105                                              int newState, int flags) {
3106         try {
3107             mPM.setApplicationEnabledSetting(packageName, newState, flags,
3108                     getUserId(), mContext.getOpPackageName());
3109         } catch (RemoteException e) {
3110             throw e.rethrowFromSystemServer();
3111         }
3112     }
3113 
3114     @Override
getApplicationEnabledSetting(String packageName)3115     public int getApplicationEnabledSetting(String packageName) {
3116         try {
3117             return mPM.getApplicationEnabledSetting(packageName, getUserId());
3118         } catch (RemoteException e) {
3119             throw e.rethrowFromSystemServer();
3120         }
3121     }
3122 
3123     @Override
flushPackageRestrictionsAsUser(int userId)3124     public void flushPackageRestrictionsAsUser(int userId) {
3125         try {
3126             mPM.flushPackageRestrictionsAsUser(userId);
3127         } catch (RemoteException e) {
3128             throw e.rethrowFromSystemServer();
3129         }
3130     }
3131 
3132     @Override
setApplicationHiddenSettingAsUser(String packageName, boolean hidden, UserHandle user)3133     public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden,
3134             UserHandle user) {
3135         try {
3136             return mPM.setApplicationHiddenSettingAsUser(packageName, hidden,
3137                     user.getIdentifier());
3138         } catch (RemoteException e) {
3139             throw e.rethrowFromSystemServer();
3140         }
3141     }
3142 
3143     @Override
getApplicationHiddenSettingAsUser(String packageName, UserHandle user)3144     public boolean getApplicationHiddenSettingAsUser(String packageName, UserHandle user) {
3145         try {
3146             return mPM.getApplicationHiddenSettingAsUser(packageName, user.getIdentifier());
3147         } catch (RemoteException e) {
3148             throw e.rethrowFromSystemServer();
3149         }
3150     }
3151 
3152     /** @hide */
3153     @Override
setSystemAppState(String packageName, @SystemAppState int state)3154     public void setSystemAppState(String packageName, @SystemAppState int state) {
3155         try {
3156             switch (state) {
3157                 case SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_HIDDEN:
3158                     mPM.setSystemAppHiddenUntilInstalled(packageName, true);
3159                     break;
3160                 case SYSTEM_APP_STATE_HIDDEN_UNTIL_INSTALLED_VISIBLE:
3161                     mPM.setSystemAppHiddenUntilInstalled(packageName, false);
3162                     break;
3163                 case SYSTEM_APP_STATE_INSTALLED:
3164                     mPM.setSystemAppInstallState(packageName, true, getUserId());
3165                     break;
3166                 case SYSTEM_APP_STATE_UNINSTALLED:
3167                     mPM.setSystemAppInstallState(packageName, false, getUserId());
3168                     break;
3169                 default:
3170             }
3171         } catch (RemoteException e) {
3172             throw e.rethrowFromSystemServer();
3173         }
3174     }
3175 
3176     /** @hide */
3177     @Override
getKeySetByAlias(String packageName, String alias)3178     public KeySet getKeySetByAlias(String packageName, String alias) {
3179         Objects.requireNonNull(packageName);
3180         Objects.requireNonNull(alias);
3181         try {
3182             return mPM.getKeySetByAlias(packageName, alias);
3183         } catch (RemoteException e) {
3184             throw e.rethrowFromSystemServer();
3185         }
3186     }
3187 
3188     /** @hide */
3189     @Override
getSigningKeySet(String packageName)3190     public KeySet getSigningKeySet(String packageName) {
3191         Objects.requireNonNull(packageName);
3192         try {
3193             return mPM.getSigningKeySet(packageName);
3194         } catch (RemoteException e) {
3195             throw e.rethrowFromSystemServer();
3196         }
3197     }
3198 
3199     /** @hide */
3200     @Override
isSignedBy(String packageName, KeySet ks)3201     public boolean isSignedBy(String packageName, KeySet ks) {
3202         Objects.requireNonNull(packageName);
3203         Objects.requireNonNull(ks);
3204         try {
3205             return mPM.isPackageSignedByKeySet(packageName, ks);
3206         } catch (RemoteException e) {
3207             throw e.rethrowFromSystemServer();
3208         }
3209     }
3210 
3211     /** @hide */
3212     @Override
isSignedByExactly(String packageName, KeySet ks)3213     public boolean isSignedByExactly(String packageName, KeySet ks) {
3214         Objects.requireNonNull(packageName);
3215         Objects.requireNonNull(ks);
3216         try {
3217             return mPM.isPackageSignedByKeySetExactly(packageName, ks);
3218         } catch (RemoteException e) {
3219             throw e.rethrowFromSystemServer();
3220         }
3221     }
3222 
3223     /**
3224      * @hide
3225      */
3226     @Override
getVerifierDeviceIdentity()3227     public VerifierDeviceIdentity getVerifierDeviceIdentity() {
3228         try {
3229             return mPM.getVerifierDeviceIdentity();
3230         } catch (RemoteException e) {
3231             throw e.rethrowFromSystemServer();
3232         }
3233     }
3234 
3235     @Override
isUpgrade()3236     public boolean isUpgrade() {
3237         return isDeviceUpgrading();
3238     }
3239 
3240     @Override
isDeviceUpgrading()3241     public boolean isDeviceUpgrading() {
3242         try {
3243             return mPM.isDeviceUpgrading();
3244         } catch (RemoteException e) {
3245             throw e.rethrowFromSystemServer();
3246         }
3247     }
3248 
3249     @Override
getPackageInstaller()3250     public PackageInstaller getPackageInstaller() {
3251         if (mInstaller == null) {
3252             try {
3253                 mInstaller = new PackageInstaller(mPM.getPackageInstaller(),
3254                         mContext.getPackageName(), mContext.getAttributionTag(), getUserId());
3255             } catch (RemoteException e) {
3256                 throw e.rethrowFromSystemServer();
3257             }
3258         }
3259         return mInstaller;
3260     }
3261 
3262     @Override
isPackageAvailable(String packageName)3263     public boolean isPackageAvailable(String packageName) {
3264         try {
3265             return mPM.isPackageAvailable(packageName, getUserId());
3266         } catch (RemoteException e) {
3267             throw e.rethrowFromSystemServer();
3268         }
3269     }
3270 
3271     /**
3272      * @hide
3273      */
3274     @Override
addCrossProfileIntentFilter(IntentFilter filter, int sourceUserId, int targetUserId, int flags)3275     public void addCrossProfileIntentFilter(IntentFilter filter, int sourceUserId, int targetUserId,
3276             int flags) {
3277         try {
3278             mPM.addCrossProfileIntentFilter(filter, mContext.getOpPackageName(),
3279                     sourceUserId, targetUserId, flags);
3280         } catch (RemoteException e) {
3281             throw e.rethrowFromSystemServer();
3282         }
3283     }
3284 
3285     /**
3286      * @hide
3287      */
3288     @Override
removeCrossProfileIntentFilter(IntentFilter filter, int sourceUserId, int targetUserId, int flags)3289     public boolean removeCrossProfileIntentFilter(IntentFilter filter, int sourceUserId,
3290             int targetUserId, int flags) {
3291         try {
3292             return mPM.removeCrossProfileIntentFilter(filter, mContext.getOpPackageName(),
3293                     sourceUserId, targetUserId, flags);
3294         } catch (RemoteException e) {
3295             throw e.rethrowFromSystemServer();
3296         }
3297     }
3298 
3299     /**
3300      * @hide
3301      */
3302     @Override
clearCrossProfileIntentFilters(int sourceUserId)3303     public void clearCrossProfileIntentFilters(int sourceUserId) {
3304         try {
3305             mPM.clearCrossProfileIntentFilters(sourceUserId, mContext.getOpPackageName());
3306         } catch (RemoteException e) {
3307             throw e.rethrowFromSystemServer();
3308         }
3309     }
3310 
3311     /**
3312      * @hide
3313      */
loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo)3314     public Drawable loadItemIcon(PackageItemInfo itemInfo, ApplicationInfo appInfo) {
3315         Drawable dr = loadUnbadgedItemIcon(itemInfo, appInfo);
3316         if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
3317             return dr;
3318         }
3319         return getUserBadgedIcon(dr, new UserHandle(getUserId()));
3320     }
3321 
3322     /**
3323      * @hide
3324      */
loadUnbadgedItemIcon(@onNull PackageItemInfo itemInfo, @Nullable ApplicationInfo appInfo)3325     public Drawable loadUnbadgedItemIcon(@NonNull PackageItemInfo itemInfo,
3326             @Nullable ApplicationInfo appInfo) {
3327         if (itemInfo.showUserIcon != UserHandle.USER_NULL) {
3328             // Indicates itemInfo is for a different user (e.g. a profile's parent), so use a
3329             // generic user icon (users generally lack permission to view each other's actual icons)
3330             int targetUserId = itemInfo.showUserIcon;
3331             return UserIcons.getDefaultUserIcon(
3332                     mContext.getResources(), targetUserId, /* light= */ false);
3333         }
3334         Drawable dr = null;
3335         if (itemInfo.packageName != null) {
3336             dr = getDrawable(itemInfo.packageName, itemInfo.icon, appInfo);
3337         }
3338         if (dr == null && itemInfo != appInfo && appInfo != null) {
3339             dr = loadUnbadgedItemIcon(appInfo, appInfo);
3340         }
3341         if (dr == null) {
3342             dr = itemInfo.loadDefaultIcon(this);
3343         }
3344         return dr;
3345     }
3346 
getBadgedDrawable(Drawable drawable, Drawable badgeDrawable, Rect badgeLocation, boolean tryBadgeInPlace)3347     private Drawable getBadgedDrawable(Drawable drawable, Drawable badgeDrawable,
3348             Rect badgeLocation, boolean tryBadgeInPlace) {
3349         final int badgedWidth = drawable.getIntrinsicWidth();
3350         final int badgedHeight = drawable.getIntrinsicHeight();
3351         final boolean canBadgeInPlace = tryBadgeInPlace
3352                 && (drawable instanceof BitmapDrawable)
3353                 && ((BitmapDrawable) drawable).getBitmap().isMutable();
3354 
3355         final Bitmap bitmap;
3356         if (canBadgeInPlace) {
3357             bitmap = ((BitmapDrawable) drawable).getBitmap();
3358         } else {
3359             bitmap = Bitmap.createBitmap(badgedWidth, badgedHeight, Bitmap.Config.ARGB_8888);
3360         }
3361         Canvas canvas = new Canvas(bitmap);
3362 
3363         if (!canBadgeInPlace) {
3364             drawable.setBounds(0, 0, badgedWidth, badgedHeight);
3365             drawable.draw(canvas);
3366         }
3367 
3368         if (badgeLocation != null) {
3369             if (badgeLocation.left < 0 || badgeLocation.top < 0
3370                     || badgeLocation.width() > badgedWidth || badgeLocation.height() > badgedHeight) {
3371                 throw new IllegalArgumentException("Badge location " + badgeLocation
3372                         + " not in badged drawable bounds "
3373                         + new Rect(0, 0, badgedWidth, badgedHeight));
3374             }
3375             badgeDrawable.setBounds(0, 0, badgeLocation.width(), badgeLocation.height());
3376 
3377             canvas.save();
3378             canvas.translate(badgeLocation.left, badgeLocation.top);
3379             badgeDrawable.draw(canvas);
3380             canvas.restore();
3381         } else {
3382             badgeDrawable.setBounds(0, 0, badgedWidth, badgedHeight);
3383             badgeDrawable.draw(canvas);
3384         }
3385 
3386         if (!canBadgeInPlace) {
3387             BitmapDrawable mergedDrawable = new BitmapDrawable(mContext.getResources(), bitmap);
3388 
3389             if (drawable instanceof BitmapDrawable) {
3390                 BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
3391                 mergedDrawable.setTargetDensity(bitmapDrawable.getBitmap().getDensity());
3392             }
3393 
3394             return mergedDrawable;
3395         }
3396 
3397         return drawable;
3398     }
3399 
hasUserBadge(int userId)3400     private boolean hasUserBadge(int userId) {
3401         return getUserManager().hasBadge(userId);
3402     }
3403 
3404     /**
3405      * @hide
3406      */
3407     @Override
getInstallReason(String packageName, UserHandle user)3408     public int getInstallReason(String packageName, UserHandle user) {
3409         try {
3410             return mPM.getInstallReason(packageName, user.getIdentifier());
3411         } catch (RemoteException e) {
3412             throw e.rethrowFromSystemServer();
3413         }
3414     }
3415 
3416     /** {@hide} */
3417     private static class MoveCallbackDelegate extends IPackageMoveObserver.Stub implements
3418             Handler.Callback {
3419         private static final int MSG_CREATED = 1;
3420         private static final int MSG_STATUS_CHANGED = 2;
3421 
3422         final MoveCallback mCallback;
3423         final Handler mHandler;
3424 
MoveCallbackDelegate(MoveCallback callback, Looper looper)3425         public MoveCallbackDelegate(MoveCallback callback, Looper looper) {
3426             mCallback = callback;
3427             mHandler = new Handler(looper, this);
3428         }
3429 
3430         @Override
handleMessage(Message msg)3431         public boolean handleMessage(Message msg) {
3432             switch (msg.what) {
3433                 case MSG_CREATED: {
3434                     final SomeArgs args = (SomeArgs) msg.obj;
3435                     mCallback.onCreated(args.argi1, (Bundle) args.arg2);
3436                     args.recycle();
3437                     return true;
3438                 }
3439                 case MSG_STATUS_CHANGED: {
3440                     final SomeArgs args = (SomeArgs) msg.obj;
3441                     mCallback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3);
3442                     args.recycle();
3443                     return true;
3444                 }
3445             }
3446             return false;
3447         }
3448 
3449         @Override
onCreated(int moveId, Bundle extras)3450         public void onCreated(int moveId, Bundle extras) {
3451             final SomeArgs args = SomeArgs.obtain();
3452             args.argi1 = moveId;
3453             args.arg2 = extras;
3454             mHandler.obtainMessage(MSG_CREATED, args).sendToTarget();
3455         }
3456 
3457         @Override
onStatusChanged(int moveId, int status, long estMillis)3458         public void onStatusChanged(int moveId, int status, long estMillis) {
3459             final SomeArgs args = SomeArgs.obtain();
3460             args.argi1 = moveId;
3461             args.argi2 = status;
3462             args.arg3 = estMillis;
3463             mHandler.obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget();
3464         }
3465     }
3466 
3467     private final ContextImpl mContext;
3468     @UnsupportedAppUsage
3469     private final IPackageManager mPM;
3470 
3471     /** Assume locked until we hear otherwise */
3472     private volatile boolean mUserUnlocked = false;
3473 
3474     private static final Object sSync = new Object();
3475     private static ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>> sIconCache
3476             = new ArrayMap<ResourceName, WeakReference<Drawable.ConstantState>>();
3477     private static ArrayMap<ResourceName, WeakReference<CharSequence>> sStringCache
3478             = new ArrayMap<ResourceName, WeakReference<CharSequence>>();
3479 
3480     @Override
canRequestPackageInstalls()3481     public boolean canRequestPackageInstalls() {
3482         try {
3483             return mPM.canRequestPackageInstalls(mContext.getPackageName(), getUserId());
3484         } catch (RemoteException e) {
3485             throw e.rethrowAsRuntimeException();
3486         }
3487     }
3488 
3489     @Override
getInstantAppResolverSettingsComponent()3490     public ComponentName getInstantAppResolverSettingsComponent() {
3491         try {
3492             return mPM.getInstantAppResolverSettingsComponent();
3493         } catch (RemoteException e) {
3494             throw e.rethrowAsRuntimeException();
3495         }
3496     }
3497 
3498     @Override
getInstantAppInstallerComponent()3499     public ComponentName getInstantAppInstallerComponent() {
3500         try {
3501             return mPM.getInstantAppInstallerComponent();
3502         } catch (RemoteException e) {
3503             throw e.rethrowAsRuntimeException();
3504         }
3505     }
3506 
3507     @Override
getInstantAppAndroidId(String packageName, UserHandle user)3508     public String getInstantAppAndroidId(String packageName, UserHandle user) {
3509         try {
3510             return mPM.getInstantAppAndroidId(packageName, user.getIdentifier());
3511         } catch (RemoteException e) {
3512             throw e.rethrowAsRuntimeException();
3513         }
3514     }
3515 
3516     private static class DexModuleRegisterResult {
3517         final String dexModulePath;
3518         final boolean success;
3519         final String message;
3520 
DexModuleRegisterResult(String dexModulePath, boolean success, String message)3521         private DexModuleRegisterResult(String dexModulePath, boolean success, String message) {
3522             this.dexModulePath = dexModulePath;
3523             this.success = success;
3524             this.message = message;
3525         }
3526     }
3527 
3528     private static class DexModuleRegisterCallbackDelegate
3529             extends android.content.pm.IDexModuleRegisterCallback.Stub
3530             implements Handler.Callback {
3531         private static final int MSG_DEX_MODULE_REGISTERED = 1;
3532         private final DexModuleRegisterCallback callback;
3533         private final Handler mHandler;
3534 
DexModuleRegisterCallbackDelegate(@onNull DexModuleRegisterCallback callback)3535         DexModuleRegisterCallbackDelegate(@NonNull DexModuleRegisterCallback callback) {
3536             this.callback = callback;
3537             mHandler = new Handler(Looper.getMainLooper(), this);
3538         }
3539 
3540         @Override
onDexModuleRegistered(@onNull String dexModulePath, boolean success, @Nullable String message)3541         public void onDexModuleRegistered(@NonNull String dexModulePath, boolean success,
3542                 @Nullable String message)throws RemoteException {
3543             mHandler.obtainMessage(MSG_DEX_MODULE_REGISTERED,
3544                     new DexModuleRegisterResult(dexModulePath, success, message)).sendToTarget();
3545         }
3546 
3547         @Override
handleMessage(Message msg)3548         public boolean handleMessage(Message msg) {
3549             if (msg.what != MSG_DEX_MODULE_REGISTERED) {
3550                 return false;
3551             }
3552             DexModuleRegisterResult result = (DexModuleRegisterResult)msg.obj;
3553             callback.onDexModuleRegistered(result.dexModulePath, result.success, result.message);
3554             return true;
3555         }
3556     }
3557 
3558     @Override
registerDexModule(@onNull String dexModule, @Nullable DexModuleRegisterCallback callback)3559     public void registerDexModule(@NonNull String dexModule,
3560             @Nullable DexModuleRegisterCallback callback) {
3561         // Create the callback delegate to be passed to package manager service.
3562         DexModuleRegisterCallbackDelegate callbackDelegate = null;
3563         if (callback != null) {
3564             callbackDelegate = new DexModuleRegisterCallbackDelegate(callback);
3565         }
3566 
3567         // Check if this is a shared module by looking if the others can read it.
3568         boolean isSharedModule = false;
3569         try {
3570             StructStat stat = Os.stat(dexModule);
3571             if ((OsConstants.S_IROTH & stat.st_mode) != 0) {
3572                 isSharedModule = true;
3573             }
3574         } catch (ErrnoException e) {
3575             if (callbackDelegate != null) {
3576                 callback.onDexModuleRegistered(dexModule, false,
3577                         "Could not get stat the module file: " + e.getMessage());
3578             }
3579             return;
3580         }
3581 
3582         // Invoke the package manager service.
3583         try {
3584             mPM.registerDexModule(mContext.getPackageName(), dexModule,
3585                     isSharedModule, callbackDelegate);
3586         } catch (RemoteException e) {
3587             throw e.rethrowAsRuntimeException();
3588         }
3589     }
3590 
3591     @Override
getHarmfulAppWarning(String packageName)3592     public CharSequence getHarmfulAppWarning(String packageName) {
3593         try {
3594             return mPM.getHarmfulAppWarning(packageName, getUserId());
3595         } catch (RemoteException e) {
3596             throw e.rethrowAsRuntimeException();
3597         }
3598     }
3599 
3600     @Override
setHarmfulAppWarning(String packageName, CharSequence warning)3601     public void setHarmfulAppWarning(String packageName, CharSequence warning) {
3602         try {
3603             mPM.setHarmfulAppWarning(packageName, warning, getUserId());
3604         } catch (RemoteException e) {
3605             throw e.rethrowAsRuntimeException();
3606         }
3607     }
3608 
3609     @Override
getArtManager()3610     public ArtManager getArtManager() {
3611         if (mArtManager == null) {
3612             try {
3613                 mArtManager = new ArtManager(mContext, mPM.getArtManager());
3614             } catch (RemoteException e) {
3615                 throw e.rethrowFromSystemServer();
3616             }
3617         }
3618         return mArtManager;
3619     }
3620 
3621     @Override
getDefaultTextClassifierPackageName()3622     public String getDefaultTextClassifierPackageName() {
3623         try {
3624             return mPM.getDefaultTextClassifierPackageName();
3625         } catch (RemoteException e) {
3626             throw e.rethrowAsRuntimeException();
3627         }
3628     }
3629 
3630     @Override
getSystemTextClassifierPackageName()3631     public String getSystemTextClassifierPackageName() {
3632         try {
3633             return mPM.getSystemTextClassifierPackageName();
3634         } catch (RemoteException e) {
3635             throw e.rethrowAsRuntimeException();
3636         }
3637     }
3638 
3639     @Override
getAttentionServicePackageName()3640     public String getAttentionServicePackageName() {
3641         try {
3642             return mPM.getAttentionServicePackageName();
3643         } catch (RemoteException e) {
3644             throw e.rethrowAsRuntimeException();
3645         }
3646     }
3647 
3648     @Override
getRotationResolverPackageName()3649     public String getRotationResolverPackageName() {
3650         try {
3651             return mPM.getRotationResolverPackageName();
3652         } catch (RemoteException e) {
3653             throw e.rethrowAsRuntimeException();
3654         }
3655     }
3656 
3657     @Override
getWellbeingPackageName()3658     public String getWellbeingPackageName() {
3659         try {
3660             return mPM.getWellbeingPackageName();
3661         } catch (RemoteException e) {
3662             throw e.rethrowAsRuntimeException();
3663         }
3664     }
3665 
3666     @Override
getAppPredictionServicePackageName()3667     public String getAppPredictionServicePackageName() {
3668         try {
3669             return mPM.getAppPredictionServicePackageName();
3670         } catch (RemoteException e) {
3671             throw e.rethrowAsRuntimeException();
3672         }
3673     }
3674 
3675     @Override
getSystemCaptionsServicePackageName()3676     public String getSystemCaptionsServicePackageName() {
3677         try {
3678             return mPM.getSystemCaptionsServicePackageName();
3679         } catch (RemoteException e) {
3680             throw e.rethrowAsRuntimeException();
3681         }
3682     }
3683 
3684     @Override
getSetupWizardPackageName()3685     public String getSetupWizardPackageName() {
3686         try {
3687             return mPM.getSetupWizardPackageName();
3688         } catch (RemoteException e) {
3689             throw e.rethrowAsRuntimeException();
3690         }
3691     }
3692 
3693     @Override
getIncidentReportApproverPackageName()3694     public String getIncidentReportApproverPackageName() {
3695         try {
3696             return mPM.getIncidentReportApproverPackageName();
3697         } catch (RemoteException e) {
3698             throw e.rethrowAsRuntimeException();
3699         }
3700     }
3701 
3702     @Override
isPackageStateProtected(String packageName, int userId)3703     public boolean isPackageStateProtected(String packageName, int userId) {
3704         try {
3705             return mPM.isPackageStateProtected(packageName, userId);
3706         } catch (RemoteException e) {
3707             throw e.rethrowAsRuntimeException();
3708         }
3709     }
3710 
sendDeviceCustomizationReadyBroadcast()3711     public void sendDeviceCustomizationReadyBroadcast() {
3712         try {
3713             mPM.sendDeviceCustomizationReadyBroadcast();
3714         } catch (RemoteException e) {
3715             throw e.rethrowAsRuntimeException();
3716         }
3717     }
3718 
3719     @Override
isAutoRevokeWhitelisted()3720     public boolean isAutoRevokeWhitelisted() {
3721         try {
3722             return mPM.isAutoRevokeWhitelisted(mContext.getPackageName());
3723         } catch (RemoteException e) {
3724             throw e.rethrowAsRuntimeException();
3725         }
3726     }
3727 
3728     @Override
setMimeGroup(String mimeGroup, Set<String> mimeTypes)3729     public void setMimeGroup(String mimeGroup, Set<String> mimeTypes) {
3730         try {
3731             mPM.setMimeGroup(mContext.getPackageName(), mimeGroup, new ArrayList<>(mimeTypes));
3732         } catch (RemoteException e) {
3733             throw e.rethrowAsRuntimeException();
3734         }
3735     }
3736 
3737     @NonNull
3738     @Override
getMimeGroup(String group)3739     public Set<String> getMimeGroup(String group) {
3740         try {
3741             List<String> mimeGroup = mPM.getMimeGroup(mContext.getPackageName(), group);
3742             return new ArraySet<>(mimeGroup);
3743         } catch (RemoteException e) {
3744             throw e.rethrowAsRuntimeException();
3745         }
3746     }
3747 
3748     @Override
getProperty(String propertyName, String packageName)3749     public Property getProperty(String propertyName, String packageName)
3750             throws NameNotFoundException {
3751         Objects.requireNonNull(packageName);
3752         Objects.requireNonNull(propertyName);
3753         return getPropertyAsUser(propertyName, packageName, null /* className */, getUserId());
3754     }
3755 
3756     @Override
getProperty(String propertyName, ComponentName component)3757     public Property getProperty(String propertyName, ComponentName component)
3758             throws NameNotFoundException {
3759         Objects.requireNonNull(component);
3760         Objects.requireNonNull(propertyName);
3761         return getPropertyAsUser(propertyName,
3762                 component.getPackageName(), component.getClassName(), getUserId());
3763     }
3764 
3765     @Override
getPropertyAsUser(@onNull String propertyName, @NonNull String packageName, @Nullable String className, int userId)3766     public Property getPropertyAsUser(@NonNull String propertyName, @NonNull String packageName,
3767             @Nullable String className, int userId) throws NameNotFoundException {
3768         Objects.requireNonNull(packageName);
3769         Objects.requireNonNull(propertyName);
3770         try {
3771             final Property property = mPM.getPropertyAsUser(propertyName,
3772                     packageName, className, userId);
3773             if (property == null) {
3774                 throw new NameNotFoundException();
3775             }
3776             return property;
3777         } catch (RemoteException e) {
3778             throw e.rethrowAsRuntimeException();
3779         }
3780     }
3781 
3782     @Override
queryApplicationProperty(String propertyName)3783     public List<Property> queryApplicationProperty(String propertyName) {
3784         Objects.requireNonNull(propertyName);
3785         try {
3786             final ParceledListSlice<Property> parceledList =
3787                     mPM.queryProperty(propertyName, TYPE_APPLICATION);
3788             if (parceledList == null) {
3789                 return Collections.emptyList();
3790             }
3791             return parceledList.getList();
3792         } catch (RemoteException e) {
3793             throw e.rethrowAsRuntimeException();
3794         }
3795     }
3796 
3797     @Override
queryActivityProperty(String propertyName)3798     public List<Property> queryActivityProperty(String propertyName) {
3799         Objects.requireNonNull(propertyName);
3800         try {
3801             final ParceledListSlice<Property> parceledList =
3802                     mPM.queryProperty(propertyName, TYPE_ACTIVITY);
3803             if (parceledList == null) {
3804                 return Collections.emptyList();
3805             }
3806             return parceledList.getList();
3807         } catch (RemoteException e) {
3808             throw e.rethrowAsRuntimeException();
3809         }
3810     }
3811 
3812     @Override
queryProviderProperty(String propertyName)3813     public List<Property> queryProviderProperty(String propertyName) {
3814         Objects.requireNonNull(propertyName);
3815         try {
3816             final ParceledListSlice<Property> parceledList =
3817                     mPM.queryProperty(propertyName, TYPE_PROVIDER);
3818             if (parceledList == null) {
3819                 return Collections.emptyList();
3820             }
3821             return parceledList.getList();
3822         } catch (RemoteException e) {
3823             throw e.rethrowAsRuntimeException();
3824         }
3825     }
3826 
3827     @Override
queryReceiverProperty(String propertyName)3828     public List<Property> queryReceiverProperty(String propertyName) {
3829         Objects.requireNonNull(propertyName);
3830         try {
3831             final ParceledListSlice<Property> parceledList =
3832                     mPM.queryProperty(propertyName, TYPE_RECEIVER);
3833             if (parceledList == null) {
3834                 return Collections.emptyList();
3835             }
3836             return parceledList.getList();
3837         } catch (RemoteException e) {
3838             throw e.rethrowAsRuntimeException();
3839         }
3840     }
3841 
3842     @Override
queryServiceProperty(String propertyName)3843     public List<Property> queryServiceProperty(String propertyName) {
3844         Objects.requireNonNull(propertyName);
3845         try {
3846             final ParceledListSlice<Property> parceledList =
3847                     mPM.queryProperty(propertyName, TYPE_SERVICE);
3848             if (parceledList == null) {
3849                 return Collections.emptyList();
3850             }
3851             return parceledList.getList();
3852         } catch (RemoteException e) {
3853             throw e.rethrowAsRuntimeException();
3854         }
3855     }
3856 
3857     @Override
canPackageQuery(@onNull String sourcePackageName, @NonNull String targetPackageName)3858     public boolean canPackageQuery(@NonNull String sourcePackageName,
3859             @NonNull String targetPackageName) throws NameNotFoundException {
3860         Objects.requireNonNull(sourcePackageName);
3861         Objects.requireNonNull(targetPackageName);
3862         return canPackageQuery(sourcePackageName, new String[]{targetPackageName})[0];
3863     }
3864 
3865     @Override
3866     @NonNull
canPackageQuery(@onNull String sourcePackageName, @NonNull String[] targetPackageNames)3867     public boolean[] canPackageQuery(@NonNull String sourcePackageName,
3868             @NonNull String[] targetPackageNames) throws NameNotFoundException {
3869         Objects.requireNonNull(sourcePackageName);
3870         Objects.requireNonNull(targetPackageNames);
3871         try {
3872             return mPM.canPackageQuery(sourcePackageName, targetPackageNames, getUserId());
3873         } catch (ParcelableException e) {
3874             e.maybeRethrow(PackageManager.NameNotFoundException.class);
3875             throw new RuntimeException(e);
3876         } catch (RemoteException re) {
3877             throw re.rethrowAsRuntimeException();
3878         }
3879     }
3880 
3881     @Override
makeUidVisible(int recipientUid, int visibleUid)3882     public void makeUidVisible(int recipientUid, int visibleUid) {
3883         try {
3884             mPM.makeUidVisible(recipientUid, visibleUid);
3885         } catch (RemoteException e) {
3886             throw e.rethrowAsRuntimeException();
3887         }
3888     }
3889 
3890     @Override
canUserUninstall(String packageName, UserHandle user)3891     public boolean canUserUninstall(String packageName, UserHandle user) {
3892         try {
3893             return mPM.getBlockUninstallForUser(packageName, user.getIdentifier());
3894         } catch (RemoteException e) {
3895             throw e.rethrowAsRuntimeException();
3896         }
3897     }
3898 
3899     @Override
shouldShowNewAppInstalledNotification()3900     public boolean shouldShowNewAppInstalledNotification() {
3901         return Settings.Global.getInt(mContext.getContentResolver(),
3902                 Settings.Global.SHOW_NEW_APP_INSTALLED_NOTIFICATION_ENABLED, 0) == 1;
3903     }
3904 
3905     @Override
relinquishUpdateOwnership(String targetPackage)3906     public void relinquishUpdateOwnership(String targetPackage) {
3907         Objects.requireNonNull(targetPackage);
3908         try {
3909             mPM.relinquishUpdateOwnership(targetPackage);
3910         } catch (RemoteException e) {
3911             throw e.rethrowFromSystemServer();
3912         }
3913     }
3914 }
3915