1 /*
2  * Copyright (C) 2015 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License
15  */
16 
17 package com.android.server.am;
18 
19 import static android.Manifest.permission.INTERACT_ACROSS_PROFILES;
20 import static android.Manifest.permission.INTERACT_ACROSS_USERS;
21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
22 import static android.Manifest.permission.MANAGE_USERS;
23 import static android.app.ActivityManager.STOP_USER_ON_SWITCH_DEFAULT;
24 import static android.app.ActivityManager.STOP_USER_ON_SWITCH_TRUE;
25 import static android.app.ActivityManager.StopUserOnSwitch;
26 import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
27 import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
28 import static android.app.ActivityManager.USER_OP_IS_CURRENT;
29 import static android.app.ActivityManager.USER_OP_SUCCESS;
30 import static android.app.ActivityManagerInternal.ALLOW_FULL_ONLY;
31 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL;
32 import static android.app.ActivityManagerInternal.ALLOW_NON_FULL_IN_PROFILE;
33 import static android.app.ActivityManagerInternal.ALLOW_PROFILES_OR_NON_FULL;
34 import static android.os.PowerWhitelistManager.REASON_BOOT_COMPLETED;
35 import static android.os.PowerWhitelistManager.REASON_LOCKED_BOOT_COMPLETED;
36 import static android.os.PowerWhitelistManager.TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED;
37 import static android.os.Process.SHELL_UID;
38 import static android.os.Process.SYSTEM_UID;
39 
40 import static com.android.internal.util.FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_LOCKED_BOOT_COMPLETED;
41 import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
42 import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
43 import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
44 import static com.android.server.am.ActivityManagerService.MY_PID;
45 import static com.android.server.am.UserState.STATE_BOOTING;
46 import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
47 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
48 import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
49 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_ABORTED;
50 import static com.android.server.pm.UserJourneyLogger.ERROR_CODE_INVALID_SESSION_ID;
51 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_BEGIN;
52 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_FINISH;
53 import static com.android.server.pm.UserJourneyLogger.EVENT_STATE_NONE;
54 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_START;
55 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_STOP;
56 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_SWITCH_FG;
57 import static com.android.server.pm.UserJourneyLogger.USER_JOURNEY_USER_SWITCH_UI;
58 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_UNLOCKED_USER;
59 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_UNLOCKING_USER;
60 import static com.android.server.pm.UserJourneyLogger.USER_LIFECYCLE_EVENT_USER_RUNNING_LOCKED;
61 import static com.android.server.pm.UserManagerInternal.USER_ASSIGNMENT_RESULT_FAILURE;
62 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND;
63 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_BACKGROUND_VISIBLE;
64 import static com.android.server.pm.UserManagerInternal.USER_START_MODE_FOREGROUND;
65 import static com.android.server.pm.UserManagerInternal.userAssignmentResultToString;
66 import static com.android.server.pm.UserManagerInternal.userStartModeToString;
67 
68 import android.annotation.NonNull;
69 import android.annotation.Nullable;
70 import android.annotation.RequiresPermission;
71 import android.annotation.UserIdInt;
72 import android.app.ActivityManager;
73 import android.app.ActivityManagerInternal;
74 import android.app.AppGlobals;
75 import android.app.AppOpsManager;
76 import android.app.BroadcastOptions;
77 import android.app.IStopUserCallback;
78 import android.app.IUserSwitchObserver;
79 import android.app.KeyguardManager;
80 import android.app.usage.UsageEvents;
81 import android.appwidget.AppWidgetManagerInternal;
82 import android.content.Context;
83 import android.content.IIntentReceiver;
84 import android.content.Intent;
85 import android.content.PermissionChecker;
86 import android.content.pm.IPackageManager;
87 import android.content.pm.PackageManager;
88 import android.content.pm.PackagePartitions;
89 import android.content.pm.UserInfo;
90 import android.content.pm.UserProperties;
91 import android.os.BatteryStats;
92 import android.os.Binder;
93 import android.os.Bundle;
94 import android.os.Debug;
95 import android.os.Handler;
96 import android.os.IBinder;
97 import android.os.IProgressListener;
98 import android.os.IRemoteCallback;
99 import android.os.IUserManager;
100 import android.os.Message;
101 import android.os.PowerManagerInternal;
102 import android.os.PowerWhitelistManager;
103 import android.os.Process;
104 import android.os.RemoteCallbackList;
105 import android.os.RemoteException;
106 import android.os.ServiceManager;
107 import android.os.SystemClock;
108 import android.os.SystemProperties;
109 import android.os.Trace;
110 import android.os.UserHandle;
111 import android.os.UserManager;
112 import android.os.storage.IStorageManager;
113 import android.os.storage.StorageManager;
114 import android.text.TextUtils;
115 import android.text.format.DateUtils;
116 import android.util.ArraySet;
117 import android.util.EventLog;
118 import android.util.IntArray;
119 import android.util.Pair;
120 import android.util.SparseArray;
121 import android.util.SparseIntArray;
122 import android.util.proto.ProtoOutputStream;
123 import android.view.Display;
124 
125 import com.android.internal.R;
126 import com.android.internal.annotations.GuardedBy;
127 import com.android.internal.annotations.VisibleForTesting;
128 import com.android.internal.policy.IKeyguardDismissCallback;
129 import com.android.internal.util.ArrayUtils;
130 import com.android.internal.util.FrameworkStatsLog;
131 import com.android.internal.util.ObjectUtils;
132 import com.android.internal.util.Preconditions;
133 import com.android.internal.widget.LockPatternUtils;
134 import com.android.server.FactoryResetter;
135 import com.android.server.FgThread;
136 import com.android.server.LocalServices;
137 import com.android.server.SystemService.UserCompletedEventType;
138 import com.android.server.SystemServiceManager;
139 import com.android.server.am.UserState.KeyEvictedCallback;
140 import com.android.server.pm.UserJourneyLogger;
141 import com.android.server.pm.UserJourneyLogger.UserJourneySession;
142 import com.android.server.pm.UserManagerInternal;
143 import com.android.server.pm.UserManagerInternal.UserLifecycleListener;
144 import com.android.server.pm.UserManagerInternal.UserStartMode;
145 import com.android.server.pm.UserManagerService;
146 import com.android.server.utils.Slogf;
147 import com.android.server.utils.TimingsTraceAndSlog;
148 import com.android.server.wm.ActivityTaskManagerInternal;
149 import com.android.server.wm.WindowManagerService;
150 
151 import java.io.PrintWriter;
152 import java.util.ArrayDeque;
153 import java.util.ArrayList;
154 import java.util.Arrays;
155 import java.util.Iterator;
156 import java.util.List;
157 import java.util.Objects;
158 import java.util.concurrent.atomic.AtomicInteger;
159 import java.util.function.Consumer;
160 
161 /**
162  * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
163  *
164  * <p>This class use {@link #mLock} to synchronize access to internal state. Methods that require
165  * {@link #mLock} to be held should have "LU" suffix in the name.
166  *
167  * <p><strong>Important:</strong> Synchronized code, i.e. one executed inside a synchronized(mLock)
168  * block or inside LU method, should only access internal state of this class or make calls to
169  * other LU methods. Non-LU method calls or calls to external classes are discouraged as they
170  * may cause lock inversion.
171  */
172 class UserController implements Handler.Callback {
173     private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
174 
175     // Amount of time we wait for observers to handle a user switch before
176     // giving up on them and dismissing the user switching dialog.
177     static final int DEFAULT_USER_SWITCH_TIMEOUT_MS = 3 * 1000;
178 
179     /**
180      * Amount of time we wait for an observer to handle a user switch before we log a warning. This
181      * wait time is per observer.
182      */
183     private static final int LONG_USER_SWITCH_OBSERVER_WARNING_TIME_MS = 500;
184 
185     // ActivityManager thread message constants
186     static final int REPORT_USER_SWITCH_MSG = 10;
187     static final int CONTINUE_USER_SWITCH_MSG = 20;
188     static final int USER_SWITCH_TIMEOUT_MSG = 30;
189     static final int START_PROFILES_MSG = 40;
190     static final int USER_START_MSG = 50;
191     static final int USER_CURRENT_MSG = 60;
192     static final int FOREGROUND_PROFILE_CHANGED_MSG = 70;
193     static final int REPORT_USER_SWITCH_COMPLETE_MSG = 80;
194     static final int USER_SWITCH_CALLBACKS_TIMEOUT_MSG = 90;
195     static final int USER_UNLOCK_MSG = 100;
196     static final int USER_UNLOCKED_MSG = 105;
197     static final int REPORT_LOCKED_BOOT_COMPLETE_MSG = 110;
198     static final int START_USER_SWITCH_FG_MSG = 120;
199     static final int COMPLETE_USER_SWITCH_MSG = 130;
200     static final int USER_COMPLETED_EVENT_MSG = 140;
201     static final int SCHEDULED_STOP_BACKGROUND_USER_MSG = 150;
202 
203     private static final int NO_ARG2 = 0;
204 
205     // Message constant to clear {@link UserJourneySession} from {@link mUserIdToUserJourneyMap} if
206     // the user journey, defined in the UserLifecycleJourneyReported atom for statsd, is not
207     // complete within {@link USER_JOURNEY_TIMEOUT}.
208     static final int CLEAR_USER_JOURNEY_SESSION_MSG = 200;
209     // Wait time for completing the user journey. If a user journey is not complete within this
210     // time, the remaining lifecycle events for the journey would not be logged in statsd.
211     // Timeout set for 90 seconds.
212     private static final int USER_JOURNEY_TIMEOUT_MS = 90_000;
213 
214     // UI thread message constants
215     static final int START_USER_SWITCH_UI_MSG = 1000;
216 
217     /**
218      * If a callback wasn't called within USER_SWITCH_CALLBACKS_TIMEOUT_MS after
219      * {@link #getUserSwitchTimeoutMs}, an error is reported. Usually it indicates a problem in the
220      * observer when it never calls back.
221      */
222     private static final int USER_SWITCH_CALLBACKS_TIMEOUT_MS = 5 * 1000;
223 
224     /**
225      * Amount of time waited for
226      * {@link ActivityTaskManagerInternal.ScreenObserver#onKeyguardStateChanged} callbacks to be
227      * called after calling {@link WindowManagerService#lockDeviceNow}.
228      * Otherwise, we should throw a {@link RuntimeException} and never dismiss the
229      * {@link UserSwitchingDialog}.
230      */
231     static final int SHOW_KEYGUARD_TIMEOUT_MS = 20 * 1000;
232 
233     /**
234      * Amount of time waited for {@link WindowManagerService#dismissKeyguard} callbacks to be
235      * called after dismissing the keyguard.
236      * Otherwise, we should move on to dismiss the dialog {@link #dismissUserSwitchDialog}}
237      * and report user switch is complete {@link #REPORT_USER_SWITCH_COMPLETE_MSG}.
238      */
239     private static final int DISMISS_KEYGUARD_TIMEOUT_MS = 2 * 1000;
240 
241     /**
242      * Time after last scheduleOnUserCompletedEvent() call at which USER_COMPLETED_EVENT_MSG will be
243      * scheduled (although it may fire sooner instead).
244      * When it fires, {@link #reportOnUserCompletedEvent} will be processed.
245      */
246     // TODO(b/197344658): Increase to 10s or 15s once we have a switch-UX-is-done invocation too.
247     private static final int USER_COMPLETED_EVENT_DELAY_MS = 5 * 1000;
248 
249     /**
250      * Maximum number of users we allow to be running at a time, including system user.
251      *
252      * <p>This parameter only affects how many background users will be stopped when switching to a
253      * new user. It has no impact on {@link #startUser(int, boolean)} behavior.
254      *
255      * <p>Note: Current and system user (and their related profiles) are never stopped when
256      * switching users. Due to that, the actual number of running users can exceed mMaxRunningUsers
257      // TODO(b/310249114): Strongly consider *not* exempting the SYSTEM user's profile.
258      */
259     @GuardedBy("mLock")
260     private int mMaxRunningUsers;
261 
262     /**
263      * Number of seconds of uptime after a full user enters the background before we attempt
264      * to stop it due to inactivity. Set to -1 to disable scheduling stopping background users.
265      *
266      * Typically set by config_backgroundUserScheduledStopTimeSecs.
267      */
268     private int mBackgroundUserScheduledStopTimeSecs = -1;
269 
270     // Lock for internal state.
271     private final Object mLock = new Object();
272 
273     private final Injector mInjector;
274     private final Handler mHandler;
275     private final Handler mUiHandler;
276 
277     // Holds the current foreground user's id. Use mLock when updating
278     @GuardedBy("mLock")
279     private volatile int mCurrentUserId = UserHandle.USER_SYSTEM;
280     // Holds the target user's id during a user switch. The value of mCurrentUserId will be updated
281     // once target user goes into the foreground. Use mLock when updating
282     @GuardedBy("mLock")
283     private volatile int mTargetUserId = UserHandle.USER_NULL;
284     // If a user switch request comes during an ongoing user switch, it is postponed to the end of
285     // the current switch, and this variable holds those user ids. Use mLock when updating
286     @GuardedBy("mLock")
287     private final ArrayDeque<Integer> mPendingTargetUserIds = new ArrayDeque<>();
288 
289     /**
290      * Which users have been started, so are allowed to run code.
291      */
292     @GuardedBy("mLock")
293     private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
294 
295     /**
296      * LRU list of history of running users, in order of when we last needed to start them.
297      *
298      * Switching to a user will move it towards the end. Attempting to start a user/profile (even
299      * if it was already running) will move it towards the end.
300      *
301      * <p>Guarantees (by the end of startUser):
302      * <li>The current user will always be at the end, even if background users were started
303      * subsequently.
304      * <li>Parents always come later than (but not necessarily adjacent to) their profiles.
305      */
306     @GuardedBy("mLock")
307     private final ArrayList<Integer> mUserLru = new ArrayList<>();
308 
309     /**
310      * Constant array of the users that are currently started.
311      */
312     @GuardedBy("mLock")
313     private int[] mStartedUserArray = new int[] { 0 };
314 
315     /**
316      * Contains the current user and its profiles (if any).
317      *
318      * <p><b>NOTE: </b>it lists all profiles, regardless of their running state (i.e., they're in
319      * this list even if not running).
320      */
321     @GuardedBy("mLock")
322     private int[] mCurrentProfileIds = new int[] {};
323 
324     /**
325      * Mapping from each known user ID to the profile group ID it is associated with.
326      * <p>Users not present in this array have a profile group of NO_PROFILE_GROUP_ID.
327      *
328      * <p>For better or worse, this class sometimes assumes that the profileGroupId of a parent user
329      * is always identical with its userId. If that ever becomes false, this class needs updating.
330      */
331     @GuardedBy("mLock")
332     private final SparseIntArray mUserProfileGroupIds = new SparseIntArray();
333 
334     /**
335      * Registered observers of the user switching mechanics.
336      */
337     private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
338             = new RemoteCallbackList<>();
339 
340     @GuardedBy("mLock")
341     private boolean mUserSwitchUiEnabled = true;
342 
343     /**
344      * Currently active user switch callbacks.
345      */
346     @GuardedBy("mLock")
347     private volatile ArraySet<String> mCurWaitingUserSwitchCallbacks;
348 
349     /**
350      * Messages for switching from {@link android.os.UserHandle#SYSTEM}.
351      */
352     @GuardedBy("mLock")
353     private String mSwitchingFromSystemUserMessage;
354 
355     /**
356      * Messages for switching to {@link android.os.UserHandle#SYSTEM}.
357      */
358     @GuardedBy("mLock")
359     private String mSwitchingToSystemUserMessage;
360 
361     /**
362      * Callbacks that are still active after {@link #getUserSwitchTimeoutMs}
363      */
364     @GuardedBy("mLock")
365     private ArraySet<String> mTimeoutUserSwitchCallbacks;
366 
367     private final LockPatternUtils mLockPatternUtils;
368 
369     // TODO(b/266158156): remove this once we improve/refactor the way broadcasts are sent for
370     //  the system user in HSUM.
371     @GuardedBy("mLock")
372     private boolean mIsBroadcastSentForSystemUserStarted;
373 
374     // TODO(b/266158156): remove this once we improve/refactor the way broadcasts are sent for
375     //  the system user in HSUM.
376     @GuardedBy("mLock")
377     private boolean mIsBroadcastSentForSystemUserStarting;
378 
379     volatile boolean mBootCompleted;
380 
381     /**
382      * In this mode, user is always stopped when switched out (unless overridden by the
383      * {@code fw.stop_bg_users_on_switch} system property) but locking of user data is
384      * postponed until total number of unlocked users in the system reaches mMaxRunningUsers.
385      * Once total number of unlocked users reach mMaxRunningUsers, least recently used user
386      * will be locked.
387      *
388      * <p> Note: Even if this is false for the device as a whole, it is possible some users may
389      * individually allow delayed locking, as specified by
390      * {@link UserProperties#getAllowStoppingUserWithDelayedLocking()}.
391      */
392     @GuardedBy("mLock")
393     private boolean mDelayUserDataLocking;
394 
395     /**
396      * Users are only allowed to be unlocked after boot complete.
397      */
398     private volatile boolean mAllowUserUnlocking;
399 
400     /**
401      * Keep track of last active users for delayUserDataLocking.
402      * The most recently stopped user with delayed locking is placed in front, while the least
403      * recently stopped user in back.
404      */
405     @GuardedBy("mLock")
406     private final ArrayList<Integer> mLastActiveUsersForDelayedLocking = new ArrayList<>();
407 
408     /**
409      * Map of userId to {@link UserCompletedEventType} event flags, indicating which as-yet-
410      * unreported user-starting events have transpired for the given user.
411      */
412     @GuardedBy("mCompletedEventTypes")
413     private final SparseIntArray mCompletedEventTypes = new SparseIntArray();
414 
415     /**
416      * Sets on {@link #setInitialConfig(boolean, int, boolean)}, which is called by
417      * {@code ActivityManager} when the system is started.
418      *
419      * <p>It's useful to ignore external operations (i.e., originated outside {@code system_server},
420      * like from {@code adb shell am switch-user})) that could happen before such call is made and
421      * the system is ready.
422      */
423     @GuardedBy("mLock")
424     private boolean mInitialized;
425 
426     /**
427      * Defines the behavior of whether the background users should be stopped when the foreground
428      * user is switched.
429      */
430     @GuardedBy("mLock")
431     private @StopUserOnSwitch int mStopUserOnSwitch = STOP_USER_ON_SWITCH_DEFAULT;
432 
433     /** @see #getLastUserUnlockingUptime */
434     private volatile long mLastUserUnlockingUptime = 0;
435 
436     /**
437      * Pending user starts waiting for shutdown step to complete.
438      */
439     @GuardedBy("mLock")
440     private final List<PendingUserStart> mPendingUserStarts = new ArrayList<>();
441 
442     private final UserLifecycleListener mUserLifecycleListener = new UserLifecycleListener() {
443         @Override
444         public void onUserCreated(UserInfo user, Object token) {
445             onUserAdded(user);
446         }
447 
448         @Override
449         public void onUserRemoved(UserInfo user) {
450             UserController.this.onUserRemoved(user.id);
451         }
452     };
453 
UserController(ActivityManagerService service)454     UserController(ActivityManagerService service) {
455         this(new Injector(service));
456     }
457 
458     @VisibleForTesting
UserController(Injector injector)459     UserController(Injector injector) {
460         mInjector = injector;
461         // This should be called early to avoid a null mHandler inside the injector
462         mHandler = mInjector.getHandler(this);
463         mUiHandler = mInjector.getUiHandler(this);
464         // User 0 is the first and only user that runs at boot.
465         final UserState uss = new UserState(UserHandle.SYSTEM);
466         uss.mUnlockProgress.addListener(new UserProgressListener());
467         mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
468         mUserLru.add(UserHandle.USER_SYSTEM);
469         mLockPatternUtils = mInjector.getLockPatternUtils();
470         updateStartedUserArrayLU();
471     }
472 
setInitialConfig(boolean userSwitchUiEnabled, int maxRunningUsers, boolean delayUserDataLocking, int backgroundUserScheduledStopTimeSecs)473     void setInitialConfig(boolean userSwitchUiEnabled, int maxRunningUsers,
474             boolean delayUserDataLocking, int backgroundUserScheduledStopTimeSecs) {
475         synchronized (mLock) {
476             mUserSwitchUiEnabled = userSwitchUiEnabled;
477             mMaxRunningUsers = maxRunningUsers;
478             mDelayUserDataLocking = delayUserDataLocking;
479             mBackgroundUserScheduledStopTimeSecs = backgroundUserScheduledStopTimeSecs;
480             mInitialized = true;
481         }
482     }
483 
isUserSwitchUiEnabled()484     private boolean isUserSwitchUiEnabled() {
485         synchronized (mLock) {
486             return mUserSwitchUiEnabled;
487         }
488     }
489 
getMaxRunningUsers()490     int getMaxRunningUsers() {
491         synchronized (mLock) {
492             return mMaxRunningUsers;
493         }
494     }
495 
setStopUserOnSwitch(@topUserOnSwitch int value)496     void setStopUserOnSwitch(@StopUserOnSwitch int value) {
497         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
498                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
499                 android.Manifest.permission.INTERACT_ACROSS_USERS)
500                 == PackageManager.PERMISSION_DENIED) {
501             throw new SecurityException(
502                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS permission to "
503                             + "call setStopUserOnSwitch()");
504         }
505 
506         synchronized (mLock) {
507             Slogf.i(TAG, "setStopUserOnSwitch(): %d -> %d", mStopUserOnSwitch, value);
508             mStopUserOnSwitch = value;
509         }
510     }
511 
shouldStopUserOnSwitch()512     private boolean shouldStopUserOnSwitch() {
513         synchronized (mLock) {
514             if (mStopUserOnSwitch != STOP_USER_ON_SWITCH_DEFAULT) {
515                 final boolean value = mStopUserOnSwitch == STOP_USER_ON_SWITCH_TRUE;
516                 Slogf.i(TAG, "shouldStopUserOnSwitch(): returning overridden value (%b)", value);
517                 return value;
518             }
519         }
520         final int property = SystemProperties.getInt("fw.stop_bg_users_on_switch", -1);
521         return property == -1 ? mDelayUserDataLocking : property == 1;
522     }
523 
finishUserSwitch(UserState uss)524     void finishUserSwitch(UserState uss) {
525         // This call holds the AM lock so we post to the handler.
526         mHandler.post(() -> {
527             finishUserBoot(uss);
528             startProfiles();
529             stopExcessRunningUsers();
530         });
531     }
532 
533     /** Adds a user to mUserLru, moving it to the end of the list if it was already present. */
addUserToUserLru(@serIdInt int userId)534     private void addUserToUserLru(@UserIdInt int userId) {
535         synchronized (mLock) {
536             final Integer userIdObj = userId;
537             mUserLru.remove(userIdObj);
538             mUserLru.add(userIdObj);
539 
540             // Now also move the user's parent to the end (if applicable).
541             Integer parentIdObj = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
542             if (parentIdObj != UserInfo.NO_PROFILE_GROUP_ID && !parentIdObj.equals(userIdObj)
543                     && mUserLru.remove(parentIdObj)) {
544                 mUserLru.add(parentIdObj);
545             }
546         }
547     }
548 
549     /** Returns a list of running users, in order of when they were started (oldest first). */
550     @GuardedBy("mLock")
551     @VisibleForTesting
getRunningUsersLU()552     List<Integer> getRunningUsersLU() {
553         ArrayList<Integer> runningUsers = new ArrayList<>();
554         for (Integer userId : mUserLru) {
555             UserState uss = mStartedUsers.get(userId);
556             if (uss == null) {
557                 // Shouldn't happen, but recover if it does.
558                 continue;
559             }
560             if (uss.state == UserState.STATE_STOPPING
561                     || uss.state == UserState.STATE_SHUTDOWN) {
562                 // This user is already stopping, doesn't count.
563                 continue;
564             }
565             runningUsers.add(userId);
566         }
567         return runningUsers;
568     }
569 
stopExcessRunningUsers()570     private void stopExcessRunningUsers() {
571         final ArraySet<Integer> exemptedUsers = new ArraySet<>();
572         final List<UserInfo> users = mInjector.getUserManager().getUsers(true);
573         for (int i = 0; i < users.size(); i++) {
574             final int userId = users.get(i).id;
575             if (isAlwaysVisibleUser(userId)) {
576                 exemptedUsers.add(userId);
577             }
578         }
579 
580         synchronized (mLock) {
581             stopExcessRunningUsersLU(mMaxRunningUsers, exemptedUsers);
582         }
583     }
584 
585     @GuardedBy("mLock")
stopExcessRunningUsersLU(int maxRunningUsers, ArraySet<Integer> exemptedUsers)586     private void stopExcessRunningUsersLU(int maxRunningUsers, ArraySet<Integer> exemptedUsers) {
587         List<Integer> currentlyRunningLru = getRunningUsersLU();
588         Iterator<Integer> iterator = currentlyRunningLru.iterator();
589         while (currentlyRunningLru.size() > maxRunningUsers && iterator.hasNext()) {
590             Integer userId = iterator.next();
591             if (userId == UserHandle.USER_SYSTEM
592                     || userId == mCurrentUserId
593                     || exemptedUsers.contains(userId)) {
594                 // System and current users can't be stopped, and an exempt user shouldn't be
595                 continue;
596             }
597             // allowDelayedLocking set here as stopping user is done without any explicit request
598             // from outside.
599             Slogf.i(TAG, "Too many running users (%d). Attempting to stop user %d",
600                     currentlyRunningLru.size(), userId);
601             if (stopUsersLU(userId,
602                     /* stopProfileRegardlessOfParent= */ false, /* allowDelayedLocking= */ true,
603                     /* stopUserCallback= */ null, /* keyEvictedCallback= */ null)
604                     == USER_OP_SUCCESS) {
605                 // Technically, stopUsersLU can remove more than one user when stopping a parent.
606                 // But mUserLru is designed so that profiles always precede their parent, so this
607                 // normally won't happen here, and therefore won't cause underestimating the number
608                 // removed.
609                 iterator.remove();
610             }
611         }
612     }
613 
614     /**
615      * Returns if more users can be started without stopping currently running users.
616      */
canStartMoreUsers()617     boolean canStartMoreUsers() {
618         synchronized (mLock) {
619             return getRunningUsersLU().size() < mMaxRunningUsers;
620         }
621     }
622 
finishUserBoot(UserState uss)623     private void finishUserBoot(UserState uss) {
624         finishUserBoot(uss, null);
625     }
626 
finishUserBoot(UserState uss, IIntentReceiver resultTo)627     private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
628         final int userId = uss.mHandle.getIdentifier();
629         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_BOOT, userId);
630 
631         synchronized (mLock) {
632             // Bail if we ended up with a stale user
633             if (mStartedUsers.get(userId) != uss) {
634                 return;
635             }
636         }
637 
638         // We always walk through all the user lifecycle states to send
639         // consistent developer events. We step into RUNNING_LOCKED here,
640         // but we might immediately step into RUNNING below if the user
641         // storage is already unlocked.
642         if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
643             mInjector.getUserJourneyLogger()
644                     .logUserLifecycleEvent(userId, USER_LIFECYCLE_EVENT_USER_RUNNING_LOCKED,
645                     EVENT_STATE_NONE);
646             mInjector.getUserManagerInternal().setUserState(userId, uss.state);
647             // Do not report secondary users, runtime restarts or first boot/upgrade
648             if (userId == UserHandle.USER_SYSTEM
649                     && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
650                 final long elapsedTimeMs = SystemClock.elapsedRealtime();
651                 FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
652                         BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_LOCKED_BOOT_COMPLETED,
653                         elapsedTimeMs);
654                 final long maxElapsedTimeMs = 120_000;
655                 if (elapsedTimeMs > maxElapsedTimeMs) {
656                     Slogf.wtf("SystemServerTiming",
657                             "finishUserBoot took too long. elapsedTimeMs=" + elapsedTimeMs);
658                 }
659             }
660 
661             if (!mInjector.getUserManager().isPreCreated(userId)) {
662                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_LOCKED_BOOT_COMPLETE_MSG,
663                         userId, 0));
664                 // The "locked boot complete" broadcast for the system user is supposed be sent when
665                 // the device has finished booting.  Normally, that is the same time that the system
666                 // user transitions to RUNNING_LOCKED.  However, in "headless system user mode", the
667                 // system user is explicitly started before the device has finished booting.  In
668                 // that case, we need to wait until onBootComplete() to send the broadcast.
669                 // Similarly, this occurs after a user switch, but in HSUM we switch to the main
670                 // user before boot is complete, so again this should be delayed until
671                 // onBootComplete if boot has not yet completed.
672                 if (mAllowUserUnlocking) {
673                     // ACTION_LOCKED_BOOT_COMPLETED
674                     sendLockedBootCompletedBroadcast(resultTo, userId);
675                 }
676             }
677         }
678 
679         // We need to delay unlocking profiles until the parent user is also unlocked.
680         final UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
681         if (parent == null) {
682             // Not a profile (or is a parentless profile) so no parent for which to wait.
683             maybeUnlockUser(userId);
684         } else if (isUserRunning(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
685             Slogf.d(TAG, "User " + userId + " (parent " + parent.id
686                     + "): attempting unlock because parent is unlocked");
687             maybeUnlockUser(userId);
688         } else {
689             Slogf.d(TAG, "User " + userId + " (parent " + parent.id
690                     + "): delaying unlock because parent is locked");
691         }
692     }
693 
sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId)694     private void sendLockedBootCompletedBroadcast(IIntentReceiver receiver, @UserIdInt int userId) {
695         if (android.os.Flags.allowPrivateProfile()
696                 && android.multiuser.Flags.enablePrivateSpaceFeatures()) {
697             final UserInfo userInfo = getUserInfo(userId);
698             if (userInfo != null && userInfo.isPrivateProfile()) {
699                 Slogf.i(TAG, "Skipping LOCKED_BOOT_COMPLETED for private profile user #" + userId);
700                 return;
701             }
702         }
703         final Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
704         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
705         intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
706                 | Intent.FLAG_RECEIVER_OFFLOAD
707                 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
708         mInjector.broadcastIntent(intent, null, receiver, 0, null, null,
709                 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
710                 AppOpsManager.OP_NONE,
711                 getTemporaryAppAllowlistBroadcastOptions(REASON_LOCKED_BOOT_COMPLETED)
712                         .toBundle(),
713                 false, MY_PID, SYSTEM_UID,
714                 Binder.getCallingUid(), Binder.getCallingPid(), userId);
715     }
716 
717     /**
718      * Step from {@link UserState#STATE_RUNNING_LOCKED} to
719      * {@link UserState#STATE_RUNNING_UNLOCKING}.
720      */
finishUserUnlocking(final UserState uss)721     private boolean finishUserUnlocking(final UserState uss) {
722         final int userId = uss.mHandle.getIdentifier();
723         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKING, userId);
724         mInjector.getUserJourneyLogger()
725                 .logUserLifecycleEvent(userId, USER_LIFECYCLE_EVENT_UNLOCKING_USER,
726                 EVENT_STATE_BEGIN);
727         // If the user's CE storage hasn't been unlocked yet, we cannot proceed.
728         if (!StorageManager.isCeStorageUnlocked(userId)) return false;
729         synchronized (mLock) {
730             // Do not proceed if unexpected state or a stale user
731             if (mStartedUsers.get(userId) != uss || uss.state != STATE_RUNNING_LOCKED) {
732                 return false;
733             }
734         }
735         uss.mUnlockProgress.start();
736 
737         // Prepare app storage before we go any further
738         uss.mUnlockProgress.setProgress(5,
739                     mInjector.getContext().getString(R.string.android_start_title));
740 
741         // Call onBeforeUnlockUser on a worker thread that allows disk I/O
742         FgThread.getHandler().post(() -> {
743             if (!StorageManager.isCeStorageUnlocked(userId)) {
744                 Slogf.w(TAG, "User's CE storage got locked unexpectedly, leaving user locked.");
745                 return;
746             }
747 
748             final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
749             t.traceBegin("UM.onBeforeUnlockUser-" + userId);
750             mInjector.getUserManager().onBeforeUnlockUser(userId);
751             t.traceEnd();
752             synchronized (mLock) {
753                 // Do not proceed if unexpected state
754                 if (!uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
755                     return;
756                 }
757             }
758             mInjector.getUserManagerInternal().setUserState(userId, uss.state);
759 
760             uss.mUnlockProgress.setProgress(20);
761 
762             mLastUserUnlockingUptime = SystemClock.uptimeMillis();
763 
764             // Dispatch unlocked to system services; when fully dispatched,
765             // that calls through to the next "unlocked" phase
766             mHandler.obtainMessage(USER_UNLOCK_MSG, userId, 0, uss).sendToTarget();
767         });
768         return true;
769     }
770 
771     /**
772      * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
773      * {@link UserState#STATE_RUNNING_UNLOCKED}.
774      */
finishUserUnlocked(final UserState uss)775     private void finishUserUnlocked(final UserState uss) {
776         final int userId = uss.mHandle.getIdentifier();
777         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKED, userId);
778         // Only keep marching forward if the user's CE storage is unlocked.
779         if (!StorageManager.isCeStorageUnlocked(userId)) return;
780         synchronized (mLock) {
781             // Bail if we ended up with a stale user
782             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
783 
784             // Do not proceed if unexpected state
785             if (!uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
786                 return;
787             }
788         }
789         mInjector.getUserManagerInternal().setUserState(userId, uss.state);
790         uss.mUnlockProgress.finish();
791 
792         // Get unaware persistent apps running and start any unaware providers
793         // in already-running apps that are partially aware
794         if (userId == UserHandle.USER_SYSTEM) {
795             mInjector.startPersistentApps(PackageManager.MATCH_DIRECT_BOOT_UNAWARE);
796         }
797         mInjector.installEncryptionUnawareProviders(userId);
798 
799         if (!mInjector.getUserManager().isPreCreated(userId)) {
800             // Dispatch unlocked to external apps
801             final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
802             unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
803             unlockedIntent.addFlags(
804                     Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
805             mInjector.broadcastIntent(unlockedIntent, null, null, 0, null,
806                     null, null, AppOpsManager.OP_NONE, null, false, MY_PID, SYSTEM_UID,
807                     Binder.getCallingUid(), Binder.getCallingPid(), userId);
808         }
809 
810         final UserInfo userInfo = getUserInfo(userId);
811         if (userInfo.isProfile()) {
812             UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
813             if (parent != null) {
814                 // Send PROFILE_ACCESSIBLE broadcast to the parent user if a profile was unlocked
815                 broadcastProfileAccessibleStateChanged(userId, parent.id,
816                         Intent.ACTION_PROFILE_ACCESSIBLE);
817 
818                 //TODO(b/175704931): send ACTION_MANAGED_PROFILE_AVAILABLE
819 
820                 // Also send MANAGED_PROFILE_UNLOCKED broadcast to the parent user
821                 // if a managed profile was unlocked
822                 if (userInfo.isManagedProfile()) {
823                     final Intent profileUnlockedIntent = new Intent(
824                             Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
825                     profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
826                     profileUnlockedIntent.addFlags(
827                             Intent.FLAG_RECEIVER_REGISTERED_ONLY
828                                     | Intent.FLAG_RECEIVER_FOREGROUND);
829                     mInjector.broadcastIntent(profileUnlockedIntent,
830                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
831                             null, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
832                             Binder.getCallingPid(), parent.id);
833                 }
834             }
835         }
836 
837         // Send PRE_BOOT broadcasts if user fingerprint changed; we
838         // purposefully block sending BOOT_COMPLETED until after all
839         // PRE_BOOT receivers are finished to avoid ANR'ing apps
840         final UserInfo info = getUserInfo(userId);
841         if (!Objects.equals(info.lastLoggedInFingerprint, PackagePartitions.FINGERPRINT)
842                 || SystemProperties.getBoolean("persist.pm.mock-upgrade", false)) {
843             // Suppress double notifications for managed profiles that
844             // were unlocked automatically as part of their parent user being
845             // unlocked.  TODO(b/217442918): this code doesn't work correctly.
846             final boolean quiet = info.isManagedProfile();
847             mInjector.sendPreBootBroadcast(userId, quiet,
848                     () -> finishUserUnlockedCompleted(uss));
849         } else {
850             finishUserUnlockedCompleted(uss);
851         }
852     }
853 
finishUserUnlockedCompleted(UserState uss)854     private void finishUserUnlockedCompleted(UserState uss) {
855         final int userId = uss.mHandle.getIdentifier();
856         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_UNLOCKED_COMPLETED, userId);
857         synchronized (mLock) {
858             // Bail if we ended up with a stale user
859             if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
860         }
861         UserInfo userInfo = getUserInfo(userId);
862         if (userInfo == null) {
863             return;
864         }
865         // Only keep marching forward if the user's CE storage is unlocked.
866         if (!StorageManager.isCeStorageUnlocked(userId)) return;
867 
868         // Remember that we logged in
869         mInjector.getUserManager().onUserLoggedIn(userId);
870 
871         Runnable initializeUser = () -> mInjector.getUserManager().makeInitialized(userInfo.id);
872         if (!userInfo.isInitialized()) {
873             Slogf.d(TAG, "Initializing user #" + userId);
874             if (userInfo.preCreated) {
875                 initializeUser.run();
876             } else if (userId != UserHandle.USER_SYSTEM) {
877                 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
878                 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND
879                         | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
880                 mInjector.broadcastIntent(intent, null,
881                         new IIntentReceiver.Stub() {
882                             @Override
883                             public void performReceive(Intent intent, int resultCode,
884                                     String data, Bundle extras, boolean ordered,
885                                     boolean sticky, int sendingUser) {
886                                 // Note: performReceive is called with mService lock held
887                                 initializeUser.run();
888                             }
889                         }, 0, null, null, null, AppOpsManager.OP_NONE,
890                         null, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
891                         Binder.getCallingPid(), userId);
892             }
893         }
894 
895         if (userInfo.preCreated) {
896             Slogf.i(TAG, "Stopping pre-created user " + userInfo.toFullString());
897             // Pre-created user was started right after creation so services could properly
898             // intialize it; it should be stopped right away as it's not really a "real" user.
899             stopUser(userInfo.id, /* allowDelayedLocking= */ false,
900                     /* stopUserCallback= */ null, /* keyEvictedCallback= */ null);
901             return;
902         }
903 
904         // Spin up app widgets prior to boot-complete, so they can be ready promptly
905         mInjector.startUserWidgets(userId);
906 
907         mHandler.obtainMessage(USER_UNLOCKED_MSG, userId, 0).sendToTarget();
908 
909         if (android.os.Flags.allowPrivateProfile()
910                 && android.multiuser.Flags.enablePrivateSpaceFeatures()) {
911             if (userInfo.isPrivateProfile()) {
912                 Slogf.i(TAG, "Skipping BOOT_COMPLETED for private profile user #" + userId);
913                 return;
914             }
915         }
916         Slogf.i(TAG, "Posting BOOT_COMPLETED user #" + userId);
917         // Do not report secondary users, runtime restarts or first boot/upgrade
918         if (userId == UserHandle.USER_SYSTEM
919                 && !mInjector.isRuntimeRestarted() && !mInjector.isFirstBootOrUpgrade()) {
920             final long elapsedTimeMs = SystemClock.elapsedRealtime();
921             FrameworkStatsLog.write(FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME_REPORTED,
922                     FrameworkStatsLog.BOOT_TIME_EVENT_ELAPSED_TIME__EVENT__FRAMEWORK_BOOT_COMPLETED,
923                     elapsedTimeMs);
924         }
925         final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
926         bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
927         bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
928                 | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND
929                 | Intent.FLAG_RECEIVER_OFFLOAD);
930         // Widget broadcasts are outbound via FgThread, so to guarantee sequencing
931         // we also send the boot_completed broadcast from that thread.
932         final int callingUid = Binder.getCallingUid();
933         final int callingPid = Binder.getCallingPid();
934         FgThread.getHandler().post(() -> {
935             mInjector.broadcastIntent(bootIntent, null,
936                     new IIntentReceiver.Stub() {
937                         @Override
938                         public void performReceive(Intent intent, int resultCode, String data,
939                                 Bundle extras, boolean ordered, boolean sticky, int sendingUser)
940                                         throws RemoteException {
941                             Slogf.i(UserController.TAG, "Finished processing BOOT_COMPLETED for u"
942                                     + userId);
943                             mBootCompleted = true;
944                         }
945                     }, 0, null, null,
946                     new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
947                     AppOpsManager.OP_NONE,
948                     getTemporaryAppAllowlistBroadcastOptions(REASON_BOOT_COMPLETED).toBundle(),
949                     false, MY_PID, SYSTEM_UID, callingUid, callingPid, userId);
950         });
951     }
952 
restartUser(final int userId, @UserStartMode int userStartMode)953     int restartUser(final int userId, @UserStartMode int userStartMode) {
954         return stopUser(userId, /* allowDelayedLocking= */ false,
955                 /* stopUserCallback= */ null, new KeyEvictedCallback() {
956                     @Override
957                     public void keyEvicted(@UserIdInt int userId) {
958                         // Post to the same handler that this callback is called from to ensure
959                         // the user cleanup is complete before restarting.
960                         mHandler.post(() -> UserController.this.startUser(userId, userStartMode));
961                     }
962                 });
963     }
964 
965     /**
966      * Stops a user only if it's a profile, with a more relaxed permission requirement:
967      * {@link android.Manifest.permission#MANAGE_USERS} or
968      * {@link android.Manifest.permission#INTERACT_ACROSS_USERS_FULL}.
969      * To be called from ActivityManagerService.
970      * @param userId the id of the user to stop.
971      * @return true if the operation was successful.
972      */
973     boolean stopProfile(final @UserIdInt int userId) {
974         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
975                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
976                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
977                 == PackageManager.PERMISSION_DENIED) {
978             throw new SecurityException(
979                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS_FULL permission to "
980                             + "stop a profile");
981         }
982 
983         final UserInfo userInfo = getUserInfo(userId);
984         if (userInfo == null || !userInfo.isProfile()) {
985             throw new IllegalArgumentException("User " + userId + " is not a profile");
986         }
987 
988         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
989         synchronized (mLock) {
990             return stopUsersLU(userId, /* allowDelayedLocking= */ false,
991                     /* stopUserCallback= */ null, /* keyEvictedCallback= */ null)
992                     == ActivityManager.USER_OP_SUCCESS;
993         }
994     }
995 
996     int stopUser(final int userId, boolean allowDelayedLocking,
997             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
998         return stopUser(userId, true, allowDelayedLocking, stopUserCallback, keyEvictedCallback);
999     }
1000 
1001     int stopUser(final int userId,
1002             final boolean stopProfileRegardlessOfParent, final boolean allowDelayedLocking,
1003             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
1004         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1005 
1006         t.traceBegin("UserController"
1007                 + (stopProfileRegardlessOfParent ? "-stopProfileRegardlessOfParent" : "")
1008                 + (allowDelayedLocking ? "-allowDelayedLocking" : "")
1009                 + (stopUserCallback != null ? "-withStopUserCallback" : "")
1010                 + "-" + userId + "-[stopUser]");
1011         try {
1012             checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "stopUser");
1013             Preconditions.checkArgument(userId >= 0, "Invalid user id %d", userId);
1014 
1015             enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, userId);
1016             synchronized (mLock) {
1017                 return stopUsersLU(userId, stopProfileRegardlessOfParent, allowDelayedLocking,
1018                         stopUserCallback, keyEvictedCallback);
1019             }
1020         } finally {
1021             t.traceEnd();
1022         }
1023     }
1024 
1025     /** Stops the user along with its profiles. */
1026     @GuardedBy("mLock")
1027     private int stopUsersLU(final int userId, boolean allowDelayedLocking,
1028             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
1029         return stopUsersLU(userId, /* stopProfileRegardlessOfParent= */ true,
1030                 allowDelayedLocking, stopUserCallback, keyEvictedCallback);
1031     }
1032 
1033     /**
1034      * Stops the user along with its profiles. The method calls
1035      * {@link #getUsersToStopLU(int)} to determine the list of users that should be stopped.
1036      *
1037      * @param stopProfileRegardlessOfParent whether to stop the profile regardless of who its
1038      *                                      parent is, e.g. even if the parent is the current user
1039      */
1040     @GuardedBy("mLock")
1041     private int stopUsersLU(final int userId,
1042             boolean stopProfileRegardlessOfParent, boolean allowDelayedLocking,
1043             final IStopUserCallback stopUserCallback, KeyEvictedCallback keyEvictedCallback) {
1044         if (userId == UserHandle.USER_SYSTEM) {
1045             return USER_OP_ERROR_IS_SYSTEM;
1046         }
1047         if (isCurrentUserLU(userId)) {
1048             return USER_OP_IS_CURRENT;
1049         }
1050         if (!stopProfileRegardlessOfParent) {
1051             final int parentId = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
1052             if (parentId != UserInfo.NO_PROFILE_GROUP_ID && parentId != userId) {
1053                 // TODO(b/310249114): Strongly consider *not* exempting the SYSTEM user's profile.
1054                 if ((UserHandle.USER_SYSTEM == parentId || isCurrentUserLU(parentId))) {
1055                     return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
1056                 }
1057             }
1058         }
1059         final int[] usersToStop = getUsersToStopLU(userId);
1060 
1061         // Final safety check: abort if one of the users we would plan to stop must not be stopped.
1062         // This should be impossible in the current code, but just in case.
1063         for (int relatedUserId : usersToStop) {
1064             if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLU(relatedUserId)) {
1065                 Slogf.e(TAG, "Cannot stop user %d because it is related to user %d. ",
1066                         userId, relatedUserId);
1067                 return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
1068             }
1069         }
1070 
1071         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1072         if (DEBUG_MU) Slogf.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
1073         for (int userIdToStop : usersToStop) {
1074             t.traceBegin("stopSingleUserLU-" + userIdToStop + "-[stopUser]");
1075             stopSingleUserLU(userIdToStop, allowDelayedLocking,
1076                     userIdToStop == userId ? stopUserCallback : null,
1077                     userIdToStop == userId ? keyEvictedCallback : null);
1078             t.traceEnd();
1079         }
1080         return USER_OP_SUCCESS;
1081     }
1082 
1083     /**
1084      * Stops a single User.
1085      *
1086      * This should only ever be called by {@link #stopUsersLU},
1087      * which is responsible to making sure any associated users are appropriately stopped too.
1088      *
1089      * This can also trigger locking user data out depending on device's
1090      * config ({@code mDelayUserDataLocking}) and arguments.
1091      *
1092      * In the default configuration for most device and users, users will be locked when stopping.
1093      * User will remain unlocked only if all the following are true
1094      * <li> {@link #canDelayDataLockingForUser(int)} (based on mDelayUserDataLocking) is true
1095      * <li> the parameter {@code allowDelayedLocking} is true
1096      * <li> {@code keyEvictedCallback} is null
1097      * -
1098      *
1099      * @param userId User Id to stop and lock the data.
1100      * @param allowDelayedLocking When set, do not lock user after stopping. Locking can happen
1101      *                            later when number of unlocked users reaches
1102      *                            {@code mMaxRunnngUsers}. Note that this is respected only when
1103      *                            delayed locking is enabled for this user and {@keyEvictedCallback}
1104      *                            is null. Otherwise the user nonetheless will be locked.
1105      * @param stopUserCallback Callback to notify that user has stopped.
1106      * @param keyEvictedCallback Callback to notify that user has been unlocked.
1107      */
1108     @GuardedBy("mLock")
1109     private void stopSingleUserLU(final int userId, boolean allowDelayedLocking,
1110             final IStopUserCallback stopUserCallback,
1111             KeyEvictedCallback keyEvictedCallback) {
1112         Slogf.i(TAG, "stopSingleUserLU userId=" + userId);
1113         if (android.multiuser.Flags.scheduleStopOfBackgroundUser()) {
1114             mHandler.removeEqualMessages(SCHEDULED_STOP_BACKGROUND_USER_MSG,
1115                     Integer.valueOf(userId));
1116         }
1117         final UserState uss = mStartedUsers.get(userId);
1118         if (uss == null) {  // User is not started
1119             // If canDelayDataLockingForUser() is true and allowDelayedLocking is false, we need
1120             // to lock the requested user as the client wants to stop and lock the user. On the
1121             // other hand, having keyEvictedCallback set will lead into locking user if
1122             // canDelayDataLockingForUser() is true as that means client wants to lock the user
1123             // immediately.
1124             // If canDelayDataLockingForUser() is false, the user was already locked when it was
1125             // stopped and no further action is necessary.
1126             if (canDelayDataLockingForUser(userId)) {
1127                 if (allowDelayedLocking && keyEvictedCallback != null) {
1128                     Slogf.wtf(TAG, "allowDelayedLocking set with KeyEvictedCallback, ignore it"
1129                             + " and lock user:" + userId, new RuntimeException());
1130                     allowDelayedLocking = false;
1131                 }
1132                 if (!allowDelayedLocking) {
1133                     if (mLastActiveUsersForDelayedLocking.remove(Integer.valueOf(userId))) {
1134                         // should lock the user, user is already gone
1135                         final ArrayList<KeyEvictedCallback> keyEvictedCallbacks;
1136                         if (keyEvictedCallback != null) {
1137                             keyEvictedCallbacks = new ArrayList<>(1);
1138                             keyEvictedCallbacks.add(keyEvictedCallback);
1139                         } else {
1140                             keyEvictedCallbacks = null;
1141                         }
1142                         dispatchUserLocking(userId, keyEvictedCallbacks);
1143                     }
1144                 }
1145             }
1146             // We do need to post the stopped callback even though user is already stopped.
1147             if (stopUserCallback != null) {
1148                 mHandler.post(() -> {
1149                     try {
1150                         stopUserCallback.userStopped(userId);
1151                     } catch (RemoteException e) {
1152                     }
1153                 });
1154             }
1155             return;
1156         }
1157 
1158         logUserJourneyBegin(userId, USER_JOURNEY_USER_STOP);
1159 
1160         if (stopUserCallback != null) {
1161             uss.mStopCallbacks.add(stopUserCallback);
1162         }
1163         if (keyEvictedCallback != null) {
1164             uss.mKeyEvictedCallbacks.add(keyEvictedCallback);
1165         }
1166 
1167         if (uss.state != UserState.STATE_STOPPING
1168                 && uss.state != UserState.STATE_SHUTDOWN) {
1169             uss.setState(UserState.STATE_STOPPING);
1170             UserManagerInternal userManagerInternal = mInjector.getUserManagerInternal();
1171             TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1172             t.traceBegin("setUserState-STATE_STOPPING-" + userId + "-[stopUser]");
1173             userManagerInternal.setUserState(userId, uss.state);
1174             t.traceEnd();
1175             t.traceBegin("unassignUserFromDisplayOnStop-" + userId + "-[stopUser]");
1176             userManagerInternal.unassignUserFromDisplayOnStop(userId);
1177             t.traceEnd();
1178 
1179             updateStartedUserArrayLU();
1180 
1181             final boolean allowDelayedLockingCopied = allowDelayedLocking;
1182             Runnable finishUserStoppingAsync = () ->
1183                     mHandler.post(() -> {
1184                         TimingsTraceAndSlog t2 = new TimingsTraceAndSlog();
1185                         t2.traceBegin("finishUserStopping-" + userId + "-[stopUser]");
1186                         finishUserStopping(userId, uss, allowDelayedLockingCopied);
1187                         t2.traceEnd();
1188                     });
1189 
1190             if (mInjector.getUserManager().isPreCreated(userId)) {
1191                 finishUserStoppingAsync.run();
1192                 return;
1193             }
1194 
1195             // Post to handler to obtain amLock
1196             mHandler.post(() -> {
1197                 // We are going to broadcast ACTION_USER_STOPPING and then
1198                 // once that is done send a final ACTION_SHUTDOWN and then
1199                 // stop the user.
1200                 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
1201                 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1202                 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1203                 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
1204                 // This is the result receiver for the initial stopping broadcast.
1205                 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
1206                     @Override
1207                     public void performReceive(Intent intent, int resultCode, String data,
1208                             Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1209                         asyncTraceEnd("broadcast-ACTION_USER_STOPPING-" + userId + "-[stopUser]",
1210                                 userId);
1211                         finishUserStoppingAsync.run();
1212                     }
1213                 };
1214 
1215                 TimingsTraceAndSlog t2 = new TimingsTraceAndSlog();
1216                 t2.traceBegin("clearBroadcastQueueForUser-" + userId + "-[stopUser]");
1217                 // Clear broadcast queue for the user to avoid delivering stale broadcasts
1218                 mInjector.clearBroadcastQueueForUser(userId);
1219                 t2.traceEnd();
1220                 asyncTraceBegin("broadcast-ACTION_USER_STOPPING-" + userId + "-[stopUser]", userId);
1221                 // Kick things off.
1222                 mInjector.broadcastIntent(stoppingIntent,
1223                         null, stoppingReceiver, 0, null, null,
1224                         new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
1225                         null, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1226                         Binder.getCallingPid(), UserHandle.USER_ALL);
1227             });
1228         }
1229     }
1230 
1231     private void finishUserStopping(final int userId, final UserState uss,
1232             final boolean allowDelayedLocking) {
1233         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_STOPPING, userId);
1234         synchronized (mLock) {
1235             if (uss.state != UserState.STATE_STOPPING) {
1236                 // Whoops, we are being started back up.  Abort, abort!
1237                 UserJourneySession session = mInjector.getUserJourneyLogger()
1238                         .logUserJourneyFinishWithError(-1, getUserInfo(userId),
1239                                 USER_JOURNEY_USER_STOP, ERROR_CODE_ABORTED);
1240                 if (session != null) {
1241                     mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1242                 } else {
1243                     mInjector.getUserJourneyLogger()
1244                             .logUserJourneyFinishWithError(-1, getUserInfo(userId),
1245                                     USER_JOURNEY_USER_STOP, ERROR_CODE_INVALID_SESSION_ID);
1246                 }
1247                 return;
1248             }
1249             uss.setState(UserState.STATE_SHUTDOWN);
1250         }
1251         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1252         t.traceBegin("setUserState-STATE_SHUTDOWN-" + userId + "-[stopUser]");
1253         mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1254         t.traceEnd();
1255 
1256         mInjector.batteryStatsServiceNoteEvent(
1257                 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
1258                 Integer.toString(userId), userId);
1259         mInjector.getSystemServiceManager().onUserStopping(userId);
1260 
1261         Runnable finishUserStoppedAsync = () ->
1262                 mHandler.post(() -> {
1263                     TimingsTraceAndSlog t2 = new TimingsTraceAndSlog();
1264                     t2.traceBegin("finishUserStopped-" + userId + "-[stopUser]");
1265                     finishUserStopped(uss, allowDelayedLocking);
1266                     t2.traceEnd();
1267                 });
1268         if (mInjector.getUserManager().isPreCreated(userId)) {
1269             finishUserStoppedAsync.run();
1270             return;
1271         }
1272 
1273         // Fire the shutdown intent.
1274         final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
1275         // This is the result receiver for the final shutdown broadcast.
1276         final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
1277             @Override
1278             public void performReceive(Intent intent, int resultCode, String data,
1279                     Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
1280                 asyncTraceEnd("broadcast-ACTION_SHUTDOWN-" + userId + "-[stopUser]", userId);
1281                 finishUserStoppedAsync.run();
1282             }
1283         };
1284         asyncTraceBegin("broadcast-ACTION_SHUTDOWN-" + userId + "-[stopUser]", userId);
1285         mInjector.broadcastIntent(shutdownIntent,
1286                 null, shutdownReceiver, 0, null, null, null,
1287                 AppOpsManager.OP_NONE,
1288                 null, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1289                 Binder.getCallingPid(), userId);
1290     }
1291 
1292     @VisibleForTesting
1293     void finishUserStopped(UserState uss, boolean allowDelayedLocking) {
1294         final int userId = uss.mHandle.getIdentifier();
1295         if (DEBUG_MU) {
1296             Slogf.i(TAG, "finishUserStopped(%d): allowDelayedLocking=%b", userId,
1297                     allowDelayedLocking);
1298         }
1299 
1300         EventLog.writeEvent(EventLogTags.UC_FINISH_USER_STOPPED, userId);
1301         final boolean stopped;
1302         boolean lockUser = true;
1303         final ArrayList<IStopUserCallback> stopCallbacks;
1304         final ArrayList<KeyEvictedCallback> keyEvictedCallbacks;
1305         int userIdToLock = userId;
1306         // Must get a reference to UserInfo before it's removed
1307         final UserInfo userInfo = getUserInfo(userId);
1308         synchronized (mLock) {
1309             stopCallbacks = new ArrayList<>(uss.mStopCallbacks);
1310             keyEvictedCallbacks = new ArrayList<>(uss.mKeyEvictedCallbacks);
1311             if (mStartedUsers.get(userId) != uss || uss.state != UserState.STATE_SHUTDOWN) {
1312                 stopped = false;
1313             } else {
1314                 stopped = true;
1315                 // User can no longer run.
1316                 Slogf.i(TAG, "Removing user state from UserController.mStartedUsers for user #"
1317                         + userId + " as a result of user being stopped");
1318                 mStartedUsers.remove(userId);
1319 
1320                 mUserLru.remove(Integer.valueOf(userId));
1321                 updateStartedUserArrayLU();
1322 
1323                 if (allowDelayedLocking && !keyEvictedCallbacks.isEmpty()) {
1324                     Slogf.wtf(TAG,
1325                             "Delayed locking enabled while KeyEvictedCallbacks not empty, userId:"
1326                                     + userId + " callbacks:" + keyEvictedCallbacks);
1327                     allowDelayedLocking = false;
1328                 }
1329                 userIdToLock = updateUserToLockLU(userId, allowDelayedLocking);
1330                 if (userIdToLock == UserHandle.USER_NULL) {
1331                     lockUser = false;
1332                 }
1333             }
1334         }
1335         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1336         if (stopped) {
1337             Slogf.i(TAG, "Removing user state from UserManager.mUserStates for user #" + userId
1338                     + " as a result of user being stopped");
1339             mInjector.getUserManagerInternal().removeUserState(userId);
1340 
1341             mInjector.activityManagerOnUserStopped(userId);
1342             // Clean up all state and processes associated with the user.
1343             // Kill all the processes for the user.
1344             t.traceBegin("stopPackagesOfStoppedUser-" + userId + "-[stopUser]");
1345             stopPackagesOfStoppedUser(userId, "finish user");
1346             t.traceEnd();
1347         }
1348 
1349         for (final IStopUserCallback callback : stopCallbacks) {
1350             try {
1351                 if (stopped) {
1352                     t.traceBegin("stopCallbacks.userStopped-" + userId + "-[stopUser]");
1353                     callback.userStopped(userId);
1354                     t.traceEnd();
1355                 } else {
1356                     t.traceBegin("stopCallbacks.userStopAborted-" + userId + "-[stopUser]");
1357                     callback.userStopAborted(userId);
1358                     t.traceEnd();
1359                 }
1360             } catch (RemoteException ignored) {
1361             }
1362         }
1363 
1364         if (stopped) {
1365             t.traceBegin("systemServiceManagerOnUserStopped-" + userId + "-[stopUser]");
1366             mInjector.systemServiceManagerOnUserStopped(userId);
1367             t.traceEnd();
1368             t.traceBegin("taskSupervisorRemoveUser-" + userId + "-[stopUser]");
1369             mInjector.taskSupervisorRemoveUser(userId);
1370             t.traceEnd();
1371 
1372             // Remove the user if it is ephemeral.
1373             if (userInfo.isEphemeral() && !userInfo.preCreated) {
1374                 mInjector.getUserManager().removeUserEvenWhenDisallowed(userId);
1375             }
1376 
1377             UserJourneySession session = mInjector.getUserJourneyLogger()
1378                     .logUserJourneyFinish(-1, userInfo, USER_JOURNEY_USER_STOP);
1379             if (session != null) {
1380                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1381             }
1382 
1383             if (lockUser) {
1384                 dispatchUserLocking(userIdToLock, keyEvictedCallbacks);
1385             }
1386 
1387             // Resume any existing pending user start,
1388             // which was paused while the SHUTDOWN flow of the user was in progress.
1389             resumePendingUserStarts(userId);
1390         } else {
1391             UserJourneySession session = mInjector.getUserJourneyLogger()
1392                     .finishAndClearIncompleteUserJourney(userId, USER_JOURNEY_USER_STOP);
1393             if (session != null) {
1394                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
1395             }
1396         }
1397     }
1398 
1399     /**
1400      * Resume any existing pending user start for the specified userId which was paused
1401      * while the shutdown flow of the user was in progress.
1402      * Remove all the handled user starts from mPendingUserStarts.
1403      * @param userId the id of the user
1404      */
1405     private void resumePendingUserStarts(@UserIdInt int userId) {
1406         synchronized (mLock) {
1407             final List<PendingUserStart> handledUserStarts = new ArrayList<>();
1408 
1409             for (PendingUserStart userStart: mPendingUserStarts) {
1410                 if (userStart.userId == userId) {
1411                     Slogf.i(TAG, "resumePendingUserStart for" + userStart);
1412                     mHandler.post(() -> startUser(userStart.userId,
1413                             userStart.userStartMode, userStart.unlockListener));
1414 
1415                     handledUserStarts.add(userStart);
1416                 }
1417             }
1418             // remove all the pending user starts which are now handled
1419             mPendingUserStarts.removeAll(handledUserStarts);
1420         }
1421     }
1422 
1423 
1424     private void dispatchUserLocking(@UserIdInt int userId,
1425             @Nullable List<KeyEvictedCallback> keyEvictedCallbacks) {
1426         // Evict the user's credential encryption key. Performed on FgThread to make it
1427         // serialized with call to UserManagerService.onBeforeUnlockUser in finishUserUnlocking
1428         // to prevent data corruption.
1429         FgThread.getHandler().post(() -> {
1430             synchronized (mLock) {
1431                 if (mStartedUsers.get(userId) != null) {
1432                     Slogf.w(TAG, "User was restarted, skipping key eviction");
1433                     return;
1434                 }
1435             }
1436             try {
1437                 Slogf.i(TAG, "Locking CE storage for user #" + userId);
1438                 mInjector.getStorageManager().lockCeStorage(userId);
1439             } catch (RemoteException re) {
1440                 throw re.rethrowAsRuntimeException();
1441             }
1442             if (keyEvictedCallbacks == null) {
1443                 return;
1444             }
1445             for (int i = 0; i < keyEvictedCallbacks.size(); i++) {
1446                 keyEvictedCallbacks.get(i).keyEvicted(userId);
1447             }
1448         });
1449     }
1450 
1451     /**
1452      * Returns which user, if any, should be locked when the given user is stopped.
1453      *
1454      * For typical (non-mDelayUserDataLocking) devices and users, this will be the provided user.
1455      *
1456      * However, for some devices or users (based on {@link #canDelayDataLockingForUser(int)}),
1457      * storage once unlocked is kept unlocked, even after the user is stopped, so the user to be
1458      * locked (if any) may differ.
1459      *
1460      * For mDelayUserDataLocking devices, the total number of unlocked user storage is limited
1461      * (currently by mMaxRunningUsers). If there are more unlocked users, evict and lock the least
1462      * recently stopped user and lock that user's data.
1463      *
1464      * Regardless of the mode, ephemeral user is always locked immediately.
1465      *
1466      * @return user id to lock. UserHandler.USER_NULL will be returned if no user should be locked.
1467      */
1468     @GuardedBy("mLock")
1469     private int updateUserToLockLU(@UserIdInt int userId, boolean allowDelayedLocking) {
1470         if (!canDelayDataLockingForUser(userId)
1471                 || !allowDelayedLocking
1472                 || getUserInfo(userId).isEphemeral()
1473                 || hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, userId)) {
1474             return userId;
1475         }
1476 
1477         // Once we reach here, we are in a delayed locking scenario.
1478         // Now, no user will be locked, unless the device's policy dictates we should based on the
1479         // maximum of such users allowed for the device.
1480         if (mDelayUserDataLocking) {
1481             // arg should be object, not index
1482             mLastActiveUsersForDelayedLocking.remove((Integer) userId);
1483             mLastActiveUsersForDelayedLocking.add(0, userId);
1484             int totalUnlockedUsers = mStartedUsers.size()
1485                     + mLastActiveUsersForDelayedLocking.size();
1486             // TODO: Decouple the delayed locking flows from mMaxRunningUsers. These users aren't
1487             //  running so this calculation shouldn't be based on this parameter. Also note that
1488             //  that if these devices ever support background running users (such as profiles), the
1489             //  implementation is incorrect since starting such users can cause the max to be
1490             //  exceeded.
1491             if (totalUnlockedUsers > mMaxRunningUsers) { // should lock a user
1492                 final int userIdToLock = mLastActiveUsersForDelayedLocking.get(
1493                         mLastActiveUsersForDelayedLocking.size() - 1);
1494                 mLastActiveUsersForDelayedLocking
1495                         .remove(mLastActiveUsersForDelayedLocking.size() - 1);
1496                 Slogf.i(TAG, "finishUserStopped: should stop user " + userId
1497                         + " but should lock user " + userIdToLock);
1498                 return userIdToLock;
1499             }
1500         }
1501         Slogf.i(TAG, "finishUserStopped: should stop user " + userId + " but without any locking");
1502         return UserHandle.USER_NULL;
1503     }
1504 
1505     /**
1506      * Returns whether the user can have its CE storage left unlocked, even when it is stopped,
1507      * either due to a global device configuration or an individual user's property.
1508      */
1509     private boolean canDelayDataLockingForUser(@UserIdInt int userIdToLock) {
1510         if (allowBiometricUnlockForPrivateProfile()) {
1511             final UserProperties userProperties = getUserProperties(userIdToLock);
1512             return (mDelayUserDataLocking || (userProperties != null
1513                     && userProperties.getAllowStoppingUserWithDelayedLocking()));
1514         }
1515         return mDelayUserDataLocking;
1516     }
1517 
1518     private boolean allowBiometricUnlockForPrivateProfile() {
1519         return android.os.Flags.allowPrivateProfile()
1520                 && android.multiuser.Flags.enableBiometricsToUnlockPrivateSpace()
1521                 && android.multiuser.Flags.enablePrivateSpaceFeatures();
1522     }
1523 
1524     /**
1525      * Determines the list of users that should be stopped together with the specified
1526      * {@code userId}, i.e. the user and its profiles (if the given user is a parent).
1527      * The returned list includes {@code userId}.
1528      */
1529     @GuardedBy("mLock")
1530     private @NonNull int[] getUsersToStopLU(@UserIdInt int userId) {
1531         int startedUsersSize = mStartedUsers.size();
1532         IntArray userIds = new IntArray();
1533         userIds.add(userId);
1534         int userGroupId = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
1535         if (userGroupId == userId) {
1536             // The user is the parent of the profile group. Stop its profiles too.
1537             for (int i = 0; i < startedUsersSize; i++) {
1538                 UserState uss = mStartedUsers.valueAt(i);
1539                 int startedUserId = uss.mHandle.getIdentifier();
1540                 // Skip unrelated users (profileGroupId mismatch)
1541                 int startedUserGroupId = mUserProfileGroupIds.get(startedUserId,
1542                         UserInfo.NO_PROFILE_GROUP_ID);
1543                 boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
1544                         && (userGroupId == startedUserGroupId);
1545                 // userId has already been added
1546                 boolean sameUserId = startedUserId == userId;
1547                 if (!sameGroup || sameUserId) {
1548                     continue;
1549                 }
1550                 userIds.add(startedUserId);
1551             }
1552         }
1553         return userIds.toArray();
1554     }
1555 
1556     private void stopPackagesOfStoppedUser(@UserIdInt int userId, String reason) {
1557         if (DEBUG_MU) Slogf.i(TAG, "stopPackagesOfStoppedUser(%d): %s", userId, reason);
1558         mInjector.activityManagerForceStopPackage(userId, reason);
1559         if (mInjector.getUserManager().isPreCreated(userId)) {
1560             // Don't fire intent for precreated.
1561             return;
1562         }
1563         Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
1564         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1565                 | Intent.FLAG_RECEIVER_FOREGROUND);
1566         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
1567         mInjector.broadcastIntent(intent,
1568                 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1569                 null, false, MY_PID, SYSTEM_UID, Binder.getCallingUid(),
1570                 Binder.getCallingPid(), UserHandle.USER_ALL);
1571 
1572         // Send PROFILE_INACCESSIBLE broadcast if a profile was stopped
1573         final UserInfo userInfo = getUserInfo(userId);
1574         if (userInfo != null && userInfo.isProfile()) {
1575             UserInfo parent = mInjector.getUserManager().getProfileParent(userId);
1576             if (parent != null) {
1577                 broadcastProfileAccessibleStateChanged(userId, parent.id,
1578                         Intent.ACTION_PROFILE_INACCESSIBLE);
1579                 //TODO(b/175704931): send ACTION_MANAGED_PROFILE_UNAVAILABLE
1580             }
1581         }
1582     }
1583 
1584     /**
1585      * Stops the guest or ephemeral user if it has gone to the background.
1586      */
1587     private void stopGuestOrEphemeralUserIfBackground(int oldUserId) {
1588         if (DEBUG_MU) Slogf.i(TAG, "Stop guest or ephemeral user if background: " + oldUserId);
1589         synchronized(mLock) {
1590             UserState oldUss = mStartedUsers.get(oldUserId);
1591             if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId || oldUss == null
1592                     || oldUss.state == UserState.STATE_STOPPING
1593                     || oldUss.state == UserState.STATE_SHUTDOWN) {
1594                 return;
1595             }
1596         }
1597 
1598         UserInfo userInfo = getUserInfo(oldUserId);
1599         if (userInfo.isEphemeral()) {
1600             LocalServices.getService(UserManagerInternal.class).onEphemeralUserStop(oldUserId);
1601         }
1602         if (userInfo.isGuest() || userInfo.isEphemeral()) {
1603             // This is a user to be stopped.
1604             Slogf.i(TAG, "Stopping background guest or ephemeral user " + oldUserId);
1605             synchronized (mLock) {
1606                 stopUsersLU(oldUserId, /* allowDelayedLocking= */ false, null, null);
1607             }
1608         }
1609     }
1610 
1611     void scheduleStartProfiles() {
1612         // Parent user transition to RUNNING_UNLOCKING happens on FgThread, so it is busy, there is
1613         // a chance the profile will reach RUNNING_LOCKED while parent is still locked, so no
1614         // attempt will be made to unlock the profile. If we go via FgThread, this will be executed
1615         // after the parent had chance to unlock fully.
1616         FgThread.getHandler().post(() -> {
1617             if (!mHandler.hasMessages(START_PROFILES_MSG)) {
1618                 mHandler.sendMessageDelayed(mHandler.obtainMessage(START_PROFILES_MSG),
1619                         DateUtils.SECOND_IN_MILLIS);
1620             }
1621         });
1622     }
1623 
1624     /** Starts all applicable profiles of the current user. */
1625     private void startProfiles() {
1626         int currentUserId = getCurrentUserId();
1627         if (DEBUG_MU) Slogf.i(TAG, "startProfilesLocked");
1628         List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
1629                 currentUserId, false /* enabledOnly */);
1630         List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
1631         for (UserInfo user : profiles) {
1632             if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
1633                     && user.id != currentUserId
1634                     && shouldStartWithParent(user)) {
1635                 profilesToStart.add(user);
1636             }
1637         }
1638         final int profilesToStartSize = profilesToStart.size();
1639         int i = 0;
1640         for (; i < profilesToStartSize && i < (getMaxRunningUsers() - 1); ++i) {
1641             // NOTE: this method is setting the profiles of the current user - which is always
1642             // assigned to the default display
1643             startUser(profilesToStart.get(i).id, USER_START_MODE_BACKGROUND_VISIBLE);
1644         }
1645         if (i < profilesToStartSize) {
1646             Slogf.w(TAG, "More profiles than MAX_RUNNING_USERS");
1647         }
1648     }
1649 
1650     private boolean shouldStartWithParent(UserInfo user) {
1651         final UserProperties properties = getUserProperties(user.id);
1652         return (properties != null && properties.getStartWithParent())
1653                 && !user.isQuietModeEnabled();
1654     }
1655 
1656     /**
1657      * Starts a {@link UserManager#isProfile() profile user}.
1658      *
1659      * <p>To be called from {@link com.android.server.am.ActivityManagerService}.
1660      *
1661      * @param userId the id of the profile user to start.
1662      * @param evenWhenDisabled whether the profile should be started if it's not enabled yet
1663      *        (most callers should pass {@code false}, except when starting the profile while it's
1664      *        being provisioned).
1665      * @param unlockListener listener to be informed when the profile has started and unlocked.
1666      *
1667      * @return {@code true} if the operation was successful.
1668      *
1669      * @throws IllegalArgumentException if the user doesn't exist or is not a profile.
1670      */
1671     @RequiresPermission(anyOf = {android.Manifest.permission.MANAGE_USERS,
1672             android.Manifest.permission.INTERACT_ACROSS_USERS_FULL})
1673     boolean startProfile(@UserIdInt int userId, boolean evenWhenDisabled,
1674             @Nullable IProgressListener unlockListener) {
1675         if (mInjector.checkCallingPermission(android.Manifest.permission.MANAGE_USERS)
1676                 == PackageManager.PERMISSION_DENIED && mInjector.checkCallingPermission(
1677                 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL)
1678                 == PackageManager.PERMISSION_DENIED) {
1679             throw new SecurityException(
1680                     "You either need MANAGE_USERS or INTERACT_ACROSS_USERS_FULL permission to "
1681                             + "start a profile");
1682         }
1683 
1684         final UserInfo userInfo = getUserInfo(userId);
1685         if (userInfo == null || !userInfo.isProfile()) {
1686             throw new IllegalArgumentException("User " + userId + " is not a profile");
1687         }
1688 
1689         if (!userInfo.isEnabled() && !evenWhenDisabled) {
1690             Slogf.w(TAG, "Cannot start disabled profile #%d", userId);
1691             return false;
1692         }
1693 
1694         return startUserNoChecks(userId, Display.DEFAULT_DISPLAY,
1695                 USER_START_MODE_BACKGROUND_VISIBLE, unlockListener);
1696     }
1697 
1698     @VisibleForTesting
1699     boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode) {
1700         return startUser(userId, userStartMode, /* unlockListener= */ null);
1701     }
1702 
1703     /**
1704      * Start user, if its not already running.
1705      *
1706      * <p>The user will be brought to the foreground, if {@code userStartMode} parameter is
1707      * set to {@link UserManagerInternal#USER_START_MODE_FOREGROUND}
1708      * When starting the user, multiple intents will be broadcast in the following order:</p>
1709      * <ul>
1710      *     <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
1711      *     <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
1712      *     user and all profiles of this user. Sent only if {@code foreground} parameter is
1713      *     {@code false}
1714      *     <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
1715      *     user and all profiles of this user. Sent only if {@code foreground} parameter is
1716      *     {@code true}
1717      *     <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
1718      *     Sent only if {@code foreground} parameter is {@code true}
1719      *     <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
1720      *     of the new fg user
1721      *     <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
1722      *     the new user
1723      *     <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
1724      *     <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
1725      *     new user. Sent only when the user is booting after a system update.
1726      *     <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
1727      *     new user. Sent only the first time a user is starting.
1728      *     <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
1729      *     user. Indicates that the user has finished booting.
1730      * </ul>
1731      *
1732      * @param userId ID of the user to start
1733      * @param userStartMode user starting mode
1734      * @param unlockListener Listener to be informed when the user has started and unlocked.
1735      * @return true if the user has been successfully started
1736      */
1737     boolean startUser(@UserIdInt int userId, @UserStartMode int userStartMode,
1738             @Nullable IProgressListener unlockListener) {
1739         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "startUser");
1740 
1741         return startUserNoChecks(userId, Display.DEFAULT_DISPLAY, userStartMode, unlockListener);
1742     }
1743 
1744     /**
1745      * Starts a user in background and make it visible in the given display.
1746      *
1747      * <p>This call will trigger the usual "user started" lifecycle events (i.e., `SystemService`
1748      * callbacks and app intents), plus a call to
1749      * {@link UserManagerInternal.UserVisibilityListener#onUserVisibilityChanged(int, boolean)} if
1750      * the user visibility changed. Notice that the visibility change is independent of the user
1751      * workflow state, and they can mismatch in some corner events (for example, if the user was
1752      * already running in the background but not associated with a display, this call for that user
1753      * would not trigger any lifecycle event but would trigger {@code onUserVisibilityChanged}).
1754      *
1755      * <p>See {@link ActivityManager#startUserInBackgroundOnSecondaryDisplay(int, int)} for more
1756      * semantics.
1757      *
1758      * @param userId user to be started
1759      * @param displayId display where the user will be visible
1760      * @param unlockListener Listener to be informed when the user has started and unlocked.
1761      *
1762      * @return whether the user was started
1763      */
1764     boolean startUserVisibleOnDisplay(@UserIdInt int userId, int displayId,
1765             @Nullable IProgressListener unlockListener) {
1766         checkCallingHasOneOfThosePermissions("startUserOnDisplay",
1767                 MANAGE_USERS, INTERACT_ACROSS_USERS);
1768 
1769         try {
1770             return startUserNoChecks(userId, displayId, USER_START_MODE_BACKGROUND_VISIBLE,
1771                     unlockListener);
1772         } catch (RuntimeException e) {
1773             Slogf.e(TAG, "startUserOnSecondaryDisplay(%d, %d) failed: %s", userId, displayId, e);
1774             return false;
1775         }
1776     }
1777 
1778     private boolean startUserNoChecks(@UserIdInt int userId, int displayId,
1779             @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener) {
1780         TimingsTraceAndSlog t = new TimingsTraceAndSlog();
1781 
1782         t.traceBegin("UserController.startUser-" + userId
1783                 + (displayId == Display.DEFAULT_DISPLAY ? "" : "-display-" + displayId)
1784                 + "-" + (userStartMode == USER_START_MODE_FOREGROUND ? "fg" : "bg")
1785                 + "-start-mode-" + userStartMode);
1786         try {
1787             return startUserInternal(userId, displayId, userStartMode, unlockListener, t);
1788         } finally {
1789             t.traceEnd();
1790         }
1791     }
1792 
1793     private boolean startUserInternal(@UserIdInt int userId, int displayId,
1794             @UserStartMode int userStartMode, @Nullable IProgressListener unlockListener,
1795             TimingsTraceAndSlog t) {
1796         if (DEBUG_MU) {
1797             Slogf.i(TAG, "Starting user %d on display %d with mode  %s", userId, displayId,
1798                     userStartModeToString(userStartMode));
1799         }
1800         boolean foreground = userStartMode == USER_START_MODE_FOREGROUND;
1801 
1802         boolean onSecondaryDisplay = displayId != Display.DEFAULT_DISPLAY;
1803         if (onSecondaryDisplay) {
1804             Preconditions.checkArgument(!foreground, "Cannot start user %d in foreground AND "
1805                     + "on secondary display (%d)", userId, displayId);
1806         }
1807         EventLog.writeEvent(EventLogTags.UC_START_USER_INTERNAL, userId, foreground ? 1 : 0,
1808                 displayId);
1809 
1810         final int callingUid = Binder.getCallingUid();
1811         final int callingPid = Binder.getCallingPid();
1812         final long ident = Binder.clearCallingIdentity();
1813         try {
1814             t.traceBegin("getStartedUserState");
1815             final int oldUserId = getCurrentUserId();
1816             if (oldUserId == userId) {
1817                 // The user we're requested to start is already the current user.
1818                 final UserState state = getStartedUserState(userId);
1819                 if (state == null) {
1820                     Slogf.wtf(TAG, "Current user has no UserState");
1821                     // continue starting.
1822                 } else {
1823                     if (userId == UserHandle.USER_SYSTEM && state.state == STATE_BOOTING) {
1824                         // system user start explicitly requested. should continue starting as it
1825                         // is not in running state.
1826                     } else {
1827                         if (state.state == STATE_RUNNING_UNLOCKED) {
1828                             // We'll skip all later code, so we must tell listener it's already
1829                             // unlocked.
1830                             notifyFinished(userId, unlockListener);
1831                         }
1832                         t.traceEnd(); //getStartedUserState
1833                         return true;
1834                     }
1835                 }
1836             }
1837             t.traceEnd(); //getStartedUserState
1838 
1839             if (foreground) {
1840                 t.traceBegin("clearAllLockedTasks");
1841                 mInjector.clearAllLockedTasks("startUser");
1842                 t.traceEnd();
1843             }
1844 
1845             t.traceBegin("getUserInfo");
1846             final UserInfo userInfo = getUserInfo(userId);
1847             t.traceEnd();
1848 
1849             if (userInfo == null) {
1850                 Slogf.w(TAG, "No user info for user #" + userId);
1851                 return false;
1852             }
1853             if (foreground && userInfo.isProfile()) {
1854                 Slogf.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
1855                 return false;
1856             }
1857 
1858             if ((foreground || onSecondaryDisplay) && userInfo.preCreated) {
1859                 Slogf.w(TAG, "Cannot start pre-created user #" + userId + " in foreground or on "
1860                         + "secondary display");
1861                 return false;
1862             }
1863 
1864             t.traceBegin("assignUserToDisplayOnStart");
1865             int result = mInjector.getUserManagerInternal().assignUserToDisplayOnStart(userId,
1866                     userInfo.profileGroupId, userStartMode, displayId);
1867             t.traceEnd();
1868 
1869             if (result == USER_ASSIGNMENT_RESULT_FAILURE) {
1870                 Slogf.e(TAG, "%s user(%d) / display (%d) assignment failed: %s",
1871                         userStartModeToString(userStartMode), userId, displayId,
1872                         userAssignmentResultToString(result));
1873                 return false;
1874             }
1875 
1876             boolean needStart = false;
1877             boolean updateUmState = false;
1878             UserState uss;
1879 
1880             // If the user we are switching to is not currently started, then
1881             // we need to start it now.
1882             t.traceBegin("updateStartedUserArrayStarting");
1883             synchronized (mLock) {
1884                 uss = mStartedUsers.get(userId);
1885                 if (uss == null) {
1886                     uss = new UserState(UserHandle.of(userId));
1887                     uss.mUnlockProgress.addListener(new UserProgressListener());
1888                     mStartedUsers.put(userId, uss);
1889                     updateStartedUserArrayLU();
1890                     needStart = true;
1891                     updateUmState = true;
1892                 } else if (uss.state == UserState.STATE_SHUTDOWN) {
1893                     Slogf.i(TAG, "User #" + userId
1894                             + " is shutting down - will start after full shutdown");
1895                     mPendingUserStarts.add(new PendingUserStart(userId, userStartMode,
1896                             unlockListener));
1897                     t.traceEnd(); // updateStartedUserArrayStarting
1898                     return true;
1899                 }
1900             }
1901 
1902             // No matter what, the fact that we're requested to start the user (even if it is
1903             // already running) puts it towards the end of the mUserLru list.
1904             addUserToUserLru(userId);
1905             if (android.multiuser.Flags.scheduleStopOfBackgroundUser()) {
1906                 mHandler.removeEqualMessages(SCHEDULED_STOP_BACKGROUND_USER_MSG,
1907                         Integer.valueOf(userId));
1908             }
1909 
1910             if (unlockListener != null) {
1911                 uss.mUnlockProgress.addListener(unlockListener);
1912             }
1913             t.traceEnd(); // updateStartedUserArrayStarting
1914 
1915             if (updateUmState) {
1916                 t.traceBegin("setUserState");
1917                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1918                 t.traceEnd();
1919             }
1920             t.traceBegin("updateConfigurationAndProfileIds");
1921             if (foreground) {
1922                 // Make sure the old user is no longer considering the display to be on.
1923                 mInjector.reportGlobalUsageEvent(UsageEvents.Event.SCREEN_NON_INTERACTIVE);
1924                 boolean userSwitchUiEnabled;
1925                 synchronized (mLock) {
1926                     mCurrentUserId = userId;
1927                     userSwitchUiEnabled = mUserSwitchUiEnabled;
1928                 }
1929                 mInjector.updateUserConfiguration();
1930                 // NOTE: updateProfileRelatedCaches() is called on both if and else parts, ideally
1931                 // it should be moved outside, but for now it's not as there are many calls to
1932                 // external components here afterwards
1933                 updateProfileRelatedCaches();
1934                 mInjector.getWindowManager().setCurrentUser(userId);
1935                 mInjector.reportCurWakefulnessUsageEvent();
1936                 if (userSwitchUiEnabled) {
1937                     mInjector.getWindowManager().setSwitchingUser(true);
1938                 }
1939 
1940             } else {
1941                 updateProfileRelatedCaches();
1942                 // We are starting a non-foreground user. They have already been added to the end
1943                 // of mUserLru, so we need to ensure that the foreground user isn't displaced.
1944                 addUserToUserLru(mCurrentUserId);
1945             }
1946             if (userStartMode == USER_START_MODE_BACKGROUND && !userInfo.isProfile()) {
1947                 scheduleStopOfBackgroundUser(userId);
1948             }
1949             t.traceEnd();
1950 
1951             // Make sure user is in the started state.  If it is currently
1952             // stopping, we need to knock that off.
1953             if (uss.state == UserState.STATE_STOPPING) {
1954                 t.traceBegin("updateStateStopping");
1955                 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
1956                 // so we can just fairly silently bring the user back from
1957                 // the almost-dead.
1958                 uss.setState(uss.lastState);
1959                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1960                 synchronized (mLock) {
1961                     updateStartedUserArrayLU();
1962                 }
1963                 needStart = true;
1964                 t.traceEnd();
1965             } else if (uss.state == UserState.STATE_SHUTDOWN) {
1966                 t.traceBegin("updateStateShutdown");
1967                 // This means ACTION_SHUTDOWN has been sent, so we will
1968                 // need to treat this as a new boot of the user.
1969                 uss.setState(UserState.STATE_BOOTING);
1970                 mInjector.getUserManagerInternal().setUserState(userId, uss.state);
1971                 synchronized (mLock) {
1972                     updateStartedUserArrayLU();
1973                 }
1974                 needStart = true;
1975                 t.traceEnd();
1976             }
1977 
1978             if (uss.state == UserState.STATE_BOOTING) {
1979                 t.traceBegin("updateStateBooting");
1980                 // Give user manager a chance to propagate user restrictions
1981                 // to other services and prepare app storage
1982                 mInjector.getUserManager().onBeforeStartUser(userId);
1983 
1984                 // Booting up a new user, need to tell system services about it.
1985                 // Note that this is on the same handler as scheduling of broadcasts,
1986                 // which is important because it needs to go first.
1987                 mHandler.sendMessage(mHandler.obtainMessage(USER_START_MSG, userId, NO_ARG2));
1988                 t.traceEnd();
1989             }
1990 
1991             t.traceBegin("sendMessages");
1992             if (foreground) {
1993                 mHandler.sendMessage(mHandler.obtainMessage(USER_CURRENT_MSG, userId, oldUserId));
1994                 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
1995                 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1996                 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
1997                         oldUserId, userId, uss));
1998                 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
1999                         oldUserId, userId, uss), getUserSwitchTimeoutMs());
2000             }
2001 
2002             if (userInfo.preCreated) {
2003                 needStart = false;
2004             }
2005 
2006             // In most cases, broadcast for the system user starting/started is sent by
2007             // ActivityManagerService#systemReady(). However on some HSUM devices (e.g. tablets)
2008             // the user switches from the system user to a secondary user while running
2009             // ActivityManagerService#systemReady(), thus broadcast is not sent for the system user.
2010             // Therefore we send the broadcast for the system user here as well in HSUM.
2011             // TODO(b/266158156): Improve/refactor the way broadcasts are sent for the system user
2012             // in HSUM. Ideally it'd be best to have one single place that sends this notification.
2013             final boolean isSystemUserInHeadlessMode = (userId == UserHandle.USER_SYSTEM)
2014                     && mInjector.isHeadlessSystemUserMode();
2015             if (needStart || isSystemUserInHeadlessMode) {
2016                 sendUserStartedBroadcast(userId, callingUid, callingPid);
2017             }
2018             t.traceEnd();
2019 
2020             if (foreground) {
2021                 t.traceBegin("moveUserToForeground");
2022                 moveUserToForeground(uss, userId);
2023                 t.traceEnd();
2024             } else {
2025                 t.traceBegin("finishUserBoot");
2026                 finishUserBoot(uss);
2027                 t.traceEnd();
2028             }
2029 
2030             if (needStart || isSystemUserInHeadlessMode) {
2031                 t.traceBegin("sendRestartBroadcast");
2032                 sendUserStartingBroadcast(userId, callingUid, callingPid);
2033                 t.traceEnd();
2034             }
2035         } finally {
2036             Binder.restoreCallingIdentity(ident);
2037         }
2038 
2039         return true;
2040     }
2041 
2042     /**
2043      * Start user, if it's not already running, and bring it to foreground.
2044      */
2045     void startUserInForeground(@UserIdInt int targetUserId) {
2046         if (android.multiuser.Flags.setPowerModeDuringUserSwitch()) {
2047             mInjector.setPerformancePowerMode(true);
2048         }
2049         boolean success = startUser(targetUserId, USER_START_MODE_FOREGROUND);
2050         if (!success) {
2051             mInjector.getWindowManager().setSwitchingUser(false);
2052             dismissUserSwitchDialog(this::endUserSwitch);
2053         }
2054     }
2055 
2056     boolean unlockUser(@UserIdInt int userId, @Nullable IProgressListener listener) {
2057         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "unlockUser");
2058         EventLog.writeEvent(EventLogTags.UC_UNLOCK_USER, userId);
2059         final long binderToken = Binder.clearCallingIdentity();
2060         try {
2061             return maybeUnlockUser(userId, listener);
2062         } finally {
2063             Binder.restoreCallingIdentity(binderToken);
2064         }
2065     }
2066 
2067     private static void notifyFinished(@UserIdInt int userId,
2068             @Nullable IProgressListener listener) {
2069         if (listener == null) return;
2070         try {
2071             listener.onFinished(userId, null);
2072         } catch (RemoteException ignored) {
2073         }
2074     }
2075 
2076     private boolean maybeUnlockUser(@UserIdInt int userId) {
2077         return maybeUnlockUser(userId, null);
2078     }
2079 
2080     /**
2081      * Tries to unlock the given user.
2082      * <p>
2083      * This will succeed only if the user's CE storage key is already unlocked or if the user
2084      * doesn't have a lockscreen credential set.
2085      */
2086     private boolean maybeUnlockUser(@UserIdInt int userId, @Nullable IProgressListener listener) {
2087 
2088         // We cannot allow users to be unlocked before PHASE_BOOT_COMPLETED, for two reasons.
2089         // First, emulated volumes aren't supposed to be used until then; StorageManagerService
2090         // assumes it can reset everything upon reaching PHASE_BOOT_COMPLETED.  Second, on some
2091         // devices the Weaver HAL needed to unlock the user's storage isn't available until sometime
2092         // shortly before PHASE_BOOT_COMPLETED.  The below logic enforces a consistent flow across
2093         // all devices, regardless of their Weaver implementation.
2094         //
2095         // Any unlocks that get delayed by this will be done by onBootComplete() instead.
2096         if (!mAllowUserUnlocking) {
2097             Slogf.i(TAG, "Not unlocking user %d yet because boot hasn't completed", userId);
2098             notifyFinished(userId, listener);
2099             return false;
2100         }
2101 
2102         UserState uss;
2103         if (!StorageManager.isCeStorageUnlocked(userId)) {
2104             // We always want to try to unlock CE storage, even if the user is not started yet.
2105             mLockPatternUtils.unlockUserKeyIfUnsecured(userId);
2106         }
2107         synchronized (mLock) {
2108             // Register the given listener to watch for unlock progress
2109             uss = mStartedUsers.get(userId);
2110             if (uss != null) {
2111                 uss.mUnlockProgress.addListener(listener);
2112             }
2113         }
2114         // Bail if user isn't actually running
2115         if (uss == null) {
2116             notifyFinished(userId, listener);
2117             return false;
2118         }
2119 
2120         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2121         t.traceBegin("finishUserUnlocking-" + userId);
2122         final boolean finishUserUnlockingResult = finishUserUnlocking(uss);
2123         t.traceEnd();
2124         if (!finishUserUnlockingResult) {
2125             notifyFinished(userId, listener);
2126             return false;
2127         }
2128 
2129         // We just unlocked a user, so let's now attempt to unlock any profiles under that user.
2130 
2131         // First, get list of userIds. Requires mLock, so we cannot make external calls, e.g. to UMS
2132         int[] userIds;
2133         synchronized (mLock) {
2134             userIds = new int[mStartedUsers.size()];
2135             for (int i = 0; i < userIds.length; i++) {
2136                 userIds[i] = mStartedUsers.keyAt(i);
2137             }
2138         }
2139         for (int testUserId : userIds) {
2140             final UserInfo parent = mInjector.getUserManager().getProfileParent(testUserId);
2141             if (parent != null && parent.id == userId && testUserId != userId) {
2142                 Slogf.d(TAG, "User " + testUserId + " (parent " + parent.id
2143                         + "): attempting unlock because parent was just unlocked");
2144                 maybeUnlockUser(testUserId);
2145             }
2146         }
2147 
2148         return true;
2149     }
2150 
2151     boolean switchUser(final int targetUserId) {
2152         enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId);
2153         EventLog.writeEvent(EventLogTags.UC_SWITCH_USER, targetUserId);
2154         int currentUserId = getCurrentUserId();
2155         UserInfo targetUserInfo = getUserInfo(targetUserId);
2156         boolean userSwitchUiEnabled;
2157         synchronized (mLock) {
2158             if (targetUserId == currentUserId && mTargetUserId == UserHandle.USER_NULL) {
2159                 Slogf.i(TAG, "user #" + targetUserId + " is already the current user");
2160                 return true;
2161             }
2162             if (targetUserInfo == null) {
2163                 Slogf.w(TAG, "No user info for user #" + targetUserId);
2164                 return false;
2165             }
2166             if (!targetUserInfo.supportsSwitchTo()) {
2167                 Slogf.w(TAG, "Cannot switch to User #" + targetUserId + ": not supported");
2168                 return false;
2169             }
2170             if (FactoryResetter.isFactoryResetting()) {
2171                 Slogf.w(TAG, "Cannot switch to User #" + targetUserId
2172                         + ": factory reset in progress");
2173                 return false;
2174             }
2175 
2176             if (!mInitialized) {
2177                 Slogf.e(TAG, "Cannot switch to User #" + targetUserId
2178                         + ": UserController not ready yet");
2179                 return false;
2180             }
2181             if (mTargetUserId != UserHandle.USER_NULL) {
2182                 Slogf.w(TAG, "There is already an ongoing user switch to User #" + mTargetUserId
2183                         + ". User #" + targetUserId + " will be added to the queue.");
2184                 mPendingTargetUserIds.offer(targetUserId);
2185                 return true;
2186             }
2187             mTargetUserId = targetUserId;
2188             userSwitchUiEnabled = mUserSwitchUiEnabled;
2189         }
2190         if (userSwitchUiEnabled) {
2191             UserInfo currentUserInfo = getUserInfo(currentUserId);
2192             Pair<UserInfo, UserInfo> userNames = new Pair<>(currentUserInfo, targetUserInfo);
2193             mUiHandler.removeMessages(START_USER_SWITCH_UI_MSG);
2194             mUiHandler.sendMessage(mUiHandler.obtainMessage(
2195                     START_USER_SWITCH_UI_MSG, userNames));
2196         } else {
2197             sendStartUserSwitchFgMessage(targetUserId);
2198         }
2199         return true;
2200     }
2201 
2202     private void sendStartUserSwitchFgMessage(int targetUserId) {
2203         mHandler.removeMessages(START_USER_SWITCH_FG_MSG);
2204         mHandler.sendMessage(mHandler.obtainMessage(START_USER_SWITCH_FG_MSG, targetUserId, 0));
2205     }
2206 
2207     private void dismissUserSwitchDialog(Runnable onDismissed) {
2208         mUiHandler.post(() -> mInjector.dismissUserSwitchingDialog(onDismissed));
2209     }
2210 
2211     private void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
2212         // The dialog will show and then initiate the user switch by calling startUserInForeground
2213         mInjector.showUserSwitchingDialog(fromToUserPair.first, fromToUserPair.second,
2214                 getSwitchingFromSystemUserMessageUnchecked(),
2215                 getSwitchingToSystemUserMessageUnchecked(),
2216                 /* onShown= */ () -> sendStartUserSwitchFgMessage(fromToUserPair.second.id));
2217     }
2218 
2219     private void dispatchForegroundProfileChanged(@UserIdInt int userId) {
2220         final int observerCount = mUserSwitchObservers.beginBroadcast();
2221         for (int i = 0; i < observerCount; i++) {
2222             try {
2223                 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
2224             } catch (RemoteException e) {
2225                 // Ignore
2226             }
2227         }
2228         mUserSwitchObservers.finishBroadcast();
2229     }
2230 
2231     /** Called on handler thread */
2232     @VisibleForTesting
2233     void dispatchUserSwitchComplete(@UserIdInt int oldUserId, @UserIdInt int newUserId) {
2234         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2235         t.traceBegin("dispatchUserSwitchComplete-" + newUserId);
2236         mInjector.getWindowManager().setSwitchingUser(false);
2237         final int observerCount = mUserSwitchObservers.beginBroadcast();
2238         for (int i = 0; i < observerCount; i++) {
2239             try {
2240                 t.traceBegin("onUserSwitchComplete-" + newUserId + " #" + i + " "
2241                         + mUserSwitchObservers.getBroadcastCookie(i));
2242                 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(newUserId);
2243                 t.traceEnd();
2244             } catch (RemoteException e) {
2245                 // Ignore
2246             }
2247         }
2248         mUserSwitchObservers.finishBroadcast();
2249         t.traceBegin("sendUserSwitchBroadcasts-" + oldUserId + "-" + newUserId);
2250         sendUserSwitchBroadcasts(oldUserId, newUserId);
2251         t.traceEnd();
2252         t.traceEnd();
2253 
2254         endUserSwitch();
2255     }
2256 
2257     private void endUserSwitch() {
2258         if (android.multiuser.Flags.setPowerModeDuringUserSwitch()) {
2259             mInjector.setPerformancePowerMode(false);
2260         }
2261         final int nextUserId;
2262         synchronized (mLock) {
2263             nextUserId = ObjectUtils.getOrElse(mPendingTargetUserIds.poll(), UserHandle.USER_NULL);
2264             mTargetUserId = UserHandle.USER_NULL;
2265         }
2266         if (nextUserId != UserHandle.USER_NULL) {
2267             switchUser(nextUserId);
2268         }
2269     }
2270 
2271     private void dispatchLockedBootComplete(@UserIdInt int userId) {
2272         final int observerCount = mUserSwitchObservers.beginBroadcast();
2273         for (int i = 0; i < observerCount; i++) {
2274             try {
2275                 mUserSwitchObservers.getBroadcastItem(i).onLockedBootComplete(userId);
2276             } catch (RemoteException e) {
2277                 // Ignore
2278             }
2279         }
2280         mUserSwitchObservers.finishBroadcast();
2281     }
2282 
2283     /**
2284      * Possibly stops the given full user (or its profile) when we switch out of it, if dictated
2285      * by policy.
2286      */
2287     private void stopUserOnSwitchIfEnforced(@UserIdInt int oldUserId) {
2288         // Never stop system user
2289         if (oldUserId == UserHandle.USER_SYSTEM) {
2290             return;
2291         }
2292         boolean hasRestriction =
2293                 hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, oldUserId);
2294         synchronized (mLock) {
2295             // If running in background is disabled or mStopUserOnSwitch mode, stop the user.
2296             if (hasRestriction || shouldStopUserOnSwitch()) {
2297                 Slogf.i(TAG, "Stopping user %d and its profiles on user switch", oldUserId);
2298                 stopUsersLU(oldUserId, /* allowDelayedLocking= */ false, null, null);
2299                 return;
2300             }
2301         }
2302 
2303         // We didn't need to stop the parent, but perhaps one of its profiles needs to be stopped.
2304         final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(
2305                 oldUserId, /* enabledOnly= */ false);
2306         final int count = profiles.size();
2307         for (int i = 0; i < count; i++) {
2308             final int profileUserId = profiles.get(i).id;
2309             if (hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND, profileUserId)) {
2310                 Slogf.i(TAG, "Stopping profile %d on user switch", profileUserId);
2311                 synchronized (mLock) {
2312                     stopUsersLU(profileUserId,
2313                             /* stopProfileRegardlessOfParent= */ false,
2314                             /* allowDelayedLocking= */ false, null, null);
2315                 }
2316             }
2317         }
2318     }
2319 
2320     /**
2321      * Possibly schedules the user to be stopped at a future point. To be used to stop background
2322      * users that haven't been actively used in a long time.
2323      * This is only intended for full users that are currently in the background.
2324      */
2325     private void scheduleStopOfBackgroundUser(@UserIdInt int oldUserId) {
2326         if (!android.multiuser.Flags.scheduleStopOfBackgroundUser()) {
2327             return;
2328         }
2329         final int delayUptimeSecs = mBackgroundUserScheduledStopTimeSecs;
2330         if (delayUptimeSecs <= 0 || UserManager.isVisibleBackgroundUsersEnabled()) {
2331             // Feature is not enabled on this device.
2332             return;
2333         }
2334         if (oldUserId == UserHandle.USER_SYSTEM) {
2335             // Never stop system user
2336             return;
2337         }
2338         if (oldUserId == mInjector.getUserManagerInternal().getMainUserId()) {
2339             // MainUser is currently special for things like Docking, so we'll exempt it for now.
2340             Slogf.i(TAG, "Exempting user %d from being stopped due to inactivity by virtue "
2341                     + "of it being the main user", oldUserId);
2342             return;
2343         }
2344         Slogf.d(TAG, "Scheduling to stop user %d in %d seconds", oldUserId, delayUptimeSecs);
2345         final int delayUptimeMs = delayUptimeSecs * 1000;
2346         final Object msgObj = oldUserId;
2347         mHandler.removeEqualMessages(SCHEDULED_STOP_BACKGROUND_USER_MSG, msgObj);
2348         mHandler.sendMessageDelayed(
2349                 mHandler.obtainMessage(SCHEDULED_STOP_BACKGROUND_USER_MSG, msgObj),
2350                 delayUptimeMs);
2351     }
2352 
2353     /**
2354      * Possibly stops the given full user due to it having been in the background for a long time.
2355      * There is no guarantee of stopping the user; it is done discretionarily.
2356      *
2357      * This should never be called for background visible users; devices that support this should
2358      * not use {@link #scheduleStopOfBackgroundUser(int)}.
2359      *
2360      * @param userIdInteger a full user to be stopped if it is still in the background
2361      */
2362     @VisibleForTesting
2363     void processScheduledStopOfBackgroundUser(Integer userIdInteger) {
2364         final int userId = userIdInteger;
2365         Slogf.d(TAG, "Considering stopping background user %d due to inactivity", userId);
2366         synchronized (mLock) {
2367             if (getCurrentOrTargetUserIdLU() == userId) {
2368                 return;
2369             }
2370             if (mPendingTargetUserIds.contains(userIdInteger)) {
2371                 // We'll soon want to switch to this user, so don't kill it now.
2372                 return;
2373             }
2374             Slogf.i(TAG, "Stopping background user %d due to inactivity", userId);
2375             stopUsersLU(userId, /* allowDelayedLocking= */ true, null, null);
2376         }
2377     }
2378 
2379     private void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
2380         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG);
2381         t.traceBegin("timeoutUserSwitch-" + oldUserId + "-to-" + newUserId);
2382         synchronized (mLock) {
2383             Slogf.e(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
2384             mTimeoutUserSwitchCallbacks = mCurWaitingUserSwitchCallbacks;
2385             mHandler.removeMessages(USER_SWITCH_CALLBACKS_TIMEOUT_MSG);
2386             sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2387             // Report observers that never called back (USER_SWITCH_CALLBACKS_TIMEOUT)
2388             mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_CALLBACKS_TIMEOUT_MSG,
2389                     oldUserId, newUserId), USER_SWITCH_CALLBACKS_TIMEOUT_MS);
2390         }
2391         t.traceEnd();
2392     }
2393 
2394     private void timeoutUserSwitchCallbacks(int oldUserId, int newUserId) {
2395         synchronized (mLock) {
2396             if (mTimeoutUserSwitchCallbacks != null && !mTimeoutUserSwitchCallbacks.isEmpty()) {
2397                 Slogf.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId
2398                         + ". Observers that didn't respond: " + mTimeoutUserSwitchCallbacks);
2399                 mTimeoutUserSwitchCallbacks = null;
2400             }
2401         }
2402     }
2403 
2404     @VisibleForTesting
2405     void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
2406         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2407         t.traceBegin("dispatchUserSwitch-" + oldUserId + "-to-" + newUserId);
2408 
2409         EventLog.writeEvent(EventLogTags.UC_DISPATCH_USER_SWITCH, oldUserId, newUserId);
2410 
2411         final int observerCount = mUserSwitchObservers.beginBroadcast();
2412         if (observerCount > 0) {
2413             for (int i = 0; i < observerCount; i++) {
2414                 final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
2415                 t.traceBegin("onBeforeUserSwitching-" + name);
2416                 try {
2417                     mUserSwitchObservers.getBroadcastItem(i).onBeforeUserSwitching(newUserId);
2418                 } catch (RemoteException e) {
2419                     // Ignore
2420                 } finally {
2421                     t.traceEnd();
2422                 }
2423             }
2424             final ArraySet<String> curWaitingUserSwitchCallbacks = new ArraySet<>();
2425             synchronized (mLock) {
2426                 uss.switching = true;
2427                 mCurWaitingUserSwitchCallbacks = curWaitingUserSwitchCallbacks;
2428             }
2429             final AtomicInteger waitingCallbacksCount = new AtomicInteger(observerCount);
2430             final long userSwitchTimeoutMs = getUserSwitchTimeoutMs();
2431             final long dispatchStartedTime = SystemClock.elapsedRealtime();
2432             for (int i = 0; i < observerCount; i++) {
2433                 final long dispatchStartedTimeForObserver = SystemClock.elapsedRealtime();
2434                 try {
2435                     // Prepend with unique prefix to guarantee that keys are unique
2436                     final String name = "#" + i + " " + mUserSwitchObservers.getBroadcastCookie(i);
2437                     synchronized (mLock) {
2438                         curWaitingUserSwitchCallbacks.add(name);
2439                     }
2440                     final IRemoteCallback callback = new IRemoteCallback.Stub() {
2441                         @Override
2442                         public void sendResult(Bundle data) throws RemoteException {
2443                             asyncTraceEnd("onUserSwitching-" + name, newUserId);
2444                             synchronized (mLock) {
2445                                 long delayForObserver = SystemClock.elapsedRealtime()
2446                                         - dispatchStartedTimeForObserver;
2447                                 if (delayForObserver > LONG_USER_SWITCH_OBSERVER_WARNING_TIME_MS) {
2448                                     Slogf.w(TAG, "User switch slowed down by observer " + name
2449                                             + ": result took " + delayForObserver
2450                                             + " ms to process.");
2451                                 }
2452 
2453                                 long totalDelay = SystemClock.elapsedRealtime()
2454                                         - dispatchStartedTime;
2455                                 if (totalDelay > userSwitchTimeoutMs) {
2456                                     Slogf.e(TAG, "User switch timeout: observer " + name
2457                                             + "'s result was received " + totalDelay
2458                                             + " ms after dispatchUserSwitch.");
2459                                 }
2460 
2461                                 curWaitingUserSwitchCallbacks.remove(name);
2462                                 // Continue switching if all callbacks have been notified and
2463                                 // user switching session is still valid
2464                                 if (waitingCallbacksCount.decrementAndGet() == 0
2465                                         && (curWaitingUserSwitchCallbacks
2466                                         == mCurWaitingUserSwitchCallbacks)) {
2467                                     sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2468                                 }
2469                             }
2470                         }
2471                     };
2472                     asyncTraceBegin("onUserSwitching-" + name, newUserId);
2473                     mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(newUserId, callback);
2474                 } catch (RemoteException e) {
2475                     // Ignore
2476                 }
2477             }
2478         } else {
2479             synchronized (mLock) {
2480                 sendContinueUserSwitchLU(uss, oldUserId, newUserId);
2481             }
2482         }
2483         mUserSwitchObservers.finishBroadcast();
2484         t.traceEnd(); // end dispatchUserSwitch-
2485     }
2486 
2487     @GuardedBy("mLock")
2488     private void sendContinueUserSwitchLU(UserState uss, int oldUserId, int newUserId) {
2489         TimingsTraceAndSlog t = new TimingsTraceAndSlog(TAG);
2490         t.traceBegin("sendContinueUserSwitchLU-" + oldUserId + "-to-" + newUserId);
2491         mCurWaitingUserSwitchCallbacks = null;
2492         mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
2493         mHandler.sendMessage(mHandler.obtainMessage(CONTINUE_USER_SWITCH_MSG,
2494                 oldUserId, newUserId, uss));
2495         t.traceEnd();
2496     }
2497 
2498     @VisibleForTesting
2499     void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
2500         final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
2501         t.traceBegin("continueUserSwitch-" + oldUserId + "-to-" + newUserId);
2502 
2503         EventLog.writeEvent(EventLogTags.UC_CONTINUE_USER_SWITCH, oldUserId, newUserId);
2504 
2505         // Do the keyguard dismiss and dismiss the user switching dialog later
2506         mHandler.removeMessages(COMPLETE_USER_SWITCH_MSG);
2507         mHandler.sendMessage(mHandler.obtainMessage(
2508                 COMPLETE_USER_SWITCH_MSG, oldUserId, newUserId));
2509 
2510         uss.switching = false;
2511         stopGuestOrEphemeralUserIfBackground(oldUserId);
2512         stopUserOnSwitchIfEnforced(oldUserId);
2513         scheduleStopOfBackgroundUser(oldUserId);
2514 
2515         t.traceEnd(); // end continueUserSwitch
2516     }
2517 
2518     @VisibleForTesting
2519     void completeUserSwitch(int oldUserId, int newUserId) {
2520         final Runnable sendUserSwitchCompleteMessage = () -> {
2521             mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
2522             mHandler.sendMessage(mHandler.obtainMessage(
2523                     REPORT_USER_SWITCH_COMPLETE_MSG, oldUserId, newUserId));
2524         };
2525         if (isUserSwitchUiEnabled()) {
2526             if (mInjector.getKeyguardManager().isDeviceSecure(newUserId)) {
2527                 this.showKeyguard(() -> dismissUserSwitchDialog(sendUserSwitchCompleteMessage));
2528             } else {
2529                 this.dismissKeyguard(() -> dismissUserSwitchDialog(sendUserSwitchCompleteMessage));
2530             }
2531         } else {
2532             sendUserSwitchCompleteMessage.run();
2533         }
2534     }
2535 
2536     protected void showKeyguard(Runnable runnable) {
2537         runWithTimeout(mInjector::showKeyguard, SHOW_KEYGUARD_TIMEOUT_MS, runnable, () -> {
2538             throw new RuntimeException(
2539                     "Keyguard is not shown in " + SHOW_KEYGUARD_TIMEOUT_MS + " ms.");
2540         }, "showKeyguard");
2541     }
2542 
2543     protected void dismissKeyguard(Runnable runnable) {
2544         runWithTimeout(mInjector::dismissKeyguard, DISMISS_KEYGUARD_TIMEOUT_MS, runnable, runnable,
2545                 "dismissKeyguard");
2546     }
2547 
2548     private void runWithTimeout(Consumer<Runnable> task, int timeoutMs, Runnable onSuccess,
2549             Runnable onTimeout, String traceMsg) {
2550         final AtomicInteger state = new AtomicInteger(0); // state = 0 (RUNNING)
2551 
2552         asyncTraceBegin(traceMsg, 0);
2553 
2554         mHandler.postDelayed(() -> {
2555             if (state.compareAndSet(0, 1)) { // state = 1 (TIMEOUT)
2556                 asyncTraceEnd(traceMsg, 0);
2557                 Slogf.w(TAG, "Timeout: %s did not finish in %d ms", traceMsg, timeoutMs);
2558                 onTimeout.run();
2559             }
2560         }, timeoutMs);
2561 
2562         task.accept(() -> {
2563             if (state.compareAndSet(0, 2)) { // state = 2 (SUCCESS)
2564                 asyncTraceEnd(traceMsg, 0);
2565                 onSuccess.run();
2566             }
2567         });
2568     }
2569 
2570     private void moveUserToForeground(UserState uss, int newUserId) {
2571         boolean homeInFront = mInjector.taskSupervisorSwitchUser(newUserId, uss);
2572         if (homeInFront) {
2573             mInjector.startHomeActivity(newUserId, "moveUserToForeground");
2574         } else {
2575             mInjector.taskSupervisorResumeFocusedStackTopActivity();
2576         }
2577         EventLogTags.writeAmSwitchUser(newUserId);
2578     }
2579 
2580     // The two methods sendUserStartedBroadcast() and sendUserStartingBroadcast()
2581     // could be merged for better reuse. However, the params they are calling broadcastIntent()
2582     // with are different - resultCode receiver, permissions, ordered, and userId, etc. Therefore,
2583     // we decided to keep two separate methods for better code readability/clarity.
2584     // TODO(b/266158156): Improve/refactor the way broadcasts are sent for the system user
2585     // in HSUM. Ideally it'd be best to have one single place that sends this notification.
2586     /** Sends {@code ACTION_USER_STARTED} broadcast. */
2587     void sendUserStartedBroadcast(@UserIdInt int userId, int callingUid, int callingPid) {
2588         if (userId == UserHandle.USER_SYSTEM) {
2589             synchronized (mLock) {
2590                 // Make sure that the broadcast is sent only once for the system user.
2591                 if (mIsBroadcastSentForSystemUserStarted) {
2592                     return;
2593                 }
2594                 mIsBroadcastSentForSystemUserStarted = true;
2595             }
2596         }
2597         final Intent intent = new Intent(Intent.ACTION_USER_STARTED);
2598         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2599                 | Intent.FLAG_RECEIVER_FOREGROUND);
2600         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2601         mInjector.broadcastIntent(intent, /* resolvedType= */ null, /* resultTo= */ null,
2602                 /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */ null,
2603                 /* requiredPermissions= */ null, AppOpsManager.OP_NONE, /* bOptions= */ null,
2604                 /* sticky= */ false, MY_PID, SYSTEM_UID,
2605                 callingUid, callingPid, userId);
2606     }
2607 
2608     /** Sends {@code ACTION_USER_STARTING} broadcast. */
2609     void sendUserStartingBroadcast(@UserIdInt int userId, int callingUid, int callingPid) {
2610         if (userId == UserHandle.USER_SYSTEM) {
2611             synchronized (mLock) {
2612                 // Make sure that the broadcast is sent only once for the system user.
2613                 if (mIsBroadcastSentForSystemUserStarting) {
2614                     return;
2615                 }
2616                 mIsBroadcastSentForSystemUserStarting = true;
2617             }
2618         }
2619         final Intent intent = new Intent(Intent.ACTION_USER_STARTING);
2620         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
2621         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
2622         mInjector.broadcastIntent(intent, /* resolvedType= */ null,
2623                 new IIntentReceiver.Stub() {
2624                     @Override
2625                     public void performReceive(Intent intent, int resultCode,
2626                             String data, Bundle extras, boolean ordered,
2627                             boolean sticky,
2628                             int sendingUser) throws RemoteException {
2629                     }
2630                 }, /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */ null,
2631                 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE, /* bOptions= */ null,
2632                 /* sticky= */ false, MY_PID, SYSTEM_UID,
2633                 callingUid, callingPid, UserHandle.USER_ALL);
2634     }
2635 
2636     void sendUserSwitchBroadcasts(int oldUserId, int newUserId) {
2637         final int callingUid = Binder.getCallingUid();
2638         final int callingPid = Binder.getCallingPid();
2639         final long ident = Binder.clearCallingIdentity();
2640         try {
2641             Intent intent;
2642             if (oldUserId >= 0) {
2643                 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
2644                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(oldUserId, false);
2645                 int count = profiles.size();
2646                 for (int i = 0; i < count; i++) {
2647                     int profileUserId = profiles.get(i).id;
2648                     intent = new Intent(Intent.ACTION_USER_BACKGROUND);
2649                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2650                             | Intent.FLAG_RECEIVER_FOREGROUND);
2651                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
2652                     // Also, add the UserHandle for mainline modules which can't use the @hide
2653                     // EXTRA_USER_HANDLE.
2654                     intent.putExtra(Intent.EXTRA_USER, UserHandle.of(profileUserId));
2655                     mInjector.broadcastIntent(intent,
2656                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
2657                             null, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
2658                             profileUserId);
2659                 }
2660             }
2661             if (newUserId >= 0) {
2662                 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
2663                 List<UserInfo> profiles = mInjector.getUserManager().getProfiles(newUserId, false);
2664                 int count = profiles.size();
2665                 for (int i = 0; i < count; i++) {
2666                     int profileUserId = profiles.get(i).id;
2667                     intent = new Intent(Intent.ACTION_USER_FOREGROUND);
2668                     intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2669                             | Intent.FLAG_RECEIVER_FOREGROUND);
2670                     intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
2671                     // Also, add the UserHandle for mainline modules which can't use the @hide
2672                     // EXTRA_USER_HANDLE.
2673                     intent.putExtra(Intent.EXTRA_USER, UserHandle.of(profileUserId));
2674                     mInjector.broadcastIntent(intent,
2675                             null, null, 0, null, null, null, AppOpsManager.OP_NONE,
2676                             null, false, MY_PID, SYSTEM_UID, callingUid, callingPid,
2677                             profileUserId);
2678                 }
2679                 intent = new Intent(Intent.ACTION_USER_SWITCHED);
2680                 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2681                         | Intent.FLAG_RECEIVER_FOREGROUND);
2682                 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
2683                 // Also, add the UserHandle for mainline modules which can't use the @hide
2684                 // EXTRA_USER_HANDLE.
2685                 intent.putExtra(Intent.EXTRA_USER, UserHandle.of(newUserId));
2686                 mInjector.broadcastIntent(intent,
2687                         null, null, 0, null, null,
2688                         new String[] {android.Manifest.permission.MANAGE_USERS},
2689                         AppOpsManager.OP_NONE, null, false, MY_PID, SYSTEM_UID, callingUid,
2690                         callingPid, UserHandle.USER_ALL);
2691             }
2692         } finally {
2693             Binder.restoreCallingIdentity(ident);
2694         }
2695     }
2696 
2697     /**
2698      * Broadcasts to the parent user when a profile is started+unlocked/stopped.
2699      * @param userId the id of the profile
2700      * @param parentId the id of the parent user
2701      * @param intentAction either ACTION_PROFILE_ACCESSIBLE or ACTION_PROFILE_INACCESSIBLE
2702      */
2703     private void broadcastProfileAccessibleStateChanged(@UserIdInt int userId,
2704             @UserIdInt int parentId,
2705             String intentAction) {
2706         final Intent intent = new Intent(intentAction);
2707         intent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
2708         intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
2709                 | Intent.FLAG_RECEIVER_FOREGROUND);
2710         mInjector.broadcastIntent(intent, /* resolvedType= */ null, /* resultTo= */
2711                 null, /* resultCode= */ 0, /* resultData= */ null, /* resultExtras= */
2712                 null, /* requiredPermissions= */ null, AppOpsManager.OP_NONE, /* bOptions= */
2713                 null, /* sticky= */ false, MY_PID, SYSTEM_UID,
2714                 Binder.getCallingUid(), Binder.getCallingPid(), parentId);
2715     }
2716 
2717     int handleIncomingUser(int callingPid, int callingUid, @UserIdInt int userId, boolean allowAll,
2718             int allowMode, String name, String callerPackage) {
2719         final int callingUserId = UserHandle.getUserId(callingUid);
2720         if (callingUserId == userId) {
2721             return userId;
2722         }
2723 
2724         // Note that we may be accessing mCurrentUserId outside of a lock...
2725         // shouldn't be a big deal, if this is being called outside
2726         // of a locked context there is intrinsically a race with
2727         // the value the caller will receive and someone else changing it.
2728         // We assume that USER_CURRENT_OR_SELF will use the current user; later
2729         // we will switch to the calling user if access to the current user fails.
2730         int targetUserId = unsafeConvertIncomingUser(userId);
2731 
2732         if (callingUid != 0 && callingUid != SYSTEM_UID) {
2733             final boolean allow;
2734             final boolean isSameProfileGroup = isSameProfileGroup(callingUserId, targetUserId);
2735             if (mInjector.isCallerRecents(callingUid) && isSameProfileGroup) {
2736                 // If the caller is Recents and the caller has ownership of the profile group,
2737                 // we then allow it to access its profiles.
2738                 allow = true;
2739             } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
2740                     callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
2741                 // If the caller has this permission, they always pass go.  And collect $200.
2742                 allow = true;
2743             } else if (allowMode == ALLOW_FULL_ONLY) {
2744                 // We require full access, sucks to be you.
2745                 allow = false;
2746             } else if (canInteractWithAcrossProfilesPermission(
2747                     allowMode, isSameProfileGroup, callingPid, callingUid, callerPackage)) {
2748                 allow = true;
2749             } else if (mInjector.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
2750                     callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
2751                 // If the caller does not have either permission, they are always doomed.
2752                 allow = false;
2753             } else if (allowMode == ALLOW_NON_FULL || allowMode == ALLOW_PROFILES_OR_NON_FULL) {
2754                 // We are blanket allowing non-full access, you lucky caller!
2755                 allow = true;
2756             } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
2757                 // We may or may not allow this depending on whether the two users are
2758                 // in the same profile.
2759                 allow = isSameProfileGroup;
2760             } else {
2761                 throw new IllegalArgumentException("Unknown mode: " + allowMode);
2762             }
2763             if (!allow) {
2764                 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
2765                     // In this case, they would like to just execute as their
2766                     // owner user instead of failing.
2767                     targetUserId = callingUserId;
2768                 } else {
2769                     StringBuilder builder = new StringBuilder(128);
2770                     builder.append("Permission Denial: ");
2771                     builder.append(name);
2772                     if (callerPackage != null) {
2773                         builder.append(" from ");
2774                         builder.append(callerPackage);
2775                     }
2776                     builder.append(" asks to run as user ");
2777                     builder.append(userId);
2778                     builder.append(" but is calling from uid ");
2779                     UserHandle.formatUid(builder, callingUid);
2780                     builder.append("; this requires ");
2781                     builder.append(INTERACT_ACROSS_USERS_FULL);
2782                     if (allowMode != ALLOW_FULL_ONLY) {
2783                         if (allowMode == ALLOW_NON_FULL
2784                                 || allowMode == ALLOW_PROFILES_OR_NON_FULL
2785                                 || (allowMode == ALLOW_NON_FULL_IN_PROFILE && isSameProfileGroup)) {
2786                             builder.append(" or ");
2787                             builder.append(INTERACT_ACROSS_USERS);
2788                         }
2789                         if (isSameProfileGroup && allowMode == ALLOW_PROFILES_OR_NON_FULL) {
2790                             builder.append(" or ");
2791                             builder.append(INTERACT_ACROSS_PROFILES);
2792                         }
2793                     }
2794                     String msg = builder.toString();
2795                     Slogf.w(TAG, msg);
2796                     throw new SecurityException(msg);
2797                 }
2798             }
2799         }
2800         if (!allowAll) {
2801             ensureNotSpecialUser(targetUserId);
2802         }
2803         // Check shell permission
2804         if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
2805             if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
2806                 throw new SecurityException("Shell does not have permission to access user "
2807                         + targetUserId + "\n " + Debug.getCallers(3));
2808             }
2809         }
2810         return targetUserId;
2811     }
2812 
2813     private boolean canInteractWithAcrossProfilesPermission(
2814             int allowMode, boolean isSameProfileGroup, int callingPid, int callingUid,
2815             String callingPackage) {
2816         if (allowMode != ALLOW_PROFILES_OR_NON_FULL) {
2817             return false;
2818         }
2819         if (!isSameProfileGroup) {
2820             return false;
2821         }
2822         return mInjector.checkPermissionForPreflight(INTERACT_ACROSS_PROFILES, callingPid,
2823                 callingUid, callingPackage);
2824     }
2825 
2826     int unsafeConvertIncomingUser(@UserIdInt int userId) {
2827         return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
2828                 ? getCurrentUserId(): userId;
2829     }
2830 
2831     void ensureNotSpecialUser(@UserIdInt int userId) {
2832         if (userId >= 0) {
2833             return;
2834         }
2835         throw new IllegalArgumentException("Call does not support special user #" + userId);
2836     }
2837 
2838     void registerUserSwitchObserver(IUserSwitchObserver observer, String name) {
2839         Objects.requireNonNull(name, "Observer name cannot be null");
2840         checkCallingPermission(INTERACT_ACROSS_USERS_FULL, "registerUserSwitchObserver");
2841         mUserSwitchObservers.register(observer, name);
2842     }
2843 
2844     void sendForegroundProfileChanged(@UserIdInt int userId) {
2845         mHandler.removeMessages(FOREGROUND_PROFILE_CHANGED_MSG);
2846         mHandler.obtainMessage(FOREGROUND_PROFILE_CHANGED_MSG, userId, 0).sendToTarget();
2847     }
2848 
2849     void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
2850         mUserSwitchObservers.unregister(observer);
2851     }
2852 
2853     UserState getStartedUserState(@UserIdInt int userId) {
2854         synchronized (mLock) {
2855             return mStartedUsers.get(userId);
2856         }
2857     }
2858 
2859     boolean hasStartedUserState(@UserIdInt int userId) {
2860         synchronized (mLock) {
2861             return mStartedUsers.get(userId) != null;
2862         }
2863     }
2864 
2865     @GuardedBy("mLock")
2866     private void updateStartedUserArrayLU() {
2867         int num = 0;
2868         for (int i = 0; i < mStartedUsers.size(); i++) {
2869             UserState uss = mStartedUsers.valueAt(i);
2870             // This list does not include stopping users.
2871             if (uss.state != UserState.STATE_STOPPING
2872                     && uss.state != UserState.STATE_SHUTDOWN) {
2873                 num++;
2874             }
2875         }
2876         mStartedUserArray = new int[num];
2877         num = 0;
2878         for (int i = 0; i < mStartedUsers.size(); i++) {
2879             UserState uss = mStartedUsers.valueAt(i);
2880             if (uss.state != UserState.STATE_STOPPING
2881                     && uss.state != UserState.STATE_SHUTDOWN) {
2882                 mStartedUserArray[num++] = mStartedUsers.keyAt(i);
2883             }
2884         }
2885     }
2886 
2887     @VisibleForTesting
2888     void setAllowUserUnlocking(boolean allowed) {
2889         mAllowUserUnlocking = allowed;
2890         if (DEBUG_MU) {
2891             Slogf.d(TAG, new Exception(), "setAllowUserUnlocking(%b)", allowed);
2892         }
2893     }
2894 
2895     void onBootComplete(IIntentReceiver resultTo) {
2896         // Now that PHASE_BOOT_COMPLETED has been reached, user unlocking is allowed.
2897         setAllowUserUnlocking(true);
2898 
2899         // Get a copy of mStartedUsers to use outside of lock.
2900         SparseArray<UserState> startedUsers;
2901         synchronized (mLock) {
2902             startedUsers = mStartedUsers.clone();
2903         }
2904         // In non-headless system user mode, call finishUserBoot() to transition the system user
2905         // from the BOOTING state to RUNNING_LOCKED, then to RUNNING_UNLOCKED if possible.
2906         //
2907         // In headless system user mode, additional users may have been started, and all users
2908         // (including the system user) that ever get started are started explicitly.  In this case,
2909         // we should *not* transition users out of the BOOTING state using finishUserBoot(), as that
2910         // doesn't handle issuing the needed onUserStarting() call, and it would just race with an
2911         // explicit start anyway.  We do, however, need to send the "locked boot complete" broadcast
2912         // as that got skipped earlier due to the *device* boot not being complete yet.
2913         // We also need to try to unlock all started users, since until now explicit user starts
2914         // didn't proceed to unlocking, due to it being too early in the device boot.
2915         //
2916         // USER_SYSTEM must be processed first.  It will be first in the array, as its ID is lowest.
2917         Preconditions.checkArgument(startedUsers.keyAt(0) == UserHandle.USER_SYSTEM);
2918         for (int i = 0; i < startedUsers.size(); i++) {
2919             int userId = startedUsers.keyAt(i);
2920             UserState uss = startedUsers.valueAt(i);
2921             if (!mInjector.isHeadlessSystemUserMode()) {
2922                 finishUserBoot(uss, resultTo);
2923             } else {
2924                 sendLockedBootCompletedBroadcast(resultTo, userId);
2925                 maybeUnlockUser(userId);
2926             }
2927         }
2928     }
2929 
2930     void onSystemReady() {
2931         if (DEBUG_MU) {
2932             Slogf.d(TAG, "onSystemReady()");
2933 
2934         }
2935         mInjector.getUserManagerInternal().addUserLifecycleListener(mUserLifecycleListener);
2936         updateProfileRelatedCaches();
2937         mInjector.reportCurWakefulnessUsageEvent();
2938     }
2939 
2940     // TODO(b/266158156): remove this method if initial system user boot logic is refactored?
2941     void onSystemUserStarting() {
2942         if (!mInjector.isHeadlessSystemUserMode()) {
2943             // Don't need to call on HSUM because it will be called when the system user is
2944             // restarted on background
2945             mInjector.onUserStarting(UserHandle.USER_SYSTEM);
2946             mInjector.onSystemUserVisibilityChanged(/* visible= */ true);
2947         }
2948     }
2949 
2950     /**
2951      * Refreshes the internal caches related to user profiles.
2952      *
2953      * <p>It's called every time a user is started.
2954      */
2955     private void updateProfileRelatedCaches() {
2956         final List<UserInfo> profiles = mInjector.getUserManager().getProfiles(getCurrentUserId(),
2957                 /* enabledOnly= */ false);
2958         int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
2959         for (int i = 0; i < currentProfileIds.length; i++) {
2960             currentProfileIds[i] = profiles.get(i).id;
2961         }
2962         final List<UserInfo> users = mInjector.getUserManager().getUsers(false);
2963         synchronized (mLock) {
2964             mCurrentProfileIds = currentProfileIds;
2965 
2966             mUserProfileGroupIds.clear();
2967             for (int i = 0; i < users.size(); i++) {
2968                 UserInfo user = users.get(i);
2969                 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
2970                     mUserProfileGroupIds.put(user.id, user.profileGroupId);
2971                 }
2972             }
2973         }
2974     }
2975 
2976     int[] getStartedUserArray() {
2977         synchronized (mLock) {
2978             return mStartedUserArray;
2979         }
2980     }
2981 
2982     boolean isUserRunning(@UserIdInt int userId, int flags) {
2983         UserState state = getStartedUserState(userId);
2984         if (state == null) {
2985             return false;
2986         }
2987         if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
2988             return true;
2989         }
2990         if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
2991             switch (state.state) {
2992                 case UserState.STATE_BOOTING:
2993                 case UserState.STATE_RUNNING_LOCKED:
2994                     return true;
2995                 default:
2996                     return false;
2997             }
2998         }
2999         if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
3000             switch (state.state) {
3001                 case UserState.STATE_RUNNING_UNLOCKING:
3002                 case UserState.STATE_RUNNING_UNLOCKED:
3003                     return true;
3004                 // In the stopping/shutdown state, return unlock state of the user's CE storage.
3005                 case UserState.STATE_STOPPING:
3006                 case UserState.STATE_SHUTDOWN:
3007                     return StorageManager.isCeStorageUnlocked(userId);
3008                 default:
3009                     return false;
3010             }
3011         }
3012         if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
3013             switch (state.state) {
3014                 case UserState.STATE_RUNNING_UNLOCKED:
3015                     return true;
3016                 // In the stopping/shutdown state, return unlock state of the user's CE storage.
3017                 case UserState.STATE_STOPPING:
3018                 case UserState.STATE_SHUTDOWN:
3019                     return StorageManager.isCeStorageUnlocked(userId);
3020                 default:
3021                     return false;
3022             }
3023         }
3024 
3025         return state.state != UserState.STATE_STOPPING && state.state != UserState.STATE_SHUTDOWN;
3026     }
3027 
3028     /**
3029      * Check if system user is already started. Unlike other user, system user is in STATE_BOOTING
3030      * even if it is not explicitly started. So isUserRunning cannot give the right state
3031      * to check if system user is started or not.
3032      * @return true if system user is started.
3033      */
3034     boolean isSystemUserStarted() {
3035         synchronized (mLock) {
3036             UserState uss = mStartedUsers.get(UserHandle.USER_SYSTEM);
3037             if (uss == null) {
3038                 return false;
3039             }
3040             return uss.state == UserState.STATE_RUNNING_LOCKED
3041                 || uss.state == UserState.STATE_RUNNING_UNLOCKING
3042                 || uss.state == UserState.STATE_RUNNING_UNLOCKED;
3043         }
3044     }
3045 
3046     private void checkGetCurrentUserPermissions() {
3047         if ((mInjector.checkCallingPermission(INTERACT_ACROSS_USERS)
3048                 != PackageManager.PERMISSION_GRANTED) && (
3049                 mInjector.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
3050                         != PackageManager.PERMISSION_GRANTED)) {
3051             String msg = "Permission Denial: getCurrentUser() from pid="
3052                     + Binder.getCallingPid()
3053                     + ", uid=" + Binder.getCallingUid()
3054                     + " requires " + INTERACT_ACROSS_USERS;
3055             Slogf.w(TAG, msg);
3056             throw new SecurityException(msg);
3057         }
3058     }
3059 
3060     UserInfo getCurrentUser() {
3061         checkGetCurrentUserPermissions();
3062 
3063         // Optimization - if there is no pending user switch, return user for current id
3064         // (no need to acquire lock because mTargetUserId and mCurrentUserId are volatile)
3065         if (mTargetUserId == UserHandle.USER_NULL) {
3066             return getUserInfo(mCurrentUserId);
3067         }
3068         synchronized (mLock) {
3069             return getCurrentUserLU();
3070         }
3071     }
3072 
3073     /**
3074      * Gets the current user id, but checking that caller has the proper permissions.
3075      */
3076     int getCurrentUserIdChecked() {
3077         checkGetCurrentUserPermissions();
3078 
3079         // Optimization - if there is no pending user switch, return current id
3080         // (no need to acquire lock because mTargetUserId and mCurrentUserId are volatile)
3081         if (mTargetUserId == UserHandle.USER_NULL) {
3082             return mCurrentUserId;
3083         }
3084         return getCurrentOrTargetUserId();
3085     }
3086 
3087     @GuardedBy("mLock")
3088     private UserInfo getCurrentUserLU() {
3089         int userId = getCurrentOrTargetUserIdLU();
3090         return getUserInfo(userId);
3091     }
3092 
3093     int getCurrentOrTargetUserId() {
3094         synchronized (mLock) {
3095             return getCurrentOrTargetUserIdLU();
3096         }
3097     }
3098 
3099     @GuardedBy("mLock")
3100     private int getCurrentOrTargetUserIdLU() {
3101         return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
3102     }
3103 
3104     Pair<Integer, Integer> getCurrentAndTargetUserIds() {
3105         synchronized (mLock) {
3106             return new Pair<>(mCurrentUserId, mTargetUserId);
3107         }
3108     }
3109 
3110     @GuardedBy("mLock")
3111     private int getCurrentUserIdLU() {
3112         return mCurrentUserId;
3113     }
3114 
3115     int getCurrentUserId() {
3116         synchronized (mLock) {
3117             return mCurrentUserId;
3118         }
3119     }
3120 
3121     @GuardedBy("mLock")
3122     private boolean isCurrentUserLU(@UserIdInt int userId) {
3123         return userId == getCurrentOrTargetUserIdLU();
3124     }
3125 
3126     /** Returns whether the user is always-visible (such as a communal profile). */
3127     private boolean isAlwaysVisibleUser(@UserIdInt int userId) {
3128         final UserProperties properties = getUserProperties(userId);
3129         return properties != null && properties.getAlwaysVisible();
3130     }
3131 
3132     int[] getUsers() {
3133         UserManagerService ums = mInjector.getUserManager();
3134         return ums != null ? ums.getUserIds() : new int[] { 0 };
3135     }
3136 
3137     private UserInfo getUserInfo(@UserIdInt int userId) {
3138         return mInjector.getUserManager().getUserInfo(userId);
3139     }
3140 
3141     private @Nullable UserProperties getUserProperties(@UserIdInt int userId) {
3142         return mInjector.getUserManagerInternal().getUserProperties(userId);
3143     }
3144 
3145     int[] getUserIds() {
3146         return mInjector.getUserManager().getUserIds();
3147     }
3148 
3149     /**
3150      * If {@code userId} is {@link UserHandle#USER_ALL}, then return an array with all running user
3151      * IDs. Otherwise return an array whose only element is the given user id.
3152      *
3153      * It doesn't handle other special user IDs such as {@link UserHandle#USER_CURRENT}.
3154      */
3155     int[] expandUserId(@UserIdInt int userId) {
3156         if (userId != UserHandle.USER_ALL) {
3157             return new int[] {userId};
3158         } else {
3159             return getUsers();
3160         }
3161     }
3162 
3163     boolean exists(@UserIdInt int userId) {
3164         return mInjector.getUserManager().exists(userId);
3165     }
3166 
3167     private void checkCallingPermission(String permission, String methodName) {
3168         checkCallingHasOneOfThosePermissions(methodName, permission);
3169     }
3170 
3171     private void checkCallingHasOneOfThosePermissions(String methodName, String...permissions) {
3172         for (String permission : permissions) {
3173             if (mInjector.checkCallingPermission(permission) == PackageManager.PERMISSION_GRANTED) {
3174                 return;
3175             }
3176         }
3177         String msg = "Permission denial: " + methodName
3178                 + "() from pid=" + Binder.getCallingPid()
3179                 + ", uid=" + Binder.getCallingUid()
3180                 + " requires "
3181                 + (permissions.length == 1
3182                         ? permissions[0]
3183                         : "one of " + Arrays.toString(permissions));
3184         Slogf.w(TAG, msg);
3185         throw new SecurityException(msg);
3186     }
3187 
3188     private void enforceShellRestriction(String restriction, @UserIdInt int userId) {
3189         if (Binder.getCallingUid() == SHELL_UID) {
3190             if (userId < 0 || hasUserRestriction(restriction, userId)) {
3191                 throw new SecurityException("Shell does not have permission to access user "
3192                         + userId);
3193             }
3194         }
3195     }
3196 
3197     boolean hasUserRestriction(String restriction, @UserIdInt int userId) {
3198         return mInjector.getUserManager().hasUserRestriction(restriction, userId);
3199     }
3200 
3201     /** Returns whether the two users are in the same profile group. */
3202     boolean isSameProfileGroup(int callingUserId, int targetUserId) {
3203         if (callingUserId == targetUserId) {
3204             return true;
3205         }
3206         synchronized (mLock) {
3207             int callingProfile = mUserProfileGroupIds.get(callingUserId,
3208                     UserInfo.NO_PROFILE_GROUP_ID);
3209             int targetProfile = mUserProfileGroupIds.get(targetUserId,
3210                     UserInfo.NO_PROFILE_GROUP_ID);
3211             return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
3212                     && callingProfile == targetProfile;
3213         }
3214     }
3215 
3216     boolean isUserOrItsParentRunning(@UserIdInt int userId) {
3217         synchronized (mLock) {
3218             if (isUserRunning(userId, 0)) {
3219                 return true;
3220             }
3221             final int parentUserId = mUserProfileGroupIds.get(userId, UserInfo.NO_PROFILE_GROUP_ID);
3222             if (parentUserId == UserInfo.NO_PROFILE_GROUP_ID) {
3223                 return false;
3224             }
3225             return isUserRunning(parentUserId, 0);
3226         }
3227     }
3228 
3229     boolean isCurrentProfile(@UserIdInt int userId) {
3230         synchronized (mLock) {
3231             return ArrayUtils.contains(mCurrentProfileIds, userId);
3232         }
3233     }
3234 
3235     int[] getCurrentProfileIds() {
3236         synchronized (mLock) {
3237             return mCurrentProfileIds;
3238         }
3239     }
3240 
3241     private void onUserAdded(UserInfo user) {
3242         if (!user.isProfile()) {
3243             return;
3244         }
3245         synchronized (mLock) {
3246             if (user.profileGroupId == mCurrentUserId) {
3247                 mCurrentProfileIds = ArrayUtils.appendInt(mCurrentProfileIds, user.id);
3248             }
3249             if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
3250                 mUserProfileGroupIds.put(user.id, user.profileGroupId);
3251             }
3252         }
3253     }
3254 
3255     void onUserRemoved(@UserIdInt int userId) {
3256         synchronized (mLock) {
3257             int size = mUserProfileGroupIds.size();
3258             for (int i = size - 1; i >= 0; i--) {
3259                 if (mUserProfileGroupIds.keyAt(i) == userId
3260                         || mUserProfileGroupIds.valueAt(i) == userId) {
3261                     mUserProfileGroupIds.removeAt(i);
3262 
3263                 }
3264             }
3265             mCurrentProfileIds = ArrayUtils.removeInt(mCurrentProfileIds, userId);
3266         }
3267     }
3268 
3269     /**
3270      * Returns whether the given user requires credential entry at this time. This is used to
3271      * intercept activity launches for apps corresponding to locked profiles due to separate
3272      * challenge being triggered or when the profile user is yet to be unlocked.
3273      */
3274     protected boolean shouldConfirmCredentials(@UserIdInt int userId) {
3275         if (getStartedUserState(userId) == null) {
3276             return false;
3277         }
3278         final UserProperties properties = getUserProperties(userId);
3279         if (properties == null || !properties.isCredentialShareableWithParent()) {
3280             return false;
3281         }
3282         if (mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
3283             final KeyguardManager km = mInjector.getKeyguardManager();
3284             return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
3285         } else {
3286             // For unified challenge, need to confirm credential if user is RUNNING_LOCKED.
3287             return isUserRunning(userId, ActivityManager.FLAG_AND_LOCKED);
3288         }
3289     }
3290 
3291     boolean isLockScreenDisabled(@UserIdInt int userId) {
3292         return mLockPatternUtils.isLockScreenDisabled(userId);
3293     }
3294 
3295     void setSwitchingFromSystemUserMessage(String switchingFromSystemUserMessage) {
3296         synchronized (mLock) {
3297             mSwitchingFromSystemUserMessage = switchingFromSystemUserMessage;
3298         }
3299     }
3300 
3301     void setSwitchingToSystemUserMessage(String switchingToSystemUserMessage) {
3302         synchronized (mLock) {
3303             mSwitchingToSystemUserMessage = switchingToSystemUserMessage;
3304         }
3305     }
3306 
3307     // Called by AMS, must check permission
3308     String getSwitchingFromSystemUserMessage() {
3309         checkHasManageUsersPermission("getSwitchingFromSystemUserMessage()");
3310 
3311         return getSwitchingFromSystemUserMessageUnchecked();
3312     }
3313 
3314     // Called by AMS, must check permission
3315     String getSwitchingToSystemUserMessage() {
3316         checkHasManageUsersPermission("getSwitchingToSystemUserMessage()");
3317 
3318         return getSwitchingToSystemUserMessageUnchecked();
3319     }
3320 
3321     private String getSwitchingFromSystemUserMessageUnchecked() {
3322         synchronized (mLock) {
3323             return mSwitchingFromSystemUserMessage;
3324         }
3325     }
3326 
3327     private String getSwitchingToSystemUserMessageUnchecked() {
3328         synchronized (mLock) {
3329             return mSwitchingToSystemUserMessage;
3330         }
3331     }
3332 
3333     private void checkHasManageUsersPermission(String operation) {
3334         if (mInjector.checkCallingPermission(
3335                 android.Manifest.permission.MANAGE_USERS) == PackageManager.PERMISSION_DENIED) {
3336             throw new SecurityException(
3337                     "You need MANAGE_USERS permission to call " + operation);
3338         }
3339     }
3340 
3341     void dumpDebug(ProtoOutputStream proto, long fieldId) {
3342         synchronized (mLock) {
3343             long token = proto.start(fieldId);
3344             for (int i = 0; i < mStartedUsers.size(); i++) {
3345                 UserState uss = mStartedUsers.valueAt(i);
3346                 final long uToken = proto.start(UserControllerProto.STARTED_USERS);
3347                 proto.write(UserControllerProto.User.ID, uss.mHandle.getIdentifier());
3348                 uss.dumpDebug(proto, UserControllerProto.User.STATE);
3349                 proto.end(uToken);
3350             }
3351             for (int i = 0; i < mStartedUserArray.length; i++) {
3352                 proto.write(UserControllerProto.STARTED_USER_ARRAY, mStartedUserArray[i]);
3353             }
3354             for (int i = 0; i < mUserLru.size(); i++) {
3355                 proto.write(UserControllerProto.USER_LRU, mUserLru.get(i));
3356             }
3357             if (mUserProfileGroupIds.size() > 0) {
3358                 for (int i = 0; i < mUserProfileGroupIds.size(); i++) {
3359                     final long uToken = proto.start(UserControllerProto.USER_PROFILE_GROUP_IDS);
3360                     proto.write(UserControllerProto.UserProfile.USER,
3361                             mUserProfileGroupIds.keyAt(i));
3362                     proto.write(UserControllerProto.UserProfile.PROFILE,
3363                             mUserProfileGroupIds.valueAt(i));
3364                     proto.end(uToken);
3365                 }
3366             }
3367             proto.write(UserControllerProto.CURRENT_USER, mCurrentUserId);
3368             for (int i = 0; i < mCurrentProfileIds.length; i++) {
3369                 proto.write(UserControllerProto.CURRENT_PROFILES, mCurrentProfileIds[i]);
3370             }
3371             proto.end(token);
3372         }
3373     }
3374 
3375     void dump(PrintWriter pw) {
3376         synchronized (mLock) {
3377             pw.println("  mStartedUsers:");
3378             for (int i = 0; i < mStartedUsers.size(); i++) {
3379                 UserState uss = mStartedUsers.valueAt(i);
3380                 pw.print("    User #");
3381                 pw.print(uss.mHandle.getIdentifier());
3382                 pw.print(": ");
3383                 uss.dump("", pw);
3384             }
3385             pw.print("  mStartedUserArray: [");
3386             for (int i = 0; i < mStartedUserArray.length; i++) {
3387                 if (i > 0)
3388                     pw.print(", ");
3389                 pw.print(mStartedUserArray[i]);
3390             }
3391             pw.println("]");
3392             pw.print("  mUserLru: [");
3393             for (int i = 0; i < mUserLru.size(); i++) {
3394                 if (i > 0)
3395                     pw.print(", ");
3396                 pw.print(mUserLru.get(i));
3397             }
3398             pw.println("]");
3399             if (mUserProfileGroupIds.size() > 0) {
3400                 pw.println("  mUserProfileGroupIds:");
3401                 for (int i=0; i< mUserProfileGroupIds.size(); i++) {
3402                     pw.print("    User #");
3403                     pw.print(mUserProfileGroupIds.keyAt(i));
3404                     pw.print(" -> profile #");
3405                     pw.println(mUserProfileGroupIds.valueAt(i));
3406                 }
3407             }
3408             pw.println("  mCurrentProfileIds:" + Arrays.toString(mCurrentProfileIds));
3409             pw.println("  mCurrentUserId:" + mCurrentUserId);
3410             pw.println("  mTargetUserId:" + mTargetUserId);
3411             pw.println("  mLastActiveUsersForDelayedLocking:" + mLastActiveUsersForDelayedLocking);
3412             pw.println("  mDelayUserDataLocking:" + mDelayUserDataLocking);
3413             pw.println("  mAllowUserUnlocking:" + mAllowUserUnlocking);
3414             pw.println("  shouldStopUserOnSwitch():" + shouldStopUserOnSwitch());
3415             pw.println("  mStopUserOnSwitch:" + mStopUserOnSwitch);
3416             pw.println("  mMaxRunningUsers:" + mMaxRunningUsers);
3417             pw.println("  mBackgroundUserScheduledStopTimeSecs:"
3418                     + mBackgroundUserScheduledStopTimeSecs);
3419             pw.println("  mUserSwitchUiEnabled:" + mUserSwitchUiEnabled);
3420             pw.println("  mInitialized:" + mInitialized);
3421             pw.println("  mIsBroadcastSentForSystemUserStarted:"
3422                     + mIsBroadcastSentForSystemUserStarted);
3423             pw.println("  mIsBroadcastSentForSystemUserStarting:"
3424                     + mIsBroadcastSentForSystemUserStarting);
3425             if (mSwitchingFromSystemUserMessage != null) {
3426                 pw.println("  mSwitchingFromSystemUserMessage: " + mSwitchingFromSystemUserMessage);
3427             }
3428             if (mSwitchingToSystemUserMessage != null) {
3429                 pw.println("  mSwitchingToSystemUserMessage: " + mSwitchingToSystemUserMessage);
3430             }
3431             pw.println("  mLastUserUnlockingUptime: " + mLastUserUnlockingUptime);
3432         }
3433     }
3434 
3435     @Override
3436     public boolean handleMessage(Message msg) {
3437         switch (msg.what) {
3438             case START_USER_SWITCH_FG_MSG:
3439                 logUserJourneyBegin(msg.arg1, USER_JOURNEY_USER_SWITCH_FG);
3440                 startUserInForeground(msg.arg1);
3441                 break;
3442             case REPORT_USER_SWITCH_MSG:
3443                 dispatchUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3444                 break;
3445             case CONTINUE_USER_SWITCH_MSG:
3446                 continueUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3447                 break;
3448             case USER_SWITCH_TIMEOUT_MSG:
3449                 timeoutUserSwitch((UserState) msg.obj, msg.arg1, msg.arg2);
3450                 break;
3451             case USER_SWITCH_CALLBACKS_TIMEOUT_MSG:
3452                 timeoutUserSwitchCallbacks(msg.arg1, msg.arg2);
3453                 break;
3454             case START_PROFILES_MSG:
3455                 startProfiles();
3456                 break;
3457             case USER_START_MSG:
3458                 mInjector.batteryStatsServiceNoteEvent(
3459                         BatteryStats.HistoryItem.EVENT_USER_RUNNING_START,
3460                         Integer.toString(msg.arg1), msg.arg1);
3461                 logUserJourneyBegin(msg.arg1, USER_JOURNEY_USER_START);
3462 
3463                 mInjector.onUserStarting(/* userId= */ msg.arg1);
3464                 scheduleOnUserCompletedEvent(msg.arg1,
3465                         UserCompletedEventType.EVENT_TYPE_USER_STARTING,
3466                         USER_COMPLETED_EVENT_DELAY_MS);
3467 
3468                 mInjector.getUserJourneyLogger().logUserJourneyFinish(-1 , getUserInfo(msg.arg1),
3469                         USER_JOURNEY_USER_START);
3470                 break;
3471             case USER_UNLOCK_MSG:
3472                 final int userId = msg.arg1;
3473                 mInjector.getSystemServiceManager().onUserUnlocking(userId);
3474                 // Loads recents on a worker thread that allows disk I/O
3475                 FgThread.getHandler().post(() -> {
3476                     mInjector.loadUserRecents(userId);
3477                 });
3478 
3479                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3480                         USER_LIFECYCLE_EVENT_UNLOCKING_USER, EVENT_STATE_FINISH);
3481                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3482                         USER_LIFECYCLE_EVENT_UNLOCKED_USER, EVENT_STATE_BEGIN);
3483 
3484                 final TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3485                 t.traceBegin("finishUserUnlocked-" + userId);
3486                 finishUserUnlocked((UserState) msg.obj);
3487                 t.traceEnd();
3488                 break;
3489             case USER_UNLOCKED_MSG:
3490                 mInjector.getSystemServiceManager().onUserUnlocked(msg.arg1);
3491                 scheduleOnUserCompletedEvent(msg.arg1,
3492                         UserCompletedEventType.EVENT_TYPE_USER_UNLOCKED,
3493                         // If it's the foreground user, we wait longer to let it fully load.
3494                         // Else, there's nothing specific to wait for, so we basically just proceed.
3495                         // (No need to acquire lock to read mCurrentUserId since it is volatile.)
3496                         // TODO: Find something to wait for in the case of a profile.
3497                         mCurrentUserId == msg.arg1 ? USER_COMPLETED_EVENT_DELAY_MS : 1000);
3498                 mInjector.getUserJourneyLogger().logUserLifecycleEvent(msg.arg1,
3499                         USER_LIFECYCLE_EVENT_UNLOCKED_USER, EVENT_STATE_FINISH);
3500                 // Unlocking user is not a journey no need to clear sessionId
3501                 break;
3502             case USER_CURRENT_MSG:
3503                 mInjector.batteryStatsServiceNoteEvent(
3504                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_FINISH,
3505                         Integer.toString(msg.arg2), msg.arg2);
3506                 mInjector.batteryStatsServiceNoteEvent(
3507                         BatteryStats.HistoryItem.EVENT_USER_FOREGROUND_START,
3508                         Integer.toString(msg.arg1), msg.arg1);
3509 
3510                 mInjector.getSystemServiceManager().onUserSwitching(msg.arg2, msg.arg1);
3511                 scheduleOnUserCompletedEvent(msg.arg1,
3512                         UserCompletedEventType.EVENT_TYPE_USER_SWITCHING,
3513                         USER_COMPLETED_EVENT_DELAY_MS);
3514                 break;
3515             case USER_COMPLETED_EVENT_MSG:
3516                 reportOnUserCompletedEvent((Integer) msg.obj);
3517                 break;
3518             case FOREGROUND_PROFILE_CHANGED_MSG:
3519                 dispatchForegroundProfileChanged(msg.arg1);
3520                 break;
3521             case REPORT_USER_SWITCH_COMPLETE_MSG:
3522                 dispatchUserSwitchComplete(msg.arg1, msg.arg2);
3523                 UserJourneySession session = mInjector.getUserJourneyLogger()
3524                         .logUserSwitchJourneyFinish(msg.arg1, getUserInfo(msg.arg2));
3525                 if (session != null) {
3526                     mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, session);
3527                 }
3528                 break;
3529             case REPORT_LOCKED_BOOT_COMPLETE_MSG:
3530                 dispatchLockedBootComplete(msg.arg1);
3531                 break;
3532             case START_USER_SWITCH_UI_MSG:
3533                 final Pair<UserInfo, UserInfo> fromToUserPair = (Pair<UserInfo, UserInfo>) msg.obj;
3534                 logUserJourneyBegin(fromToUserPair.second.id, USER_JOURNEY_USER_SWITCH_UI);
3535                 showUserSwitchDialog(fromToUserPair);
3536                 break;
3537             case CLEAR_USER_JOURNEY_SESSION_MSG:
3538                 mInjector.getUserJourneyLogger()
3539                         .finishAndClearIncompleteUserJourney(msg.arg1, msg.arg2);
3540                 mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, msg.obj);
3541                 break;
3542             case COMPLETE_USER_SWITCH_MSG:
3543                 completeUserSwitch(msg.arg1, msg.arg2);
3544                 break;
3545             case SCHEDULED_STOP_BACKGROUND_USER_MSG:
3546                 processScheduledStopOfBackgroundUser((Integer) msg.obj);
3547                 break;
3548         }
3549         return false;
3550     }
3551 
3552     /**
3553      * Schedules {@link SystemServiceManager#onUserCompletedEvent()} with the given
3554      * {@link UserCompletedEventType} event, which will be combined with any other events for that
3555      * user already scheduled.
3556      * If it isn't rescheduled first, it will fire after a delayMs delay.
3557      *
3558      * @param eventType event type flags from {@link UserCompletedEventType} to append to the
3559      *                  schedule. Use 0 to schedule the ssm call without modifying the event types.
3560      */
3561     // TODO(b/197344658): Also call scheduleOnUserCompletedEvent(userId, 0, 0) after switch UX done.
3562     @VisibleForTesting
3563     void scheduleOnUserCompletedEvent(
3564             int userId, @UserCompletedEventType.EventTypesFlag int eventType, int delayMs) {
3565 
3566         if (eventType != 0) {
3567             synchronized (mCompletedEventTypes) {
3568                 mCompletedEventTypes.put(userId, mCompletedEventTypes.get(userId, 0) | eventType);
3569             }
3570         }
3571 
3572         final Object msgObj = userId;
3573         mHandler.removeEqualMessages(USER_COMPLETED_EVENT_MSG, msgObj);
3574         mHandler.sendMessageDelayed(
3575                 mHandler.obtainMessage(USER_COMPLETED_EVENT_MSG, msgObj),
3576                 delayMs);
3577     }
3578 
3579     /**
3580      * Calls {@link SystemServiceManager#onUserCompletedEvent()} for the given user, sending all the
3581      * {@link UserCompletedEventType} events that have been scheduled for it if they are still
3582      * applicable.
3583      *
3584      * Called on the mHandler thread.
3585      */
3586     @VisibleForTesting
3587     void reportOnUserCompletedEvent(Integer userId) {
3588         mHandler.removeEqualMessages(USER_COMPLETED_EVENT_MSG, userId);
3589 
3590         int eventTypes;
3591         synchronized (mCompletedEventTypes) {
3592             eventTypes = mCompletedEventTypes.get(userId, 0);
3593             mCompletedEventTypes.delete(userId);
3594         }
3595 
3596         // Now, remove any eventTypes that are no longer true.
3597         int eligibleEventTypes = 0;
3598         synchronized (mLock) {
3599             final UserState uss = mStartedUsers.get(userId);
3600             if (uss != null && uss.state != UserState.STATE_SHUTDOWN) {
3601                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_STARTING;
3602             }
3603             if (uss != null && uss.state == STATE_RUNNING_UNLOCKED) {
3604                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_UNLOCKED;
3605             }
3606             if (userId == mCurrentUserId) {
3607                 eligibleEventTypes |= UserCompletedEventType.EVENT_TYPE_USER_SWITCHING;
3608             }
3609         }
3610         Slogf.i(TAG, "reportOnUserCompletedEvent(%d): stored=%s, eligible=%s", userId,
3611                 Integer.toBinaryString(eventTypes), Integer.toBinaryString(eligibleEventTypes));
3612         eventTypes &= eligibleEventTypes;
3613 
3614         mInjector.systemServiceManagerOnUserCompletedEvent(userId, eventTypes);
3615     }
3616 
3617     /**
3618      * statsd helper method for logging the start of a user journey via a UserLifecycleEventOccurred
3619      * atom given the originating and targeting users for the journey.
3620      */
3621     private void logUserJourneyBegin(int targetId,
3622             @UserJourneyLogger.UserJourney int journey) {
3623         UserJourneySession oldSession = mInjector.getUserJourneyLogger()
3624                     .finishAndClearIncompleteUserJourney(targetId, journey);
3625         if (oldSession != null) {
3626             if (DEBUG_MU) {
3627                 Slogf.d(TAG,
3628                         "Starting a new journey: " + journey + " with session id: "
3629                                 + oldSession);
3630             }
3631             /*
3632              * User lifecycle journey would be complete when {@code #clearSessionId} is called
3633              * after the last expected lifecycle event for the journey. It may be possible that
3634              * the last event is not called, e.g., user not unlocked after user switching. In such
3635              * cases user journey is cleared after {@link USER_JOURNEY_TIMEOUT}.
3636              */
3637             mHandler.removeMessages(CLEAR_USER_JOURNEY_SESSION_MSG, oldSession);
3638         }
3639         UserJourneySession newSession = mInjector.getUserJourneyLogger()
3640                 .logUserJourneyBegin(targetId, journey);
3641         mHandler.sendMessageDelayed(mHandler.obtainMessage(CLEAR_USER_JOURNEY_SESSION_MSG,
3642                 targetId, /* arg2= */ journey, newSession), USER_JOURNEY_TIMEOUT_MS);
3643 
3644     }
3645 
3646     BroadcastOptions getTemporaryAppAllowlistBroadcastOptions(
3647             @PowerWhitelistManager.ReasonCode int reasonCode) {
3648         long duration = 10_000;
3649         final ActivityManagerInternal amInternal =
3650                 LocalServices.getService(ActivityManagerInternal.class);
3651         if (amInternal != null) {
3652             duration = amInternal.getBootTimeTempAllowListDuration();
3653         }
3654         final BroadcastOptions bOptions = BroadcastOptions.makeBasic();
3655         bOptions.setTemporaryAppAllowlist(duration,
3656                 TEMPORARY_ALLOWLIST_TYPE_FOREGROUND_SERVICE_ALLOWED, reasonCode, "");
3657         return bOptions;
3658     }
3659 
3660     private static int getUserSwitchTimeoutMs() {
3661         final String userSwitchTimeoutMs = SystemProperties.get(
3662                 "debug.usercontroller.user_switch_timeout_ms");
3663         if (!TextUtils.isEmpty(userSwitchTimeoutMs)) {
3664             try {
3665                 return Integer.parseInt(userSwitchTimeoutMs);
3666             } catch (NumberFormatException ignored) {
3667                 // Ignored.
3668             }
3669         }
3670         return DEFAULT_USER_SWITCH_TIMEOUT_MS;
3671     }
3672 
3673     private static void asyncTraceBegin(String msg, int cookie) {
3674         Slogf.d(TAG, "%s - asyncTraceBegin(%d)", msg, cookie);
3675         Trace.asyncTraceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, msg, cookie);
3676     }
3677 
3678     private static void asyncTraceEnd(String msg, int cookie) {
3679         Trace.asyncTraceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER, msg, cookie);
3680         Slogf.d(TAG, "%s - asyncTraceEnd(%d)", msg, cookie);
3681     }
3682 
3683     /**
3684      * Uptime when any user was being unlocked most recently. 0 if no users have been unlocked
3685      * yet. To avoid lock contention (since it's used by OomAdjuster), it's volatile internally.
3686      */
3687     public long getLastUserUnlockingUptime() {
3688         return mLastUserUnlockingUptime;
3689     }
3690 
3691     private static class UserProgressListener extends IProgressListener.Stub {
3692         private volatile long mUnlockStarted;
3693         @Override
3694         public void onStarted(int id, Bundle extras) throws RemoteException {
3695             Slogf.d(TAG, "Started unlocking user " + id);
3696             mUnlockStarted = SystemClock.uptimeMillis();
3697         }
3698 
3699         @Override
3700         public void onProgress(int id, int progress, Bundle extras) throws RemoteException {
3701             Slogf.d(TAG, "Unlocking user " + id + " progress " + progress);
3702         }
3703 
3704         @Override
3705         public void onFinished(int id, Bundle extras) throws RemoteException {
3706             long unlockTime = SystemClock.uptimeMillis() - mUnlockStarted;
3707 
3708             // Report system user unlock time to perf dashboard
3709             if (id == UserHandle.USER_SYSTEM) {
3710                 new TimingsTraceAndSlog().logDuration("SystemUserUnlock", unlockTime);
3711             } else {
3712                 new TimingsTraceAndSlog().logDuration("User" + id + "Unlock", unlockTime);
3713             }
3714         }
3715     }
3716 
3717     /**
3718      * Helper class for keeping track of user starts which are paused while user's
3719      * shutdown is taking place.
3720      */
3721     private static class PendingUserStart {
3722         public final @UserIdInt int userId;
3723         public final @UserStartMode int userStartMode;
3724         public final IProgressListener unlockListener;
3725 
3726         PendingUserStart(int userId, @UserStartMode int userStartMode,
3727                 IProgressListener unlockListener) {
3728             this.userId = userId;
3729             this.userStartMode = userStartMode;
3730             this.unlockListener = unlockListener;
3731         }
3732 
3733         @Override
3734         public String toString() {
3735             return "PendingUserStart{"
3736                     + "userId=" + userId
3737                     + ", userStartMode=" + userStartModeToString(userStartMode)
3738                     + ", unlockListener=" + unlockListener
3739                     + '}';
3740         }
3741     }
3742 
3743     @VisibleForTesting
3744     static class Injector {
3745         private final ActivityManagerService mService;
3746         private UserManagerService mUserManager;
3747         private UserManagerInternal mUserManagerInternal;
3748         private PowerManagerInternal mPowerManagerInternal;
3749         private Handler mHandler;
3750         private final Object mUserSwitchingDialogLock = new Object();
3751         @GuardedBy("mUserSwitchingDialogLock")
3752         private UserSwitchingDialog mUserSwitchingDialog;
3753 
3754         Injector(ActivityManagerService service) {
3755             mService = service;
3756         }
3757 
3758         protected Handler getHandler(Handler.Callback callback) {
3759             return mHandler = new Handler(mService.mHandlerThread.getLooper(), callback);
3760         }
3761 
3762         protected Handler getUiHandler(Handler.Callback callback) {
3763             return new Handler(mService.mUiHandler.getLooper(), callback);
3764         }
3765 
3766         protected UserJourneyLogger getUserJourneyLogger() {
3767             return getUserManager().getUserJourneyLogger();
3768         }
3769 
3770         protected Context getContext() {
3771             return mService.mContext;
3772         }
3773 
3774         protected LockPatternUtils getLockPatternUtils() {
3775             return new LockPatternUtils(getContext());
3776         }
3777 
3778         protected int broadcastIntent(Intent intent, String resolvedType,
3779                 IIntentReceiver resultTo, int resultCode, String resultData,
3780                 Bundle resultExtras, String[] requiredPermissions, int appOp, Bundle bOptions,
3781                 boolean sticky, int callingPid, int callingUid, int realCallingUid,
3782                 int realCallingPid, @UserIdInt int userId) {
3783 
3784             int logUserId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3785             if (logUserId == UserHandle.USER_NULL) {
3786                 logUserId = userId;
3787             }
3788             EventLog.writeEvent(EventLogTags.UC_SEND_USER_BROADCAST, logUserId, intent.getAction());
3789 
3790             TimingsTraceAndSlog t = new TimingsTraceAndSlog();
3791             // TODO b/64165549 Verify that mLock is not held before calling AMS methods
3792             synchronized (mService) {
3793                 t.traceBegin("broadcastIntent-" + userId + "-" + intent.getAction());
3794                 final int result = mService.broadcastIntentLocked(null, null, null, intent,
3795                         resolvedType, resultTo, resultCode, resultData, resultExtras,
3796                         requiredPermissions, null, null, appOp, bOptions, false, sticky,
3797                         callingPid, callingUid, realCallingUid, realCallingPid, userId);
3798                 t.traceEnd();
3799                 return result;
3800             }
3801         }
3802 
3803         int checkCallingPermission(String permission) {
3804             return mService.checkCallingPermission(permission);
3805         }
3806 
3807         WindowManagerService getWindowManager() {
3808             return mService.mWindowManager;
3809         }
3810 
3811         ActivityTaskManagerInternal getActivityTaskManagerInternal() {
3812             return mService.mAtmInternal;
3813         }
3814 
3815         void activityManagerOnUserStopped(@UserIdInt int userId) {
3816             LocalServices.getService(ActivityTaskManagerInternal.class).onUserStopped(userId);
3817         }
3818 
3819         void systemServiceManagerOnUserStopped(@UserIdInt int userId) {
3820             getSystemServiceManager().onUserStopped(userId);
3821         }
3822 
3823         void systemServiceManagerOnUserCompletedEvent(@UserIdInt int userId, int eventTypes) {
3824             getSystemServiceManager().onUserCompletedEvent(userId, eventTypes);
3825         }
3826 
3827         protected UserManagerService getUserManager() {
3828             if (mUserManager == null) {
3829                 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
3830                 mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
3831             }
3832             return mUserManager;
3833         }
3834 
3835         UserManagerInternal getUserManagerInternal() {
3836             if (mUserManagerInternal == null) {
3837                 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
3838             }
3839             return mUserManagerInternal;
3840         }
3841 
3842         PowerManagerInternal getPowerManagerInternal() {
3843             if (mPowerManagerInternal == null) {
3844                 mPowerManagerInternal = LocalServices.getService(PowerManagerInternal.class);
3845             }
3846             return mPowerManagerInternal;
3847         }
3848 
3849         KeyguardManager getKeyguardManager() {
3850             return mService.mContext.getSystemService(KeyguardManager.class);
3851         }
3852 
3853         void batteryStatsServiceNoteEvent(int code, String name, int uid) {
3854             mService.mBatteryStatsService.noteEvent(code, name, uid);
3855         }
3856 
3857         boolean isRuntimeRestarted() {
3858             return getSystemServiceManager().isRuntimeRestarted();
3859         }
3860 
3861         SystemServiceManager getSystemServiceManager() {
3862             return mService.mSystemServiceManager;
3863         }
3864 
3865         boolean isFirstBootOrUpgrade() {
3866             IPackageManager pm = AppGlobals.getPackageManager();
3867             try {
3868                 return pm.isFirstBoot() || pm.isDeviceUpgrading();
3869             } catch (RemoteException e) {
3870                 throw e.rethrowFromSystemServer();
3871             }
3872         }
3873 
3874         void sendPreBootBroadcast(@UserIdInt int userId, boolean quiet, final Runnable onFinish) {
3875             EventLog.writeEvent(EventLogTags.UC_SEND_USER_BROADCAST,
3876                     userId, Intent.ACTION_PRE_BOOT_COMPLETED);
3877             new PreBootBroadcaster(mService, userId, null, quiet) {
3878                 @Override
3879                 public void onFinished() {
3880                     onFinish.run();
3881                 }
3882             }.sendNext();
3883         }
3884 
3885         void activityManagerForceStopPackage(@UserIdInt int userId, String reason) {
3886             synchronized (mService) {
3887                 mService.forceStopPackageLocked(null, -1, false, false, true, false, false, false,
3888                         userId, reason);
3889             }
3890         };
3891 
3892         int checkComponentPermission(String permission, int pid, int uid, int owningUid,
3893                 boolean exported) {
3894             return mService.checkComponentPermission(permission, pid, uid, owningUid, exported);
3895         }
3896 
3897         boolean checkPermissionForPreflight(String permission, int pid, int uid, String pkg) {
3898             return  PermissionChecker.PERMISSION_GRANTED
3899                     == PermissionChecker.checkPermissionForPreflight(
3900                             getContext(), permission, pid, uid, pkg);
3901         }
3902 
3903         protected void startHomeActivity(@UserIdInt int userId, String reason) {
3904             mService.mAtmInternal.startHomeActivity(userId, reason);
3905         }
3906 
3907         void startUserWidgets(@UserIdInt int userId) {
3908             AppWidgetManagerInternal awm = LocalServices.getService(AppWidgetManagerInternal.class);
3909             if (awm != null) {
3910                 // Out of band, because this is called during a sequence with
3911                 // sensitive cross-service lock management
3912                 FgThread.getHandler().post(() -> {
3913                     awm.unlockUser(userId);
3914                 });
3915             }
3916         }
3917 
3918         void updateUserConfiguration() {
3919             mService.mAtmInternal.updateUserConfiguration();
3920         }
3921 
3922         void clearBroadcastQueueForUser(@UserIdInt int userId) {
3923             synchronized (mService) {
3924                 mService.clearBroadcastQueueForUserLocked(userId);
3925             }
3926         }
3927 
3928         void loadUserRecents(@UserIdInt int userId) {
3929             mService.mAtmInternal.loadRecentTasksForUser(userId);
3930         }
3931 
3932         void startPersistentApps(int matchFlags) {
3933             mService.startPersistentApps(matchFlags);
3934         }
3935 
3936         void installEncryptionUnawareProviders(@UserIdInt int userId) {
3937             mService.mCpHelper.installEncryptionUnawareProviders(userId);
3938         }
3939 
3940         void dismissUserSwitchingDialog(@Nullable Runnable onDismissed) {
3941             synchronized (mUserSwitchingDialogLock) {
3942                 if (mUserSwitchingDialog != null) {
3943                     mUserSwitchingDialog.dismiss(onDismissed);
3944                     mUserSwitchingDialog = null;
3945                 } else if (onDismissed != null) {
3946                     onDismissed.run();
3947                 }
3948             }
3949         }
3950 
3951         void showUserSwitchingDialog(UserInfo fromUser, UserInfo toUser,
3952                 String switchingFromSystemUserMessage, String switchingToSystemUserMessage,
3953                 @NonNull Runnable onShown) {
3954             if (mService.mContext.getPackageManager()
3955                     .hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE)) {
3956                 // config_customUserSwitchUi is set to true on Automotive as CarSystemUI is
3957                 // responsible to show the UI; OEMs should not change that, but if they do, we
3958                 // should at least warn the user...
3959                 Slogf.w(TAG, "Showing user switch dialog on UserController, it could cause a race "
3960                         + "condition if it's shown by CarSystemUI as well");
3961             }
3962             synchronized (mUserSwitchingDialogLock) {
3963                 dismissUserSwitchingDialog(null);
3964                 mUserSwitchingDialog = new UserSwitchingDialog(mService.mContext, fromUser, toUser,
3965                         switchingFromSystemUserMessage, switchingToSystemUserMessage,
3966                         getWindowManager());
3967                 mUserSwitchingDialog.show(onShown);
3968             }
3969         }
3970 
3971         void reportGlobalUsageEvent(int event) {
3972             mService.reportGlobalUsageEvent(event);
3973         }
3974 
3975         void reportCurWakefulnessUsageEvent() {
3976             mService.reportCurWakefulnessUsageEvent();
3977         }
3978 
3979         void taskSupervisorRemoveUser(@UserIdInt int userId) {
3980             mService.mAtmInternal.removeUser(userId);
3981         }
3982 
3983         protected boolean taskSupervisorSwitchUser(@UserIdInt int userId, UserState uss) {
3984             return mService.mAtmInternal.switchUser(userId, uss);
3985         }
3986 
3987         protected void taskSupervisorResumeFocusedStackTopActivity() {
3988             mService.mAtmInternal.resumeTopActivities(false /* scheduleIdle */);
3989         }
3990 
3991         protected void clearAllLockedTasks(String reason) {
3992             mService.mAtmInternal.clearLockedTasks(reason);
3993         }
3994 
3995         boolean isCallerRecents(int callingUid) {
3996             return mService.mAtmInternal.isCallerRecents(callingUid);
3997         }
3998 
3999         protected IStorageManager getStorageManager() {
4000             return IStorageManager.Stub.asInterface(ServiceManager.getService("mount"));
4001         }
4002 
4003         protected void showKeyguard(Runnable runnable) {
4004             if (getWindowManager().isKeyguardLocked()) {
4005                 runnable.run();
4006                 return;
4007             }
4008             getActivityTaskManagerInternal().registerScreenObserver(
4009                     new ActivityTaskManagerInternal.ScreenObserver() {
4010                         @Override
4011                         public void onAwakeStateChanged(boolean isAwake) {
4012 
4013                         }
4014 
4015                         @Override
4016                         public void onKeyguardStateChanged(boolean isShowing) {
4017                             if (isShowing) {
4018                                 getActivityTaskManagerInternal().unregisterScreenObserver(this);
4019                                 runnable.run();
4020                             }
4021                         }
4022                     }
4023             );
4024             getWindowManager().lockDeviceNow();
4025         }
4026 
4027         protected void dismissKeyguard(Runnable runnable) {
4028             getWindowManager().dismissKeyguard(new IKeyguardDismissCallback.Stub() {
4029                 @Override
4030                 public void onDismissError() throws RemoteException {
4031                     runnable.run();
4032                 }
4033 
4034                 @Override
4035                 public void onDismissSucceeded() throws RemoteException {
4036                     runnable.run();
4037                 }
4038 
4039                 @Override
4040                 public void onDismissCancelled() throws RemoteException {
4041                     runnable.run();
4042                 }
4043             }, /* message= */ null);
4044         }
4045 
4046         boolean isHeadlessSystemUserMode() {
4047             return UserManager.isHeadlessSystemUserMode();
4048         }
4049 
4050         boolean isUsersOnSecondaryDisplaysEnabled() {
4051             return UserManager.isVisibleBackgroundUsersEnabled();
4052         }
4053 
4054         void onUserStarting(@UserIdInt int userId) {
4055             getSystemServiceManager().onUserStarting(TimingsTraceAndSlog.newAsyncLog(), userId);
4056         }
4057 
4058         void setPerformancePowerMode(boolean enabled) {
4059             Slogf.i(TAG, "Setting power mode MODE_FIXED_PERFORMANCE to " + enabled);
4060             getPowerManagerInternal().setPowerMode(
4061                     PowerManagerInternal.MODE_FIXED_PERFORMANCE, enabled);
4062         }
4063 
4064         void onSystemUserVisibilityChanged(boolean visible) {
4065             getUserManagerInternal().onSystemUserVisibilityChanged(visible);
4066         }
4067     }
4068 }
4069