Analysis of----binder mechanism and remote service invocation mechanism of Android system

Source: Internet
Author: User
Tags semaphore mremote

I. Overview of the Outlook

Recently to implement the Android registration activity can run the problem, then the result is done, Just can not be declared in the Androidmanifest.xml this activity can run, mainly through cheat system, steal dragon turn Phoenix technology, this knowledge point will be explained in detail, because in the process of studying this problem encountered a lot of knowledge points, of course, the most important is the most fundamental is the Android B Inder mechanism and remote service invocation mechanism, and about the binder mechanism, in Android is a very large system architecture module, the light This article is certainly not explained to all, and I am not very familiar with the binder mechanism, just published personal understanding, And will be in the simplest language to explain the core of knowledge, because there is a lot of knowledge is introduced binder mechanism, but most of the said is too abstract most of them can not understand.


Ii. specific needs

The next few are mainly about the Android application launch process, through the hook mechanism to intercept the activity's activation process, to achieve the function we want, You can also achieve the effect that activity does not need to be declared in Androidmanifest.xml.


Third, the remote service call analysis in Android

If we do a lot of communication between the process of understanding the use of remote services, the use is very simple, the following is a look at how to define their own remote services:

1. Define a Aidl file

Similar to defining an interface type, this aidl file will be used both locally and in the remote



2. Define Remote Service

The Onbind method in the remote service implements the specific method of the Aidl interface, and returns the Binder object



3. Create a Connection object locally

Create a service Connection object locally, implement the serviceconnection interface, after the connection is successful, you will get a binder object passed by the far end, which is returned by the remote service Onbind method above. After the binder object is converted, the Aidl object can be obtained, and then the method is called.



4. Connection Service

The connection service is also relatively simple, at this time to pass the above connection object in can



Here we see the completion of the local and remote communication, if the Demoservice remote service is defined in another process, then it is possible to implement multi-process communication. See the above steps is very simple, but there is a central place is the Demo.stub class, this class plays an important role, the following analysis of his implementation, each time the Aidl interface file is defined, the compilation will be generated in the Gen directory of the corresponding Java files:


The implementation here is a little bit more complicated, but these are actually the compiler tools to help us achieve, and this implementation is a certain rule:

1. Aidl interface must implement IInterface interface

The implementation of the IInterface interface is also simple:


Here you can convert the current Aidl object to a IBinder type Object

2, Aidl interface must have a static implementation class stub

This class must implement the Binder class, as well as its own Aidl interface type. Then this class has four functions in the Binder class:

1 "can convert binder object to Aidl object, call Asinterface method, can see this method actually and the above Asbinder method opposite

2 "Communication method Ontransact implementation, this method is the most core for communication between the logical implementation

3 "Through the Querylocalinterface method you can obtain the corresponding Aidl object (in fact, the IInterface type) based on the descriptor of the class (the string can uniquely identify the name of the remote service).

4 "In the constructor method, the Attachinterface method in binder must be called to associate the current service object with the descriptor

After reading the stub class, found that he is actually a remote service binder object of a middle, used to interact with the client, and then look at the proxy class:


This proxy object is actually a proxy that is passed over to the binder object at the far end, and he is the intermediary between the client side and the server interface. We can see in the previous stub class that:


This converts the Binder object passed from the far end into a local object, and finds that the object is obtained by using the Querylocalinterface method with the service descriptor:


The relationship between this mowner and Mdescriptor is initialized in the Attachinterface method, which is in the construction method of the stub class.


Now it is clear that if the client and server are in a process, then in fact Querylocalinterface gets the stub object, if not a process Querylocalinterface query object is definitely NULL, Because different processes have different virtual machines, it is certain that the Mowner object is not found, so this time is actually the proxy object returned. After the above explanation, it is found that the multi-process service communication benchmark is the binder object, the Binder object is passed, and then the binder is transferred to the available native object can be called, and for the stub class and the proxy class is equivalent to the service side and the client intermediary, By encapsulating some of the logic, this design is not so messy:

