Revert "Reduce coupling between DefaultPermissionGrantPolicy and PM"

This reverts commit 47e8820816f2f48afb0e3db670bf5c52c893c2d3.

Reason for revert: 115854330

Bug: 115854330
Change-Id: I44edb7863daa12352935ffdbed701d4772e93132
(cherry picked from commit fa894222e67542f59e126771ad381dd44fd19f87)
diff --git a/core/java/android/content/pm/PackageManagerInternal.java b/core/java/android/content/pm/PackageManagerInternal.java
index b5b4432..20e1454 100644
--- a/core/java/android/content/pm/PackageManagerInternal.java
+++ b/core/java/android/content/pm/PackageManagerInternal.java
@@ -136,6 +136,24 @@
     public abstract void setVoiceInteractionPackagesProvider(PackagesProvider provider);
 
     /**
+     * Sets the SMS packages provider.
+     * @param provider The packages provider.
+     */
+    public abstract void setSmsAppPackagesProvider(PackagesProvider provider);
+
+    /**
+     * Sets the dialer packages provider.
+     * @param provider The packages provider.
+     */
+    public abstract void setDialerAppPackagesProvider(PackagesProvider provider);
+
+    /**
+     * Sets the sim call manager packages provider.
+     * @param provider The packages provider.
+     */
+    public abstract void setSimCallManagerPackagesProvider(PackagesProvider provider);
+
+    /**
      * Sets the Use Open Wifi packages provider.
      * @param provider The packages provider.
      */
@@ -148,28 +166,26 @@
     public abstract void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider);
 
     /**
-     * Called when the package for the default dialer changed
-     *
-     * @param packageName the new dialer package
-     * @param userId user for which the change was made
+     * Requests granting of the default permissions to the current default SMS app.
+     * @param packageName The default SMS package name.
+     * @param userId The user for which to grant the permissions.
      */
-    public void onDefaultDialerAppChanged(String packageName, int userId) {}
+    public abstract void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId);
 
     /**
-     * Called when the package for the default SMS handler changed
-     *
-     * @param packageName the new sms package
-     * @param userId user for which the change was made
+     * Requests granting of the default permissions to the current default dialer app.
+     * @param packageName The default dialer package name.
+     * @param userId The user for which to grant the permissions.
      */
-    public void onDefaultSmsAppChanged(String packageName, int userId) {}
+    public abstract void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId);
 
     /**
-     * Called when the package for the default sim call manager changed
-     *
-     * @param packageName the new sms package
-     * @param userId user for which the change was made
+     * Requests granting of the default permissions to the current default sim call manager.
+     * @param packageName The default sim call manager package name.
+     * @param userId The user for which to grant the permissions.
      */
-    public void onDefaultSimCallManagerAppChanged(String packageName, int userId) {}
+    public abstract void grantDefaultPermissionsToDefaultSimCallManager(String packageName,
+            int userId);
 
     /**
      * Requests granting of the default permissions to the current default Use Open Wifi app.
@@ -430,8 +446,8 @@
          *
          * @param packageName The package to check for
          * @param uid the uid in which the package is running
-         * @return {@link #USER_TRUSTED} if the user has trusted the package, {@link #USER_BLOCKED}
-         * if user has blocked requests from the package, {@link #USER_DEFAULT} if the user response
+         * @return {@link USER_TRUSTED} if the user has trusted the package, {@link USER_BLOCKED}
+         * if user has blocked requests from the package, {@link USER_DEFAULT} if the user response
          * is not yet available
          */
         int getPackageTrustedToInstallApps(String packageName, int uid);
@@ -545,7 +561,7 @@
     /**
      * Returns a list without a change observer.
      *
-     * @see #getPackageList(PackageListObserver)
+     * {@see #getPackageList(PackageListObserver)}
      */
     public @NonNull PackageList getPackageList() {
         return getPackageList(null);
@@ -574,16 +590,7 @@
     /**
      * Returns a package object for the disabled system package name.
      */
-    public abstract @Nullable PackageParser.Package getDisabledSystemPackage(
-            @NonNull String packageName);
-
-    /**
-     * Returns the package name for the disabled system package.
-     *
-     * This is equivalent to
-     * {@link #getDisabledSystemPackage(String)}.{@link PackageParser.Package#packageName}
-     */
-    public abstract @Nullable String getDisabledSystemPackageName(@NonNull String packageName);
+    public abstract @Nullable PackageParser.Package getDisabledPackage(@NonNull String packageName);
 
     /**
      * Returns whether or not the component is the resolver activity.
@@ -612,7 +619,7 @@
      * Access may be limited based upon whether the calling or target applications
      * are instant applications.
      *
-     * @see #canAccessInstantApps
+     * @see #canAccessInstantApps(int)
      */
     public abstract boolean filterAppAccess(
             @Nullable PackageParser.Package pkg, int callingUid, int userId);
@@ -628,9 +635,6 @@
     public abstract void updatePermissionFlagsTEMP(@NonNull String permName,
             @NonNull String packageName, int flagMask, int flagValues, int userId);
 
-    /** Returns whether the given package was signed by the platform */
-    public abstract boolean isPlatformSigned(String pkg);
-
     /**
      * Returns true if it's still safe to restore data backed up from this app's version
      * that was signed with restoringFromSigHash.
diff --git a/services/core/java/com/android/server/pm/ComponentResolver.java b/services/core/java/com/android/server/pm/ComponentResolver.java
index 5bf323a..560ca92 100644
--- a/services/core/java/com/android/server/pm/ComponentResolver.java
+++ b/services/core/java/com/android/server/pm/ComponentResolver.java
@@ -378,7 +378,7 @@
         for (int i = newIntents.size() - 1; i >= 0; --i) {
             final PackageParser.ActivityIntentInfo intentInfo = newIntents.get(i);
             final PackageParser.Package disabledPkg = sPackageManagerInternal
-                    .getDisabledSystemPackage(intentInfo.activity.info.packageName);
+                    .getDisabledPackage(intentInfo.activity.info.packageName);
             final List<PackageParser.Activity> systemActivities =
                     disabledPkg != null ? disabledPkg.activities : null;
             adjustPriority(systemActivities, intentInfo, setupWizardPackage);
diff --git a/services/core/java/com/android/server/pm/PackageManagerService.java b/services/core/java/com/android/server/pm/PackageManagerService.java
index 91af0ec..db0c13c 100644
--- a/services/core/java/com/android/server/pm/PackageManagerService.java
+++ b/services/core/java/com/android/server/pm/PackageManagerService.java
@@ -718,8 +718,6 @@
     @GuardedBy("mPackages")
     final private ArraySet<PackageListObserver> mPackageListObservers = new ArraySet<>();
 
-    private PackageManager mPackageManager;
-
     class PackageParserCallback implements PackageParser.Callback {
         @Override public final boolean hasFeature(String feature) {
             return PackageManagerService.this.hasSystemFeature(feature, 0);
@@ -22238,22 +22236,6 @@
         }
 
         @Override
-        public boolean isPlatformSigned(String packageName) {
-            PackageSetting packageSetting = mSettings.mPackages.get(packageName);
-            if (packageSetting == null) {
-                return false;
-            }
-            PackageParser.Package pkg = packageSetting.pkg;
-            if (pkg == null) {
-                // May happen if package in on a removable sd card
-                return false;
-            }
-            return pkg.mSigningDetails.hasAncestorOrSelf(mPlatformPackage.mSigningDetails)
-                    || mPlatformPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
-                    PackageParser.SigningDetails.CertCapabilities.PERMISSION);
-        }
-
-        @Override
         public boolean isDataRestoreSafe(byte[] restoringFromSigHash, String packageName) {
             SigningDetails sd = getSigningDetails(packageName);
             if (sd == null) {
@@ -22365,7 +22347,7 @@
         }
 
         @Override
-        public PackageParser.Package getDisabledSystemPackage(String packageName) {
+        public PackageParser.Package getDisabledPackage(String packageName) {
             synchronized (mPackages) {
                 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName);
                 return (ps != null) ? ps.pkg : null;
@@ -22373,12 +22355,6 @@
         }
 
         @Override
-        public @Nullable String getDisabledSystemPackageName(@NonNull String packageName) {
-            PackageParser.Package pkg = getDisabledSystemPackage(packageName);
-            return pkg == null ? null : pkg.packageName;
-        }
-
-        @Override
         public String getKnownPackageName(int knownPackage, int userId) {
             switch(knownPackage) {
                 case PackageManagerInternal.PACKAGE_BROWSER:
@@ -22416,6 +22392,21 @@
         }
 
         @Override
+        public void setSmsAppPackagesProvider(PackagesProvider provider) {
+            mDefaultPermissionPolicy.setSmsAppPackagesProvider(provider);
+        }
+
+        @Override
+        public void setDialerAppPackagesProvider(PackagesProvider provider) {
+            mDefaultPermissionPolicy.setDialerAppPackagesProvider(provider);
+        }
+
+        @Override
+        public void setSimCallManagerPackagesProvider(PackagesProvider provider) {
+            mDefaultPermissionPolicy.setSimCallManagerPackagesProvider(provider);
+        }
+
+        @Override
         public void setUseOpenWifiAppPackagesProvider(PackagesProvider provider) {
             mDefaultPermissionPolicy.setUseOpenWifiAppPackagesProvider(provider);
         }
@@ -22426,10 +22417,22 @@
         }
 
         @Override
-        public void onDefaultDialerAppChanged(String packageName, int userId) {
+        public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
+            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsApp(packageName, userId);
+        }
+
+        @Override
+        public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
             synchronized (mPackages) {
                 mSettings.setDefaultDialerPackageNameLPw(packageName, userId);
             }
+            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerApp(packageName, userId);
+        }
+
+        @Override
+        public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
+            mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManager(
+                    packageName, userId);
         }
 
         @Override
diff --git a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
index d9eb7e8..846c7b7 100644
--- a/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
+++ b/services/core/java/com/android/server/pm/permission/DefaultPermissionGrantPolicy.java
@@ -23,13 +23,12 @@
 import android.annotation.Nullable;
 import android.app.ActivityManager;
 import android.app.DownloadManager;
-import android.app.SearchManager;
 import android.app.admin.DevicePolicyManager;
 import android.companion.CompanionDeviceManager;
 import android.content.Context;
 import android.content.Intent;
 import android.content.pm.ApplicationInfo;
-import android.content.pm.PackageInfo;
+import android.content.pm.PackageList;
 import android.content.pm.PackageManager;
 import android.content.pm.PackageManagerInternal;
 import android.content.pm.PackageManagerInternal.PackagesProvider;
@@ -54,7 +53,6 @@
 import android.provider.MediaStore;
 import android.provider.Telephony.Sms.Intents;
 import android.security.Credentials;
-import android.speech.RecognitionService;
 import android.telephony.TelephonyManager;
 import android.text.TextUtils;
 import android.util.ArrayMap;
@@ -63,7 +61,6 @@
 import android.util.Slog;
 import android.util.Xml;
 
-import com.android.internal.util.ArrayUtils;
 import com.android.internal.util.XmlUtils;
 import com.android.server.LocalServices;
 
@@ -76,7 +73,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
 import java.util.Map;
@@ -98,15 +94,10 @@
     private static final String TAG = "DefaultPermGrantPolicy"; // must be <= 23 chars
     private static final boolean DEBUG = false;
 
-    @PackageManager.ResolveInfoFlags
-    private static final int DEFAULT_INTENT_QUERY_FLAGS =
+    private static final int DEFAULT_FLAGS =
             PackageManager.MATCH_DIRECT_BOOT_AWARE | PackageManager.MATCH_DIRECT_BOOT_UNAWARE
                     | PackageManager.MATCH_UNINSTALLED_PACKAGES;
 
-    @PackageManager.PackageInfoFlags
-    private static final int DEFAULT_PACKAGE_INFO_QUERY_FLAGS =
-            PackageManager.MATCH_UNINSTALLED_PACKAGES | PackageManager.GET_PERMISSIONS;
-
     private static final String AUDIO_MIME_TYPE = "audio/mpeg";
 
     private static final String TAG_EXCEPTIONS = "exceptions";
@@ -117,8 +108,6 @@
     private static final String ATTR_FIXED = "fixed";
 
     private static final Set<String> PHONE_PERMISSIONS = new ArraySet<>();
-
-
     static {
         PHONE_PERMISSIONS.add(Manifest.permission.READ_PHONE_STATE);
         PHONE_PERMISSIONS.add(Manifest.permission.CALL_PHONE);
@@ -230,7 +219,7 @@
     private final DefaultPermissionGrantedCallback mPermissionGrantedCallback;
     public interface DefaultPermissionGrantedCallback {
         /** Callback when permissions have been granted */
-        void onDefaultRuntimePermissionsGranted(int userId);
+        public void onDefaultRuntimePermissionsGranted(int userId);
     }
 
     public DefaultPermissionGrantPolicy(Context context, Looper looper,
@@ -302,9 +291,9 @@
         grantDefaultPermissionExceptions(userId);
     }
 
