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