Binder之Java层Binder

Java Binder要想和Native Binder进行通信,需要通过JNI


JNI注册

Java Binder要想和Native Binder进行通信,需要通过JNI,JNI各种函数是在Zygote进程启动过程中注册的

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
//frameworks/base/core/jni/AndroidRuntime.cpp
void AndroidRuntime::start(){
......
/* start the virtual machine */
//startVm启动java虚拟机(创建虚拟机)
if (startVm(&mJavaVM, &env, zygote) != 0) {
return;
}

//执行onVmCreated方法,空方法
onVmCreated(env);

//Register android functions.
if (startReg(env) < 0) {
ALOGE("Unable to register all android natives\n");
return;
}
......
}

/*
* Register android native functions with the VM.
*/

int AndroidRuntime::startReg(JNIEnv* env){
......
//register_jni_procs就是循环调用gRegJNI数组内的函数
if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) < 0) {
env->PopLocalFrame(NULL);
return -1;
}
......
return 0;
}

void AndroidRuntime::onVmCreated(){}

//100多个函数
//REG_JNI是一个宏定义
static const RegJNIRec gRegJNI[] = {
REG_JNI(register_com_android_internal_os_RuntimeInit),
REG_JNI(register_com_android_internal_os_ZygoteInit_nativeZygoteInit),
......
//负责Java Binder和Native Binder通信的函数
REG_JNI(register_android_os_Binder),
......
}

//frameworks/base/core/jni/android_util_Binder.cpp
int register_android_os_Binder(JNIEnv* env){
if (int_register_android_os_Binder(env) < 0)
return -1;
if (int_register_android_os_BinderInternal(env) < 0)
return -1;
if (int_register_android_os_BinderProxy(env) < 0)
return -1;
......
return 0;
}
  1. 注册Binder类
  2. 注册BinderInternal类
  3. 注册BinderProxy类

Binder类的注册(BinderInternal类的注册 类似)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
static const JNINativeMethod gBinderMethods[] = {
/* name, signature, funcPtr */
//Binder的Native方法(Java层)与JNI层函数的对应关系
{ "getCallingPid", "()I", (void*)android_os_Binder_getCallingPid },
{ "getCallingUid", "()I", (void*)android_os_Binder_getCallingUid },
......
}

const char* const kBinderPathName = "android/os/Binder";
static int int_register_android_os_Binder(JNIEnv* env){

jclass clazz = FindClassOrDie(env, kBinderPathName);
gBinderOffsets.mClass = MakeGlobalRefOrDie(env, clazz);
gBinderOffsets.mExecTransact = GetMethodIDOrDie(env, clazz, "execTransact",
"(IJJI)Z");
gBinderOffsets.mObject = GetFieldIDOrDie(env, clazz, "mObject", "J");

//注册gBinderMethods中定义的函数
//其中gBinderMethods 是JNINativeMethod类型的数组
//里面存储的是(Java层)Binder的Native方法与JNI层函数的对应关系。
return RegisterMethodsOrDie(
env, kBinderPathName,
gBinderMethods, NELEM(gBinderMethods));
}

//使用gBinderOffsets结构体,为了提升效率
static struct bindernative_offsets_t{
jclass mClass;
jmethodID mExecTransact;
jfieldID mObject;
} gBinderOffsets;

AMS注册

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
//frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {new SystemServer().run();}
private void run() {
……
startBootstrapServices();
……
}
private void startBootstrapServices() {
……
//844行
mActivityManagerService.setSystemProcess();
……
}

//frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

//AMS继承自Bidner
public class ActivityManagerService extends IActivityManager.Stub

public void setSystemProcess() {
……
//这个this就是AMS
ServiceManager.addService(Context.ACTIVITY_SERVICE, this, ……);
……
}

//frameworks/base/core/java/android/os/ServiceManager.java
public static void addService(String name, IBinder service) {
addService(name, service, false, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);
}

public static void addService(String name, IBinder service, boolean allowIsolated) {
addService(name, service, allowIsolated, IServiceManager.DUMP_FLAG_PRIORITY_DEFAULT);
}

public static void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority) {
try {
getIServiceManager().addService(name, service, allowIsolated, dumpPriority);
} catch (RemoteException e) {
Log.e(TAG, "error in addService", e);
}
}

private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {return sServiceManager;}
// Find the service manager
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));
return sServiceManager;
}

先处理getIServiceManager中的逻辑:

  • BinderInternal.getContextObject()
  • Binder.allowBlocking()
  • ServiceManagerNative.asInterface()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//frameworks/base/core/java/com/android/internal/os/BinderInternal.java
public static final native IBinder getContextObject();


//frameworks/base/core/jni/android_util_Binder.cpp
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz){
//这里返回一个 BpBinder
sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
return javaObjectForIBinder(env, b);
}

sp<IBinder> ProcessState::getContextObject(const sp<IBinder>&){
return getStrongProxyForHandle(0);
}

sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle){
……
if (b == nullptr || !e->refs->attemptIncWeak(this)) {
……
b = BpBinder::create(handle);
……
}
……
}

得出ProcessState.getContextObject()返回BpBinder对象

javaObjectForIBinder(env, b)返回一个BinderProxy对象,其中mObject(BinderProxy成员变量)记录了BpBinder对象

得出BinderInternal.getContextObject()最终为BinderProxy对象(Java Binder的客户端的代表)

Binder.allowBlocking的作用是将BinderProxy的sWarnOnBlocking值置为false

接着分析 ServiceManagerNative.asInterface()
1
2
3
4
5
6
7
8
9
10
11
//frameworks/base/core/java/android/os/ServiceManager.java
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(BinderInternal.getContextObject()));

//frameworks/base/core/java/android/os/ServiceManagerNative.java
static public IServiceManager asInterface(IBinder obj){
if (obj == null) {return null;}
IServiceManager in = (IServiceManager)obj.queryLocalInterface(descriptor);
if (in != null) {return in;}
return new ServiceManagerProxy(obj);
}

可以得出:
sServiceManager(getIServiceManager())是ServiceManagerProxy对象,其中有addService方法

小结:

1
2
3
4
Jave Binder 客户端的代表:BinderProxy
Native Binder 客户端的代表:BpBinder
Java:ServiceManagerProxy通过BinderProxy来实现通信
Native:BpServiceManager通过BpBinder来实现通信
接着分析addService()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
//frameworks/base/core/java/android/os/ServiceManagerNative.java#ServiceManagerProxy
class ServiceManagerProxy implements IServiceManager {
public ServiceManagerProxy(IBinder remote) {
//remote为BinderProxy
mRemote = remote;
}

public void addService(String name, IBinder service, boolean allowIsolated, int dumpPriority)throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
//将数据写入到Parcel类型的对象data中
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name);
//这里service是AMS
data.writeStrongBinder(service);
data.writeInt(allowIsolated ? 1 : 0);
data.writeInt(dumpPriority);
//mRemote是BinderProxy对象
//BinderProxy.transact是native函数
mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
reply.recycle();
data.recycle();
}
}

//frameworks/base/core/jni/android_util_Binder.cpp
static jboolean android_os_BinderProxy_transact(){
......
//将Java层的Parcel对象转化成为Native层的Parcel对象
Parcel* data = parcelForJavaObject(env, dataObj);
......
//将Java层的Parcel对象转化成为Native层的Parcel对象
Parcel* reply = parcelForJavaObject(env, replyObj);
......
//获取保存在mObject内的BpBinder对象
IBinder* target = getBPNativeData(env, obj)->mObject.get();
......
//最终调用BpBinder的transact方法
status_t err = target->transact(code, *data, reply, flags);
}

可以看出进行了 Framework -> JNI -> Native 这个过程

接下来可参考【Binder之系统服务注册】一文,执行ioctl,像Binder驱动发送数据

分析 data.writeStrongBinder(service);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
//frameworks/base/core/java/android/os/Parcel.java
public final void writeStrongBinder(IBinder val) {
nativeWriteStrongBinder(mNativePtr, val);
}

//frameworks/base/core/jni/android_os_Parcel.cpp
static void android_os_Parcel_writeStrongBinder(...){
......
const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env,object));
......
}

//frameworks/base/core/jni/android_util_Binder.cpp
sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj){
if (obj == NULL) return NULL;

// Instance of Binder?
if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
env->GetLongField(obj, gBinderOffsets.mObject);
return jbh->get(env, obj);
//查看源码可以看出jbh->get这里返回JavaBBinder
}

// Instance of BinderProxy?
if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
return getBPNativeData(env, obj)->mObject;
}

ALOGW("ibinderForJavaObject: %p is not a Binder object", obj);
return NULL;
}

得出:data.writeStrongBinder(service)
即 data.writeStrongBinder(JavaBBinder(Binder))
传入的不是AMS本身,而是JavaBBinder

JavaBBinder
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
//frameworks/base/core/jni/android_util_Binder.cpp#JavaBBinderHolder#JavaBBinder
class JavaBBinder : public BBinder{//可以看出继承BBinder
//接受Binder驱动的响应
virtual status_t onTransact(){
......
//调用java层Binder的execTransact函数
//这里结合【int_register_android_os_Binder】Binder注册来看
//mObject就是Java层 Binder对象
jboolean res = env->CallBooleanMethod(mObject,gBinderOffsets.mExecTransact,code, reinterpret_cast<jlong>(&data), reinterpret_cast<jlong>(reply),flags);
......
}
}

//frameworks/base/core/java/android/os/Binder.java
private boolean execTransact(int code, long dataObj, long replyObj, int flags) {
......
execTransactInternal(code, dataObj, replyObj, flags, callingUid);
......
}

private boolean execTransactInternal(int code, long dataObj, long replyObj, int flags, int callingUid){
......
res = onTransact(code, data, reply, flags);
......
}

//由于AMS实现了onTransact函数,逻辑回到AMS的onTransact方法