Search in sources :

Example 91 with StorageManager

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

the class UserManagerService method createUserInternalUnchecked.

private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
    if (ActivityManager.isLowRamDeviceStatic()) {
        return null;
    }
    final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
    final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
    final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
    final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
    final long ident = Binder.clearCallingIdentity();
    UserInfo userInfo;
    UserData userData;
    final int userId;
    try {
        synchronized (mPackagesLock) {
            UserData parent = null;
            if (parentId != UserHandle.USER_NULL) {
                synchronized (mUsersLock) {
                    parent = getUserDataLU(parentId);
                }
                if (parent == null)
                    return null;
            }
            if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
                Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
                return null;
            }
            if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
                // been reached, cannot add a user.
                return null;
            }
            // If we're adding a guest and there already exists one, bail.
            if (isGuest && findCurrentGuestUser() != null) {
                return null;
            }
            // In legacy mode, restricted profile's parent can only be the owner user
            if (isRestricted && !UserManager.isSplitSystemUser() && (parentId != UserHandle.USER_SYSTEM)) {
                Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
                return null;
            }
            if (isRestricted && UserManager.isSplitSystemUser()) {
                if (parent == null) {
                    Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be " + "specified");
                    return null;
                }
                if (!parent.info.canHaveProfile()) {
                    Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be " + "created for the specified parent user id " + parentId);
                    return null;
                }
            }
            if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0 && (flags & UserInfo.FLAG_DEMO) == 0) {
                Log.e(LOG_TAG, "Ephemeral users are supported on split-system-user systems only.");
                return null;
            }
            // And if there is no device owner, we also assign the admin flag to primary user.
            if (UserManager.isSplitSystemUser() && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
                flags |= UserInfo.FLAG_PRIMARY;
                synchronized (mUsersLock) {
                    if (!mIsDeviceManaged) {
                        flags |= UserInfo.FLAG_ADMIN;
                    }
                }
            }
            userId = getNextAvailableId();
            Environment.getUserSystemDirectory(userId).mkdirs();
            boolean ephemeralGuests = Resources.getSystem().getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
            synchronized (mUsersLock) {
                // Add ephemeral flag to guests/users if required. Also inherit it from parent.
                if ((isGuest && ephemeralGuests) || mForceEphemeralUsers || (parent != null && parent.info.isEphemeral())) {
                    flags |= UserInfo.FLAG_EPHEMERAL;
                }
                userInfo = new UserInfo(userId, name, null, flags);
                userInfo.serialNumber = mNextSerialNumber++;
                long now = System.currentTimeMillis();
                userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
                userInfo.partial = true;
                userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
                userData = new UserData();
                userData.info = userInfo;
                mUsers.put(userId, userData);
            }
            writeUserLP(userData);
            writeUserListLP();
            if (parent != null) {
                if (isManagedProfile) {
                    if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
                        parent.info.profileGroupId = parent.info.id;
                        writeUserLP(parent);
                    }
                    userInfo.profileGroupId = parent.info.profileGroupId;
                } else if (isRestricted) {
                    if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
                        parent.info.restrictedProfileParentId = parent.info.id;
                        writeUserLP(parent);
                    }
                    userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
                }
            }
        }
        final StorageManager storage = mContext.getSystemService(StorageManager.class);
        storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
        mPm.prepareUserData(userId, userInfo.serialNumber, StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
        mPm.createNewUser(userId);
        userInfo.partial = false;
        synchronized (mPackagesLock) {
            writeUserLP(userData);
        }
        updateUserIds();
        Bundle restrictions = new Bundle();
        if (isGuest) {
            synchronized (mGuestRestrictions) {
                restrictions.putAll(mGuestRestrictions);
            }
        }
        synchronized (mRestrictionsLock) {
            mBaseUserRestrictions.append(userId, restrictions);
        }
        mPm.onNewUserCreated(userId);
        Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
        addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
        mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, android.Manifest.permission.MANAGE_USERS);
        MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
    return userInfo;
}
Also used : Bundle(android.os.Bundle) PersistableBundle(android.os.PersistableBundle) StorageManager(android.os.storage.StorageManager) UserInfo(android.content.pm.UserInfo) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent)

