上一篇文章我们着重分析了 1.Binder在Native层如何巧妙的将通讯与业务结合起来; 2.服务是如何路由的。这两个方都是从服务管理和提供的角度分析的。从整个Android系统来看Service包含两层一层是以Java语言铸成的,另外一层是以C++铸成的;今天我们来分析Framework层的Binder框架,Java层的Binder框架是Native中Binder框架的镜像,其实现结构上是类似的,废话少说直接上代码。
首先我们还是从IBinder开始分析
/frameworks/base/core/java/android/os/IBinder.java
public interface IBinder {
......
public @Nullable String getInterfaceDescriptor() throws RemoteException;
public boolean pingBinder();
public boolean isBinderAlive();
public @Nullable IInterface queryLocalInterface(@NonNull String descriptor);
......
//顶层中比较重要的方法
public boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply, int flags)
throws RemoteException;
......
}
Binder类实现了IBinder接口,重写了transact()方法
public final boolean transact(int code, @NonNull Parcel data, @Nullable Parcel reply,
int flags) throws RemoteException {
if (false) Log.v("Binder", "Transact: " + code + " to " + this);
if (data != null) {
data.setDataPosition(0);
}
boolean r = onTransact(code, data, reply, flags); //接受协议
if (reply != null) {
reply.setDataPosition(0);
}
return r;
}
onTransact() 将交给子类重写
protected boolean onTransact(int code, @NonNull Parcel data, @Nullable Parcel reply,
int flags) throws RemoteException {
if (code == INTERFACE_TRANSACTION) {
reply.writeString(getInterfaceDescriptor());
return true;
} else if (code == DUMP_TRANSACTION) {
......
return true;
} else if (code == SHELL_COMMAND_TRANSACTION) {
......
return true;
}
return false;
}
同时BinderProxy作为Binder内部类,同样实现了IBinder接口以及transact()方法
final class BinderProxy implements IBinder {
......
public boolean transact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
......
try {
return transactNative(code, data, reply, flags); //调用native方法
} finally {
if (tracingEnabled) {
Trace.traceEnd(Trace.TRACE_TAG_ALWAYS);
}
}
}
}
至此我们先稍微打断一下,转而从ServiceManager的角度看一看。
/frameworks/base/core/java/android/os/IInterface.java
public interface IInterface
{
/**
* Retrieve the Binder object associated with this interface.
* You must use this instead of a plain cast, so that proxy objects
* can return the correct result.
*/
public IBinder asBinder(); // 仅此一个方法申明
}
IServiceManager继承自IInterface,申明了一些通用方法
/frameworks/base/core/java/android/os/IServiceManager.java
public interface IServiceManager extends IInterface
{
public IBinder getService(String name) throws RemoteException;
public IBinder checkService(String name) throws RemoteException;
public void addService(String name, IBinder service, boolean allowIsolated)
throws RemoteException;
public String[] listServices() throws RemoteException;
......
}
服务管理最终交给ServiceManagerNative,ServiceManagerNative继承子Binder实现自IServiceManager,内部类ServiceManagerProxy同样实现了IServiceManager。
/frameworks/base/core/java/android/os/ServiceManagerNative.java
private static IServiceManager getIServiceManager() {
if (sServiceManager != null) {
return sServiceManager;
}
// Find the service manager
sServiceManager = ServiceManagerNative
.asInterface(Binder.allowBlocking(
BinderInternal.getContextObject())); //BinderInternal获取上下文
return sServiceManager;
}
BinderInternal 将调用native的方法
public class BinderInternal {
......
public static final native IBinder getContextObject(); //获取上下文
......
}
在android_util_Binder.cpp文件中可以查到JNI函数
static const JNINativeMethod gBinderInternalMethods[] = {
/* name, signature, funcPtr */
{ "getContextObject", "()Landroid/os/IBinder;", (void*)android_os_BinderInternal_getContextObject },
{ "joinThreadPool", "()V", (void*)android_os_BinderInternal_joinThreadPool },
{ "disableBackgroundScheduling", "(Z)V", (void*)android_os_BinderInternal_disableBackgroundScheduling },
{ "setMaxThreads", "(I)V", (void*)android_os_BinderInternal_setMaxThreads },
{ "handleGc", "()V", (void*)android_os_BinderInternal_handleGc }
};
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz)
{
sp<IBinder> b = ProcessState::self()->getContextObject(NULL); //BpBinder
return javaObjectForIBinder(env, b); //java对象转换
}
指向一个IBinder对象
jobject javaObjectForIBinder(JNIEnv* env, const sp<IBinder>& val)
{
......
// gBinderProxyOffsets 是一个结构体
object = env->NewObject(gBinderProxyOffsets.mClass, gBinderProxyOffsets.mConstructor);
if (object != NULL) {
LOGDEATH("objectForBinder %p: created new proxy %p !\n", val.get(), object);
// The proxy holds a reference to the native object.
env->SetLongField(object, gBinderProxyOffsets.mObject, (jlong)val.get()); //存入
val->incStrong((void*)javaObjectForIBinder);
// The native object needs to hold a weak reference back to the
// proxy, so we can retrieve the same proxy if it is still active.
jobject refObject = env->NewGlobalRef(
env->GetObjectField(object, gBinderProxyOffsets.mSelf)); //全局
val->attachObject(&gBinderProxyOffsets, refObject,
jnienv_to_javavm(env), proxy_cleanup);
// Also remember the death recipients registered on this proxy
sp<DeathRecipientList> drl = new DeathRecipientList;
drl->incStrong((void*)javaObjectForIBinder);
env->SetLongField(object, gBinderProxyOffsets.mOrgue, reinterpret_cast<jlong>(drl.get()));
// Note that a new object reference has been created.
android_atomic_inc(&gNumProxyRefs);
incRefsCreated(env);
}
return object;
}
返回一个ServiceManagerProxy,并将Native层对应的BpBinder传进去
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);
}
将传入的BpBinder 由 mRemote 引用
class ServiceManagerProxy implements IServiceManager {
public ServiceManagerProxy(IBinder remote) {
mRemote = remote;
}
public IBinder asBinder() {
return mRemote;
}
public IBinder getService(String name) throws RemoteException {
Parcel data = Parcel.obtain();
Parcel reply = Parcel.obtain();
data.writeInterfaceToken(IServiceManager.descriptor);
data.writeString(name); //Parcel类调用写入
mRemote.transact(GET_SERVICE_TRANSACTION, data, reply, 0); //执行IBinder的transact
IBinder binder = reply.readStrongBinder();
reply.recycle();
data.recycle();
return binder;
}
......
private IBinder mRemote;
}
回到BinderProxy的transact()方法会调用transactNative()方法,由上述JNI注册表可以查到此函数,将调用native层的BpBinder执行驱动交互
static jboolean android_os_BinderProxy_transact(JNIEnv* env, jobject obj,
jint code, jobject dataObj, jobject replyObj, jint flags) // throws RemoteException
{
......
IBinder* target = (IBinder*)
env->GetLongField(obj, gBinderProxyOffsets.mObject); //取出 BpBinder
if (target == NULL) {
jniThrowException(env, "java/lang/IllegalStateException", "Binder has been finalized!");
return JNI_FALSE;
}
.......
//printf("Transact from Java code to %p sending: ", target); data->print();
status_t err = target->transact(code, *data, reply, flags); // 执行transact
return JNI_FALSE;
}
至此Binder在Java层的框架就讲完了,整体上Java层的Binder框架最终还是要借助Native层的Binder框架来完成与驱动层的交互,两层交互时需要结束JNI技术进行相互调用,JNI的函数注册就跳过不讲了,分为动态和静态两种方式,有兴趣可以自行了解。
在下一篇的Binder系列中我们将讲述Binder三角架的另一重要实现HAL层的Binder实现,它主要为HAL层而生,更多的是涉及到驱动相关,敬请期待。