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