Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is a SystemServer process

2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article mainly explains "what is the SystemServer process". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what is the SystemServer process".

Born

Before, during the startup process of the Android system, Speaking of, the SystemServer process comes from the Zygote process fork.

The fork () function creates a process that is almost identical to the original process through a system call, which can be understood as COPY a process, and this new process is its child process.

And about the birth of SystemServer, but also from the forkSystemServer method of ZygoteInit. (keep only the main code)

Private static Runnable forkSystemServer (String abiList, String socketName, ZygoteServer zygoteServer) {/... / / 1 int pid Pid = Zygote.forkSystemServer (parsedArgs.uid, parsedArgs.gid, parsedArgs.gids, parsedArgs.runtimeFlags, null, parsedArgs.permittedCapabilities, parsedArgs.effectiveCapabilities) / * For child process * / if (pid = = 0) {/ / 2 zygoteServer.closeServerSocket (); / / 3 return handleSystemServerProcess (parsedArgs);} return true;} / * Finish remaining work for the newly forked system server process. * / private static Runnable handleSystemServerProcess (ZygoteConnection.Arguments parsedArgs) {/ /... / * * Pass the remaining arguments to SystemServer. * / ZygoteInit.zygoteInit (parsedArgs.targetSdkVersion, parsedArgs.remainingArgs, cl);} public static final Runnable zygoteInit (int targetSdkVersion, String [] argv, ClassLoader classLoader) {/... / / 4 RuntimeInit.commonInit (); / / 5 ZygoteInit.nativeZygoteInit (); / / 6 return RuntimeInit.applicationInit (targetSdkVersion, argv, classLoader);}

In startSystemServer method:

1. The child process, the SystemServer process, is created by calling the forkSystemServer method.

2. After fork, it is determined whether the return value pid of fork is equal to 0. If it is equal to 0, it means that fork is successful and is in the SystemServer process. The Socket object brought from the Zygote process fork is then closed.

3. Then call the handleSystemServerProcess method, and finally go to zygoteInit, and do some initialization of the new process.

In zygoteInit method:

4. The commonInit method does some common initialization work of the process, such as setting the time zone and resetting the log configuration.

5. The nativeZygoteInit method goes to the native layer through JNI, and the main job is to create a new Binder thread pool so that SystemServer can communicate with major app processes.

6. The applicationInit method will eventually go to the findStaticMain method, call the main method of the SystemServer class through reflection, and simply paste the code:

Protected static Runnable findStaticMain (String className, String [] argv, ClassLoader classLoader) {Class cl; try {cl = Class.forName (className, true, classLoader);} / / Method m; try {m = cl.getMethod ("main", new Class [] {String [] .class});} / /. Return new MethodAndArgsCaller (m, argv);}

Work

The SystemServer process has been created and some initialization has been done, and then it's time for the main method, and as the name suggests, it's time to get down to major work.

Public static void main (String [] args) {new SystemServer () .run ();} private void run () {try {/... / / 1 android.os.Process.setThreadPriority (android.os.Process.THREAD_PRIORITY_FOREGROUND); android.os.Process.setCanSelfBackground (false); Looper.prepareMainLooper () Looper.getMainLooper () .setSlowLogThresholdMs (SLOW_DISPATCH_THRESHOLD_MS, SLOW_DELIVERY_THRESHOLD_MS); / / 2 System.loadLibrary ("android_servers"); / / 3 performPendingShutdown (); / / 4 createSystemContext (); / / 5 mSystemServiceManager = new SystemServiceManager (mSystemContext) MSystemServiceManager.setStartInfo (mRuntimeRestart, mRuntimeStartElapsedTime, mRuntimeStartUptime); LocalServices.addService (SystemServiceManager.class, mSystemServiceManager); / / Prepare the thread pool for init tasks that can be parallelized SystemServerInitThreadPool.get ();} finally {traceEnd ();} / /... / / Start services. Try {/ / 6 startBootstrapServices (); / / 7 startCoreServices (); / / 8 startOtherServices (); SystemServerInitThreadPool.shutdown ();} / /... / / Loop forever. Looper.loop (); throw new RuntimeException ("Main thread loop unexpectedly exited");}

