Introduction (Summary)

Yi, Yi, Yi.

I had planned to finish binder at the end of August and record what I had learned with an article, but:

  • Read read, feel the lack of a can connect the wholebinderThe mainline, so decided to addtakeaway
  • Writing, suddenly found that a fit, so split into three
    • takeawayandIntroduction of binderFor a
    • The use of binder is a
    • Principle of binderFor a large piece (85KB….)
      • Digging can not be divided into: principle
      • The excavation can not be divided into: driving

Simple start

Let’s start with a brief overview of the concepts involved in binder architecture:

  • The client process: The process that initiates the remote method call
  • Service process: The process that the real service runs on
  • Binder drive:Binder communicationIs the core through which remote calls are processed and passed
  • servicemanager: a managementBinder serviceThe process of

A simple version of the process called across processes:

  • The client processSend the call informationdriveAnd wait fordriveReturn messages
  • driveProcess the call information and notifyService process
  • Service processreceiveddriveTo start execution based on the call information
  • Service processCompletion of execution, noticedrive
  • driveTo receiveService processFor simple data processing, notificationThe client processRead the data
  • The client processReceived notification, readdriveReturned data

Two nouns that need to be easily distinguished:

  • To implement aBinder service:BinderTo implement one of my ownIPCService (how to useBinder)
  • BinderThe implementation of the:BinderThe realization of the principle, involving learningBinder drivePart of the

Binder’s questions

The first question is, how do you determine which service to call if the client process wants to call the function of the server process? How do you know which function to call?

Let’s start with a few points:

  • inBinder serviceAndroid defines some template classes for the use of
    • inService processIf you write a service that you want to supportBinder Remote call, you have to write it the way I do
      • forC++Layer, to be implemented manuallyBn...,Bp...Such as class (do not know how to write? There are so many IPC support services in Android, learn from them. The good news is there’s aHIDLSimplifies development)
      • forJavaLayer, becauseAIDLThere will be automatic script generationBn...,Bp...Class, just implement the business logic in the callback
    • And forThe client processIf you want to complete a remote call, you must do it at programming time
      • forC++Layer, to get the service that you want to callBp.....Type information is ok, it’s written in during the programming phaseThe client process
      • forJavaLayer, copy what you want to callService processIn theAIDLinThe client process, recompile to get the corresponding service interface class
    • forThe client processThere is another way to do remote calls, which is the various methods we use. Manager
      • andc++Layer and theAIDLSimilarly, we also pass for the client process. ManagerClass interface to complete the call
  • Imagine aFree communication stateIt should be: Give me aBinder driveI can live with that. Why integrate yoursService interface classAh, so many rules. I want to call whichIPCService, directly throughdriveJust send it to him.
    • I am not thorough, just an example:
      • How do I get the service object to invoke? Background service thousands of millions, even if do not get, also have to inform this service
      • How do you pass which method to call?
      • How many ways are there to get remote services?
      • In addition to completing business logic, a server process is written to work independently and to drive communication.
    • These questions,AndroidWith self-designed Binder relatedTemplate classHave solved the
      • Don’t know where the service object is?
        • Then inThe client processPlus I designed itBp...Class with predefined interfacesasInterface, directly conversion is good
      • Don’t know what methods you can call remotely?
        • All give youBp...Class, what elseThe bicycle?
      • Use andBinder driveCommunication?
        • Through what letter ah, wrapped up, call method directly on the line
  • Answer hereFirst question:
    • In programming, we call what needs to be called according to requirementsIPCThe service ofBp...Class party to our client process
      • Bp...Class aasInterfaceMethod, can be converted into what we need through this methodProxy objects
    • Binder will specify the method to callBp...andBn...The template class defines the function number to call
      • The client process is readyBp...Class, also have the call function number

Second question, when did the service we wrote start?

Generally speaking, our service should start listening for messages from the outside world when the process starts, otherwise it will miss messages.

Binder did the same thing:

  • forService processfor
    • Will be inProcess startedWhen performingjoinThreadPool
      • This function is going to enterThe while loopreadBinder driveThe data of
  • forThe client processfor
    • Is executed when a remote call is senttransactWhen the function
      • This function sends the call data toBinder driveThen, it continues to read and view the returned data

Why doesn’t the Servicemanager get a lot of space?

First of all this is not a problem, hahaha!

  • servicemanagerisAndroidUsed to manage registrationBinder serviceOursgetServiceMost likely I’m looking for it. (Have not read the source code, do not believe)
  • servicemanagerInstead of following the template defined by Android, we implemented a simple version
  • servicemanagerIt starts when Android starts, and this part is ininit.rcIn the configuration
  • There is noservicemanagerDoes not affect our understanding of learningbinderOverall process and structure
  • There are theservicemanagerCan deepen our understanding ofbinderThe understanding of the