Example 92 with StorageManager

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

the class MountService method onVolumeCreatedLocked.

private void onVolumeCreatedLocked(VolumeInfo vol) {
    if (mPms.isOnlyCoreApps()) {
        Slog.d(TAG, "System booted in core-only mode; ignoring volume " + vol.getId());
        return;
    }
    if (vol.type == VolumeInfo.TYPE_EMULATED) {
        final StorageManager storage = mContext.getSystemService(StorageManager.class);
        final VolumeInfo privateVol = storage.findPrivateForEmulated(vol);
        if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, mPrimaryStorageUuid) && VolumeInfo.ID_PRIVATE_INTERNAL.equals(privateVol.id)) {
            Slog.v(TAG, "Found primary storage at " + vol);
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
            mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
        } else if (Objects.equals(privateVol.fsUuid, mPrimaryStorageUuid)) {
            Slog.v(TAG, "Found primary storage at " + vol);
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
            mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
        }
    } else if (vol.type == VolumeInfo.TYPE_PUBLIC) {
        // TODO: only look at first public partition
        if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, mPrimaryStorageUuid) && vol.disk.isDefaultPrimary()) {
            Slog.v(TAG, "Found primary storage at " + vol);
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_PRIMARY;
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
        }
        // public API requirement of being in a stable location.
        if (vol.disk.isAdoptable()) {
            vol.mountFlags |= VolumeInfo.MOUNT_FLAG_VISIBLE;
        }
        vol.mountUserId = mCurrentUserId;
        mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
    } else if (vol.type == VolumeInfo.TYPE_PRIVATE) {
        mHandler.obtainMessage(H_VOLUME_MOUNT, vol).sendToTarget();
    } else {
        Slog.d(TAG, "Skipping automatic mounting of " + vol);
    }
}
Also used : StorageManager(android.os.storage.StorageManager) VolumeInfo(android.os.storage.VolumeInfo)

Example 93 with StorageManager

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

the class PackageManagerService method movePackageInternal.