1. Prepare the main thread, Looper.

2. Load the dynamic library.

3. Check whether the last shutdown process failed.

4. Initialize the system context.

Private void createSystemContext () {ActivityThread activityThread = ActivityThread.systemMain (); mSystemContext = activityThread.getSystemContext (); mSystemContext.setTheme (DEFAULT_SYSTEM_THEME); final Context systemUiContext = activityThread.getSystemUiContext (); systemUiContext.setTheme (DEFAULT_SYSTEM_THEME);}

In this method, the ActivityThread class is created, the context is obtained, and some system themes are set.

5. Create a SystemServiceManager for subsequent system service management and creation.

The final work of the run method is to start services of three service types, which are also our key concerns, namely, bootstrapping services, core services, and other services.

There are more than 100 of these services, which are related to the entire application ecology of Android. Let's talk about it in detail below.

6. Start the boot service

Private void startBootstrapServices () {/ / install APK service traceBeginAndSlog ("StartInstaller"); Installer installer = mSystemServiceManager.startService (Installer.class); traceEnd (); / / AMS, responsible for the startup and scheduling of the four major components mActivityManagerService = mSystemServiceManager.startService (ActivityManagerService.Lifecycle.class). GetService (); mActivityManagerService.setSystemServiceManager (mSystemServiceManager); mActivityManagerService.setInstaller (installer) TraceEnd (); / manage and display services such as backlit LED traceBeginAndSlog ("StartLightsService"); mSystemServiceManager.startService (LightsService.class); traceEnd (); / / PMS, responsible for APK installation, parsing and uninstalling traceBeginAndSlog ("StartPackageManagerService"); mPackageManagerService = PackageManagerService.main (mSystemContext, installer, mFactoryTestMode! = FactoryTest.FACTORY_TEST_OFF, mOnlyCore) MFirstBoot = mPackageManagerService.isFirstBoot (); mPackageManager = mSystemContext.getPackageManager (); traceEnd (); / /...}

Among the boot services, there are a few we are familiar with after all, such as AMS and PMS.

7. Start core services

Private void startCoreServices () {traceBeginAndSlog ("StartBatteryService"); / / manage battery-related services mSystemServiceManager.startService (BatteryService.class); traceEnd (); / / collect traceBeginAndSlog ("StartUsageService"); mSystemServiceManager.startService (UsageStatsService.class); mActivityManagerService.setUsageStatsManager (LocalServices.getService (UsageStatsManagerInternal.class)); traceEnd () / / Webview update service if (mPackageManager.hasSystemFeature (PackageManager.FEATURE_WEBVIEW)) {traceBeginAndSlog ("StartWebViewUpdateService"); mWebViewUpdateService = mSystemServiceManager.startService (WebViewUpdateService.class); traceEnd ();} / /.}

8. Start other services

Private void startOtherServices () {/ /... / phone management service traceBeginAndSlog ("StartTelephonyRegistry"); telephonyRegistry = new TelephonyRegistry (context); ServiceManager.addService ("telephony.registry", telephonyRegistry); traceEnd (); / / WMS, window management service, traceBeginAndSlog ("StartWindowManagerService") ConcurrentUtils.waitForFutureNoInterrupt (mSensorServiceStart, START_SENSOR_SERVICE); mSensorServiceStart = null; wm = WindowManagerService.main (context, inputManager, mFactoryTestMode! = FactoryTest.FACTORY_TEST_LOW_LEVEL,! mFirstBoot, mOnlyCore, new PhoneWindowManager ()) ServiceManager.addService (Context.WINDOW_SERVICE, wm, / * allowIsolated= * / false, DUMP_FLAG_PRIORITY_CRITICAL | DUMP_FLAG_PROTO); ServiceManager.addService (Context.INPUT_SERVICE, inputManager, / * allowIsolated= * / false, DUMP_FLAG_PRIORITY_CRITICAL); traceEnd () / / enter event management service traceBeginAndSlog ("StartInputManager"); inputManager.setWindowManagerCallbacks (wm.getInputMonitor ()); inputManager.start (); traceEnd (); / /.}