The stub class is the intermediary of the service side, generally implements the Aidl interface type and inherits the Binder class, and has the ability to convert the binder object into native object.

The proxy class is the intermediary of the client, generally implements the Aidl interface type



Iv. Analysis of system service invocation process

This figure is enough image, so you will see some of the system in the use of some services are actually cross-process use, such as the following to see the famous Packagemanager,ipackagemanager,packagemanagerservice System:


This is the ipackagemanager.aidl file, because we have not compiled the source code, so here may need to aidl tools compiled separately to see Ipackagemanager.java:


Here you see the familiar remote service intermediate stub and the local side of the intermediate proxy class, and the rules of these two classes are the same as above.

Here's a look at the remote Service implementation code Packagemanagerservice.java:


Implementation of the above stub class functionality.

Let's go over it again. Get the Packagemanager process:


And this Getpackagemanager method is implemented in the Contextimpl.java:


See, here we get a IBinder object from ServiceManager's GetService to a packagemanager far end, Then in the use of the stub Asinterface method to convert to a local Packagemanager object, is actually the proxy object. You can then call the method with Packagemanager to communicate with the remote Packagemanagerservice service.


Through the above Packagemanager case, we can analyze the process when we use the services in the system:


Each application will take such a few steps when using the system service:

1. Call the Getsystemservice (String serviceName) method to get the service object

2, and Getsystemservice is generally implemented in the Contextimpl class, is actually called the ServiceManager GetService method

3. Call ServiceManager's GetService method to get the IBinder object of the remote service

4. After the IBinder object with the remote service, the conversion object is asinterface by using the intermediary stub of the remote service.

5, because the service in the system is definitely cross-process, the remote service is in the system_server process, so the Asinterface method returns the proxy agent object, that is, the middle of the local side.

6, the last object returned is actually this proxy object, and this object is used inside the static proxy method, inside there is a mremote variable from the far end is the IBinder object. Then the direct call method is actually called Mremote's Transact method to communicate.

So in this process you can see that there are two objects that are important, one is ServiceManager, and the other is a IBinder object. Here's another introduction.


Five, the service of the big butler ServiceManager

So now there are a few questions, what is this servicemanager for? How can I get the IBinder object of the corresponding service through the service descriptor? This will take a look at the function of ServiceManager:

First look at his IBinder object method for obtaining a remote service, he will maintain a ibinder cache pool, and for the sake of high efficiency, it is much more efficient to use some services frequently for an application.


Then the most central way to get the service is the Getiservicemanager method:


This method sees, again a remote communication gets binder object, and this time is the Iservicemanager object:


See here the ServiceManager is also through the remote service to get to his IBinder object, and then converted to a local object for use. So just see the system's services are obtained through ServiceManager management, and now ServiceManager itself is how to obtain the IBinder object? This is going to start from the time of the system, it is well known that the system is started according to the Init.rc file operation:


Here will start a ServiceManager service, then go to the SERVICE_MANAGER.C program to see the entry program:


This portal actually contains important information about the binder mechanism, and is mainly about three things:

1, open the bottom binder driver, this later introduces the binder mechanism in the introduction

2. By sending a command to the Binder program: Binder_set_context_mgr, tell the binder program that I'm going to be a big housekeeper

3, into the Loop monitor upper application service request processing, so here can see actually ServiceManager is a daemon in the background silently monitoring

In the second step become the great Steward of the code in-depth look at:


In fact, the logic here is also relatively simple, first create a binder node belonging to ServiceManager, and then create a binder linked list, and the role of this list is to store the upper layer of the system to serve all the binder object node, This way, the ServiceManager can realize the service increment and the query operation.

Let's take a look at the Add service operation for ServiceManager:


Add the service is more complex, first check that the service has no registration permission restrictions, not all services can be registered, and then check whether the service has been registered, and finally notify the binder driver to register a service.

Then look at ServiceManager's lookup service features:


The lookup service is relatively straightforward, traversing the binder list node directly through the service descriptor name.

