Search in sources :

Example 1 with MountServiceInternal

use of android.os.storage.MountServiceInternal in project platform_frameworks_base by android.

the class PackageManagerService method systemReady.

@Override
public void systemReady() {
    mSystemReady = true;
    // Disable any carrier apps. We do this very early in boot to prevent the apps from being
    // disabled after already being started.
    CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, mContext.getContentResolver(), UserHandle.USER_SYSTEM);
    // Read the compatibilty setting when the system is ready.
    boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
    PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
    if (DEBUG_SETTINGS) {
        Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
    }
    int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
    synchronized (mPackages) {
        // Verify that all of the preferred activity components actually
        // exist.  It is possible for applications to be updated and at
        // that point remove a previously declared activity component that
        // had been set as a preferred activity.  We try to clean this up
        // the next time we encounter that preferred activity, but it is
        // possible for the user flow to never be able to return to that
        // situation so here we do a sanity check to make sure we haven't
        // left any junk around.
        ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
        for (int i = 0; i < mSettings.mPreferredActivities.size(); i++) {
            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
            removed.clear();
            for (PreferredActivity pa : pir.filterSet()) {
                if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
                    removed.add(pa);
                }
            }
            if (removed.size() > 0) {
                for (int r = 0; r < removed.size(); r++) {
                    PreferredActivity pa = removed.get(r);
                    Slog.w(TAG, "Removing dangling preferred activity: " + pa.mPref.mComponent);
                    pir.removeFilter(pa);
                }
                mSettings.writePackageRestrictionsLPr(mSettings.mPreferredActivities.keyAt(i));
            }
        }
        for (int userId : UserManagerService.getInstance().getUserIds()) {
            if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
                grantPermissionsUserIds = ArrayUtils.appendInt(grantPermissionsUserIds, userId);
            }
        }
    }
    sUserManager.systemReady();
    // If we upgraded grant all default permissions before kicking off.
    for (int userId : grantPermissionsUserIds) {
        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
    }
    // disk on a new user creation.
    if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
        mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
    }
    // Kick off any messages waiting for system ready
    if (mPostSystemReadyMessages != null) {
        for (Message msg : mPostSystemReadyMessages) {
            msg.sendToTarget();
        }
        mPostSystemReadyMessages = null;
    }
    // Watch for external volumes that come and go over time
    final StorageManager storage = mContext.getSystemService(StorageManager.class);
    storage.registerListener(mStorageListener);
    mInstallerService.systemReady();
    mPackageDexOptimizer.systemReady();
    MountServiceInternal mountServiceInternal = LocalServices.getService(MountServiceInternal.class);
    mountServiceInternal.addExternalStoragePolicy(new MountServiceInternal.ExternalStorageMountPolicy() {

        @Override
        public int getMountMode(int uid, String packageName) {
            if (Process.isIsolated(uid)) {
                return Zygote.MOUNT_EXTERNAL_NONE;
            }
            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
                return Zygote.MOUNT_EXTERNAL_DEFAULT;
            }
            if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_DEFAULT;
            }
            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_READ;
            }
            return Zygote.MOUNT_EXTERNAL_WRITE;
        }

        @Override
        public boolean hasExternalStorage(int uid, String packageName) {
            return true;
        }
    });
    // Now that we're mostly running, clean up stale users and apps
    reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
    reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
}
Also used : Message(android.os.Message) MountServiceInternal(android.os.storage.MountServiceInternal) ArrayList(java.util.ArrayList) StorageManager(android.os.storage.StorageManager)

Example 2 with MountServiceInternal

use of android.os.storage.MountServiceInternal in project platform_frameworks_base by android.

the class PackageManagerService method grantRuntimePermission.

