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