[]Android Binder design and implementation design

Recommended for you: Get network issues from WhatsUp Gold. Not end users.


Binder is a Android system interprocess communication (IPC) is one of the ways. Linux already has a pipeline, system V IPC, socket IPC means, but also rely on Binder to realize inter process communication, Binder has the advantage that there is nothing comparable to this. In depth understanding of Binder and traditional IPC do contribute to our in-depth understanding of inter process communication implementation and performance optimization. This paper will design details on the Binder to do a comprehensive exposition, first introduced by Binder communication model and Binder communication protocol to understand the design requirement of Binder; and then expatiates the role of Binder in different parts of the system and the expressions of Binder in number; finally explain according to consider the design of the receiver, including the thread pool management, the memory mapping and the waiting queue management etc. By comparing the details of Binder and other IPC communication mode, the reader will be on the advantages of Binder and using Binder as the main reason Android IPC a deep understanding of.

1 Introduction

Communication method based on Client-Server is widely used in the Internet and database access to the embedded handheld fields of internal communication equipment. Intelligent mobile phone platform especially in Android system, in order to provide the various functions to the application developers, this means of communication is ubiquitous, such as media playback, video audio frequently capture, sensor to allow mobile phone more intelligent (acceleration, range, temperature, light and etc.) by different Server is responsible for the management, application just as the establishment and the Server Client connection can use these services, spend a little time and effort to develop a blinding function. Client-Server is widely used on the way interprocess communication (IPC) mechanism is a challenge. Currently Linux supports IPC including traditional pipeline, System V IPC, message queue / shared memory / signal, communication is only supported on socket Client-Server and socket. Of course, also can set up a set of protocols in the underlying mechanism to realize Client-Server communication, but this increases the complexity of the system, the mobile phone of this condition is complex, the reliability of the scarcity of resources environment is also hard to guarantee.

On the other hand is the transmission performance. Socket as a universal interface, the transmission efficiency is low, big spending, mainly used in inter network interprocess communication and the machine process between the low-speed communication. Message queue and pipeline using store and forward mode, namely the data from the sender buffer copy to the kernel development buffer, and then from the kernel buffer is copied to the buffer, there are at least two times the copy process. Shared memory although no copy, but the control of complex, difficult to use.

Table 1 IPC the data copy times


The data copy times

Shared memory




Socket/Pipeline / message queue


Another point is considering safety. Android as an open platform, with many developers, the source application widely, to ensure that the intelligent terminal safety is very important. End users don't want from the Internet to download programs peeping privacy data unknowingly, connected to a wireless network, long-term operation device result in battery soon depleted etc. The traditional IPC without any safety measures, entirely dependent on the upper layer protocol to ensure. First, the traditional IPC receiver unobtainable process reliable UID/PID (user ID/ process ID), thus unable to identify the identity of the other side. Android is assigned its own UID application installed good for each, so the process of UID is an important symbol of the identity of the identification process. Traditional IPC can only be used by the user in the data packet is filled with UID/PID, but it is reliable, easy to be malicious program using. Identification of reliable only added by the IPC mechanism in the kernel. Secondly, the traditional IPC access point is open, the private channel could not be established. Name such as named pipes, system V key, socket IP address or the file name is open, as long as you know these access points program can be connected and to end up, no matter how can prevent malicious programs by guessing receiver address get connected.

Based on the above reasons, Android need to establish a new IPC mechanism to meet the communication mode, the transmission performance and safety requirements, this is Binder. Binder Client-Server communication mode based on the process of transmission, only one copy, to send to add the UID/PID identity, both to support real Binder also supports anonymous Binder, high safety.

2 object oriented Binder IPC

Binder use Client-Server communication: a process as Server services such as video / audio decoding, video capture, address book query, network connection service; multiple processes as Client to Server launched a service request, to obtain the required service. In order to realize the Client-Server communication according to must achieve the following two points: one is the server must have certain access point or address to accept the request of Client, and the Client can through some way to acquire the Server address; the two is to develop Command-Reply protocol to transmit data. For example, the access point Server in the network communication is the Server host IP address and port number, transmission protocol for the TCP protocol. For Binder, Binder can be regarded as the access point to a specific service implementation provided by the Server, Client the &lsquo address ’ Server; to send the request to use the service; for Client, Binder can be seen as the path to the Server pipeline entrance, to a Server communication must first establish the pipeline and obtain the pipeline entrance.

Unlike other IPC, Binder uses the object-oriented thought to describe as an access point of Binder and Client in the entrance: Binder is an entity in the Server object, the object is to provide a method for the realization of the service request, member functions like class. Entrance around in client can be seen as pointing to this binder object pointer to ‘ ’, once the &lsquo pointer; ’ you can call the object access server. In the view of Client, through the Binder&lsquo pointer; ’ call the method provided by the method pointer and call any other local object does not have the difference, although the former entity in the Server, the latter entity located in the local memory. ‘The pointer is ’ C++ terminology, and more generally, is quoted, namely Client through Binder's reference to access the Server. While the software field another term handle ‘ ’ can also be used in expressions of Binder in Client. From the communication point of view, in the Client Binder can be regarded as Server Binder ‘ &rsquo agent;, provides the service for Client in the local representative of the remote Server. This paper will use ‘ &rsquo or ‘ reference; the handle to the ’ the two widely used term.

Introducing the object oriented thought will inter process communication into the method call by reference of the object is a Binder object, which is unique in the Binder object is a process of cross referenced objects, the entity is located in a process, each process and its reference is throughout the system. The most attractive is, the references and Java references can be strongly typed, can also be a weak type, but also from one process to another process, so that everyone can access the same Server, like an object or a reference variable to another reference. Binder fuzzy process boundary, weaken the inter process communication process, the whole system seems to run in the same object oriented programming. Of every hue Binder object and dotted with reference as bonding each application of glue, which is Binder in English meaning.

Of course, just for object-oriented applications, for the Binder driver and kernel modules using the C language, there is no concept of class and object. Binder driver provide underlying support for object oriented interprocess communication.

3 Binder communication model

Binder framework defines four roles: Server, Client, ServiceManager (SMgr) and Binder drive. The Server, Client, SMgr running in user space, drive runs in kernel space. These four characters and the relationship between the Internet: Server is similar to Client server, client terminal, SMgr is the domain name server (DNS), the drive is the router.

