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