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