private void movePackageInternal(final String packageName, final String volumeUuid, final int moveId, UserHandle user) throws PackageManagerException {
    final StorageManager storage = mContext.getSystemService(StorageManager.class);
    final PackageManager pm = mContext.getPackageManager();
    final boolean currentAsec;
    final String currentVolumeUuid;
    final File codeFile;
    final String installerPackageName;
    final String packageAbiOverride;
    final int appId;
    final String seinfo;
    final String label;
    final int targetSdkVersion;
    final PackageFreezer freezer;
    final int[] installedUserIds;
    // reader
    synchronized (mPackages) {
        final PackageParser.Package pkg = mPackages.get(packageName);
        final PackageSetting ps = mSettings.mPackages.get(packageName);
        if (pkg == null || ps == null) {
            throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package");
        }
        if (pkg.applicationInfo.isSystemApp()) {
            throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, "Cannot move system application");
        }
        if (pkg.applicationInfo.isExternalAsec()) {
            currentAsec = true;
            currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL;
        } else if (pkg.applicationInfo.isForwardLocked()) {
            currentAsec = true;
            currentVolumeUuid = "forward_locked";
        } else {
            currentAsec = false;
            currentVolumeUuid = ps.volumeUuid;
            final File probe = new File(pkg.codePath);
            final File probeOat = new File(probe, "oat");
            if (!probe.isDirectory() || !probeOat.isDirectory()) {
                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, "Move only supported for modern cluster style installs");
            }
        }
        if (Objects.equals(currentVolumeUuid, volumeUuid)) {
            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, "Package already moved to " + volumeUuid);
        }
        if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) {
            throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, "Device admin cannot be moved");
        }
        if (mFrozenPackages.contains(packageName)) {
            throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, "Failed to move already frozen package");
        }
        codeFile = new File(pkg.codePath);
        installerPackageName = ps.installerPackageName;
        packageAbiOverride = ps.cpuAbiOverrideString;
        appId = UserHandle.getAppId(pkg.applicationInfo.uid);
        seinfo = pkg.applicationInfo.seinfo;
        label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo));
        targetSdkVersion = pkg.applicationInfo.targetSdkVersion;
        freezer = freezePackage(packageName, "movePackageInternal");
        installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true);
    }
    final Bundle extras = new Bundle();
    extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName);
    extras.putString(Intent.EXTRA_TITLE, label);
    mMoveCallbacks.notifyCreated(moveId, extras);
    int installFlags;
    final boolean moveCompleteApp;
    final File measurePath;
    if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) {
        installFlags = INSTALL_INTERNAL;
        moveCompleteApp = !currentAsec;
        measurePath = Environment.getDataAppDirectory(volumeUuid);
    } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) {
        installFlags = INSTALL_EXTERNAL;
        moveCompleteApp = false;
        measurePath = storage.getPrimaryPhysicalVolume().getPath();
    } else {
        final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid);
        if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE || !volume.isMountedWritable()) {
            freezer.close();
            throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, "Move location not mounted private volume");
        }
        Preconditions.checkState(!currentAsec);
        installFlags = INSTALL_INTERNAL;
        moveCompleteApp = true;
        measurePath = Environment.getDataAppDirectory(volumeUuid);
    }
    final PackageStats stats = new PackageStats(null, -1);
    synchronized (mInstaller) {
        for (int userId : installedUserIds) {
            if (!getPackageSizeInfoLI(packageName, userId, stats)) {
                freezer.close();
                throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, "Failed to measure package size");
            }
        }
    }
    if (DEBUG_INSTALL)
        Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " + stats.dataSize);
    final long startFreeBytes = measurePath.getFreeSpace();
    final long sizeBytes;
    if (moveCompleteApp) {
        sizeBytes = stats.codeSize + stats.dataSize;
    } else {
        sizeBytes = stats.codeSize;
    }
    if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) {
        freezer.close();
        throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, "Not enough free space to move");
    }
    mMoveCallbacks.notifyStatusChanged(moveId, 10);
    final CountDownLatch installedLatch = new CountDownLatch(1);
    final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() {

        @Override
        public void onUserActionRequired(Intent intent) throws RemoteException {
            throw new IllegalStateException();
        }

        @Override
        public void onPackageInstalled(String basePackageName, int returnCode, String msg, Bundle extras) throws RemoteException {
            if (DEBUG_INSTALL)
                Slog.d(TAG, "Install result for move: " + PackageManager.installStatusToString(returnCode, msg));
            installedLatch.countDown();
            freezer.close();
            final int status = PackageManager.installStatusToPublicStatus(returnCode);
            switch(status) {
                case PackageInstaller.STATUS_SUCCESS:
                    mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_SUCCEEDED);
                    break;
                case PackageInstaller.STATUS_FAILURE_STORAGE:
                    mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE);
                    break;
                default:
                    mMoveCallbacks.notifyStatusChanged(moveId, PackageManager.MOVE_FAILED_INTERNAL_ERROR);
                    break;
            }
        }
    };
    final MoveInfo move;
    if (moveCompleteApp) {
        // Kick off a thread to report progress estimates
        new Thread() {

            @Override
            public void run() {
                while (true) {
                    try {
                        if (installedLatch.await(1, TimeUnit.SECONDS)) {
                            break;
                        }
                    } catch (InterruptedException ignored) {
                    }
                    final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace();
                    final int progress = 10 + (int) MathUtils.constrain(((deltaFreeBytes * 80) / sizeBytes), 0, 80);
                    mMoveCallbacks.notifyStatusChanged(moveId, progress);
                }
            }
        }.start();
        final String dataAppName = codeFile.getName();
        move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, dataAppName, appId, seinfo, targetSdkVersion);
    } else {
        move = null;
    }
    installFlags |= PackageManager.INSTALL_REPLACE_EXISTING;
    final Message msg = mHandler.obtainMessage(INIT_COPY);
    final OriginInfo origin = OriginInfo.fromExistingFile(codeFile);
    final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, installerPackageName, volumeUuid, null, /*verificationInfo*/
    user, packageAbiOverride, null, /*grantedPermissions*/
    null);
    params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params));
    msg.obj = params;
    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", System.identityHashCode(msg.obj));
    Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", System.identityHashCode(msg.obj));
    mHandler.sendMessage(msg);
}
Also used : Message(android.os.Message) StorageManager(android.os.storage.StorageManager) VolumeInfo(android.os.storage.VolumeInfo) PackageManager(android.content.pm.PackageManager) IPackageManager(android.content.pm.IPackageManager) PackageStats(android.content.pm.PackageStats) Bundle(android.os.Bundle) Intent(android.content.Intent) CountDownLatch(java.util.concurrent.CountDownLatch) ServiceThread(com.android.server.ServiceThread) FgThread(com.android.server.FgThread) PackageParser(android.content.pm.PackageParser) IPackageInstallObserver2(android.content.pm.IPackageInstallObserver2) PackageParser.isApkFile(android.content.pm.PackageParser.isApkFile) File(java.io.File) DexFile(dalvik.system.DexFile) StrictJarFile(android.util.jar.StrictJarFile)