@Override
public void grantRuntimePermission(String packageName, String name, final int userId) {
    if (!sUserManager.exists(userId)) {
        Log.e(TAG, "No such user:" + userId);
        return;
    }
    mContext.enforceCallingOrSelfPermission(android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, "grantRuntimePermission");
    enforceCrossUserPermission(Binder.getCallingUid(), userId, true, /* requireFullPermission */
    true, /* checkShell */
    "grantRuntimePermission");
    final int uid;
    final SettingBase sb;
    synchronized (mPackages) {
        final PackageParser.Package pkg = mPackages.get(packageName);
        if (pkg == null) {
            throw new IllegalArgumentException("Unknown package: " + packageName);
        }
        final BasePermission bp = mSettings.mPermissions.get(name);
        if (bp == null) {
            throw new IllegalArgumentException("Unknown permission: " + name);
        }
        enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp);
        // install permission's state is shared across all users.
        if ((mPermissionReviewRequired || Build.PERMISSIONS_REVIEW_REQUIRED) && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M && bp.isRuntime()) {
            return;
        }
        uid = UserHandle.getUid(userId, pkg.applicationInfo.uid);
        sb = (SettingBase) pkg.mExtras;
        if (sb == null) {
            throw new IllegalArgumentException("Unknown package: " + packageName);
        }
        final PermissionsState permissionsState = sb.getPermissionsState();
        final int flags = permissionsState.getPermissionFlags(name, userId);
        if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) {
            throw new SecurityException("Cannot grant system fixed permission " + name + " for package " + packageName);
        }
        if (bp.isDevelopment()) {
            // normal runtime permissions.  For now they apply to all users.
            if (permissionsState.grantInstallPermission(bp) != PermissionsState.PERMISSION_OPERATION_FAILURE) {
                scheduleWriteSettingsLocked();
            }
            return;
        }
        if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) {
            Slog.w(TAG, "Cannot grant runtime permission to a legacy app");
            return;
        }
        final int result = permissionsState.grantRuntimePermission(bp, userId);
        switch(result) {
            case PermissionsState.PERMISSION_OPERATION_FAILURE:
                {
                    return;
                }
            case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED:
                {
                    final int appId = UserHandle.getAppId(pkg.applicationInfo.uid);
                    mHandler.post(new Runnable() {

                        @Override
                        public void run() {
                            killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED);
                        }
                    });
                }
                break;
        }
        mOnPermissionChangeListeners.onPermissionsChanged(uid);
        // Not critical if that is lost - app has to request again.
        mSettings.writeRuntimePermissionsForUserLPr(userId, false);
    }
    // to make an expensive call to remount processes for the changed permissions.
    if (READ_EXTERNAL_STORAGE.equals(name) || WRITE_EXTERNAL_STORAGE.equals(name)) {
        final long token = Binder.clearCallingIdentity();
        try {
            if (sUserManager.isInitialized(userId)) {
                MountServiceInternal mountServiceInternal = LocalServices.getService(MountServiceInternal.class);
                mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName);
            }
        } finally {
            Binder.restoreCallingIdentity(token);
        }
    }
}
Also used : PackageParser(android.content.pm.PackageParser) MountServiceInternal(android.os.storage.MountServiceInternal)

Example 3 with MountServiceInternal

use of android.os.storage.MountServiceInternal in project android_frameworks_base by DirtyUnicorns.

the class PackageManagerService method systemReady.