-    private void grantRuntimePermissionsForSystemPackage(int userId, PackageInfo pkg) {
+    private void grantRuntimePermissionsForPackage(int userId, PackageParser.Package pkg) {
         Set<String> permissions = new ArraySet<>();
-        for (String permission : pkg.requestedPermissions) {
+        for (String permission :  pkg.requestedPermissions) {
             final BasePermission bp = mPermissionManager.getPermission(permission);
             if (bp == null) {
                 continue;
@@ -318,71 +307,36 @@
         }
     }
 
+    private void grantAllRuntimePermissions(int userId) {
+        Log.i(TAG, "Granting all runtime permissions for user " + userId);
+        final PackageList packageList = mServiceInternal.getPackageList();
+        for (String packageName : packageList.getPackageNames()) {
+            final PackageParser.Package pkg = mServiceInternal.getPackage(packageName);
+            if (pkg == null) {
+                continue;
+            }
+            grantRuntimePermissionsForPackage(userId, pkg);
+        }
+    }
+
     public void scheduleReadDefaultPermissionExceptions() {
         mHandler.sendEmptyMessage(MSG_READ_DEFAULT_PERMISSION_EXCEPTIONS);
     }
 
     private void grantPermissionsToSysComponentsAndPrivApps(int userId) {
         Log.i(TAG, "Granting permissions to platform components for user " + userId);
-        List<PackageInfo> packages = mContext.getPackageManager().getInstalledPackagesAsUser(
-                DEFAULT_PACKAGE_INFO_QUERY_FLAGS, UserHandle.USER_SYSTEM);
-        for (PackageInfo pkg : packages) {
+        final PackageList packageList = mServiceInternal.getPackageList();
+        for (String packageName : packageList.getPackageNames()) {
+            final PackageParser.Package pkg = mServiceInternal.getPackage(packageName);
             if (pkg == null) {
                 continue;
             }
             if (!isSysComponentOrPersistentPlatformSignedPrivApp(pkg)
                     || !doesPackageSupportRuntimePermissions(pkg)
-                    || ArrayUtils.isEmpty(pkg.requestedPermissions)) {
+                    || pkg.requestedPermissions.isEmpty()) {
                 continue;
             }
-            grantRuntimePermissionsForSystemPackage(userId, pkg);
-        }
-    }
-
-    @SafeVarargs
-    private final void grantIgnoringSystemPackage(String packageName, int userId,
-            Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, false, true, permissionGroups);
-    }
-
-    @SafeVarargs
-    private final void grantSystemFixedPermissionsToSystemPackage(String packageName, int userId,
-            Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, true, false, permissionGroups);
-    }
-
-    @SafeVarargs
-    private final void grantPermissionsToSystemPackage(
-            String packageName, int userId, Set<String>... permissionGroups) {
-        grantPermissionsToSystemPackage(packageName, userId, false, false, permissionGroups);
-    }
-
-    @SafeVarargs
-    private final void grantPermissionsToSystemPackage(String packageName, int userId,
-            boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
-        if (!ignoreSystemPackage && !isSystemPackage(packageName)) {
-            return;
-        }
-        grantRuntimePermissionsToPackage(getSystemPackageInfo(packageName),
-                userId, systemFixed, ignoreSystemPackage, permissionGroups);
-    }
-
-    @SafeVarargs
-    private final void grantRuntimePermissionsToPackage(String packageName, int userId,
-            boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
-        grantRuntimePermissionsToPackage(getPackageInfo(packageName),
-                userId, systemFixed, ignoreSystemPackage, permissionGroups);
-    }
-
-    @SafeVarargs
-    private final void grantRuntimePermissionsToPackage(PackageInfo packageName, int userId,
-            boolean systemFixed, boolean ignoreSystemPackage, Set<String>... permissionGroups) {
-        if (packageName == null) return;
-        if (doesPackageSupportRuntimePermissions(packageName)) {
-            for (Set<String> permissionGroup : permissionGroups) {
-                grantRuntimePermissions(packageName, permissionGroup, systemFixed,
-                        ignoreSystemPackage, userId);
-            }
+            grantRuntimePermissionsForPackage(userId, pkg);
         }
     }
 
@@ -425,373 +379,594 @@
                 syncAdapterPackagesProvider.getPackages(CalendarContract.AUTHORITY, userId) : null;
 
         // Installer
-        grantSystemFixedPermissionsToSystemPackage(
-                getKnownPackage(PackageManagerInternal.PACKAGE_INSTALLER, userId),
-                userId, STORAGE_PERMISSIONS);
+        final String installerPackageName = mServiceInternal.getKnownPackageName(
+                PackageManagerInternal.PACKAGE_INSTALLER, userId);
+        PackageParser.Package installerPackage = getSystemPackage(installerPackageName);
+        if (installerPackage != null
+                && doesPackageSupportRuntimePermissions(installerPackage)) {
+            grantRuntimePermissions(installerPackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // Verifier
-        final String verifier = getKnownPackage(PackageManagerInternal.PACKAGE_VERIFIER, userId);
-        grantSystemFixedPermissionsToSystemPackage(verifier, userId, STORAGE_PERMISSIONS);
-        grantPermissionsToSystemPackage(verifier, userId, PHONE_PERMISSIONS, SMS_PERMISSIONS);
+        final String verifierPackageName = mServiceInternal.getKnownPackageName(
+                PackageManagerInternal.PACKAGE_VERIFIER, userId);
+        PackageParser.Package verifierPackage = getSystemPackage(verifierPackageName);
+        if (verifierPackage != null
+                && doesPackageSupportRuntimePermissions(verifierPackage)) {
+            grantRuntimePermissions(verifierPackage, STORAGE_PERMISSIONS, true, userId);
+            grantRuntimePermissions(verifierPackage, PHONE_PERMISSIONS, false, userId);
+            grantRuntimePermissions(verifierPackage, SMS_PERMISSIONS, false, userId);
+        }
 
         // SetupWizard
-        grantPermissionsToSystemPackage(
-                getKnownPackage(PackageManagerInternal.PACKAGE_SETUP_WIZARD, userId), userId,
-                PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, LOCATION_PERMISSIONS, CAMERA_PERMISSIONS);
+        final String setupWizardPackageName = mServiceInternal.getKnownPackageName(
+                PackageManagerInternal.PACKAGE_SETUP_WIZARD, userId);
+        PackageParser.Package setupPackage = getSystemPackage(setupWizardPackageName);
+        if (setupPackage != null
+                && doesPackageSupportRuntimePermissions(setupPackage)) {
+            grantRuntimePermissions(setupPackage, PHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(setupPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(setupPackage, LOCATION_PERMISSIONS, userId);
+            grantRuntimePermissions(setupPackage, CAMERA_PERMISSIONS, userId);
+        }
 
         // Camera
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(MediaStore.ACTION_IMAGE_CAPTURE, userId),
-                userId, CAMERA_PERMISSIONS, MICROPHONE_PERMISSIONS, STORAGE_PERMISSIONS);
+        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
+        PackageParser.Package cameraPackage = getDefaultSystemHandlerActivityPackage(
+                cameraIntent, userId);
+        if (cameraPackage != null
+                && doesPackageSupportRuntimePermissions(cameraPackage)) {
+            grantRuntimePermissions(cameraPackage, CAMERA_PERMISSIONS, userId);
+            grantRuntimePermissions(cameraPackage, MICROPHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(cameraPackage, STORAGE_PERMISSIONS, userId);
+        }
 
         // Media provider
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultProviderAuthorityPackage(MediaStore.AUTHORITY, userId), userId,
-                STORAGE_PERMISSIONS, MEDIA_AURAL_PERMISSIONS, MEDIA_VISUAL_PERMISSIONS,
-                PHONE_PERMISSIONS);
+        PackageParser.Package mediaStorePackage = getDefaultProviderAuthorityPackage(
+                MediaStore.AUTHORITY, userId);
+        if (mediaStorePackage != null) {
+            grantRuntimePermissions(mediaStorePackage, STORAGE_PERMISSIONS, true, userId);
+            grantRuntimePermissions(mediaStorePackage, MEDIA_AURAL_PERMISSIONS, true, userId);
+            grantRuntimePermissions(mediaStorePackage, MEDIA_VISUAL_PERMISSIONS, true, userId);
+            grantRuntimePermissions(mediaStorePackage, PHONE_PERMISSIONS, true, userId);
+        }
 
         // Downloads provider
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultProviderAuthorityPackage("downloads", userId), userId,
-                STORAGE_PERMISSIONS);
+        PackageParser.Package downloadsPackage = getDefaultProviderAuthorityPackage(
+                "downloads", userId);
+        if (downloadsPackage != null) {
+            grantRuntimePermissions(downloadsPackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // Downloads UI
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(
-                        DownloadManager.ACTION_VIEW_DOWNLOADS, userId),
-                userId, STORAGE_PERMISSIONS);
+        Intent downloadsUiIntent = new Intent(DownloadManager.ACTION_VIEW_DOWNLOADS);
+        PackageParser.Package downloadsUiPackage = getDefaultSystemHandlerActivityPackage(
+                downloadsUiIntent, userId);
+        if (downloadsUiPackage != null
+                && doesPackageSupportRuntimePermissions(downloadsUiPackage)) {
+            grantRuntimePermissions(downloadsUiPackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // Storage provider
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultProviderAuthorityPackage("com.android.externalstorage.documents", userId),
-                userId, STORAGE_PERMISSIONS);
+        PackageParser.Package storagePackage = getDefaultProviderAuthorityPackage(
+                "com.android.externalstorage.documents", userId);
+        if (storagePackage != null) {
+            grantRuntimePermissions(storagePackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // CertInstaller
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(Credentials.INSTALL_ACTION, userId), userId,
-                STORAGE_PERMISSIONS);
+        Intent certInstallerIntent = new Intent(Credentials.INSTALL_ACTION);
+        PackageParser.Package certInstallerPackage = getDefaultSystemHandlerActivityPackage(
+                certInstallerIntent, userId);
+        if (certInstallerPackage != null
+                && doesPackageSupportRuntimePermissions(certInstallerPackage)) {
+            grantRuntimePermissions(certInstallerPackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // Dialer
         if (dialerAppPackageNames == null) {
-            String dialerPackage =
-                    getDefaultSystemHandlerActivityPackage(Intent.ACTION_DIAL, userId);
-            grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
+            Intent dialerIntent = new Intent(Intent.ACTION_DIAL);
+            PackageParser.Package dialerPackage = getDefaultSystemHandlerActivityPackage(
+                    dialerIntent, userId);
+            if (dialerPackage != null) {
+                grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
+            }
         } else {
             for (String dialerAppPackageName : dialerAppPackageNames) {
-                grantDefaultPermissionsToDefaultSystemDialerApp(dialerAppPackageName, userId);
+                PackageParser.Package dialerPackage = getSystemPackage(dialerAppPackageName);
+                if (dialerPackage != null) {
+                    grantDefaultPermissionsToDefaultSystemDialerApp(dialerPackage, userId);
+                }
             }
         }
 
         // Sim call manager
         if (simCallManagerPackageNames != null) {
             for (String simCallManagerPackageName : simCallManagerPackageNames) {
-                grantDefaultPermissionsToDefaultSystemSimCallManager(
-                        simCallManagerPackageName, userId);
+                PackageParser.Package simCallManagerPackage =
+                        getSystemPackage(simCallManagerPackageName);
+                if (simCallManagerPackage != null) {
+                    grantDefaultPermissionsToDefaultSimCallManager(simCallManagerPackage,
+                            userId);
+                }
             }
         }
 
         // Use Open Wifi
         if (useOpenWifiAppPackageNames != null) {
             for (String useOpenWifiPackageName : useOpenWifiAppPackageNames) {
-                grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(
-                        useOpenWifiPackageName, userId);
+                PackageParser.Package useOpenWifiPackage =
+                        getSystemPackage(useOpenWifiPackageName);
+                if (useOpenWifiPackage != null) {
+                    grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(useOpenWifiPackage,
+                            userId);
+                }
             }
         }
 
         // SMS
         if (smsAppPackageNames == null) {
-            String smsPackage = getDefaultSystemHandlerActivityPackageForCategory(
-                    Intent.CATEGORY_APP_MESSAGING, userId);
-            grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
+            Intent smsIntent = new Intent(Intent.ACTION_MAIN);
+            smsIntent.addCategory(Intent.CATEGORY_APP_MESSAGING);
+            PackageParser.Package smsPackage = getDefaultSystemHandlerActivityPackage(
+                    smsIntent, userId);
+            if (smsPackage != null) {
+               grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
+            }
         } else {
-            for (String smsPackage : smsAppPackageNames) {
-                grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
+            for (String smsPackageName : smsAppPackageNames) {
+                PackageParser.Package smsPackage = getSystemPackage(smsPackageName);
+                if (smsPackage != null) {
+                    grantDefaultPermissionsToDefaultSystemSmsApp(smsPackage, userId);
+                }
             }
         }
 
         // Cell Broadcast Receiver
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(Intents.SMS_CB_RECEIVED_ACTION, userId),
-                userId, SMS_PERMISSIONS);
+        Intent cbrIntent = new Intent(Intents.SMS_CB_RECEIVED_ACTION);
+        PackageParser.Package cbrPackage =
+                getDefaultSystemHandlerActivityPackage(cbrIntent, userId);
+        if (cbrPackage != null && doesPackageSupportRuntimePermissions(cbrPackage)) {
+            grantRuntimePermissions(cbrPackage, SMS_PERMISSIONS, userId);
+        }
 
         // Carrier Provisioning Service
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerServicePackage(Intents.SMS_CARRIER_PROVISION_ACTION, userId),
-                userId, SMS_PERMISSIONS);
+        Intent carrierProvIntent = new Intent(Intents.SMS_CARRIER_PROVISION_ACTION);
+        PackageParser.Package carrierProvPackage =
+                getDefaultSystemHandlerServicePackage(carrierProvIntent, userId);
+        if (carrierProvPackage != null
+                && doesPackageSupportRuntimePermissions(carrierProvPackage)) {
+            grantRuntimePermissions(carrierProvPackage, SMS_PERMISSIONS, false, userId);
+        }
 
         // Calendar
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackageForCategory(
-                        Intent.CATEGORY_APP_CALENDAR, userId),
-                userId, CALENDAR_PERMISSIONS, CONTACTS_PERMISSIONS);
+        Intent calendarIntent = new Intent(Intent.ACTION_MAIN);
+        calendarIntent.addCategory(Intent.CATEGORY_APP_CALENDAR);
+        PackageParser.Package calendarPackage = getDefaultSystemHandlerActivityPackage(
+                calendarIntent, userId);
+        if (calendarPackage != null
+                && doesPackageSupportRuntimePermissions(calendarPackage)) {
+            grantRuntimePermissions(calendarPackage, CALENDAR_PERMISSIONS, userId);
+            grantRuntimePermissions(calendarPackage, CONTACTS_PERMISSIONS, userId);
+        }
 
         // Calendar provider
-        String calendarProvider =
-                getDefaultProviderAuthorityPackage(CalendarContract.AUTHORITY, userId);
-        grantPermissionsToSystemPackage(calendarProvider, userId,
-                CONTACTS_PERMISSIONS, STORAGE_PERMISSIONS);
-        grantSystemFixedPermissionsToSystemPackage(calendarProvider, userId, CALENDAR_PERMISSIONS);
+        PackageParser.Package calendarProviderPackage = getDefaultProviderAuthorityPackage(
+                CalendarContract.AUTHORITY, userId);
+        if (calendarProviderPackage != null) {
+            grantRuntimePermissions(calendarProviderPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(calendarProviderPackage, CALENDAR_PERMISSIONS,
+                    true, userId);
+            grantRuntimePermissions(calendarProviderPackage, STORAGE_PERMISSIONS, userId);
+        }
 
         // Calendar provider sync adapters
-        grantPermissionToEachSystemPackage(
-                getHeadlessSyncAdapterPackages(calendarSyncAdapterPackages, userId),
-                userId, CALENDAR_PERMISSIONS);
-
-        // Contacts
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackageForCategory(
-                        Intent.CATEGORY_APP_CONTACTS, userId),
-                userId, CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
-
-        // Contacts provider sync adapters
-        grantPermissionToEachSystemPackage(
-                getHeadlessSyncAdapterPackages(contactsSyncAdapterPackages, userId),
-                userId, CONTACTS_PERMISSIONS);
-
-        // Contacts provider
-        String contactsProviderPackage =
-                getDefaultProviderAuthorityPackage(ContactsContract.AUTHORITY, userId);
-        grantSystemFixedPermissionsToSystemPackage(contactsProviderPackage, userId,
-                CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
-        grantPermissionsToSystemPackage(contactsProviderPackage, userId, STORAGE_PERMISSIONS);
-
-        // Device provisioning
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(
-                        DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE, userId),
-                userId, CONTACTS_PERMISSIONS);
-
-        // Maps
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackageForCategory(Intent.CATEGORY_APP_MAPS, userId),
-                userId, LOCATION_PERMISSIONS);
-
-        // Gallery
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackageForCategory(
-                        Intent.CATEGORY_APP_GALLERY, userId),
-                userId, STORAGE_PERMISSIONS, MEDIA_VISUAL_PERMISSIONS);
-
-        // Email
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackageForCategory(
-                        Intent.CATEGORY_APP_EMAIL, userId),
-                userId, CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS);
-
-        // Browser
-        String browserPackage = getKnownPackage(PackageManagerInternal.PACKAGE_BROWSER, userId);
-        if (browserPackage == null) {
-            browserPackage = getDefaultSystemHandlerActivityPackageForCategory(
-                    Intent.CATEGORY_APP_BROWSER, userId);
-            if (!isSystemPackage(browserPackage)) {
-                browserPackage = null;
+        List<PackageParser.Package> calendarSyncAdapters = getHeadlessSyncAdapterPackages(
+                calendarSyncAdapterPackages, userId);
+        final int calendarSyncAdapterCount = calendarSyncAdapters.size();
+        for (int i = 0; i < calendarSyncAdapterCount; i++) {
+            PackageParser.Package calendarSyncAdapter = calendarSyncAdapters.get(i);
+            if (doesPackageSupportRuntimePermissions(calendarSyncAdapter)) {
+                grantRuntimePermissions(calendarSyncAdapter, CALENDAR_PERMISSIONS, userId);
             }
         }
-        grantRuntimePermissionsToPackage(browserPackage, userId,
-                false /* systemFixed */, false /* ignoreSystemPackage */,
-                LOCATION_PERMISSIONS);
+
+        // Contacts
+        Intent contactsIntent = new Intent(Intent.ACTION_MAIN);
+        contactsIntent.addCategory(Intent.CATEGORY_APP_CONTACTS);
+        PackageParser.Package contactsPackage = getDefaultSystemHandlerActivityPackage(
+                contactsIntent, userId);
+        if (contactsPackage != null
+                && doesPackageSupportRuntimePermissions(contactsPackage)) {
+            grantRuntimePermissions(contactsPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(contactsPackage, PHONE_PERMISSIONS, userId);
+        }
+
+        // Contacts provider sync adapters
+        List<PackageParser.Package> contactsSyncAdapters = getHeadlessSyncAdapterPackages(
+                contactsSyncAdapterPackages, userId);
+        final int contactsSyncAdapterCount = contactsSyncAdapters.size();
+        for (int i = 0; i < contactsSyncAdapterCount; i++) {
+            PackageParser.Package contactsSyncAdapter = contactsSyncAdapters.get(i);
+            if (doesPackageSupportRuntimePermissions(contactsSyncAdapter)) {
+                grantRuntimePermissions(contactsSyncAdapter, CONTACTS_PERMISSIONS, userId);
+            }
+        }
+
+        // Contacts provider
+        PackageParser.Package contactsProviderPackage = getDefaultProviderAuthorityPackage(
+                ContactsContract.AUTHORITY, userId);
+        if (contactsProviderPackage != null) {
+            grantRuntimePermissions(contactsProviderPackage, CONTACTS_PERMISSIONS,
+                    true, userId);
+            grantRuntimePermissions(contactsProviderPackage, PHONE_PERMISSIONS,
+                    true, userId);
+            grantRuntimePermissions(contactsProviderPackage, STORAGE_PERMISSIONS, userId);
+        }
+
+        // Device provisioning
+        Intent deviceProvisionIntent = new Intent(
+                DevicePolicyManager.ACTION_PROVISION_MANAGED_DEVICE);
+        PackageParser.Package deviceProvisionPackage =
+                getDefaultSystemHandlerActivityPackage(deviceProvisionIntent, userId);
+        if (deviceProvisionPackage != null
+                && doesPackageSupportRuntimePermissions(deviceProvisionPackage)) {
+            grantRuntimePermissions(deviceProvisionPackage, CONTACTS_PERMISSIONS, userId);
+        }
+
+        // Maps
+        Intent mapsIntent = new Intent(Intent.ACTION_MAIN);
+        mapsIntent.addCategory(Intent.CATEGORY_APP_MAPS);
+        PackageParser.Package mapsPackage = getDefaultSystemHandlerActivityPackage(
+                mapsIntent, userId);
+        if (mapsPackage != null
+                && doesPackageSupportRuntimePermissions(mapsPackage)) {
+            grantRuntimePermissions(mapsPackage, LOCATION_PERMISSIONS, userId);
+        }
+
+        // Gallery
+        Intent galleryIntent = new Intent(Intent.ACTION_MAIN);
+        galleryIntent.addCategory(Intent.CATEGORY_APP_GALLERY);
+        PackageParser.Package galleryPackage = getDefaultSystemHandlerActivityPackage(
+                galleryIntent, userId);
+        if (galleryPackage != null
+                && doesPackageSupportRuntimePermissions(galleryPackage)) {
+            grantRuntimePermissions(galleryPackage, STORAGE_PERMISSIONS, userId);
+            grantRuntimePermissions(galleryPackage, MEDIA_VISUAL_PERMISSIONS, userId);
+        }
+
+        // Email
+        Intent emailIntent = new Intent(Intent.ACTION_MAIN);
+        emailIntent.addCategory(Intent.CATEGORY_APP_EMAIL);
+        PackageParser.Package emailPackage = getDefaultSystemHandlerActivityPackage(
+                emailIntent, userId);
+        if (emailPackage != null
+                && doesPackageSupportRuntimePermissions(emailPackage)) {
+            grantRuntimePermissions(emailPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(emailPackage, CALENDAR_PERMISSIONS, userId);
+        }
+
+        // Browser
+        PackageParser.Package browserPackage = null;
+        String defaultBrowserPackage = mServiceInternal.getKnownPackageName(
+                PackageManagerInternal.PACKAGE_BROWSER, userId);
+        if (defaultBrowserPackage != null) {
+            browserPackage = getPackage(defaultBrowserPackage);
+        }
+        if (browserPackage == null) {
+            Intent browserIntent = new Intent(Intent.ACTION_MAIN);
+            browserIntent.addCategory(Intent.CATEGORY_APP_BROWSER);
+            browserPackage = getDefaultSystemHandlerActivityPackage(
+                    browserIntent, userId);
+        }
+        if (browserPackage != null
+                && doesPackageSupportRuntimePermissions(browserPackage)) {
+            grantRuntimePermissions(browserPackage, LOCATION_PERMISSIONS, userId);
+        }
 
         // Voice interaction
         if (voiceInteractPackageNames != null) {
             for (String voiceInteractPackageName : voiceInteractPackageNames) {
-                grantPermissionsToSystemPackage(voiceInteractPackageName, userId,
-                        CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS, MICROPHONE_PERMISSIONS,
-                        PHONE_PERMISSIONS, SMS_PERMISSIONS, LOCATION_PERMISSIONS);
+                PackageParser.Package voiceInteractPackage = getSystemPackage(
+                        voiceInteractPackageName);
+                if (voiceInteractPackage != null
+                        && doesPackageSupportRuntimePermissions(voiceInteractPackage)) {
+                    grantRuntimePermissions(voiceInteractPackage,
+                            CONTACTS_PERMISSIONS, userId);
+                    grantRuntimePermissions(voiceInteractPackage,
+                            CALENDAR_PERMISSIONS, userId);
+                    grantRuntimePermissions(voiceInteractPackage,
+                            MICROPHONE_PERMISSIONS, userId);
+                    grantRuntimePermissions(voiceInteractPackage,
+                            PHONE_PERMISSIONS, userId);
+                    grantRuntimePermissions(voiceInteractPackage,
+                            SMS_PERMISSIONS, userId);
+                    grantRuntimePermissions(voiceInteractPackage,
+                            LOCATION_PERMISSIONS, userId);
+                }
             }
         }
 
         if (ActivityManager.isLowRamDeviceStatic()) {
             // Allow voice search on low-ram devices
-            grantPermissionsToSystemPackage(
-                    getDefaultSystemHandlerActivityPackage(
-                            SearchManager.INTENT_ACTION_GLOBAL_SEARCH, userId),
-                    userId, MICROPHONE_PERMISSIONS, LOCATION_PERMISSIONS);
+            Intent globalSearchIntent = new Intent("android.search.action.GLOBAL_SEARCH");
+            PackageParser.Package globalSearchPickerPackage =
+                getDefaultSystemHandlerActivityPackage(globalSearchIntent, userId);
+
+            if (globalSearchPickerPackage != null
+                    && doesPackageSupportRuntimePermissions(globalSearchPickerPackage)) {
+                grantRuntimePermissions(globalSearchPickerPackage,
+                    MICROPHONE_PERMISSIONS, false, userId);
+                grantRuntimePermissions(globalSearchPickerPackage,
+                    LOCATION_PERMISSIONS, false, userId);
+            }
         }
 
         // Voice recognition
-        Intent voiceRecoIntent = new Intent(RecognitionService.SERVICE_INTERFACE)
-                .addCategory(Intent.CATEGORY_DEFAULT);
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerServicePackage(voiceRecoIntent, userId), userId,
-                MICROPHONE_PERMISSIONS);
+        Intent voiceRecoIntent = new Intent("android.speech.RecognitionService");
+        voiceRecoIntent.addCategory(Intent.CATEGORY_DEFAULT);
+        PackageParser.Package voiceRecoPackage = getDefaultSystemHandlerServicePackage(
+                voiceRecoIntent, userId);
+        if (voiceRecoPackage != null
+                && doesPackageSupportRuntimePermissions(voiceRecoPackage)) {
+            grantRuntimePermissions(voiceRecoPackage, MICROPHONE_PERMISSIONS, userId);
+        }
 
         // Location
         if (locationPackageNames != null) {
             for (String packageName : locationPackageNames) {
-                grantPermissionsToSystemPackage(packageName, userId,
-                        CONTACTS_PERMISSIONS, CALENDAR_PERMISSIONS, MICROPHONE_PERMISSIONS,
-                        PHONE_PERMISSIONS, SMS_PERMISSIONS, CAMERA_PERMISSIONS,
-                        SENSORS_PERMISSIONS, STORAGE_PERMISSIONS);
-                grantSystemFixedPermissionsToSystemPackage(packageName, userId,
-                        LOCATION_PERMISSIONS);
+                PackageParser.Package locationPackage = getSystemPackage(packageName);
+                if (locationPackage != null
+                        && doesPackageSupportRuntimePermissions(locationPackage)) {
+                    grantRuntimePermissions(locationPackage, CONTACTS_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, CALENDAR_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, MICROPHONE_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, PHONE_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, SMS_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, LOCATION_PERMISSIONS,
+                            true, userId);
+                    grantRuntimePermissions(locationPackage, CAMERA_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, SENSORS_PERMISSIONS, userId);
+                    grantRuntimePermissions(locationPackage, STORAGE_PERMISSIONS, userId);
+                }
             }
         }
 
         // Music
-        Intent musicIntent = new Intent(Intent.ACTION_VIEW)
-                .addCategory(Intent.CATEGORY_DEFAULT)
-                .setDataAndType(Uri.fromFile(new File("foo.mp3")), AUDIO_MIME_TYPE);
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(musicIntent, userId), userId,
-                STORAGE_PERMISSIONS, MEDIA_AURAL_PERMISSIONS);
+        Intent musicIntent = new Intent(Intent.ACTION_VIEW);
+        musicIntent.addCategory(Intent.CATEGORY_DEFAULT);
+        musicIntent.setDataAndType(Uri.fromFile(new File("foo.mp3")),
+                AUDIO_MIME_TYPE);
+        PackageParser.Package musicPackage = getDefaultSystemHandlerActivityPackage(
+                musicIntent, userId);
+        if (musicPackage != null
+                && doesPackageSupportRuntimePermissions(musicPackage)) {
+            grantRuntimePermissions(musicPackage, STORAGE_PERMISSIONS, userId);
+            grantRuntimePermissions(musicPackage, MEDIA_AURAL_PERMISSIONS, userId);
+        }
 
         // Home
-        Intent homeIntent = new Intent(Intent.ACTION_MAIN)
-                .addCategory(Intent.CATEGORY_HOME)
-                .addCategory(Intent.CATEGORY_LAUNCHER_APP);
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(homeIntent, userId), userId,
-                LOCATION_PERMISSIONS);
+        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
+        homeIntent.addCategory(Intent.CATEGORY_HOME);
+        homeIntent.addCategory(Intent.CATEGORY_LAUNCHER_APP);
+        PackageParser.Package homePackage = getDefaultSystemHandlerActivityPackage(
+                homeIntent, userId);
+        if (homePackage != null
+                && doesPackageSupportRuntimePermissions(homePackage)) {
+            grantRuntimePermissions(homePackage, LOCATION_PERMISSIONS, false, userId);
+        }
 
         // Watches
         if (mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0)) {
             // Home application on watches
+            Intent wearHomeIntent = new Intent(Intent.ACTION_MAIN);
+            wearHomeIntent.addCategory(Intent.CATEGORY_HOME_MAIN);
 
-            String wearPackage = getDefaultSystemHandlerActivityPackageForCategory(
-                    Intent.CATEGORY_HOME_MAIN, userId);
-            grantPermissionsToSystemPackage(wearPackage, userId,
-                    CONTACTS_PERMISSIONS, MICROPHONE_PERMISSIONS, LOCATION_PERMISSIONS);
-            grantSystemFixedPermissionsToSystemPackage(wearPackage, userId, PHONE_PERMISSIONS);
+            PackageParser.Package wearHomePackage = getDefaultSystemHandlerActivityPackage(
+                    wearHomeIntent, userId);
+
+            if (wearHomePackage != null
+                    && doesPackageSupportRuntimePermissions(wearHomePackage)) {
+                grantRuntimePermissions(wearHomePackage, CONTACTS_PERMISSIONS, false,
+                        userId);
+                grantRuntimePermissions(wearHomePackage, PHONE_PERMISSIONS, true, userId);
+                grantRuntimePermissions(wearHomePackage, MICROPHONE_PERMISSIONS, false,
+                        userId);
+                grantRuntimePermissions(wearHomePackage, LOCATION_PERMISSIONS, false,
+                        userId);
+            }
 
             // Fitness tracking on watches
-            grantPermissionsToSystemPackage(
-                    getDefaultSystemHandlerActivityPackage(ACTION_TRACK, userId), userId,
-                    SENSORS_PERMISSIONS, LOCATION_PERMISSIONS);
+            Intent trackIntent = new Intent(ACTION_TRACK);
+            PackageParser.Package trackPackage = getDefaultSystemHandlerActivityPackage(
+                    trackIntent, userId);
+            if (trackPackage != null
+                    && doesPackageSupportRuntimePermissions(trackPackage)) {
+                grantRuntimePermissions(trackPackage, SENSORS_PERMISSIONS, false, userId);
+                grantRuntimePermissions(trackPackage, LOCATION_PERMISSIONS, false, userId);
+            }
         }
 
         // Print Spooler
-        grantSystemFixedPermissionsToSystemPackage(PrintManager.PRINT_SPOOLER_PACKAGE_NAME, userId,
-                LOCATION_PERMISSIONS);
+        PackageParser.Package printSpoolerPackage = getSystemPackage(
+                PrintManager.PRINT_SPOOLER_PACKAGE_NAME);
+        if (printSpoolerPackage != null
+                && doesPackageSupportRuntimePermissions(printSpoolerPackage)) {
+            grantRuntimePermissions(printSpoolerPackage, LOCATION_PERMISSIONS, true, userId);
+        }
 
         // EmergencyInfo
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(
-                        TelephonyManager.ACTION_EMERGENCY_ASSISTANCE, userId),
-                userId, CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
+        Intent emergencyInfoIntent = new Intent(TelephonyManager.ACTION_EMERGENCY_ASSISTANCE);
+        PackageParser.Package emergencyInfoPckg = getDefaultSystemHandlerActivityPackage(
+                emergencyInfoIntent, userId);
+        if (emergencyInfoPckg != null
+                && doesPackageSupportRuntimePermissions(emergencyInfoPckg)) {
+            grantRuntimePermissions(emergencyInfoPckg, CONTACTS_PERMISSIONS, true, userId);
+            grantRuntimePermissions(emergencyInfoPckg, PHONE_PERMISSIONS, true, userId);
+        }
 
         // NFC Tag viewer
-        Intent nfcTagIntent = new Intent(Intent.ACTION_VIEW)
-                .setType("vnd.android.cursor.item/ndef_msg");
-        grantPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(nfcTagIntent, userId), userId,
-                CONTACTS_PERMISSIONS, PHONE_PERMISSIONS);
+        Intent nfcTagIntent = new Intent(Intent.ACTION_VIEW);
+        nfcTagIntent.setType("vnd.android.cursor.item/ndef_msg");
+        PackageParser.Package nfcTagPkg = getDefaultSystemHandlerActivityPackage(
+                nfcTagIntent, userId);
+        if (nfcTagPkg != null
+                && doesPackageSupportRuntimePermissions(nfcTagPkg)) {
+            grantRuntimePermissions(nfcTagPkg, CONTACTS_PERMISSIONS, false, userId);
+            grantRuntimePermissions(nfcTagPkg, PHONE_PERMISSIONS, false, userId);
+        }
 
         // Storage Manager
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(
-                        StorageManager.ACTION_MANAGE_STORAGE, userId),
-                userId, STORAGE_PERMISSIONS);
+        Intent storageManagerIntent = new Intent(StorageManager.ACTION_MANAGE_STORAGE);
+        PackageParser.Package storageManagerPckg = getDefaultSystemHandlerActivityPackage(
+                storageManagerIntent, userId);
+        if (storageManagerPckg != null
+                && doesPackageSupportRuntimePermissions(storageManagerPckg)) {
+            grantRuntimePermissions(storageManagerPckg, STORAGE_PERMISSIONS, true, userId);
+        }
 
         // Companion devices
-        grantSystemFixedPermissionsToSystemPackage(
-                CompanionDeviceManager.COMPANION_DEVICE_DISCOVERY_PACKAGE_NAME, userId,
-                LOCATION_PERMISSIONS);
+        PackageParser.Package companionDeviceDiscoveryPackage = getSystemPackage(
+                CompanionDeviceManager.COMPANION_DEVICE_DISCOVERY_PACKAGE_NAME);
+        if (companionDeviceDiscoveryPackage != null
+                && doesPackageSupportRuntimePermissions(companionDeviceDiscoveryPackage)) {
+            grantRuntimePermissions(companionDeviceDiscoveryPackage,
+                    LOCATION_PERMISSIONS, true, userId);
+        }
 
         // Ringtone Picker
-        grantSystemFixedPermissionsToSystemPackage(
-                getDefaultSystemHandlerActivityPackage(
-                        RingtoneManager.ACTION_RINGTONE_PICKER, userId),
-                userId, STORAGE_PERMISSIONS);
+        Intent ringtonePickerIntent = new Intent(RingtoneManager.ACTION_RINGTONE_PICKER);
+        PackageParser.Package ringtonePickerPackage =
+                getDefaultSystemHandlerActivityPackage(ringtonePickerIntent, userId);
+        if (ringtonePickerPackage != null
+                && doesPackageSupportRuntimePermissions(ringtonePickerPackage)) {
+            grantRuntimePermissions(ringtonePickerPackage,
+                    STORAGE_PERMISSIONS, true, userId);
+        }
 
         // TextClassifier Service
         String textClassifierPackageName =
                 mContext.getPackageManager().getSystemTextClassifierPackageName();
         if (!TextUtils.isEmpty(textClassifierPackageName)) {
-            grantPermissionsToSystemPackage(textClassifierPackageName, userId,
-                    PHONE_PERMISSIONS, SMS_PERMISSIONS, CALENDAR_PERMISSIONS,
-                    LOCATION_PERMISSIONS, CONTACTS_PERMISSIONS);
+            PackageParser.Package textClassifierPackage =
+                    getSystemPackage(textClassifierPackageName);
+            if (textClassifierPackage != null
+                    && doesPackageSupportRuntimePermissions(textClassifierPackage)) {
+                grantRuntimePermissions(textClassifierPackage, PHONE_PERMISSIONS, false, userId);
+                grantRuntimePermissions(textClassifierPackage, SMS_PERMISSIONS, false, userId);
+                grantRuntimePermissions(textClassifierPackage, CALENDAR_PERMISSIONS, false, userId);
+                grantRuntimePermissions(textClassifierPackage, LOCATION_PERMISSIONS, false, userId);
+                grantRuntimePermissions(textClassifierPackage, CONTACTS_PERMISSIONS, false, userId);
+            }
         }
 
         // There is no real "marker" interface to identify the shared storage backup, it is
         // hardcoded in BackupManagerService.SHARED_BACKUP_AGENT_PACKAGE.
-        grantSystemFixedPermissionsToSystemPackage("com.android.sharedstoragebackup", userId,
-                STORAGE_PERMISSIONS);
+        PackageParser.Package sharedStorageBackupPackage = getSystemPackage(
+                "com.android.sharedstoragebackup");
+        if (sharedStorageBackupPackage != null) {
+            grantRuntimePermissions(sharedStorageBackupPackage, STORAGE_PERMISSIONS, true, userId);
+        }
 
         if (mPermissionGrantedCallback != null) {
             mPermissionGrantedCallback.onDefaultRuntimePermissionsGranted(userId);
         }
     }
 
-    private String getDefaultSystemHandlerActivityPackageForCategory(String category, int userId) {
-        return getDefaultSystemHandlerActivityPackage(
-                new Intent(Intent.ACTION_MAIN).addCategory(category), userId);
-    }
-
-    @SafeVarargs
-    private final void grantPermissionToEachSystemPackage(
-            ArrayList<String> packages, int userId, Set<String>... permissions) {
-        if (packages == null) return;
-        final int count = packages.size();
-        for (int i = 0; i < count; i++) {
-            grantPermissionsToSystemPackage(packages.get(i), userId, permissions);
-        }
-    }
-
-    private String getKnownPackage(int knownPkgId, int userId) {
-        return mServiceInternal.getKnownPackageName(knownPkgId, userId);
-    }
-
     private void grantDefaultPermissionsToDefaultSystemDialerApp(
-            String dialerPackage, int userId) {
-        if (dialerPackage == null) {
-            return;
+            PackageParser.Package dialerPackage, int userId) {
+        if (doesPackageSupportRuntimePermissions(dialerPackage)) {
+            boolean isPhonePermFixed =
+                    mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0);
+            grantRuntimePermissions(
+                    dialerPackage, PHONE_PERMISSIONS, isPhonePermFixed, userId);
+            grantRuntimePermissions(dialerPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(dialerPackage, SMS_PERMISSIONS, userId);
+            grantRuntimePermissions(dialerPackage, MICROPHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(dialerPackage, CAMERA_PERMISSIONS, userId);
         }
-        boolean isPhonePermFixed =
-                mContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WATCH, 0);
-        if (isPhonePermFixed) {
-            grantSystemFixedPermissionsToSystemPackage(dialerPackage, userId, PHONE_PERMISSIONS);
-        } else {
-            grantPermissionsToSystemPackage(dialerPackage, userId, PHONE_PERMISSIONS);
-        }
-        grantPermissionsToSystemPackage(dialerPackage, userId,
-                CONTACTS_PERMISSIONS, SMS_PERMISSIONS, MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
     }
 
-    private void grantDefaultPermissionsToDefaultSystemSmsApp(String smsPackage, int userId) {
-        grantPermissionsToSystemPackage(smsPackage, userId,
-                PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, SMS_PERMISSIONS,
-                STORAGE_PERMISSIONS, MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
+    private void grantDefaultPermissionsToDefaultSystemSmsApp(
+            PackageParser.Package smsPackage, int userId) {
+        if (doesPackageSupportRuntimePermissions(smsPackage)) {
+            grantRuntimePermissions(smsPackage, PHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(smsPackage, CONTACTS_PERMISSIONS, userId);
+            grantRuntimePermissions(smsPackage, SMS_PERMISSIONS, userId);
+            grantRuntimePermissions(smsPackage, STORAGE_PERMISSIONS, userId);
+            grantRuntimePermissions(smsPackage, MICROPHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(smsPackage, CAMERA_PERMISSIONS, userId);
+        }
     }
 
     private void grantDefaultPermissionsToDefaultSystemUseOpenWifiApp(
-            String useOpenWifiPackage, int userId) {
-        grantPermissionsToSystemPackage(
-                useOpenWifiPackage, userId, COARSE_LOCATION_PERMISSIONS);
+            PackageParser.Package useOpenWifiPackage, int userId) {
+        if (doesPackageSupportRuntimePermissions(useOpenWifiPackage)) {
+            grantRuntimePermissions(useOpenWifiPackage, COARSE_LOCATION_PERMISSIONS, userId);
+        }
     }
 
     public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) {
         Log.i(TAG, "Granting permissions to default sms app for user:" + userId);
-        grantIgnoringSystemPackage(packageName, userId,
-                PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, SMS_PERMISSIONS, STORAGE_PERMISSIONS,
-                MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
+        if (packageName == null) {
+            return;
+        }
+        PackageParser.Package smsPackage = getPackage(packageName);
+        if (smsPackage != null && doesPackageSupportRuntimePermissions(smsPackage)) {
+            grantRuntimePermissions(smsPackage, PHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(smsPackage, CONTACTS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(smsPackage, SMS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(smsPackage, STORAGE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(smsPackage, MICROPHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(smsPackage, CAMERA_PERMISSIONS, false, true, userId);
+        }
     }
 
     public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) {
-        mServiceInternal.onDefaultDialerAppChanged(packageName, userId);
         Log.i(TAG, "Granting permissions to default dialer app for user:" + userId);
-        grantIgnoringSystemPackage(packageName, userId,
-                PHONE_PERMISSIONS, CONTACTS_PERMISSIONS, SMS_PERMISSIONS,
-                MICROPHONE_PERMISSIONS, CAMERA_PERMISSIONS);
+        if (packageName == null) {
+            return;
+        }
+        PackageParser.Package dialerPackage = getPackage(packageName);
+        if (dialerPackage != null
+                && doesPackageSupportRuntimePermissions(dialerPackage)) {
+            grantRuntimePermissions(dialerPackage, PHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(dialerPackage, CONTACTS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(dialerPackage, SMS_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(dialerPackage, MICROPHONE_PERMISSIONS, false, true, userId);
+            grantRuntimePermissions(dialerPackage, CAMERA_PERMISSIONS, false, true, userId);
+        }
     }
 
     public void grantDefaultPermissionsToDefaultUseOpenWifiApp(String packageName, int userId) {
         Log.i(TAG, "Granting permissions to default Use Open WiFi app for user:" + userId);
-        grantIgnoringSystemPackage(packageName, userId, COARSE_LOCATION_PERMISSIONS);
+        if (packageName == null) {
+            return;
+        }
+        PackageParser.Package useOpenWifiPackage = getPackage(packageName);
+        if (useOpenWifiPackage != null
+                && doesPackageSupportRuntimePermissions(useOpenWifiPackage)) {
+            grantRuntimePermissions(
+                    useOpenWifiPackage, COARSE_LOCATION_PERMISSIONS, false, true, userId);
+        }
+    }
+
+    private void grantDefaultPermissionsToDefaultSimCallManager(
+            PackageParser.Package simCallManagerPackage, int userId) {
+        Log.i(TAG, "Granting permissions to sim call manager for user:" + userId);
+        if (doesPackageSupportRuntimePermissions(simCallManagerPackage)) {
+            grantRuntimePermissions(simCallManagerPackage, PHONE_PERMISSIONS, userId);
+            grantRuntimePermissions(simCallManagerPackage, MICROPHONE_PERMISSIONS, userId);
+        }
     }
 
     public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) {
         if (packageName == null) {
             return;
         }
-        Log.i(TAG, "Granting permissions to sim call manager for user:" + userId);
-        grantRuntimePermissionsToPackage(packageName, userId, false, false,
-                PHONE_PERMISSIONS, MICROPHONE_PERMISSIONS);
-    }
-
-    private void grantDefaultPermissionsToDefaultSystemSimCallManager(
-            String packageName, int userId) {
-        if (isSystemPackage(packageName)) {
-            grantDefaultPermissionsToDefaultSimCallManager(packageName, userId);
+        PackageParser.Package simCallManagerPackage = getPackage(packageName);
+        if (simCallManagerPackage != null) {
+            grantDefaultPermissionsToDefaultSimCallManager(simCallManagerPackage, userId);
         }
     }
 
@@ -801,8 +976,13 @@
             return;
         }
         for (String packageName : packageNames) {
-            grantPermissionsToSystemPackage(packageName, userId,
-                    PHONE_PERMISSIONS, LOCATION_PERMISSIONS, SMS_PERMISSIONS);
+            PackageParser.Package carrierPackage = getSystemPackage(packageName);
+            if (carrierPackage != null
+                    && doesPackageSupportRuntimePermissions(carrierPackage)) {
+                grantRuntimePermissions(carrierPackage, PHONE_PERMISSIONS, userId);
+                grantRuntimePermissions(carrierPackage, LOCATION_PERMISSIONS, userId);
+                grantRuntimePermissions(carrierPackage, SMS_PERMISSIONS, userId);
+            }
         }
     }
 
@@ -812,9 +992,15 @@
             return;
         }
         for (String packageName : packageNames) {
-            grantPermissionsToSystemPackage(packageName, userId,
-                    PHONE_PERMISSIONS, MICROPHONE_PERMISSIONS, LOCATION_PERMISSIONS,
-                    CAMERA_PERMISSIONS, CONTACTS_PERMISSIONS);
+            PackageParser.Package imsServicePackage = getSystemPackage(packageName);
+            if (imsServicePackage != null
+                    && doesPackageSupportRuntimePermissions(imsServicePackage)) {
+                grantRuntimePermissions(imsServicePackage, PHONE_PERMISSIONS, userId);
+                grantRuntimePermissions(imsServicePackage, MICROPHONE_PERMISSIONS, userId);
+                grantRuntimePermissions(imsServicePackage, LOCATION_PERMISSIONS, userId);
+                grantRuntimePermissions(imsServicePackage, CAMERA_PERMISSIONS, userId);
+                grantRuntimePermissions(imsServicePackage, CONTACTS_PERMISSIONS, userId);
+            }
         }
     }
 
@@ -825,12 +1011,15 @@
             return;
         }
         for (String packageName : packageNames) {
-            // Grant these permissions as system-fixed, so that nobody can accidentally
-            // break cellular data.
-            grantSystemFixedPermissionsToSystemPackage(packageName, userId,
-                    PHONE_PERMISSIONS, LOCATION_PERMISSIONS);
+            PackageParser.Package dataServicePackage = getSystemPackage(packageName);
+            if (dataServicePackage != null
+                    && doesPackageSupportRuntimePermissions(dataServicePackage)) {
+                // Grant these permissions as system-fixed, so that nobody can accidentally
+                // break cellular data.
+                grantRuntimePermissions(dataServicePackage, PHONE_PERMISSIONS, true, userId);
+                grantRuntimePermissions(dataServicePackage, LOCATION_PERMISSIONS, true, userId);
+            }
         }
-
     }
 
     public void revokeDefaultPermissionsFromDisabledTelephonyDataServices(
@@ -840,17 +1029,25 @@
             return;
         }
         for (String packageName : packageNames) {
-            PackageInfo pkg = getSystemPackageInfo(packageName);
-            if (isSystemPackage(pkg) && doesPackageSupportRuntimePermissions(pkg)) {
-                revokeRuntimePermissions(packageName, PHONE_PERMISSIONS, true, userId);
-                revokeRuntimePermissions(packageName, LOCATION_PERMISSIONS, true, userId);
+            PackageParser.Package dataServicePackage = getSystemPackage(packageName);
+            if (dataServicePackage != null
+                    && doesPackageSupportRuntimePermissions(dataServicePackage)) {
+                revokeRuntimePermissions(dataServicePackage, PHONE_PERMISSIONS, true, userId);
+                revokeRuntimePermissions(dataServicePackage, LOCATION_PERMISSIONS, true, userId);
             }
         }
     }
 
     public void grantDefaultPermissionsToActiveLuiApp(String packageName, int userId) {
         Log.i(TAG, "Granting permissions to active LUI app for user:" + userId);
-        grantSystemFixedPermissionsToSystemPackage(packageName, userId, CAMERA_PERMISSIONS);
+        if (packageName == null) {
+            return;
+        }
+        PackageParser.Package luiAppPackage = getSystemPackage(packageName);
+        if (luiAppPackage != null
+                && doesPackageSupportRuntimePermissions(luiAppPackage)) {
+            grantRuntimePermissions(luiAppPackage, CAMERA_PERMISSIONS, true, userId);
+        }
     }
 
     public void revokeDefaultPermissionsFromLuiApps(String[] packageNames, int userId) {
@@ -859,116 +1056,123 @@
             return;
         }
         for (String packageName : packageNames) {
-            PackageInfo pkg = getSystemPackageInfo(packageName);
-            if (isSystemPackage(pkg) && doesPackageSupportRuntimePermissions(pkg)) {
-                revokeRuntimePermissions(packageName, CAMERA_PERMISSIONS, true, userId);
+            PackageParser.Package luiAppPackage = getSystemPackage(packageName);
+            if (luiAppPackage != null
+                    && doesPackageSupportRuntimePermissions(luiAppPackage)) {
+                revokeRuntimePermissions(luiAppPackage, CAMERA_PERMISSIONS, true, userId);
             }
         }
     }
 
     public void grantDefaultPermissionsToDefaultBrowser(String packageName, int userId) {
         Log.i(TAG, "Granting permissions to default browser for user:" + userId);
-        grantPermissionsToSystemPackage(packageName, userId, LOCATION_PERMISSIONS);
+        if (packageName == null) {
+            return;
+        }
+        PackageParser.Package browserPackage = getSystemPackage(packageName);
+        if (browserPackage != null
+                && doesPackageSupportRuntimePermissions(browserPackage)) {
+            grantRuntimePermissions(browserPackage, LOCATION_PERMISSIONS, false, false, userId);
+        }
     }
 
-    private String getDefaultSystemHandlerActivityPackage(String intentAction, int userId) {
-        return getDefaultSystemHandlerActivityPackage(new Intent(intentAction), userId);
-    }
-
-    private String getDefaultSystemHandlerActivityPackage(Intent intent, int userId) {
+    private PackageParser.Package getDefaultSystemHandlerActivityPackage(
+            Intent intent, int userId) {
         ResolveInfo handler = mServiceInternal.resolveIntent(intent,
-                intent.resolveType(mContext.getContentResolver()), DEFAULT_INTENT_QUERY_FLAGS,
-                userId, false, Binder.getCallingUid());
+                intent.resolveType(mContext.getContentResolver()), DEFAULT_FLAGS, userId, false,
+                Binder.getCallingUid());
         if (handler == null || handler.activityInfo == null) {
             return null;
         }
         if (mServiceInternal.isResolveActivityComponent(handler.activityInfo)) {
             return null;
         }
-        String packageName = handler.activityInfo.packageName;
-        return isSystemPackage(packageName) ? packageName : null;
+        return getSystemPackage(handler.activityInfo.packageName);
     }
 
-    private String getDefaultSystemHandlerServicePackage(String intentAction, int userId) {
-        return getDefaultSystemHandlerServicePackage(new Intent(intentAction), userId);
-    }
-
-    private String getDefaultSystemHandlerServicePackage(
+    private PackageParser.Package getDefaultSystemHandlerServicePackage(
             Intent intent, int userId) {
         List<ResolveInfo> handlers = mServiceInternal.queryIntentServices(
-                intent, DEFAULT_INTENT_QUERY_FLAGS, Binder.getCallingUid(), userId);
+                intent, DEFAULT_FLAGS, Binder.getCallingUid(), userId);
         if (handlers == null) {
             return null;
         }
         final int handlerCount = handlers.size();
         for (int i = 0; i < handlerCount; i++) {
             ResolveInfo handler = handlers.get(i);
-            String handlerPackage = handler.serviceInfo.packageName;
-            if (isSystemPackage(handlerPackage)) {
+            PackageParser.Package handlerPackage = getSystemPackage(
+                    handler.serviceInfo.packageName);
+            if (handlerPackage != null) {
                 return handlerPackage;
             }
         }
         return null;
     }
 
-    private ArrayList<String> getHeadlessSyncAdapterPackages(
+    private List<PackageParser.Package> getHeadlessSyncAdapterPackages(
             String[] syncAdapterPackageNames, int userId) {
-        ArrayList<String> syncAdapterPackages = new ArrayList<>();
+        List<PackageParser.Package> syncAdapterPackages = new ArrayList<>();
 
-        Intent homeIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
+        Intent homeIntent = new Intent(Intent.ACTION_MAIN);
+        homeIntent.addCategory(Intent.CATEGORY_LAUNCHER);
 
         for (String syncAdapterPackageName : syncAdapterPackageNames) {
             homeIntent.setPackage(syncAdapterPackageName);
 
             ResolveInfo homeActivity = mServiceInternal.resolveIntent(homeIntent,
-                    homeIntent.resolveType(mContext.getContentResolver()),
-                    DEFAULT_INTENT_QUERY_FLAGS,
+                    homeIntent.resolveType(mContext.getContentResolver()), DEFAULT_FLAGS,
                     userId, false, Binder.getCallingUid());
             if (homeActivity != null) {
                 continue;
             }
 
-            if (isSystemPackage(syncAdapterPackageName)) {
-                syncAdapterPackages.add(syncAdapterPackageName);
+            PackageParser.Package syncAdapterPackage = getSystemPackage(syncAdapterPackageName);
+            if (syncAdapterPackage != null) {
+                syncAdapterPackages.add(syncAdapterPackage);
             }
         }
 
         return syncAdapterPackages;
     }
 
-    private String getDefaultProviderAuthorityPackage(String authority, int userId) {
-        ProviderInfo provider = mServiceInternal.resolveContentProvider(
-                authority, DEFAULT_INTENT_QUERY_FLAGS, userId);
+    private PackageParser.Package getDefaultProviderAuthorityPackage(
+            String authority, int userId) {
+        ProviderInfo provider =
+                mServiceInternal.resolveContentProvider(authority, DEFAULT_FLAGS, userId);
         if (provider != null) {
-            return provider.packageName;
+            return getSystemPackage(provider.packageName);
         }
         return null;
     }
 
-    private boolean isSystemPackage(String packageName) {
-        return isSystemPackage(getSystemPackageInfo(packageName));
+    private PackageParser.Package getPackage(String packageName) {
+        return mServiceInternal.getPackage(packageName);
     }
 
-    private boolean isSystemPackage(PackageInfo pkg) {
-        if (pkg == null) {
-            return false;
+    private PackageParser.Package getSystemPackage(String packageName) {
+        PackageParser.Package pkg = getPackage(packageName);
+        if (pkg != null && pkg.isSystem()) {
+            return !isSysComponentOrPersistentPlatformSignedPrivApp(pkg) ? pkg : null;
         }
-        return pkg.applicationInfo.isSystemApp()
-                && !isSysComponentOrPersistentPlatformSignedPrivApp(pkg);
+        return null;
     }
 
-    private void grantRuntimePermissions(PackageInfo pkg, Set<String> permissions,
+    private void grantRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
+            int userId) {
+        grantRuntimePermissions(pkg, permissions, false, false, userId);
+    }
+
+    private void grantRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
             boolean systemFixed, int userId) {
         grantRuntimePermissions(pkg, permissions, systemFixed, false, userId);
     }
 
-    private void revokeRuntimePermissions(String packageName, Set<String> permissions,
+    private void revokeRuntimePermissions(PackageParser.Package pkg, Set<String> permissions,
             boolean systemFixed, int userId) {
-        PackageInfo pkg = getSystemPackageInfo(packageName);
-        if (ArrayUtils.isEmpty(pkg.requestedPermissions)) {
+        if (pkg.requestedPermissions.isEmpty()) {
             return;
         }
-        Set<String> revokablePermissions = new ArraySet<>(Arrays.asList(pkg.requestedPermissions));
+        Set<String> revokablePermissions = new ArraySet<>(pkg.requestedPermissions);
 
         for (String permission : permissions) {
             // We can't revoke what wasn't requested.
@@ -977,7 +1181,7 @@
             }
 
             final int flags = mServiceInternal.getPermissionFlagsTEMP(
-                    permission, packageName, userId);
+                    permission, pkg.packageName, userId);
 
             // We didn't get this through the default grant policy. Move along.
             if ((flags & PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT) == 0) {
@@ -993,35 +1197,29 @@
             if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0 && !systemFixed) {
                 continue;
             }
-            mServiceInternal.revokeRuntimePermission(packageName, permission, userId, false);
+            mServiceInternal.revokeRuntimePermission(pkg.packageName, permission, userId, false);
 
             if (DEBUG) {
                 Log.i(TAG, "revoked " + (systemFixed ? "fixed " : "not fixed ")
-                        + permission + " to " + packageName);
+                        + permission + " to " + pkg.packageName);
             }
 
             // Remove the GRANTED_BY_DEFAULT flag without touching the others.
             // Note that we do not revoke FLAG_PERMISSION_SYSTEM_FIXED. That bit remains
             // sticky once set.
-            mServiceInternal.updatePermissionFlagsTEMP(permission, packageName,
+            mServiceInternal.updatePermissionFlagsTEMP(permission, pkg.packageName,
                     PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT, 0, userId);
         }
     }
 
-    private void grantRuntimePermissions(PackageInfo pkg,
+    private void grantRuntimePermissions(PackageParser.Package pkg,
             Set<String> permissionsWithoutSplits, boolean systemFixed, boolean ignoreSystemPackage,
             int userId) {
-        if (pkg == null) {
-            return;
-        }
-
-        String[] requestedPermissions = pkg.requestedPermissions;
-        if (ArrayUtils.isEmpty(requestedPermissions)) {
+        if (pkg.requestedPermissions.isEmpty()) {
             return;
         }
 
         final ArraySet<String> permissions = new ArraySet<>(permissionsWithoutSplits);
-        ApplicationInfo applicationInfo = pkg.applicationInfo;
 
         // Automatically attempt to grant split permissions to older APKs
         final int numSplitPerms = PackageParser.SPLIT_PERMISSIONS.length;
@@ -1029,13 +1227,13 @@
             final PackageParser.SplitPermissionInfo splitPerm =
                     PackageParser.SPLIT_PERMISSIONS[splitPermNum];
 
-            if (applicationInfo != null
-                    && applicationInfo.targetSdkVersion < splitPerm.targetSdk
+            if (pkg.applicationInfo.targetSdkVersion < splitPerm.targetSdk
                     && permissionsWithoutSplits.contains(splitPerm.rootPerm)) {
                 Collections.addAll(permissions, splitPerm.newPerms);
             }
         }
 
+        List<String> requestedPermissions = pkg.requestedPermissions;
         Set<String> grantablePermissions = null;
 
         // In some cases, like for the Phone or SMS app, we grant permissions regardless
@@ -1044,25 +1242,23 @@
         // choice to grant this app the permissions needed to function. For all other
         // apps, (default grants on first boot and user creation) we don't grant default
         // permissions if the version on the system image does not declare them.
-        if (!ignoreSystemPackage
-                && applicationInfo != null
-                && applicationInfo.isUpdatedSystemApp()) {
-            final PackageInfo disabledPkg = getSystemPackageInfo(
-                    mServiceInternal.getDisabledSystemPackageName(pkg.packageName));
+        if (!ignoreSystemPackage && pkg.isUpdatedSystemApp()) {
+            final PackageParser.Package disabledPkg =
+                    mServiceInternal.getDisabledPackage(pkg.packageName);
             if (disabledPkg != null) {
-                if (ArrayUtils.isEmpty(disabledPkg.requestedPermissions)) {
+                if (disabledPkg.requestedPermissions.isEmpty()) {
                     return;
                 }
                 if (!requestedPermissions.equals(disabledPkg.requestedPermissions)) {
-                    grantablePermissions = new ArraySet<>(Arrays.asList(requestedPermissions));
+                    grantablePermissions = new ArraySet<>(requestedPermissions);
                     requestedPermissions = disabledPkg.requestedPermissions;
                 }
             }
         }
 
-        final int grantablePermissionCount = requestedPermissions.length;
+        final int grantablePermissionCount = requestedPermissions.size();
         for (int i = 0; i < grantablePermissionCount; i++) {
-            String permission = requestedPermissions[i];
+            String permission = requestedPermissions.get(i);
 
             // If there is a disabled system app it may request a permission the updated
             // version ot the data partition doesn't, In this case skip the permission.
@@ -1092,7 +1288,7 @@
                             pkg.packageName, permission, userId, false);
                     if (DEBUG) {
                         Log.i(TAG, "Granted " + (systemFixed ? "fixed " : "not fixed ")
-                                + permission + " to default handler " + pkg);
+                                + permission + " to default handler " + pkg.packageName);
                     }
 
                     int newFlags = PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT;
@@ -1111,7 +1307,7 @@
                         && !systemFixed) {
                     if (DEBUG) {
                         Log.i(TAG, "Granted not fixed " + permission + " to default handler "
-                                + pkg);
+                                + pkg.packageName);
                     }
                     mServiceInternal.updatePermissionFlagsTEMP(permission, pkg.packageName,
                             PackageManager.FLAG_PERMISSION_SYSTEM_FIXED, 0, userId);
@@ -1120,42 +1316,28 @@
         }
     }
 
-    private PackageInfo getSystemPackageInfo(String pkg) {
-        //TODO not MATCH_SYSTEM_ONLY?
-        return getPackageInfo(pkg, PackageManager.MATCH_FACTORY_ONLY);
-    }
-
-    private PackageInfo getPackageInfo(String pkg) {
-        return getPackageInfo(pkg, 0 /* extraFlags */);
-    }
-
-    private PackageInfo getPackageInfo(String pkg,
-            @PackageManager.PackageInfoFlags int extraFlags) {
-        return mServiceInternal.getPackageInfo(pkg,
-                DEFAULT_PACKAGE_INFO_QUERY_FLAGS | extraFlags,
-                //TODO is this the right filterCallingUid?
-                UserHandle.USER_SYSTEM, UserHandle.USER_SYSTEM);
-    }
-
-    private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageInfo pkg) {
+    private boolean isSysComponentOrPersistentPlatformSignedPrivApp(PackageParser.Package pkg) {
         if (UserHandle.getAppId(pkg.applicationInfo.uid) < FIRST_APPLICATION_UID) {
             return true;
         }
-        if (!pkg.applicationInfo.isPrivilegedApp()) {
+        if (!pkg.isPrivileged()) {
             return false;
         }
-        final PackageInfo disabledPkg = getSystemPackageInfo(
-                mServiceInternal.getDisabledSystemPackageName(pkg.applicationInfo.packageName));
+        final PackageParser.Package disabledPkg =
+                mServiceInternal.getDisabledPackage(pkg.packageName);
         if (disabledPkg != null) {
-            ApplicationInfo disabledPackageAppInfo = disabledPkg.applicationInfo;
-            if (disabledPackageAppInfo != null
-                    && (disabledPackageAppInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
+            if ((disabledPkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
                 return false;
             }
         } else if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) == 0) {
             return false;
         }
-        return mServiceInternal.isPlatformSigned(pkg.packageName);
+        final String systemPackageName = mServiceInternal.getKnownPackageName(
+                PackageManagerInternal.PACKAGE_SYSTEM, UserHandle.USER_SYSTEM);
+        final PackageParser.Package systemPackage = getPackage(systemPackageName);
+        return pkg.mSigningDetails.hasAncestorOrSelf(systemPackage.mSigningDetails)
+                || systemPackage.mSigningDetails.checkCapability(pkg.mSigningDetails,
+                        PackageParser.SigningDetails.CertCapabilities.PERMISSION);
     }
 
     private void grantDefaultPermissionExceptions(int userId) {
@@ -1175,7 +1357,7 @@
         final int exceptionCount = mGrantExceptions.size();
         for (int i = 0; i < exceptionCount; i++) {
             String packageName = mGrantExceptions.keyAt(i);
-            PackageInfo pkg = getSystemPackageInfo(packageName);
+            PackageParser.Package pkg = getSystemPackage(packageName);
             List<DefaultPermissionGrant> permissionGrants = mGrantExceptions.valueAt(i);
             final int permissionGrantCount = permissionGrants.size();
             for (int j = 0; j < permissionGrantCount; j++) {
@@ -1186,7 +1368,8 @@
                     permissions.clear();
                 }
                 permissions.add(permissionGrant.name);
-                grantRuntimePermissions(pkg, permissions, permissionGrant.fixed, userId);
+                grantRuntimePermissions(pkg, permissions,
+                        permissionGrant.fixed, userId);
             }
         }
     }
@@ -1291,14 +1474,15 @@
                         outGrantExceptions.get(packageName);
                 if (packageExceptions == null) {
                     // The package must be on the system image
-                    if (!isSystemPackage(packageName)) {
+                    PackageParser.Package pkg = getSystemPackage(packageName);
+                    if (pkg == null) {
                         Log.w(TAG, "Unknown package:" + packageName);
                         XmlUtils.skipCurrentTag(parser);
                         continue;
                     }
 
                     // The package must support runtime permissions
-                    if (!doesPackageSupportRuntimePermissions(getSystemPackageInfo(packageName))) {
+                    if (!doesPackageSupportRuntimePermissions(pkg)) {
                         Log.w(TAG, "Skipping non supporting runtime permissions package:"
                                 + packageName);
                         XmlUtils.skipCurrentTag(parser);
@@ -1343,9 +1527,8 @@
         }
     }
 
-    private static boolean doesPackageSupportRuntimePermissions(PackageInfo pkg) {
-        return pkg.applicationInfo != null
-                && pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1;
+    private static boolean doesPackageSupportRuntimePermissions(PackageParser.Package pkg) {
+        return pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1;
     }
 
     private static final class DefaultPermissionGrant {
diff --git a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
index 4b6760c..c4f90a12 100644
--- a/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
+++ b/services/core/java/com/android/server/pm/permission/PermissionManagerService.java
@@ -1189,7 +1189,7 @@
                 // is granted only if it had been defined by the original application.
                 if (pkg.isUpdatedSystemApp()) {
                     final PackageParser.Package disabledPkg =
-                            mPackageManagerInt.getDisabledSystemPackage(pkg.packageName);
+                            mPackageManagerInt.getDisabledPackage(pkg.packageName);
                     final PackageSetting disabledPs =
                             (disabledPkg != null) ? (PackageSetting) disabledPkg.mExtras : null;
                     if (disabledPs != null
@@ -1221,7 +1221,7 @@
                         // packages can also get the permission.
                         if (pkg.parentPackage != null) {
                             final PackageParser.Package disabledParentPkg = mPackageManagerInt
-                                    .getDisabledSystemPackage(pkg.parentPackage.packageName);
+                                    .getDisabledPackage(pkg.parentPackage.packageName);
                             final PackageSetting disabledParentPs = (disabledParentPkg != null)
                                     ? (PackageSetting) disabledParentPkg.mExtras : null;
                             if (disabledParentPkg != null
@@ -1372,7 +1372,7 @@
             return;
         }
         final PackageParser.Package disabledPkg =
-                mPackageManagerInt.getDisabledSystemPackage(pkg.parentPackage.packageName);
+                mPackageManagerInt.getDisabledPackage(pkg.parentPackage.packageName);
         if (disabledPkg == null || disabledPkg.mExtras == null) {
             return;
         }
diff --git a/services/core/java/com/android/server/telecom/TelecomLoaderService.java b/services/core/java/com/android/server/telecom/TelecomLoaderService.java
index 7a3f030..6c5452a 100644
--- a/services/core/java/com/android/server/telecom/TelecomLoaderService.java
+++ b/services/core/java/com/android/server/telecom/TelecomLoaderService.java
@@ -22,6 +22,7 @@
 import android.content.Intent;
 import android.content.IntentFilter;
 import android.content.ServiceConnection;
+import android.content.pm.PackageManagerInternal;
 import android.database.ContentObserver;
 import android.net.Uri;
 import android.os.Handler;
@@ -38,13 +39,12 @@
 import android.util.IntArray;
 import android.util.Slog;
 
+import android.util.SparseBooleanArray;
 import com.android.internal.annotations.GuardedBy;
 import com.android.internal.telephony.SmsApplication;
 import com.android.server.LocalServices;
 import com.android.server.SystemService;
 import com.android.server.pm.UserManagerService;
-import com.android.server.pm.permission.DefaultPermissionGrantPolicy;
-import com.android.server.pm.permission.PermissionManagerInternal;
 
 /**
  * Starts the telecom component by binding to its ITelecomService implementation. Telecom is setup
@@ -72,8 +72,8 @@
                 synchronized (mLock) {
                     if (mDefaultSmsAppRequests != null || mDefaultDialerAppRequests != null
                             || mDefaultSimCallManagerRequests != null) {
-                        final DefaultPermissionGrantPolicy permissionPolicy =
-                                getDefaultPermissionGrantPolicy();
+                        final PackageManagerInternal packageManagerInternal = LocalServices
+                                .getService(PackageManagerInternal.class);
 
                         if (mDefaultSmsAppRequests != null) {
                             ComponentName smsComponent = SmsApplication.getDefaultSmsApplication(
@@ -83,7 +83,7 @@
                                 for (int i = requestCount - 1; i >= 0; i--) {
                                     final int userid = mDefaultSmsAppRequests.get(i);
                                     mDefaultSmsAppRequests.remove(i);
-                                    permissionPolicy.grantDefaultPermissionsToDefaultSmsApp(
+                                    packageManagerInternal.grantDefaultPermissionsToDefaultSmsApp(
                                             smsComponent.getPackageName(), userid);
                                 }
                             }
@@ -97,7 +97,7 @@
                                 for (int i = requestCount - 1; i >= 0; i--) {
                                     final int userId = mDefaultDialerAppRequests.get(i);
                                     mDefaultDialerAppRequests.remove(i);
-                                    permissionPolicy.grantDefaultPermissionsToDefaultDialerApp(
+                                    packageManagerInternal.grantDefaultPermissionsToDefaultDialerApp(
                                             packageName, userId);
                                 }
                             }
@@ -113,7 +113,7 @@
                                 for (int i = requestCount - 1; i >= 0; i--) {
                                     final int userId = mDefaultSimCallManagerRequests.get(i);
                                     mDefaultSimCallManagerRequests.remove(i);
-                                    permissionPolicy
+                                    packageManagerInternal
                                             .grantDefaultPermissionsToDefaultSimCallManager(
                                                     packageName, userId);
                                 }
@@ -132,11 +132,6 @@
         }
     }
 
-    private DefaultPermissionGrantPolicy getDefaultPermissionGrantPolicy() {
-        return LocalServices.getService(PermissionManagerInternal.class)
-                .getDefaultPermissionGrantPolicy();
-    }
-
     private static final ComponentName SERVICE_COMPONENT = new ComponentName(
             "com.android.server.telecom",
             "com.android.server.telecom.components.TelecomService");
@@ -201,68 +196,82 @@
 
 
     private void registerDefaultAppProviders() {
-        final DefaultPermissionGrantPolicy permissionPolicy = getDefaultPermissionGrantPolicy();
+        final PackageManagerInternal packageManagerInternal = LocalServices.getService(
+                PackageManagerInternal.class);
 
-        // Set a callback for the permission grant policy to query the default sms app.
-        permissionPolicy.setSmsAppPackagesProvider(userId -> {
-            synchronized (mLock) {
-                if (mServiceConnection == null) {
-                    if (mDefaultSmsAppRequests == null) {
-                        mDefaultSmsAppRequests = new IntArray();
+        // Set a callback for the package manager to query the default sms app.
+        packageManagerInternal.setSmsAppPackagesProvider(
+                new PackageManagerInternal.PackagesProvider() {
+            @Override
+            public String[] getPackages(int userId) {
+                synchronized (mLock) {
+                    if (mServiceConnection == null) {
+                        if (mDefaultSmsAppRequests == null) {
+                            mDefaultSmsAppRequests = new IntArray();
+                        }
+                        mDefaultSmsAppRequests.add(userId);
+                        return null;
                     }
-                    mDefaultSmsAppRequests.add(userId);
-                    return null;
                 }
+                ComponentName smsComponent = SmsApplication.getDefaultSmsApplication(
+                        mContext, true);
+                if (smsComponent != null) {
+                    return new String[]{smsComponent.getPackageName()};
+                }
+                return null;
             }
-            ComponentName smsComponent = SmsApplication.getDefaultSmsApplication(
-                    mContext, true);
-            if (smsComponent != null) {
-                return new String[]{smsComponent.getPackageName()};
-            }
-            return null;
         });
 
-        // Set a callback for the permission grant policy to query the default dialer app.
-        permissionPolicy.setDialerAppPackagesProvider(userId -> {
-            synchronized (mLock) {
-                if (mServiceConnection == null) {
-                    if (mDefaultDialerAppRequests == null) {
-                        mDefaultDialerAppRequests = new IntArray();
+        // Set a callback for the package manager to query the default dialer app.
+        packageManagerInternal.setDialerAppPackagesProvider(
+                new PackageManagerInternal.PackagesProvider() {
+            @Override
+            public String[] getPackages(int userId) {
+                synchronized (mLock) {
+                    if (mServiceConnection == null) {
+                        if (mDefaultDialerAppRequests == null) {
+                            mDefaultDialerAppRequests = new IntArray();
+                        }
+                        mDefaultDialerAppRequests.add(userId);
+                        return null;
                     }
-                    mDefaultDialerAppRequests.add(userId);
-                    return null;
                 }
+                String packageName = DefaultDialerManager.getDefaultDialerApplication(mContext);
+                if (packageName != null) {
+                    return new String[]{packageName};
+                }
+                return null;
             }
-            String packageName = DefaultDialerManager.getDefaultDialerApplication(mContext);
-            if (packageName != null) {
-                return new String[]{packageName};
-            }
-            return null;
         });
 
-        // Set a callback for the permission grant policy to query the default sim call manager.
-        permissionPolicy.setSimCallManagerPackagesProvider(userId -> {
-            synchronized (mLock) {
-                if (mServiceConnection == null) {
-                    if (mDefaultSimCallManagerRequests == null) {
-                        mDefaultSimCallManagerRequests = new IntArray();
+        // Set a callback for the package manager to query the default sim call manager.
+        packageManagerInternal.setSimCallManagerPackagesProvider(
+                new PackageManagerInternal.PackagesProvider() {
+            @Override
+            public String[] getPackages(int userId) {
+                synchronized (mLock) {
+                    if (mServiceConnection == null) {
+                        if (mDefaultSimCallManagerRequests == null) {
+                            mDefaultSimCallManagerRequests = new IntArray();
+                        }
+                        mDefaultSimCallManagerRequests.add(userId);
+                        return null;
                     }
-                    mDefaultSimCallManagerRequests.add(userId);
-                    return null;
                 }
-            }
-            TelecomManager telecomManager =
+                TelecomManager telecomManager =
                     (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
-            PhoneAccountHandle phoneAccount = telecomManager.getSimCallManager(userId);
-            if (phoneAccount != null) {
-                return new String[]{phoneAccount.getComponentName().getPackageName()};
+                PhoneAccountHandle phoneAccount = telecomManager.getSimCallManager(userId);
+                if (phoneAccount != null) {
+                    return new String[]{phoneAccount.getComponentName().getPackageName()};
+                }
+                return null;
             }
-            return null;
         });
     }
 
     private void registerDefaultAppNotifier() {
-        final DefaultPermissionGrantPolicy permissionPolicy = getDefaultPermissionGrantPolicy();
+        final PackageManagerInternal packageManagerInternal = LocalServices.getService(
+                PackageManagerInternal.class);
 
         // Notify the package manager on default app changes
         final Uri defaultSmsAppUri = Settings.Secure.getUriFor(
@@ -278,17 +287,17 @@
                     ComponentName smsComponent = SmsApplication.getDefaultSmsApplication(
                             mContext, true);
                     if (smsComponent != null) {
-                        permissionPolicy.grantDefaultPermissionsToDefaultSmsApp(
+                        packageManagerInternal.grantDefaultPermissionsToDefaultSmsApp(
                                 smsComponent.getPackageName(), userId);
                     }
                 } else if (defaultDialerAppUri.equals(uri)) {
                     String packageName = DefaultDialerManager.getDefaultDialerApplication(
                             mContext);
                     if (packageName != null) {
-                        permissionPolicy.grantDefaultPermissionsToDefaultDialerApp(
+                        packageManagerInternal.grantDefaultPermissionsToDefaultDialerApp(
                                 packageName, userId);
                     }
-                    updateSimCallManagerPermissions(permissionPolicy, userId);
+                    updateSimCallManagerPermissions(packageManagerInternal, userId);
                 }
             }
         };
@@ -301,12 +310,14 @@
 
 
     private void registerCarrierConfigChangedReceiver() {
+        final PackageManagerInternal packageManagerInternal = LocalServices.getService(
+                PackageManagerInternal.class);
         BroadcastReceiver receiver = new BroadcastReceiver() {
             @Override
             public void onReceive(Context context, Intent intent) {
                 if (intent.getAction().equals(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)) {
                     for (int userId : UserManagerService.getInstance().getUserIds()) {
-                        updateSimCallManagerPermissions(getDefaultPermissionGrantPolicy(), userId);
+                        updateSimCallManagerPermissions(packageManagerInternal, userId);
                     }
                 }
             }
@@ -316,15 +327,15 @@
             new IntentFilter(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED), null, null);
     }
 
-    private void updateSimCallManagerPermissions(
-            DefaultPermissionGrantPolicy permissionGrantPolicy, int userId) {
+    private void updateSimCallManagerPermissions(PackageManagerInternal packageManagerInternal,
+            int userId) {
         TelecomManager telecomManager =
             (TelecomManager) mContext.getSystemService(Context.TELECOM_SERVICE);
         PhoneAccountHandle phoneAccount = telecomManager.getSimCallManager(userId);
         if (phoneAccount != null) {
             Slog.i(TAG, "updating sim call manager permissions for userId:" + userId);
             String packageName = phoneAccount.getComponentName().getPackageName();
-            permissionGrantPolicy.grantDefaultPermissionsToDefaultSimCallManager(
+            packageManagerInternal.grantDefaultPermissionsToDefaultSimCallManager(
                 packageName, userId);
         }
     }