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_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;
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;
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;
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;
110 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
112 final class UserController {
113 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
115 // Maximum number of users we allow to be running at a time.
116 static final int MAX_RUNNING_USERS = 3;
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;
122 private final Object mLock;
123 private final Injector mInjector;
124 private final Handler mHandler;
126 // Holds the current foreground user's id
128 private int mCurrentUserId = UserHandle.USER_SYSTEM;
129 // Holds the target user's id during a user switch
131 private int mTargetUserId = UserHandle.USER_NULL;
134 * Which users have been started, so are allowed to run code.
137 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
140 * LRU list of history of current users. Most recently current is at the end.
143 private final ArrayList<Integer> mUserLru = new ArrayList<>();
146 * Constant array of the users that are currently started.
149 private int[] mStartedUserArray = new int[] { 0 };
151 // If there are multiple profiles for the current user, their ids are here
152 // Currently only the primary user can have managed profiles
154 private int[] mCurrentProfileIds = new int[] {};
157 * Mapping from each known user ID to the profile group ID it is associated with.
159 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
162 * Registered observers of the user switching mechanics.
164 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
165 = new RemoteCallbackList<>();
167 boolean mUserSwitchUiEnabled = true;
170 * Currently active user switch callbacks.
173 private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
175 private volatile UserManagerService mUserManager;
177 private final LockPatternUtils mLockPatternUtils;
179 UserController(ActivityManagerService service) {
180 this(new Injector(service));
184 UserController(Injector injector) {
185 mInjector = injector;
186 mLock = injector.getLock();
187 mHandler = injector.getHandler();
188 // User 0 is the first and only user that runs at boot.
189 final UserState uss = new UserState(UserHandle.SYSTEM);
190 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
191 mUserLru.add(UserHandle.USER_SYSTEM);
192 mLockPatternUtils = mInjector.getLockPatternUtils();
193 updateStartedUserArrayLocked();
196 void finishUserSwitch(UserState uss) {
197 synchronized (mLock) {
200 startProfilesLocked();
201 stopRunningUsersLocked(MAX_RUNNING_USERS);
205 void stopRunningUsersLocked(int maxRunningUsers) {
206 int num = mUserLru.size();
208 while (num > maxRunningUsers && i < mUserLru.size()) {
209 Integer oldUserId = mUserLru.get(i);
210 UserState oldUss = mStartedUsers.get(oldUserId);
211 if (oldUss == null) {
212 // Shouldn't happen, but be sane if it does.
217 if (oldUss.state == UserState.STATE_STOPPING
218 || oldUss.state == UserState.STATE_SHUTDOWN) {
219 // This user is already stopping, doesn't count.
224 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
225 // Owner/System user and current user can't be stopped. We count it as running
226 // when it is not a pure system user.
227 if (UserInfo.isSystemOnly(oldUserId)) {
233 // This is a user to be stopped.
234 if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
242 private void finishUserBoot(UserState uss) {
243 finishUserBoot(uss, null);
246 private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
247 final int userId = uss.mHandle.getIdentifier();
249 Slog.d(TAG, "Finishing user boot " + userId);
250 synchronized (mLock) {
251 // Bail if we ended up with a stale user
252 if (mStartedUsers.get(userId) != uss) return;
254 // We always walk through all the user lifecycle states to send
255 // consistent developer events. We step into RUNNING_LOCKED here,
256 // but we might immediately step into RUNNING below if the user
257 // storage is already unlocked.
258 if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
259 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
260 // Do not report secondary users, runtime restarts or first boot/upgrade
261 if (userId == UserHandle.USER_SYSTEM
262 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
263 int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
264 MetricsLogger.histogram(mInjector.getContext(),
265 "framework_locked_boot_completed", uptimeSeconds);
266 final int MAX_UPTIME_SECONDS = 120;
267 if (uptimeSeconds > MAX_UPTIME_SECONDS) {
268 Slog.wtf("SystemServerTiming",
269 "finishUserBoot took too long. uptimeSeconds=" + uptimeSeconds);
273 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
275 Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
276 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
277 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
278 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
279 mInjector.broadcastIntentLocked(intent, null, resultTo, 0, null, null,
280 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
281 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
284 // We need to delay unlocking managed profiles until the parent user
286 if (mInjector.getUserManager().isManagedProfile(userId)) {
287 final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
289 && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
290 Slog.d(TAG, "User " + userId + " (parent " + parent.id
291 + "): attempting unlock because parent is unlocked");
292 maybeUnlockUser(userId);
294 String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
295 Slog.d(TAG, "User " + userId + " (parent " + parentId
296 + "): delaying unlock because parent is locked");
299 maybeUnlockUser(userId);
305 * Step from {@link UserState#STATE_RUNNING_LOCKED} to
306 * {@link UserState#STATE_RUNNING_UNLOCKING}.
308 private void finishUserUnlocking(final UserState uss) {
309 final int userId = uss.mHandle.getIdentifier();
310 boolean proceedWithUnlock = false;
311 synchronized (mLock) {
312 // Bail if we ended up with a stale user
313 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
315 // Only keep marching forward if user is actually unlocked
316 if (!StorageManager.isUserKeyUnlocked(userId)) return;
318 if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
319 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
320 proceedWithUnlock = true;
324 if (proceedWithUnlock) {
325 uss.mUnlockProgress.start();
327 // Prepare app storage before we go any further
328 uss.mUnlockProgress.setProgress(5,
329 mInjector.getContext().getString(R.string.android_start_title));
330 mInjector.getUserManager().onBeforeUnlockUser(userId);
331 uss.mUnlockProgress.setProgress(20);
333 // Dispatch unlocked to system services; when fully dispatched,
334 // that calls through to the next "unlocked" phase
335 mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
341 * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
342 * {@link UserState#STATE_RUNNING_UNLOCKED}.
344 void finishUserUnlocked(final UserState uss) {
345 final int userId = uss.mHandle.getIdentifier();
346 synchronized (mLock) {
347 // Bail if we ended up with a stale user
348 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
350 // Only keep marching forward if user is actually unlocked
351 if (!StorageManager.isUserKeyUnlocked(userId)) return;
353 if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
354 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
355 uss.mUnlockProgress.finish();
357 // Dispatch unlocked to external apps
358 final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
359 unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
360 unlockedIntent.addFlags(
361 Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
362 mInjector.broadcastIntentLocked(unlockedIntent, null, null, 0, null,
363 null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
366 if (getUserInfo(userId).isManagedProfile()) {
367 UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
368 if (parent != null) {
369 final Intent profileUnlockedIntent = new Intent(
370 Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
371 profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
372 profileUnlockedIntent.addFlags(
373 Intent.FLAG_RECEIVER_REGISTERED_ONLY
374 | Intent.FLAG_RECEIVER_FOREGROUND);
375 mInjector.broadcastIntentLocked(profileUnlockedIntent,
376 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
377 null, false, false, MY_PID, SYSTEM_UID,
382 // Send PRE_BOOT broadcasts if user fingerprint changed; we
383 // purposefully block sending BOOT_COMPLETED until after all
384 // PRE_BOOT receivers are finished to avoid ANR'ing apps
385 final UserInfo info = getUserInfo(userId);
386 if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
387 // Suppress double notifications for managed profiles that
388 // were unlocked automatically as part of their parent user
391 if (info.isManagedProfile()) {
392 quiet = !uss.tokenProvided
393 || !mLockPatternUtils.isSeparateProfileChallengeEnabled(userId);
397 mInjector.sendPreBootBroadcast(userId, quiet,
398 () -> finishUserUnlockedCompleted(uss));
400 finishUserUnlockedCompleted(uss);
406 private void finishUserUnlockedCompleted(UserState uss) {
407 final int userId = uss.mHandle.getIdentifier();
408 synchronized (mLock) {
409 // Bail if we ended up with a stale user
410 if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
411 final UserInfo userInfo = getUserInfo(userId);
412 if (userInfo == null) {
416 // Only keep marching forward if user is actually unlocked
417 if (!StorageManager.isUserKeyUnlocked(userId)) return;
419 // Remember that we logged in
420 mInjector.getUserManager().onUserLoggedIn(userId);
422 if (!userInfo.isInitialized()) {
423 if (userId != UserHandle.USER_SYSTEM) {
424 Slog.d(TAG, "Initializing user #" + userId);
425 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
426 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
427 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
428 mInjector.broadcastIntentLocked(intent, null,
429 new IIntentReceiver.Stub() {
431 public void performReceive(Intent intent, int resultCode,
432 String data, Bundle extras, boolean ordered,
433 boolean sticky, int sendingUser) {
434 // Note: performReceive is called with mService lock held
435 mInjector.getUserManager().makeInitialized(userInfo.id);
437 }, 0, null, null, null, AppOpsManager.OP_NONE,
438 null, true, false, MY_PID, SYSTEM_UID, userId);
442 Slog.i(TAG, "Sending BOOT_COMPLETE user #" + userId);
443 // Do not report secondary users, runtime restarts or first boot/upgrade
444 if (userId == UserHandle.USER_SYSTEM
445 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
446 int uptimeSeconds = (int) (SystemClock.elapsedRealtime() / 1000);
447 MetricsLogger.histogram(mInjector.getContext(), "framework_boot_completed",
450 final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
451 bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
452 bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
453 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
454 mInjector.broadcastIntentLocked(bootIntent, null, new IIntentReceiver.Stub() {
456 public void performReceive(Intent intent, int resultCode, String data,
457 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
458 throws RemoteException {
459 Slog.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u" + userId);
462 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
463 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
467 int restartUser(final int userId, final boolean foreground) {
468 return stopUser(userId, /* force */ true, new IStopUserCallback.Stub() {
470 public void userStopped(final int userId) {
471 // Post to the same handler that this callback is called from to ensure the user
472 // cleanup is complete before restarting.
473 mHandler.post(() -> startUser(userId, foreground));
476 public void userStopAborted(final int userId) {}
480 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
481 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
482 != PackageManager.PERMISSION_GRANTED) {
483 String msg = "Permission Denial: switchUser() from pid="
484 + Binder.getCallingPid()
485 + ", uid=" + Binder.getCallingUid()
486 + " requires " + INTERACT_ACROSS_USERS_FULL;
488 throw new SecurityException(msg);
490 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
491 throw new IllegalArgumentException("Can't stop system user " + userId);
493 mInjector.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
494 synchronized (mLock) {
495 return stopUsersLocked(userId, force, callback);
500 * Stops the user along with its related users. The method calls
501 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
503 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
504 if (userId == UserHandle.USER_SYSTEM) {
505 return USER_OP_ERROR_IS_SYSTEM;
507 if (isCurrentUserLocked(userId)) {
508 return USER_OP_IS_CURRENT;
510 int[] usersToStop = getUsersToStopLocked(userId);
511 // If one of related users is system or current, no related users should be stopped
512 for (int i = 0; i < usersToStop.length; i++) {
513 int relatedUserId = usersToStop[i];
514 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
515 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
517 // We still need to stop the requested user if it's a force stop.
520 "Force stop user " + userId + ". Related users will not be stopped");
521 stopSingleUserLocked(userId, callback);
522 return USER_OP_SUCCESS;
524 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
527 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
528 for (int userIdToStop : usersToStop) {
529 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
531 return USER_OP_SUCCESS;
534 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
535 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
536 final UserState uss = mStartedUsers.get(userId);
538 // User is not started, nothing to do... but we do need to
539 // callback if requested.
540 if (callback != null) {
541 mHandler.post(new Runnable() {
545 callback.userStopped(userId);
546 } catch (RemoteException e) {
554 if (callback != null) {
555 uss.mStopCallbacks.add(callback);
558 if (uss.state != UserState.STATE_STOPPING
559 && uss.state != UserState.STATE_SHUTDOWN) {
560 uss.setState(UserState.STATE_STOPPING);
561 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
562 updateStartedUserArrayLocked();
564 long ident = Binder.clearCallingIdentity();
566 // We are going to broadcast ACTION_USER_STOPPING and then
567 // once that is done send a final ACTION_SHUTDOWN and then
569 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
570 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
571 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
572 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
573 // This is the result receiver for the initial stopping broadcast.
574 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
576 public void performReceive(Intent intent, int resultCode, String data,
577 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
578 mHandler.post(new Runnable() {
581 finishUserStopping(userId, uss);
586 // Clear broadcast queue for the user to avoid delivering stale broadcasts
587 mInjector.clearBroadcastQueueForUserLocked(userId);
589 mInjector.broadcastIntentLocked(stoppingIntent,
590 null, stoppingReceiver, 0, null, null,
591 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
592 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
594 Binder.restoreCallingIdentity(ident);
599 void finishUserStopping(final int userId, final UserState uss) {
601 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
602 shutdownIntent.addFlags(Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
603 // This is the result receiver for the final shutdown broadcast.
604 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
606 public void performReceive(Intent intent, int resultCode, String data,
607 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
608 mHandler.post(new Runnable() {
611 finishUserStopped(uss);
617 synchronized (mLock) {
618 if (uss.state != UserState.STATE_STOPPING) {
619 // Whoops, we are being started back up. Abort, abort!
622 uss.setState(UserState.STATE_SHUTDOWN);
624 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
626 mInjector.batteryStatsServiceNoteEvent(
627 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
628 Integer.toString(userId), userId);
629 mInjector.systemServiceManagerStopUser(userId);
631 synchronized (mLock) {
632 mInjector.broadcastIntentLocked(shutdownIntent,
633 null, shutdownReceiver, 0, null, null, null,
634 AppOpsManager.OP_NONE,
635 null, true, false, MY_PID, SYSTEM_UID, userId);
639 void finishUserStopped(UserState uss) {
640 final int userId = uss.mHandle.getIdentifier();
642 ArrayList<IStopUserCallback> callbacks;
643 synchronized (mLock) {
644 callbacks = new ArrayList<>(uss.mStopCallbacks);
645 if (mStartedUsers.get(userId) != uss) {
647 } else if (uss.state != UserState.STATE_SHUTDOWN) {
651 // User can no longer run.
652 mStartedUsers.remove(userId);
653 mInjector.getUserManagerInternal().removeUserState(userId);
654 mUserLru.remove(Integer.valueOf(userId));
655 updateStartedUserArrayLocked();
657 mInjector.activityManagerOnUserStopped(userId);
658 // Clean up all state and processes associated with the user.
659 // Kill all the processes for the user.
660 forceStopUserLocked(userId, "finish user");
664 for (int i = 0; i < callbacks.size(); i++) {
666 if (stopped) callbacks.get(i).userStopped(userId);
667 else callbacks.get(i).userStopAborted(userId);
668 } catch (RemoteException e) {
673 // Evict the user's credential encryption key
675 getStorageManager().lockUserKey(userId);
676 } catch (RemoteException re) {
677 throw re.rethrowAsRuntimeException();
679 mInjector.systemServiceManagerCleanupUser(userId);
680 synchronized (mLock) {
681 mInjector.getActivityStackSupervisor().removeUserLocked(userId);
683 // Remove the user if it is ephemeral.
684 if (getUserInfo(userId).isEphemeral()) {
685 mInjector.getUserManager().removeUser(userId);
691 * Determines the list of users that should be stopped together with the specified
692 * {@code userId}. The returned list includes {@code userId}.
694 private @NonNull int[] getUsersToStopLocked(int userId) {
695 int startedUsersSize = mStartedUsers.size();
696 IntArray userIds = new IntArray();
698 synchronized (mUserProfileGroupIdsSelfLocked) {
699 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
700 UserInfo.NO_PROFILE_GROUP_ID);
701 for (int i = 0; i < startedUsersSize; i++) {
702 UserState uss = mStartedUsers.valueAt(i);
703 int startedUserId = uss.mHandle.getIdentifier();
704 // Skip unrelated users (profileGroupId mismatch)
705 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
706 UserInfo.NO_PROFILE_GROUP_ID);
707 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
708 && (userGroupId == startedUserGroupId);
709 // userId has already been added
710 boolean sameUserId = startedUserId == userId;
711 if (!sameGroup || sameUserId) {
714 userIds.add(startedUserId);
717 return userIds.toArray();
720 private void forceStopUserLocked(int userId, String reason) {
721 mInjector.activityManagerForceStopPackageLocked(userId, reason);
722 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
723 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
724 | Intent.FLAG_RECEIVER_FOREGROUND);
725 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
726 mInjector.broadcastIntentLocked(intent,
727 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
728 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
732 * Stops the guest or ephemeral user if it has gone to the background.
734 private void stopGuestOrEphemeralUserIfBackground() {
735 synchronized (mLock) {
736 final int num = mUserLru.size();
737 for (int i = 0; i < num; i++) {
738 Integer oldUserId = mUserLru.get(i);
739 UserState oldUss = mStartedUsers.get(oldUserId);
740 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
741 || oldUss.state == UserState.STATE_STOPPING
742 || oldUss.state == UserState.STATE_SHUTDOWN) {
745 UserInfo userInfo = getUserInfo(oldUserId);
746 if (userInfo.isEphemeral()) {
747 LocalServices.getService(UserManagerInternal.class)
748 .onEphemeralUserStop(oldUserId);
750 if (userInfo.isGuest() || userInfo.isEphemeral()) {
751 // This is a user to be stopped.
752 stopUsersLocked(oldUserId, true, null);
759 void startProfilesLocked() {
760 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
761 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
762 mCurrentUserId, false /* enabledOnly */);
763 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
764 for (UserInfo user : profiles) {
765 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
766 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
767 profilesToStart.add(user);
770 final int profilesToStartSize = profilesToStart.size();
772 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
773 startUser(profilesToStart.get(i).id, /* foreground= */ false);
775 if (i < profilesToStartSize) {
776 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
780 private IStorageManager getStorageManager() {
781 return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
785 * Start user, if its not already running.
786 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
787 * When starting the user, multiple intents will be broadcast in the following order:</p>
789 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
790 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
791 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
792 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
793 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
794 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
795 * Sent only if {@code foreground} parameter is true
796 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
798 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
800 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
801 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
802 * new user. Sent only when the user is booting after a system update.
803 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
804 * new user. Sent only the first time a user is starting.
805 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
806 * user. Indicates that the user has finished booting.
809 * @param userId ID of the user to start
810 * @param foreground true if user should be brought to the foreground
811 * @return true if the user has been successfully started
813 boolean startUser(final int userId, final boolean foreground) {
814 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
815 != PackageManager.PERMISSION_GRANTED) {
816 String msg = "Permission Denial: switchUser() from pid="
817 + Binder.getCallingPid()
818 + ", uid=" + Binder.getCallingUid()
819 + " requires " + INTERACT_ACROSS_USERS_FULL;
821 throw new SecurityException(msg);
824 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
826 final long ident = Binder.clearCallingIdentity();
828 synchronized (mLock) {
829 final int oldUserId = mCurrentUserId;
830 if (oldUserId == userId) {
835 mInjector.getActivityStackSupervisor().setLockTaskModeLocked(
836 null, ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
839 final UserInfo userInfo = getUserInfo(userId);
840 if (userInfo == null) {
841 Slog.w(TAG, "No user info for user #" + userId);
844 if (foreground && userInfo.isManagedProfile()) {
845 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
849 if (foreground && mUserSwitchUiEnabled) {
850 mInjector.getWindowManager().startFreezingScreen(
851 R.anim.screen_user_exit, R.anim.screen_user_enter);
854 boolean needStart = false;
856 // If the user we are switching to is not currently started, then
857 // we need to start it now.
858 if (mStartedUsers.get(userId) == null) {
859 UserState userState = new UserState(UserHandle.of(userId));
860 mStartedUsers.put(userId, userState);
861 mInjector.getUserManagerInternal().setUserState(userId, userState.state);
862 updateStartedUserArrayLocked();
866 final UserState uss = mStartedUsers.get(userId);
867 final Integer userIdInt = userId;
868 mUserLru.remove(userIdInt);
869 mUserLru.add(userIdInt);
872 mCurrentUserId = userId;
873 mInjector.updateUserConfigurationLocked();
874 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
875 updateCurrentProfileIdsLocked();
876 mInjector.getWindowManager().setCurrentUser(userId, mCurrentProfileIds);
877 // Once the internal notion of the active user has switched, we lock the device
878 // with the option to show the user switcher on the keyguard.
879 if (mUserSwitchUiEnabled) {
880 mInjector.getWindowManager().setSwitchingUser(true);
881 mInjector.getWindowManager().lockNow(null);
884 final Integer currentUserIdInt = mCurrentUserId;
885 updateCurrentProfileIdsLocked();
886 mInjector.getWindowManager().setCurrentProfileIds(mCurrentProfileIds);
887 mUserLru.remove(currentUserIdInt);
888 mUserLru.add(currentUserIdInt);
891 // Make sure user is in the started state. If it is currently
892 // stopping, we need to knock that off.
893 if (uss.state == UserState.STATE_STOPPING) {
894 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
895 // so we can just fairly silently bring the user back from
897 uss.setState(uss.lastState);
898 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
899 updateStartedUserArrayLocked();
901 } else if (uss.state == UserState.STATE_SHUTDOWN) {
902 // This means ACTION_SHUTDOWN has been sent, so we will
903 // need to treat this as a new boot of the user.
904 uss.setState(UserState.STATE_BOOTING);
905 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
906 updateStartedUserArrayLocked();
910 if (uss.state == UserState.STATE_BOOTING) {
911 // Give user manager a chance to propagate user restrictions
912 // to other services and prepare app storage
913 mInjector.getUserManager().onBeforeStartUser(userId);
915 // Booting up a new user, need to tell system services about it.
916 // Note that this is on the same handler as scheduling of broadcasts,
917 // which is important because it needs to go first.
918 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
922 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
924 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
925 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
926 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
927 oldUserId, userId, uss));
928 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
929 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
933 // Send USER_STARTED broadcast
934 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
935 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
936 | Intent.FLAG_RECEIVER_FOREGROUND);
937 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
938 mInjector.broadcastIntentLocked(intent,
939 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
940 null, false, false, MY_PID, SYSTEM_UID, userId);
944 moveUserToForegroundLocked(uss, oldUserId, userId);
950 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
951 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
952 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
953 mInjector.broadcastIntentLocked(intent,
954 null, new IIntentReceiver.Stub() {
956 public void performReceive(Intent intent, int resultCode,
957 String data, Bundle extras, boolean ordered, boolean sticky,
958 int sendingUser) throws RemoteException {
961 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
962 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
966 Binder.restoreCallingIdentity(ident);
973 * Start user, if its not already running, and bring it to foreground.
975 void startUserInForeground(final int targetUserId) {
976 boolean success = startUser(targetUserId, /* foreground */ true);
978 mInjector.getWindowManager().setSwitchingUser(false);
982 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
983 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
984 != PackageManager.PERMISSION_GRANTED) {
985 String msg = "Permission Denial: unlockUser() from pid="
986 + Binder.getCallingPid()
987 + ", uid=" + Binder.getCallingUid()
988 + " requires " + INTERACT_ACROSS_USERS_FULL;
990 throw new SecurityException(msg);
993 final long binderToken = Binder.clearCallingIdentity();
995 return unlockUserCleared(userId, token, secret, listener);
997 Binder.restoreCallingIdentity(binderToken);
1002 * Attempt to unlock user without a credential token. This typically
1003 * succeeds when the device doesn't have credential-encrypted storage, or
1004 * when the the credential-encrypted storage isn't tied to a user-provided
1007 boolean maybeUnlockUser(final int userId) {
1008 // Try unlocking storage using empty token
1009 return unlockUserCleared(userId, null, null, null);
1012 private static void notifyFinished(int userId, IProgressListener listener) {
1013 if (listener == null) return;
1015 listener.onFinished(userId, null);
1016 } catch (RemoteException ignored) {
1020 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
1021 IProgressListener listener) {
1023 synchronized (mLock) {
1024 // TODO Move this block outside of synchronized if it causes lock contention
1025 if (!StorageManager.isUserKeyUnlocked(userId)) {
1026 final UserInfo userInfo = getUserInfo(userId);
1027 final IStorageManager storageManager = getStorageManager();
1029 // We always want to unlock user storage, even user is not started yet
1030 storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
1031 } catch (RemoteException | RuntimeException e) {
1032 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
1035 // Bail if user isn't actually running, otherwise register the given
1036 // listener to watch for unlock progress
1037 uss = mStartedUsers.get(userId);
1039 notifyFinished(userId, listener);
1042 uss.mUnlockProgress.addListener(listener);
1043 uss.tokenProvided = (token != null);
1047 finishUserUnlocking(uss);
1049 final ArraySet<Integer> childProfilesToUnlock = new ArraySet<>();
1050 synchronized (mLock) {
1052 // We just unlocked a user, so let's now attempt to unlock any
1053 // managed profiles under that user.
1054 for (int i = 0; i < mStartedUsers.size(); i++) {
1055 final int testUserId = mStartedUsers.keyAt(i);
1056 final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
1057 if (parent != null && parent.id == userId && testUserId != userId) {
1058 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
1059 + "): attempting unlock because parent was just unlocked");
1060 childProfilesToUnlock.add(testUserId);
1065 final int size = childProfilesToUnlock.size();
1066 for (int i = 0; i < size; i++) {
1067 maybeUnlockUser(childProfilesToUnlock.valueAt(i));
1073 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
1074 // The dialog will show and then initiate the user switch by calling startUserInForeground
1075 mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second);
1078 void dispatchForegroundProfileChanged(int userId) {
1079 final int observerCount = mUserSwitchObservers.beginBroadcast();
1080 for (int i = 0; i < observerCount; i++) {
1082 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1083 } catch (RemoteException e) {
1087 mUserSwitchObservers.finishBroadcast();
1090 /** Called on handler thread */
1091 void dispatchUserSwitchComplete(int userId) {
1092 mInjector.getWindowManager().setSwitchingUser(false);
1093 final int observerCount = mUserSwitchObservers.beginBroadcast();
1094 for (int i = 0; i < observerCount; i++) {
1096 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1097 } catch (RemoteException e) {
1100 mUserSwitchObservers.finishBroadcast();
1103 void dispatchLockedBootComplete(int userId) {
1104 final int observerCount = mUserSwitchObservers.beginBroadcast();
1105 for (int i = 0; i < observerCount; i++) {
1107 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
1108 } catch (RemoteException e) {
1112 mUserSwitchObservers.finishBroadcast();
1115 private void stopBackgroundUsersIfEnforced(int oldUserId) {
1116 // Never stop system user
1117 if (oldUserId == UserHandle.USER_SYSTEM) {
1120 // For now, only check for user restriction. Additional checks can be added here
1121 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1123 if (!disallowRunInBg) {
1126 synchronized (mLock) {
1127 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1128 + " and related users");
1129 stopUsersLocked(oldUserId, false, null);
1133 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1134 synchronized (mLock) {
1135 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
1136 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1140 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1141 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
1142 final int observerCount = mUserSwitchObservers.beginBroadcast();
1143 if (observerCount > 0) {
1144 final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
1145 synchronized (mLock) {
1146 uss.switching = true;
1147 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
1149 final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
1150 final long dispatchStartedTime = SystemClock.elapsedRealtime();
1151 for (int i = 0; i < observerCount; i++) {
1153 // Prepend with unique prefix to guarantee that keys are unique
1154 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
1155 synchronized (mLock) {
1156 curWaitingUserSwitchCallbacks.add(name);
1158 final IRemoteCallback callback = new IRemoteCallback.Stub() {
1160 public void sendResult(Bundle data) throws RemoteException {
1161 synchronized (mLock) {
1162 long delay = SystemClock.elapsedRealtime() - dispatchStartedTime;
1163 if (delay > USER_SWITCH_TIMEOUT) {
1164 Slog.wtf(TAG, "User switch timeout: observer " + name
1165 + " sent result after " + delay + " ms");
1167 // Early return if this session is no longer valid
1168 if (curWaitingUserSwitchCallbacks
1169 != mCurWaitingUserSwitchCallbacks) {
1172 curWaitingUserSwitchCallbacks.remove(name);
1173 // Continue switching if all callbacks have been notified
1174 if (waitingCallbacksCount.decrementAndGet() == 0) {
1175 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1180 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
1181 } catch (RemoteException e) {
1185 synchronized (mLock) {
1186 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1189 mUserSwitchObservers.finishBroadcast();
1192 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1193 mCurWaitingUserSwitchCallbacks = null;
1194 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1195 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1196 oldUserId, newUserId, uss));
1199 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1200 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
1201 if (mUserSwitchUiEnabled) {
1202 synchronized (mLock) {
1203 mInjector.getWindowManager().stopFreezingScreen();
1206 uss.switching = false;
1207 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1208 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1210 stopGuestOrEphemeralUserIfBackground();
1211 stopBackgroundUsersIfEnforced(oldUserId);
1214 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1215 boolean homeInFront =
1216 mInjector.getActivityStackSupervisor().switchUserLocked(newUserId, uss);
1218 mInjector.startHomeActivityLocked(newUserId, "moveUserToForeground");
1220 mInjector.getActivityStackSupervisor().resumeFocusedStackTopActivityLocked();
1222 EventLogTags.writeAmSwitchUser(newUserId);
1223 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1226 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1227 long ident = Binder.clearCallingIdentity();
1230 if (oldUserId >= 0) {
1231 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1232 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
1233 int count = profiles.size();
1234 for (int i = 0; i < count; i++) {
1235 int profileUserId = profiles.get(i).id;
1236 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1237 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1238 | Intent.FLAG_RECEIVER_FOREGROUND);
1239 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1240 mInjector.broadcastIntentLocked(intent,
1241 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1242 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1245 if (newUserId >= 0) {
1246 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1247 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
1248 int count = profiles.size();
1249 for (int i = 0; i < count; i++) {
1250 int profileUserId = profiles.get(i).id;
1251 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1252 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1253 | Intent.FLAG_RECEIVER_FOREGROUND);
1254 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1255 mInjector.broadcastIntentLocked(intent,
1256 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1257 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1259 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1260 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1261 | Intent.FLAG_RECEIVER_FOREGROUND);
1262 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1263 mInjector.broadcastIntentLocked(intent,
1264 null, null, 0, null, null,
1265 new String[] {android.Manifest.permission.MANAGE_USERS},
1266 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1267 UserHandle.USER_ALL);
1270 Binder.restoreCallingIdentity(ident);
1275 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1276 int allowMode, String name, String callerPackage) {
1277 final int callingUserId = UserHandle.getUserId(callingUid);
1278 if (callingUserId == userId) {
1282 // Note that we may be accessing mCurrentUserId outside of a lock...
1283 // shouldn't be a big deal, if this is being called outside
1284 // of a locked context there is intrinsically a race with
1285 // the value the caller will receive and someone else changing it.
1286 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1287 // we will switch to the calling user if access to the current user fails.
1288 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1290 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1291 final boolean allow;
1292 if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1293 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1294 // If the caller has this permission, they always pass go. And collect $200.
1296 } else if (allowMode == ALLOW_FULL_ONLY) {
1297 // We require full access, sucks to be you.
1299 } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1300 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1301 // If the caller does not have either permission, they are always doomed.
1303 } else if (allowMode == ALLOW_NON_FULL) {
1304 // We are blanket allowing non-full access, you lucky caller!
1306 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1307 // We may or may not allow this depending on whether the two users are
1308 // in the same profile.
1309 allow = isSameProfileGroup(callingUserId, targetUserId);
1311 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1314 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1315 // In this case, they would like to just execute as their
1316 // owner user instead of failing.
1317 targetUserId = callingUserId;
1319 StringBuilder builder = new StringBuilder(128);
1320 builder.append("Permission Denial: ");
1321 builder.append(name);
1322 if (callerPackage != null) {
1323 builder.append(" from ");
1324 builder.append(callerPackage);
1326 builder.append(" asks to run as user ");
1327 builder.append(userId);
1328 builder.append(" but is calling from user ");
1329 builder.append(UserHandle.getUserId(callingUid));
1330 builder.append("; this requires ");
1331 builder.append(INTERACT_ACROSS_USERS_FULL);
1332 if (allowMode != ALLOW_FULL_ONLY) {
1333 builder.append(" or ");
1334 builder.append(INTERACT_ACROSS_USERS);
1336 String msg = builder.toString();
1338 throw new SecurityException(msg);
1342 if (!allowAll && targetUserId < 0) {
1343 throw new IllegalArgumentException(
1344 "Call does not support special user #" + targetUserId);
1346 // Check shell permission
1347 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1348 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1349 throw new SecurityException("Shell does not have permission to access user "
1350 + targetUserId + "\n " + Debug.getCallers(3));
1353 return targetUserId;
1356 int unsafeConvertIncomingUserLocked(int userId) {
1357 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1358 ? getCurrentUserIdLocked(): userId;
1361 void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
1362 Preconditions.checkNotNull(name, "Observer name cannot be null");
1363 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1364 != PackageManager.PERMISSION_GRANTED) {
1365 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1366 + Binder.getCallingPid()
1367 + ", uid=" + Binder.getCallingUid()
1368 + " requires " + INTERACT_ACROSS_USERS_FULL;
1370 throw new SecurityException(msg);
1372 mUserSwitchObservers.register(observer, name);
1375 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1376 mUserSwitchObservers.unregister(observer);
1379 UserState getStartedUserStateLocked(int userId) {
1380 return mStartedUsers.get(userId);
1383 boolean hasStartedUserState(int userId) {
1384 return mStartedUsers.get(userId) != null;
1387 private void updateStartedUserArrayLocked() {
1389 for (int i = 0; i < mStartedUsers.size(); i++) {
1390 UserState uss = mStartedUsers.valueAt(i);
1391 // This list does not include stopping users.
1392 if (uss.state != UserState.STATE_STOPPING
1393 && uss.state != UserState.STATE_SHUTDOWN) {
1397 mStartedUserArray = new int[num];
1399 for (int i = 0; i < mStartedUsers.size(); i++) {
1400 UserState uss = mStartedUsers.valueAt(i);
1401 if (uss.state != UserState.STATE_STOPPING
1402 && uss.state != UserState.STATE_SHUTDOWN) {
1403 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1408 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1409 for (int i = 0; i < mStartedUsers.size(); i++) {
1410 UserState uss = mStartedUsers.valueAt(i);
1411 finishUserBoot(uss, resultTo);
1415 void onSystemReady() {
1416 updateCurrentProfileIdsLocked();
1420 * Refreshes the list of users related to the current user when either a
1421 * user switch happens or when a new related user is started in the
1424 private void updateCurrentProfileIdsLocked() {
1425 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(mCurrentUserId,
1426 false /* enabledOnly */);
1427 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1428 for (int i = 0; i < currentProfileIds.length; i++) {
1429 currentProfileIds[i] = profiles.get(i).id;
1431 mCurrentProfileIds = currentProfileIds;
1433 synchronized (mUserProfileGroupIdsSelfLocked) {
1434 mUserProfileGroupIdsSelfLocked.clear();
1435 final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
1436 for (int i = 0; i < users.size(); i++) {
1437 UserInfo user = users.get(i);
1438 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1439 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1445 int[] getStartedUserArrayLocked() {
1446 return mStartedUserArray;
1449 boolean isUserStoppingOrShuttingDownLocked(int userId) {
1450 UserState state = getStartedUserStateLocked(userId);
1451 if (state == null) {
1454 return state.state == UserState.STATE_STOPPING
1455 || state.state == UserState.STATE_SHUTDOWN;
1458 boolean isUserRunningLocked(int userId, int flags) {
1459 UserState state = getStartedUserStateLocked(userId);
1460 if (state == null) {
1463 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1466 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1467 switch (state.state) {
1468 case UserState.STATE_BOOTING:
1469 case UserState.STATE_RUNNING_LOCKED:
1475 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1476 switch (state.state) {
1477 case UserState.STATE_RUNNING_UNLOCKING:
1478 case UserState.STATE_RUNNING_UNLOCKED:
1484 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1485 switch (state.state) {
1486 case UserState.STATE_RUNNING_UNLOCKED:
1493 // One way or another, we're running!
1497 UserInfo getCurrentUser() {
1498 if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
1499 != PackageManager.PERMISSION_GRANTED) && (
1500 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1501 != PackageManager.PERMISSION_GRANTED)) {
1502 String msg = "Permission Denial: getCurrentUser() from pid="
1503 + Binder.getCallingPid()
1504 + ", uid=" + Binder.getCallingUid()
1505 + " requires " + INTERACT_ACROSS_USERS;
1507 throw new SecurityException(msg);
1509 synchronized (mLock) {
1510 return getCurrentUserLocked();
1514 UserInfo getCurrentUserLocked() {
1515 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1516 return getUserInfo(userId);
1519 int getCurrentOrTargetUserIdLocked() {
1520 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1523 int getCurrentUserIdLocked() {
1524 return mCurrentUserId;
1527 private boolean isCurrentUserLocked(int userId) {
1528 return userId == getCurrentOrTargetUserIdLocked();
1531 int setTargetUserIdLocked(int targetUserId) {
1532 return mTargetUserId = targetUserId;
1536 UserManagerService ums = mInjector.getUserManager();
1537 return ums != null ? ums.getUserIds() : new int[] { 0 };
1540 UserInfo getUserInfo(int userId) {
1541 return mInjector.getUserManager().getUserInfo(userId);
1544 int[] getUserIds() {
1545 return mInjector.getUserManager().getUserIds();
1548 boolean exists(int userId) {
1549 return mInjector.getUserManager().exists(userId);
1552 boolean hasUserRestriction(String restriction, int userId) {
1553 return mInjector.getUserManager().hasUserRestriction(restriction, userId);
1556 Set<Integer> getProfileIds(int userId) {
1557 Set<Integer> userIds = new HashSet<>();
1558 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(userId,
1559 false /* enabledOnly */);
1560 for (UserInfo user : profiles) {
1561 userIds.add(user.id);
1566 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1567 if (callingUserId == targetUserId) {
1570 synchronized (mUserProfileGroupIdsSelfLocked) {
1571 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1572 UserInfo.NO_PROFILE_GROUP_ID);
1573 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1574 UserInfo.NO_PROFILE_GROUP_ID);
1575 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1576 && callingProfile == targetProfile;
1580 boolean isCurrentProfileLocked(int userId) {
1581 return ArrayUtils.contains(mCurrentProfileIds, userId);
1584 int[] getCurrentProfileIdsLocked() {
1585 return mCurrentProfileIds;
1589 * Returns whether the given user requires credential entry at this time. This is used to
1590 * intercept activity launches for work apps when the Work Challenge is present.
1592 boolean shouldConfirmCredentials(int userId) {
1593 synchronized (mLock) {
1594 if (mStartedUsers.get(userId) == null) {
1598 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1601 final KeyguardManager km = mInjector.getKeyguardManager();
1602 return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
1605 boolean isLockScreenDisabled(@UserIdInt int userId) {
1606 return mLockPatternUtils.isLockScreenDisabled(userId);
1609 void dump(PrintWriter pw, boolean dumpAll) {
1610 pw.println(" mStartedUsers:");
1611 for (int i = 0; i < mStartedUsers.size(); i++) {
1612 UserState uss = mStartedUsers.valueAt(i);
1613 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1614 pw.print(": "); uss.dump("", pw);
1616 pw.print(" mStartedUserArray: [");
1617 for (int i = 0; i < mStartedUserArray.length; i++) {
1618 if (i > 0) pw.print(", ");
1619 pw.print(mStartedUserArray[i]);
1622 pw.print(" mUserLru: [");
1623 for (int i = 0; i < mUserLru.size(); i++) {
1624 if (i > 0) pw.print(", ");
1625 pw.print(mUserLru.get(i));
1629 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1631 synchronized (mUserProfileGroupIdsSelfLocked) {
1632 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1633 pw.println(" mUserProfileGroupIds:");
1634 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1635 pw.print(" User #");
1636 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1637 pw.print(" -> profile #");
1638 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1645 static class Injector {
1646 private final ActivityManagerService mService;
1647 private UserManagerService mUserManager;
1648 private UserManagerInternal mUserManagerInternal;
1650 Injector(ActivityManagerService service) {
1654 protected Object getLock() {
1658 protected Handler getHandler() {
1659 return mService.mHandler;
1662 protected Context getContext() {
1663 return mService.mContext;
1666 protected LockPatternUtils getLockPatternUtils() {
1667 return new LockPatternUtils(getContext());
1670 protected int broadcastIntentLocked(Intent intent, String resolvedType,
1671 IIntentReceiver resultTo, int resultCode, String resultData,
1672 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
1673 boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) {
1674 return mService.broadcastIntentLocked(null, null, intent, resolvedType, resultTo,
1675 resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions,
1676 ordered, sticky, callingPid, callingUid, userId);
1679 int checkCallingPermission(String permission) {
1680 return mService.checkCallingPermission(permission);
1683 WindowManagerService getWindowManager() {
1684 return mService.mWindowManager;
1686 void activityManagerOnUserStopped(int userId) {
1687 mService.onUserStoppedLocked(userId);
1690 void systemServiceManagerCleanupUser(int userId) {
1691 mService.mSystemServiceManager.cleanupUser(userId);
1694 protected UserManagerService getUserManager() {
1695 if (mUserManager == null) {
1696 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
1697 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
1699 return mUserManager;
1702 UserManagerInternal getUserManagerInternal() {
1703 if (mUserManagerInternal == null) {
1704 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1706 return mUserManagerInternal;
1709 KeyguardManager getKeyguardManager() {
1710 return mService.mContext.getSystemService(KeyguardManager.class);
1713 void batteryStatsServiceNoteEvent(int code, String name, int uid) {
1714 mService.mBatteryStatsService.noteEvent(code, name, uid);
1717 void systemServiceManagerStopUser(int userId) {
1718 mService.mSystemServiceManager.stopUser(userId);
1721 boolean isRuntimeRestarted() {
1722 return mService.mSystemServiceManager.isRuntimeRestarted();
1725 boolean isFirstBootOrUpgrade() {
1726 IPackageManager pm = AppGlobals.getPackageManager();
1728 return pm.isFirstBoot() || pm.isUpgrade();
1729 } catch (RemoteException e) {
1730 throw e.rethrowFromSystemServer();
1734 void sendPreBootBroadcast(int userId, boolean quiet, final Runnable onFinish) {
1735 new PreBootBroadcaster(mService, userId, null, quiet) {
1737 public void onFinished() {
1743 void activityManagerForceStopPackageLocked(int userId, String reason) {
1744 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
1748 int checkComponentPermission(String permission, int pid, int uid, int owningUid,
1750 return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
1753 void startHomeActivityLocked(int userId, String reason) {
1754 mService.startHomeActivityLocked(userId, reason);
1757 void updateUserConfigurationLocked() {
1758 mService.updateUserConfigurationLocked();
1761 void clearBroadcastQueueForUserLocked(int userId) {
1762 mService.clearBroadcastQueueForUserLocked(userId);
1765 void enforceShellRestriction(String restriction, int userId) {
1766 mService.enforceShellRestriction(restriction, userId);
1769 void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser) {
1770 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromUser, toUser,
1771 true /* above system */);
1775 ActivityStackSupervisor getActivityStackSupervisor() {
1776 return mService.mStackSupervisor;