1 /* 2 * Copyright (C) 2013 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; 18 19 import static android.os.IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT; 20 21 import android.annotation.IntDef; 22 import android.annotation.NonNull; 23 import android.annotation.Nullable; 24 import android.annotation.SystemApi; 25 import android.annotation.SystemApi.Client; 26 import android.annotation.UserIdInt; 27 import android.app.ActivityThread; 28 import android.content.Context; 29 import android.content.pm.UserInfo; 30 import android.os.IBinder; 31 import android.os.ServiceManager; 32 import android.os.UserHandle; 33 import android.os.UserManager; 34 35 import com.android.internal.annotations.VisibleForTesting; 36 import com.android.server.pm.UserManagerService; 37 38 import java.io.PrintWriter; 39 import java.lang.annotation.Retention; 40 import java.lang.annotation.RetentionPolicy; 41 import java.util.ArrayList; 42 import java.util.List; 43 44 /** 45 * The base class for services running in the system process. Override and implement 46 * the lifecycle event callback methods as needed. 47 * <p> 48 * The lifecycle of a SystemService: 49 * </p><ul> 50 * <li>The constructor is called and provided with the system {@link Context} 51 * to initialize the system service. 52 * <li>{@link #onStart()} is called to get the service running. The service should 53 * publish its binder interface at this point using 54 * {@link #publishBinderService(String, IBinder)}. It may also publish additional 55 * local interfaces that other services within the system server may use to access 56 * privileged internal functions. 57 * <li>Then {@link #onBootPhase(int)} is called as many times as there are boot phases 58 * until {@link #PHASE_BOOT_COMPLETED} is sent, which is the last boot phase. Each phase 59 * is an opportunity to do special work, like acquiring optional service dependencies, 60 * waiting to see if SafeMode is enabled, or registering with a service that gets 61 * started after this one. 62 * </ul><p> 63 * NOTE: All lifecycle methods are called from the system server's main looper thread. 64 * </p> 65 * 66 * {@hide} 67 */ 68 @SystemApi(client = Client.SYSTEM_SERVER) 69 public abstract class SystemService { 70 71 /** @hide */ 72 protected static final boolean DEBUG_USER = false; 73 74 /** 75 * The earliest boot phase the system send to system services on boot. 76 */ 77 public static final int PHASE_WAIT_FOR_DEFAULT_DISPLAY = 100; 78 79 /** 80 * Boot phase that blocks on SensorService availability. The service gets started 81 * asynchronously since it may take awhile to actually finish initializing. 82 * 83 * @hide 84 */ 85 public static final int PHASE_WAIT_FOR_SENSOR_SERVICE = 200; 86 87 /** 88 * After receiving this boot phase, services can obtain lock settings data. 89 */ 90 public static final int PHASE_LOCK_SETTINGS_READY = 480; 91 92 /** 93 * After receiving this boot phase, services can safely call into core system services 94 * such as the PowerManager or PackageManager. 95 */ 96 public static final int PHASE_SYSTEM_SERVICES_READY = 500; 97 98 /** 99 * After receiving this boot phase, services can safely call into device specific services. 100 */ 101 public static final int PHASE_DEVICE_SPECIFIC_SERVICES_READY = 520; 102 103 /** 104 * After receiving this boot phase, services can broadcast Intents. 105 */ 106 public static final int PHASE_ACTIVITY_MANAGER_READY = 550; 107 108 /** 109 * After receiving this boot phase, services can start/bind to third party apps. 110 * Apps will be able to make Binder calls into services at this point. 111 */ 112 public static final int PHASE_THIRD_PARTY_APPS_CAN_START = 600; 113 114 /** 115 * After receiving this boot phase, services can allow user interaction with the device. 116 * This phase occurs when boot has completed and the home application has started. 117 * System services may prefer to listen to this phase rather than registering a 118 * broadcast receiver for {@link android.content.Intent#ACTION_LOCKED_BOOT_COMPLETED} 119 * to reduce overall latency. 120 */ 121 public static final int PHASE_BOOT_COMPLETED = 1000; 122 123 /** @hide */ 124 @IntDef(flag = true, prefix = { "PHASE_" }, value = { 125 PHASE_WAIT_FOR_DEFAULT_DISPLAY, 126 PHASE_LOCK_SETTINGS_READY, 127 PHASE_SYSTEM_SERVICES_READY, 128 PHASE_DEVICE_SPECIFIC_SERVICES_READY, 129 PHASE_ACTIVITY_MANAGER_READY, 130 PHASE_THIRD_PARTY_APPS_CAN_START, 131 PHASE_BOOT_COMPLETED 132 }) 133 @Retention(RetentionPolicy.SOURCE) 134 public @interface BootPhase {} 135 136 private final Context mContext; 137 138 /** 139 * Class representing user in question in the lifecycle callbacks. 140 * @hide 141 */ 142 @SystemApi(client = Client.SYSTEM_SERVER) 143 public static final class TargetUser { 144 145 // NOTE: attributes below must be immutable while ther user is running (i.e., from the 146 // moment it's started until after it's shutdown). 147 private final @UserIdInt int mUserId; 148 private final boolean mFull; 149 private final boolean mManagedProfile; 150 private final boolean mPreCreated; 151 152 /** @hide */ TargetUser(@onNull UserInfo userInfo)153 public TargetUser(@NonNull UserInfo userInfo) { 154 mUserId = userInfo.id; 155 mFull = userInfo.isFull(); 156 mManagedProfile = userInfo.isManagedProfile(); 157 mPreCreated = userInfo.preCreated; 158 } 159 160 /** 161 * Checks if the target user is {@link UserInfo#isFull() full}. 162 * 163 * @hide 164 */ isFull()165 public boolean isFull() { 166 return mFull; 167 } 168 169 /** 170 * Checks if the target user is a managed profile. 171 * 172 * @hide 173 */ isManagedProfile()174 public boolean isManagedProfile() { 175 return mManagedProfile; 176 } 177 178 /** 179 * Checks if the target user is a pre-created user. 180 * 181 * @hide 182 */ isPreCreated()183 public boolean isPreCreated() { 184 return mPreCreated; 185 } 186 187 /** 188 * Gets the target user's {@link UserHandle}. 189 */ 190 @NonNull getUserHandle()191 public UserHandle getUserHandle() { 192 return UserHandle.of(mUserId); 193 } 194 195 /** 196 * Gets the target user's id. 197 * 198 * @hide 199 */ getUserIdentifier()200 public @UserIdInt int getUserIdentifier() { 201 return mUserId; 202 } 203 204 @Override toString()205 public String toString() { 206 return Integer.toString(mUserId); 207 } 208 209 /** 210 * @hide 211 */ dump(@onNull PrintWriter pw)212 public void dump(@NonNull PrintWriter pw) { 213 pw.print(getUserIdentifier()); 214 215 if (!isFull() && !isManagedProfile()) return; 216 217 pw.print('('); 218 boolean addComma = false; 219 if (isFull()) { 220 pw.print("full"); 221 } 222 if (isManagedProfile()) { 223 if (addComma) pw.print(','); 224 pw.print("mp"); 225 } 226 pw.print(')'); 227 } 228 } 229 230 /** 231 * Class representing the types of "onUser" events that we are being informed about as having 232 * finished. 233 * 234 * @hide 235 */ 236 public static final class UserCompletedEventType { 237 /** 238 * Flag representing the {@link #onUserStarting} event. 239 * @hide 240 */ 241 public static final int EVENT_TYPE_USER_STARTING = 1 << 0; 242 /** 243 * Flag representing the {@link #onUserUnlocked} event. 244 * @hide 245 */ 246 public static final int EVENT_TYPE_USER_UNLOCKED = 1 << 1; 247 /** 248 * Flag representing the {@link #onUserSwitching} event. 249 * @hide 250 */ 251 public static final int EVENT_TYPE_USER_SWITCHING = 1 << 2; 252 253 /** 254 * @hide 255 */ 256 @IntDef(flag = true, prefix = "EVENT_TYPE_USER_", value = { 257 EVENT_TYPE_USER_STARTING, 258 EVENT_TYPE_USER_UNLOCKED, 259 EVENT_TYPE_USER_SWITCHING 260 }) 261 @Retention(RetentionPolicy.SOURCE) 262 public @interface EventTypesFlag { 263 } 264 265 private final @EventTypesFlag int mEventType; 266 267 /** @hide */ UserCompletedEventType(@ventTypesFlag int eventType)268 UserCompletedEventType(@EventTypesFlag int eventType) { 269 mEventType = eventType; 270 } 271 272 /** 273 * Creates a new instance of {@link UserCompletedEventType}. 274 * @hide 275 */ 276 @VisibleForTesting newUserCompletedEventTypeForTest( @ventTypesFlag int eventType)277 public static UserCompletedEventType newUserCompletedEventTypeForTest( 278 @EventTypesFlag int eventType) { 279 return new UserCompletedEventType(eventType); 280 } 281 282 /** Returns whether one of the events is {@link #onUserStarting}. */ includesOnUserStarting()283 public boolean includesOnUserStarting() { 284 return (mEventType & EVENT_TYPE_USER_STARTING) != 0; 285 } 286 287 /** Returns whether one of the events is {@link #onUserUnlocked}. */ includesOnUserUnlocked()288 public boolean includesOnUserUnlocked() { 289 return (mEventType & EVENT_TYPE_USER_UNLOCKED) != 0; 290 } 291 292 /** Returns whether one of the events is {@link #onUserSwitching}. */ includesOnUserSwitching()293 public boolean includesOnUserSwitching() { 294 return (mEventType & EVENT_TYPE_USER_SWITCHING) != 0; 295 } 296 297 @Override toString()298 public String toString() { 299 final StringBuilder sb = new StringBuilder("{"); 300 // List each in reverse order (to line up with binary better). 301 if (includesOnUserSwitching()) sb.append("|Switching"); 302 if (includesOnUserUnlocked()) sb.append("|Unlocked"); 303 if (includesOnUserStarting()) sb.append("|Starting"); 304 if (sb.length() > 1) sb.append("|"); 305 sb.append("}"); 306 return sb.toString(); 307 } 308 } 309 310 /** 311 * Initializes the system service. 312 * <p> 313 * Subclasses must define a single argument constructor that accepts the context 314 * and passes it to super. 315 * </p> 316 * 317 * @param context The system server context. 318 */ SystemService(@onNull Context context)319 public SystemService(@NonNull Context context) { 320 mContext = context; 321 } 322 323 /** 324 * Gets the system context. 325 */ 326 @NonNull getContext()327 public final Context getContext() { 328 return mContext; 329 } 330 331 /** 332 * Get the system UI context. This context is to be used for displaying UI. It is themable, 333 * which means resources can be overridden at runtime. Do not use to retrieve properties that 334 * configure the behavior of the device that is not UX related. 335 * 336 * @hide 337 */ getUiContext()338 public final Context getUiContext() { 339 // This has already been set up by the time any SystemServices are created. 340 return ActivityThread.currentActivityThread().getSystemUiContext(); 341 } 342 343 /** 344 * Returns true if the system is running in safe mode. 345 * TODO: we should define in which phase this becomes valid 346 * 347 * @hide 348 */ isSafeMode()349 public final boolean isSafeMode() { 350 return getManager().isSafeMode(); 351 } 352 353 /** 354 * Called when the system service should publish a binder service using 355 * {@link #publishBinderService(String, IBinder).} 356 */ onStart()357 public abstract void onStart(); 358 359 /** 360 * Called on each phase of the boot process. Phases before the service's start phase 361 * (as defined in the @Service annotation) are never received. 362 * 363 * @param phase The current boot phase. 364 */ onBootPhase(@ootPhase int phase)365 public void onBootPhase(@BootPhase int phase) {} 366 367 /** 368 * Checks if the service should be available for the given user. 369 * 370 * <p>By default returns {@code true}, but subclasses should extend for optimization, if they 371 * don't support some types (like headless system user). 372 */ isUserSupported(@onNull TargetUser user)373 public boolean isUserSupported(@NonNull TargetUser user) { 374 return true; 375 } 376 377 /** 378 * Helper method used to dump which users are {@link #onUserStarting(TargetUser) supported}. 379 * 380 * @hide 381 */ dumpSupportedUsers(@onNull PrintWriter pw, @NonNull String prefix)382 protected void dumpSupportedUsers(@NonNull PrintWriter pw, @NonNull String prefix) { 383 final List<UserInfo> allUsers = UserManager.get(mContext).getUsers(); 384 final List<Integer> supportedUsers = new ArrayList<>(allUsers.size()); 385 for (int i = 0; i < allUsers.size(); i++) { 386 final UserInfo user = allUsers.get(i); 387 if (isUserSupported(new TargetUser(user))) { 388 supportedUsers.add(user.id); 389 } 390 } 391 if (supportedUsers.isEmpty()) { 392 pw.print(prefix); pw.println("No supported users"); 393 return; 394 } 395 final int size = supportedUsers.size(); 396 pw.print(prefix); pw.print(size); pw.print(" supported user"); 397 if (size > 1) pw.print("s"); 398 pw.print(": "); pw.println(supportedUsers); 399 } 400 401 /** 402 * Called when a new user is starting, for system services to initialize any per-user 403 * state they maintain for running users. 404 * 405 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 406 * this user. 407 * 408 * @param user target user 409 */ onUserStarting(@onNull TargetUser user)410 public void onUserStarting(@NonNull TargetUser user) { 411 } 412 413 /** 414 * Called when an existing user is in the process of being unlocked. This 415 * means the credential-encrypted storage for that user is now available, 416 * and encryption-aware component filtering is no longer in effect. 417 * <p> 418 * While dispatching this event to services, the user is in the 419 * {@code STATE_RUNNING_UNLOCKING} state, and once dispatching is finished 420 * the user will transition into the {@code STATE_RUNNING_UNLOCKED} state. 421 * Code written inside system services should use 422 * {@link UserManager#isUserUnlockingOrUnlocked(int)} to handle both of 423 * these states, or use {@link #onUserUnlocked(TargetUser)} instead. 424 * <p> 425 * This method is only called when the service {@link #isUserSupported(TargetUser) supports} 426 * this user. 427 * 428 * @param user target user 429 */ onUserUnlocking(@onNull TargetUser user)430 public void onUserUnlocking(@NonNull TargetUser user) { 431 } 432 433 /** 434 * Called after an existing user is unlocked. 435 * 436 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 437 * this user. 438 * 439 * @param user target user 440 */ onUserUnlocked(@onNull TargetUser user)441 public void onUserUnlocked(@NonNull TargetUser user) { 442 } 443 444 /** 445 * Called when switching to a different foreground user, for system services that have 446 * special behavior for whichever user is currently in the foreground. This is called 447 * before any application processes are aware of the new user. 448 * 449 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 450 * either of the users ({@code from} or {@code to}). 451 * 452 * <b>NOTE: </b> both {@code from} and {@code to} are "live" objects 453 * referenced by {@link UserManagerService} and hence should not be modified. 454 * 455 * @param from the user switching from 456 * @param to the user switching to 457 */ onUserSwitching(@ullable TargetUser from, @NonNull TargetUser to)458 public void onUserSwitching(@Nullable TargetUser from, @NonNull TargetUser to) { 459 } 460 461 /** 462 * Called when an existing user is stopping, for system services to finalize any per-user 463 * state they maintain for running users. This is called prior to sending the SHUTDOWN 464 * broadcast to the user; it is a good place to stop making use of any resources of that 465 * user (such as binding to a service running in the user). 466 * 467 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 468 * this user. 469 * 470 * <p>NOTE: This is the last callback where the callee may access the target user's CE storage. 471 * 472 * @param user target user 473 */ onUserStopping(@onNull TargetUser user)474 public void onUserStopping(@NonNull TargetUser user) { 475 } 476 477 /** 478 * Called after an existing user is stopped. 479 * 480 * <p>This is called after all application process teardown of the user is complete. 481 * 482 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 483 * this user. 484 * 485 * @param user target user 486 */ onUserStopped(@onNull TargetUser user)487 public void onUserStopped(@NonNull TargetUser user) { 488 } 489 490 /** 491 * Called some time <i>after</i> an onUser... event has completed, for the events delineated in 492 * {@link UserCompletedEventType}. May include more than one event. 493 * 494 * <p> 495 * This can be useful for processing tasks that must run after such an event but are non-urgent. 496 * 497 * There are no strict guarantees about how long after the event this will be called, only that 498 * it will be called if applicable. There is no guarantee about the order in which each service 499 * is informed, and these calls may be made in parallel using a thread pool. 500 * 501 * <p>Note that if the event is no longer applicable (for example, we switched to user 10, but 502 * before this method was called, we switched to user 11), the event will not be included in the 503 * {@code eventType} (i.e. user 10 won't mention the switch - even though it happened, it is no 504 * longer applicable). 505 * 506 * <p>This method is only called when the service {@link #isUserSupported(TargetUser) supports} 507 * this user. 508 * 509 * @param user target user completing the event (e.g. user being switched to) 510 * @param eventType the types of onUser event applicable (e.g. user starting and being unlocked) 511 * 512 * @hide 513 */ onUserCompletedEvent(@onNull TargetUser user, UserCompletedEventType eventType)514 public void onUserCompletedEvent(@NonNull TargetUser user, UserCompletedEventType eventType) { 515 } 516 517 /** 518 * Publish the service so it is accessible to other services and apps. 519 * 520 * @param name the name of the new service 521 * @param service the service object 522 */ publishBinderService(@onNull String name, @NonNull IBinder service)523 protected final void publishBinderService(@NonNull String name, @NonNull IBinder service) { 524 publishBinderService(name, service, false); 525 } 526 527 /** 528 * Publish the service so it is accessible to other services and apps. 529 * 530 * @param name the name of the new service 531 * @param service the service object 532 * @param allowIsolated set to true to allow isolated sandboxed processes 533 * to access this service 534 */ publishBinderService(@onNull String name, @NonNull IBinder service, boolean allowIsolated)535 protected final void publishBinderService(@NonNull String name, @NonNull IBinder service, 536 boolean allowIsolated) { 537 publishBinderService(name, service, allowIsolated, DUMP_FLAG_PRIORITY_DEFAULT); 538 } 539 540 /** 541 * Publish the service so it is accessible to other services and apps. 542 * 543 * @param name the name of the new service 544 * @param service the service object 545 * @param allowIsolated set to true to allow isolated sandboxed processes 546 * to access this service 547 * @param dumpPriority supported dump priority levels as a bitmask 548 * 549 * @hide 550 */ publishBinderService(String name, IBinder service, boolean allowIsolated, int dumpPriority)551 protected final void publishBinderService(String name, IBinder service, 552 boolean allowIsolated, int dumpPriority) { 553 ServiceManager.addService(name, service, allowIsolated, dumpPriority); 554 } 555 556 /** 557 * Get a binder service by its name. 558 * 559 * @hide 560 */ getBinderService(String name)561 protected final IBinder getBinderService(String name) { 562 return ServiceManager.getService(name); 563 } 564 565 /** 566 * Publish the service so it is only accessible to the system process. 567 * 568 * @hide 569 */ publishLocalService(Class<T> type, T service)570 protected final <T> void publishLocalService(Class<T> type, T service) { 571 LocalServices.addService(type, service); 572 } 573 574 /** 575 * Get a local service by interface. 576 * 577 * @hide 578 */ getLocalService(Class<T> type)579 protected final <T> T getLocalService(Class<T> type) { 580 return LocalServices.getService(type); 581 } 582 getManager()583 private SystemServiceManager getManager() { 584 return LocalServices.getService(SystemServiceManager.class); 585 } 586 } 587