blob: e04f138fb4219a6c5ac8baa9f3b4099b49ed9c7f [file] [log] [blame]
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001/*
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_IS_CURRENT;
22import static android.app.ActivityManager.USER_OP_SUCCESS;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070023import static android.os.Process.SYSTEM_UID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070024import static com.android.server.am.ActivityManagerDebugConfig.DEBUG_MU;
25import static com.android.server.am.ActivityManagerDebugConfig.TAG_AM;
26import static com.android.server.am.ActivityManagerDebugConfig.TAG_WITH_CLASS_NAME;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070027import static com.android.server.am.ActivityManagerService.ALLOW_FULL_ONLY;
28import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL;
29import static com.android.server.am.ActivityManagerService.ALLOW_NON_FULL_IN_PROFILE;
30import static com.android.server.am.ActivityManagerService.MY_PID;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070031import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_COMPLETE_MSG;
32import static com.android.server.am.ActivityManagerService.REPORT_USER_SWITCH_MSG;
33import static com.android.server.am.ActivityManagerService.SYSTEM_USER_CURRENT_MSG;
34import static com.android.server.am.ActivityManagerService.SYSTEM_USER_START_MSG;
35import static com.android.server.am.ActivityManagerService.USER_SWITCH_TIMEOUT_MSG;
36
37import android.app.ActivityManager;
38import android.app.AppOpsManager;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070039import android.app.Dialog;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070040import android.app.IStopUserCallback;
41import android.app.IUserSwitchObserver;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070042import android.content.Context;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070043import android.content.IIntentReceiver;
44import android.content.Intent;
45import android.content.pm.PackageManager;
46import android.content.pm.UserInfo;
47import android.os.BatteryStats;
48import android.os.Binder;
49import android.os.Bundle;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070050import android.os.Debug;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070051import android.os.Handler;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070052import android.os.IBinder;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070053import android.os.IRemoteCallback;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070054import android.os.IUserManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070055import android.os.Process;
56import android.os.RemoteCallbackList;
57import android.os.RemoteException;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070058import android.os.ServiceManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080059import android.os.SystemProperties;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070060import android.os.UserHandle;
61import android.os.UserManager;
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -080062import android.os.storage.IMountService;
63import android.os.storage.StorageManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070064import android.util.Slog;
65import android.util.SparseArray;
66import android.util.SparseIntArray;
67
68import com.android.internal.R;
Jeff Sharkeyba512352015-11-12 20:17:45 -080069import com.android.internal.annotations.GuardedBy;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070070import com.android.internal.util.ArrayUtils;
71import com.android.server.pm.UserManagerService;
72
73import java.io.PrintWriter;
74import java.util.ArrayList;
75import java.util.Arrays;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070076import java.util.HashSet;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070077import java.util.List;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070078import java.util.Set;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070079
80/**
81 * Helper class for {@link ActivityManagerService} responsible for multi-user functionality.
82 */
83final class UserController {
84 private static final String TAG = TAG_WITH_CLASS_NAME ? "UserController" : TAG_AM;
85 // Maximum number of users we allow to be running at a time.
86 static final int MAX_RUNNING_USERS = 3;
87
88 // Amount of time we wait for observers to handle a user switch before
89 // giving up on them and unfreezing the screen.
90 static final int USER_SWITCH_TIMEOUT = 2 * 1000;
91
92 private final ActivityManagerService mService;
93 private final Handler mHandler;
94
95 // Holds the current foreground user's id
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070096 private int mCurrentUserId = UserHandle.USER_SYSTEM;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070097 // Holds the target user's id during a user switch
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -070098 private int mTargetUserId = UserHandle.USER_NULL;
Fyodor Kupolov610acda2015-10-19 18:44:07 -070099
100 /**
101 * Which users have been started, so are allowed to run code.
102 */
Jeff Sharkeyba512352015-11-12 20:17:45 -0800103 @GuardedBy("mService")
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700104 private final SparseArray<UserState> mStartedUsers = new SparseArray<>();
Jeff Sharkeyba512352015-11-12 20:17:45 -0800105
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700106 /**
107 * LRU list of history of current users. Most recently current is at the end.
108 */
109 private final ArrayList<Integer> mUserLru = new ArrayList<>();
110
111 /**
112 * Constant array of the users that are currently started.
113 */
114 private int[] mStartedUserArray = new int[] { 0 };
115
116 // If there are multiple profiles for the current user, their ids are here
117 // Currently only the primary user can have managed profiles
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700118 private int[] mCurrentProfileIds = new int[] {};
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700119
120 /**
121 * Mapping from each known user ID to the profile group ID it is associated with.
122 */
123 private final SparseIntArray mUserProfileGroupIdsSelfLocked = new SparseIntArray();
124
125 /**
126 * Registered observers of the user switching mechanics.
127 */
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700128 private final RemoteCallbackList<IUserSwitchObserver> mUserSwitchObservers
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700129 = new RemoteCallbackList<>();
130
131 /**
132 * Currently active user switch.
133 */
134 Object mCurUserSwitchCallback;
135
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700136 private volatile UserManagerService mUserManager;
137
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700138 UserController(ActivityManagerService service) {
139 mService = service;
140 mHandler = mService.mHandler;
141 // User 0 is the first and only user that runs at boot.
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800142 final UserState uss = new UserState(UserHandle.SYSTEM);
143 mStartedUsers.put(UserHandle.USER_SYSTEM, uss);
144 updateUserUnlockedState(uss);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700145 mUserLru.add(UserHandle.USER_SYSTEM);
146 updateStartedUserArrayLocked();
147 }
148
149 void finishUserSwitch(UserState uss) {
150 synchronized (mService) {
151 finishUserBoot(uss);
152
153 startProfilesLocked();
154
155 int num = mUserLru.size();
156 int i = 0;
157 while (num > MAX_RUNNING_USERS && i < mUserLru.size()) {
158 Integer oldUserId = mUserLru.get(i);
159 UserState oldUss = mStartedUsers.get(oldUserId);
160 if (oldUss == null) {
161 // Shouldn't happen, but be sane if it does.
162 mUserLru.remove(i);
163 num--;
164 continue;
165 }
166 if (oldUss.mState == UserState.STATE_STOPPING
167 || oldUss.mState == UserState.STATE_SHUTDOWN) {
168 // This user is already stopping, doesn't count.
169 num--;
170 i++;
171 continue;
172 }
173 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId) {
174 // Owner/System user and current user can't be stopped. We count it as running
175 // when it is not a pure system user.
176 if (UserInfo.isSystemOnly(oldUserId)) {
177 num--;
178 }
179 i++;
180 continue;
181 }
182 // This is a user to be stopped.
183 stopUserLocked(oldUserId, null);
184 num--;
185 i++;
186 }
187 }
188 }
189
190 void finishUserBoot(UserState uss) {
191 synchronized (mService) {
192 if (uss.mState == UserState.STATE_BOOTING
193 && mStartedUsers.get(uss.mHandle.getIdentifier()) == uss) {
194 uss.mState = UserState.STATE_RUNNING;
195 final int userId = uss.mHandle.getIdentifier();
196 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
197 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
198 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
199 mService.broadcastIntentLocked(null, null, intent,
200 null, null, 0, null, null,
201 new String[]{android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700202 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700203 }
204 }
205 }
206
207 int stopUser(final int userId, final IStopUserCallback callback) {
208 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
209 != PackageManager.PERMISSION_GRANTED) {
210 String msg = "Permission Denial: switchUser() from pid="
211 + Binder.getCallingPid()
212 + ", uid=" + Binder.getCallingUid()
213 + " requires " + INTERACT_ACROSS_USERS_FULL;
214 Slog.w(TAG, msg);
215 throw new SecurityException(msg);
216 }
217 if (userId < 0 || userId == UserHandle.USER_SYSTEM) {
218 throw new IllegalArgumentException("Can't stop system user " + userId);
219 }
220 mService.enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES,
221 userId);
222 synchronized (mService) {
223 return stopUserLocked(userId, callback);
224 }
225 }
226
227 private int stopUserLocked(final int userId, final IStopUserCallback callback) {
228 if (DEBUG_MU) Slog.i(TAG, "stopUserLocked userId=" + userId);
229 if (mCurrentUserId == userId && mTargetUserId == UserHandle.USER_NULL) {
230 return USER_OP_IS_CURRENT;
231 }
232
233 final UserState uss = mStartedUsers.get(userId);
234 if (uss == null) {
235 // User is not started, nothing to do... but we do need to
236 // callback if requested.
237 if (callback != null) {
238 mHandler.post(new Runnable() {
239 @Override
240 public void run() {
241 try {
242 callback.userStopped(userId);
243 } catch (RemoteException e) {
244 }
245 }
246 });
247 }
248 return USER_OP_SUCCESS;
249 }
250
251 if (callback != null) {
252 uss.mStopCallbacks.add(callback);
253 }
254
255 if (uss.mState != UserState.STATE_STOPPING
256 && uss.mState != UserState.STATE_SHUTDOWN) {
257 uss.mState = UserState.STATE_STOPPING;
258 updateStartedUserArrayLocked();
259
260 long ident = Binder.clearCallingIdentity();
261 try {
262 // We are going to broadcast ACTION_USER_STOPPING and then
263 // once that is done send a final ACTION_SHUTDOWN and then
264 // stop the user.
265 final Intent stoppingIntent = new Intent(Intent.ACTION_USER_STOPPING);
266 stoppingIntent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
267 stoppingIntent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
268 stoppingIntent.putExtra(Intent.EXTRA_SHUTDOWN_USERSPACE_ONLY, true);
269 final Intent shutdownIntent = new Intent(Intent.ACTION_SHUTDOWN);
270 // This is the result receiver for the final shutdown broadcast.
271 final IIntentReceiver shutdownReceiver = new IIntentReceiver.Stub() {
272 @Override
273 public void performReceive(Intent intent, int resultCode, String data,
274 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
275 finishUserStop(uss);
276 }
277 };
278 // This is the result receiver for the initial stopping broadcast.
279 final IIntentReceiver stoppingReceiver = new IIntentReceiver.Stub() {
280 @Override
281 public void performReceive(Intent intent, int resultCode, String data,
282 Bundle extras, boolean ordered, boolean sticky, int sendingUser) {
283 // On to the next.
284 synchronized (mService) {
285 if (uss.mState != UserState.STATE_STOPPING) {
286 // Whoops, we are being started back up. Abort, abort!
287 return;
288 }
289 uss.mState = UserState.STATE_SHUTDOWN;
290 }
291 mService.mBatteryStatsService.noteEvent(
292 BatteryStats.HistoryItem.EVENT_USER_RUNNING_FINISH,
293 Integer.toString(userId), userId);
294 mService.mSystemServiceManager.stopUser(userId);
295 mService.broadcastIntentLocked(null, null, shutdownIntent,
296 null, shutdownReceiver, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700297 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700298 }
299 };
300 // Kick things off.
301 mService.broadcastIntentLocked(null, null, stoppingIntent,
302 null, stoppingReceiver, 0, null, null,
303 new String[]{INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700304 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700305 } finally {
306 Binder.restoreCallingIdentity(ident);
307 }
308 }
309
310 return USER_OP_SUCCESS;
311 }
312
313 void finishUserStop(UserState uss) {
314 final int userId = uss.mHandle.getIdentifier();
315 boolean stopped;
316 ArrayList<IStopUserCallback> callbacks;
317 synchronized (mService) {
318 callbacks = new ArrayList<>(uss.mStopCallbacks);
319 if (mStartedUsers.get(userId) != uss) {
320 stopped = false;
321 } else if (uss.mState != UserState.STATE_SHUTDOWN) {
322 stopped = false;
323 } else {
324 stopped = true;
325 // User can no longer run.
326 mStartedUsers.remove(userId);
327 mUserLru.remove(Integer.valueOf(userId));
328 updateStartedUserArrayLocked();
329
330 // Clean up all state and processes associated with the user.
331 // Kill all the processes for the user.
332 forceStopUserLocked(userId, "finish user");
333 }
334 }
335
336 for (int i = 0; i < callbacks.size(); i++) {
337 try {
338 if (stopped) callbacks.get(i).userStopped(userId);
339 else callbacks.get(i).userStopAborted(userId);
340 } catch (RemoteException e) {
341 }
342 }
343
344 if (stopped) {
345 mService.mSystemServiceManager.cleanupUser(userId);
346 synchronized (mService) {
347 mService.mStackSupervisor.removeUserLocked(userId);
348 }
349 }
350 }
351
352 private void forceStopUserLocked(int userId, String reason) {
353 mService.forceStopPackageLocked(null, -1, false, false, true, false, false,
354 userId, reason);
355 Intent intent = new Intent(Intent.ACTION_USER_STOPPED);
356 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
357 | Intent.FLAG_RECEIVER_FOREGROUND);
358 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
359 mService.broadcastIntentLocked(null, null, intent,
360 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700361 null, false, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700362 }
363
364
365 /**
366 * Stops the guest user if it has gone to the background.
367 */
368 private void stopGuestUserIfBackground() {
369 synchronized (mService) {
370 final int num = mUserLru.size();
371 for (int i = 0; i < num; i++) {
372 Integer oldUserId = mUserLru.get(i);
373 UserState oldUss = mStartedUsers.get(oldUserId);
374 if (oldUserId == UserHandle.USER_SYSTEM || oldUserId == mCurrentUserId
375 || oldUss.mState == UserState.STATE_STOPPING
376 || oldUss.mState == UserState.STATE_SHUTDOWN) {
377 continue;
378 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700379 UserInfo userInfo = getUserInfo(oldUserId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700380 if (userInfo.isGuest()) {
381 // This is a user to be stopped.
382 stopUserLocked(oldUserId, null);
383 break;
384 }
385 }
386 }
387 }
388
389 void startProfilesLocked() {
390 if (DEBUG_MU) Slog.i(TAG, "startProfilesLocked");
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700391 List<UserInfo> profiles = getUserManager().getProfiles(
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700392 mCurrentUserId, false /* enabledOnly */);
393 List<UserInfo> profilesToStart = new ArrayList<>(profiles.size());
394 for (UserInfo user : profiles) {
395 if ((user.flags & UserInfo.FLAG_INITIALIZED) == UserInfo.FLAG_INITIALIZED
396 && user.id != mCurrentUserId) {
397 profilesToStart.add(user);
398 }
399 }
400 final int profilesToStartSize = profilesToStart.size();
401 int i = 0;
402 for (; i < profilesToStartSize && i < (MAX_RUNNING_USERS - 1); ++i) {
403 startUser(profilesToStart.get(i).id, /* foreground= */ false);
404 }
405 if (i < profilesToStartSize) {
406 Slog.w(TAG, "More profiles than MAX_RUNNING_USERS");
407 }
408 }
409
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700410 private UserManagerService getUserManager() {
411 UserManagerService userManager = mUserManager;
412 if (userManager == null) {
413 IBinder b = ServiceManager.getService(Context.USER_SERVICE);
414 userManager = mUserManager = (UserManagerService) IUserManager.Stub.asInterface(b);
415 }
416 return userManager;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700417 }
418
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800419 private void updateUserUnlockedState(UserState uss) {
420 final IMountService mountService = IMountService.Stub
Jeff Sharkeyba512352015-11-12 20:17:45 -0800421 .asInterface(ServiceManager.getService("mount"));
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800422 if (mountService != null) {
423 try {
424 uss.unlocked = mountService.isUserKeyUnlocked(uss.mHandle.getIdentifier());
425 } catch (RemoteException e) {
426 throw e.rethrowAsRuntimeException();
427 }
428 } else {
429 // System isn't fully booted yet, so guess based on property
Jeff Sharkeyba512352015-11-12 20:17:45 -0800430 uss.unlocked = !StorageManager.isFileBasedEncryptionEnabled();
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800431 }
432 }
433
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700434 boolean startUser(final int userId, final boolean foreground) {
435 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
436 != PackageManager.PERMISSION_GRANTED) {
437 String msg = "Permission Denial: switchUser() from pid="
438 + Binder.getCallingPid()
439 + ", uid=" + Binder.getCallingUid()
440 + " requires " + INTERACT_ACROSS_USERS_FULL;
441 Slog.w(TAG, msg);
442 throw new SecurityException(msg);
443 }
444
445 if (DEBUG_MU) Slog.i(TAG, "starting userid:" + userId + " fore:" + foreground);
446
447 final long ident = Binder.clearCallingIdentity();
448 try {
449 synchronized (mService) {
450 final int oldUserId = mCurrentUserId;
451 if (oldUserId == userId) {
452 return true;
453 }
454
455 mService.mStackSupervisor.setLockTaskModeLocked(null,
456 ActivityManager.LOCK_TASK_MODE_NONE, "startUser", false);
457
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700458 final UserInfo userInfo = getUserInfo(userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700459 if (userInfo == null) {
460 Slog.w(TAG, "No user info for user #" + userId);
461 return false;
462 }
463 if (foreground && userInfo.isManagedProfile()) {
464 Slog.w(TAG, "Cannot switch to User #" + userId + ": not a full user");
465 return false;
466 }
467
468 if (foreground) {
469 mService.mWindowManager.startFreezingScreen(
470 R.anim.screen_user_exit, R.anim.screen_user_enter);
471 }
472
473 boolean needStart = false;
474
475 // If the user we are switching to is not currently started, then
476 // we need to start it now.
477 if (mStartedUsers.get(userId) == null) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800478 mStartedUsers.put(userId, new UserState(new UserHandle(userId)));
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700479 updateStartedUserArrayLocked();
480 needStart = true;
481 }
482
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -0800483 final UserState uss = mStartedUsers.get(userId);
484 updateUserUnlockedState(uss);
485
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700486 final Integer userIdInt = userId;
487 mUserLru.remove(userIdInt);
488 mUserLru.add(userIdInt);
489
490 if (foreground) {
491 mCurrentUserId = userId;
492 mService.updateUserConfigurationLocked();
493 mTargetUserId = UserHandle.USER_NULL; // reset, mCurrentUserId has caught up
494 updateCurrentProfileIdsLocked();
495 mService.mWindowManager.setCurrentUser(userId, mCurrentProfileIds);
496 // Once the internal notion of the active user has switched, we lock the device
497 // with the option to show the user switcher on the keyguard.
498 mService.mWindowManager.lockNow(null);
499 } else {
500 final Integer currentUserIdInt = mCurrentUserId;
501 updateCurrentProfileIdsLocked();
502 mService.mWindowManager.setCurrentProfileIds(mCurrentProfileIds);
503 mUserLru.remove(currentUserIdInt);
504 mUserLru.add(currentUserIdInt);
505 }
506
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700507 // Make sure user is in the started state. If it is currently
508 // stopping, we need to knock that off.
509 if (uss.mState == UserState.STATE_STOPPING) {
510 // If we are stopping, we haven't sent ACTION_SHUTDOWN,
511 // so we can just fairly silently bring the user back from
512 // the almost-dead.
513 uss.mState = UserState.STATE_RUNNING;
514 updateStartedUserArrayLocked();
515 needStart = true;
516 } else if (uss.mState == UserState.STATE_SHUTDOWN) {
517 // This means ACTION_SHUTDOWN has been sent, so we will
518 // need to treat this as a new boot of the user.
519 uss.mState = UserState.STATE_BOOTING;
520 updateStartedUserArrayLocked();
521 needStart = true;
522 }
523
524 if (uss.mState == UserState.STATE_BOOTING) {
525 // Booting up a new user, need to tell system services about it.
526 // Note that this is on the same handler as scheduling of broadcasts,
527 // which is important because it needs to go first.
528 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_START_MSG, userId, 0));
529 }
530
531 if (foreground) {
532 mHandler.sendMessage(mHandler.obtainMessage(SYSTEM_USER_CURRENT_MSG, userId,
533 oldUserId));
534 mHandler.removeMessages(REPORT_USER_SWITCH_MSG);
535 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
536 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_MSG,
537 oldUserId, userId, uss));
538 mHandler.sendMessageDelayed(mHandler.obtainMessage(USER_SWITCH_TIMEOUT_MSG,
539 oldUserId, userId, uss), USER_SWITCH_TIMEOUT);
540 }
541
542 if (needStart) {
543 // Send USER_STARTED broadcast
544 Intent intent = new Intent(Intent.ACTION_USER_STARTED);
545 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
546 | Intent.FLAG_RECEIVER_FOREGROUND);
547 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
548 mService.broadcastIntentLocked(null, null, intent,
549 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700550 null, false, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700551 }
552
553 if ((userInfo.flags&UserInfo.FLAG_INITIALIZED) == 0) {
554 if (userId != UserHandle.USER_SYSTEM) {
555 Intent intent = new Intent(Intent.ACTION_USER_INITIALIZE);
556 intent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND);
557 mService.broadcastIntentLocked(null, null, intent, null,
558 new IIntentReceiver.Stub() {
559 public void performReceive(Intent intent, int resultCode,
560 String data, Bundle extras, boolean ordered,
561 boolean sticky, int sendingUser) {
562 onUserInitialized(uss, foreground, oldUserId, userId);
563 }
564 }, 0, null, null, null, AppOpsManager.OP_NONE,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700565 null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700566 uss.initializing = true;
567 } else {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700568 getUserManager().makeInitialized(userInfo.id);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700569 }
570 }
571
572 if (foreground) {
573 if (!uss.initializing) {
574 moveUserToForegroundLocked(uss, oldUserId, userId);
575 }
576 } else {
577 mService.mStackSupervisor.startBackgroundUserLocked(userId, uss);
578 }
579
580 if (needStart) {
581 Intent intent = new Intent(Intent.ACTION_USER_STARTING);
582 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
583 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
584 mService.broadcastIntentLocked(null, null, intent,
585 null, new IIntentReceiver.Stub() {
586 @Override
587 public void performReceive(Intent intent, int resultCode,
588 String data, Bundle extras, boolean ordered, boolean sticky,
589 int sendingUser) throws RemoteException {
590 }
591 }, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700592 new String[] {INTERACT_ACROSS_USERS}, AppOpsManager.OP_NONE,
593 null, true, false, MY_PID, SYSTEM_UID, UserHandle.USER_ALL);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700594 }
595 }
596 } finally {
597 Binder.restoreCallingIdentity(ident);
598 }
599
600 return true;
601 }
602
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700603 /**
604 * Start user, if its not already running, and bring it to foreground.
605 */
606 boolean startUserInForeground(final int userId, Dialog dlg) {
607 boolean result = startUser(userId, /* foreground */ true);
608 dlg.dismiss();
609 return result;
610 }
611
Jeff Sharkeyba512352015-11-12 20:17:45 -0800612 boolean unlockUser(final int userId, byte[] token) {
613 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
614 != PackageManager.PERMISSION_GRANTED) {
615 String msg = "Permission Denial: unlockUser() from pid="
616 + Binder.getCallingPid()
617 + ", uid=" + Binder.getCallingUid()
618 + " requires " + INTERACT_ACROSS_USERS_FULL;
619 Slog.w(TAG, msg);
620 throw new SecurityException(msg);
621 }
622
623 final UserInfo userInfo = getUserInfo(userId);
624 final IMountService mountService = IMountService.Stub
625 .asInterface(ServiceManager.getService("mount"));
626 try {
627 mountService.unlockUserKey(userId, userInfo.serialNumber, token);
628 } catch (RemoteException e) {
629 Slog.w(TAG, "Failed to unlock: " + e.getMessage());
630 throw e.rethrowAsRuntimeException();
631 }
632
633 synchronized (mService) {
634 final UserState uss = mStartedUsers.get(userId);
635 updateUserUnlockedState(uss);
636 }
637
638 return true;
639 }
640
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700641 void showUserSwitchDialog(int userId, String userName) {
642 // The dialog will show and then initiate the user switch by calling startUserInForeground
643 Dialog d = new UserSwitchingDialog(mService, mService.mContext, userId, userName,
644 true /* above system */);
645 d.show();
646 }
647
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700648 void dispatchForegroundProfileChanged(int userId) {
649 final int observerCount = mUserSwitchObservers.beginBroadcast();
650 for (int i = 0; i < observerCount; i++) {
651 try {
652 mUserSwitchObservers.getBroadcastItem(i).onForegroundProfileSwitch(userId);
653 } catch (RemoteException e) {
654 // Ignore
655 }
656 }
657 mUserSwitchObservers.finishBroadcast();
658 }
659
660 /** Called on handler thread */
661 void dispatchUserSwitchComplete(int userId) {
662 final int observerCount = mUserSwitchObservers.beginBroadcast();
663 for (int i = 0; i < observerCount; i++) {
664 try {
665 mUserSwitchObservers.getBroadcastItem(i).onUserSwitchComplete(userId);
666 } catch (RemoteException e) {
667 }
668 }
669 mUserSwitchObservers.finishBroadcast();
670 }
671
672 void timeoutUserSwitch(UserState uss, int oldUserId, int newUserId) {
673 synchronized (mService) {
674 Slog.w(TAG, "User switch timeout: from " + oldUserId + " to " + newUserId);
675 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
676 }
677 }
678
679 void dispatchUserSwitch(final UserState uss, final int oldUserId,
680 final int newUserId) {
681 final int observerCount = mUserSwitchObservers.beginBroadcast();
682 if (observerCount > 0) {
683 final IRemoteCallback callback = new IRemoteCallback.Stub() {
684 int mCount = 0;
685 @Override
686 public void sendResult(Bundle data) throws RemoteException {
687 synchronized (mService) {
688 if (mCurUserSwitchCallback == this) {
689 mCount++;
690 if (mCount == observerCount) {
691 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
692 }
693 }
694 }
695 }
696 };
697 synchronized (mService) {
698 uss.switching = true;
699 mCurUserSwitchCallback = callback;
700 }
701 for (int i = 0; i < observerCount; i++) {
702 try {
703 mUserSwitchObservers.getBroadcastItem(i).onUserSwitching(
704 newUserId, callback);
705 } catch (RemoteException e) {
706 }
707 }
708 } else {
709 synchronized (mService) {
710 sendContinueUserSwitchLocked(uss, oldUserId, newUserId);
711 }
712 }
713 mUserSwitchObservers.finishBroadcast();
714 }
715
716 void sendContinueUserSwitchLocked(UserState uss, int oldUserId, int newUserId) {
717 mCurUserSwitchCallback = null;
718 mHandler.removeMessages(USER_SWITCH_TIMEOUT_MSG);
719 mHandler.sendMessage(mHandler.obtainMessage(ActivityManagerService.CONTINUE_USER_SWITCH_MSG,
720 oldUserId, newUserId, uss));
721 }
722
723 void continueUserSwitch(UserState uss, int oldUserId, int newUserId) {
724 completeSwitchAndInitialize(uss, newUserId, false, true);
725 }
726
727 void onUserInitialized(UserState uss, boolean foreground, int oldUserId, int newUserId) {
728 synchronized (mService) {
729 if (foreground) {
730 moveUserToForegroundLocked(uss, oldUserId, newUserId);
731 }
732 }
733 completeSwitchAndInitialize(uss, newUserId, true, false);
734 }
735
736 void completeSwitchAndInitialize(UserState uss, int newUserId,
737 boolean clearInitializing, boolean clearSwitching) {
738 boolean unfrozen = false;
739 synchronized (mService) {
740 if (clearInitializing) {
741 uss.initializing = false;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700742 getUserManager().makeInitialized(uss.mHandle.getIdentifier());
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700743 }
744 if (clearSwitching) {
745 uss.switching = false;
746 }
747 if (!uss.switching && !uss.initializing) {
748 mService.mWindowManager.stopFreezingScreen();
749 unfrozen = true;
750 }
751 }
752 if (unfrozen) {
753 mHandler.removeMessages(REPORT_USER_SWITCH_COMPLETE_MSG);
754 mHandler.sendMessage(mHandler.obtainMessage(REPORT_USER_SWITCH_COMPLETE_MSG,
755 newUserId, 0));
756 }
757 stopGuestUserIfBackground();
758 }
759
760 void moveUserToForegroundLocked(UserState uss, int oldUserId, int newUserId) {
761 boolean homeInFront = mService.mStackSupervisor.switchUserLocked(newUserId, uss);
762 if (homeInFront) {
763 mService.startHomeActivityLocked(newUserId, "moveUserToForeground");
764 } else {
765 mService.mStackSupervisor.resumeTopActivitiesLocked();
766 }
767 EventLogTags.writeAmSwitchUser(newUserId);
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700768 getUserManager().onUserForeground(newUserId);
769 sendUserSwitchBroadcastsLocked(oldUserId, newUserId);
770 }
771
772 void sendUserSwitchBroadcastsLocked(int oldUserId, int newUserId) {
773 long ident = Binder.clearCallingIdentity();
774 try {
775 Intent intent;
776 if (oldUserId >= 0) {
777 // Send USER_BACKGROUND broadcast to all profiles of the outgoing user
778 List<UserInfo> profiles = getUserManager().getProfiles(oldUserId, false);
779 int count = profiles.size();
780 for (int i = 0; i < count; i++) {
781 int profileUserId = profiles.get(i).id;
782 intent = new Intent(Intent.ACTION_USER_BACKGROUND);
783 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
784 | Intent.FLAG_RECEIVER_FOREGROUND);
785 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
786 mService.broadcastIntentLocked(null, null, intent,
787 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
788 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
789 }
790 }
791 if (newUserId >= 0) {
792 // Send USER_FOREGROUND broadcast to all profiles of the incoming user
793 List<UserInfo> profiles = getUserManager().getProfiles(newUserId, false);
794 int count = profiles.size();
795 for (int i = 0; i < count; i++) {
796 int profileUserId = profiles.get(i).id;
797 intent = new Intent(Intent.ACTION_USER_FOREGROUND);
798 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
799 | Intent.FLAG_RECEIVER_FOREGROUND);
800 intent.putExtra(Intent.EXTRA_USER_HANDLE, profileUserId);
801 mService.broadcastIntentLocked(null, null, intent,
802 null, null, 0, null, null, null, AppOpsManager.OP_NONE,
803 null, false, false, MY_PID, SYSTEM_UID, profileUserId);
804 }
805 intent = new Intent(Intent.ACTION_USER_SWITCHED);
806 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY
807 | Intent.FLAG_RECEIVER_FOREGROUND);
808 intent.putExtra(Intent.EXTRA_USER_HANDLE, newUserId);
809 mService.broadcastIntentLocked(null, null, intent,
810 null, null, 0, null, null,
811 new String[] {android.Manifest.permission.MANAGE_USERS},
812 AppOpsManager.OP_NONE, null, false, false, MY_PID, SYSTEM_UID,
813 UserHandle.USER_ALL);
814 }
815 } finally {
816 Binder.restoreCallingIdentity(ident);
817 }
818 }
819
820
821 int handleIncomingUser(int callingPid, int callingUid, int userId, boolean allowAll,
822 int allowMode, String name, String callerPackage) {
823 final int callingUserId = UserHandle.getUserId(callingUid);
824 if (callingUserId == userId) {
825 return userId;
826 }
827
828 // Note that we may be accessing mCurrentUserId outside of a lock...
829 // shouldn't be a big deal, if this is being called outside
830 // of a locked context there is intrinsically a race with
831 // the value the caller will receive and someone else changing it.
832 // We assume that USER_CURRENT_OR_SELF will use the current user; later
833 // we will switch to the calling user if access to the current user fails.
834 int targetUserId = unsafeConvertIncomingUserLocked(userId);
835
836 if (callingUid != 0 && callingUid != SYSTEM_UID) {
837 final boolean allow;
838 if (mService.checkComponentPermission(INTERACT_ACROSS_USERS_FULL, callingPid,
839 callingUid, -1, true) == PackageManager.PERMISSION_GRANTED) {
840 // If the caller has this permission, they always pass go. And collect $200.
841 allow = true;
842 } else if (allowMode == ALLOW_FULL_ONLY) {
843 // We require full access, sucks to be you.
844 allow = false;
845 } else if (mService.checkComponentPermission(INTERACT_ACROSS_USERS, callingPid,
846 callingUid, -1, true) != PackageManager.PERMISSION_GRANTED) {
847 // If the caller does not have either permission, they are always doomed.
848 allow = false;
849 } else if (allowMode == ALLOW_NON_FULL) {
850 // We are blanket allowing non-full access, you lucky caller!
851 allow = true;
852 } else if (allowMode == ALLOW_NON_FULL_IN_PROFILE) {
853 // We may or may not allow this depending on whether the two users are
854 // in the same profile.
855 allow = isSameProfileGroup(callingUserId, targetUserId);
856 } else {
857 throw new IllegalArgumentException("Unknown mode: " + allowMode);
858 }
859 if (!allow) {
860 if (userId == UserHandle.USER_CURRENT_OR_SELF) {
861 // In this case, they would like to just execute as their
862 // owner user instead of failing.
863 targetUserId = callingUserId;
864 } else {
865 StringBuilder builder = new StringBuilder(128);
866 builder.append("Permission Denial: ");
867 builder.append(name);
868 if (callerPackage != null) {
869 builder.append(" from ");
870 builder.append(callerPackage);
871 }
872 builder.append(" asks to run as user ");
873 builder.append(userId);
874 builder.append(" but is calling from user ");
875 builder.append(UserHandle.getUserId(callingUid));
876 builder.append("; this requires ");
877 builder.append(INTERACT_ACROSS_USERS_FULL);
878 if (allowMode != ALLOW_FULL_ONLY) {
879 builder.append(" or ");
880 builder.append(INTERACT_ACROSS_USERS);
881 }
882 String msg = builder.toString();
883 Slog.w(TAG, msg);
884 throw new SecurityException(msg);
885 }
886 }
887 }
888 if (!allowAll && targetUserId < 0) {
889 throw new IllegalArgumentException(
890 "Call does not support special user #" + targetUserId);
891 }
892 // Check shell permission
893 if (callingUid == Process.SHELL_UID && targetUserId >= UserHandle.USER_SYSTEM) {
894 if (hasUserRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, targetUserId)) {
895 throw new SecurityException("Shell does not have permission to access user "
896 + targetUserId + "\n " + Debug.getCallers(3));
897 }
898 }
899 return targetUserId;
900 }
901
902 int unsafeConvertIncomingUserLocked(int userId) {
903 return (userId == UserHandle.USER_CURRENT || userId == UserHandle.USER_CURRENT_OR_SELF)
904 ? getCurrentUserIdLocked(): userId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700905 }
906
907 void registerUserSwitchObserver(IUserSwitchObserver observer) {
908 if (mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
909 != PackageManager.PERMISSION_GRANTED) {
910 final String msg = "Permission Denial: registerUserSwitchObserver() from pid="
911 + Binder.getCallingPid()
912 + ", uid=" + Binder.getCallingUid()
913 + " requires " + INTERACT_ACROSS_USERS_FULL;
914 Slog.w(TAG, msg);
915 throw new SecurityException(msg);
916 }
917
918 mUserSwitchObservers.register(observer);
919 }
920
921 void unregisterUserSwitchObserver(IUserSwitchObserver observer) {
922 mUserSwitchObservers.unregister(observer);
923 }
924
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700925 UserState getStartedUserStateLocked(int userId) {
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700926 return mStartedUsers.get(userId);
927 }
928
929 boolean hasStartedUserState(int userId) {
930 return mStartedUsers.get(userId) != null;
931 }
932
933 private void updateStartedUserArrayLocked() {
934 int num = 0;
935 for (int i = 0; i < mStartedUsers.size(); i++) {
936 UserState uss = mStartedUsers.valueAt(i);
937 // This list does not include stopping users.
938 if (uss.mState != UserState.STATE_STOPPING
939 && uss.mState != UserState.STATE_SHUTDOWN) {
940 num++;
941 }
942 }
943 mStartedUserArray = new int[num];
944 num = 0;
945 for (int i = 0; i < mStartedUsers.size(); i++) {
946 UserState uss = mStartedUsers.valueAt(i);
947 if (uss.mState != UserState.STATE_STOPPING
948 && uss.mState != UserState.STATE_SHUTDOWN) {
949 mStartedUserArray[num] = mStartedUsers.keyAt(i);
950 num++;
951 }
952 }
953 }
954
955 void sendBootCompletedLocked(IIntentReceiver resultTo) {
956 for (int i = 0; i < mStartedUsers.size(); i++) {
957 UserState uss = mStartedUsers.valueAt(i);
958 if (uss.mState == UserState.STATE_BOOTING) {
959 uss.mState = UserState.STATE_RUNNING;
960 final int userId = mStartedUsers.keyAt(i);
961 Intent intent = new Intent(Intent.ACTION_BOOT_COMPLETED, null);
962 intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
963 intent.addFlags(Intent.FLAG_RECEIVER_NO_ABORT);
964 mService.broadcastIntentLocked(null, null, intent, null,
965 resultTo, 0, null, null,
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700966 new String[] {android.Manifest.permission.RECEIVE_BOOT_COMPLETED},
967 AppOpsManager.OP_NONE, null, true, false, MY_PID, SYSTEM_UID, userId);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700968 }
969 }
970 }
971
972 /**
973 * Refreshes the list of users related to the current user when either a
974 * user switch happens or when a new related user is started in the
975 * background.
976 */
977 void updateCurrentProfileIdsLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700978 final List<UserInfo> profiles = getUserManager().getProfiles(mCurrentUserId,
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700979 false /* enabledOnly */);
980 int[] currentProfileIds = new int[profiles.size()]; // profiles will not be null
981 for (int i = 0; i < currentProfileIds.length; i++) {
982 currentProfileIds[i] = profiles.get(i).id;
983 }
984 mCurrentProfileIds = currentProfileIds;
985
986 synchronized (mUserProfileGroupIdsSelfLocked) {
987 mUserProfileGroupIdsSelfLocked.clear();
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -0700988 final List<UserInfo> users = getUserManager().getUsers(false);
Fyodor Kupolov610acda2015-10-19 18:44:07 -0700989 for (int i = 0; i < users.size(); i++) {
990 UserInfo user = users.get(i);
991 if (user.profileGroupId != UserInfo.NO_PROFILE_GROUP_ID) {
992 mUserProfileGroupIdsSelfLocked.put(user.id, user.profileGroupId);
993 }
994 }
995 }
996 }
997
998 int[] getStartedUserArrayLocked() {
999 return mStartedUserArray;
1000 }
1001
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001002 boolean isUserRunningLocked(int userId, int flags) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001003 UserState state = getStartedUserStateLocked(userId);
1004 if (state == null) {
1005 return false;
1006 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001007 if ((flags & ActivityManager.FLAG_OR_STOPPED) != 0) {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001008 return true;
1009 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001010 if ((flags & ActivityManager.FLAG_WITH_AMNESIA) != 0) {
Jeff Sharkeyf9fc6d62015-11-08 16:46:05 -08001011 // If user is currently locked, we fall through to default "running"
1012 // behavior below
1013 if (state.unlocked) {
1014 return false;
1015 }
Jeff Sharkeye17ac152015-11-06 22:40:29 -08001016 }
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001017 return state.mState != UserState.STATE_STOPPING
1018 && state.mState != UserState.STATE_SHUTDOWN;
1019 }
1020
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001021 UserInfo getCurrentUser() {
1022 if ((mService.checkCallingPermission(INTERACT_ACROSS_USERS)
1023 != PackageManager.PERMISSION_GRANTED) && (
1024 mService.checkCallingPermission(INTERACT_ACROSS_USERS_FULL)
1025 != PackageManager.PERMISSION_GRANTED)) {
1026 String msg = "Permission Denial: getCurrentUser() from pid="
1027 + Binder.getCallingPid()
1028 + ", uid=" + Binder.getCallingUid()
1029 + " requires " + INTERACT_ACROSS_USERS;
1030 Slog.w(TAG, msg);
1031 throw new SecurityException(msg);
1032 }
1033 synchronized (mService) {
1034 return getCurrentUserLocked();
1035 }
1036 }
1037
1038 UserInfo getCurrentUserLocked() {
1039 int userId = mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001040 return getUserInfo(userId);
1041 }
1042
1043 int getCurrentOrTargetUserIdLocked() {
1044 return mTargetUserId != UserHandle.USER_NULL ? mTargetUserId : mCurrentUserId;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001045 }
1046
1047 int getCurrentUserIdLocked() {
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001048 return mCurrentUserId;
1049 }
1050
1051 int setTargetUserIdLocked(int targetUserId) {
1052 return mTargetUserId = targetUserId;
1053 }
1054
1055 int[] getUsers() {
1056 UserManagerService ums = getUserManager();
1057 return ums != null ? ums.getUserIds() : new int[] { 0 };
1058 }
1059
1060 UserInfo getUserInfo(int userId) {
1061 return getUserManager().getUserInfo(userId);
1062 }
1063
1064 int[] getUserIds() {
1065 return getUserManager().getUserIds();
1066 }
1067
1068 boolean exists(int userId) {
1069 return getUserManager().exists(userId);
1070 }
1071
1072 boolean hasUserRestriction(String restriction, int userId) {
1073 return getUserManager().hasUserRestriction(restriction, userId);
1074 }
1075
1076 Set<Integer> getProfileIds(int userId) {
1077 Set<Integer> userIds = new HashSet<>();
1078 final List<UserInfo> profiles = getUserManager().getProfiles(userId,
1079 false /* enabledOnly */);
1080 for (UserInfo user : profiles) {
1081 userIds.add(user.id);
1082 }
1083 return userIds;
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001084 }
1085
1086 boolean isSameProfileGroup(int callingUserId, int targetUserId) {
1087 synchronized (mUserProfileGroupIdsSelfLocked) {
1088 int callingProfile = mUserProfileGroupIdsSelfLocked.get(callingUserId,
1089 UserInfo.NO_PROFILE_GROUP_ID);
1090 int targetProfile = mUserProfileGroupIdsSelfLocked.get(targetUserId,
1091 UserInfo.NO_PROFILE_GROUP_ID);
1092 return callingProfile != UserInfo.NO_PROFILE_GROUP_ID
1093 && callingProfile == targetProfile;
1094 }
1095 }
1096
1097 boolean isCurrentProfileLocked(int userId) {
1098 return ArrayUtils.contains(mCurrentProfileIds, userId);
1099 }
1100
Fyodor Kupolovf63b89c2015-10-27 18:08:56 -07001101 int[] getCurrentProfileIdsLocked() {
1102 return mCurrentProfileIds;
1103 }
1104
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001105 void dump(PrintWriter pw, boolean dumpAll) {
1106 pw.println(" mStartedUsers:");
1107 for (int i = 0; i < mStartedUsers.size(); i++) {
1108 UserState uss = mStartedUsers.valueAt(i);
1109 pw.print(" User #"); pw.print(uss.mHandle.getIdentifier());
1110 pw.print(": "); uss.dump("", pw);
1111 }
1112 pw.print(" mStartedUserArray: [");
1113 for (int i = 0; i < mStartedUserArray.length; i++) {
1114 if (i > 0) pw.print(", ");
1115 pw.print(mStartedUserArray[i]);
1116 }
1117 pw.println("]");
1118 pw.print(" mUserLru: [");
1119 for (int i = 0; i < mUserLru.size(); i++) {
1120 if (i > 0) pw.print(", ");
1121 pw.print(mUserLru.get(i));
1122 }
1123 pw.println("]");
1124 if (dumpAll) {
1125 pw.print(" mStartedUserArray: "); pw.println(Arrays.toString(mStartedUserArray));
1126 }
1127 synchronized (mUserProfileGroupIdsSelfLocked) {
1128 if (mUserProfileGroupIdsSelfLocked.size() > 0) {
1129 pw.println(" mUserProfileGroupIds:");
1130 for (int i=0; i<mUserProfileGroupIdsSelfLocked.size(); i++) {
1131 pw.print(" User #");
1132 pw.print(mUserProfileGroupIdsSelfLocked.keyAt(i));
1133 pw.print(" -> profile #");
1134 pw.println(mUserProfileGroupIdsSelfLocked.valueAt(i));
1135 }
1136 }
1137 }
1138 }
Fyodor Kupolov610acda2015-10-19 18:44:07 -07001139}