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