3.1 Binder driver

And as a router, Binder drive though unknown to the public, the core is communication. Despite the name ‘ &rsquo driver;, actually has nothing to do with hardware equipment, just realizing method and device driver is the same: it works in kernel mode, open (), MMAP (), poll (), IOCTL () standard file operations, with character driven equipment misc equipment registration in the list of equipment /dev, /dev/binder users visit it. Binder communication is established between the driver responsible for process, Binder transfer between processes, Binder reference count management, data packets in the process of transmission and the interaction between a series of bottom support. Driving between application and defines a set of interface protocol, main function by IOCTL () interface, does not provide read (), write (IOCTL) (for) interface, flexible and convenient, and can be a call to read after write to satisfy the synchronous interaction, instead of using write (respectively) and read(). Binder driven code is located in the Linux directory drivers/staging/android/binder.c.

3.2 ServiceManager and real Binder

Similar to DNS, SMgr is the role of the character form of the Binder name into a reference to the Binder Client, the Client can obtain a reference to the Binder entities in Server by using the Binder name. Registered the name Binder is called real Binder, as each site in addition to IP address and your web site. Server created the Binder entity, a character in the form, readable and easy to name, the Binder along with the name in the form of data packets through the Binder drive is sent to the SMgr, notify SMgr registered to a man named Zhang San Binder, it is located in an Server. Driving a physical node in the kernel and SMgr references to entities for the across process boundaries Binder, the name and the new reference packing transfer to SMgr. SMgr received data packet, remove the name from the references in and fill a lookup table.

The careful reader may find one catch: SMgr is a process, Server is another process, Server registered with SMgr Binder will inevitably involve interprocess communication. The current implementation is inter process communication and inter process communication is used, it is like eggs can be hatched chicken the premise is to find a chicken eggs. Binder to achieve more clever: pre create a chicken to egg: SMgr and other process using the same Binder communication, SMgr Server end, have their own Binder objects (entities), other processes are Client, need to refer to the Binder to realize the Binder registration, query and retrieval. SMgr Binder is special, it has no name does not need to register, when a process to use the BINDER_SET_CONTEXT_MGR command to register themselves into a SMgr Binder driver will be automatically created for it a Binder entity (this is the only pre made chicken). Secondly, the reference to the Binder in all Client are fixed to 0 without obtaining by other means. That is to say, a Server to SMgr your Binder must be registered by 0 this reference number and SMgr Binder communication. Analog network communication, 0, cited as the domain name server address, you must manually or dynamic configuration. Note here that the Client is compared with SMgr, an application may be a service provided to SMgr Server, but it is still a Client.

Reference 3.3 Client name Binder

Server to the SMgr registered Binder entity and its name, Client can be obtained through the Binder name references. Client also uses reserved 0 references to SMgr requests access to a Binder: quote me to apply for the name Zhang San Binder. SMgr receives the connection request from the request packet, get a Binder name lookup table the name is found, the corresponding entry, remove the Binder references from the entry, the reference as a reply is sent to the Client request. From the point of view of object-oriented, this Binder object is now have two references: one is located in SMgr, one at the request of Client. If there is more Client requests to the Binder, the system will have more references to the Binder, an object like Java has multiple references. But such a reference to the Binder is a strongly typed, so as to ensure that as long as there are references to Binder entity will not be released. Through the above process can be seen, SMgr like a train ticket daishoudian, gathered all the train ticket, can buy the train ticket to ride - get a reference to a Binder.

3.4 anonymous Binder

Not all of the Binder are required to be registered to SMgr advertising. Server terminal will be able to create Binder to Client entity has been established through the Binder connection, of course, this article has established the Binder connection must be achieved by real Binder. Because the Binder is not registered names to SMgr, so it is an anonymous Binder. Client will receive a reference to the anonymous Binder, through this reference to the sending entity in Server request at. Anonymous Binder set up a private channel for the communication of both sides, as long as the Server did not leave the anonymous Binder to another process, other processes can not be exhaustive or guessing by any ways to get references to the Binder, the Binder sends a request to the.

The diagram below shows all the roles involved in Binder communication, will be in later chapters one one to.


Fig. 1 communication example Binder

4 Binder protocol

The Binder protocol is the basic format (Command + data), the use of IOCTL (FD, CMD, Arg) to realize the interactive function. The command by the parameter CMD bearing, Arg bearing data by parameters, varied with cmd. The table below lists all the commands and the corresponding data:

Table 2 Binder communication command word





The command to write or read data to Binder. Parameter is divided into two sections: write and read part. If write_size is not 0 to write_buffer the data written to the Binder; if read_size is not 0 then reads data from Binder into read_buffer. Write_consumed and read_consumed said the operation is completed when the Binder drive the actual number of read or write data.