Example 94 with StorageManager

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

the class UserManagerService method createUserInternalUnchecked.

private UserInfo createUserInternalUnchecked(String name, int flags, int parentId) {
    if (ActivityManager.isLowRamDeviceStatic()) {
        return null;
    }
    final boolean isGuest = (flags & UserInfo.FLAG_GUEST) != 0;
    final boolean isManagedProfile = (flags & UserInfo.FLAG_MANAGED_PROFILE) != 0;
    final boolean isRestricted = (flags & UserInfo.FLAG_RESTRICTED) != 0;
    final boolean isDemo = (flags & UserInfo.FLAG_DEMO) != 0;
    final long ident = Binder.clearCallingIdentity();
    UserInfo userInfo;
    UserData userData;
    final int userId;
    try {
        synchronized (mPackagesLock) {
            UserData parent = null;
            if (parentId != UserHandle.USER_NULL) {
                synchronized (mUsersLock) {
                    parent = getUserDataLU(parentId);
                }
                if (parent == null)
                    return null;
            }
            if (isManagedProfile && !canAddMoreManagedProfiles(parentId, false)) {
                Log.e(LOG_TAG, "Cannot add more managed profiles for user " + parentId);
                return null;
            }
            if (!isGuest && !isManagedProfile && !isDemo && isUserLimitReached()) {
                // been reached, cannot add a user.
                return null;
            }
            // If we're adding a guest and there already exists one, bail.
            if (isGuest && findCurrentGuestUser() != null) {
                return null;
            }
            // In legacy mode, restricted profile's parent can only be the owner user
            if (isRestricted && !UserManager.isSplitSystemUser() && (parentId != UserHandle.USER_SYSTEM)) {
                Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be owner");
                return null;
            }
            if (isRestricted && UserManager.isSplitSystemUser()) {
                if (parent == null) {
                    Log.w(LOG_TAG, "Cannot add restricted profile - parent user must be " + "specified");
                    return null;
                }
                if (!parent.info.canHaveProfile()) {
                    Log.w(LOG_TAG, "Cannot add restricted profile - profiles cannot be " + "created for the specified parent user id " + parentId);
                    return null;
                }
            }
            if (!UserManager.isSplitSystemUser() && (flags & UserInfo.FLAG_EPHEMERAL) != 0 && (flags & UserInfo.FLAG_DEMO) == 0) {
                Log.e(LOG_TAG, "Ephemeral users are supported on split-system-user systems only.");
                return null;
            }
            // And if there is no device owner, we also assign the admin flag to primary user.
            if (UserManager.isSplitSystemUser() && !isGuest && !isManagedProfile && getPrimaryUser() == null) {
                flags |= UserInfo.FLAG_PRIMARY;
                synchronized (mUsersLock) {
                    if (!mIsDeviceManaged) {
                        flags |= UserInfo.FLAG_ADMIN;
                    }
                }
            }
            userId = getNextAvailableId();
            Environment.getUserSystemDirectory(userId).mkdirs();
            boolean ephemeralGuests = Resources.getSystem().getBoolean(com.android.internal.R.bool.config_guestUserEphemeral);
            synchronized (mUsersLock) {
                // Add ephemeral flag to guests/users if required. Also inherit it from parent.
                if ((isGuest && ephemeralGuests) || mForceEphemeralUsers || (parent != null && parent.info.isEphemeral())) {
                    flags |= UserInfo.FLAG_EPHEMERAL;
                }
                userInfo = new UserInfo(userId, name, null, flags);
                userInfo.serialNumber = mNextSerialNumber++;
                long now = System.currentTimeMillis();
                userInfo.creationTime = (now > EPOCH_PLUS_30_YEARS) ? now : 0;
                userInfo.partial = true;
                userInfo.lastLoggedInFingerprint = Build.FINGERPRINT;
                userData = new UserData();
                userData.info = userInfo;
                mUsers.put(userId, userData);
            }
            writeUserLP(userData);
            writeUserListLP();
            if (parent != null) {
                if (isManagedProfile) {
                    if (parent.info.profileGroupId == UserInfo.NO_PROFILE_GROUP_ID) {
                        parent.info.profileGroupId = parent.info.id;
                        writeUserLP(parent);
                    }
                    userInfo.profileGroupId = parent.info.profileGroupId;
                } else if (isRestricted) {
                    if (parent.info.restrictedProfileParentId == UserInfo.NO_PROFILE_GROUP_ID) {
                        parent.info.restrictedProfileParentId = parent.info.id;
                        writeUserLP(parent);
                    }
                    userInfo.restrictedProfileParentId = parent.info.restrictedProfileParentId;
                }
            }
        }
        final StorageManager storage = mContext.getSystemService(StorageManager.class);
        storage.createUserKey(userId, userInfo.serialNumber, userInfo.isEphemeral());
        mPm.prepareUserData(userId, userInfo.serialNumber, StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE);
        mPm.createNewUser(userId);
        userInfo.partial = false;
        synchronized (mPackagesLock) {
            writeUserLP(userData);
        }
        updateUserIds();
        Bundle restrictions = new Bundle();
        if (isGuest) {
            synchronized (mGuestRestrictions) {
                restrictions.putAll(mGuestRestrictions);
            }
        }
        synchronized (mRestrictionsLock) {
            mBaseUserRestrictions.append(userId, restrictions);
        }
        mPm.onNewUserCreated(userId);
        Intent addedIntent = new Intent(Intent.ACTION_USER_ADDED);
        addedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
        mContext.sendBroadcastAsUser(addedIntent, UserHandle.ALL, android.Manifest.permission.MANAGE_USERS);
        MetricsLogger.count(mContext, isGuest ? TRON_GUEST_CREATED : TRON_USER_CREATED, 1);
    } finally {
        Binder.restoreCallingIdentity(ident);
    }
    return userInfo;
}
Also used : Bundle(android.os.Bundle) PersistableBundle(android.os.PersistableBundle) StorageManager(android.os.storage.StorageManager) UserInfo(android.content.pm.UserInfo) PendingIntent(android.app.PendingIntent) Intent(android.content.Intent)

