Home | History | Annotate | Download | only in am
      1 /*
      2  * Copyright (C) 2015 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License
     15  */
     16 
     17 package com.android.server.am;
     18 
     19 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
     20 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
     21 import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
     22 import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
     23 import static android.app.ActivityManager.USER_OP_IS_CURRENT;
     24 import static android.app.ActivityManager.USER_OP_SUCCESS;
     25 import static android.content.Context.KEYGUARD_SERVICE;
     26 import static android.os.Process.SYSTEM_UID;
     27 
     28 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
     29 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
     30 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
     31 import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
     32 import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
     33 import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
     34 import static com.android.server.am.ActivityManagerService.MY_PID;
     35 import static com.android.server.am.ActivityManagerService.REPORT_LOCKED_BOOT_COMPLETE_MSG;
     36 import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
     37 import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
     38 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
     39 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
     40 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
     41 import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
     42 import static com.android.server.am.UserState.STATE_BOOTING;
     43 import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
     44 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
     45 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
     46 
     47 import android.annotation.NonNull;
     48 import android.annotation.UserIdInt;
     49 import android.app.ActivityManager;
     50 import android.app.AppGlobals;
     51 import android.app.AppOpsManager;
     52 import android.app.Dialog;
     53 import android.app.IStopUserCallback;
     54 import android.app.IUserSwitchObserver;
     55 import android.app.KeyguardManager;
     56 import android.content.Context;
     57 import android.content.IIntentReceiver;
     58 import android.content.Intent;
     59 import android.content.pm.IPackageManager;
     60 import android.content.pm.PackageManager;
     61 import android.content.pm.UserInfo;
     62 import android.os.BatteryStats;
     63 import android.os.Binder;
     64 import android.os.Build;
     65 import android.os.Bundle;
     66 import android.os.Debug;
     67 import android.os.Handler;
     68 import android.os.IBinder;
     69 import android.os.IProgressListener;
     70 import android.os.IRemoteCallback;
     71 import android.os.IUserManager;
     72 import android.os.Process;
     73 import android.os.RemoteCallbackList;
     74 import android.os.RemoteException;
     75 import android.os.ServiceManager;
     76 import android.os.SystemClock;
     77 import android.os.UserHandle;
     78 import android.os.UserManager;
     79 import android.os.UserManagerInternal;
     80 import android.os.storage.IStorageManager;
     81 import android.os.storage.StorageManager;
     82 import android.util.ArraySet;
     83 import android.util.IntArray;
     84 import android.util.Pair;
     85 import android.util.Slog;
     86 import android.util.SparseArray;
     87 import android.util.SparseIntArray;
     88 
     89 import com.android.internal.R;
     90 import com.android.internal.annotations.GuardedBy;
     91 import com.android.internal.annotations.VisibleForTesting;
     92 import com.android.internal.logging.MetricsLogger;
     93 import com.android.internal.util.ArrayUtils;
     94 import com.android.internal.util.Preconditions;
     95 import com.android.internal.widget.LockPatternUtils;
     96 import com.android.server.LocalServices;
     97 import com.android.server.pm.UserManagerService;
     98 import com.android.server.wm.WindowManagerService;
     99 
    100 import java.io.PrintWriter;
    101 import java.util.ArrayList;
    102 import java.util.Arrays;
    103 import java.util.HashSet;
    104 import java.util.List;
    105 import java.util.Objects;
    106 import java.util.Set;
    107 import java.util.concurrent.atomic.AtomicInteger;
    108 
    109 /**
    110  * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
    111  */
    112 final class UserController {
    113     private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
    114 
    115     // Maximum number of users we allow to be running at a time.
    116     static final int MAX_RUNNING_USERS = 3;
    117 
    118     // Amount of time we wait for observers to handle a user switch before
    119     // giving up on them and unfreezing the screen.
    120     static final int USER_SWITCH_TIMEOUT = 3 * 1000;
    121 
    122     private final Object mLock;
    123     private final Injector mInjector;
    124     private final Handler mHandler;
    125 
    126     // Holds the current foreground user's id
    127     @GuardedBy("mLock")
    128     private int mCurrentUserId = UserHandle.USER_SYSTEM;
    129     // Holds the target user's id during a user switch
    130     @GuardedBy("mLock")
    131     private int mTargetUserId = UserHandle.USER_NULL;
    132 
    133     /**
    134      * Which users have been started, so are allowed to run code.
    135      */
    136     @GuardedBy("mLock")
    137     private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
    138 
    139     /**
    140      * LRU list of history of current users.  Most recently current is at the end.
    141      */
    142     @GuardedBy("mLock")
    143     private final ArrayList<Integer> mUserLru = new ArrayList<>();
    144 
    145     /**
    146      * Constant array of the users that are currently started.
    147      */
    148     @GuardedBy("mLock")
    149     private int[] mStartedUserArray = new int[] { 0 };
    150 
    151     // If there are multiple profiles for the current user, their ids are here
    152     // Currently only the primary user can have managed profiles
    153     @GuardedBy("mLock")
    154     private int[] mCurrentProfileIds = new int[] {};
    155 
    156     /**
    157      * Mapping from each known user ID to the profile group ID it is associated with.
    158      */
    159     private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
    160 
    161     /**
    162      * Registered observers of the user switching mechanics.
    163      */
    164     private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
    165             = new RemoteCallbackList<>();
    166 
    167     boolean mUserSwitchUiEnabled = true;
    168 
    169     /**
    170      * Currently active user switch callbacks.
    171      */
    172     @GuardedBy("mLock")
    173     private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
    174 
    175     private volatile UserManagerService mUserManager;
    176 
    177     private final LockPatternUtils mLockPatternUtils;
    178 
    179     UserController(ActivityManagerService service) {
    180         this(new Injector(service));
    181     }
    182 
    183     @VisibleForTesting
    184     UserController(Injector injector) {
    185         mInjector = injector;
    186         mLock = injector.getLock();
    187         mHandler = injector.getHandler();
    188         // User 0 is the first and only user that runs at boot.
    189         final UserState uss = new UserState(UserHandle.SYSTEM);
    190         mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
    191         mUserLru.add(UserHandle.USER_SYSTEM);
    192         mLockPatternUtils = mInjector.getLockPatternUtils();
    193         updateStartedUserArrayLocked();
    194     }
    195 
    196     void finishUserSwitch(UserState uss) {
    197         synchronized (mLock) {
    198             finishUserBoot(uss);
    199 
    200             startProfilesLocked();
    201             stopRunningUsersLocked(MAX_RUNNING_USERS);
    202         }
    203     }
    204 
    205     void stopRunningUsersLocked(int maxRunningUsers) {
    206         int num = mUserLru.size();
    207         int i = 0;
    208         while (num > maxRunningUsers && i < mUserLru.size()) {
    209             Integer oldUserId = mUserLru.get(i);
    210             UserState oldUss = mStartedUsers.get(oldUserId);
    211             if (oldUss == null) {
    212                 // Shouldn't happen, but be sane if it does.
    213                 mUserLru.remove(i);
    214                 num--;
    215                 continue;
    216             }
    217             if (oldUss.state == UserState.STATE_STOPPING
    218                     || oldUss.state == UserState.STATE_SHUTDOWN) {
    219                 // This user is already stopping, doesn't count.
    220                 num--;
    221                 i++;
    222                 continue;
    223             }
    224             if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
    225                 // Owner/System user and current user can't be stopped. We count it as running
    226                 // when it is not a pure system user.
    227                 if (UserInfo.isSystemOnly(oldUserId)) {
    228                     num--;
    229                 }
    230                 i++;
    231                 continue;
    232             }
    233             // This is a user to be stopped.
    234             if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
    235                 num--;
    236             }
    237             num--;
    238             i++;
    239         }
    240     }
    241 
    242     private void finishUserBoot(UserState uss) {
    243         finishUserBoot(uss, null);
    244     }
    245 
    246     private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
    247         final int userId = uss.mHandle.getIdentifier();
    248 
    249         Slog.d(TAG, "Finishing user boot " + userId);
    250         synchronized (mLock) {
    251             // Bail if we ended up with a stale user
    252             if (mStartedUsers.get(userId) != uss) return;
    253 
    254             // We always walk through all the user lifecycle states to send
    255             // consistent developer events. We step into RUNNING_LOCKED here,
    256             // but we might immediately step into RUNNING below if the user
    257             // storage is already unlocked.
    258             if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
    259                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    260                 // Do not report secondary users, runtime restarts or first boot/upgrade
    261                 if (userId == UserHandle.USER_SYSTEM
    262                         && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
    263                     int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
    264                     MetricsLogger.histogram(mInjector.getContext(),
    265                             "framework_locked_boot_completed", uptimeSeconds);
    266                     final int MAX_UPTIME_SECONDS = 120;
    267                     if (uptimeSeconds > MAX_UPTIME_SECONDS) {
    268                         Slog.wtf("SystemServerTiming",
    269                                 "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
    270                     }
    271                 }
    272 
    273                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
    274                         userId, 0));
    275                 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
    276                 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    277                 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
    278                         | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
    279                 mInjector.broadcastIntentLocked(intent, null, resultTo, 0, null, null,
    280                         new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
    281                         AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
    282             }
    283 
    284             // We need to delay unlocking managed profiles until the parent user
    285             // is also unlocked.
    286             if (mInjector.getUserManager().isManagedProfile(userId)) {
    287                 final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
    288                 if (parent != null
    289                         && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
    290                     Slog.d(TAG, "User " + userId + " (parent " + parent.id
    291                             + "): attempting unlock because parent is unlocked");
    292                     maybeUnlockUser(userId);
    293                 } else {
    294                     String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
    295                     Slog.d(TAG, "User " + userId + " (parent " + parentId
    296                             + "): delaying unlock because parent is locked");
    297                 }
    298             } else {
    299                 maybeUnlockUser(userId);
    300             }
    301         }
    302     }
    303 
    304     /**
    305      * Step from {@link UserState#STATE_RUNNING_LOCKED} to
    306      * {@link UserState#STATE_RUNNING_UNLOCKING}.
    307      */
    308     private void finishUserUnlocking(final UserState uss) {
    309         final int userId = uss.mHandle.getIdentifier();
    310         boolean proceedWithUnlock = false;
    311         synchronized (mLock) {
    312             // Bail if we ended up with a stale user
    313             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
    314 
    315             // Only keep marching forward if user is actually unlocked
    316             if (!StorageManager.isUserKeyUnlocked(userId)) return;
    317 
    318             if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
    319                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    320                 proceedWithUnlock = true;
    321             }
    322         }
    323 
    324         if (proceedWithUnlock) {
    325             uss.mUnlockProgress.start();
    326 
    327             // Prepare app storage before we go any further
    328             uss.mUnlockProgress.setProgress(5,
    329                         mInjector.getContext().getString(R.string.android_start_title));
    330             mInjector.getUserManager().onBeforeUnlockUser(userId);
    331             uss.mUnlockProgress.setProgress(20);
    332 
    333             // Dispatch unlocked to system services; when fully dispatched,
    334             // that calls through to the next "unlocked" phase
    335             mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
    336                     .sendToTarget();
    337         }
    338     }
    339 
    340     /**
    341      * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
    342      * {@link UserState#STATE_RUNNING_UNLOCKED}.
    343      */
    344     void finishUserUnlocked(final UserState uss) {
    345         final int userId = uss.mHandle.getIdentifier();
    346         synchronized (mLock) {
    347             // Bail if we ended up with a stale user
    348             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
    349 
    350             // Only keep marching forward if user is actually unlocked
    351             if (!StorageManager.isUserKeyUnlocked(userId)) return;
    352 
    353             if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
    354                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    355                 uss.mUnlockProgress.finish();
    356 
    357                 // Dispatch unlocked to external apps
    358                 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
    359                 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    360                 unlockedIntent.addFlags(
    361                         Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
    362                 mInjector.broadcastIntentLocked(unlockedIntent, null, null, 0, null,
    363                         null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
    364                         userId);
    365 
    366                 if (getUserInfo(userId).isManagedProfile()) {
    367                     UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
    368                     if (parent != null) {
    369                         final Intent profileUnlockedIntent = new Intent(
    370                                 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
    371                         profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
    372                         profileUnlockedIntent.addFlags(
    373                                 Intent.FLAG_RECEIVER_REGISTERED_ONLY
    374                                 | Intent.FLAG_RECEIVER_FOREGROUND);
    375                         mInjector.broadcastIntentLocked(profileUnlockedIntent,
    376                                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
    377                                 null, false, false, MY_PID, SYSTEM_UID,
    378                                 parent.id);
    379                     }
    380                 }
    381 
    382                 // Send PRE_BOOT broadcasts if user fingerprint changed; we
    383                 // purposefully block sending BOOT_COMPLETED until after all
    384                 // PRE_BOOT receivers are finished to avoid ANR'ing apps
    385                 final UserInfo info = getUserInfo(userId);
    386                 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
    387                     // Suppress double notifications for managed profiles that
    388                     // were unlocked automatically as part of their parent user
    389                     // being unlocked.
    390                     final boolean quiet;
    391                     if (info.isManagedProfile()) {
    392                         quiet = !uss.tokenProvided
    393                                 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
    394                     } else {
    395                         quiet = false;
    396                     }
    397                     mInjector.sendPreBootBroadcast(userId, quiet,
    398                             () -> finishUserUnlockedCompleted(uss));
    399                 } else {
    400                     finishUserUnlockedCompleted(uss);
    401                 }
    402             }
    403         }
    404     }
    405 
    406     private void finishUserUnlockedCompleted(UserState uss) {
    407         final int userId = uss.mHandle.getIdentifier();
    408         synchronized (mLock) {
    409             // Bail if we ended up with a stale user
    410             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
    411             final UserInfo userInfo = getUserInfo(userId);
    412             if (userInfo == null) {
    413                 return;
    414             }
    415 
    416             // Only keep marching forward if user is actually unlocked
    417             if (!StorageManager.isUserKeyUnlocked(userId)) return;
    418 
    419             // Remember that we logged in
    420             mInjector.getUserManager().onUserLoggedIn(userId);
    421 
    422             if (!userInfo.isInitialized()) {
    423                 if (userId != UserHandle.USER_SYSTEM) {
    424                     Slog.d(TAG, "Initializing user #" + userId);
    425                     Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
    426                     intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
    427                             | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
    428                     mInjector.broadcastIntentLocked(intent, null,
    429                             new IIntentReceiver.Stub() {
    430                                 @Override
    431                                 public void performReceive(Intent intent, int resultCode,
    432                                         String data, Bundle extras, boolean ordered,
    433                                         boolean sticky, int sendingUser) {
    434                                     // Note: performReceive is called with mService lock held
    435                                     mInjector.getUserManager().makeInitialized(userInfo.id);
    436                                 }
    437                             }, 0, null, null, null, AppOpsManager.OP_NONE,
    438                             null, true, false, MY_PID, SYSTEM_UID, userId);
    439                 }
    440             }
    441 
    442             Slog.i(TAG, "Sending BOOT_COMPLETE user #" + userId);
    443             // Do not report secondary users, runtime restarts or first boot/upgrade
    444             if (userId == UserHandle.USER_SYSTEM
    445                     && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
    446                 int uptimeSeconds = (int) (SystemClock.elapsedRealtime() / 1000);
    447                 MetricsLogger.histogram(mInjector.getContext(), "framework_boot_completed",
    448                         uptimeSeconds);
    449             }
    450             final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
    451             bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    452             bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
    453                     | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
    454             mInjector.broadcastIntentLocked(bootIntent, null, new IIntentReceiver.Stub() {
    455                 @Override
    456                 public void performReceive(Intent intent, int resultCode, String data,
    457                         Bundle extras, boolean ordered, boolean sticky, int sendingUser)
    458                         throws RemoteException {
    459                     Slog.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u" + userId);
    460                 }
    461             }, 0, null, null,
    462                     new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
    463                     AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
    464         }
    465     }
    466 
    467     int restartUser(final int userId, final boolean foreground) {
    468         return stopUser(userId, /* force */ true, new IStopUserCallback.Stub() {
    469             @Override
    470             public void userStopped(final int userId) {
    471                 // Post to the same handler that this callback is called from to ensure the user
    472                 // cleanup is complete before restarting.
    473                 mHandler.post(() -> startUser(userId, foreground));
    474             }
    475             @Override
    476             public void userStopAborted(final int userId) {}
    477         });
    478     }
    479 
    480     int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
    481         if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
    482                 != PackageManager.PERMISSION_GRANTED) {
    483             String msg = "Permission Denial: switchUser() from pid="
    484                     + Binder.getCallingPid()
    485                     + ", uid=" + Binder.getCallingUid()
    486                     + " requires " + INTERACT_ACROSS_USERS_FULL;
    487             Slog.w(TAG, msg);
    488             throw new SecurityException(msg);
    489         }
    490         if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
    491             throw new IllegalArgumentException("Can't stop system user " + userId);
    492         }
    493         mInjector.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
    494         synchronized (mLock) {
    495             return stopUsersLocked(userId, force, callback);
    496         }
    497     }
    498 
    499     /**
    500      * Stops the user along with its related users. The method calls
    501      * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
    502      */
    503     private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
    504         if (userId == UserHandle.USER_SYSTEM) {
    505             return USER_OP_ERROR_IS_SYSTEM;
    506         }
    507         if (isCurrentUserLocked(userId)) {
    508             return USER_OP_IS_CURRENT;
    509         }
    510         int[] usersToStop = getUsersToStopLocked(userId);
    511         // If one of related users is system or current, no related users should be stopped
    512         for (int i = 0; i < usersToStop.length; i++) {
    513             int relatedUserId = usersToStop[i];
    514             if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
    515                 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
    516                         + relatedUserId);
    517                 // We still need to stop the requested user if it's a force stop.
    518                 if (force) {
    519                     Slog.i(TAG,
    520                             "Force stop user " + userId + ". Related users will not be stopped");
    521                     stopSingleUserLocked(userId, callback);
    522                     return USER_OP_SUCCESS;
    523                 }
    524                 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
    525             }
    526         }
    527         if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
    528         for (int userIdToStop : usersToStop) {
    529             stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
    530         }
    531         return USER_OP_SUCCESS;
    532     }
    533 
    534     private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
    535         if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
    536         final UserState uss = mStartedUsers.get(userId);
    537         if (uss == null) {
    538             // User is not started, nothing to do...  but we do need to
    539             // callback if requested.
    540             if (callback != null) {
    541                 mHandler.post(new Runnable() {
    542                     @Override
    543                     public void run() {
    544                         try {
    545                             callback.userStopped(userId);
    546                         } catch (RemoteException e) {
    547                         }
    548                     }
    549                 });
    550             }
    551             return;
    552         }
    553 
    554         if (callback != null) {
    555             uss.mStopCallbacks.add(callback);
    556         }
    557 
    558         if (uss.state != UserState.STATE_STOPPING
    559                 && uss.state != UserState.STATE_SHUTDOWN) {
    560             uss.setState(UserState.STATE_STOPPING);
    561             mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    562             updateStartedUserArrayLocked();
    563 
    564             long ident = Binder.clearCallingIdentity();
    565             try {
    566                 // We are going to broadcast ACTION_USER_STOPPING and then
    567                 // once that is done send a final ACTION_SHUTDOWN and then
    568                 // stop the user.
    569                 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
    570                 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    571                 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    572                 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
    573                 // This is the result receiver for the initial stopping broadcast.
    574                 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
    575                     @Override
    576                     public void performReceive(Intent intent, int resultCode, String data,
    577                             Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
    578                         mHandler.post(new Runnable() {
    579                             @Override
    580                             public void run() {
    581                                 finishUserStopping(userId, uss);
    582                             }
    583                         });
    584                     }
    585                 };
    586                 // Clear broadcast queue for the user to avoid delivering stale broadcasts
    587                 mInjector.clearBroadcastQueueForUserLocked(userId);
    588                 // Kick things off.
    589                 mInjector.broadcastIntentLocked(stoppingIntent,
    590                         null, stoppingReceiver, 0, null, null,
    591                         new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
    592                         null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
    593             } finally {
    594                 Binder.restoreCallingIdentity(ident);
    595             }
    596         }
    597     }
    598 
    599     void finishUserStopping(final int userId, final UserState uss) {
    600         // On to the next.
    601         final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
    602         shutdownIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
    603         // This is the result receiver for the final shutdown broadcast.
    604         final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
    605             @Override
    606             public void performReceive(Intent intent, int resultCode, String data,
    607                     Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
    608                 mHandler.post(new Runnable() {
    609                     @Override
    610                     public void run() {
    611                         finishUserStopped(uss);
    612                     }
    613                 });
    614             }
    615         };
    616 
    617         synchronized (mLock) {
    618             if (uss.state != UserState.STATE_STOPPING) {
    619                 // Whoops, we are being started back up.  Abort, abort!
    620                 return;
    621             }
    622             uss.setState(UserState.STATE_SHUTDOWN);
    623         }
    624         mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    625 
    626         mInjector.batteryStatsServiceNoteEvent(
    627                 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
    628                 Integer.toString(userId), userId);
    629         mInjector.systemServiceManagerStopUser(userId);
    630 
    631         synchronized (mLock) {
    632             mInjector.broadcastIntentLocked(shutdownIntent,
    633                     null, shutdownReceiver, 0, null, null, null,
    634                     AppOpsManager.OP_NONE,
    635                     null, true, false, MY_PID, SYSTEM_UID, userId);
    636         }
    637     }
    638 
    639     void finishUserStopped(UserState uss) {
    640         final int userId = uss.mHandle.getIdentifier();
    641         boolean stopped;
    642         ArrayList<IStopUserCallback> callbacks;
    643         synchronized (mLock) {
    644             callbacks = new ArrayList<>(uss.mStopCallbacks);
    645             if (mStartedUsers.get(userId) != uss) {
    646                 stopped = false;
    647             } else if (uss.state != UserState.STATE_SHUTDOWN) {
    648                 stopped = false;
    649             } else {
    650                 stopped = true;
    651                 // User can no longer run.
    652                 mStartedUsers.remove(userId);
    653                 mInjector.getUserManagerInternal().removeUserState(userId);
    654                 mUserLru.remove(Integer.valueOf(userId));
    655                 updateStartedUserArrayLocked();
    656 
    657                 mInjector.activityManagerOnUserStopped(userId);
    658                 // Clean up all state and processes associated with the user.
    659                 // Kill all the processes for the user.
    660                 forceStopUserLocked(userId, "finish user");
    661             }
    662         }
    663 
    664         for (int i = 0; i < callbacks.size(); i++) {
    665             try {
    666                 if (stopped) callbacks.get(i).userStopped(userId);
    667                 else callbacks.get(i).userStopAborted(userId);
    668             } catch (RemoteException e) {
    669             }
    670         }
    671 
    672         if (stopped) {
    673             // Evict the user's credential encryption key
    674             try {
    675                 getStorageManager().lockUserKey(userId);
    676             } catch (RemoteException re) {
    677                 throw re.rethrowAsRuntimeException();
    678             }
    679             mInjector.systemServiceManagerCleanupUser(userId);
    680             synchronized (mLock) {
    681                 mInjector.getActivityStackSupervisor().removeUserLocked(userId);
    682             }
    683             // Remove the user if it is ephemeral.
    684             if (getUserInfo(userId).isEphemeral()) {
    685                 mInjector.getUserManager().removeUser(userId);
    686             }
    687         }
    688     }
    689 
    690     /**
    691      * Determines the list of users that should be stopped together with the specified
    692      * {@code userId}. The returned list includes {@code userId}.
    693      */
    694     private @NonNull int[] getUsersToStopLocked(int userId) {
    695         int startedUsersSize = mStartedUsers.size();
    696         IntArray userIds = new IntArray();
    697         userIds.add(userId);
    698         synchronized (mUserProfileGroupIdsSelfLocked) {
    699             int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
    700                     UserInfo.NO_PROFILE_GROUP_ID);
    701             for (int i = 0; i < startedUsersSize; i++) {
    702                 UserState uss = mStartedUsers.valueAt(i);
    703                 int startedUserId = uss.mHandle.getIdentifier();
    704                 // Skip unrelated users (profileGroupId mismatch)
    705                 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
    706                         UserInfo.NO_PROFILE_GROUP_ID);
    707                 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
    708                         && (userGroupId == startedUserGroupId);
    709                 // userId has already been added
    710                 boolean sameUserId = startedUserId == userId;
    711                 if (!sameGroup || sameUserId) {
    712                     continue;
    713                 }
    714                 userIds.add(startedUserId);
    715             }
    716         }
    717         return userIds.toArray();
    718     }
    719 
    720     private void forceStopUserLocked(int userId, String reason) {
    721         mInjector.activityManagerForceStopPackageLocked(userId, reason);
    722         Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
    723         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
    724                 | Intent.FLAG_RECEIVER_FOREGROUND);
    725         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    726         mInjector.broadcastIntentLocked(intent,
    727                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
    728                 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
    729     }
    730 
    731     /**
    732      * Stops the guest or ephemeral user if it has gone to the background.
    733      */
    734     private void stopGuestOrEphemeralUserIfBackground() {
    735         synchronized (mLock) {
    736             final int num = mUserLru.size();
    737             for (int i = 0; i < num; i++) {
    738                 Integer oldUserId = mUserLru.get(i);
    739                 UserState oldUss = mStartedUsers.get(oldUserId);
    740                 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
    741                         || oldUss.state == UserState.STATE_STOPPING
    742                         || oldUss.state == UserState.STATE_SHUTDOWN) {
    743                     continue;
    744                 }
    745                 UserInfo userInfo = getUserInfo(oldUserId);
    746                 if (userInfo.isEphemeral()) {
    747                     LocalServices.getService(UserManagerInternal.class)
    748                             .onEphemeralUserStop(oldUserId);
    749                 }
    750                 if (userInfo.isGuest() || userInfo.isEphemeral()) {
    751                     // This is a user to be stopped.
    752                     stopUsersLocked(oldUserId, true, null);
    753                     break;
    754                 }
    755             }
    756         }
    757     }
    758 
    759     void startProfilesLocked() {
    760         if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
    761         List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
    762                 mCurrentUserId, false /* enabledOnly */);
    763         List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
    764         for (UserInfo user : profiles) {
    765             if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
    766                     && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
    767                 profilesToStart.add(user);
    768             }
    769         }
    770         final int profilesToStartSize = profilesToStart.size();
    771         int i = 0;
    772         for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
    773             startUser(profilesToStart.get(i).id, /* foreground= */ false);
    774         }
    775         if (i < profilesToStartSize) {
    776             Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
    777         }
    778     }
    779 
    780     private IStorageManager getStorageManager() {
    781         return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
    782     }
    783 
    784     /**
    785      * Start user, if its not already running.
    786      * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
    787      * When starting the user, multiple intents will be broadcast in the following order:</p>
    788      * <ul>
    789      *     <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
    790      *     <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
    791      *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
    792      *     <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
    793      *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
    794      *     <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
    795      *     Sent only if {@code foreground} parameter is true
    796      *     <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
    797      *     of the new fg user
    798      *     <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
    799      *     the new user
    800      *     <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
    801      *     <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
    802      *     new user. Sent only when the user is booting after a system update.
    803      *     <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
    804      *     new user. Sent only the first time a user is starting.
    805      *     <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
    806      *     user. Indicates that the user has finished booting.
    807      * </ul>
    808      *
    809      * @param userId ID of the user to start
    810      * @param foreground true if user should be brought to the foreground
    811      * @return true if the user has been successfully started
    812      */
    813     boolean startUser(final int userId, final boolean foreground) {
    814         if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
    815                 != PackageManager.PERMISSION_GRANTED) {
    816             String msg = "Permission Denial: switchUser() from pid="
    817                     + Binder.getCallingPid()
    818                     + ", uid=" + Binder.getCallingUid()
    819                     + " requires " + INTERACT_ACROSS_USERS_FULL;
    820             Slog.w(TAG, msg);
    821             throw new SecurityException(msg);
    822         }
    823 
    824         Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
    825 
    826         final long ident = Binder.clearCallingIdentity();
    827         try {
    828             synchronized (mLock) {
    829                 final int oldUserId = mCurrentUserId;
    830                 if (oldUserId == userId) {
    831                     return true;
    832                 }
    833 
    834                 if (foreground) {
    835                     mInjector.getActivityStackSupervisor().setLockTaskModeLocked(
    836                             null, ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
    837                 }
    838 
    839                 final UserInfo userInfo = getUserInfo(userId);
    840                 if (userInfo == null) {
    841                     Slog.w(TAG, "No user info for user #" + userId);
    842                     return false;
    843                 }
    844                 if (foreground && userInfo.isManagedProfile()) {
    845                     Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
    846                     return false;
    847                 }
    848 
    849                 if (foreground && mUserSwitchUiEnabled) {
    850                     mInjector.getWindowManager().startFreezingScreen(
    851                             R.anim.screen_user_exit, R.anim.screen_user_enter);
    852                 }
    853 
    854                 boolean needStart = false;
    855 
    856                 // If the user we are switching to is not currently started, then
    857                 // we need to start it now.
    858                 if (mStartedUsers.get(userId) == null) {
    859                     UserState userState = new UserState(UserHandle.of(userId));
    860                     mStartedUsers.put(userId, userState);
    861                     mInjector.getUserManagerInternal().setUserState(userId, userState.state);
    862                     updateStartedUserArrayLocked();
    863                     needStart = true;
    864                 }
    865 
    866                 final UserState uss = mStartedUsers.get(userId);
    867                 final Integer userIdInt = userId;
    868                 mUserLru.remove(userIdInt);
    869                 mUserLru.add(userIdInt);
    870 
    871                 if (foreground) {
    872                     mCurrentUserId = userId;
    873                     mInjector.updateUserConfigurationLocked();
    874                     mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
    875                     updateCurrentProfileIdsLocked();
    876                     mInjector.getWindowManager().setCurrentUser(userId, mCurrentProfileIds);
    877                     // Once the internal notion of the active user has switched, we lock the device
    878                     // with the option to show the user switcher on the keyguard.
    879                     if (mUserSwitchUiEnabled) {
    880                         mInjector.getWindowManager().setSwitchingUser(true);
    881                         mInjector.getWindowManager().lockNow(null);
    882                     }
    883                 } else {
    884                     final Integer currentUserIdInt = mCurrentUserId;
    885                     updateCurrentProfileIdsLocked();
    886                     mInjector.getWindowManager().setCurrentProfileIds(mCurrentProfileIds);
    887                     mUserLru.remove(currentUserIdInt);
    888                     mUserLru.add(currentUserIdInt);
    889                 }
    890 
    891                 // Make sure user is in the started state.  If it is currently
    892                 // stopping, we need to knock that off.
    893                 if (uss.state == UserState.STATE_STOPPING) {
    894                     // If we are stopping, we haven't sent ACTION_SHUTDOWN,
    895                     // so we can just fairly silently bring the user back from
    896                     // the almost-dead.
    897                     uss.setState(uss.lastState);
    898                     mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    899                     updateStartedUserArrayLocked();
    900                     needStart = true;
    901                 } else if (uss.state == UserState.STATE_SHUTDOWN) {
    902                     // This means ACTION_SHUTDOWN has been sent, so we will
    903                     // need to treat this as a new boot of the user.
    904                     uss.setState(UserState.STATE_BOOTING);
    905                     mInjector.getUserManagerInternal().setUserState(userId, uss.state);
    906                     updateStartedUserArrayLocked();
    907                     needStart = true;
    908                 }
    909 
    910                 if (uss.state == UserState.STATE_BOOTING) {
    911                     // Give user manager a chance to propagate user restrictions
    912                     // to other services and prepare app storage
    913                     mInjector.getUserManager().onBeforeStartUser(userId);
    914 
    915                     // Booting up a new user, need to tell system services about it.
    916                     // Note that this is on the same handler as scheduling of broadcasts,
    917                     // which is important because it needs to go first.
    918                     mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
    919                 }
    920 
    921                 if (foreground) {
    922                     mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
    923                             oldUserId));
    924                     mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
    925                     mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
    926                     mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
    927                             oldUserId, userId, uss));
    928                     mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
    929                             oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
    930                 }
    931 
    932                 if (needStart) {
    933                     // Send USER_STARTED broadcast
    934                     Intent intent = new Intent(Intent.ACTION_USER_STARTED);
    935                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
    936                             | Intent.FLAG_RECEIVER_FOREGROUND);
    937                     intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    938                     mInjector.broadcastIntentLocked(intent,
    939                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
    940                             null, false, false, MY_PID, SYSTEM_UID, userId);
    941                 }
    942 
    943                 if (foreground) {
    944                     moveUserToForegroundLocked(uss, oldUserId, userId);
    945                 } else {
    946                     finishUserBoot(uss);
    947                 }
    948 
    949                 if (needStart) {
    950                     Intent intent = new Intent(Intent.ACTION_USER_STARTING);
    951                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
    952                     intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
    953                     mInjector.broadcastIntentLocked(intent,
    954                             null, new IIntentReceiver.Stub() {
    955                                 @Override
    956                                 public void performReceive(Intent intent, int resultCode,
    957                                         String data, Bundle extras, boolean ordered, boolean sticky,
    958                                         int sendingUser) throws RemoteException {
    959                                 }
    960                             }, 0, null, null,
    961                             new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
    962                             null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
    963                 }
    964             }
    965         } finally {
    966             Binder.restoreCallingIdentity(ident);
    967         }
    968 
    969         return true;
    970     }
    971 
    972     /**
    973      * Start user, if its not already running, and bring it to foreground.
    974      */
    975     void startUserInForeground(final int targetUserId) {
    976         boolean success = startUser(targetUserId, /* foreground */ true);
    977         if (!success) {
    978             mInjector.getWindowManager().setSwitchingUser(false);
    979         }
    980     }
    981 
    982     boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
    983         if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
    984                 != PackageManager.PERMISSION_GRANTED) {
    985             String msg = "Permission Denial: unlockUser() from pid="
    986                     + Binder.getCallingPid()
    987                     + ", uid=" + Binder.getCallingUid()
    988                     + " requires " + INTERACT_ACROSS_USERS_FULL;
    989             Slog.w(TAG, msg);
    990             throw new SecurityException(msg);
    991         }
    992 
    993         final long binderToken = Binder.clearCallingIdentity();
    994         try {
    995             return unlockUserCleared(userId, token, secret, listener);
    996         } finally {
    997             Binder.restoreCallingIdentity(binderToken);
    998         }
    999     }
   1000 
   1001     /**
   1002      * Attempt to unlock user without a credential token. This typically
   1003      * succeeds when the device doesn't have credential-encrypted storage, or
   1004      * when the the credential-encrypted storage isn't tied to a user-provided
   1005      * PIN or pattern.
   1006      */
   1007     boolean maybeUnlockUser(final int userId) {
   1008         // Try unlocking storage using empty token
   1009         return unlockUserCleared(userId, null, null, null);
   1010     }
   1011 
   1012     private static void notifyFinished(int userId, IProgressListener listener) {
   1013         if (listener == null) return;
   1014         try {
   1015             listener.onFinished(userId, null);
   1016         } catch (RemoteException ignored) {
   1017         }
   1018     }
   1019 
   1020     boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
   1021             IProgressListener listener) {
   1022         UserState uss;
   1023         synchronized (mLock) {
   1024             // TODO Move this block outside of synchronized if it causes lock contention
   1025             if (!StorageManager.isUserKeyUnlocked(userId)) {
   1026                 final UserInfo userInfo = getUserInfo(userId);
   1027                 final IStorageManager storageManager = getStorageManager();
   1028                 try {
   1029                     // We always want to unlock user storage, even user is not started yet
   1030                     storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
   1031                 } catch (RemoteException | RuntimeException e) {
   1032                     Slog.w(TAG, "Failed to unlock: " + e.getMessage());
   1033                 }
   1034             }
   1035             // Bail if user isn't actually running, otherwise register the given
   1036             // listener to watch for unlock progress
   1037             uss = mStartedUsers.get(userId);
   1038             if (uss == null) {
   1039                 notifyFinished(userId, listener);
   1040                 return false;
   1041             } else {
   1042                 uss.mUnlockProgress.addListener(listener);
   1043                 uss.tokenProvided = (token != null);
   1044             }
   1045         }
   1046 
   1047         finishUserUnlocking(uss);
   1048 
   1049         final ArraySet<Integer> childProfilesToUnlock = new ArraySet<>();
   1050         synchronized (mLock) {
   1051 
   1052             // We just unlocked a user, so let's now attempt to unlock any
   1053             // managed profiles under that user.
   1054             for (int i = 0; i < mStartedUsers.size(); i++) {
   1055                 final int testUserId = mStartedUsers.keyAt(i);
   1056                 final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
   1057                 if (parent != null && parent.id == userId && testUserId != userId) {
   1058                     Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
   1059                             + "): attempting unlock because parent was just unlocked");
   1060                     childProfilesToUnlock.add(testUserId);
   1061                 }
   1062             }
   1063         }
   1064 
   1065         final int size = childProfilesToUnlock.size();
   1066         for (int i = 0; i < size; i++) {
   1067             maybeUnlockUser(childProfilesToUnlock.valueAt(i));
   1068         }
   1069 
   1070         return true;
   1071     }
   1072 
   1073     void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
   1074         // The dialog will show and then initiate the user switch by calling startUserInForeground
   1075         mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second);
   1076     }
   1077 
   1078     void dispatchForegroundProfileChanged(int userId) {
   1079         final int observerCount = mUserSwitchObservers.beginBroadcast();
   1080         for (int i = 0; i < observerCount; i++) {
   1081             try {
   1082                 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
   1083             } catch (RemoteException e) {
   1084                 // Ignore
   1085             }
   1086         }
   1087         mUserSwitchObservers.finishBroadcast();
   1088     }
   1089 
   1090     /** Called on handler thread */
   1091     void dispatchUserSwitchComplete(int userId) {
   1092         mInjector.getWindowManager().setSwitchingUser(false);
   1093         final int observerCount = mUserSwitchObservers.beginBroadcast();
   1094         for (int i = 0; i < observerCount; i++) {
   1095             try {
   1096                 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
   1097             } catch (RemoteException e) {
   1098             }
   1099         }
   1100         mUserSwitchObservers.finishBroadcast();
   1101     }
   1102 
   1103     void dispatchLockedBootComplete(int userId) {
   1104         final int observerCount = mUserSwitchObservers.beginBroadcast();
   1105         for (int i = 0; i < observerCount; i++) {
   1106             try {
   1107                 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
   1108             } catch (RemoteException e) {
   1109                 // Ignore
   1110             }
   1111         }
   1112         mUserSwitchObservers.finishBroadcast();
   1113     }
   1114 
   1115     private void stopBackgroundUsersIfEnforced(int oldUserId) {
   1116         // Never stop system user
   1117         if (oldUserId == UserHandle.USER_SYSTEM) {
   1118             return;
   1119         }
   1120         // For now, only check for user restriction. Additional checks can be added here
   1121         boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
   1122                 oldUserId);
   1123         if (!disallowRunInBg) {
   1124             return;
   1125         }
   1126         synchronized (mLock) {
   1127             if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
   1128                     + " and related users");
   1129             stopUsersLocked(oldUserId, false, null);
   1130         }
   1131     }
   1132 
   1133     void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
   1134         synchronized (mLock) {
   1135             Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
   1136             sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
   1137         }
   1138     }
   1139 
   1140     void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
   1141         Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
   1142         final int observerCount = mUserSwitchObservers.beginBroadcast();
   1143         if (observerCount > 0) {
   1144             final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
   1145             synchronized (mLock) {
   1146                 uss.switching = true;
   1147                 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
   1148             }
   1149             final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
   1150             final long dispatchStartedTime = SystemClock.elapsedRealtime();
   1151             for (int i = 0; i < observerCount; i++) {
   1152                 try {
   1153                     // Prepend with unique prefix to guarantee that keys are unique
   1154                     final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
   1155                     synchronized (mLock) {
   1156                         curWaitingUserSwitchCallbacks.add(name);
   1157                     }
   1158                     final IRemoteCallback callback = new IRemoteCallback.Stub() {
   1159                         @Override
   1160                         public void sendResult(Bundle data) throws RemoteException {
   1161                             synchronized (mLock) {
   1162                                 long delay = SystemClock.elapsedRealtime() - dispatchStartedTime;
   1163                                 if (delay > USER_SWITCH_TIMEOUT) {
   1164                                     Slog.wtf(TAG, "User switch timeout: observer "  + name
   1165                                             + " sent result after " + delay + " ms");
   1166                                 }
   1167                                 // Early return if this session is no longer valid
   1168                                 if (curWaitingUserSwitchCallbacks
   1169                                         != mCurWaitingUserSwitchCallbacks) {
   1170                                     return;
   1171                                 }
   1172                                 curWaitingUserSwitchCallbacks.remove(name);
   1173                                 // Continue switching if all callbacks have been notified
   1174                                 if (waitingCallbacksCount.decrementAndGet() == 0) {
   1175                                     sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
   1176                                 }
   1177                             }
   1178                         }
   1179                     };
   1180                     mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
   1181                 } catch (RemoteException e) {
   1182                 }
   1183             }
   1184         } else {
   1185             synchronized (mLock) {
   1186                 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
   1187             }
   1188         }
   1189         mUserSwitchObservers.finishBroadcast();
   1190     }
   1191 
   1192     void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
   1193         mCurWaitingUserSwitchCallbacks = null;
   1194         mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
   1195         mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
   1196                 oldUserId, newUserId, uss));
   1197     }
   1198 
   1199     void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
   1200         Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
   1201         if (mUserSwitchUiEnabled) {
   1202             synchronized (mLock) {
   1203                 mInjector.getWindowManager().stopFreezingScreen();
   1204             }
   1205         }
   1206         uss.switching = false;
   1207         mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
   1208         mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
   1209                 newUserId, 0));
   1210         stopGuestOrEphemeralUserIfBackground();
   1211         stopBackgroundUsersIfEnforced(oldUserId);
   1212     }
   1213 
   1214     void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
   1215         boolean homeInFront =
   1216                 mInjector.getActivityStackSupervisor().switchUserLocked(newUserId, uss);
   1217         if (homeInFront) {
   1218             mInjector.startHomeActivityLocked(newUserId, "moveUserToForeground");
   1219         } else {
   1220             mInjector.getActivityStackSupervisor().resumeFocusedStackTopActivityLocked();
   1221         }
   1222         EventLogTags.writeAmSwitchUser(newUserId);
   1223         sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
   1224     }
   1225 
   1226     void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
   1227         long ident = Binder.clearCallingIdentity();
   1228         try {
   1229             Intent intent;
   1230             if (oldUserId >= 0) {
   1231                 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
   1232                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
   1233                 int count = profiles.size();
   1234                 for (int i = 0; i < count; i++) {
   1235                     int profileUserId = profiles.get(i).id;
   1236                     intent = new Intent(Intent.ACTION_USER_BACKGROUND);
   1237                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   1238                             | Intent.FLAG_RECEIVER_FOREGROUND);
   1239                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
   1240                     mInjector.broadcastIntentLocked(intent,
   1241                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   1242                             null, false, false, MY_PID, SYSTEM_UID, profileUserId);
   1243                 }
   1244             }
   1245             if (newUserId >= 0) {
   1246                 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
   1247                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
   1248                 int count = profiles.size();
   1249                 for (int i = 0; i < count; i++) {
   1250                     int profileUserId = profiles.get(i).id;
   1251                     intent = new Intent(Intent.ACTION_USER_FOREGROUND);
   1252                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   1253                             | Intent.FLAG_RECEIVER_FOREGROUND);
   1254                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
   1255                     mInjector.broadcastIntentLocked(intent,
   1256                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
   1257                             null, false, false, MY_PID, SYSTEM_UID, profileUserId);
   1258                 }
   1259                 intent = new Intent(Intent.ACTION_USER_SWITCHED);
   1260                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
   1261                         | Intent.FLAG_RECEIVER_FOREGROUND);
   1262                 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
   1263                 mInjector.broadcastIntentLocked(intent,
   1264                         null, null, 0, null, null,
   1265                         new String[] {android.Manifest.permission.MANAGE_USERS},
   1266                         AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
   1267                         UserHandle.USER_ALL);
   1268             }
   1269         } finally {
   1270             Binder.restoreCallingIdentity(ident);
   1271         }
   1272     }
   1273 
   1274 
   1275     int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
   1276             int allowMode, String name, String callerPackage) {
   1277         final int callingUserId = UserHandle.getUserId(callingUid);
   1278         if (callingUserId == userId) {
   1279             return userId;
   1280         }
   1281 
   1282         // Note that we may be accessing mCurrentUserId outside of a lock...
   1283         // shouldn't be a big deal, if this is being called outside
   1284         // of a locked context there is intrinsically a race with
   1285         // the value the caller will receive and someone else changing it.
   1286         // We assume that USER_CURRENT_OR_SELF will use the current user; later
   1287         // we will switch to the calling user if access to the current user fails.
   1288         int targetUserId = unsafeConvertIncomingUserLocked(userId);
   1289 
   1290         if (callingUid != 0 && callingUid != SYSTEM_UID) {
   1291             final boolean allow;
   1292             if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
   1293                     callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
   1294                 // If the caller has this permission, they always pass go.  And collect $200.
   1295                 allow = true;
   1296             } else if (allowMode == ALLOW_FULL_ONLY) {
   1297                 // We require full access, sucks to be you.
   1298                 allow = false;
   1299             } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
   1300                     callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
   1301                 // If the caller does not have either permission, they are always doomed.
   1302                 allow = false;
   1303             } else if (allowMode == ALLOW_NON_FULL) {
   1304                 // We are blanket allowing non-full access, you lucky caller!
   1305                 allow = true;
   1306             } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
   1307                 // We may or may not allow this depending on whether the two users are
   1308                 // in the same profile.
   1309                 allow = isSameProfileGroup(callingUserId, targetUserId);
   1310             } else {
   1311                 throw new IllegalArgumentException("Unknown mode: " + allowMode);
   1312             }
   1313             if (!allow) {
   1314                 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
   1315                     // In this case, they would like to just execute as their
   1316                     // owner user instead of failing.
   1317                     targetUserId = callingUserId;
   1318                 } else {
   1319                     StringBuilder builder = new StringBuilder(128);
   1320                     builder.append("Permission Denial: ");
   1321                     builder.append(name);
   1322                     if (callerPackage != null) {
   1323                         builder.append(" from ");
   1324                         builder.append(callerPackage);
   1325                     }
   1326                     builder.append(" asks to run as user ");
   1327                     builder.append(userId);
   1328                     builder.append(" but is calling from user ");
   1329                     builder.append(UserHandle.getUserId(callingUid));
   1330                     builder.append("; this requires ");
   1331                     builder.append(INTERACT_ACROSS_USERS_FULL);
   1332                     if (allowMode != ALLOW_FULL_ONLY) {
   1333                         builder.append(" or ");
   1334                         builder.append(INTERACT_ACROSS_USERS);
   1335                     }
   1336                     String msg = builder.toString();
   1337                     Slog.w(TAG, msg);
   1338                     throw new SecurityException(msg);
   1339                 }
   1340             }
   1341         }
   1342         if (!allowAll && targetUserId < 0) {
   1343             throw new IllegalArgumentException(
   1344                     "Call does not support special user #" + targetUserId);
   1345         }
   1346         // Check shell permission
   1347         if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
   1348             if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
   1349                 throw new SecurityException("Shell does not have permission to access user "
   1350                         + targetUserId + "\n " + Debug.getCallers(3));
   1351             }
   1352         }
   1353         return targetUserId;
   1354     }
   1355 
   1356     int unsafeConvertIncomingUserLocked(int userId) {
   1357         return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
   1358                 ? getCurrentUserIdLocked(): userId;
   1359     }
   1360 
   1361     void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
   1362         Preconditions.checkNotNull(name, "Observer name cannot be null");
   1363         if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
   1364                 != PackageManager.PERMISSION_GRANTED) {
   1365             final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
   1366                     + Binder.getCallingPid()
   1367                     + ", uid=" + Binder.getCallingUid()
   1368                     + " requires " + INTERACT_ACROSS_USERS_FULL;
   1369             Slog.w(TAG, msg);
   1370             throw new SecurityException(msg);
   1371         }
   1372         mUserSwitchObservers.register(observer, name);
   1373     }
   1374 
   1375     void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
   1376         mUserSwitchObservers.unregister(observer);
   1377     }
   1378 
   1379     UserState getStartedUserStateLocked(int userId) {
   1380         return mStartedUsers.get(userId);
   1381     }
   1382 
   1383     boolean hasStartedUserState(int userId) {
   1384         return mStartedUsers.get(userId) != null;
   1385     }
   1386 
   1387     private void updateStartedUserArrayLocked() {
   1388         int num = 0;
   1389         for (int i = 0; i < mStartedUsers.size(); i++) {
   1390             UserState uss = mStartedUsers.valueAt(i);
   1391             // This list does not include stopping users.
   1392             if (uss.state != UserState.STATE_STOPPING
   1393                     && uss.state != UserState.STATE_SHUTDOWN) {
   1394                 num++;
   1395             }
   1396         }
   1397         mStartedUserArray = new int[num];
   1398         num = 0;
   1399         for (int i = 0; i < mStartedUsers.size(); i++) {
   1400             UserState uss = mStartedUsers.valueAt(i);
   1401             if (uss.state != UserState.STATE_STOPPING
   1402                     && uss.state != UserState.STATE_SHUTDOWN) {
   1403                 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
   1404             }
   1405         }
   1406     }
   1407 
   1408     void sendBootCompletedLocked(IIntentReceiver resultTo) {
   1409         for (int i = 0; i < mStartedUsers.size(); i++) {
   1410             UserState uss = mStartedUsers.valueAt(i);
   1411             finishUserBoot(uss, resultTo);
   1412         }
   1413     }
   1414 
   1415     void onSystemReady() {
   1416         updateCurrentProfileIdsLocked();
   1417     }
   1418 
   1419     /**
   1420      * Refreshes the list of users related to the current user when either a
   1421      * user switch happens or when a new related user is started in the
   1422      * background.
   1423      */
   1424     private void updateCurrentProfileIdsLocked() {
   1425         final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(mCurrentUserId,
   1426                 false /* enabledOnly */);
   1427         int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
   1428         for (int i = 0; i < currentProfileIds.length; i++) {
   1429             currentProfileIds[i] = profiles.get(i).id;
   1430         }
   1431         mCurrentProfileIds = currentProfileIds;
   1432 
   1433         synchronized (mUserProfileGroupIdsSelfLocked) {
   1434             mUserProfileGroupIdsSelfLocked.clear();
   1435             final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
   1436             for (int i = 0; i < users.size(); i++) {
   1437                 UserInfo user = users.get(i);
   1438                 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
   1439                     mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
   1440                 }
   1441             }
   1442         }
   1443     }
   1444 
   1445     int[] getStartedUserArrayLocked() {
   1446         return mStartedUserArray;
   1447     }
   1448 
   1449     boolean isUserStoppingOrShuttingDownLocked(int userId) {
   1450         UserState state = getStartedUserStateLocked(userId);
   1451         if (state == null) {
   1452             return false;
   1453         }
   1454         return state.state == UserState.STATE_STOPPING
   1455                 || state.state == UserState.STATE_SHUTDOWN;
   1456     }
   1457 
   1458     boolean isUserRunningLocked(int userId, int flags) {
   1459         UserState state = getStartedUserStateLocked(userId);
   1460         if (state == null) {
   1461             return false;
   1462         }
   1463         if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
   1464             return true;
   1465         }
   1466         if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
   1467             switch (state.state) {
   1468                 case UserState.STATE_BOOTING:
   1469                 case UserState.STATE_RUNNING_LOCKED:
   1470                     return true;
   1471                 default:
   1472                     return false;
   1473             }
   1474         }
   1475         if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
   1476             switch (state.state) {
   1477                 case UserState.STATE_RUNNING_UNLOCKING:
   1478                 case UserState.STATE_RUNNING_UNLOCKED:
   1479                     return true;
   1480                 default:
   1481                     return false;
   1482             }
   1483         }
   1484         if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
   1485             switch (state.state) {
   1486                 case UserState.STATE_RUNNING_UNLOCKED:
   1487                     return true;
   1488                 default:
   1489                     return false;
   1490             }
   1491         }
   1492 
   1493         // One way or another, we're running!
   1494         return true;
   1495     }
   1496 
   1497     UserInfo getCurrentUser() {
   1498         if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
   1499                 != PackageManager.PERMISSION_GRANTED) && (
   1500                 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
   1501                         != PackageManager.PERMISSION_GRANTED)) {
   1502             String msg = "Permission Denial: getCurrentUser() from pid="
   1503                     + Binder.getCallingPid()
   1504                     + ", uid=" + Binder.getCallingUid()
   1505                     + " requires " + INTERACT_ACROSS_USERS;
   1506             Slog.w(TAG, msg);
   1507             throw new SecurityException(msg);
   1508         }
   1509         synchronized (mLock) {
   1510             return getCurrentUserLocked();
   1511         }
   1512     }
   1513 
   1514     UserInfo getCurrentUserLocked() {
   1515         int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
   1516         return getUserInfo(userId);
   1517     }
   1518 
   1519     int getCurrentOrTargetUserIdLocked() {
   1520         return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
   1521     }
   1522 
   1523     int getCurrentUserIdLocked() {
   1524         return mCurrentUserId;
   1525     }
   1526 
   1527     private boolean isCurrentUserLocked(int userId) {
   1528         return userId == getCurrentOrTargetUserIdLocked();
   1529     }
   1530 
   1531     int setTargetUserIdLocked(int targetUserId) {
   1532         return mTargetUserId = targetUserId;
   1533     }
   1534 
   1535     int[] getUsers() {
   1536         UserManagerService ums = mInjector.getUserManager();
   1537         return ums != null ? ums.getUserIds() : new int[] { 0 };
   1538     }
   1539 
   1540     UserInfo getUserInfo(int userId) {
   1541         return mInjector.getUserManager().getUserInfo(userId);
   1542     }
   1543 
   1544     int[] getUserIds() {
   1545         return mInjector.getUserManager().getUserIds();
   1546     }
   1547 
   1548     boolean exists(int userId) {
   1549         return mInjector.getUserManager().exists(userId);
   1550     }
   1551 
   1552     boolean hasUserRestriction(String restriction, int userId) {
   1553         return mInjector.getUserManager().hasUserRestriction(restriction, userId);
   1554     }
   1555 
   1556     Set<Integer> getProfileIds(int userId) {
   1557         Set<Integer> userIds = new HashSet<>();
   1558         final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(userId,
   1559                 false /* enabledOnly */);
   1560         for (UserInfo user : profiles) {
   1561             userIds.add(user.id);
   1562         }
   1563         return userIds;
   1564     }
   1565 
   1566     boolean isSameProfileGroup(int callingUserId, int targetUserId) {
   1567         if (callingUserId == targetUserId) {
   1568             return true;
   1569         }
   1570         synchronized (mUserProfileGroupIdsSelfLocked) {
   1571             int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
   1572                     UserInfo.NO_PROFILE_GROUP_ID);
   1573             int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
   1574                     UserInfo.NO_PROFILE_GROUP_ID);
   1575             return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
   1576                     && callingProfile == targetProfile;
   1577         }
   1578     }
   1579 
   1580     boolean isCurrentProfileLocked(int userId) {
   1581         return ArrayUtils.contains(mCurrentProfileIds, userId);
   1582     }
   1583 
   1584     int[] getCurrentProfileIdsLocked() {
   1585         return mCurrentProfileIds;
   1586     }
   1587 
   1588     /**
   1589      * Returns whether the given user requires credential entry at this time. This is used to
   1590      * intercept activity launches for work apps when the Work Challenge is present.
   1591      */
   1592     boolean shouldConfirmCredentials(int userId) {
   1593         synchronized (mLock) {
   1594             if (mStartedUsers.get(userId) == null) {
   1595                 return false;
   1596             }
   1597         }
   1598         if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
   1599             return false;
   1600         }
   1601         final KeyguardManager km = mInjector.getKeyguardManager();
   1602         return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
   1603     }
   1604 
   1605     boolean isLockScreenDisabled(@UserIdInt int userId) {
   1606         return mLockPatternUtils.isLockScreenDisabled(userId);
   1607     }
   1608 
   1609     void dump(PrintWriter pw, boolean dumpAll) {
   1610         pw.println("  mStartedUsers:");
   1611         for (int i = 0; i < mStartedUsers.size(); i++) {
   1612             UserState uss = mStartedUsers.valueAt(i);
   1613             pw.print("    User #"); pw.print(uss.mHandle.getIdentifier());
   1614             pw.print(": "); uss.dump("", pw);
   1615         }
   1616         pw.print("  mStartedUserArray: [");
   1617         for (int i = 0; i < mStartedUserArray.length; i++) {
   1618             if (i > 0) pw.print(", ");
   1619             pw.print(mStartedUserArray[i]);
   1620         }
   1621         pw.println("]");
   1622         pw.print("  mUserLru: [");
   1623         for (int i = 0; i < mUserLru.size(); i++) {
   1624             if (i > 0) pw.print(", ");
   1625             pw.print(mUserLru.get(i));
   1626         }
   1627         pw.println("]");
   1628         if (dumpAll) {
   1629             pw.print("  mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
   1630         }
   1631         synchronized (mUserProfileGroupIdsSelfLocked) {
   1632             if (mUserProfileGroupIdsSelfLocked.size() > 0) {
   1633                 pw.println("  mUserProfileGroupIds:");
   1634                 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
   1635                     pw.print("    User #");
   1636                     pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
   1637                     pw.print(" -> profile #");
   1638                     pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
   1639                 }
   1640             }
   1641         }
   1642     }
   1643 
   1644     @VisibleForTesting
   1645     static class Injector {
   1646         private final ActivityManagerService mService;
   1647         private UserManagerService mUserManager;
   1648         private UserManagerInternal mUserManagerInternal;
   1649 
   1650         Injector(ActivityManagerService service) {
   1651             mService = service;
   1652         }
   1653 
   1654         protected Object getLock() {
   1655             return mService;
   1656         }
   1657 
   1658         protected Handler getHandler() {
   1659             return mService.mHandler;
   1660         }
   1661 
   1662         protected Context getContext() {
   1663             return mService.mContext;
   1664         }
   1665 
   1666         protected LockPatternUtils getLockPatternUtils() {
   1667             return new LockPatternUtils(getContext());
   1668         }
   1669 
   1670         protected int broadcastIntentLocked(Intent intent, String resolvedType,
   1671                 IIntentReceiver resultTo, int resultCode, String resultData,
   1672                 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
   1673                 boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) {
   1674             return mService.broadcastIntentLocked(null, null, intent, resolvedType, resultTo,
   1675                     resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions,
   1676                     ordered, sticky, callingPid, callingUid, userId);
   1677         }
   1678 
   1679         int checkCallingPermission(String permission) {
   1680             return mService.checkCallingPermission(permission);
   1681         }
   1682 
   1683         WindowManagerService getWindowManager() {
   1684             return mService.mWindowManager;
   1685         }
   1686         void activityManagerOnUserStopped(int userId) {
   1687             mService.onUserStoppedLocked(userId);
   1688         }
   1689 
   1690         void systemServiceManagerCleanupUser(int userId) {
   1691             mService.mSystemServiceManager.cleanupUser(userId);
   1692         }
   1693 
   1694         protected UserManagerService getUserManager() {
   1695             if (mUserManager == null) {
   1696                 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
   1697                 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
   1698             }
   1699             return mUserManager;
   1700         }
   1701 
   1702         UserManagerInternal getUserManagerInternal() {
   1703             if (mUserManagerInternal == null) {
   1704                 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
   1705             }
   1706             return mUserManagerInternal;
   1707         }
   1708 
   1709         KeyguardManager getKeyguardManager() {
   1710             return mService.mContext.getSystemService(KeyguardManager.class);
   1711         }
   1712 
   1713         void batteryStatsServiceNoteEvent(int code, String name, int uid) {
   1714             mService.mBatteryStatsService.noteEvent(code, name, uid);
   1715         }
   1716 
   1717         void systemServiceManagerStopUser(int userId) {
   1718             mService.mSystemServiceManager.stopUser(userId);
   1719         }
   1720 
   1721         boolean isRuntimeRestarted() {
   1722             return mService.mSystemServiceManager.isRuntimeRestarted();
   1723         }
   1724 
   1725         boolean isFirstBootOrUpgrade() {
   1726             IPackageManager pm = AppGlobals.getPackageManager();
   1727             try {
   1728                 return pm.isFirstBoot() || pm.isUpgrade();
   1729             } catch (RemoteException e) {
   1730                 throw e.rethrowFromSystemServer();
   1731             }
   1732         }
   1733 
   1734         void sendPreBootBroadcast(int userId, boolean quiet, final Runnable onFinish) {
   1735             new PreBootBroadcaster(mService, userId, null, quiet) {
   1736                 @Override
   1737                 public void onFinished() {
   1738                     onFinish.run();
   1739                 }
   1740             }.sendNext();
   1741         }
   1742 
   1743         void activityManagerForceStopPackageLocked(int userId, String reason) {
   1744             mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
   1745                     userId, reason);
   1746         };
   1747 
   1748         int checkComponentPermission(String permission, int pid, int uid, int owningUid,
   1749                 boolean exported) {
   1750             return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
   1751         }
   1752 
   1753         void startHomeActivityLocked(int userId, String reason) {
   1754             mService.startHomeActivityLocked(userId, reason);
   1755         }
   1756 
   1757         void updateUserConfigurationLocked() {
   1758             mService.updateUserConfigurationLocked();
   1759         }
   1760 
   1761         void clearBroadcastQueueForUserLocked(int userId) {
   1762             mService.clearBroadcastQueueForUserLocked(userId);
   1763         }
   1764 
   1765         void enforceShellRestriction(String restriction, int userId) {
   1766             mService.enforceShellRestriction(restriction, userId);
   1767         }
   1768 
   1769         void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser) {
   1770             Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromUser, toUser,
   1771                     true /* above system */);
   1772             d.show();
   1773         }
   1774 
   1775         ActivityStackSupervisor getActivityStackSupervisor() {
   1776             return mService.mStackSupervisor;
   1777         }
   1778     }
   1779 }
   1780