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