Detailed explanation of Android system Binder

 Android system startup

1, "Introduction to the Android System Startup Process"

2, "Android init process startup process"

3. "Android zygote process startup process"

4. "Android SystemServer Process Startup Process"

5. "Android launcher startup process"

6. "Detailed Explanation of Android Activity Startup Process"

Android System Development Preparation

1, "Android Source Code Download and Compilation"

2. "Android 11 source code compilation and pixel3 flashing"

3. "Android Framework Code IDE Loading and Debugging"

Android System Development Practice

1. "Android Setting Default Input Method"

2, "android framework prefabricated APK application"

3. "Detailed Explanation of Restricting Apps from Starting at the Android System Level"

4. "Android compiles the framework module separately and pushes it"

5. "Android Framework Development System Problem Analysis"

Android System Development Core Knowledge Reserve

1, "Android Compilation System - envsetup and lunch code articles"

2. "Android Compilation System - Concept"

3. "Detailed Explanation of Android Log System"

4. "Android System Handler Detailed Explanation"

5. "Android System Binder Detailed Explanation"

6. "Detailed Explanation of the Relationship between Activity, View and Window in Android"

7. "Detailed Explanation of the Android View Drawing Process"

8. "Detailed Explanation of Android Reading System Attributes"

9. "Detailed Explanation of Android Window Management Mechanism"

10. "Acquaintance with Android System"

11. "The communication method of AMS process in android notifying Zygote process fork new process"

Detailed explanation of Android core functions

1. "Android application market click to download APK installation details"

2, "Android gesture navigation (swipe from bottom to top to enter the multitasking page)"

3. "Android Gesture Analysis (Swipe left to right on the application interface to exit the application)"

4. "Detailed Explanation of Android Application Installation Process"

5, "android11 ​​installation application triggers desktop icon refresh process"

6. "Detailed Explanation of Android System Multitasking Recents"

7. "Android System Navigation Bar View Analysis"

———————————————————————————————————————————

Table of contents

1. Background introduction

1.1 Introduction

1.2 Core Concepts

Two, Binder principle

2.1 Process space

2.2 Binder one copy

2.3 Use of Binder

2.4 Binder communication process

Three, actual combat


1. Background introduction

1.1 Introduction

        The Binder mechanism is a cross-process communication mechanism provided by the Android system. It uses technologies such as proxy objects, shared memory, and serialization to realize the functions of inter-process communication and remote invocation. It allows data transfer and method calls between different processes, achieving decoupling between processes. In the Android system, Binder is widely used in communication between various components, such as Activity and Service, Service and Service, application and system services, etc.

1.2 Core Concepts

  1. Driver layer: Binder exists in the Linux kernel as a device driver. When the application communicates with the Binder object, it is actually interacting with the Binder driver. The Binder driver is responsible for managing Binder objects, transferring data, and context switching between processes. Device file nodes are usually/dev/binder。
  2. User space library: Binder provides a set of C++ library and Java library to facilitate the use of user space applications. These libraries include tools for serializing/deserializing data, tools for managing the reference count of Binder objects, and proxy and stub objects when calling methods between processes. At the Java layer, AIDL (Android Interface Definition Language) is usually used to define cross-process interfaces.

  3. Proxy and stub: Binder uses proxy (Proxy) and stub (Stub) objects to implement inter-process method calls. When a process calls a method in another process, it converts the method call into a Binder transaction through the proxy object. Then, this transaction will be sent to the receiving process, and the stub object will parse and execute the corresponding method. Finally, the stub object returns the result to the proxy object, completing the entire cross-process call.

  4. Serialization and deserialization: When transferring data between processes, the data needs to be serialized into a byte stream for transmission between different processes. During the receiving process, the data is deserialized back to its original format. Binder provides a set of serialization and deserialization tools (such as the Parcel class) for transferring data between processes.

  5. Reference counting and death notification: The Binder mechanism manages the life cycle of Binder objects through reference counting. When a process obtains a Binder object reference from another process, the reference count increases. When the reference count is reduced to zero, the Binder object will be destroyed. In addition, Binder also supports the death notification mechanism, which allows a process to monitor the Binder object death event of another process.


Two, Binder principle

2.1 Process space

        Process space division: user space (User Space) - kernel space (Kernel Space)

1. Each Android process can only run in the virtual address space owned by its own process.
2. For user space, different processes cannot be shared, but the kernel space can be shared. 3. The
communication between the Client process and the Server process is precisely the use of the shared kernel memory space between processes to complete the underlying communication work
. , Client and Server processes often use methods such as ioctl to interact with drivers in the kernel space.

2.2 Binder one copy

        How do user processes in the Android system communicate through the kernel module (Binder driver)? Of course, it is not the previous copy of data from the sender process to the kernel buffer, and then copy the data from the kernel buffer to the receiver process. Instead via memory mapping:

    1. In simple terms, memory mapping is to map a memory area of ​​user space to kernel space. After the mapping relationship is established, the modification of this memory area by the user can be directly reflected in the kernel space 2. Otherwise, the modification of this area by the kernel
    space It can also directly respond to user space. Memory mapping can reduce the number of data copies and realize efficient interaction between user space and kernel space

        Binder IPC is implemented based on memory mapping (mmap), but mmap is usually used on file systems with physical media, and the user area in the process cannot directly deal with physical devices. If you want to read the data on the disk to the user area of ​​the process, you need to copy it twice (disk –> kernel space –> user space), usually mmap can play a role in this scenario, through physical media and user space Create mapping between spaces, reduce the number of data copies, replace I/O reading and writing with memory reading and writing, and improve file reading efficiency.

The copy is directly copied into the kernel state and mapped to B, so what is memory mapping ,

  • The underlying principle is actually virtual memory

  • To put it simply: different virtual memory points to the same physical memory, so as to realize shared memory and shared files

 

