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