0%

AndroidBinder

IServiceConnection

bindService,我们会传递一个ServiceConnection对象,这个ServiceConnection对与IServiceConnection做一个映射,系统帮我们初始化完成Service后会将我们自己写的Binder Stub(Server端)通过IServiceConnection返回给Client端

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
60
61
62
public interface IServiceConnection extends IInterface {
@UnsupportedAppUsage
void connected(ComponentName componentName, IBinder iBinder, boolean z) throws RemoteException;

public static abstract class Stub extends Binder implements IServiceConnection {

@Override // android.os.Binder
public boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
ComponentName _arg0;
if (code == 1) {
data.enforceInterface(DESCRIPTOR);
if (data.readInt() != 0) {
_arg0 = ComponentName.CREATOR.createFromParcel(data);
} else {
_arg0 = null;
}
connected(_arg0, data.readStrongBinder(), data.readInt() != 0);
return true;
} else if (code != 1598968902) {
return super.onTransact(code, data, reply, flags);
} else {
reply.writeString(DESCRIPTOR);
return true;
}
}

/* access modifiers changed from: private */
public static class Proxy implements IServiceConnection {

@Override // android.app.IServiceConnection
public void connected(ComponentName name, IBinder service, boolean dead) throws RemoteException {
Parcel _data = Parcel.obtain();
try {
_data.writeInterfaceToken(Stub.DESCRIPTOR);
int i = 0;
if (name != null) {
_data.writeInt(1);
name.writeToParcel(_data, 0);
} else {
_data.writeInt(0);
}

// 1.writeStrongBinder 方法
_data.writeStrongBinder(service);
if (dead) {
i = 1;
}
_data.writeInt(i);

// 2.transact 方法
if (this.mRemote.transact(1, _data, null, 1) || Stub.getDefaultImpl() == null) {
_data.recycle();
} else {
Stub.getDefaultImpl().connected(name, service, dead);
}
} finally {
_data.recycle();
}
}
}
}
}

这里我们关注Proxy,其中的mRemote为BinderProxy,这里我们不太需要关注mRemote,因为它已经有了跨进程能力,这里我们关注两个点

  • writeStrongBinder
  • transact

writeStrongBinder

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class Parcel {
private Parcel(long nativePtr) {
if (DEBUG_RECYCLE) {
mStack = new RuntimeException();
}
//Log.i(TAG, "Initializing obj=0x" + Integer.toHexString(obj), mStack);
init(nativePtr);
}

private void init(long nativePtr) {
if (nativePtr != 0) {
mNativePtr = nativePtr;
mOwnsNativeParcelObject = false;
} else {
mNativePtr = nativeCreate();
mOwnsNativeParcelObject = true;
}
}
public final void writeStrongBinder(IBinder val) {
nativeWriteStrongBinder(mNativePtr, val);
}

private static native void nativeWriteStrongBinder(long nativePtr, IBinder val);
}

首次Parcel创建的时候,会调用native c++ 中的
/Volumes/android/aosp/frameworks/base/core/jni/android_os_Parcel.cpp

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
{"nativeCreate",              "()J", (void*)android_os_Parcel_create},
{"nativeWriteStrongBinder", "(JLandroid/os/IBinder;)V", (void*)android_os_Parcel_writeStrongBinder},

static jlong android_os_Parcel_create(JNIEnv* env, jclass clazz)
{
Parcel* parcel = new Parcel();
return reinterpret_cast<jlong>(parcel);
}

static jobject android_os_Parcel_readStrongBinder(JNIEnv* env, jclass clazz, jlong nativePtr)
{
Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
if (parcel != NULL) {
return javaObjectForIBinder(env, parcel->readStrongBinder());
}
return NULL;
}

static void android_os_Parcel_writeStrongBinder(JNIEnv* env, jclass clazz, jlong nativePtr, jobject object)
{
Parcel* parcel = reinterpret_cast<Parcel*>(nativePtr);
if (parcel != NULL) {

const status_t err = parcel->writeStrongBinder(ibinderForJavaObject(env, object));
if (err != NO_ERROR) {
signalExceptionForError(env, clazz, err);
}
}
}