1, Service Manager can centrally manage all the services within the system, it can be applied to control the rights, not any process can be registered services.
2. Service Manager supports the use of string names to find the corresponding service.
3, due to various reasons, the server process may be life and death impermanence. If the service Manager is unified, the client will be able to get the latest information from the server as long as it queries the service Manager.


six, System service registration process Analysis

Let's take a look at how some of the system services are registered, and use mediaservice to check it out:

The startup of the Mediaservice service in the system is also in the init.rc


View the main function of the Main_mediaserver.cpp source code:


See the system mediaserver depend on a lot of other services, and these services must be registered, their registration operations are in their own initialization method, here with Mediaplayerservice to see the registration operation:


See the familiar code put, here through ServiceManager to do service registration, then here is how to get to ServiceManager?


Look at the source code of ProcessState.cpp:


Look at the Getstrongproxyforhandle method implementation:


As you can see here, we use Ipcthreadstate's Transact method to communicate with the underlying binder, and then use a handle handle to construct a Bpbinder object. And the Bpbinder object is actually the native layer implementation of binder object, as long as the first to see the BP is the proxy object corresponding to the Java layer proxy object, the BN begins is the native object corresponding to the Java layer stub object.

In the above analysis ServiceManager know will maintain a binder node list, there is actually a binder corresponding to the handle handle, and subsequent communication is through the handle to identify which service is the binder object, This will not occur in the communication of the disorder, and ServiceManager's handle handle is 0. There is also a knowledge point is the IPC communication can be seen when the transmission of data using the parcel class, this class is for cross-process communication generated, he has a method readstrongbinder, can be obtained from the parcel data to binder object, This is also the central place to pass binder objects across processes.


Well, the above is the system MediaServer service to explain the system service registration process:



We're done here. Remote service invocation mechanism logic in Android and ServiceManager this service the role of the Great Butler:


1, the first cross-process communication, there will certainly be two objects: one is the local side of the intermediate proxy object, a remote end of the intermediary stub object

2, the proxy object through the static proxy mode to maintain a remote pass through the binder object, and the stub object can transfer the far end of the binder object into a real service object to the application

3, Android in the use of system services through the Getsystemservice method to obtain is actually stub to the far end of the binder conversion object, because the system services are in the system_server process, so it is certainly cross-process to obtain the object, So this binder object is actually the proxy object above.

4, the system's services are in a specified system process System_server

5, service Butler ServiceManager in the system when the start is also obtained from the Binder object, and then into the actual operation of the object, and then can be operating system services registration and query function

The following is the registration process for some of the system services:




The above has introduced the remote five-blessing call mechanism and the implementation principle of ServiceManager, the following will look at another focus, is also mentioned above an important object binder, exactly this is the binder mechanism, In the Android binder mechanism of the most complex architecture system, its design is very complex, so a lot of students in understanding the binder mechanism, always look at the faint, today we will say the key, and it is relatively clear and simple.


analysis of binder mechanism

First, why does the IPC in Android use the binder mechanism

Binder is one of the inter-process communication (IPC) modes of Android systems. The inter-process communication IPC means that Linux already possesses include (Internet process Connection): Pipeline (pipe), signal (Signal) and Trace (trace), socket (socket), Message queue (message), Shared memory ( Share Memory) and Semaphore (Semaphore).

Binder based on the Client-server communication mode, the transfer process only one copy, for sending the Uid,pid identity, both support real name binder and anonymous binder support, high security. For binder, Binder can be seen as the access point that the server provides to implement a particular service, and the client through this ' Address ' sends a request to the server to use the service; For the client, binder can be viewed as a conduit entry to the server, and in order to communicate with a server you must first establish the pipeline and obtain a pipeline entry.


Second, the principle of binder implementation in Android

In fact, the binder communication in Android is implemented by the virtual driver Program/dev/binder, we know that some hardware will correspond to a driver, and binder driver does not have the corresponding hardware, so called Virtual Drive device program, In fact, he is a character drive device, or Miscdevice hybrid device driver.