@Override
public void systemReady() {
    mSystemReady = true;
    // Disable any carrier apps. We do this very early in boot to prevent the apps from being
    // disabled after already being started.
    CarrierAppUtils.disableCarrierAppsUntilPrivileged(mContext.getOpPackageName(), this, mContext.getContentResolver(), UserHandle.USER_SYSTEM);
    // Read the compatibilty setting when the system is ready.
    boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt(mContext.getContentResolver(), android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1;
    PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled);
    if (DEBUG_SETTINGS) {
        Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled);
    }
    int[] grantPermissionsUserIds = EMPTY_INT_ARRAY;
    synchronized (mPackages) {
        // Verify that all of the preferred activity components actually
        // exist.  It is possible for applications to be updated and at
        // that point remove a previously declared activity component that
        // had been set as a preferred activity.  We try to clean this up
        // the next time we encounter that preferred activity, but it is
        // possible for the user flow to never be able to return to that
        // situation so here we do a sanity check to make sure we haven't
        // left any junk around.
        ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>();
        for (int i = 0; i < mSettings.mPreferredActivities.size(); i++) {
            PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i);
            removed.clear();
            for (PreferredActivity pa : pir.filterSet()) {
                if (mActivities.mActivities.get(pa.mPref.mComponent) == null) {
                    removed.add(pa);
                }
            }
            if (removed.size() > 0) {
                for (int r = 0; r < removed.size(); r++) {
                    PreferredActivity pa = removed.get(r);
                    Slog.w(TAG, "Removing dangling preferred activity: " + pa.mPref.mComponent);
                    pir.removeFilter(pa);
                }
                mSettings.writePackageRestrictionsLPr(mSettings.mPreferredActivities.keyAt(i));
            }
        }
        for (int userId : UserManagerService.getInstance().getUserIds()) {
            if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) {
                grantPermissionsUserIds = ArrayUtils.appendInt(grantPermissionsUserIds, userId);
            }
        }
    }
    sUserManager.systemReady();
    // If we upgraded grant all default permissions before kicking off.
    for (int userId : grantPermissionsUserIds) {
        mDefaultPermissionPolicy.grantDefaultPermissions(userId);
    }
    // disk on a new user creation.
    if (grantPermissionsUserIds == EMPTY_INT_ARRAY) {
        mDefaultPermissionPolicy.scheduleReadDefaultPermissionExceptions();
    }
    // Kick off any messages waiting for system ready
    if (mPostSystemReadyMessages != null) {
        for (Message msg : mPostSystemReadyMessages) {
            msg.sendToTarget();
        }
        mPostSystemReadyMessages = null;
    }
    // Watch for external volumes that come and go over time
    final StorageManager storage = mContext.getSystemService(StorageManager.class);
    storage.registerListener(mStorageListener);
    mInstallerService.systemReady();
    mPackageDexOptimizer.systemReady();
    MountServiceInternal mountServiceInternal = LocalServices.getService(MountServiceInternal.class);
    mountServiceInternal.addExternalStoragePolicy(new MountServiceInternal.ExternalStorageMountPolicy() {

        @Override
        public int getMountMode(int uid, String packageName) {
            if (Process.isIsolated(uid)) {
                return Zygote.MOUNT_EXTERNAL_NONE;
            }
            if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) {
                return Zygote.MOUNT_EXTERNAL_DEFAULT;
            }
            if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_DEFAULT;
            }
            if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) {
                return Zygote.MOUNT_EXTERNAL_READ;
            }
            return Zygote.MOUNT_EXTERNAL_WRITE;
        }

        @Override
        public boolean hasExternalStorage(int uid, String packageName) {
            return true;
        }
    });
    // Now that we're mostly running, clean up stale users and apps
    reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL);
    reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL);
}
Also used : Message(android.os.Message) MountServiceInternal(android.os.storage.MountServiceInternal) ArrayList(java.util.ArrayList) StorageManager(android.os.storage.StorageManager)

Example 4 with MountServiceInternal

use of android.os.storage.MountServiceInternal in project android_frameworks_base by DirtyUnicorns.

the class ActivityManagerService method startProcessLocked.

