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
17package com.android.server.am;
18
19import static android.Manifest.permission.INTERACT_ACROSS_USERS;
20import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
21import static android.app.ActivityManager.USER_OP_ERROR_IS_SYSTEM;
22import static android.app.ActivityManager.USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
23import static android.app.ActivityManager.USER_OP_IS_CURRENT;
24import static android.app.ActivityManager.USER_OP_SUCCESS;
25import static android.content.Context.KEYGUARD_SERVICE;
26import static android.os.Process.SYSTEM_UID;
27
28import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
29import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
30import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
31import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
32import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
33import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
34import static com.android.server.am.ActivityManagerService.MY_PID;
35import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
36import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
37import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
38import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
39import static com.android.server.am.ActivityManagerService.SYSTEM_USER_UNLOCK_MSG;
40import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
41import static com.android.server.am.UserState.STATE_BOOTING;
42import static com.android.server.am.UserState.STATE_RUNNING_LOCKED;
43import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKED;
44import static com.android.server.am.UserState.STATE_RUNNING_UNLOCKING;
45
46import android.annotation.NonNull;
47import android.annotation.UserIdInt;
48import android.app.ActivityManager;
49import android.app.AppOpsManager;
50import android.app.Dialog;
51import android.app.IStopUserCallback;
52import android.app.IUserSwitchObserver;
53import android.app.KeyguardManager;
54import android.content.Context;
55import android.content.IIntentReceiver;
56import android.content.Intent;
57import android.content.pm.PackageManager;
58import android.content.pm.UserInfo;
59import android.os.BatteryStats;
60import android.os.Binder;
61import android.os.Build;
62import android.os.Bundle;
63import android.os.Debug;
64import android.os.Handler;
65import android.os.IBinder;
66import android.os.IProgressListener;
67import android.os.IRemoteCallback;
68import android.os.IUserManager;
69import android.os.Process;
70import android.os.RemoteCallbackList;
71import android.os.RemoteException;
72import android.os.ServiceManager;
73import android.os.SystemClock;
74import android.os.UserHandle;
75import android.os.UserManager;
76import android.os.UserManagerInternal;
77import android.os.storage.IMountService;
78import android.os.storage.StorageManager;
79import android.util.IntArray;
80import android.util.Pair;
81import android.util.Slog;
82import android.util.SparseArray;
83import android.util.SparseIntArray;
84
85import com.android.internal.R;
86import com.android.internal.annotations.GuardedBy;
87import com.android.internal.logging.MetricsLogger;
88import com.android.internal.util.ArrayUtils;
89import com.android.internal.widget.LockPatternUtils;
90import com.android.server.LocalServices;
91import com.android.server.pm.UserManagerService;
92
93import java.io.PrintWriter;
94import java.util.ArrayList;
95import java.util.Arrays;
96import java.util.HashSet;
97import java.util.List;
98import java.util.Objects;
99import java.util.Set;
100
101/**
102 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
103 */
104final class UserController {
105    private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
106
107    // Maximum number of users we allow to be running at a time.
108    static final int MAX_RUNNING_USERS = 3;
109
110    // Amount of time we wait for observers to handle a user switch before
111    // giving up on them and unfreezing the screen.
112    static final int USER_SWITCH_TIMEOUT = 2 * 1000;
113
114    private final ActivityManagerService mService;
115    private final Handler mHandler;
116
117    // Holds the current foreground user's id
118    private int mCurrentUserId = UserHandle.USER_SYSTEM;
119    // Holds the target user's id during a user switch
120    private int mTargetUserId = UserHandle.USER_NULL;
121
122    /**
123     * Which users have been started, so are allowed to run code.
124     */
125    @GuardedBy("mService")
126    private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
127
128    /**
129     * LRU list of history of current users.  Most recently current is at the end.
130     */
131    private final ArrayList<Integer> mUserLru = new ArrayList<>();
132
133    /**
134     * Constant array of the users that are currently started.
135     */
136    private int[] mStartedUserArray = new int[] { 0 };
137
138    // If there are multiple profiles for the current user, their ids are here
139    // Currently only the primary user can have managed profiles
140    private int[] mCurrentProfileIds = new int[] {};
141
142    /**
143     * Mapping from each known user ID to the profile group ID it is associated with.
144     */
145    private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
146
147    /**
148     * Registered observers of the user switching mechanics.
149     */
150    private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
151            = new RemoteCallbackList<>();
152
153    /**
154     * Currently active user switch.
155     */
156    Object mCurUserSwitchCallback;
157
158    private volatile UserManagerService mUserManager;
159
160    private final LockPatternUtils mLockPatternUtils;
161
162    private UserManagerInternal mUserManagerInternal;
163
164    UserController(ActivityManagerService service) {
165        mService = service;
166        mHandler = mService.mHandler;
167        // User 0 is the first and only user that runs at boot.
168        final UserState uss = new UserState(UserHandle.SYSTEM);
169        mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
170        mUserLru.add(UserHandle.USER_SYSTEM);
171        mLockPatternUtils = new LockPatternUtils(mService.mContext);
172        updateStartedUserArrayLocked();
173    }
174
175    void finishUserSwitch(UserState uss) {
176        synchronized (mService) {
177            finishUserBoot(uss);
178
179            startProfilesLocked();
180            stopRunningUsersLocked(MAX_RUNNING_USERS);
181        }
182    }
183
184    void stopRunningUsersLocked(int maxRunningUsers) {
185        int num = mUserLru.size();
186        int i = 0;
187        while (num > maxRunningUsers && i < mUserLru.size()) {
188            Integer oldUserId = mUserLru.get(i);
189            UserState oldUss = mStartedUsers.get(oldUserId);
190            if (oldUss == null) {
191                // Shouldn't happen, but be sane if it does.
192                mUserLru.remove(i);
193                num--;
194                continue;
195            }
196            if (oldUss.state == UserState.STATE_STOPPING
197                    || oldUss.state == UserState.STATE_SHUTDOWN) {
198                // This user is already stopping, doesn't count.
199                num--;
200                i++;
201                continue;
202            }
203            if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
204                // Owner/System user and current user can't be stopped. We count it as running
205                // when it is not a pure system user.
206                if (UserInfo.isSystemOnly(oldUserId)) {
207                    num--;
208                }
209                i++;
210                continue;
211            }
212            // This is a user to be stopped.
213            if (stopUsersLocked(oldUserId, false, null) != USER_OP_SUCCESS) {
214                num--;
215            }
216            num--;
217            i++;
218        }
219    }
220
221    private void finishUserBoot(UserState uss) {
222        finishUserBoot(uss, null);
223    }
224
225    private void finishUserBoot(UserState uss, IIntentReceiver resultTo) {
226        final int userId = uss.mHandle.getIdentifier();
227        Slog.d(TAG, "Finishing user boot " + userId);
228        synchronized (mService) {
229            // Bail if we ended up with a stale user
230            if (mStartedUsers.get(userId) != uss) return;
231
232            // We always walk through all the user lifecycle states to send
233            // consistent developer events. We step into RUNNING_LOCKED here,
234            // but we might immediately step into RUNNING below if the user
235            // storage is already unlocked.
236            if (uss.setState(STATE_BOOTING, STATE_RUNNING_LOCKED)) {
237                getUserManagerInternal().setUserState(userId, uss.state);
238
239                int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
240                MetricsLogger.histogram(mService.mContext, "framework_locked_boot_completed",
241                    uptimeSeconds);
242
243                Intent intent = new Intent(Intent.ACTION_LOCKED_BOOT_COMPLETED, null);
244                intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
245                intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
246                        | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
247                mService.broadcastIntentLocked(null, null, intent, null, resultTo, 0, null, null,
248                        new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
249                        AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
250            }
251
252            // We need to delay unlocking managed profiles until the parent user
253            // is also unlocked.
254            if (getUserManager().isManagedProfile(userId)) {
255                final UserInfo parent = getUserManager().getProfileParent(userId);
256                if (parent != null
257                        && isUserRunningLocked(parent.id, ActivityManager.FLAG_AND_UNLOCKED)) {
258                    Slog.d(TAG, "User " + userId + " (parent " + parent.id
259                            + "): attempting unlock because parent is unlocked");
260                    maybeUnlockUser(userId);
261                } else {
262                    String parentId = (parent == null) ? "<null>" : String.valueOf(parent.id);
263                    Slog.d(TAG, "User " + userId + " (parent " + parentId
264                            + "): delaying unlock because parent is locked");
265                }
266            } else {
267                maybeUnlockUser(userId);
268            }
269        }
270    }
271
272    /**
273     * Step from {@link UserState#STATE_RUNNING_LOCKED} to
274     * {@link UserState#STATE_RUNNING_UNLOCKING}.
275     */
276    private void finishUserUnlocking(final UserState uss) {
277        final int userId = uss.mHandle.getIdentifier();
278        synchronized (mService) {
279            // Bail if we ended up with a stale user
280            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
281
282            // Only keep marching forward if user is actually unlocked
283            if (!StorageManager.isUserKeyUnlocked(userId)) return;
284
285            if (uss.setState(STATE_RUNNING_LOCKED, STATE_RUNNING_UNLOCKING)) {
286                getUserManagerInternal().setUserState(userId, uss.state);
287                uss.mUnlockProgress.start();
288
289                // Prepare app storage before we go any further
290                uss.mUnlockProgress.setProgress(5,
291                        mService.mContext.getString(R.string.android_start_title));
292                mUserManager.onBeforeUnlockUser(userId);
293                uss.mUnlockProgress.setProgress(20);
294
295                // Dispatch unlocked to system services; when fully dispatched,
296                // that calls through to the next "unlocked" phase
297                mHandler.obtainMessage(SYSTEM_USER_UNLOCK_MSG, userId, 0, uss)
298                        .sendToTarget();
299            }
300        }
301    }
302
303    /**
304     * Step from {@link UserState#STATE_RUNNING_UNLOCKING} to
305     * {@link UserState#STATE_RUNNING_UNLOCKED}.
306     */
307    void finishUserUnlocked(final UserState uss) {
308        final int userId = uss.mHandle.getIdentifier();
309        synchronized (mService) {
310            // Bail if we ended up with a stale user
311            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
312
313            // Only keep marching forward if user is actually unlocked
314            if (!StorageManager.isUserKeyUnlocked(userId)) return;
315
316            if (uss.setState(STATE_RUNNING_UNLOCKING, STATE_RUNNING_UNLOCKED)) {
317                getUserManagerInternal().setUserState(userId, uss.state);
318                uss.mUnlockProgress.finish();
319
320                // Dispatch unlocked to external apps
321                final Intent unlockedIntent = new Intent(Intent.ACTION_USER_UNLOCKED);
322                unlockedIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
323                unlockedIntent.addFlags(
324                        Intent.FLAG_RECEIVER_REGISTERED_ONLY | Intent.FLAG_RECEIVER_FOREGROUND);
325                mService.broadcastIntentLocked(null, null, unlockedIntent, null, null, 0, null,
326                        null, null, AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
327                        userId);
328
329                if (getUserInfo(userId).isManagedProfile()) {
330                    UserInfo parent = getUserManager().getProfileParent(userId);
331                    if (parent != null) {
332                        final Intent profileUnlockedIntent = new Intent(
333                                Intent.ACTION_MANAGED_PROFILE_UNLOCKED);
334                        profileUnlockedIntent.putExtra(Intent.EXTRA_USER, UserHandle.of(userId));
335                        profileUnlockedIntent.addFlags(
336                                Intent.FLAG_RECEIVER_REGISTERED_ONLY
337                                | Intent.FLAG_RECEIVER_FOREGROUND);
338                        mService.broadcastIntentLocked(null, null, profileUnlockedIntent,
339                                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
340                                null, false, false, MY_PID, SYSTEM_UID,
341                                parent.id);
342                    }
343                }
344
345                // Send PRE_BOOT broadcasts if user fingerprint changed; we
346                // purposefully block sending BOOT_COMPLETED until after all
347                // PRE_BOOT receivers are finished to avoid ANR'ing apps
348                final UserInfo info = getUserInfo(userId);
349                if (!Objects.equals(info.lastLoggedInFingerprint, Build.FINGERPRINT)) {
350                    new PreBootBroadcaster(mService, userId, null) {
351                        @Override
352                        public void onFinished() {
353                            finishUserUnlockedCompleted(uss);
354                        }
355                    }.sendNext();
356                } else {
357                    finishUserUnlockedCompleted(uss);
358                }
359            }
360        }
361    }
362
363    private void finishUserUnlockedCompleted(UserState uss) {
364        final int userId = uss.mHandle.getIdentifier();
365        synchronized (mService) {
366            // Bail if we ended up with a stale user
367            if (mStartedUsers.get(uss.mHandle.getIdentifier()) != uss) return;
368            final UserInfo userInfo = getUserInfo(userId);
369            if (userInfo == null) {
370                return;
371            }
372
373            // Only keep marching forward if user is actually unlocked
374            if (!StorageManager.isUserKeyUnlocked(userId)) return;
375
376            // Remember that we logged in
377            mUserManager.onUserLoggedIn(userId);
378
379            if (!userInfo.isInitialized()) {
380                if (userId != UserHandle.USER_SYSTEM) {
381                    Slog.d(TAG, "Initializing user #" + userId);
382                    Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
383                    intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
384                    mService.broadcastIntentLocked(null, null, intent, null,
385                            new IIntentReceiver.Stub() {
386                                @Override
387                                public void performReceive(Intent intent, int resultCode,
388                                        String data, Bundle extras, boolean ordered,
389                                        boolean sticky, int sendingUser) {
390                                    // Note: performReceive is called with mService lock held
391                                    getUserManager().makeInitialized(userInfo.id);
392                                }
393                            }, 0, null, null, null, AppOpsManager.OP_NONE,
394                            null, true, false, MY_PID, SYSTEM_UID, userId);
395                }
396            }
397
398            Slog.d(TAG, "Sending BOOT_COMPLETE user #" + userId);
399            int uptimeSeconds = (int)(SystemClock.elapsedRealtime() / 1000);
400            MetricsLogger.histogram(mService.mContext, "framework_boot_completed", uptimeSeconds);
401            final Intent bootIntent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
402            bootIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
403            bootIntent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT
404                    | Intent.FLAG_RECEIVER_INCLUDE_BACKGROUND);
405            mService.broadcastIntentLocked(null, null, bootIntent, null, null, 0, null, null,
406                    new String[] { android.Manifest.permission.RECEIVE_BOOT_COMPLETED },
407                    AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
408        }
409    }
410
411    int stopUser(final int userId, final boolean force, final IStopUserCallback callback) {
412        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
413                != PackageManager.PERMISSION_GRANTED) {
414            String msg = "Permission Denial: switchUser() from pid="
415                    + Binder.getCallingPid()
416                    + ", uid=" + Binder.getCallingUid()
417                    + " requires " + INTERACT_ACROSS_USERS_FULL;
418            Slog.w(TAG, msg);
419            throw new SecurityException(msg);
420        }
421        if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
422            throw new IllegalArgumentException("Can't stop system user " + userId);
423        }
424        mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
425                userId);
426        synchronized (mService) {
427            return stopUsersLocked(userId, force, callback);
428        }
429    }
430
431    /**
432     * Stops the user along with its related users. The method calls
433     * {@link #getUsersToStopLocked(int)} to determine the list of users that should be stopped.
434     */
435    private int stopUsersLocked(final int userId, boolean force, final IStopUserCallback callback) {
436        if (userId == UserHandle.USER_SYSTEM) {
437            return USER_OP_ERROR_IS_SYSTEM;
438        }
439        if (isCurrentUserLocked(userId)) {
440            return USER_OP_IS_CURRENT;
441        }
442        int[] usersToStop = getUsersToStopLocked(userId);
443        // If one of related users is system or current, no related users should be stopped
444        for (int i = 0; i < usersToStop.length; i++) {
445            int relatedUserId = usersToStop[i];
446            if ((UserHandle.USER_SYSTEM == relatedUserId) || isCurrentUserLocked(relatedUserId)) {
447                if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked cannot stop related user "
448                        + relatedUserId);
449                // We still need to stop the requested user if it's a force stop.
450                if (force) {
451                    Slog.i(TAG,
452                            "Force stop user " + userId + ". Related users will not be stopped");
453                    stopSingleUserLocked(userId, callback);
454                    return USER_OP_SUCCESS;
455                }
456                return USER_OP_ERROR_RELATED_USERS_CANNOT_STOP;
457            }
458        }
459        if (DEBUG_MU) Slog.i(TAG, "stopUsersLocked usersToStop=" + Arrays.toString(usersToStop));
460        for (int userIdToStop : usersToStop) {
461            stopSingleUserLocked(userIdToStop, userIdToStop == userId ? callback : null);
462        }
463        return USER_OP_SUCCESS;
464    }
465
466    private void stopSingleUserLocked(final int userId, final IStopUserCallback callback) {
467        if (DEBUG_MU) Slog.i(TAG, "stopSingleUserLocked userId=" + userId);
468        final UserState uss = mStartedUsers.get(userId);
469        if (uss == null) {
470            // User is not started, nothing to do...  but we do need to
471            // callback if requested.
472            if (callback != null) {
473                mHandler.post(new Runnable() {
474                    @Override
475                    public void run() {
476                        try {
477                            callback.userStopped(userId);
478                        } catch (RemoteException e) {
479                        }
480                    }
481                });
482            }
483            return;
484        }
485
486        if (callback != null) {
487            uss.mStopCallbacks.add(callback);
488        }
489
490        if (uss.state != UserState.STATE_STOPPING
491                && uss.state != UserState.STATE_SHUTDOWN) {
492            uss.setState(UserState.STATE_STOPPING);
493            getUserManagerInternal().setUserState(userId, uss.state);
494            updateStartedUserArrayLocked();
495
496            long ident = Binder.clearCallingIdentity();
497            try {
498                // We are going to broadcast ACTION_USER_STOPPING and then
499                // once that is done send a final ACTION_SHUTDOWN and then
500                // stop the user.
501                final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
502                stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
503                stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
504                stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
505                // This is the result receiver for the initial stopping broadcast.
506                final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
507                    @Override
508                    public void performReceive(Intent intent, int resultCode, String data,
509                            Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
510                        mHandler.post(new Runnable() {
511                            @Override
512                            public void run() {
513                                finishUserStopping(userId, uss);
514                            }
515                        });
516                    }
517                };
518                // Clear broadcast queue for the user to avoid delivering stale broadcasts
519                mService.clearBroadcastQueueForUserLocked(userId);
520                // Kick things off.
521                mService.broadcastIntentLocked(null, null, stoppingIntent,
522                        null, stoppingReceiver, 0, null, null,
523                        new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
524                        null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
525            } finally {
526                Binder.restoreCallingIdentity(ident);
527            }
528        }
529    }
530
531    void finishUserStopping(final int userId, final UserState uss) {
532        // On to the next.
533        final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
534        // This is the result receiver for the final shutdown broadcast.
535        final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
536            @Override
537            public void performReceive(Intent intent, int resultCode, String data,
538                    Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
539                mHandler.post(new Runnable() {
540                    @Override
541                    public void run() {
542                        finishUserStopped(uss);
543                    }
544                });
545            }
546        };
547
548        synchronized (mService) {
549            if (uss.state != UserState.STATE_STOPPING) {
550                // Whoops, we are being started back up.  Abort, abort!
551                return;
552            }
553            uss.setState(UserState.STATE_SHUTDOWN);
554        }
555        getUserManagerInternal().setUserState(userId, uss.state);
556
557        mService.mBatteryStatsService.noteEvent(
558                BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
559                Integer.toString(userId), userId);
560        mService.mSystemServiceManager.stopUser(userId);
561
562        synchronized (mService) {
563            mService.broadcastIntentLocked(null, null, shutdownIntent,
564                    null, shutdownReceiver, 0, null, null, null,
565                    AppOpsManager.OP_NONE,
566                    null, true, false, MY_PID, SYSTEM_UID, userId);
567        }
568    }
569
570    void finishUserStopped(UserState uss) {
571        final int userId = uss.mHandle.getIdentifier();
572        boolean stopped;
573        ArrayList<IStopUserCallback> callbacks;
574        synchronized (mService) {
575            callbacks = new ArrayList<>(uss.mStopCallbacks);
576            if (mStartedUsers.get(userId) != uss) {
577                stopped = false;
578            } else if (uss.state != UserState.STATE_SHUTDOWN) {
579                stopped = false;
580            } else {
581                stopped = true;
582                // User can no longer run.
583                mStartedUsers.remove(userId);
584                getUserManagerInternal().removeUserState(userId);
585                mUserLru.remove(Integer.valueOf(userId));
586                updateStartedUserArrayLocked();
587
588                mService.onUserStoppedLocked(userId);
589                // Clean up all state and processes associated with the user.
590                // Kill all the processes for the user.
591                forceStopUserLocked(userId, "finish user");
592            }
593        }
594
595        for (int i = 0; i < callbacks.size(); i++) {
596            try {
597                if (stopped) callbacks.get(i).userStopped(userId);
598                else callbacks.get(i).userStopAborted(userId);
599            } catch (RemoteException e) {
600            }
601        }
602
603        if (stopped) {
604            mService.mSystemServiceManager.cleanupUser(userId);
605            synchronized (mService) {
606                mService.mStackSupervisor.removeUserLocked(userId);
607            }
608            // Remove the user if it is ephemeral.
609            if (getUserInfo(userId).isEphemeral()) {
610                mUserManager.removeUser(userId);
611            }
612        }
613    }
614
615    /**
616     * Determines the list of users that should be stopped together with the specified
617     * {@code userId}. The returned list includes {@code userId}.
618     */
619    private @NonNull int[] getUsersToStopLocked(int userId) {
620        int startedUsersSize = mStartedUsers.size();
621        IntArray userIds = new IntArray();
622        userIds.add(userId);
623        synchronized (mUserProfileGroupIdsSelfLocked) {
624            int userGroupId = mUserProfileGroupIdsSelfLocked.get(userId,
625                    UserInfo.NO_PROFILE_GROUP_ID);
626            for (int i = 0; i < startedUsersSize; i++) {
627                UserState uss = mStartedUsers.valueAt(i);
628                int startedUserId = uss.mHandle.getIdentifier();
629                // Skip unrelated users (profileGroupId mismatch)
630                int startedUserGroupId = mUserProfileGroupIdsSelfLocked.get(startedUserId,
631                        UserInfo.NO_PROFILE_GROUP_ID);
632                boolean sameGroup = (userGroupId != UserInfo.NO_PROFILE_GROUP_ID)
633                        && (userGroupId == startedUserGroupId);
634                // userId has already been added
635                boolean sameUserId = startedUserId == userId;
636                if (!sameGroup || sameUserId) {
637                    continue;
638                }
639                userIds.add(startedUserId);
640            }
641        }
642        return userIds.toArray();
643    }
644
645    private void forceStopUserLocked(int userId, String reason) {
646        mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
647                userId, reason);
648        Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
649        intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
650                | Intent.FLAG_RECEIVER_FOREGROUND);
651        intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
652        mService.broadcastIntentLocked(null, null, intent,
653                null, null, 0, null, null, null, AppOpsManager.OP_NONE,
654                null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
655    }
656
657    /**
658     * Stops the guest or ephemeral user if it has gone to the background.
659     */
660    private void stopGuestOrEphemeralUserIfBackground() {
661        synchronized (mService) {
662            final int num = mUserLru.size();
663            for (int i = 0; i < num; i++) {
664                Integer oldUserId = mUserLru.get(i);
665                UserState oldUss = mStartedUsers.get(oldUserId);
666                if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
667                        || oldUss.state == UserState.STATE_STOPPING
668                        || oldUss.state == UserState.STATE_SHUTDOWN) {
669                    continue;
670                }
671                UserInfo userInfo = getUserInfo(oldUserId);
672                if (userInfo.isEphemeral()) {
673                    LocalServices.getService(UserManagerInternal.class)
674                            .onEphemeralUserStop(oldUserId);
675                }
676                if (userInfo.isGuest() || userInfo.isEphemeral()) {
677                    // This is a user to be stopped.
678                    stopUsersLocked(oldUserId, true, null);
679                    break;
680                }
681            }
682        }
683    }
684
685    void startProfilesLocked() {
686        if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
687        List<UserInfo> profiles = getUserManager().getProfiles(
688                mCurrentUserId, false /* enabledOnly */);
689        List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
690        for (UserInfo user : profiles) {
691            if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
692                    && user.id != mCurrentUserId && !user.isQuietModeEnabled()) {
693                profilesToStart.add(user);
694            }
695        }
696        final int profilesToStartSize = profilesToStart.size();
697        int i = 0;
698        for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
699            startUser(profilesToStart.get(i).id, /* foreground= */ false);
700        }
701        if (i < profilesToStartSize) {
702            Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
703        }
704    }
705
706    private UserManagerService getUserManager() {
707        UserManagerService userManager = mUserManager;
708        if (userManager == null) {
709            IBinder b = ServiceManager.getService(Context.USER_SERVICE);
710            userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
711        }
712        return userManager;
713    }
714
715    private IMountService getMountService() {
716        return IMountService.Stub.asInterface(ServiceManager.getService("mount"));
717    }
718
719    /**
720     * Start user, if its not already running.
721     * <p>The user will be brought to the foreground, if {@code foreground} parameter is set.
722     * When starting the user, multiple intents will be broadcast in the following order:</p>
723     * <ul>
724     *     <li>{@link Intent#ACTION_USER_STARTED} - sent to registered receivers of the new user
725     *     <li>{@link Intent#ACTION_USER_BACKGROUND} - sent to registered receivers of the outgoing
726     *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
727     *     <li>{@link Intent#ACTION_USER_FOREGROUND} - sent to registered receivers of the new
728     *     user and all profiles of this user. Sent only if {@code foreground} parameter is true
729     *     <li>{@link Intent#ACTION_USER_SWITCHED} - sent to registered receivers of the new user.
730     *     Sent only if {@code foreground} parameter is true
731     *     <li>{@link Intent#ACTION_USER_STARTING} - ordered broadcast sent to registered receivers
732     *     of the new fg user
733     *     <li>{@link Intent#ACTION_LOCKED_BOOT_COMPLETED} - ordered broadcast sent to receivers of
734     *     the new user
735     *     <li>{@link Intent#ACTION_USER_UNLOCKED} - sent to registered receivers of the new user
736     *     <li>{@link Intent#ACTION_PRE_BOOT_COMPLETED} - ordered broadcast sent to receivers of the
737     *     new user. Sent only when the user is booting after a system update.
738     *     <li>{@link Intent#ACTION_USER_INITIALIZE} - ordered broadcast sent to receivers of the
739     *     new user. Sent only the first time a user is starting.
740     *     <li>{@link Intent#ACTION_BOOT_COMPLETED} - ordered broadcast sent to receivers of the new
741     *     user. Indicates that the user has finished booting.
742     * </ul>
743     *
744     * @param userId ID of the user to start
745     * @param foreground true if user should be brought to the foreground
746     * @return true if the user has been successfully started
747     */
748    boolean startUser(final int userId, final boolean foreground) {
749        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
750                != PackageManager.PERMISSION_GRANTED) {
751            String msg = "Permission Denial: switchUser() from pid="
752                    + Binder.getCallingPid()
753                    + ", uid=" + Binder.getCallingUid()
754                    + " requires " + INTERACT_ACROSS_USERS_FULL;
755            Slog.w(TAG, msg);
756            throw new SecurityException(msg);
757        }
758
759        Slog.i(TAG, "Starting userid:" + userId + " fg:" + foreground);
760
761        final long ident = Binder.clearCallingIdentity();
762        try {
763            synchronized (mService) {
764                final int oldUserId = mCurrentUserId;
765                if (oldUserId == userId) {
766                    return true;
767                }
768
769                mService.mStackSupervisor.setLockTaskModeLocked(null,
770                        ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
771
772                final UserInfo userInfo = getUserInfo(userId);
773                if (userInfo == null) {
774                    Slog.w(TAG, "No user info for user #" + userId);
775                    return false;
776                }
777                if (foreground && userInfo.isManagedProfile()) {
778                    Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
779                    return false;
780                }
781
782                if (foreground) {
783                    mService.mWindowManager.startFreezingScreen(
784                            R.anim.screen_user_exit, R.anim.screen_user_enter);
785                }
786
787                boolean needStart = false;
788
789                // If the user we are switching to is not currently started, then
790                // we need to start it now.
791                if (mStartedUsers.get(userId) == null) {
792                    UserState userState = new UserState(UserHandle.of(userId));
793                    mStartedUsers.put(userId, userState);
794                    getUserManagerInternal().setUserState(userId, userState.state);
795                    updateStartedUserArrayLocked();
796                    needStart = true;
797                }
798
799                final UserState uss = mStartedUsers.get(userId);
800                final Integer userIdInt = userId;
801                mUserLru.remove(userIdInt);
802                mUserLru.add(userIdInt);
803
804                if (foreground) {
805                    mCurrentUserId = userId;
806                    mService.updateUserConfigurationLocked();
807                    mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
808                    updateCurrentProfileIdsLocked();
809                    mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
810                    // Once the internal notion of the active user has switched, we lock the device
811                    // with the option to show the user switcher on the keyguard.
812                    mService.mWindowManager.lockNow(null);
813                } else {
814                    final Integer currentUserIdInt = mCurrentUserId;
815                    updateCurrentProfileIdsLocked();
816                    mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
817                    mUserLru.remove(currentUserIdInt);
818                    mUserLru.add(currentUserIdInt);
819                }
820
821                // Make sure user is in the started state.  If it is currently
822                // stopping, we need to knock that off.
823                if (uss.state == UserState.STATE_STOPPING) {
824                    // If we are stopping, we haven't sent ACTION_SHUTDOWN,
825                    // so we can just fairly silently bring the user back from
826                    // the almost-dead.
827                    uss.setState(uss.lastState);
828                    getUserManagerInternal().setUserState(userId, uss.state);
829                    updateStartedUserArrayLocked();
830                    needStart = true;
831                } else if (uss.state == UserState.STATE_SHUTDOWN) {
832                    // This means ACTION_SHUTDOWN has been sent, so we will
833                    // need to treat this as a new boot of the user.
834                    uss.setState(UserState.STATE_BOOTING);
835                    getUserManagerInternal().setUserState(userId, uss.state);
836                    updateStartedUserArrayLocked();
837                    needStart = true;
838                }
839
840                if (uss.state == UserState.STATE_BOOTING) {
841                    // Give user manager a chance to propagate user restrictions
842                    // to other services and prepare app storage
843                    getUserManager().onBeforeStartUser(userId);
844
845                    // Booting up a new user, need to tell system services about it.
846                    // Note that this is on the same handler as scheduling of broadcasts,
847                    // which is important because it needs to go first.
848                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
849                }
850
851                if (foreground) {
852                    mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
853                            oldUserId));
854                    mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
855                    mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
856                    mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
857                            oldUserId, userId, uss));
858                    mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
859                            oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
860                }
861
862                if (needStart) {
863                    // Send USER_STARTED broadcast
864                    Intent intent = new Intent(Intent.ACTION_USER_STARTED);
865                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
866                            | Intent.FLAG_RECEIVER_FOREGROUND);
867                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
868                    mService.broadcastIntentLocked(null, null, intent,
869                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
870                            null, false, false, MY_PID, SYSTEM_UID, userId);
871                }
872
873                if (foreground) {
874                    moveUserToForegroundLocked(uss, oldUserId, userId);
875                } else {
876                    mService.mUserController.finishUserBoot(uss);
877                }
878
879                if (needStart) {
880                    Intent intent = new Intent(Intent.ACTION_USER_STARTING);
881                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
882                    intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
883                    mService.broadcastIntentLocked(null, null, intent,
884                            null, new IIntentReceiver.Stub() {
885                                @Override
886                                public void performReceive(Intent intent, int resultCode,
887                                        String data, Bundle extras, boolean ordered, boolean sticky,
888                                        int sendingUser) throws RemoteException {
889                                }
890                            }, 0, null, null,
891                            new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
892                            null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
893                }
894            }
895        } finally {
896            Binder.restoreCallingIdentity(ident);
897        }
898
899        return true;
900    }
901
902    /**
903     * Start user, if its not already running, and bring it to foreground.
904     */
905    boolean startUserInForeground(final int userId, Dialog dlg) {
906        boolean result = startUser(userId, /* foreground */ true);
907        dlg.dismiss();
908        return result;
909    }
910
911    boolean unlockUser(final int userId, byte[] token, byte[] secret, IProgressListener listener) {
912        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
913                != PackageManager.PERMISSION_GRANTED) {
914            String msg = "Permission Denial: unlockUser() from pid="
915                    + Binder.getCallingPid()
916                    + ", uid=" + Binder.getCallingUid()
917                    + " requires " + INTERACT_ACROSS_USERS_FULL;
918            Slog.w(TAG, msg);
919            throw new SecurityException(msg);
920        }
921
922        final long binderToken = Binder.clearCallingIdentity();
923        try {
924            return unlockUserCleared(userId, token, secret, listener);
925        } finally {
926            Binder.restoreCallingIdentity(binderToken);
927        }
928    }
929
930    /**
931     * Attempt to unlock user without a credential token. This typically
932     * succeeds when the device doesn't have credential-encrypted storage, or
933     * when the the credential-encrypted storage isn't tied to a user-provided
934     * PIN or pattern.
935     */
936    boolean maybeUnlockUser(final int userId) {
937        // Try unlocking storage using empty token
938        return unlockUserCleared(userId, null, null, null);
939    }
940
941    private static void notifyFinished(int userId, IProgressListener listener) {
942        if (listener == null) return;
943        try {
944            listener.onFinished(userId, null);
945        } catch (RemoteException ignored) {
946        }
947    }
948
949    boolean unlockUserCleared(final int userId, byte[] token, byte[] secret,
950            IProgressListener listener) {
951        synchronized (mService) {
952            // TODO Move this block outside of synchronized if it causes lock contention
953            if (!StorageManager.isUserKeyUnlocked(userId)) {
954                final UserInfo userInfo = getUserInfo(userId);
955                final IMountService mountService = getMountService();
956                try {
957                    // We always want to unlock user storage, even user is not started yet
958                    mountService.unlockUserKey(userId, userInfo.serialNumber, token, secret);
959                } catch (RemoteException | RuntimeException e) {
960                    Slog.w(TAG, "Failed to unlock: " + e.getMessage());
961                }
962            }
963            // Bail if user isn't actually running, otherwise register the given
964            // listener to watch for unlock progress
965            final UserState uss = mStartedUsers.get(userId);
966            if (uss == null) {
967                notifyFinished(userId, listener);
968                return false;
969            } else {
970                uss.mUnlockProgress.addListener(listener);
971            }
972
973            finishUserUnlocking(uss);
974
975            // We just unlocked a user, so let's now attempt to unlock any
976            // managed profiles under that user.
977            for (int i = 0; i < mStartedUsers.size(); i++) {
978                final int testUserId = mStartedUsers.keyAt(i);
979                final UserInfo parent = getUserManager().getProfileParent(testUserId);
980                if (parent != null && parent.id == userId && testUserId != userId) {
981                    Slog.d(TAG, "User " + testUserId + " (parent " + parent.id
982                            + "): attempting unlock because parent was just unlocked");
983                    maybeUnlockUser(testUserId);
984                }
985            }
986        }
987
988        return true;
989    }
990
991    void showUserSwitchDialog(Pair<UserInfo, UserInfo> fromToUserPair) {
992        // The dialog will show and then initiate the user switch by calling startUserInForeground
993        Dialog d = new UserSwitchingDialog(mService, mService.mContext, fromToUserPair.first,
994                fromToUserPair.second, true /* above system */);
995        d.show();
996    }
997
998    void dispatchForegroundProfileChanged(int userId) {
999        final int observerCount = mUserSwitchObservers.beginBroadcast();
1000        for (int i = 0; i < observerCount; i++) {
1001            try {
1002                mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
1003            } catch (RemoteException e) {
1004                // Ignore
1005            }
1006        }
1007        mUserSwitchObservers.finishBroadcast();
1008    }
1009
1010    /** Called on handler thread */
1011    void dispatchUserSwitchComplete(int userId) {
1012        final int observerCount = mUserSwitchObservers.beginBroadcast();
1013        for (int i = 0; i < observerCount; i++) {
1014            try {
1015                mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
1016            } catch (RemoteException e) {
1017            }
1018        }
1019        mUserSwitchObservers.finishBroadcast();
1020    }
1021
1022    private void stopBackgroundUsersIfEnforced(int oldUserId) {
1023        // Never stop system user
1024        if (oldUserId == UserHandle.USER_SYSTEM) {
1025            return;
1026        }
1027        // For now, only check for user restriction. Additional checks can be added here
1028        boolean disallowRunInBg = hasUserRestriction(UserManager.DISALLOW_RUN_IN_BACKGROUND,
1029                oldUserId);
1030        if (!disallowRunInBg) {
1031            return;
1032        }
1033        synchronized (mService) {
1034            if (DEBUG_MU) Slog.i(TAG, "stopBackgroundUsersIfEnforced stopping " + oldUserId
1035                    + " and related users");
1036            stopUsersLocked(oldUserId, false, null);
1037        }
1038    }
1039
1040    void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
1041        synchronized (mService) {
1042            Slog.wtf(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
1043            sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1044        }
1045    }
1046
1047    void dispatchUserSwitch(final UserState uss, final int oldUserId, final int newUserId) {
1048        Slog.d(TAG, "Dispatch onUserSwitching oldUser #" + oldUserId + " newUser #" + newUserId);
1049        final int observerCount = mUserSwitchObservers.beginBroadcast();
1050        if (observerCount > 0) {
1051            final IRemoteCallback callback = new IRemoteCallback.Stub() {
1052                int mCount = 0;
1053                @Override
1054                public void sendResult(Bundle data) throws RemoteException {
1055                    synchronized (mService) {
1056                        if (mCurUserSwitchCallback == this) {
1057                            mCount++;
1058                            if (mCount == observerCount) {
1059                                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1060                            }
1061                        }
1062                    }
1063                }
1064            };
1065            synchronized (mService) {
1066                uss.switching = true;
1067                mCurUserSwitchCallback = callback;
1068            }
1069            for (int i = 0; i < observerCount; i++) {
1070                try {
1071                    mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
1072                            newUserId, callback);
1073                } catch (RemoteException e) {
1074                }
1075            }
1076        } else {
1077            synchronized (mService) {
1078                sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
1079            }
1080        }
1081        mUserSwitchObservers.finishBroadcast();
1082    }
1083
1084    void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
1085        mCurUserSwitchCallback = null;
1086        mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
1087        mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
1088                oldUserId, newUserId, uss));
1089    }
1090
1091    void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
1092        Slog.d(TAG, "Continue user switch oldUser #" + oldUserId + ", newUser #" + newUserId);
1093        synchronized (mService) {
1094            mService.mWindowManager.stopFreezingScreen();
1095        }
1096        uss.switching = false;
1097        mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
1098        mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
1099                newUserId, 0));
1100        stopGuestOrEphemeralUserIfBackground();
1101        stopBackgroundUsersIfEnforced(oldUserId);
1102    }
1103
1104    void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
1105        boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
1106        if (homeInFront) {
1107            mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
1108        } else {
1109            mService.mStackSupervisor.resumeFocusedStackTopActivityLocked();
1110        }
1111        EventLogTags.writeAmSwitchUser(newUserId);
1112        sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
1113    }
1114
1115    void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
1116        long ident = Binder.clearCallingIdentity();
1117        try {
1118            Intent intent;
1119            if (oldUserId >= 0) {
1120                // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
1121                List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
1122                int count = profiles.size();
1123                for (int i = 0; i < count; i++) {
1124                    int profileUserId = profiles.get(i).id;
1125                    intent = new Intent(Intent.ACTION_USER_BACKGROUND);
1126                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1127                            | Intent.FLAG_RECEIVER_FOREGROUND);
1128                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1129                    mService.broadcastIntentLocked(null, null, intent,
1130                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1131                            null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1132                }
1133            }
1134            if (newUserId >= 0) {
1135                // Send USER_FOREGROUND broadcast to all profiles of the incoming user
1136                List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
1137                int count = profiles.size();
1138                for (int i = 0; i < count; i++) {
1139                    int profileUserId = profiles.get(i).id;
1140                    intent = new Intent(Intent.ACTION_USER_FOREGROUND);
1141                    intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1142                            | Intent.FLAG_RECEIVER_FOREGROUND);
1143                    intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
1144                    mService.broadcastIntentLocked(null, null, intent,
1145                            null, null, 0, null, null, null, AppOpsManager.OP_NONE,
1146                            null, false, false, MY_PID, SYSTEM_UID, profileUserId);
1147                }
1148                intent = new Intent(Intent.ACTION_USER_SWITCHED);
1149                intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
1150                        | Intent.FLAG_RECEIVER_FOREGROUND);
1151                intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
1152                mService.broadcastIntentLocked(null, null, intent,
1153                        null, null, 0, null, null,
1154                        new String[] {android.Manifest.permission.MANAGE_USERS},
1155                        AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
1156                        UserHandle.USER_ALL);
1157            }
1158        } finally {
1159            Binder.restoreCallingIdentity(ident);
1160        }
1161    }
1162
1163
1164    int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
1165            int allowMode, String name, String callerPackage) {
1166        final int callingUserId = UserHandle.getUserId(callingUid);
1167        if (callingUserId == userId) {
1168            return userId;
1169        }
1170
1171        // Note that we may be accessing mCurrentUserId outside of a lock...
1172        // shouldn't be a big deal, if this is being called outside
1173        // of a locked context there is intrinsically a race with
1174        // the value the caller will receive and someone else changing it.
1175        // We assume that USER_CURRENT_OR_SELF will use the current user; later
1176        // we will switch to the calling user if access to the current user fails.
1177        int targetUserId = unsafeConvertIncomingUserLocked(userId);
1178
1179        if (callingUid != 0 && callingUid != SYSTEM_UID) {
1180            final boolean allow;
1181            if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
1182                    callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
1183                // If the caller has this permission, they always pass go.  And collect $200.
1184                allow = true;
1185            } else if (allowMode == ALLOW_FULL_ONLY) {
1186                // We require full access, sucks to be you.
1187                allow = false;
1188            } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
1189                    callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
1190                // If the caller does not have either permission, they are always doomed.
1191                allow = false;
1192            } else if (allowMode == ALLOW_NON_FULL) {
1193                // We are blanket allowing non-full access, you lucky caller!
1194                allow = true;
1195            } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
1196                // We may or may not allow this depending on whether the two users are
1197                // in the same profile.
1198                allow = isSameProfileGroup(callingUserId, targetUserId);
1199            } else {
1200                throw new IllegalArgumentException("Unknown mode: " + allowMode);
1201            }
1202            if (!allow) {
1203                if (userId == UserHandle.USER_CURRENT_OR_SELF) {
1204                    // In this case, they would like to just execute as their
1205                    // owner user instead of failing.
1206                    targetUserId = callingUserId;
1207                } else {
1208                    StringBuilder builder = new StringBuilder(128);
1209                    builder.append("Permission Denial: ");
1210                    builder.append(name);
1211                    if (callerPackage != null) {
1212                        builder.append(" from ");
1213                        builder.append(callerPackage);
1214                    }
1215                    builder.append(" asks to run as user ");
1216                    builder.append(userId);
1217                    builder.append(" but is calling from user ");
1218                    builder.append(UserHandle.getUserId(callingUid));
1219                    builder.append("; this requires ");
1220                    builder.append(INTERACT_ACROSS_USERS_FULL);
1221                    if (allowMode != ALLOW_FULL_ONLY) {
1222                        builder.append(" or ");
1223                        builder.append(INTERACT_ACROSS_USERS);
1224                    }
1225                    String msg = builder.toString();
1226                    Slog.w(TAG, msg);
1227                    throw new SecurityException(msg);
1228                }
1229            }
1230        }
1231        if (!allowAll && targetUserId < 0) {
1232            throw new IllegalArgumentException(
1233                    "Call does not support special user #" + targetUserId);
1234        }
1235        // Check shell permission
1236        if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
1237            if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
1238                throw new SecurityException("Shell does not have permission to access user "
1239                        + targetUserId + "\n " + Debug.getCallers(3));
1240            }
1241        }
1242        return targetUserId;
1243    }
1244
1245    int unsafeConvertIncomingUserLocked(int userId) {
1246        return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
1247                ? getCurrentUserIdLocked(): userId;
1248    }
1249
1250    void registerUserSwitchObserver(IUserSwitchObserver observer) {
1251        if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1252                != PackageManager.PERMISSION_GRANTED) {
1253            final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
1254                    + Binder.getCallingPid()
1255                    + ", uid=" + Binder.getCallingUid()
1256                    + " requires " + INTERACT_ACROSS_USERS_FULL;
1257            Slog.w(TAG, msg);
1258            throw new SecurityException(msg);
1259        }
1260
1261        mUserSwitchObservers.register(observer);
1262    }
1263
1264    void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
1265        mUserSwitchObservers.unregister(observer);
1266    }
1267
1268    UserState getStartedUserStateLocked(int userId) {
1269        return mStartedUsers.get(userId);
1270    }
1271
1272    boolean hasStartedUserState(int userId) {
1273        return mStartedUsers.get(userId) != null;
1274    }
1275
1276    private void updateStartedUserArrayLocked() {
1277        int num = 0;
1278        for (int i = 0; i < mStartedUsers.size(); i++) {
1279            UserState uss = mStartedUsers.valueAt(i);
1280            // This list does not include stopping users.
1281            if (uss.state != UserState.STATE_STOPPING
1282                    && uss.state != UserState.STATE_SHUTDOWN) {
1283                num++;
1284            }
1285        }
1286        mStartedUserArray = new int[num];
1287        num = 0;
1288        for (int i = 0; i < mStartedUsers.size(); i++) {
1289            UserState uss = mStartedUsers.valueAt(i);
1290            if (uss.state != UserState.STATE_STOPPING
1291                    && uss.state != UserState.STATE_SHUTDOWN) {
1292                mStartedUserArray[num++] = mStartedUsers.keyAt(i);
1293            }
1294        }
1295    }
1296
1297    void sendBootCompletedLocked(IIntentReceiver resultTo) {
1298        for (int i = 0; i < mStartedUsers.size(); i++) {
1299            UserState uss = mStartedUsers.valueAt(i);
1300            finishUserBoot(uss, resultTo);
1301        }
1302    }
1303
1304    void onSystemReady() {
1305        updateCurrentProfileIdsLocked();
1306    }
1307
1308    /**
1309     * Refreshes the list of users related to the current user when either a
1310     * user switch happens or when a new related user is started in the
1311     * background.
1312     */
1313    private void updateCurrentProfileIdsLocked() {
1314        final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
1315                false /* enabledOnly */);
1316        int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
1317        for (int i = 0; i < currentProfileIds.length; i++) {
1318            currentProfileIds[i] = profiles.get(i).id;
1319        }
1320        mCurrentProfileIds = currentProfileIds;
1321
1322        synchronized (mUserProfileGroupIdsSelfLocked) {
1323            mUserProfileGroupIdsSelfLocked.clear();
1324            final List<UserInfo> users = getUserManager().getUsers(false);
1325            for (int i = 0; i < users.size(); i++) {
1326                UserInfo user = users.get(i);
1327                if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
1328                    mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
1329                }
1330            }
1331        }
1332    }
1333
1334    int[] getStartedUserArrayLocked() {
1335        return mStartedUserArray;
1336    }
1337
1338    boolean isUserStoppingOrShuttingDownLocked(int userId) {
1339        UserState state = getStartedUserStateLocked(userId);
1340        if (state == null) {
1341            return false;
1342        }
1343        return state.state == UserState.STATE_STOPPING
1344                || state.state == UserState.STATE_SHUTDOWN;
1345    }
1346
1347    boolean isUserRunningLocked(int userId, int flags) {
1348        UserState state = getStartedUserStateLocked(userId);
1349        if (state == null) {
1350            return false;
1351        }
1352        if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
1353            return true;
1354        }
1355        if ((flags & ActivityManager.FLAG_AND_LOCKED) != 0) {
1356            switch (state.state) {
1357                case UserState.STATE_BOOTING:
1358                case UserState.STATE_RUNNING_LOCKED:
1359                    return true;
1360                default:
1361                    return false;
1362            }
1363        }
1364        if ((flags & ActivityManager.FLAG_AND_UNLOCKING_OR_UNLOCKED) != 0) {
1365            switch (state.state) {
1366                case UserState.STATE_RUNNING_UNLOCKING:
1367                case UserState.STATE_RUNNING_UNLOCKED:
1368                    return true;
1369                default:
1370                    return false;
1371            }
1372        }
1373        if ((flags & ActivityManager.FLAG_AND_UNLOCKED) != 0) {
1374            switch (state.state) {
1375                case UserState.STATE_RUNNING_UNLOCKED:
1376                    return true;
1377                default:
1378                    return false;
1379            }
1380        }
1381
1382        // One way or another, we're running!
1383        return true;
1384    }
1385
1386    UserInfo getCurrentUser() {
1387        if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1388                != PackageManager.PERMISSION_GRANTED) && (
1389                mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1390                        != PackageManager.PERMISSION_GRANTED)) {
1391            String msg = "Permission Denial: getCurrentUser() from pid="
1392                    + Binder.getCallingPid()
1393                    + ", uid=" + Binder.getCallingUid()
1394                    + " requires " + INTERACT_ACROSS_USERS;
1395            Slog.w(TAG, msg);
1396            throw new SecurityException(msg);
1397        }
1398        synchronized (mService) {
1399            return getCurrentUserLocked();
1400        }
1401    }
1402
1403    UserInfo getCurrentUserLocked() {
1404        int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1405        return getUserInfo(userId);
1406    }
1407
1408    int getCurrentOrTargetUserIdLocked() {
1409        return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
1410    }
1411
1412    int getCurrentUserIdLocked() {
1413        return mCurrentUserId;
1414    }
1415
1416    private boolean isCurrentUserLocked(int userId) {
1417        return userId == getCurrentOrTargetUserIdLocked();
1418    }
1419
1420    int setTargetUserIdLocked(int targetUserId) {
1421        return mTargetUserId = targetUserId;
1422    }
1423
1424    int[] getUsers() {
1425        UserManagerService ums = getUserManager();
1426        return ums != null ? ums.getUserIds() : new int[] { 0 };
1427    }
1428
1429    UserInfo getUserInfo(int userId) {
1430        return getUserManager().getUserInfo(userId);
1431    }
1432
1433    int[] getUserIds() {
1434        return getUserManager().getUserIds();
1435    }
1436
1437    boolean exists(int userId) {
1438        return getUserManager().exists(userId);
1439    }
1440
1441    boolean hasUserRestriction(String restriction, int userId) {
1442        return getUserManager().hasUserRestriction(restriction, userId);
1443    }
1444
1445    Set<Integer> getProfileIds(int userId) {
1446        Set<Integer> userIds = new HashSet<>();
1447        final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1448                false /* enabledOnly */);
1449        for (UserInfo user : profiles) {
1450            userIds.add(user.id);
1451        }
1452        return userIds;
1453    }
1454
1455    boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1456        synchronized (mUserProfileGroupIdsSelfLocked) {
1457            int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1458                    UserInfo.NO_PROFILE_GROUP_ID);
1459            int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1460                    UserInfo.NO_PROFILE_GROUP_ID);
1461            return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1462                    && callingProfile == targetProfile;
1463        }
1464    }
1465
1466    boolean isCurrentProfileLocked(int userId) {
1467        return ArrayUtils.contains(mCurrentProfileIds, userId);
1468    }
1469
1470    int[] getCurrentProfileIdsLocked() {
1471        return mCurrentProfileIds;
1472    }
1473
1474    /**
1475     * Returns whether the given user requires credential entry at this time. This is used to
1476     * intercept activity launches for work apps when the Work Challenge is present.
1477     */
1478    boolean shouldConfirmCredentials(int userId) {
1479        synchronized (mService) {
1480            if (mStartedUsers.get(userId) == null) {
1481                return false;
1482            }
1483        }
1484        if (!mLockPatternUtils.isSeparateProfileChallengeEnabled(userId)) {
1485            return false;
1486        }
1487        final KeyguardManager km = (KeyguardManager) mService.mContext
1488                .getSystemService(KEYGUARD_SERVICE);
1489        return km.isDeviceLocked(userId) && km.isDeviceSecure(userId);
1490    }
1491
1492    boolean isLockScreenDisabled(@UserIdInt int userId) {
1493        return mLockPatternUtils.isLockScreenDisabled(userId);
1494    }
1495
1496    private UserManagerInternal getUserManagerInternal() {
1497        if (mUserManagerInternal == null) {
1498            mUserManagerInternal = LocalServices.getService(UserManagerInternal.class);
1499        }
1500        return mUserManagerInternal;
1501    }
1502
1503    void dump(PrintWriter pw, boolean dumpAll) {
1504        pw.println("  mStartedUsers:");
1505        for (int i = 0; i < mStartedUsers.size(); i++) {
1506            UserState uss = mStartedUsers.valueAt(i);
1507            pw.print("    User #"); pw.print(uss.mHandle.getIdentifier());
1508            pw.print(": "); uss.dump("", pw);
1509        }
1510        pw.print("  mStartedUserArray: [");
1511        for (int i = 0; i < mStartedUserArray.length; i++) {
1512            if (i > 0) pw.print(", ");
1513            pw.print(mStartedUserArray[i]);
1514        }
1515        pw.println("]");
1516        pw.print("  mUserLru: [");
1517        for (int i = 0; i < mUserLru.size(); i++) {
1518            if (i > 0) pw.print(", ");
1519            pw.print(mUserLru.get(i));
1520        }
1521        pw.println("]");
1522        if (dumpAll) {
1523            pw.print("  mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1524        }
1525        synchronized (mUserProfileGroupIdsSelfLocked) {
1526            if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1527                pw.println("  mUserProfileGroupIds:");
1528                for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1529                    pw.print("    User #");
1530                    pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1531                    pw.print(" -> profile #");
1532                    pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1533                }
1534            }
1535        }
1536    }
1537}
1538