Example 95 with StorageManager

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

the class PackageManagerService method loadPrivatePackagesInner.

private void loadPrivatePackagesInner(VolumeInfo vol) {
    final String volumeUuid = vol.fsUuid;
    if (TextUtils.isEmpty(volumeUuid)) {
        Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring");
        return;
    }
    final ArrayList<PackageFreezer> freezers = new ArrayList<>();
    final ArrayList<ApplicationInfo> loaded = new ArrayList<>();
    final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE;
    final VersionInfo ver;
    final List<PackageSetting> packages;
    synchronized (mPackages) {
        ver = mSettings.findOrCreateVersion(volumeUuid);
        packages = mSettings.getVolumePackagesLPr(volumeUuid);
    }
    for (PackageSetting ps : packages) {
        freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner"));
        synchronized (mInstallLock) {
            final PackageParser.Package pkg;
            try {
                pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null);
                loaded.add(pkg.applicationInfo);
            } catch (PackageManagerException e) {
                Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage());
            }
            if (!Build.FINGERPRINT.equals(ver.fingerprint)) {
                clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY);
            }
        }
    }
    // Reconcile app data for all started/unlocked users
    final StorageManager sm = mContext.getSystemService(StorageManager.class);
    final UserManager um = mContext.getSystemService(UserManager.class);
    UserManagerInternal umInternal = getUserManagerInternal();
    for (UserInfo user : um.getUsers()) {
        final int flags;
        if (umInternal.isUserUnlockingOrUnlocked(user.id)) {
            flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE;
        } else if (umInternal.isUserRunning(user.id)) {
            flags = StorageManager.FLAG_STORAGE_DE;
        } else {
            continue;
        }
        try {
            sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags);
            synchronized (mInstallLock) {
                reconcileAppsDataLI(volumeUuid, user.id, flags);
            }
        } catch (IllegalStateException e) {
            // Device was probably ejected, and we'll process that event momentarily
            Slog.w(TAG, "Failed to prepare storage: " + e);
        }
    }
    synchronized (mPackages) {
        int updateFlags = UPDATE_PERMISSIONS_ALL;
        if (ver.sdkVersion != mSdkVersion) {
            logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " + mSdkVersion + "; regranting permissions for " + volumeUuid);
            updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL;
        }
        updatePermissionsLPw(null, null, volumeUuid, updateFlags);
        // Yay, everything is now upgraded
        ver.forceCurrent();
        mSettings.writeLPr();
    }
    for (PackageFreezer freezer : freezers) {
        freezer.close();
    }
    if (DEBUG_INSTALL)
        Slog.d(TAG, "Loaded packages " + loaded);
    sendResourcesChangedBroadcast(true, false, loaded, null);
}
Also used : ArrayList(java.util.ArrayList) EphemeralApplicationInfo(android.content.pm.EphemeralApplicationInfo) ApplicationInfo(android.content.pm.ApplicationInfo) StorageManager(android.os.storage.StorageManager) UserInfo(android.content.pm.UserInfo) VersionInfo(com.android.server.pm.Settings.VersionInfo) PackageParser(android.content.pm.PackageParser) UserManagerInternal(android.os.UserManagerInternal) UserManager(android.os.UserManager)

Aggregations

StorageManager (android.os.storage.StorageManager)161 File (java.io.File)43 IOException (java.io.IOException)42 VolumeInfo (android.os.storage.VolumeInfo)38 FileNotFoundException (java.io.FileNotFoundException)32 ParcelFileDescriptor (android.os.ParcelFileDescriptor)25 LargeTest (android.test.suitebuilder.annotation.LargeTest)20 NameNotFoundException (android.content.pm.PackageManager.NameNotFoundException)17 RemoteException (android.os.RemoteException)14 ArrayList (java.util.ArrayList)14 Intent (android.content.Intent)13 Bundle (android.os.Bundle)13 StorageVolume (android.os.storage.StorageVolume)13 PackageParserException (android.content.pm.PackageParser.PackageParserException)12 NotFoundException (android.content.res.Resources.NotFoundException)12 StorageListener (android.os.storage.StorageListener)12 SettingNotFoundException (android.provider.Settings.SettingNotFoundException)12 ErrnoException (android.system.ErrnoException)12 NonNull (android.annotation.NonNull)10 ZipFile (java.util.zip.ZipFile)10