private final void startProcessLocked(ProcessRecord app, String hostingType, String hostingNameStr, String abiOverride, String entryPoint, String[] entryPointArgs) {
    long startTime = SystemClock.elapsedRealtime();
    if (app.pid > 0 && app.pid != MY_PID) {
        checkTime(startTime, "startProcess: removing from pids map");
        synchronized (mPidsSelfLocked) {
            mPidsSelfLocked.remove(app.pid);
            mHandler.removeMessages(PROC_START_TIMEOUT_MSG, app);
        }
        checkTime(startTime, "startProcess: done removing from pids map");
        app.setPid(0);
    }
    if (DEBUG_PROCESSES && mProcessesOnHold.contains(app))
        Slog.v(TAG_PROCESSES, "startProcessLocked removing on hold: " + app);
    mProcessesOnHold.remove(app);
    checkTime(startTime, "startProcess: starting to update cpu stats");
    updateCpuStats();
    checkTime(startTime, "startProcess: done updating cpu stats");
    try {
        try {
            final int userId = UserHandle.getUserId(app.uid);
            AppGlobals.getPackageManager().checkPackageStartable(app.info.packageName, userId);
        } catch (RemoteException e) {
            throw e.rethrowAsRuntimeException();
        }
        int uid = app.uid;
        int[] gids = null;
        int mountExternal = Zygote.MOUNT_EXTERNAL_NONE;
        if (!app.isolated) {
            int[] permGids = null;
            try {
                checkTime(startTime, "startProcess: getting gids from package manager");
                final IPackageManager pm = AppGlobals.getPackageManager();
                permGids = pm.getPackageGids(app.info.packageName, MATCH_DEBUG_TRIAGED_MISSING, app.userId);
                MountServiceInternal mountServiceInternal = LocalServices.getService(MountServiceInternal.class);
                mountExternal = mountServiceInternal.getExternalStorageMountMode(uid, app.info.packageName);
            } catch (RemoteException e) {
                throw e.rethrowAsRuntimeException();
            }
            /*
                 * Add shared application and profile GIDs so applications can share some
                 * resources like shared libraries and access user-wide resources
                 */
            if (ArrayUtils.isEmpty(permGids)) {
                gids = new int[2];
            } else {
                gids = new int[permGids.length + 2];
                System.arraycopy(permGids, 0, gids, 2, permGids.length);
            }
            gids[0] = UserHandle.getSharedAppGid(UserHandle.getAppId(uid));
            gids[1] = UserHandle.getUserGid(UserHandle.getUserId(uid));
        }
        checkTime(startTime, "startProcess: building args");
        if (mFactoryTest != FactoryTest.FACTORY_TEST_OFF) {
            if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL && mTopComponent != null && app.processName.equals(mTopComponent.getPackageName())) {
                uid = 0;
            }
            if (mFactoryTest == FactoryTest.FACTORY_TEST_HIGH_LEVEL && (app.info.flags & ApplicationInfo.FLAG_FACTORY_TEST) != 0) {
                uid = 0;
            }
        }
        int debugFlags = 0;
        if ((app.info.flags & ApplicationInfo.FLAG_DEBUGGABLE) != 0) {
            debugFlags |= Zygote.DEBUG_ENABLE_DEBUGGER;
            // Also turn on CheckJNI for debuggable apps. It's quite
            // awkward to turn on otherwise.
            debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
        }
        // system is booted in safe mode.
        if ((app.info.flags & ApplicationInfo.FLAG_VM_SAFE_MODE) != 0 || mSafeMode == true) {
            debugFlags |= Zygote.DEBUG_ENABLE_SAFEMODE;
        }
        if ("1".equals(SystemProperties.get("debug.checkjni"))) {
            debugFlags |= Zygote.DEBUG_ENABLE_CHECKJNI;
        }
        String genDebugInfoProperty = SystemProperties.get("debug.generate-debug-info");
        if ("true".equals(genDebugInfoProperty)) {
            debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO;
        }
        if ("1".equals(SystemProperties.get("debug.jni.logging"))) {
            debugFlags |= Zygote.DEBUG_ENABLE_JNI_LOGGING;
        }
        if ("1".equals(SystemProperties.get("debug.assert"))) {
            debugFlags |= Zygote.DEBUG_ENABLE_ASSERT;
        }
        if (mNativeDebuggingApp != null && mNativeDebuggingApp.equals(app.processName)) {
            // Enable all debug flags required by the native debugger.
            // Don't interpret anything
            debugFlags |= Zygote.DEBUG_ALWAYS_JIT;
            // Generate debug info
            debugFlags |= Zygote.DEBUG_GENERATE_DEBUG_INFO;
            // Disbale optimizations
            debugFlags |= Zygote.DEBUG_NATIVE_DEBUGGABLE;
            mNativeDebuggingApp = null;
        }
        //Check if zygote should refresh its fonts
        boolean refreshTheme = false;
        if (SystemProperties.getBoolean(PROP_REFRESH_THEME, false)) {
            SystemProperties.set(PROP_REFRESH_THEME, "false");
            refreshTheme = true;
        }
        String requiredAbi = (abiOverride != null) ? abiOverride : app.info.primaryCpuAbi;
        if (requiredAbi == null) {
            requiredAbi = Build.SUPPORTED_ABIS[0];
        }
        String instructionSet = null;
        if (app.info.primaryCpuAbi != null) {
            instructionSet = VMRuntime.getInstructionSet(app.info.primaryCpuAbi);
        }
        app.gids = gids;
        app.requiredAbi = requiredAbi;
        app.instructionSet = instructionSet;
        // Start the process.  It will either succeed and return a result containing
        // the PID of the new process, or else throw a RuntimeException.
        boolean isActivityProcess = (entryPoint == null);
        if (entryPoint == null)
            entryPoint = "android.app.ActivityThread";
        Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "Start proc: " + app.processName);
        checkTime(startTime, "startProcess: asking zygote to start proc");
        Process.ProcessStartResult startResult = Process.start(entryPoint, app.processName, uid, uid, gids, debugFlags, mountExternal, app.info.targetSdkVersion, app.info.seinfo, requiredAbi, instructionSet, app.info.dataDir, refreshTheme, entryPointArgs);
        checkTime(startTime, "startProcess: returned from zygote!");
        Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER);
        mBatteryStatsService.noteProcessStart(app.processName, app.info.uid);
        checkTime(startTime, "startProcess: done updating battery stats");
        EventLog.writeEvent(EventLogTags.AM_PROC_START, UserHandle.getUserId(uid), startResult.pid, uid, app.processName, hostingType, hostingNameStr != null ? hostingNameStr : "");
        try {
            AppGlobals.getPackageManager().logAppProcessStartIfNeeded(app.processName, app.uid, app.info.seinfo, app.info.sourceDir, startResult.pid);
        } catch (RemoteException ex) {
        // Ignore
        }
        if (app.persistent) {
            Watchdog.getInstance().processStarted(app.processName, startResult.pid);
        }
        checkTime(startTime, "startProcess: building log message");
        StringBuilder buf = mStringBuilder;
        buf.setLength(0);
        buf.append("Start proc ");
        buf.append(startResult.pid);
        buf.append(':');
        buf.append(app.processName);
        buf.append('/');
        UserHandle.formatUid(buf, uid);
        if (!isActivityProcess) {
            buf.append(" [");
            buf.append(entryPoint);
            buf.append("]");
        }
        buf.append(" for ");
        buf.append(hostingType);
        if (hostingNameStr != null) {
            buf.append(" ");
            buf.append(hostingNameStr);
        }
        Slog.i(TAG, buf.toString());
        app.setPid(startResult.pid);
        app.usingWrapper = startResult.usingWrapper;
        app.removed = false;
        app.killed = false;
        app.killedByAm = false;
        checkTime(startTime, "startProcess: starting to update pids map");
        ProcessRecord oldApp;
        synchronized (mPidsSelfLocked) {
            oldApp = mPidsSelfLocked.get(startResult.pid);
        }
        // If there is already an app occupying that pid that hasn't been cleaned up
        if (oldApp != null && !app.isolated) {
            // Clean up anything relating to this pid first
            Slog.w(TAG, "Reusing pid " + startResult.pid + " while app is still mapped to it");
            cleanUpApplicationRecordLocked(oldApp, false, false, -1, true);
        }
        synchronized (mPidsSelfLocked) {
            this.mPidsSelfLocked.put(startResult.pid, app);
            if (isActivityProcess) {
                Message msg = mHandler.obtainMessage(PROC_START_TIMEOUT_MSG);
                msg.obj = app;
                mHandler.sendMessageDelayed(msg, startResult.usingWrapper ? PROC_START_TIMEOUT_WITH_WRAPPER : PROC_START_TIMEOUT);
            }
        }
        checkTime(startTime, "startProcess: done updating pids map");
    } catch (RuntimeException e) {
        Slog.e(TAG, "Failure starting process " + app.processName, e);
        // Something went very wrong while trying to start this process; one
        // common case is when the package is frozen due to an active
        // upgrade. To recover, clean up any active bookkeeping related to
        // starting this process. (We already invoked this method once when
        // the package was initially frozen through KILL_APPLICATION_MSG, so
        // it doesn't hurt to use it again.)
        forceStopPackageLocked(app.info.packageName, UserHandle.getAppId(app.uid), false, false, true, false, false, UserHandle.getUserId(app.userId), "start failure");
    }
}
Also used : MountServiceInternal(android.os.storage.MountServiceInternal) Message(android.os.Message) Process(android.os.Process) Point(android.graphics.Point) IPackageManager(android.content.pm.IPackageManager) RemoteException(android.os.RemoteException)

