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