A complete Binder IPC communication process is usually like this,

    1. The Binder driver creates a data receiving buffer in the kernel space;
    2. Then open a kernel buffer in the kernel space, establish the mapping relationship between the kernel buffer and the data receiving buffer in the kernel, and the data receiving buffer in the kernel The mapping relationship with the user space address of the receiving process;
    3. The sending process copies the data to the kernel cache area in the kernel through the system call copy_from_user(). Since there is a memory mapping between the kernel buffer area and the user space of the receiving process, it is quite Because the data is sent to the user space of the receiving process, an inter-process communication is completed.

2.3 Use of Binder

Four roles of Binder communication:

    1. Client process: the process that uses the service.
    2. Server process: a process that provides services.
    3. ServiceManager process: The function of ServiceManager is to convert the Binder name in character form into a reference to the Binder in the Client, so that the Client can obtain a reference to the Binder entity in the Server through the Binder name.
    4. Binder driver: The driver is responsible for the establishment of Binder communication between processes, the transfer of Binder between processes, the management of Binder reference counts, the transfer and interaction of data packets between processes, and a series of underlying supports.
        

        Binder communication adopts c/s architecture, including Client, Server, ServiceManager and binder driver, where ServiceManager is used to manage various services in the system.

        Server first registers a service with ServiceManager, which is actually a string. Then the Client obtains the service from the ServiceManager, and the keyword is the registered string. In this way, Client and Server can communicate. The real data flow is the binder driver that leaves the underlying Linux kernel space, but this is encapsulated, so you don’t need to care about the real binder driver, just call functions between the Client and Server to send and receive data. It is the server's onTransact function and the client's remote()->transact(TEST, data, &reply). The sent data is stored in data, and the returned data is stored in reply. Both Client and Server can send and receive data.

        The mutual communication between Client, Server and ServiceManage in the above figure is based on the Binder mechanism. Since the communication is based on the Binder mechanism, it is also a C/S architecture, and the three major steps in the figure have corresponding Client and Server ends.

    1. Register service (addService): The Server process must first register Service to ServiceManager. The process: Server is the client, and ServiceManager is the server.
    2. Get Service (getService): Before the Client process uses a Service, it must first obtain the corresponding Service from the ServiceManager. The process: Client is the client, ServiceManager is the server.
    3. Using the service: The Client establishes a communication path with the Server process where the Service is located according to the obtained Service information, and then can directly interact with the Service. The process: Client is the client, and Server is the server.

        The interaction between Client, Server, and Service Manager in the above figure is indicated by dotted lines, because they do not interact directly with each other, but all interact with the Binder driver, thereby realizing the IPC communication (Interprocess Communication) method.

        Among them, the Binder driver is located in the kernel space, and the Client, Server, and Service Manager are located in the user space.

        Binder driver and Service Manager can be regarded as the infrastructure of the Android platform, while Client and Server are the application layers of Android. Developers only need to customize the implementation of Client and Server, and use the basic platform architecture of Android to directly perform IPC communication.


        Client, Server, ServiceManager, and Binder drivers are like the relationship between the server (Server), client (Client), DNS domain name server (ServiceManager) and router (Binder driver) in the Internet.

2.4 Binder communication process

1. First, a process uses the BINDERSETCONTEXT_MGR command to register itself as a ServiceManager through the Binder driver;

2. The Server registers the Binder (Binder entity in the Server) with the ServiceManager through the driver, indicating that it can provide external services. The driver creates the entity node in the kernel and the reference of the ServiceManager to the entity for the Binder, packs the name and the newly created reference to the ServiceManager, and the ServiceManger fills it into the lookup table.

3. The Client obtains the reference to the Binder entity from the ServiceManager with the help of the Binder driver through the name, through which the communication with the Server process can be realized.
 

Three, actual combat

A simple example of a program calling system services across processes, part of the code for implementing a floating window:

	//获取WindowManager服务引用
	WindowManager wm = (WindowManager) getSystemService(getApplication().WINDOW_SERVICE);
	//布局参数layoutParams相关设置略...
	View view = LayoutInflater.from(getApplication()).inflate(R.layout.float_layout, null);
	//添加view
	wm.addView(view, layoutParams);

1. Registration service (addService): During the boot process of Android, Android will initialize various services of the system, and register these services with ServiceManager (that is, let ServiceManager manage them). This step is done automatically by the system.

2. Get service (getService): If the client wants to get a specific Service, it can directly ask the ServiceManager. The client first queries the ServiceManager to obtain a specific Service reference, usually the proxy object of the Service reference, and performs some processing operations on the data. That is, in the second line of code, the obtained wm is a reference to the WindowManager object.

3. Use the service: Send a request to the specific server through this reference, and the server will return after the execution is completed. That is, calling the addView function of WindowManager in line 6 will trigger a remote call, and the call is the addView function of WindowManager running in the systemServer process.

1. The Client calls the Server by obtaining a proxy interface of the Server.
2. There is a one-to-one correspondence between the methods defined in the proxy interface and the methods defined in the Server.
3. When the client calls a method in a proxy interface, the method of the proxy interface will pack the parameters passed by the client
into a Parcel object.
4. The proxy interface sends Parcel to the Binder Driver in the kernel.
5. The Server will read the request data in the Binder Driver, if it is sent to itself, unpack the Parcel
object, process it and return the result.
6. The entire calling process is a synchronous process, and the Client will be blocked while the Server is processing. Therefore
, the Client calling process should not be in the main thread.


——————————————————
Reference: Yawn__Original
link: https://blog.csdn.net/ly0724ok/article/details/117566381/

Guess you like

Origin blog.csdn.net/allen_xu_2012_new/article/details/131123375