In fact, hybrid drive device is a kind of character device, they share a main device number (10), but the second device number is different, all the hybrid device form a list, the device access to the kernel according to the secondary device number to find the corresponding Miscdevice device. For example: Touch screen, LED, button, serial port. That is: In order to save the main device number, some devices are linked together in the form of a list, and finally by finding the secondary device to differentiate. Here with the main device can not match the device driver, can only find the linked list, and then through the second device number, to find the device driver. As previously learned, the general character device, through the main device number, will be able to find the device driver. We can view the/dev/binder driver's main device number by command:



Third, the binder communication mechanism in Android

Take a look at a diagram, we can generally understand the client and the server through the binder driver to communicate


First, whether the client process or the server process is in the user space, and the binder driver is in the kernel space, the data of the communication is a specified format also called IPC data, since it is a communication mechanism, it is necessary to need the protocol, data format and other basic structure information:


Above in the analysis of the start of the ServiceManager said, the first step is to open the driver, specifically open the function in the BINDER.C:


Before using a driver, you must first turn on the driver, then map the driver into memory, and then communicate with the IPCTreadState.cpp and binder driver:


So see here Ipcthreadstate also need to enter the background to listen, processing from the client and server data transmission message


Finally, we look at the communication sequence diagram.


Here we introduce the binder mechanism, the binder mechanism is best not to look too deep, because the deeper you think the more complex the more difficult to understand, in fact, as long as you understand that he is a communication tool, communications using the drive operation, transmission of IPC data to communicate. Other details about his data format and communication protocols, interested students can understand, but too complex and in practice, not much use, so here is not introduced.


Viii. Summary of technical points

1, understanding the remote service communication mechanism

Through the case of the first understanding of the local and server-side cross-process communication, mainly through the use of binders for functional calls, and here there are two core classes, one is the stub class, This class is inherited by the binder class with a remote transfer of binder object to the local real object Asinterface method can be, while implementing the Ixxx interface, need to implement Aidl function method, there is a class is the proxy class, the implementation of the Ixxx interface, At the same time, the binder object passed by the remote is retained internally, and then the remote method is called through this object. Here the stub class is the intermediary of the service side, and proxy is the intermediary of the local side.

2. System service invocation Process

After analyzing the principle of cross-process communication mechanism, then look at the Android system in the use of some services, through the Getsystemservice method to obtain the service object, in fact, this is through the cross-process to obtain the remote Service Binder object, The system service objects are then converted to application calls, and the binder objects of these system services are automatically registered to ServiceManager when the system is started.

3, service big Butler ServiceManager

In the whole remote service invocation process two important objects, one is the binder object, one is the ServiceManager class, this class is the management system service class, he can register services, query services, system services at the time of system startup will be through AddService service registration, The application is then able to query the service through GetService, and in this process, the underlying will maintain a binder list structure of these services, while the binder object for each service is a handle handle, which represents the communication identity, so that communication is not disordered.

4, the bottom communication core binder

Finally, the paper analyzes the mechanism binder of the bottom layer to realize the cross-process communication, actually communicates through the virtual driver/dev/binder. A communication mechanism must have a communication protocol, the transmission of the data structure, but there is no introduction of this knowledge, because we do not have the need to use these, and secondly, these knowledge points too detailed introduction is not good, because the more chaotic.


Ix. Summary

This article is a bit more, but if you master the binder mechanism in Android and the remote service call mechanism on the back of the interception system API made a cushion , speaking of the end to tell everyone why to introduce this knowledge point, Because of the recent study of how to intercept a system to initiate activity, it is important to understand the activation process of the activity, but in this process one object is Activitymanagerservice, And he is closely linked to the binder and remote service invocation mechanism, if you do not understand the binder mechanism, there is no way behind the work, well, when it comes to a final picture of God is summed up the content of this article:


This is a good illustration of the process of using system services in Android, and it is the best and most complete explanation. After reading this picture, the binder mechanism and the remote service invocation mechanism in Android can be mastered and can be used for subsequent interception operations.


Click here for more information:

Focus on the public, the latest technology dry real-time push



Analysis of----binder mechanism and remote service invocation mechanism of Android system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.