End of the introduction

The Binder introduction section describes some knowledge points simply. See the text for details

  • The source code in the book isThe Android 5.0, butbinderThis part from9.0Not much has changed on the top, just a few morelogprint
  • The code’s strong vitality is exactly what we’re after, hahaha
  • I was going to say that in the introductionA copy ofForget it and leave it in the text

Binder’s course was two weeks behind schedule…

Fortunately, really drop can learn a lot of things, the following is the text, not proficient, please carefully read 😌


Introduction of Binder

Binder is an Android – specific way of communicating between processes. Android Binder, formerly Known as OpenBinder, was first developed by Dianne Hackborn for PalmOS, who later joined Google, Android Binder was developed based on OpenBinder

Binder incorporates the concept of remote procedure call (RPC) compared to traditional IPC mechanisms, and this remote call is not a traditional procedure oriented remote call, but an object-oriented remote call.

Developed from Unix, IPC mechanism can only provide a relatively primitive inter-process communication means, communication between the two sides must deal with thread synchronization, memory management and other complex issues, not only a large workload, but also prone to error.

In addition to sockets and anonymous pipes, traditional IPC, such as named pipes, semaphores, message queues, etc. have been removed from Android.

Compared with other IPC, Socket is a more mature means of communication, synchronization control is also easy to achieve. Socket is good for network communication, but not very efficient for interprocess communication.

The Android architecture has always wanted to blur the concept of processes and replace it with the concept of components. Applications do not need to be concerned with where components are stored, which process they are running in, the life cycle, etc. Component functionality is available anytime, anywhere with a Binder object. Binder acts as a web that holds together the components of an entire system, across processes and threads.

Binder is powerful and complex. But when we use it, it is a very easy thing, no need to consider thread synchronization, memory allocation, etc. All of this complexity is done with the Binder framework.

Because of this, Android services are built with Binder. Android has dozens of services that no other embedded platform has.

Android uses shared memory to transfer data between processes, so that data can be copied from one process to another only once (common IPC requires two steps, from user process to kernel, and then from kernel to server process), greatly improving data transmission efficiency.

Binder calls pass the process’S EUID to the server. Therefore, the server can check the calling process’s permission to decide whether to allow it to use the called service.

Binder is the IPC mechanism for Android. To deepen the understanding, the article has a surprise

BinderObject definitions

Binder objects are defined as follows for ease of understanding:

  • Binder entity object:Binder entity objectisBinderService provider. An offerBinderThe class of the service must be inheritedBBinderClass. Therefore, sometimes to emphasize the type of the object, also usedBBinder objectTo take the place ofBinder entity object.
  • Binder reference object:Binder reference objectisBinder entity objectOn behalf of the client process, the type of each reference object isBpBinderClass. You can also use namesBpBinder objectTo take the place ofBinder reference object.
  • Binder Proxy object:Binder Proxy objectAlso known asBinder Interface object, it mainly provides interface services for the client’s upper-layer applications fromIInterfaceClass derived, which implementsBinderThe functional interface of the service, of course, is just an empty shell for tuning. throughBinder Proxy objectApplications can use remote objects as if they were local objectsBinder entity objectServices provided.
  • IBinder object:BBinderandBpBinderClass fromIBinderObject inherited from. In many cases, there is no need to distinguishBinder entity objectandBinder reference objectThis is a deliberate useIBinder objectTo call them all together.

Binder interface objects work with applications. The advantage of separating Binder interface objects from Binder reference objects is that Binder interface objects can have many instances, but they all contain the same Binder reference object, which facilitates the use of the user layer.

The diagram is as follows:

Binder interface objects can be used directly with Binder interface objects, but they are not compatible. The separation of Binder reference objects and Binder interface objects on the client side enables Android to provide Binder services to both the Java layer and Native layer in a single architecture. After isolation, the Binder layer does not need to care about the implementation details of the upper layer and only needs to interact with Binder entity objects and Binder reference objects.

BinderThe architecture of the

The participants of Binder Communications consist of four parts:

  • Binder drive:BinderThe core of various implementationsBinderThe underlying operation of.
  • ServiceManager: provideBinder entity objectThe name of theBinder reference objectConversion service of
  • The service side:BinderService provider
  • The client:BinderConsumer of the Service

The diagram is as follows:

