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.d(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, null, 0, null, null,
455 new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
456 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
460 int restartUser(final int userId, final boolean foreground) {
461 return stopUser(userId, /* force */ true, new IStopUserCallback.Stub() {
463 public void userStopped(final int userId) {
464 // Post to the same handler that this callback is called from to ensure the user
465 // cleanup is complete before restarting.
466 mHandler.post(() -> startUser(userId, foreground));
469 public void userStopAborted(final int userId) {}
473 int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
474 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
475 != PackageManager.PERMISSION_GRANTED) {
476 String msg = "Permission Denial: switchUser() from pid="
477 + Binder.getCallingPid()
478 + ", uid=" + Binder.getCallingUid()
479 + " requires " + INTERACT_ACROSS_USERS_FULL;
481 throw new SecurityException(msg);
483 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
484 throw new IllegalArgumentException("Can't stop system user " + userId);
486 mInjector.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
487 synchronized (mLock) {
488 return stopUsersLocked(userId, force, callback);
493 * Stops the user along with its related users. The method calls
494 * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
496 private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
497 if (userId == UserHandle.USER_SYSTEM) {
498 return USER_OP_ERROR_IS_SYSTEM;
500 if (isCurrentUserLocked(userId)) {
501 return USER_OP_IS_CURRENT;
503 int[] usersToStop = getUsersToStopLocked(userId);
504 // If one of related users is system or current, no related users should be stopped
505 for (int i = 0; i < usersToStop.length; i++) {
506 int relatedUserId = usersToStop[i];
507 if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
508 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
510 // We still need to stop the requested user if it's a force stop.
513 "Force stop user " + userId + ". Related users will not be stopped");
514 stopSingleUserLocked(userId, callback);
515 return USER_OP_SUCCESS;
517 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
520 if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
521 for (int userIdToStop : usersToStop) {
522 stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
524 return USER_OP_SUCCESS;
527 private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
528 if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
529 final UserState uss = mStartedUsers.get(userId);
531 // User is not started, nothing to do... but we do need to
532 // callback if requested.
533 if (callback != null) {
534 mHandler.post(new Runnable() {
538 callback.userStopped(userId);
539 } catch (RemoteException e) {
547 if (callback != null) {
548 uss.mStopCallbacks.add(callback);
551 if (uss.state != UserState.STATE_STOPPING
552 && uss.state != UserState.STATE_SHUTDOWN) {
553 uss.setState(UserState.STATE_STOPPING);
554 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
555 updateStartedUserArrayLocked();
557 long ident = Binder.clearCallingIdentity();
559 // We are going to broadcast ACTION_USER_STOPPING and then
560 // once that is done send a final ACTION_SHUTDOWN and then
562 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
563 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
564 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
565 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
566 // This is the result receiver for the initial stopping broadcast.
567 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
569 public void performReceive(Intent intent, int resultCode, String data,
570 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
571 mHandler.post(new Runnable() {
574 finishUserStopping(userId, uss);
579 // Clear broadcast queue for the user to avoid delivering stale broadcasts
580 mInjector.clearBroadcastQueueForUserLocked(userId);
582 mInjector.broadcastIntentLocked(stoppingIntent,
583 null, stoppingReceiver, 0, null, null,
584 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
585 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
587 Binder.restoreCallingIdentity(ident);
592 void finishUserStopping(final int userId, final UserState uss) {
594 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
595 // This is the result receiver for the final shutdown broadcast.
596 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
598 public void performReceive(Intent intent, int resultCode, String data,
599 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
600 mHandler.post(new Runnable() {
603 finishUserStopped(uss);
609 synchronized (mLock) {
610 if (uss.state != UserState.STATE_STOPPING) {
611 // Whoops, we are being started back up. Abort, abort!
614 uss.setState(UserState.STATE_SHUTDOWN);
616 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
618 mInjector.batteryStatsServiceNoteEvent(
619 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
620 Integer.toString(userId), userId);
621 mInjector.systemServiceManagerStopUser(userId);
623 synchronized (mLock) {
624 mInjector.broadcastIntentLocked(shutdownIntent,
625 null, shutdownReceiver, 0, null, null, null,
626 AppOpsManager.OP_NONE,
627 null, true, false, MY_PID, SYSTEM_UID, userId);
631 void finishUserStopped(UserState uss) {
632 final int userId = uss.mHandle.getIdentifier();
634 ArrayList<IStopUserCallback> callbacks;
635 synchronized (mLock) {
636 callbacks = new ArrayList<>(uss.mStopCallbacks);
637 if (mStartedUsers.get(userId) != uss) {
639 } else if (uss.state != UserState.STATE_SHUTDOWN) {
643 // User can no longer run.
644 mStartedUsers.remove(userId);
645 mInjector.getUserManagerInternal().removeUserState(userId);
646 mUserLru.remove(Integer.valueOf(userId));
647 updateStartedUserArrayLocked();
649 mInjector.activityManagerOnUserStopped(userId);
650 // Clean up all state and processes associated with the user.
651 // Kill all the processes for the user.
652 forceStopUserLocked(userId, "finish user");
656 for (int i = 0; i < callbacks.size(); i++) {
658 if (stopped) callbacks.get(i).userStopped(userId);
659 else callbacks.get(i).userStopAborted(userId);
660 } catch (RemoteException e) {
665 // Evict the user's credential encryption key
667 getStorageManager().lockUserKey(userId);
668 } catch (RemoteException re) {
669 throw re.rethrowAsRuntimeException();
671 mInjector.systemServiceManagerCleanupUser(userId);
672 synchronized (mLock) {
673 mInjector.getActivityStackSupervisor().removeUserLocked(userId);
675 // Remove the user if it is ephemeral.
676 if (getUserInfo(userId).isEphemeral()) {
677 mInjector.getUserManager().removeUser(userId);
683 * Determines the list of users that should be stopped together with the specified
684 * {@code userId}. The returned list includes {@code userId}.
686 private @NonNull int[] getUsersToStopLocked(int userId) {
687 int startedUsersSize = mStartedUsers.size();
688 IntArray userIds = new IntArray();
690 synchronized (mUserProfileGroupIdsSelfLocked) {
691 int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
692 UserInfo.NO_PROFILE_GROUP_ID);
693 for (int i = 0; i < startedUsersSize; i++) {
694 UserState uss = mStartedUsers.valueAt(i);
695 int startedUserId = uss.mHandle.getIdentifier();
696 // Skip unrelated users (profileGroupId mismatch)
697 int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
698 UserInfo.NO_PROFILE_GROUP_ID);
699 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
700 && (userGroupId == startedUserGroupId);
701 // userId has already been added
702 boolean sameUserId = startedUserId == userId;
703 if (!sameGroup || sameUserId) {
706 userIds.add(startedUserId);
709 return userIds.toArray();
712 private void forceStopUserLocked(int userId, String reason) {
713 mInjector.activityManagerForceStopPackageLocked(userId, reason);
714 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
715 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
716 | Intent.FLAG_RECEIVER_FOREGROUND);
717 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
718 mInjector.broadcastIntentLocked(intent,
719 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
720 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
724 * Stops the guest or ephemeral user if it has gone to the background.
726 private void stopGuestOrEphemeralUserIfBackground() {
727 synchronized (mLock) {
728 final int num = mUserLru.size();
729 for (int i = 0; i < num; i++) {
730 Integer oldUserId = mUserLru.get(i);
731 UserState oldUss = mStartedUsers.get(oldUserId);
732 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
733 || oldUss.state == UserState.STATE_STOPPING
734 || oldUss.state == UserState.STATE_SHUTDOWN) {
737 UserInfo userInfo = getUserInfo(oldUserId);
738 if (userInfo.isEphemeral()) {
739 LocalServices.getService(UserManagerInternal.class)
740 .onEphemeralUserStop(oldUserId);
742 if (userInfo.isGuest() || userInfo.isEphemeral()) {
743 // This is a user to be stopped.
744 stopUsersLocked(oldUserId, true, null);
751 void startProfilesLocked() {
752 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
753 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
754 mCurrentUserId, false /* enabledOnly */);
755 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
756 for (UserInfo user : profiles) {
757 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
758 && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
759 profilesToStart.add(user);
762 final int profilesToStartSize = profilesToStart.size();
764 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
765 startUser(profilesToStart.get(i).id, /* foreground= */ false);
767 if (i < profilesToStartSize) {
768 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
772 private IStorageManager getStorageManager() {
773 return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
777 * Start user, if its not already running.
778 * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
779 * When starting the user, multiple intents will be broadcast in the following order:</p>
781 * <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
782 * <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
783 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
784 * <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
785 * user and all profiles of this user. Sent only if {@code foreground} parameter is true
786 * <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
787 * Sent only if {@code foreground} parameter is true
788 * <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
790 * <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
792 * <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
793 * <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
794 * new user. Sent only when the user is booting after a system update.
795 * <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
796 * new user. Sent only the first time a user is starting.
797 * <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
798 * user. Indicates that the user has finished booting.
801 * @param userId ID of the user to start
802 * @param foreground true if user should be brought to the foreground
803 * @return true if the user has been successfully started
805 boolean startUser(final int userId, final boolean foreground) {
806 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
807 != PackageManager.PERMISSION_GRANTED) {
808 String msg = "Permission Denial: switchUser() from pid="
809 + Binder.getCallingPid()
810 + ", uid=" + Binder.getCallingUid()
811 + " requires " + INTERACT_ACROSS_USERS_FULL;
813 throw new SecurityException(msg);
816 Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
818 final long ident = Binder.clearCallingIdentity();
820 synchronized (mLock) {
821 final int oldUserId = mCurrentUserId;
822 if (oldUserId == userId) {
827 mInjector.getActivityStackSupervisor().setLockTaskModeLocked(
828 null, ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
831 final UserInfo userInfo = getUserInfo(userId);
832 if (userInfo == null) {
833 Slog.w(TAG, "No user info for user #" + userId);
836 if (foreground && userInfo.isManagedProfile()) {
837 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
841 if (foreground && mUserSwitchUiEnabled) {
842 mInjector.getWindowManager().startFreezingScreen(
843 R.anim.screen_user_exit, R.anim.screen_user_enter);
846 boolean needStart = false;
848 // If the user we are switching to is not currently started, then
849 // we need to start it now.
850 if (mStartedUsers.get(userId) == null) {
851 UserState userState = new UserState(UserHandle.of(userId));
852 mStartedUsers.put(userId, userState);
853 mInjector.getUserManagerInternal().setUserState(userId, userState.state);
854 updateStartedUserArrayLocked();
858 final UserState uss = mStartedUsers.get(userId);
859 final Integer userIdInt = userId;
860 mUserLru.remove(userIdInt);
861 mUserLru.add(userIdInt);
864 mCurrentUserId = userId;
865 mInjector.updateUserConfigurationLocked();
866 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
867 updateCurrentProfileIdsLocked();
868 mInjector.getWindowManager().setCurrentUser(userId, mCurrentProfileIds);
869 // Once the internal notion of the active user has switched, we lock the device
870 // with the option to show the user switcher on the keyguard.
871 if (mUserSwitchUiEnabled) {
872 mInjector.getWindowManager().setSwitchingUser(true);
873 mInjector.getWindowManager().lockNow(null);
876 final Integer currentUserIdInt = mCurrentUserId;
877 updateCurrentProfileIdsLocked();
878 mInjector.getWindowManager().setCurrentProfileIds(mCurrentProfileIds);
879 mUserLru.remove(currentUserIdInt);
880 mUserLru.add(currentUserIdInt);
883 // Make sure user is in the started state. If it is currently
884 // stopping, we need to knock that off.
885 if (uss.state == UserState.STATE_STOPPING) {
886 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
887 // so we can just fairly silently bring the user back from
889 uss.setState(uss.lastState);
890 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
891 updateStartedUserArrayLocked();
893 } else if (uss.state == UserState.STATE_SHUTDOWN) {
894 // This means ACTION_SHUTDOWN has been sent, so we will
895 // need to treat this as a new boot of the user.
896 uss.setState(UserState.STATE_BOOTING);
897 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
898 updateStartedUserArrayLocked();
902 if (uss.state == UserState.STATE_BOOTING) {
903 // Give user manager a chance to propagate user restrictions
904 // to other services and prepare app storage
905 mInjector.getUserManager().onBeforeStartUser(userId);
907 // Booting up a new user, need to tell system services about it.
908 // Note that this is on the same handler as scheduling of broadcasts,
909 // which is important because it needs to go first.
910 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
914 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
916 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
917 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
918 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
919 oldUserId, userId, uss));
920 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
921 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
925 // Send USER_STARTED broadcast
926 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
927 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
928 | Intent.FLAG_RECEIVER_FOREGROUND);
929 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
930 mInjector.broadcastIntentLocked(intent,
931 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
932 null, false, false, MY_PID, SYSTEM_UID, userId);
936 moveUserToForegroundLocked(uss, oldUserId, userId);
942 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
943 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
944 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
945 mInjector.broadcastIntentLocked(intent,
946 null, new IIntentReceiver.Stub() {
948 public void performReceive(Intent intent, int resultCode,
949 String data, Bundle extras, boolean ordered, boolean sticky,
950 int sendingUser) throws RemoteException {
953 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
954 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
958 Binder.restoreCallingIdentity(ident);
965 * Start user, if its not already running, and bring it to foreground.
967 void startUserInForeground(final int targetUserId) {
968 boolean success = startUser(targetUserId, /* foreground */ true);
970 mInjector.getWindowManager().setSwitchingUser(false);
974 boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
975 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
976 != PackageManager.PERMISSION_GRANTED) {
977 String msg = "Permission Denial: unlockUser() from pid="
978 + Binder.getCallingPid()
979 + ", uid=" + Binder.getCallingUid()
980 + " requires " + INTERACT_ACROSS_USERS_FULL;
982 throw new SecurityException(msg);
985 final long binderToken = Binder.clearCallingIdentity();
987 return unlockUserCleared(userId, token, secret, listener);
989 Binder.restoreCallingIdentity(binderToken);
994 * Attempt to unlock user without a credential token. This typically
995 * succeeds when the device doesn't have credential-encrypted storage, or
996 * when the the credential-encrypted storage isn't tied to a user-provided
999 boolean maybeUnlockUser(final int userId) {
1000 // Try unlocking storage using empty token
1001 return unlockUserCleared(userId, null, null, null);
1004 private static void notifyFinished(int userId, IProgressListener listener) {
1005 if (listener == null) return;
1007 listener.onFinished(userId, null);
1008 } catch (RemoteException ignored) {
1012 boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
1013 IProgressListener listener) {
1015 synchronized (mLock) {
1016 // TODO Move this block outside of synchronized if it causes lock contention
1017 if (!StorageManager.isUserKeyUnlocked(userId)) {
1018 final UserInfo userInfo = getUserInfo(userId);
1019 final IStorageManager storageManager = getStorageManager();
1021 // We always want to unlock user storage, even user is not started yet
1022 storageManager.unlockUserKey(userId, userInfo.serialNumber, token, secret);
1023 } catch (RemoteException | RuntimeException e) {
1024 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
1027 // Bail if user isn't actually running, otherwise register the given
1028 // listener to watch for unlock progress
1029 uss = mStartedUsers.get(userId);
1031 notifyFinished(userId, listener);
1034 uss.mUnlockProgress.addListener(listener);
1035 uss.tokenProvided = (token != null);
1039 finishUserUnlocking(uss);
1041 final ArraySet<Integer> childProfilesToUnlock = new ArraySet<>();
1042 synchronized (mLock) {
1044 // We just unlocked a user, so let's now attempt to unlock any
1045 // managed profiles under that user.
1046 for (int i = 0; i < mStartedUsers.size(); i++) {
1047 final int testUserId = mStartedUsers.keyAt(i);
1048 final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
1049 if (parent != null && parent.id == userId && testUserId != userId) {
1050 Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
1051 + "): attempting unlock because parent was just unlocked");
1052 childProfilesToUnlock.add(testUserId);
1057 final int size = childProfilesToUnlock.size();
1058 for (int i = 0; i < size; i++) {
1059 maybeUnlockUser(childProfilesToUnlock.valueAt(i));
1065 void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
1066 // The dialog will show and then initiate the user switch by calling startUserInForeground
1067 mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second);
1070 void dispatchForegroundProfileChanged(int userId) {
1071 final int observerCount = mUserSwitchObservers.beginBroadcast();
1072 for (int i = 0; i < observerCount; i++) {
1074 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1075 } catch (RemoteException e) {
1079 mUserSwitchObservers.finishBroadcast();
1082 /** Called on handler thread */
1083 void dispatchUserSwitchComplete(int userId) {
1084 mInjector.getWindowManager().setSwitchingUser(false);
1085 final int observerCount = mUserSwitchObservers.beginBroadcast();
1086 for (int i = 0; i < observerCount; i++) {
1088 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1089 } catch (RemoteException e) {
1092 mUserSwitchObservers.finishBroadcast();
1095 void dispatchLockedBootComplete(int userId) {
1096 final int observerCount = mUserSwitchObservers.beginBroadcast();
1097 for (int i = 0; i < observerCount; i++) {
1099 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
1100 } catch (RemoteException e) {
1104 mUserSwitchObservers.finishBroadcast();
1107 private void stopBackgroundUsersIfEnforced(int oldUserId) {
1108 // Never stop system user
1109 if (oldUserId == UserHandle.USER_SYSTEM) {
1112 // For now, only check for user restriction. Additional checks can be added here
1113 boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1115 if (!disallowRunInBg) {
1118 synchronized (mLock) {
1119 if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1120 + " and related users");
1121 stopUsersLocked(oldUserId, false, null);
1125 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1126 synchronized (mLock) {
1127 Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
1128 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1132 void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1133 Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
1134 final int observerCount = mUserSwitchObservers.beginBroadcast();
1135 if (observerCount > 0) {
1136 final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
1137 synchronized (mLock) {
1138 uss.switching = true;
1139 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
1141 final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
1142 final long dispatchStartedTime = SystemClock.elapsedRealtime();
1143 for (int i = 0; i < observerCount; i++) {
1145 // Prepend with unique prefix to guarantee that keys are unique
1146 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
1147 synchronized (mLock) {
1148 curWaitingUserSwitchCallbacks.add(name);
1150 final IRemoteCallback callback = new IRemoteCallback.Stub() {
1152 public void sendResult(Bundle data) throws RemoteException {
1153 synchronized (mLock) {
1154 long delay = SystemClock.elapsedRealtime() - dispatchStartedTime;
1155 if (delay > USER_SWITCH_TIMEOUT) {
1156 Slog.wtf(TAG, "User switch timeout: observer " + name
1157 + " sent result after " + delay + " ms");
1159 // Early return if this session is no longer valid
1160 if (curWaitingUserSwitchCallbacks
1161 != mCurWaitingUserSwitchCallbacks) {
1164 curWaitingUserSwitchCallbacks.remove(name);
1165 // Continue switching if all callbacks have been notified
1166 if (waitingCallbacksCount.decrementAndGet() == 0) {
1167 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1172 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
1173 } catch (RemoteException e) {
1177 synchronized (mLock) {
1178 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1181 mUserSwitchObservers.finishBroadcast();
1184 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1185 mCurWaitingUserSwitchCallbacks = null;
1186 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1187 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1188 oldUserId, newUserId, uss));
1191 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1192 Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
1193 if (mUserSwitchUiEnabled) {
1194 synchronized (mLock) {
1195 mInjector.getWindowManager().stopFreezingScreen();
1198 uss.switching = false;
1199 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1200 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1202 stopGuestOrEphemeralUserIfBackground();
1203 stopBackgroundUsersIfEnforced(oldUserId);
1206 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1207 boolean homeInFront =
1208 mInjector.getActivityStackSupervisor().switchUserLocked(newUserId, uss);
1210 mInjector.startHomeActivityLocked(newUserId, "moveUserToForeground");
1212 mInjector.getActivityStackSupervisor().resumeFocusedStackTopActivityLocked();
1214 EventLogTags.writeAmSwitchUser(newUserId);
1215 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1218 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1219 long ident = Binder.clearCallingIdentity();
1222 if (oldUserId >= 0) {
1223 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1224 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
1225 int count = profiles.size();
1226 for (int i = 0; i < count; i++) {
1227 int profileUserId = profiles.get(i).id;
1228 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1229 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1230 | Intent.FLAG_RECEIVER_FOREGROUND);
1231 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1232 mInjector.broadcastIntentLocked(intent,
1233 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1234 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1237 if (newUserId >= 0) {
1238 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1239 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
1240 int count = profiles.size();
1241 for (int i = 0; i < count; i++) {
1242 int profileUserId = profiles.get(i).id;
1243 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1244 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1245 | Intent.FLAG_RECEIVER_FOREGROUND);
1246 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1247 mInjector.broadcastIntentLocked(intent,
1248 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1249 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1251 intent = new Intent(Intent.ACTION_USER_SWITCHED);
1252 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1253 | Intent.FLAG_RECEIVER_FOREGROUND);
1254 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1255 mInjector.broadcastIntentLocked(intent,
1256 null, null, 0, null, null,
1257 new String[] {android.Manifest.permission.MANAGE_USERS},
1258 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1259 UserHandle.USER_ALL);
1262 Binder.restoreCallingIdentity(ident);
1267 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1268 int allowMode, String name, String callerPackage) {
1269 final int callingUserId = UserHandle.getUserId(callingUid);
1270 if (callingUserId == userId) {
1274 // Note that we may be accessing mCurrentUserId outside of a lock...
1275 // shouldn't be a big deal, if this is being called outside
1276 // of a locked context there is intrinsically a race with
1277 // the value the caller will receive and someone else changing it.
1278 // We assume that USER_CURRENT_OR_SELF will use the current user; later
1279 // we will switch to the calling user if access to the current user fails.
1280 int targetUserId = unsafeConvertIncomingUserLocked(userId);
1282 if (callingUid != 0 && callingUid != SYSTEM_UID) {
1283 final boolean allow;
1284 if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1285 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1286 // If the caller has this permission, they always pass go. And collect $200.
1288 } else if (allowMode == ALLOW_FULL_ONLY) {
1289 // We require full access, sucks to be you.
1291 } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1292 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1293 // If the caller does not have either permission, they are always doomed.
1295 } else if (allowMode == ALLOW_NON_FULL) {
1296 // We are blanket allowing non-full access, you lucky caller!
1298 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1299 // We may or may not allow this depending on whether the two users are
1300 // in the same profile.
1301 allow = isSameProfileGroup(callingUserId, targetUserId);
1303 throw new IllegalArgumentException("Unknown mode: " + allowMode);
1306 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1307 // In this case, they would like to just execute as their
1308 // owner user instead of failing.
1309 targetUserId = callingUserId;
1311 StringBuilder builder = new StringBuilder(128);
1312 builder.append("Permission Denial: ");
1313 builder.append(name);
1314 if (callerPackage != null) {
1315 builder.append(" from ");
1316 builder.append(callerPackage);
1318 builder.append(" asks to run as user ");
1319 builder.append(userId);
1320 builder.append(" but is calling from user ");
1321 builder.append(UserHandle.getUserId(callingUid));
1322 builder.append("; this requires ");
1323 builder.append(INTERACT_ACROSS_USERS_FULL);
1324 if (allowMode != ALLOW_FULL_ONLY) {
1325 builder.append(" or ");
1326 builder.append(INTERACT_ACROSS_USERS);
1328 String msg = builder.toString();
1330 throw new SecurityException(msg);
1334 if (!allowAll && targetUserId < 0) {
1335 throw new IllegalArgumentException(
1336 "Call does not support special user #" + targetUserId);
1338 // Check shell permission
1339 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1340 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1341 throw new SecurityException("Shell does not have permission to access user "
1342 + targetUserId + "\n " + Debug.getCallers(3));
1345 return targetUserId;
1348 int unsafeConvertIncomingUserLocked(int userId) {
1349 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1350 ? getCurrentUserIdLocked(): userId;
1353 void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
1354 Preconditions.checkNotNull(name, "Observer name cannot be null");
1355 if (mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1356 != PackageManager.PERMISSION_GRANTED) {
1357 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1358 + Binder.getCallingPid()
1359 + ", uid=" + Binder.getCallingUid()
1360 + " requires " + INTERACT_ACROSS_USERS_FULL;
1362 throw new SecurityException(msg);
1364 mUserSwitchObservers.register(observer, name);
1367 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1368 mUserSwitchObservers.unregister(observer);
1371 UserState getStartedUserStateLocked(int userId) {
1372 return mStartedUsers.get(userId);
1375 boolean hasStartedUserState(int userId) {
1376 return mStartedUsers.get(userId) != null;
1379 private void updateStartedUserArrayLocked() {
1381 for (int i = 0; i < mStartedUsers.size(); i++) {
1382 UserState uss = mStartedUsers.valueAt(i);
1383 // This list does not include stopping users.
1384 if (uss.state != UserState.STATE_STOPPING
1385 && uss.state != UserState.STATE_SHUTDOWN) {
1389 mStartedUserArray = new int[num];
1391 for (int i = 0; i < mStartedUsers.size(); i++) {
1392 UserState uss = mStartedUsers.valueAt(i);
1393 if (uss.state != UserState.STATE_STOPPING
1394 && uss.state != UserState.STATE_SHUTDOWN) {
1395 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1400 void sendBootCompletedLocked(IIntentReceiver resultTo) {
1401 for (int i = 0; i < mStartedUsers.size(); i++) {
1402 UserState uss = mStartedUsers.valueAt(i);
1403 finishUserBoot(uss, resultTo);
1407 void onSystemReady() {
1408 updateCurrentProfileIdsLocked();
1412 * Refreshes the list of users related to the current user when either a
1413 * user switch happens or when a new related user is started in the
1416 private void updateCurrentProfileIdsLocked() {
1417 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(mCurrentUserId,
1418 false /* enabledOnly */);
1419 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1420 for (int i = 0; i < currentProfileIds.length; i++) {
1421 currentProfileIds[i] = profiles.get(i).id;
1423 mCurrentProfileIds = currentProfileIds;
1425 synchronized (mUserProfileGroupIdsSelfLocked) {
1426 mUserProfileGroupIdsSelfLocked.clear();
1427 final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
1428 for (int i = 0; i < users.size(); i++) {
1429 UserInfo user = users.get(i);
1430 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1431 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1437 int[] getStartedUserArrayLocked() {
1438 return mStartedUserArray;
1441 boolean isUserStoppingOrShuttingDownLocked(int userId) {
1442 UserState state = getStartedUserStateLocked(userId);
1443 if (state == null) {
1446 return state.state == UserState.STATE_STOPPING
1447 || state.state == UserState.STATE_SHUTDOWN;
1450 boolean isUserRunningLocked(int userId, int flags) {
1451 UserState state = getStartedUserStateLocked(userId);
1452 if (state == null) {
1455 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1458 if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1459 switch (state.state) {
1460 case UserState.STATE_BOOTING:
1461 case UserState.STATE_RUNNING_LOCKED:
1467 if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1468 switch (state.state) {
1469 case UserState.STATE_RUNNING_UNLOCKING:
1470 case UserState.STATE_RUNNING_UNLOCKED:
1476 if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1477 switch (state.state) {
1478 case UserState.STATE_RUNNING_UNLOCKED:
1485 // One way or another, we're running!
1489 UserInfo getCurrentUser() {
1490 if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
1491 != PackageManager.PERMISSION_GRANTED) && (
1492 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1493 != PackageManager.PERMISSION_GRANTED)) {
1494 String msg = "Permission Denial: getCurrentUser() from pid="
1495 + Binder.getCallingPid()
1496 + ", uid=" + Binder.getCallingUid()
1497 + " requires " + INTERACT_ACROSS_USERS;
1499 throw new SecurityException(msg);
1501 synchronized (mLock) {
1502 return getCurrentUserLocked();
1506 UserInfo getCurrentUserLocked() {
1507 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1508 return getUserInfo(userId);
1511 int getCurrentOrTargetUserIdLocked() {
1512 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1515 int getCurrentUserIdLocked() {
1516 return mCurrentUserId;
1519 private boolean isCurrentUserLocked(int userId) {
1520 return userId == getCurrentOrTargetUserIdLocked();
1523 int setTargetUserIdLocked(int targetUserId) {
1524 return mTargetUserId = targetUserId;
1528 UserManagerService ums = mInjector.getUserManager();
1529 return ums != null ? ums.getUserIds() : new int[] { 0 };
1532 UserInfo getUserInfo(int userId) {
1533 return mInjector.getUserManager().getUserInfo(userId);
1536 int[] getUserIds() {
1537 return mInjector.getUserManager().getUserIds();
1540 boolean exists(int userId) {
1541 return mInjector.getUserManager().exists(userId);
1544 boolean hasUserRestriction(String restriction, int userId) {
1545 return mInjector.getUserManager().hasUserRestriction(restriction, userId);
1548 Set<Integer> getProfileIds(int userId) {
1549 Set<Integer> userIds = new HashSet<>();
1550 final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(userId,
1551 false /* enabledOnly */);
1552 for (UserInfo user : profiles) {
1553 userIds.add(user.id);
1558 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1559 if (callingUserId == targetUserId) {
1562 synchronized (mUserProfileGroupIdsSelfLocked) {
1563 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1564 UserInfo.NO_PROFILE_GROUP_ID);
1565 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1566 UserInfo.NO_PROFILE_GROUP_ID);
1567 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1568 && callingProfile == targetProfile;
1572 boolean isCurrentProfileLocked(int userId) {
1573 return ArrayUtils.contains(mCurrentProfileIds, userId);
1576 int[] getCurrentProfileIdsLocked() {
1577 return mCurrentProfileIds;
1581 * Returns whether the given user requires credential entry at this time. This is used to
1582 * intercept activity launches for work apps when the Work Challenge is present.
1584 boolean shouldConfirmCredentials(int userId) {
1585 synchronized (mLock) {
1586 if (mStartedUsers.get(userId) == null) {
1590 if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1593 final KeyguardManager km = mInjector.getKeyguardManager();
1594 return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
1597 boolean isLockScreenDisabled(@UserIdInt int userId) {
1598 return mLockPatternUtils.isLockScreenDisabled(userId);
1601 void dump(PrintWriter pw, boolean dumpAll) {
1602 pw.println(" mStartedUsers:");
1603 for (int i = 0; i < mStartedUsers.size(); i++) {
1604 UserState uss = mStartedUsers.valueAt(i);
1605 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1606 pw.print(": "); uss.dump("", pw);
1608 pw.print(" mStartedUserArray: [");
1609 for (int i = 0; i < mStartedUserArray.length; i++) {
1610 if (i > 0) pw.print(", ");
1611 pw.print(mStartedUserArray[i]);
1614 pw.print(" mUserLru: [");
1615 for (int i = 0; i < mUserLru.size(); i++) {
1616 if (i > 0) pw.print(", ");
1617 pw.print(mUserLru.get(i));
1621 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1623 synchronized (mUserProfileGroupIdsSelfLocked) {
1624 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1625 pw.println(" mUserProfileGroupIds:");
1626 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1627 pw.print(" User #");
1628 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1629 pw.print(" -> profile #");
1630 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1637 static class Injector {
1638 private final ActivityManagerService mService;
1639 private UserManagerService mUserManager;
1640 private UserManagerInternal mUserManagerInternal;
1642 Injector(ActivityManagerService service) {
1646 protected Object getLock() {
1650 protected Handler getHandler() {
1651 return mService.mHandler;
1654 protected Context getContext() {
1655 return mService.mContext;
1658 protected LockPatternUtils getLockPatternUtils() {
1659 return new LockPatternUtils(getContext());
1662 protected int broadcastIntentLocked(Intent intent, String resolvedType,
1663 IIntentReceiver resultTo, int resultCode, String resultData,
1664 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
1665 boolean ordered, boolean sticky, int callingPid, int callingUid, int userId) {
1666 return mService.broadcastIntentLocked(null, null, intent, resolvedType, resultTo,
1667 resultCode, resultData, resultExtras, requiredPermissions, appOp, bOptions,
1668 ordered, sticky, callingPid, callingUid, userId);
1671 int checkCallingPermission(String permission) {
1672 return mService.checkCallingPermission(permission);
1675 WindowManagerService getWindowManager() {
1676 return mService.mWindowManager;
1678 void activityManagerOnUserStopped(int userId) {
1679 mService.onUserStoppedLocked(userId);
1682 void systemServiceManagerCleanupUser(int userId) {
1683 mService.mSystemServiceManager.cleanupUser(userId);
1686 protected UserManagerService getUserManager() {
1687 if (mUserManager == null) {
1688 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
1689 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
1691 return mUserManager;
1694 UserManagerInternal getUserManagerInternal() {
1695 if (mUserManagerInternal == null) {
1696 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1698 return mUserManagerInternal;
1701 KeyguardManager getKeyguardManager() {
1702 return mService.mContext.getSystemService(KeyguardManager.class);
1705 void batteryStatsServiceNoteEvent(int code, String name, int uid) {
1706 mService.mBatteryStatsService.noteEvent(code, name, uid);
1709 void systemServiceManagerStopUser(int userId) {
1710 mService.mSystemServiceManager.stopUser(userId);
1713 boolean isRuntimeRestarted() {
1714 return mService.mSystemServiceManager.isRuntimeRestarted();
1717 boolean isFirstBootOrUpgrade() {
1718 IPackageManager pm = AppGlobals.getPackageManager();
1720 return pm.isFirstBoot() || pm.isUpgrade();
1721 } catch (RemoteException e) {
1722 throw e.rethrowFromSystemServer();
1726 void sendPreBootBroadcast(int userId, boolean quiet, final Runnable onFinish) {
1727 new PreBootBroadcaster(mService, userId, null, quiet) {
1729 public void onFinished() {
1735 void activityManagerForceStopPackageLocked(int userId, String reason) {
1736 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
1740 int checkComponentPermission(String permission, int pid, int uid, int owningUid,
1742 return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
1745 void startHomeActivityLocked(int userId, String reason) {
1746 mService.startHomeActivityLocked(userId, reason);
1749 void updateUserConfigurationLocked() {
1750 mService.updateUserConfigurationLocked();
1753 void clearBroadcastQueueForUserLocked(int userId) {
1754 mService.clearBroadcastQueueForUserLocked(userId);
1757 void enforceShellRestriction(String restriction, int userId) {
1758 mService.enforceShellRestriction(restriction, userId);
1761 void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser) {
1762 Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromUser, toUser,
1763 true /* above system */);
1767 ActivityStackSupervisor getActivityStackSupervisor() {
1768 return mService.mStackSupervisor;