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