Binder driver simple explanation:

  • Binder driveBelong toBinderThe core of the architecture is through standard interfaces within the file system, such asopen,ioctl,mmapEtc., providing services to the user layer.
  • The application andBinder driveBetween the data throughioctlInterface to complete and is not usedreadandwriteSystem call. useioctlThe advantage is that a system call can complete the two-way data exchange between the user system and the driver, not only simplifies the control logic, but also improves the transmission efficiency.
  • Binder driveThe main function of theBinderCommunication channel, maintenanceBinderObject reference count, transform in transitBinder entity objectandBinder reference objectAnd manage the data cache.

ServiceManager:

  • ServiceManagerIs a daemon that providesBinderThe query function of a service that returns a reference to the service being queried.
  • For aBinderA service will usually have a unique string identifier as long as it identifies toServiceManagerBy registering the identity, the application can be acquired by the identityBinderThe reference object of the service.
    • ServiceManagerIs a separate process for others to obtainBinderFor the process of service, the first task is to obtainServiceManager.
    • ServiceManagerAlso through the Binder framework to provide services, it feels like the situation of chicken born chicken eggs
    • To ensure that other processes can obtainServiceManagerAndroid registers bindings by defaultServiceManager:Binder reference objectThe core data is oneBinder entity objectIs a value assigned within the driver.Binder frameworkIt’s hard and fast0On behalf ofServiceManager. This allows the user process to use parameters0You can construct it directlyServiceManagertheBinder reference object.
  • Why searchBinderService functions are not placed directlyBinder driveHow about in?
    • Android is a security management requirement that does not allow any process to registerBinderService,Although any process can be createdBinderservice, but onlyThe root processorThe system processBefore they can have unlimited access toServiceManagerRegistration services.
    • ServiceManagerThere is a table specifying the user ids of the processes that can register the service, and the names of the services that can register.

Binder services can be divided into two types: real name services and anonymous services. Except for the fact that the real name service can be queried through the ServiceManager, there is no other difference between development and use.

Binder services for common application development are anonymous services. For anonymous services that are not available through ServiceManager, how do clients obtain Binder reference objects?

  • First of all,Anonymous Binder ServicesThe transmission must be based on established Binder communication connections, i.e. based on real name registrationBinder
  • ServerwillAnonymous Binder objectswriteParcelAnd then throughioctlandBinder driveThe communication,Bidner driveIncoming objects are checked.
  • If you find incomingtypeisbinderIn the current process (ServerThe correspondingproc) to see if the node exists
    • If not, use the incoming oneAnonymous Binder objectsIn user spacePointer to theandcookie(usuallyBBinderConstruct a new node, and then getAnonymous Binder objectsReferences, stored intransaction_dataWaiting in theClientTo obtain.
  • ClientTo get thisAnonymous BinderThrough this reference to theServerThe entity in the.

These are the information collected by Anonymous Binder for the time being, which can be supplemented after learning

componentServiceAnd anonymous Binder services

Android component Services contain a way to start Java anonymous Binder services, which we’ll take a quick look at

  • First, you need to apply the callbindServiceMethod emits aIntent
  • FrameworkAccording to theIntentFind the corresponding componentServiceAnd start itServiceIn theAnonymous Binder ServicesIt will be created at the same time.
  • Then,FrameworkIt will be servedIBinderObject throughConnectivityManagerThe callback method ofonServiceConnected()Pass back to the application
  • So we have our applicationAnonymous Binder ServicesReference object to

Here’s AndroidFrameworkwithIntentInstead of aBinder serviceThe name to look up the corresponding service, and also bear itServiceManagerThe work of parsingIntentAnd returns a reference object to the service. As shown in figure:

The Android Framework does not use new techniques to pass Binder objects because the ActivityManagerService that plays this role in the Framework is itself a Binder service, Ultimately, IBinder objects are passed between the server and client through the Binder framework.

The level of the Binder

In terms of code implementation, Binde’s designed classes can be divided into four levels, as shown in the figure:

  • The topmost layer is located atFrameworkBinder service classes and their interface classes. This layer has many classes, such as:ActivityManagerService,WindowManagerService,PackageManagerServiceThey provide a variety of services for applications.
  • The second layer is for the top layerService classes and interface classesProvides the basis for the development of IBinder, BBinder, BpBinder, etc.
  • The third layer is sumBinder driveThe interaction ofIPCThreadStateandProcessStateclass
  • The bottom isBinder drive.

From the diagram, libbinder is split into two layers for the following reasons:

  • Layer 1 and Layer 2 are closely linked, with various Binder classes in layer 2 supporting the development of service and proxy classes
  • But the third tierIPCThreadIt’s very coupled to the fourth level drive

This is where the Binder architecture has been criticized for being too coupling between the driver and application layers, which violates the principles of Linux driver design. As a result, mainstream Linux has been reluctant to embrace Binder.