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