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