struct binder_write_read {

signed long write_size;

signed long write_consumed;

unsigned long write_buffer;

signed long read_size;

signed long read_consumed;

unsigned long read_buffer;



This command tells Binder to drive the receiver (usually Server) the maximum number of threads in the thread pool. Because Client is associated with Server terminal sends a request to the Server end of the thread pool, must be developed to provide services for these concurrent requests. Inform the maximum driving the thread pool is to let the driver found the number of threads when reaching the value don't command receiver to start a new thread.

int max_threads;


The current process to register for SMgr. The system also can only have a SMgr. As long as the current SMgr does not call close () to close the Binder driver cannot have another process can become a SMgr.



Inform the Binder drive current thread exit. Binder will all participate in the Binder communication thread (including Server threads in the thread pool and Client the requesting thread) to establish the corresponding data structure. These threads must inform the driver to release the corresponding data structure on exit.



Binder driver version number.


This is one of the most commonly used commands is BINDER_WRITE_READ. The order parameter includes two parts: one part is the data written to the Binder data, a part is to read from the Binder data, the driver first write part processing read part. The advantage of this arrangement is the application can be very flexible processing command synchronous or asynchronous. For example, if you want to send asynchronous command can only fill in the writing part and the read_size set to 0; to obtain data to write some empty write_size set to 0 from Binder; if you want to send the request and returns the data synchronization waiting can be two parts are arranged on the.

4.1 BINDER_WRITE_READ write operation

Binder write operation data format is also (Command + data). This command and data are stored in the binder_write_read structure of the write_buffer domain to memory space, multiple commands can be stored in a row. The data stored in the command following behind, format is different according to different order. The following table lists Binder write operations support command:

Table 3 Binder write operations command word





BC_TRANSACTION for Client sends a request to the Server data; BC_REPLY for the Server to the Client to send data back (Ying Da). It followed by a binder_transaction_data structure shows that the data to be written.

struct binder_transaction_data


Not implemented



The release of a mapped memory. The MMAP (Binder) by mapping a large memory space, Binder driving this piece of memory by the best matching algorithm for dynamic allocation and release the receiving data buffer based on concurrent requests, to meet the demand of a receiving buffer. Application to finish processing the data as soon as possible to use this command to release the buffer, otherwise will be unable to receive new data because the buffer depletion.

Pointer to a buffer to release; the pointer in the received Binder packet


This set of commands to increase or decrease the Binder's reference count, is used to realize the strong or weak of function pointer to pointer.

32 digit Binder reference number


The first Binder entity reference counting, driven process to send BR_INCREFS to Binder, where the entity BR_ACQUIRE message; the Binder entity process is finished processing feedback BC_INCREFS_DONE, BC_ACQUIRE_DONE

void *ptr: The Binder entity in the user space pointer

void *cookie: Additional data associated with the entity


This set of commands with BINDER_SET_MAX_THREADS a Binder drive on the receiving side thread pool management. BC_REGISTER_LOOPER informs the driver in the thread pool to a thread has been created; BC_ENTER_LOOPER notification to drive the thread has entered the main loop, you can receive data; BC_EXIT_LOOPER notice to drive the thread to exit the main loop, no longer receive data.



Binder reference process through the command to drive in the Binder entity destruction notice. Although strong pointer can ensure that as long as the reference is not destroy the entity, but after all it is a process of cross references, no one can guarantee that entity and disappeared because of where the Server closing the Binder drive or abnormal exit, reference can do is ask Server now gives notice.

uint32 *ptr; Need to get the death notice Binder references

Void **cookie: is associated with death notification information, driving will be returned to the requesting process in a death notice.


Received the entity death notice process the command delete references to inform drivers.

void **cookie

In all of them, the most commonly used is the BC_TRANSACTION/BC_REPLY command, Binder request and response data is sent to the command to receiver through the. The bearing of the command packet by the structure struct binder_transaction_data definition. Binder interaction with synchronous and asynchronous points, distinguished by the use of flag in the binder_transaction_data domain. If the flag domain of TF_ONE_WAY is 1 for asynchronous interaction, namely the Client terminal sends the request that the end is not interactive, Server returns BC_REPLY data packet; otherwise Server will return the BC_REPLY packet, Client end must wait to receive the data packet to complete an interaction.

4.2 BINDER_WRITE_READ : Read data from the Binder

Read from the data in Binder format and write to the data in Binder format, using the (message ID+ data), and multiple messages can be stored in a row. The following table lists the parameters from the Binder read command words and their corresponding:

Table 4 the Binder read operation message ID

The news




An internal error occurred (such as memory allocation failure)



The operation completed



The message for the receiver thread pool management. When the drive that all threads in the total threads busy and thread pool does not exceed the maximum number of threads BINDER_SET_MAX_THREADS settings, to send the command receiver requirements create more threads for receiving data.



The two message corresponding to the sender's BC_TRANSACTION and BC_REPLY, said the data currently receives a request or reply.



Has not yet been achieved



The interactive process if found each other process or thread dead returns the message



The sender by BC_TRANSACTION or BC_REPLY to send a data packet, can receive the message is successfully sent as feedback. This is not the same as BR_REPLY, inform the sender has sent successfully is driven, rather than the Server side to return the requested data. So whether synchronous or asynchronous interaction receiver can get this message.



This set of messages for the reference count management strong / weak pointers. Only the Binder entity process can receive this message.

void *ptr: The Binder entity in the user space pointer

void *cookie: Additional data associated with the entity


To get the send Binder entity process Binder cited death notice; received notice of death process will return BC_DEAD_BINDER_DONE for confirmation.

void **cookie: Additional parameters in the use of BC_REQUEST_DEATH_NOTIFICATION registered death notification when the.


If the sending illegal reference number returns the message


Like to write data, one of the most important news is BR_TRANSACTION or BR_REPLY, that received a format for the request binder_transaction_data data packet (BR_TRANSACTION) or return data package(BR_REPLY).

4.3 struct binder_transaction_data : Send and receive data packet structure

The structure of Binder standard format for receiving / sending data packets, each member is defined as follows:

Table 5 Binder to send and receive data packet structure: binder_transaction_data



union {

size_t handle;

void *ptr;

} target;

To send data packets to a party, the members specified transmission destination. Since the objective is in the remote, so here in is a reference to the Binder entity, stored in the target.handle. As mentioned above, Binder reference is also called the handle in the code(handle).

When packets arrive at the receiver, the drive has the member to modify Binder entity, which is a pointer to a Binder object in memory, use target.ptr to get. The pointer is submitted to the drive in the Binder entity is transmitted to the other process, the driver will be able to automatically fill the reference pointer sender into recipient Binder objects, so the receiver can directly as the object to which the pointer to use (usually the reinterpret_cast into the corresponding class).

void *cookie;

The sender to ignore the members; the receiver receives data packets, the member store is to create the Binder entity when the recipient by any custom value, as additional information related to the Binder pointer stored in the drive. Drive basically do not care about the members.

unsigned int code;

This member holds the transceiver agreed command code, driving don't care about the member's content. Usually the public interface function of Server terminal defined number.

unsigned int flags;

And the sign of interaction related, of which the most important is TF_ONE_WAY. If the position that the interaction is asynchronous, Server does not return any data. Driven by the position to decide whether the construction and return the data structure. Another TF_ACCEPT_FDS is for safety, if the request of a party does not wish to receive the file in the form of response in Binder can be the position. Because receives a documented Binder will automatically to the data receiver to open a file, use the bit can prevent too many open files.

pid_t sender_pid;

uid_t sender_euid;

This member holds the sender process ID and user ID, driven by the responsible for fill, recipient can read the members informed of the identity of the sender.

size_t data_size;

The member that stored in the buffer pointed to by data.buffer data length. Fill in by the sender to send data, said the outgoing data length; in the receiver to inform the received data length.

size_t offsets_size;

Drive normally don't care what data.buffer stored data, but if there is a Binder in which the transmission is to be relatively data.buffer offset that lets drivers know. There may be multiple Binder at the same time transfer in the data, so that all must be offset by array. The members said the size of the array.

union {

struct {

const void *buffer;

const void *offsets;

} ptr;

uint8_t buf[8];

} data;

The data.bufer store to be sent or received data; data.offsets refers to the Binder offset array, the array can be located in data.buffer, also can be in another memory space, there is no limit. Buf[8] is for both guarantee 32 bit or 64 bit platform, a member of the data size is 8 bytes.

Here it is necessary to emphasize the two members of offsets_size and data.offsets, which is different from other IPC local Binder communication. As mentioned above, Binder uses object-oriented design idea, a Binder entity can refer to send other processes to establish many cross process; in addition to these references can also be passed between processes, like Java will be a reference is assigned to another reference. For the Binder based on different reference must be driven in the process of participation, driven by the kernel to create and register the corresponding data structure after the receiver can use the references. But these references can be strongly typed, need to drive for its maintenance reference counting. However, the process of cross transmission of Binder mixed in the data packet sent by application, data format defined by the user, if you do not put them in one one marked told drive, drive will not be able to extract it from the data. Then using an array of data.offsets store each Binder relative to the data.buffer offset user data, with offsets_size said the size of the array. Driving in sending data packets will be scattered according to data.offsets and offset_size in data.buffer Binder to find out and one one for them to create data structure related. In the Binder data packet transmission type structure of struct flat_binder_object, see the.

For the receiver, the structure is only equivalent to a fixed length message header, the actual user data stored in the buffer pointed to by the data.buffer. If the data is embedded with one or more Binder, received data packets in the same data.offsets and offset_size point out that with each location of the Binder and the total number of. But usually the receiver can ignore this information, because the recipient know data format, reference format definition can be agreed upon between the parties know these Binder in what position.


Figure 2 BINDER_WRITE_READ packet case

5 Binder expression

Examine an Binder communication process will find, Binder exists in the system the following sections:

· Application process: located in the Server process and Client process

· Binder driver: manage to reference the Binder entity and the Client Server end end

· Data transmission: because Binder can cross process transfer, need to be stated in the transmission of data

In different parts of the system, the functions of Binder in different forms, not the same. Then discusses the Binder data structure at the role and use of each part of the play.

5.1 Binder in an application expression

Although the Binder used the object-oriented thought, but does not limit the application must use the object-oriented language, both the C language or C++ language can easily use Binder to communication. For example, although Android the main use of java/C++, like SMgr such an important process is implemented with C language. But the object-oriented way more convenient, so we assume that the application is using object oriented language.

Binder is essentially just a kind of communication mode, it doesn't matter and specific service. In order to provide specific services, Server must provide a set of interface functions for Client using a variety of services via remote access. This usually adopts Proxy design pattern: the interface functions defined in an abstract class, Server and Client will be in this abstract class is the base class implementation all interface function, which is different from the Server terminal is a real function, but Client is the function of remote calls to packaging. So how to combine Binder and Proxy design pattern is the application realization of the fundamental problems of object oriented Binder communication.

5.1.1 Binder at the Server end of the &ndash representation of the Binder entity;

As the basis of the Proxy design pattern, we define an abstract interface class that encapsulates the Server all functions, including a series of pure virtual functions for Server and Proxy respectively realize. Because these functions need to cross process calls, must be the one one number, so Server can determine which function according to the received serial number. The second is to introduce Binder. Server defines the end of another Binder abstract class from Client Binder request packet, the most important member function is virtual onTransact(). The function of the received data packets, call the relevant interface functions process the request.

The inheritance interface classes and the Binder abstract class to build a base class Binder in Server entities, all the base class virtual function, including public interface function and data packet processing function: onTransact(). The function of the input is binder_transaction_data structure from the Client packet. As mentioned, a member code the structure, including the interface function request the number. onTransact()The case-by-case analysis of code value, from the data packet function parameters, the corresponding interface class, public interface function has been achieved. Function is executed, if you need to return data to construct a binder_transaction_data package will return the data packet into the.

Then each Binder entity (onTransact) and when to call? This requires the drive in. Before that, the Binder entity needs to other processes to establish Binder communications to transmit Binde transmission structure form of flat_binder_object, while the Binder entity pointer is stored in the handle field of the structure. Drive according to the Binder position array from the transmission of data transmission structure of the Binder, a Binder node in the kernel for it, the Binder entity pointer records at the node. If then there are other processes to the Binder to send data, drive according to the information recorded in the Binder entity node pointer in binder_transaction_data target.ptr returned to the receiving thread. The receiving thread from the removal of the pointer data package, reinterpret_cast Binder abstract class and call onTransact () function. Because this is a virtual function, have their own different kinds of Binder entity, which can be called to different entities with onTransact Binder().

5.1.2 Binder at the Client end of the &ndash Binder reference expression;

As part of the Proxy design pattern, the public interface class Client end Binder the same to inherit Server and implement public function. But this is not true, but to the remote function call packaging: the function parameters packing, through Binder sent to the Server application and wait for the return value. Therefore Client end Binder must know the relevant information, the Binder entity, which is a reference to the Binder entity. The reference or come forward by the SMgr, the real Binder reference or come by another process directly, a reference to the anonymous Binder.

Due to the inheritance of the public interface class the same, Client Binder provides the function prototype with Server Binder, the user can not feel Server is running on a local or remote. Client Binder, packing public interface function is: create a binder_transaction_data packet, the corresponding code in the code domain, the parameters of the function call to data.buffer to fill the cache, and specify the destination of the packet, that is already available to the Binder entity references, filled with target.handle in packet. Notice the difference between here and Server: actually target domain is a union, including two members of the PTR and handle, the former is used for receiving the packet Server, pointing to the Binder entity corresponding memory space; the latter is used as the reference for the requesting party Client, Binder entities, inform the driver data packet is routed to which entity. The packet is ready, the driver interface sends out. After BC_TRANSACTION/BC_REPLY rounds complete remote function call and return value.

5.2 Binder in the transmission of data representation

Binder can plug in the valid data and process the packet boundary from one process to another process, the transmission of Binder is represented by the structure of flat_binder_object, as shown in the following table.:

Table 6 Binder transmission structure: flat_binder_object



unsigned long type

That indicates the type of the Binder, including the following:

BINDER_TYPE_BINDER: The representation of transfer is a Binder entity, and the entity reference point is strongly typed,

BINDER_TYPE_WEAK_BINDER: The representation of transfer is a Binder entity, and the entity reference points are weakly typed,

BINDER_TYPE_HANDLE: The representation of transfer is strongly typed reference Binder

BINDER_TYPE_WEAK_HANDLE: The representation of transfer is weak Binder type reference

BINDER_TYPE_FD: The representation of transfer is documented Binder, see the next section

unsigned long flags

The domain is only valid for the first pass Binder entity, because now drive to create entity corresponding nodes in the kernel, some parameters need to be removed from this domain:

Article 0-7: code using the FLAT_BINDER_FLAG_PRIORITY_MASK, said the lowest priority processing the entity requesting thread of packets. When an application providing a plurality of entity, through the processing parameter adjustment is assigned to each entity.

Eighth: code using the FLAT_BINDER_FLAG_ACCEPTS_FDS, the 1 indicates that the entity can receive other process sends the file format of Binder. Because the received file form Binder will automatically open the file in the process, some of the Server can use the logo prohibit the function, to prevent too many open files.

union {

void *binder;

signed long handle;


Use the binder field when transmission is a Binder entity, pointing to the Binder entity in the application's address.

When the transfer is to use the handle domain of Binder references, reference number stored in the process of Binder.

void *cookie;

The domain is only valid for Binder entity, to store additional information associated with the Binder.

Both the Binder entities or references to entities are affiliated with a process, so the structure can not be transmitted transparently in the process, must be driven translation. For example, when Server the Binder entity is passed to the Client, sending data stream, flat_binder_object type is BINDER_TYPE_BINDER, binder to Server process user space address. If transmitted to the receiving end will be of no use, the drive must make changes to the data flow in the Binder: type the BINDER_TYPE_HANDLE; for the Binder in the receiving process in the creation in the reference in the kernel and the reference number in the handle. For the data flow in a reference type Binder will do the same conversion. After treatment the receiving process is referenced from the data flow acquired Binder after is effective, it can fill in the target.handle domain of binder_transaction_data data packet, sends a request to the Binder entity.

It is also considering safety: the application can not guess a reference number in the target.handle can request a service to Server, because the drive is not for you to create the reference in the kernel, will be driving refusal. Only through authentication to confirm the legal authority, by ‘ ’ (Binder driver) have granted your Binder to use, because it has been driven in the kernel for you to use the Binder to do the registration, to the reference number you are legal.

The following table summarizes the driver do when flat_binder_object structure through the drive operation:

Table 7 driving operation on flat_binder_object

Binder Type( type Domain)

In the sender's operation

In recipient operation



Only send this type of Binder entity's process. If this is the first time sends driving node will create entity in the kernel, and the preservation of binder, cookie, flag domain.

If the quote first receives the Binder entity in the kernel; handle replaced with references to the new domain, type domain is replaced by BINDER_TYPE;_(WEAK_)HANDLE



Binder reference process can send the type Binder. Drive according to the handle domain provides reference number lookup based on kernel references. If you find a quote, legal, or reject the request to send.

If the received Binder entity at the receiving process: the PTR domain is replaced with the binder value stored in the node; cookie replaced the cookie value stored in the node; type replacement for BINDER_TYPE_(WEAK_)BINDER.

If you receive a Binder entity is not in the receiving process: if this is the first time to receive reference does create entity in the kernel; the handle domain are replaced with references to the new No.


Verify the handle domain provides a number of open file is valid, invalid rejected the request to send.

Create a new file open, and the open file description structure and binding in the receiver.

The file format of 5.2.1 Binder

In addition to the usual sense for communication of Binder, there is a special kind of Binder file: Binder. The basic idea of Binder is: the file as Binder entity, process open file number as a reference to the Binder. A process can be opened file, transfer to another process, and another process also open the same file, cited in the process of transfer between like Binder.

A process to open a file, and the file was bound to open the file number. From the perspective of Binder, Linux in the kernel to create open file describes the structure struct file is a Binder entity, open the file number is a reference to the entity of the process. Since Binder is then can be passed between processes, it can also use the flat_binder_object structure of Binder files by data packet is sent to the other processes, only the type domain structure in the value is BINDER_TYPE_FD, indicating that the Binder is the file Binder. While the handle domain structure in the storage file in the sender process to open the file number. We know the number of open files is limited to a process, once the process has no meaning. This point and the Binder entity Binder user pointer or reference number is the same, if you want to cross process also need to drive the conversion. The drive to create a new file in receiving Binder process space, will open the file it with the existing structure description of struct file hook, then the Binder entity and a reference. The new open file number covering flat_binder_object original document number to the receiving process. The receiving process which can be used to execute read (), write (), file operations.

A document why go to so much trouble, directly to the file name with the Binder pass in the past, the receiver uses the open () to open the line is not it? In fact, this is a difference. Firstly, with an open file sharing of different levels: use the file Binder to open the file sharing in Linux VFS struct file, struct dentry, struct inode structure, which means that a process using the read (/seek) /write () () to change the file pointer, the file pointer to another process will change; and if two processes are using the same file name to open the file with struct file's own structure, thereby maintaining the file pointer independently, without mutual interference. The second is the special device file in struct file level sharing can be used, such as another Android drive ashmem, it is the same as Binder and misc equipment, to achieve shared memory between processes. A process to open a ashmem file only achieve shared memory through Binder documents sent to another process, which greatly improves the security of shared memory, reason and enhances the security of Binder IPC is the same.

5.3 Binder in driving expression

Driving is the core of Binder communication, all Binder entities in the system and each entity references in each process are registered in the drive; driving need to record Binder reference -> among the entities in a one to many relationship; as a reference to find the corresponding entity; created for entities in a process or to find the corresponding reference; attribution to record Binder (which is located in the process); the management of Binder strong / weak reference creation / destruction of Binder entity.

Drive Binder is when you create? As mentioned before, in order to achieve the real name registration system of Binder, you must create the first chicken – created for SMgr, is used to register real name Binder Binder entities, real name registration process for Binder interprocess communication. Since founded entity references to the corresponding: in the process of driving all 0 references are reserved for the Binder entity, namely all the processes of 0 references to point to the registered name of natural Binder special Binder, no special operation that can be used for reference to register the name Binder No. 0. Next, as applications continue to register real name Binder, to SMgr for Binder references, the Binder is passed from one process to another, more and more Binder to transfer structure - flat_binder_object form through the drive to do cross process migration. Since array data.offset in the presence of binder_transaction_data, all through the Binder driven away but drive eyes. Binder will do the following operations on these across process boundaries: type Binder domain to examine the transmission structure, if it is BINDER_TYPE_BINDER or BINDER_TYPE_WEAK_BINDER to create a Binder entity; if it is refer to BINDER_TYPE_HANDLE or BINDER_TYPE_WEAK_HANDLE create Binder; if BINDER_TYPE_HANDLE is a process to open the file, without creating any data structure. The detailed process can refer to table 7. With more and more Binder entity or reference in the process, driving node will create more and more in the kernel or reference, of course, this process is transparent to the user.

5.3.1 Binder entity in driving expression

Drive Binder entity named ‘ &rsquo node;, belonging to offer physical process, by the struct binder_node structure to represent:

Table 8 describes the structure of Binder node: binder_node



int debug_id;

For debugging.

struct binder_work work;

When the node reference counting change, need to inform the process, through the member into the process of to-do hanging queue, wake up the process of the implementation of Binder entity reference counting modifications.

union {

struct rb_node rb_node;

struct hlist_node dead_node;


Each process maintains a red black tree, to the Binder entity in the user space pointer, the structure of the PTR members as the index storage of the process all the Binder entity. So the driver can according to the Binder entity pointer in user space soon found at its core node. Rb_node is used for the node chain into the red black tree.

The destruction of the rb_node node from the red black tree removal, but if the node and the reference not cut, will the node isolation to another list with dead_node, until notification of all processes and cut references the node, the node can be destroyed.

struct binder_proc *proc;

The member node belongs to the process, which provides the node process.

struct hlist_head refs;

This member is the head of the queue, all references to the nodes are linked in the queue. These references may belong to different process. The queue can traverse all references to that node.

int internal_strong_refs;

With the counter to achieve strong pointer: a strong reference to the nodes of the count will add 1.

int local_weak_refs;

Counting a weak reference driven transmission in the Binder settings. If a Binder is packaged in a data packet sent from one process to another, the drive will increase the reference count of the Binder, until the process of receiving notice drive release the packet data through the BC_FREE_BUFFER.

int local_strong_refs;

The drive set for the transmission of Binder and strong reference counting. Ditto.

void __user *ptr;

Pointer to the user space Binder entity, from the flat_binder_object binder member

void __user *cookie;

Additional pointer to user space, from the flat_binder_object cookie member

unsigned has_strong_ref;

unsigned pending_strong_ref;

unsigned has_weak_ref;

unsigned pending_weak_ref

This group of signs used to control driver and Binder entities interactive revise reference counting process

unsigned has_async_transaction,

The member that the node has not yet completed in asynchronous interaction in the to-do queue. The drive will be all sent to the receiving end receives the packet is temporarily stored in the thread or process the to-do queue. For asynchronous interaction, driving the flow control: if the to-do queue with asynchronous interaction pending the member is set to 1, this will lead to new asynchronous interaction in the &ndash to store the structure members; asynch_todo queue, and not directly to a to-do queue. For the purpose of synchronous interaction way, avoid long time blocking send end.

unsigned accept_fds

Indicates whether the node accepts files from Binder, flags member of the flat_binder_object FLAT_BINDER_FLAG_ACCEPTS_FDS. Because the received file Binder will automatically open a file for the process, occupy the limited file descriptors, the node can be set the rejection of such conduct.

int min_priority

Set the lowest priority processing the Binder request thread. The sending thread submit data to the receiving thread processing, driver sends the thread priority has also given the receiving thread, make the data even cross the process can be treated in the same priority. But if the sending thread priority is too low, the receiving thread will be the default minimum operation.

The field values from the flat_binder_object flags member.

struct list_head async_todo

Asynchronous interaction waiting queue; used for splitting the node to asynchronous interaction.

Each process has a red black tree is used to store the node creates good, using Binder in user space pointer as an index. Whenever in the transmission of data detected a representative Binder flat_binder_object entity, to the structure of the binder pointer as the index search tree; if it is not found on the establishment of a new node is added to the tree. As for the same process memory address is unique, so it will not repeat construction cause confusion.

5.3.2 Binder quoted in driving expression

And like entities, Binder reference is driven according to the transmission of data to create flat_binder_object, belonging to obtain the reference process, represented by the struct binder_ref structure:

Table 9 describes the structure of Binder reference: binder_ref



int debug_id;


struct rb_node rb_node_desc;

There is a red black tree each process, process all references to reference number (i.e., the structure of the desc domain) as an index into the tree. The member for the link to a node of the tree.

struct rb_node rb_node_node;

There is a red black tree and each process, process all references to node entities in the drive of the memory address (that is, the structure of the node domain) is added into the tree in the. The member for the link to a node of the tree.

struct hlist_node node_entry;

The domain of the reference binder_node Binder entity structure pointing to the node chain in refs queue

struct binder_proc *proc;

The reference of process

struct binder_node *node;

The reference node points (Binder entity)

uint32_t desc;

Reference number of the structure

int strong;

The strong reference counting

int weak;

A weak reference counting

struct binder_ref_death *death;

Application to send BC_REQUEST_DEATH_NOTIFICATION or BC_CLEAR_DEATH_NOTIFICATION command driven so that when the Binder entity can receive from destruction to remind the driver. The domain is not empty show users to subscribe to the corresponding physical destruction of the &lsquo news;’.

Like an object has many pointers, with a Binder entity may have many references, these references may distribution is different in different processes. And like entities, each process is used to store all references to use red black tree. Unlike the Binder references can through two key index:

· The corresponding entity in the kernel's address. Note this is binder_node structure driven founded in kernel address, rather than the Binder entity in the user process. Entities in the kernel's address is unique, has two meanings in the index will not; but the entity may come from different user process, and the entity in the different users in the process of address may be coincidence, not for indexing. Driven by the red black tree is referenced in a process to quickly find a corresponding Binder entities (an entity established within a process only a reference).

· Reference number. Reference number is driven as a reference distribution of a 32 bit identifier, within a process is the only, but in different processes may have the same value, and the process number of open file is very similar. Reference number will be returned to the application, Binder can be viewed as a reference to the users in the process of. In addition to 0 reference in all processes are fixed reserved for other values of SMgr, driven by the dynamic allocation. Send Binder packet, the application will reference number in the target.handle domain structure of binder_transaction_data indicates that the packet's destination Binder. Drive according to the reference number to find binder_ref structure referenced in a red black tree, then know that the target Binder entity's process and other related information through its node domain, realize the routing packet.

6 Binder memory mapping and a receiving buffer management

Put aside the Binder, consider the traditional IPC method, how the data is from the sender to the receiver? Typically, the sender will be ready for the data stored in the buffer, call the API into the kernel through system calls. The kernel service program in the memory kernel space allocation, data from the sender buffer is copied into a kernel buffer. The reading of data to provide a buffer, the kernel data from the kernel buffer is copied to the receiver buffer provided in and wake up the receiving thread, to complete a data transmission. The store and forward mechanism has two defects: first is the low efficiency, need to do two copy user space kernel space: -> -> user space. The use of copy_from_user (Linux) and copy_to_user () the two cross space copy, in this process, if you use the high memory (high memory), this copy is needed to set up temporary / cancel page mapping, resulting in loss of performance. The second is to receive data cache to the recipient, the recipient can not know how big a cache is enough, can open a large space or call API to receive messages head to get the message body size, to open the appropriate space to receive the message body. Two approaches are inadequate, not a waste of space is a waste of time.

Binder adopts a new strategy: driven by Binder is responsible for the management of data receiving cache. We note that the Binder driver to implement the MMAP () system call, which is special for character device, because the MMAP () is often used in file system has the physical storage media such as Binder, but no physical medium for communication, pure character device need not support (MMAP). The Binder driver is certainly not to do mapping on the physical media and user space, but to create a buffer space data reception. Look at how to use MMAP ():

fd = open("/dev/binder", O_RDWR);


This Binder receiver has a size of a receiving buffer MAP_SIZE. MMAP () returns the address of the memory mapping in user space, but this space is managed by the driver, the user need not can not directly access (mapping type is PROT_READ, read-only mapping).

Mapping a receiving buffer good can be done after the cache pool receive and store data. Before that, the receiving structure of data packets for the binder_transaction_data, but this is only the message header, payload real is pointed to by data.buffer memory. This piece of memory does not require the recipient, it is MMAP (from) the cache mapping. Copy from a sender to receiver in data, driving will be based on the size of sending data packets, using the best matching algorithm to find a good size piece of space from the buffer pool, to send data from the cache copy. Note that, for binder_transaction_data structure itself as well as in Table 4 all messages in the memory space or by the recipient, but the data size is fixed, the number is not much, won't cause inconvenience to the receiver. Mapping cache pool should be large enough to interact, because the thread pool may simultaneously process multiple concurrent, each interaction need to obtain the objective storage area from the buffer pool, once the cache pool depletion will lead to unintended consequences.

A distribution must be released. The receiver in the processed data package, will inform the drive data.buffer release the memory pointed to by the district. As already mentioned in the introduction of Binder protocol, this is done by the command BC_FREE_BUFFER.

Through the above introduction can see, driving for recipient sharing the most tedious task: allocation / deallocation of unequal size, effective load buffer is difficult to predict, and the receiver only needs to provide the cache to store the size is fixed, the message header to the maximum space can be predicted. In efficiency, because MMAP () the allocated memory is mapped in the user space, the overall effect is equivalent to the payload data to do the direct data once from the sender to the recipient user space to user space kernel buffer copy, this step is omitted, a performance boost times. The way to raise a point, Linux kernel does not actually function from a user space to another user space direct copy, need to use copy_from_user () copy to kernel space, then copy_to_user () copy to another user space. Copy to user space to user space, (MMAP) the allocated memory in addition to mapping into the receiver process, also mapped into kernel space. So call copy_from_user () to copy the data into the kernel space is equivalent to copy into the user space, this is Binder only one copy of the ‘ the secret’.

The 7 Binder receiving thread management

Binder communication is communication between threads in different processes. If process S is Server side, provides the Binder entity, thread T1 from Client process in C1 through Binder references to process S send request. S in order to start the thread T2 to handle the request, and the thread T1 in the receive data back to the waiting state. T2 processed the request will be processed results are returned to the T1, T1 was awakened by the processing results. In this process, T2 as T1 agent in the process in S, representing the T1 long missions, and to the T1 feeling is like travel to the S in the implementation of a section of code is returned to C1. In order to make the crossing more real, driving will be some property is assigned to T1 T2, especially the T1 priority nice, so that T2 will use time and T1 similar to complete the task. A lot of data will use ‘ thread migration ’ to describe this phenomenon, misleading. One thread is simply not possible to jump between processes, and T2 addition and T1 priority, other have nothing in common, including identity, open the file, the stack size, signal processing, such as private data.

For the Server process S, there may be many Client at the same time request, in order to improve the efficiency of often open the thread pool concurrency received requests. How to use the thread pool implementation of concurrent processing? This is related to the specific mechanism of IPC. Take socket for example, the Server end of the socket is set to a listening mode, a connection request a special thread using the socket listener from Client, which is blocked in accept (). The socket like a raw egg chicken, upon receiving the request will be from Client to lay an egg to create new socket – and from the accept () Returns. Listener thread from the thread pool to start a worker thread and just under the egg to the thread. The subsequent business processing by the thread finishes and through this single with Client system.

But for Binder, neither listening mode does not lay eggs, how to manage the thread pool? A simple approach is, regardless of the consequence, first create a heap of threads, each thread command to read Binder BINDER_WRITE_READ. The thread will block the settings for the Binder in the drive of the waiting queue, once the data from the Client drive from the queue in the wake of a thread to handle. It is simple and intuitive, saves the thread pool, but began to create a stack of thread a waste of resources. So Binder protocol introduces special commands or information to help the user management thread pool, including:






First of all to the thread pool managed to know how big the application pool, through the BINDER_SET_MAX_THREADS tell driver can create up to several threads. After each thread in the creation, the main loop is entered, respectively, using BC_REGISTER_LOOP, to withdraw from the main circulating BC_ENTER_LOOP, BC_EXIT_LOOP told the driver to drive, collect and record the current state of the thread pool. Whenever the driver received the packet back to read the Binder thread, have to check is it right? There is no idle thread. If it is, but not beyond the thread pool thread count the maximum number of threads in the current, will read data packet back then appends a BR_SPAWN_LOOPER message, tell the user thread is not enough, please restart some, otherwise the next request may not be timely response. The new thread start again through the BC_xxx_LOOP to inform the driver update state. As long as the thread is not exhausted, there is always the idle threads waiting on standby at any time in the queue, the timely processing of requests.

A worker thread startup, Binder drive has also made a small optimization. When the process of P1 thread T1 requests to process P2 transmission, drive will check whether the thread T1 is also dealing with the P2 from a thread requested but not completed (no reply). This typically occurs in two processes have Binder entity and each of the hair request. If the driver found such a thread in a process in P2, such as T2, this will require T2 to handle the T1 request. Because the T2 and sends T1 request has not yet been return packets, indicating that T2 would (or will) obstruction in reading return package state. This allows T2 to do something, rather than waiting idle. But if the T2 is not thread pool threads can also share the work for the thread pool thread pool, reduce the use rate.

8 data packet receiving queue and queue management (thread)

Receiving usually data transmission terminal has two queues: packet reception queue and queue (thread), to ease the contradiction between supply and demand. When purchasing the supermarket (packets) too much, the goods will be packed in the warehouse; shoppers (thread) too much, will be waiting in line at the checkout, the principles are the same. In the drive, the receiving queue each process has a global, also known as the to-do queue, not to store thread specific data packet; accordingly there is a global queue, all waiting to receive queue data thread in the queue from the global queue. Each thread has its own private to-do queue, stored data packets sent to the threads; each thread has its selfishness corresponding waiting queue, specifically for the thread waiting to receive your to-do queue data. Although the name of the queue, in fact, thread private wait up to only one thread in the queue, that is its own.

Due to send no special markers, drive how to judge which packets the into the global to-do queue, which data packets sent to a particular thread the to-do queue? Here are two rules. Request data rule 1:Client to Server packets are submitted to the Server process global to-do queue. But there is a special case, is the section talked about Binder on thread startup optimization. After optimization, the request from the T1 is not submitted to the P2 global to-do queue, but into the T2 private to-do queue. Rule 2: synchronous request return packet (sent by the BC_REPLY package) are sent to the request thread private to-do queue. As shown in the example above, if the process P1 thread T1 to process P2 thread T2 is synchronous request, then T2 returns the data packet will be sent to the T1 private to-do queue and not committed to the global P1 to-do queue.

The packet into the receiving queue unspoken rule has also decided the thread enters the waiting queue unspoken rule, namely a thread as long as not to receive a return packet should wait for the new task in the queue at the global, otherwise it should be in their private waiting in the queue waiting for Server to return data. Or the example above, T1 sends a synchronization request to T2 must wait queue in which private, rather than in the P1 global waiting queue, otherwise it will not return to T2 data packets.

The unspoken rule is driving restrictions on Binder communication both applied, reflected in the application's synchronization request thread consistency in the interactive process: 1) Client end, waiting for the return of the thread package must be send request thread, but not by sending a thread request package, another thread waiting to receive package, otherwise it will not receive the return package; 2) Server end, sending back data packets corresponding threads must be thread receives the request packet, the packet will not be delivered or returned to send the request thread. This is because the return data packet's destination Binder is not a user specified, but driving record in the requested thread data packet, if send a return packet is not received the request packet thread thread drive will never know return packets will be sent to where.

Then discuss the Binder driver is how to submit the synchronous interaction and asynchronous interaction. As we know, the difference between synchronous and asynchronous interaction interaction is synchronous interaction request end (client) in request data packet need to wait for the response end (Server) returns the data packet, and sends the asynchronous interactive end sends request packet after the interaction is the end. For the two kinds of interaction of the request data packet, the driver can regardless of the consequence, completely lost to the receiver of the to-do queue in one treatment. But the driver did not, But the current limit of asynchronous interaction, It is a synchronous interaction., Specific approach is: for a Binder entity, As long as there is an asynchronous interaction not processed, For example, being lined up a thread processing or in any one of the to-do queue, So next to the entity of the asynchronous interactive package will no longer be delivered to the to-do queue, But blocking asynchronous open for the entity in the driven interaction the receiving queue (async_todo domain Binder node)., But this time synchronous interaction is still not restricted directly into the to-do queue for processing. Until the asynchronous interactive processing is finished the next asynchronous interaction can from asynchronous interaction into the to-do queue queue. This is done because synchronous interaction request end need to wait for the return package, response speed must be processed quickly so as not to affect the request side, while the asynchronous interaction belongs to ‘ after launching &rsquo, a little delay; don't block other threads. So will many asynchronous interaction with specialized buffered queue, so as not to burst a lot of asynchronous interaction occupy the processing capability of the Server end of the thread pool threads or exhausted, thereby blocking synchronous interaction.

9 summary

Binder use Client-Server communication, good safety, simple and efficient, coupled with its object oriented design, unique receiving cache management and thread pool management mode, become the mainstay of Android interprocess communication.


But it did not realize, CSDN layout is too bad, the form is too wide words can not fully, directly turn the

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Jenny at December 15, 2013 - 3:52 PM