2 * Copyright (C) 2015 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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
17 package com.android.server.am;
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;
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_USER_SWITCH_COMPLETE_MSG;
36 import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
37 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
38 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
39 import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
40 import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
41 import static com.android.server.am.UserState.STATE_BOOTING;
42 import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
43 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
44 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
46 import android.annotation.NonNull;
47 import android.annotation.UserIdInt;
48 import android.app.ActivityManager;
49 import android.app.AppOpsManager;
50 import android.app.Dialog;
51 import android.app.IStopUserCallback;
52 import android.app.IUserSwitchObserver;
53 import android.app.KeyguardManager;
54 import android.content.Context;
55 import android.content.IIntentReceiver;
56 import android.content.Intent;
57 import android.content.pm.PackageManager;
58 import android.content.pm.UserInfo;
59 import android.os.BatteryStats;
60 import android.os.Binder;
61 import android.os.Build;
62 import android.os.Bundle;
63 import android.os.Debug;
64 import android.os.Handler;
65 import android.os.IBinder;
66 import android.os.IProgressListener;
67 import android.os.IRemoteCallback;
68 import android.os.IUserManager;
69 import android.os.Process;
70 import android.os.RemoteCallbackList;
71 import android.os.RemoteException;
72 import android.os.ServiceManager;
73 import android.os.SystemClock;
74 import android.os.UserHandle;
75 import android.os.UserManager;
76 import android.os.UserManagerInternal;
77 import android.os.storage.IMountService;
78 import android.os.storage.StorageManager;
79 import android.util.ArraySet;
80 import android.util.IntArray;
81 import android.util.Pair;
82 import android.util.Slog;
83 import android.util.SparseArray;
84 import android.util.SparseIntArray;
86 import com.android.internal.R;
87 import com.android.internal.annotations.GuardedBy;
88 import com.android.internal.logging.MetricsLogger;
89 import com.android.internal.util.ArrayUtils;
90 import com.android.internal.util.Preconditions;
91 import com.android.internal.widget.LockPatternUtils;
92 import com.android.server.LocalServices;
93 import com.android.server.pm.UserManagerService;
95 import java.io.PrintWriter;
96 import java.util.ArrayList;
97 import java.util.Arrays;
98 import java.util.HashSet;
99 import java.util.List;
100 import java.util.Objects;
101 import java.util.Set;
102 import java.util.concurrent.atomic.AtomicInteger;
105 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
107 final class UserController {
108 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
110 // Maximum number of users we allow to be running at a time.
111 static final int MAX_RUNNING_USERS = 3;
113 // Amount of time we wait for observers to handle a user switch before
114 // giving up on them and unfreezing the screen.
115 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
117 private final ActivityManagerService mService;
118 private final Handler mHandler;
120 // Holds the current foreground user's id
121 private int mCurrentUserId = UserHandle.USER_SYSTEM;
122 // Holds the target user's id during a user switch
123 private int mTargetUserId = UserHandle.USER_NULL;
126 * Which users have been started, so are allowed to run code.
128 @GuardedBy("mService")
129 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
132 * LRU list of history of current users. Most recently current is at the end.
134 private final ArrayList<Integer> mUserLru = new ArrayList<>();
137 * Constant array of the users that are currently started.
139 private int[] mStartedUserArray = new int[] { 0 };
141 // If there are multiple profiles for the current user, their ids are here
142 // Currently only the primary user can have managed profiles
143 private int[] mCurrentProfileIds = new int[] {};
146 * Mapping from each known user ID to the profile group ID it is associated with.
148 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
151 * Registered observers of the user switching mechanics.
153 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
154 = new RemoteCallbackList<>();
157 * Currently active user switch callbacks.
159 private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
161 private volatile UserManagerService mUserManager;
163 private final LockPatternUtils mLockPatternUtils;
165 private UserManagerInternal mUserManagerInternal;
167 UserController(ActivityManagerService service) {
169 mHandler = mService.mHandler;
170 // User 0 is the first and only user that runs at boot.
171 final UserState uss = new UserState(UserHandle.SYSTEM);
172 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
173 mUserLru.add(UserHandle.USER_SYSTEM);
174 mLockPatternUtils = new LockPatternUtils(mService.mContext);
175 updateStartedUserArrayLocked();
178 void finishUserSwitch(UserState uss) {
179 synchronized (mService) {
182 startProfilesLocked();
183 stopRunningUsersLocked(MAX_RUNNING_USERS);
187 void stopRunningUsersLocked(int maxRunningUsers) {
188 int num = mUserLru.size();
190 while (num > maxRunningUsers && i < mUserLru.size()) {
191 Integer oldUserId = mUserLru.get(i);
192 UserState oldUss = mStartedUsers.get(oldUserId);
193 if (oldUss == null) {
194 // Shouldn't happen, but be sane if it does.
199 if (oldUss.state == UserState.STATE_STOPPING
200 || oldUss.state == UserState.STATE_SHUTDOWN) {
201 // This user is already stopping, doesn't count.
206 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
207 // Owner/System user and current user can't be stopped. We count it as running
208 // when it is not a pure system user.
209 if (UserInfo.isSystemOnly(oldUserId)) {
215 // This is a user to be stopped.
216 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
224 private void finishUserBoot(UserState uss) {
225 finishUserBoot(uss, null);
228 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
229 final int userId = uss.mHandle.getIdentifier();
231 Slog.d(TAG, "Finishing user boot " + userId);
232 synchronized (mService) {
233 // Bail if we ended up with a stale user
234 if (mStartedUsers.get(userId) != uss) return;
236 // We always walk through all the user lifecycle states to send
237 // consistent developer events. We step into RUNNING_LOCKED here,
238 // but we might immediately step into RUNNING below if the user
239 // storage is already unlocked.
240 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
241 getUserManagerInternal().setUserState(userId, uss.state);
243 int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
244 MetricsLogger.histogram(mService.mContext, "framework_locked_boot_completed",
247 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
248 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
249 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
250 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
251 mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
252 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
253 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
256 // We need to delay unlocking managed profiles until the parent user
258 if (getUserManager().isManagedProfile(userId)) {
259 final UserInfo parent = getUserManager().getProfileParent(userId);
261 && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
262 Slog.d(TAG, "User " + userId + " (parent " + parent.id
263 + "): attempting unlock because parent is unlocked");
264 maybeUnlockUser(userId);
266 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
267 Slog.d(TAG, "User " + userId + " (parent " + parentId
268 + "): delaying unlock because parent is locked");
271 maybeUnlockUser(userId);
277 * Step from {@link UserState#STATE_RUNNING_LOCKED} to
278 * {@link UserState#STATE_RUNNING_UNLOCKING}.
280 private void finishUserUnlocking(final UserState uss) {
281 final int userId = uss.mHandle.getIdentifier();
282 boolean proceedWithUnlock = false;
283 synchronized (mService) {
284 // Bail if we ended up with a stale user
285 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
287 // Only keep marching forward if user is actually unlocked
288 if (!StorageManager.isUserKeyUnlocked(userId)) return;
290 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
291 getUserManagerInternal().setUserState(userId, uss.state);
292 proceedWithUnlock = true;
296 if (proceedWithUnlock) {
297 uss.mUnlockProgress.start();
299 // Prepare app storage before we go any further
300 uss.mUnlockProgress.setProgress(5,
301 mService.mContext.getString(R.string.android_start_title));
302 mUserManager.onBeforeUnlockUser(userId);
303 uss.mUnlockProgress.setProgress(20);
305 // Dispatch unlocked to system services; when fully dispatched,
306 // that calls through to the next "unlocked" phase
307 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
313 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
314 * {@link UserState#STATE_RUNNING_UNLOCKED}.
316 void finishUserUnlocked(final UserState uss) {
317 final int userId = uss.mHandle.getIdentifier();
318 synchronized (mService) {
319 // Bail if we ended up with a stale user
320 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
322 // Only keep marching forward if user is actually unlocked
323 if (!StorageManager.isUserKeyUnlocked(userId)) return;
325 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
326 getUserManagerInternal().setUserState(userId, uss.state);
327 uss.mUnlockProgress.finish();
329 // Dispatch unlocked to external apps
330 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
331 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
332 unlockedIntent.addFlags(
333 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
334 mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
335 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
338 if (getUserInfo(userId).isManagedProfile()) {
339 UserInfo parent = getUserManager().getProfileParent(userId);
340 if (parent != null) {
341 final Intent profileUnlockedIntent = new Intent(
342 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
343 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
344 profileUnlockedIntent.addFlags(
345 Intent.FLAG_RECEIVER_REGISTERED_ONLY
346 | Intent.FLAG_RECEIVER_FOREGROUND);
347 mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
348 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
349 null, false, false, MY_PID, SYSTEM_UID,
354 // Send PRE_BOOT broadcasts if user fingerprint changed; we
355 // purposefully block sending BOOT_COMPLETED until after all
356 // PRE_BOOT receivers are finished to avoid ANR'ing apps
357 final UserInfo info = getUserInfo(userId);
358 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
359 // Suppress double notifications for managed profiles that
360 // were unlocked automatically as part of their parent user
363 if (info.isManagedProfile()) {
364 quiet = !uss.tokenProvided
365 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
369 new PreBootBroadcaster(mService, userId, null, quiet) {
371 public void onFinished() {
372 finishUserUnlockedCompleted(uss);
376 finishUserUnlockedCompleted(uss);
382 private void finishUserUnlockedCompleted(UserState uss) {
383 final int userId = uss.mHandle.getIdentifier();
384 synchronized (mService) {
385 // Bail if we ended up with a stale user
386 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
387 final UserInfo userInfo = getUserInfo(userId);
388 if (userInfo == null) {
392 // Only keep marching forward if user is actually unlocked
393 if (!StorageManager.isUserKeyUnlocked(userId)) return;
395 // Remember that we logged in
396 mUserManager.onUserLoggedIn(userId);
398 if (!userInfo.isInitialized()) {
399 if (userId != UserHandle.USER_SYSTEM) {
400 Slog.d(TAG, "Initializing user #" + userId);
401 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
402 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
403 mService.broadcastIntentLocked(null, null, intent, null,
404 new IIntentReceiver.Stub() {
406 public void performReceive(Intent intent, int resultCode,
407 String data, Bundle extras, boolean ordered,
408 boolean sticky, int sendingUser) {
409 // Note: performReceive is called with mService lock held
410 getUserManager().makeInitialized(userInfo.id);
412 }, 0, null, null, null, AppOpsManager.OP_NONE,
413 null, true, false, MY_PID, SYSTEM_UID, userId);
417 Slog.d(TAG, "Sending BOOT_COMPLETE user #" + userId);
418 int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
419 MetricsLogger.histogram(mService.mContext, "framework_boot_completed", uptimeSeconds);
420 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
421 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
422 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
423 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
424 mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
425 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
426 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
430 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
431 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
432 != PackageManager.PERMISSION_GRANTED) {
433 String msg = "Permission Denial: switchUser() from pid="
434 + Binder.getCallingPid()
435 + ", uid=" + Binder.getCallingUid()
436 + " requires " + INTERACT_ACROSS_USERS_FULL;
438 throw new SecurityException(msg);
440 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
441 throw new IllegalArgumentException("Can't stop system user " + userId);
443 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
445 synchronized (mService) {
446 return stopUsersLocked(userId, force, callback);
451 * Stops the user along with its related users. The method calls
452 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
454 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
455 if (userId == UserHandle.USER_SYSTEM) {
456 return USER_OP_ERROR_IS_SYSTEM;
458 if (isCurrentUserLocked(userId)) {
459 return USER_OP_IS_CURRENT;
461 int[] usersToStop = getUsersToStopLocked(userId);
462 // If one of related users is system or current, no related users should be stopped
463 for (int i = 0; i < usersToStop.length; i++) {
464 int relatedUserId = usersToStop[i];
465 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
466 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
468 // We still need to stop the requested user if it's a force stop.
471 "Force stop user " + userId + ". Related users will not be stopped");
472 stopSingleUserLocked(userId, callback);
473 return USER_OP_SUCCESS;
475 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
478 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
479 for (int userIdToStop : usersToStop) {
480 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
482 return USER_OP_SUCCESS;
485 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
486 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
487 final UserState uss = mStartedUsers.get(userId);
489 // User is not started, nothing to do... but we do need to
490 // callback if requested.
491 if (callback != null) {
492 mHandler.post(new Runnable() {
496 callback.userStopped(userId);
497 } catch (RemoteException e) {
505 if (callback != null) {
506 uss.mStopCallbacks.add(callback);
509 if (uss.state != UserState.STATE_STOPPING
510 && uss.state != UserState.STATE_SHUTDOWN) {
511 uss.setState(UserState.STATE_STOPPING);
512 getUserManagerInternal().setUserState(userId, uss.state);
513 updateStartedUserArrayLocked();
515 long ident = Binder.clearCallingIdentity();
517 // We are going to broadcast ACTION_USER_STOPPING and then
518 // once that is done send a final ACTION_SHUTDOWN and then
520 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
521 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
522 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
523 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
524 // This is the result receiver for the initial stopping broadcast.
525 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
527 public void performReceive(Intent intent, int resultCode, String data,
528 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
529 mHandler.post(new Runnable() {
532 finishUserStopping(userId, uss);
537 // Clear broadcast queue for the user to avoid delivering stale broadcasts
538 mService.clearBroadcastQueueForUserLocked(userId);
540 mService.broadcastIntentLocked(null, null, stoppingIntent,
541 null, stoppingReceiver, 0, null, null,
542 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
543 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
545 Binder.restoreCallingIdentity(ident);
550 void finishUserStopping(final int userId, final UserState uss) {
552 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
553 // This is the result receiver for the final shutdown broadcast.
554 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
556 public void performReceive(Intent intent, int resultCode, String data,
557 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
558 mHandler.post(new Runnable() {
561 finishUserStopped(uss);
567 synchronized (mService) {
568 if (uss.state != UserState.STATE_STOPPING) {
569 // Whoops, we are being started back up. Abort, abort!
572 uss.setState(UserState.STATE_SHUTDOWN);
574 getUserManagerInternal().setUserState(userId, uss.state);
576 mService.mBatteryStatsService.noteEvent(
577 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
578 Integer.toString(userId), userId);
579 mService.mSystemServiceManager.stopUser(userId);
581 synchronized (mService) {
582 mService.broadcastIntentLocked(null, null, shutdownIntent,
583 null, shutdownReceiver, 0, null, null, null,
584 AppOpsManager.OP_NONE,
585 null, true, false, MY_PID, SYSTEM_UID, userId);
589 void finishUserStopped(UserState uss) {
590 final int userId = uss.mHandle.getIdentifier();
592 ArrayList<IStopUserCallback> callbacks;
593 synchronized (mService) {
594 callbacks = new ArrayList<>(uss.mStopCallbacks);
595 if (mStartedUsers.get(userId) != uss) {
597 } else if (uss.state != UserState.STATE_SHUTDOWN) {
601 // User can no longer run.
602 mStartedUsers.remove(userId);
603 getUserManagerInternal().removeUserState(userId);
604 mUserLru.remove(Integer.valueOf(userId));
605 updateStartedUserArrayLocked();
607 mService.onUserStoppedLocked(userId);
608 // Clean up all state and processes associated with the user.
609 // Kill all the processes for the user.
610 forceStopUserLocked(userId, "finish user");
614 for (int i = 0; i < callbacks.size(); i++) {
616 if (stopped) callbacks.get(i).userStopped(userId);
617 else callbacks.get(i).userStopAborted(userId);
618 } catch (RemoteException e) {
623 mService.mSystemServiceManager.cleanupUser(userId);
624 synchronized (mService) {
625 mService.mStackSupervisor.removeUserLocked(userId);
627 // Remove the user if it is ephemeral.
628 if (getUserInfo(userId).isEphemeral()) {
629 mUserManager.removeUser(userId);
635 * Determines the list of users that should be stopped together with the specified
636 * {@code userId}. The returned list includes {@code userId}.
638 private @NonNull int[] getUsersToStopLocked(int userId) {
639 int startedUsersSize = mStartedUsers.size();
640 IntArray userIds = new IntArray();
642 synchronized (mUserProfileGroupIdsSelfLocked) {
643 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
644 UserInfo.NO_PROFILE_GROUP_ID);
645 for (int i = 0; i < startedUsersSize; i++) {
646 UserState uss = mStartedUsers.valueAt(i);
647 int startedUserId = uss.mHandle.getIdentifier();
648 // Skip unrelated users (profileGroupId mismatch)
649 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
650 UserInfo.NO_PROFILE_GROUP_ID);
651 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
652 && (userGroupId == startedUserGroupId);
653 // userId has already been added
654 boolean sameUserId = startedUserId == userId;
655 if (!sameGroup || sameUserId) {
658 userIds.add(startedUserId);
661 return userIds.toArray();
664 private void forceStopUserLocked(int userId, String reason) {
665 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
667 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
668 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
669 | Intent.FLAG_RECEIVER_FOREGROUND);
670 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
671 mService.broadcastIntentLocked(null, null, intent,
672 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
673 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
677 * Stops the guest or ephemeral user if it has gone to the background.
679 private void stopGuestOrEphemeralUserIfBackground() {
680 synchronized (mService) {
681 final int num = mUserLru.size();
682 for (int i = 0; i < num; i++) {
683 Integer oldUserId = mUserLru.get(i);
684 UserState oldUss = mStartedUsers.get(oldUserId);
685 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
686 || oldUss.state == UserState.STATE_STOPPING
687 || oldUss.state == UserState.STATE_SHUTDOWN) {
690 UserInfo userInfo = getUserInfo(oldUserId);
691 if (userInfo.isEphemeral()) {
692 LocalServices.getService(UserManagerInternal.class)
693 .onEphemeralUserStop(oldUserId);
695 if (userInfo.isGuest() || userInfo.isEphemeral()) {
696 // This is a user to be stopped.
697 stopUsersLocked(oldUserId, true, null);
704 void startProfilesLocked() {
705 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
706 List<UserInfo> profiles = getUserManager().getProfiles(
707 mCurrentUserId, false /* enabledOnly */);
708 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
709 for (UserInfo user : profiles) {
710 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
711 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
712 profilesToStart.add(user);
715 final int profilesToStartSize = profilesToStart.size();
717 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
718 startUser(profilesToStart.get(i).id, /* foreground= */ false);
720 if (i < profilesToStartSize) {
721 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
725 private UserManagerService getUserManager() {
726 UserManagerService userManager = mUserManager;
727 if (userManager == null) {
728 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
729 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
734 private IMountService getMountService() {
735 return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
739 * Start user, if its not already running.
740 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
741 * When starting the user, multiple intents will be broadcast in the following order:</p>
743 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
744 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
745 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
746 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
747 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
748 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
749 * Sent only if {@code foreground} parameter is true
750 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
752 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
754 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
755 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
756 * new user. Sent only when the user is booting after a system update.
757 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
758 * new user. Sent only the first time a user is starting.
759 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
760 * user. Indicates that the user has finished booting.
763 * @param userId ID of the user to start
764 * @param foreground true if user should be brought to the foreground
765 * @return true if the user has been successfully started
767 boolean startUser(final int userId, final boolean foreground) {
768 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
769 != PackageManager.PERMISSION_GRANTED) {
770 String msg = "Permission Denial: switchUser() from pid="
771 + Binder.getCallingPid()
772 + ", uid=" + Binder.getCallingUid()
773 + " requires " + INTERACT_ACROSS_USERS_FULL;
775 throw new SecurityException(msg);
778 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
780 final long ident = Binder.clearCallingIdentity();
782 synchronized (mService) {
783 final int oldUserId = mCurrentUserId;
784 if (oldUserId == userId) {
788 mService.mStackSupervisor.setLockTaskModeLocked(null,
789 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
791 final UserInfo userInfo = getUserInfo(userId);
792 if (userInfo == null) {
793 Slog.w(TAG, "No user info for user #" + userId);
796 if (foreground && userInfo.isManagedProfile()) {
797 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
802 mService.mWindowManager.startFreezingScreen(
803 R.anim.screen_user_exit, R.anim.screen_user_enter);
806 boolean needStart = false;
808 // If the user we are switching to is not currently started, then
809 // we need to start it now.
810 if (mStartedUsers.get(userId) == null) {
811 UserState userState = new UserState(UserHandle.of(userId));
812 mStartedUsers.put(userId, userState);
813 getUserManagerInternal().setUserState(userId, userState.state);
814 updateStartedUserArrayLocked();
818 final UserState uss = mStartedUsers.get(userId);
819 final Integer userIdInt = userId;
820 mUserLru.remove(userIdInt);
821 mUserLru.add(userIdInt);
824 mCurrentUserId = userId;
825 mService.updateUserConfigurationLocked();
826 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
827 updateCurrentProfileIdsLocked();
828 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
829 // Once the internal notion of the active user has switched, we lock the device
830 // with the option to show the user switcher on the keyguard.
831 mService.mWindowManager.lockNow(null);
833 final Integer currentUserIdInt = mCurrentUserId;
834 updateCurrentProfileIdsLocked();
835 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
836 mUserLru.remove(currentUserIdInt);
837 mUserLru.add(currentUserIdInt);
840 // Make sure user is in the started state. If it is currently
841 // stopping, we need to knock that off.
842 if (uss.state == UserState.STATE_STOPPING) {
843 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
844 // so we can just fairly silently bring the user back from
846 uss.setState(uss.lastState);
847 getUserManagerInternal().setUserState(userId, uss.state);
848 updateStartedUserArrayLocked();
850 } else if (uss.state == UserState.STATE_SHUTDOWN) {
851 // This means ACTION_SHUTDOWN has been sent, so we will
852 // need to treat this as a new boot of the user.
853 uss.setState(UserState.STATE_BOOTING);
854 getUserManagerInternal().setUserState(userId, uss.state);
855 updateStartedUserArrayLocked();
859 if (uss.state == UserState.STATE_BOOTING) {
860 // Give user manager a chance to propagate user restrictions
861 // to other services and prepare app storage
862 getUserManager().onBeforeStartUser(userId);
864 // Booting up a new user, need to tell system services about it.
865 // Note that this is on the same handler as scheduling of broadcasts,
866 // which is important because it needs to go first.
867 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
871 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
873 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
874 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
875 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
876 oldUserId, userId, uss));
877 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
878 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
882 // Send USER_STARTED broadcast
883 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
884 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
885 | Intent.FLAG_RECEIVER_FOREGROUND);
886 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
887 mService.broadcastIntentLocked(null, null, intent,
888 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
889 null, false, false, MY_PID, SYSTEM_UID, userId);
893 moveUserToForegroundLocked(uss, oldUserId, userId);
895 mService.mUserController.finishUserBoot(uss);
899 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
900 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
901 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
902 mService.broadcastIntentLocked(null, null, intent,
903 null, new IIntentReceiver.Stub() {
905 public void performReceive(Intent intent, int resultCode,
906 String data, Bundle extras, boolean ordered, boolean sticky,
907 int sendingUser) throws RemoteException {
910 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
911 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
915 Binder.restoreCallingIdentity(ident);
922 * Start user, if its not already running, and bring it to foreground.
924 boolean startUserInForeground(final int userId, Dialog dlg) {
925 boolean result = startUser(userId, /* foreground */ true);
930 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
931 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
932 != PackageManager.PERMISSION_GRANTED) {
933 String msg = "Permission Denial: unlockUser() from pid="
934 + Binder.getCallingPid()
935 + ", uid=" + Binder.getCallingUid()
936 + " requires " + INTERACT_ACROSS_USERS_FULL;
938 throw new SecurityException(msg);
941 final long binderToken = Binder.clearCallingIdentity();
943 return unlockUserCleared(userId, token, secret, listener);
945 Binder.restoreCallingIdentity(binderToken);
950 * Attempt to unlock user without a credential token. This typically
951 * succeeds when the device doesn't have credential-encrypted storage, or
952 * when the the credential-encrypted storage isn't tied to a user-provided
955 boolean maybeUnlockUser(final int userId) {
956 // Try unlocking storage using empty token
957 return unlockUserCleared(userId, null, null, null);
960 private static void notifyFinished(int userId, IProgressListener listener) {
961 if (listener == null) return;
963 listener.onFinished(userId, null);
964 } catch (RemoteException ignored) {
968 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
969 IProgressListener listener) {
971 synchronized (mService) {
972 // TODO Move this block outside of synchronized if it causes lock contention
973 if (!StorageManager.isUserKeyUnlocked(userId)) {
974 final UserInfo userInfo = getUserInfo(userId);
975 final IMountService mountService = getMountService();
977 // We always want to unlock user storage, even user is not started yet
978 mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
979 } catch (RemoteException | RuntimeException e) {
980 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
983 // Bail if user isn't actually running, otherwise register the given
984 // listener to watch for unlock progress
985 uss = mStartedUsers.get(userId);
987 notifyFinished(userId, listener);
990 uss.mUnlockProgress.addListener(listener);
991 uss.tokenProvided = (token != null);
995 finishUserUnlocking(uss);
997 final ArraySet<Integer> childProfilesToUnlock = new ArraySet<>();
998 synchronized (mService) {
1000 // We just unlocked a user, so let's now attempt to unlock any
1001 // managed profiles under that user.
1002 for (int i = 0; i < mStartedUsers.size(); i++) {
1003 final int testUserId = mStartedUsers.keyAt(i);
1004 final UserInfo parent = getUserManager().getProfileParent(testUserId);
1005 if (parent != null && parent.id == userId && testUserId != userId) {
1006 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
1007 + "): attempting unlock because parent was just unlocked");
1008 childProfilesToUnlock.add(testUserId);
1013 final int size = childProfilesToUnlock.size();
1014 for (int i = 0; i < size; i++) {
1015 maybeUnlockUser(childProfilesToUnlock.valueAt(i));
1021 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
1022 // The dialog will show and then initiate the user switch by calling startUserInForeground
1023 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
1024 fromToUserPair.second, true /* above system */);
1028 void dispatchForegroundProfileChanged(int userId) {
1029 final int observerCount = mUserSwitchObservers.beginBroadcast();
1030 for (int i = 0; i < observerCount; i++) {
1032 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1033 } catch (RemoteException e) {
1037 mUserSwitchObservers.finishBroadcast();
1040 /** Called on handler thread */
1041 void dispatchUserSwitchComplete(int userId) {
1042 final int observerCount = mUserSwitchObservers.beginBroadcast();
1043 for (int i = 0; i < observerCount; i++) {
1045 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1046 } catch (RemoteException e) {
1049 mUserSwitchObservers.finishBroadcast();
1052 private void stopBackgroundUsersIfEnforced(int oldUserId) {
1053 // Never stop system user
1054 if (oldUserId == UserHandle.USER_SYSTEM) {
1057 // For now, only check for user restriction. Additional checks can be added here
1058 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1060 if (!disallowRunInBg) {
1063 synchronized (mService) {
1064 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1065 + " and related users");
1066 stopUsersLocked(oldUserId, false, null);
1070 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1071 synchronized (mService) {
1072 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId
1073 + ". Observers that didn't send results: " + mCurWaitingUserSwitchCallbacks);
1074 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1078 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1079 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
1080 final int observerCount = mUserSwitchObservers.beginBroadcast();
1081 if (observerCount > 0) {
1082 final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
1083 synchronized (mService) {
1084 uss.switching = true;
1085 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
1087 final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
1088 for (int i = 0; i < observerCount; i++) {
1090 // Prepend with unique prefix to guarantee that keys are unique
1091 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
1092 synchronized (mService) {
1093 curWaitingUserSwitchCallbacks.add(name);
1095 final IRemoteCallback callback = new IRemoteCallback.Stub() {
1097 public void sendResult(Bundle data) throws RemoteException {
1098 synchronized (mService) {
1099 // Early return if this session is no longer valid
1100 if (curWaitingUserSwitchCallbacks
1101 != mCurWaitingUserSwitchCallbacks) {
1104 curWaitingUserSwitchCallbacks.remove(name);
1105 // Continue switching if all callbacks have been notified
1106 if (waitingCallbacksCount.decrementAndGet() == 0) {
1107 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1112 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
1113 } catch (RemoteException e) {
1117 synchronized (mService) {
1118 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1121 mUserSwitchObservers.finishBroadcast();
1124 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1125 mCurWaitingUserSwitchCallbacks = null;
1126 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1127 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1128 oldUserId, newUserId, uss));
1131 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1132 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
1133 synchronized (mService) {
1134 mService.mWindowManager.stopFreezingScreen();
1136 uss.switching = false;
1137 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1138 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1140 stopGuestOrEphemeralUserIfBackground();
1141 stopBackgroundUsersIfEnforced(oldUserId);
1144 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1145 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1147 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1149 mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
1151 EventLogTags.writeAmSwitchUser(newUserId);
1152 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1155 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1156 long ident = Binder.clearCallingIdentity();
1159 if (oldUserId >= 0) {
1160 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1161 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1162 int count = profiles.size();
1163 for (int i = 0; i < count; i++) {
1164 int profileUserId = profiles.get(i).id;
1165 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1166 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1167 | Intent.FLAG_RECEIVER_FOREGROUND);
1168 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1169 mService.broadcastIntentLocked(null, null, intent,
1170 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1171 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1174 if (newUserId >= 0) {
1175 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1176 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1177 int count = profiles.size();
1178 for (int i = 0; i < count; i++) {
1179 int profileUserId = profiles.get(i).id;
1180 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1181 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1182 | Intent.FLAG_RECEIVER_FOREGROUND);
1183 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1184 mService.broadcastIntentLocked(null, null, intent,
1185 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1186 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1188 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1189 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1190 | Intent.FLAG_RECEIVER_FOREGROUND);
1191 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1192 mService.broadcastIntentLocked(null, null, intent,
1193 null, null, 0, null, null,
1194 new String[] {android.Manifest.permission.MANAGE_USERS},
1195 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1196 UserHandle.USER_ALL);
1199 Binder.restoreCallingIdentity(ident);
1204 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1205 int allowMode, String name, String callerPackage) {
1206 final int callingUserId = UserHandle.getUserId(callingUid);
1207 if (callingUserId == userId) {
1211 // Note that we may be accessing mCurrentUserId outside of a lock...
1212 // shouldn't be a big deal, if this is being called outside
1213 // of a locked context there is intrinsically a race with
1214 // the value the caller will receive and someone else changing it.
1215 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1216 // we will switch to the calling user if access to the current user fails.
1217 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1219 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1220 final boolean allow;
1221 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1222 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1223 // If the caller has this permission, they always pass go. And collect $200.
1225 } else if (allowMode == ALLOW_FULL_ONLY) {
1226 // We require full access, sucks to be you.
1228 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1229 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1230 // If the caller does not have either permission, they are always doomed.
1232 } else if (allowMode == ALLOW_NON_FULL) {
1233 // We are blanket allowing non-full access, you lucky caller!
1235 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1236 // We may or may not allow this depending on whether the two users are
1237 // in the same profile.
1238 allow = isSameProfileGroup(callingUserId, targetUserId);
1240 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1243 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1244 // In this case, they would like to just execute as their
1245 // owner user instead of failing.
1246 targetUserId = callingUserId;
1248 StringBuilder builder = new StringBuilder(128);
1249 builder.append("Permission Denial: ");
1250 builder.append(name);
1251 if (callerPackage != null) {
1252 builder.append(" from ");
1253 builder.append(callerPackage);
1255 builder.append(" asks to run as user ");
1256 builder.append(userId);
1257 builder.append(" but is calling from user ");
1258 builder.append(UserHandle.getUserId(callingUid));
1259 builder.append("; this requires ");
1260 builder.append(INTERACT_ACROSS_USERS_FULL);
1261 if (allowMode != ALLOW_FULL_ONLY) {
1262 builder.append(" or ");
1263 builder.append(INTERACT_ACROSS_USERS);
1265 String msg = builder.toString();
1267 throw new SecurityException(msg);
1271 if (!allowAll && targetUserId < 0) {
1272 throw new IllegalArgumentException(
1273 "Call does not support special user #" + targetUserId);
1275 // Check shell permission
1276 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1277 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1278 throw new SecurityException("Shell does not have permission to access user "
1279 + targetUserId + "\n " + Debug.getCallers(3));
1282 return targetUserId;
1285 int unsafeConvertIncomingUserLocked(int userId) {
1286 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1287 ? getCurrentUserIdLocked(): userId;
1290 void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
1291 Preconditions.checkNotNull(name, "Observer name cannot be null");
1292 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1293 != PackageManager.PERMISSION_GRANTED) {
1294 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1295 + Binder.getCallingPid()
1296 + ", uid=" + Binder.getCallingUid()
1297 + " requires " + INTERACT_ACROSS_USERS_FULL;
1299 throw new SecurityException(msg);
1301 mUserSwitchObservers.register(observer, name);
1304 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1305 mUserSwitchObservers.unregister(observer);
1308 UserState getStartedUserStateLocked(int userId) {
1309 return mStartedUsers.get(userId);
1312 boolean hasStartedUserState(int userId) {
1313 return mStartedUsers.get(userId) != null;
1316 private void updateStartedUserArrayLocked() {
1318 for (int i = 0; i < mStartedUsers.size(); i++) {
1319 UserState uss = mStartedUsers.valueAt(i);
1320 // This list does not include stopping users.
1321 if (uss.state != UserState.STATE_STOPPING
1322 && uss.state != UserState.STATE_SHUTDOWN) {
1326 mStartedUserArray = new int[num];
1328 for (int i = 0; i < mStartedUsers.size(); i++) {
1329 UserState uss = mStartedUsers.valueAt(i);
1330 if (uss.state != UserState.STATE_STOPPING
1331 && uss.state != UserState.STATE_SHUTDOWN) {
1332 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1337 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1338 for (int i = 0; i < mStartedUsers.size(); i++) {
1339 UserState uss = mStartedUsers.valueAt(i);
1340 finishUserBoot(uss, resultTo);
1344 void onSystemReady() {
1345 updateCurrentProfileIdsLocked();
1349 * Refreshes the list of users related to the current user when either a
1350 * user switch happens or when a new related user is started in the
1353 private void updateCurrentProfileIdsLocked() {
1354 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
1355 false /* enabledOnly */);
1356 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1357 for (int i = 0; i < currentProfileIds.length; i++) {
1358 currentProfileIds[i] = profiles.get(i).id;
1360 mCurrentProfileIds = currentProfileIds;
1362 synchronized (mUserProfileGroupIdsSelfLocked) {
1363 mUserProfileGroupIdsSelfLocked.clear();
1364 final List<UserInfo> users = getUserManager().getUsers(false);
1365 for (int i = 0; i < users.size(); i++) {
1366 UserInfo user = users.get(i);
1367 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1368 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1374 int[] getStartedUserArrayLocked() {
1375 return mStartedUserArray;
1378 boolean isUserStoppingOrShuttingDownLocked(int userId) {
1379 UserState state = getStartedUserStateLocked(userId);
1380 if (state == null) {
1383 return state.state == UserState.STATE_STOPPING
1384 || state.state == UserState.STATE_SHUTDOWN;
1387 boolean isUserRunningLocked(int userId, int flags) {
1388 UserState state = getStartedUserStateLocked(userId);
1389 if (state == null) {
1392 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1395 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1396 switch (state.state) {
1397 case UserState.STATE_BOOTING:
1398 case UserState.STATE_RUNNING_LOCKED:
1404 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1405 switch (state.state) {
1406 case UserState.STATE_RUNNING_UNLOCKING:
1407 case UserState.STATE_RUNNING_UNLOCKED:
1413 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1414 switch (state.state) {
1415 case UserState.STATE_RUNNING_UNLOCKED:
1422 // One way or another, we're running!
1426 UserInfo getCurrentUser() {
1427 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1428 != PackageManager.PERMISSION_GRANTED) && (
1429 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1430 != PackageManager.PERMISSION_GRANTED)) {
1431 String msg = "Permission Denial: getCurrentUser() from pid="
1432 + Binder.getCallingPid()
1433 + ", uid=" + Binder.getCallingUid()
1434 + " requires " + INTERACT_ACROSS_USERS;
1436 throw new SecurityException(msg);
1438 synchronized (mService) {
1439 return getCurrentUserLocked();
1443 UserInfo getCurrentUserLocked() {
1444 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1445 return getUserInfo(userId);
1448 int getCurrentOrTargetUserIdLocked() {
1449 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1452 int getCurrentUserIdLocked() {
1453 return mCurrentUserId;
1456 private boolean isCurrentUserLocked(int userId) {
1457 return userId == getCurrentOrTargetUserIdLocked();
1460 int setTargetUserIdLocked(int targetUserId) {
1461 return mTargetUserId = targetUserId;
1465 UserManagerService ums = getUserManager();
1466 return ums != null ? ums.getUserIds() : new int[] { 0 };
1469 UserInfo getUserInfo(int userId) {
1470 return getUserManager().getUserInfo(userId);
1473 int[] getUserIds() {
1474 return getUserManager().getUserIds();
1477 boolean exists(int userId) {
1478 return getUserManager().exists(userId);
1481 boolean hasUserRestriction(String restriction, int userId) {
1482 return getUserManager().hasUserRestriction(restriction, userId);
1485 Set<Integer> getProfileIds(int userId) {
1486 Set<Integer> userIds = new HashSet<>();
1487 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1488 false /* enabledOnly */);
1489 for (UserInfo user : profiles) {
1490 userIds.add(user.id);
1495 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1496 if (callingUserId == targetUserId) {
1499 synchronized (mUserProfileGroupIdsSelfLocked) {
1500 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1501 UserInfo.NO_PROFILE_GROUP_ID);
1502 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1503 UserInfo.NO_PROFILE_GROUP_ID);
1504 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1505 && callingProfile == targetProfile;
1509 boolean isCurrentProfileLocked(int userId) {
1510 return ArrayUtils.contains(mCurrentProfileIds, userId);
1513 int[] getCurrentProfileIdsLocked() {
1514 return mCurrentProfileIds;
1518 * Returns whether the given user requires credential entry at this time. This is used to
1519 * intercept activity launches for work apps when the Work Challenge is present.
1521 boolean shouldConfirmCredentials(int userId) {
1522 synchronized (mService) {
1523 if (mStartedUsers.get(userId) == null) {
1527 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1530 final KeyguardManager km = (KeyguardManager) mService.mContext
1531 .getSystemService(KEYGUARD_SERVICE);
1532 return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
1535 boolean isLockScreenDisabled(@UserIdInt int userId) {
1536 return mLockPatternUtils.isLockScreenDisabled(userId);
1539 private UserManagerInternal getUserManagerInternal() {
1540 if (mUserManagerInternal == null) {
1541 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1543 return mUserManagerInternal;
1546 void dump(PrintWriter pw, boolean dumpAll) {
1547 pw.println(" mStartedUsers:");
1548 for (int i = 0; i < mStartedUsers.size(); i++) {
1549 UserState uss = mStartedUsers.valueAt(i);
1550 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1551 pw.print(": "); uss.dump("", pw);
1553 pw.print(" mStartedUserArray: [");
1554 for (int i = 0; i < mStartedUserArray.length; i++) {
1555 if (i > 0) pw.print(", ");
1556 pw.print(mStartedUserArray[i]);
1559 pw.print(" mUserLru: [");
1560 for (int i = 0; i < mUserLru.size(); i++) {
1561 if (i > 0) pw.print(", ");
1562 pw.print(mUserLru.get(i));
1566 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1568 synchronized (mUserProfileGroupIdsSelfLocked) {
1569 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1570 pw.println(" mUserProfileGroupIds:");
1571 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1572 pw.print(" User #");
1573 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1574 pw.print(" -> profile #");
1575 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));