With so many services started, let's take a look at how the services are started:

Public T startService (Class serviceClass) {try {final String name = serviceClass.getName (); / / Create the service. Final T service; try {Constructor constructor = serviceClass.getConstructor (Context.class); service = constructor.newInstance (mContext);} / /. StartService (service); return service;} finally {Trace.traceEnd (Trace.TRACE_TAG_SYSTEM_SERVER);}} / / the collection of all system services private final ArrayList mServices = new ArrayList (); public void startService (@ NonNull final SystemService service) {/ / Register it. MServices.add (service); / / Start it. Long time = SystemClock.elapsedRealtime (); try {service.onStart ();} catch (RuntimeException ex) {throw new RuntimeException ("Failed to start service" + service.getClass (). GetName () + ": onStart threw an exception", ex);} warnIfTooLong (SystemClock.elapsedRealtime ()-time, service, "onStart");}

As you can see, the corresponding Service class is first created through reflection, and then the corresponding Service is added to the mServices collection to complete the registration. Then call the onStart method to start the corresponding Service and complete the initialization work.

At this point, the start-up work of SystemServer is completed. Let's review this process. What on earth did you do?

First, Zygote fork the child process SystemServer, then close the original socket and create a new Binder thread pool.

Secondly, some initialization work is done, creating a Context object and a SystemServiceManager class to manage all system services.

Finally, three types of system services are started, namely, boot service, core service and other services.

Extension of system knowledge

Socket and Binder

We noticed that after the SystemServer was fork, one action was done to close the Sokcet and start the Binder thread pool for interprocess communication. The question is, why does the Zygote process communicate with Socket while the SystemServer process communicates with Binder?

In fact, these are two questions. The first question is why Android uses Binder process communication to obtain system services.

This involves the knowledge of Binder. Binder is designed because it has two advantages different from other IPC methods:

High performance and high efficiency: traditional IPC (sockets, pipes, message queues) need to copy memory twice, Binder only need to copy memory once, shared memory does not need to copy memory.

Good security: the receiver can obtain the sending process Id and user Id from the data packet to verify the identity of the sender. Other IPC want to experiment can only be actively stored, but this may be modified during the sending process.

The second question is, why do Zygote processes communicate with Socket instead of Binder? This is also a problem in wanAndroid:

Ask every day | most of the Activity startup process uses Binder to communicate, so why use socket when communicating with Zygote? (https://www.wanandroid.com/wenda/show/10482)

The comments section mainly has the following views:

ServiceManager does not guarantee that it will be initialized when zygote is up, so Binder cannot be used.

The owner of Socket is root, and only users with system permissions can read and write.

Binder work depends on multithreading, but multithreading is not allowed in fork. In the case of multithreading, the process fork is easy to cause deadlock, so Binder is not used.

Binder thread pool

What exactly is the Binder thread pool? Some readers have asked similar questions before.

The Binder thread pool is located on the server side, and its main function is to forward the Binder requests of each business module to the remote Servie for execution, thus avoiding the repeated process of creating Service. That is, there is only one server, but it can handle Binder requests from many different clients.

AMS,PMS,WMS

In the process of starting the SystemServer process, many system services are also started, including three services that interact with the application more:

AMS,ActivityManagerService, responsible for the startup, switching and scheduling of the four components.

PMS,PackageManagerService, responsible for the installation, parsing and uninstallation of APK.

WMS,WindowManagerService, responsible for window startup, add, delete and other work.

Thank you for your reading, the above is the content of "what is the SystemServer process", after the study of this article, I believe you have a deeper understanding of what is the SystemServer process, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report