Example 5 with MountServiceInternal

use of android.os.storage.MountServiceInternal in project android_frameworks_base by ResurrectionRemix.

the class AppOpsService method systemReady.

public void systemReady() {
    synchronized (this) {
        boolean changed = false;
        for (int i = mUidStates.size() - 1; i >= 0; i--) {
            UidState uidState = mUidStates.valueAt(i);
            String[] packageNames = getPackagesForUid(uidState.uid);
            if (ArrayUtils.isEmpty(packageNames)) {
                uidState.clear();
                mUidStates.removeAt(i);
                changed = true;
                continue;
            }
            ArrayMap<String, Ops> pkgs = uidState.pkgOps;
            if (pkgs == null) {
                continue;
            }
            Iterator<Ops> it = pkgs.values().iterator();
            while (it.hasNext()) {
                Ops ops = it.next();
                int curUid = -1;
                try {
                    curUid = AppGlobals.getPackageManager().getPackageUid(ops.packageName, PackageManager.MATCH_UNINSTALLED_PACKAGES, UserHandle.getUserId(ops.uidState.uid));
                } catch (RemoteException ignored) {
                }
                if (curUid != ops.uidState.uid) {
                    // Do not prune apps that are not currently present in the device
                    // (like SDcard ones). While booting, SDcards are not available but
                    // must not be purged from AppOps, because they are still present
                    // in the Android app database.
                    String pkgName = mContext.getPackageManager().getNameForUid(ops.uidState.uid);
                    if (curUid != -1 || pkgName == null || !pkgName.equals(ops.packageName)) {
                        Slog.i(TAG, "Pruning old package " + ops.packageName + "/" + ops.uidState + ": new uid=" + curUid);
                        it.remove();
                        changed = true;
                    }
                }
            }
            if (uidState.isDefault()) {
                mUidStates.removeAt(i);
            }
        }
        if (changed) {
            scheduleFastWriteLocked();
        }
    }
    MountServiceInternal mountServiceInternal = LocalServices.getService(MountServiceInternal.class);
    mountServiceInternal.addExternalStoragePolicy(new MountServiceInternal.ExternalStorageMountPolicy() {

        @Override
        public int getMountMode(int uid, String packageName) {
            if (Process.isIsolated(uid)) {
                return Zygote.MOUNT_EXTERNAL_NONE;
            }
            if (noteOperation(AppOpsManager.OP_READ_EXTERNAL_STORAGE, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
                return Zygote.MOUNT_EXTERNAL_NONE;
            }
            if (noteOperation(AppOpsManager.OP_WRITE_EXTERNAL_STORAGE, uid, packageName) != AppOpsManager.MODE_ALLOWED) {
                return Zygote.MOUNT_EXTERNAL_READ;
            }
            return Zygote.MOUNT_EXTERNAL_WRITE;
        }

        @Override
        public boolean hasExternalStorage(int uid, String packageName) {
            final int mountMode = getMountMode(uid, packageName);
            return mountMode == Zygote.MOUNT_EXTERNAL_READ || mountMode == Zygote.MOUNT_EXTERNAL_WRITE;
        }
    });
    mPowerManager = (PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
    IntentFilter filter = new IntentFilter();
    filter.addAction(Intent.ACTION_SCREEN_OFF);
    mContext.registerReceiver(mIntentReceiver, filter);
}
Also used : IntentFilter(android.content.IntentFilter) MountServiceInternal(android.os.storage.MountServiceInternal) RemoteException(android.os.RemoteException)

Aggregations

MountServiceInternal (android.os.storage.MountServiceInternal)11 RemoteException (android.os.RemoteException)7 Message (android.os.Message)4 IntentFilter (android.content.IntentFilter)2 IPackageManager (android.content.pm.IPackageManager)2 PackageParser (android.content.pm.PackageParser)2 Point (android.graphics.Point)2 Process (android.os.Process)2 StorageManager (android.os.storage.StorageManager)2 ArrayList (java.util.ArrayList)2 AtomicFile (android.util.AtomicFile)1 File (java.io.File)1