/Volumes/android/aosp/frameworks/base/core/jni/android_util_Binder.cpp

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
// 写入的时候肯定是BinderProxy,因为server进程拿到的是用户进程的Service Binder
// 这里有两点
// 进程1 - Server Binder - BinderProxy
// Server - 进程2 BinderProxy - BinderProxy
sp<IBinder> ibinderForJavaObject(JNIEnv* env, jobject obj)
{
if (obj == NULL) return NULL;
// 本地Binder
// Instance of Binder?
if (env->IsInstanceOf(obj, gBinderOffsets.mClass)) {
// 获取java端 Binder对象
JavaBBinderHolder* jbh = (JavaBBinderHolder*)
env->GetLongField(obj, gBinderOffsets.mObject);
return jbh->get(env, obj);
}
// 远程Binder
// Instance of BinderProxy?
if (env->IsInstanceOf(obj, gBinderProxyOffsets.mClass)) {
// 获取java端 BinderProxy
return getBPNativeData(env, obj)->mObject;
}

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

BinderProxyNativeData* getBPNativeData(JNIEnv* env, jobject obj) {
return (BinderProxyNativeData *) env->GetLongField(obj, gBinderProxyOffsets.mNativeData);
}

/Volumes/android/aosp/frameworks/native/libs/binder/Parcel.cpp

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
Parcel::Parcel()
{
LOG_ALLOC("Parcel %p: constructing", this
initState();
}

status_t Parcel::writeStrongBinder(const sp<IBinder>& val)
{
return flatten_binder(ProcessState::self(), val, this);
}

status_t flatten_binder(const sp<ProcessState>& /*proc*/,
const sp<IBinder>& binder, Parcel* out)
{
flat_binder_object obj;

if (IPCThreadState::self()->backgroundSchedulingDisabled()) {
/* minimum priority for all nodes is nice 0 */
obj.flags = FLAT_BINDER_FLAG_ACCEPTS_FDS;
} else {
/* minimum priority for all nodes is MAX_NICE(19) */
obj.flags = 0x13 | FLAT_BINDER_FLAG_ACCEPTS_FDS;
}

if (binder != nullptr) {
BBinder *local = binder->localBinder();
if (!local) {
BpBinder *proxy = binder->remoteBinder();
if (proxy == nullptr) {
ALOGE("null proxy");
}
const int32_t handle = proxy ? proxy->handle() : 0;
obj.hdr.type = BINDER_TYPE_HANDLE;
obj.binder = 0; /* Don't pass uninitialized stack data to a remote process */
// 赋值handle
obj.handle = handle;
obj.cookie = 0;
} else {
if (local->isRequestingSid()) {
obj.flags |= FLAT_BINDER_FLAG_TXN_SECURITY_CTX;
}
obj.hdr.type = BINDER_TYPE_BINDER;
// 赋值binder
obj.binder = reinterpret_cast<uintptr_t>(local->getWeakRefs());
obj.cookie = reinterpret_cast<uintptr_t>(local);
}
} else {
obj.hdr.type = BINDER_TYPE_BINDER;
obj.binder = 0;
obj.cookie = 0;
}

return finish_flatten_binder(binder, obj, out);
}

transact

BinderProxy

1
2
public native boolean transactNative(int code, Parcel data, Parcel reply,
int flags) throws RemoteException;

/Volumes/android/aosp/frameworks/base/core/jni/android_util_Binder.cpp

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
60
61
62
63
64
65
66
{"transactNative",      "(ILandroid/os/Parcel;Landroid/os/Parcel;I)Z", (void*)android_os_BinderProxy_transact},



static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
{
if (dataObj == NULL) {
jniThrowNullPointerException(env, NULL);
return JNI_FALSE;
}
// 将发送数据 转为 c++ Parcel
Parcel* data = parcelForJavaObject(env, dataObj);
if (data == NULL) {
return JNI_FALSE;
}
// 将回复数据 转为 c++ Parcel
Parcel* reply = parcelForJavaObject(env, replyObj);
if (reply == NULL && replyObj != NULL) {
return JNI_FALSE;
}
// obj 为 BinderProxy
// 获取 IServiceConnect BinderProxy 获取 C++中的IBinder
IBinder* target = getBPNativeData(env, obj)->mObject.get();
if (target == NULL) {
jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
return JNI_FALSE;
}

ALOGV("Java code calling transact on %p in Java object %p with code %" PRId32 "\n",
target, obj, code);


bool time_binder_calls;
int64_t start_millis;
if (kEnableBinderSample) {
// Only log the binder call duration for things on the Java-level main thread.
// But if we don't
time_binder_calls = should_time_binder_calls();

if (time_binder_calls) {
start_millis = uptimeMillis();
}
}

//printf("Transact from Java code to %p sending: ", target); data->print();
// 这里的target
status_t err = target->transact(code, *data, reply, flags);
//if (reply) printf("Transact from Java code to %p received: ", target); reply->print();

if (kEnableBinderSample) {
if (time_binder_calls) {
conditionally_log_binder_call(start_millis, target, code);
}
}

if (err == NO_ERROR) {
return JNI_TRUE;
} else if (err == UNKNOWN_TRANSACTION) {
return JNI_FALSE;
}

signalExceptionForError(env, obj, err, true /*canThrowRemoteException*/, data->dataSize());
return JNI_FALSE;
}