通过AMS分析Binder流程(Java到Kernel)

栗子:
public class MainActivity extends Activity{
 
  @Override
  protected void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
 
     Intent intent = new Intent(this, DisplayMessageActivity.class);
     startActivity(intent);//启动一个Activity
  }
}
 
1.frameworks/base/core/java/android/app/Activity.java
<1>.public void startActivity(Intent intent) {
  this.startActivity(intent, null); 
}
<2>.注意:这里继承关系: Activity —-—> ContextThemeWrapper ——> ContextWrapper ——> Context
   ————>public class Activity extends ContextThemeWrapper{}
     ————>public class ContextThemeWrapper extends ContextWrapper{}
       ————>public class ContextWrapper extends Context {}
 
<3>.在frameworks/base/core/java/android/content/Context.java中定义抽象方法startActivity()
    public abstract void startActivity(@RequiresPermission Intent intent);
    并且在frameworks/base/core/java/android/app/ContextImpl.java中实现了startActivity()抽象方法.
    public void startActivity(Intent intent) {
       mMainThread.getInstrumentation().execStartActivity();
    }
2.frameworks/base/core/java/android/app/Instrumentation.java
public ActivityResult execStartActivity(){
  int result = ActivityManagerNative.getDefault().startActivity();
}
 
 
3.frameworks/base/core/java/android/app/ActivityManagerNative.java
<1>.static public IActivityManager getDefault(){
  return gDefault.get();
}
 
<2>.private static final Singleton<IActivityManager> gDefault = new Singleton<IActivityManager>(){
    IBinder b = ServiceManager.getService("activity");
    IActivityManager am = asInterface(b);
    return am;
}
 
4.frameworks/base/core/java/android/os/ServiceManager.java
   public static void getService(String name, IBinder service){
 
   }
<1>.public static IBinder getService(String name) {
  return getIServiceManager().getService(name);
}
 
<2>.private static IServiceManager getIServiceManager() {
  sServiceManager = ServiceManagerNative.asInterface(BinderInternal.getContextObject());
  return sServiceManager;
}
 
 
5.frameworks/base/core/java/com/android/internal/os/BinderInternal.java
public static final native IBinder getContextObject();//jni函数
 
6.frameworks/base/core/jni/android_util_Binder.cpp
static jobject android_os_BinderInternal_getContextObject(JNIEnv* env, jobject clazz){
  sp<IBinder> b = ProcessState::self()->getContextObject(NULL);
  return javaObjectForIBinder(env, b);
}
 
7.frameworks/native/libs/binder/ProcessState.cpp
<1>.sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& /*caller*/){
  //这里参数为0,就是ServiceManager的binder handle值。所以这里你给个0,就返回给你servicemanager的Binder代理对象。
  return getStrongProxyForHandle(0);
}
 
8.sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle){
   sp<IBinder> result;
   Parcel data;
   status_t status = IPCThreadState::self()->transact(0, IBinder::PING_TRANSACTION, data, NULL, 0);
   b = new BpBinder(handle);
   result = b; //把BpBinder对象传给了IBinder对象,并且返回IBinder
 
   return result;//返回的result是IBinder*类型
}
注意:frameworks/native/include/binder/BpBinder.h这里BpBinder类是继承于IBinder的.
class BpBinder : public IBinder{
 
}
 
9.分析BpBinder(Proxy Binder)和BBinder(Base Binder)怎么联系起来的?
所以在frameworks/native/libs/binder/IServiceManager.cpp里
//frameworks/native/libs/binder/Static.cpp
sp<IServiceManager> gDefaultServiceManager;
gDefaultServiceManager = interface_cast<IServiceManager>(ProcessState::self()->getContextObject(NULL));
 
注意:sp<IBinder> result;
      b = new BpBinder(handle);
      result = b;
      return result;
IBinder就是new BpBinder(0);
======>interface_cast<IServiceManager>(new BpBinder(handle)/*handle为0;*/);
  ======>interface_cast<IServiceManager>(new BpBinder(0)//返回IBinder类型);
    ======>IServiceManager::asInterface(obj);//obj就是传进来:new BpBinder(0);即IBinder
      ======>new BpServiceManager(obj);//obj就是传进来:new BpBinder(0);即IBinder
        ======>class BpServiceManager : public BpInterface<IServiceManager>{}
          ======>inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& obj) : BpRefBase(remote){}
            ======>BpRefBase::BpRefBase(const sp<IBinder>& o): mRemote(o.get()), mRefs(NULL), mState(0){}
                   注意:sp<IBinder>& o类型初始化函数列表:把o传给mRemote,这里o就是new BpServiceManager(obj)的obj==>new BpBinder(0);即IBinder        		   
                   最终目的:把BpBinder传给了mRemote,mRemote就是remote(),就是IBinder*类型对象; 
                   后边使用remote()->transact()传输到kernel层,就调到BpBinder.cpp里的transact()函数,
                   这条路就打通了.因为:BpBinder和BBinder就是通过IBinder联系起来的.
		   //一.BBinder继承表
                   class BBinder : public IBinder{};
                   class BnInterface : public INTERFACE, public BBinder{};
                   
		   //二.BpBinder继承表
	           class BpRefBase : public virtual RefBase{
	                 IBinder* const mRemote;
			 inline  IBinder* remote() { return mRemote; } 
                    }
                   class BpInterface : public INTERFACE, public BpRefBase{};
                   inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote){}
 
 
<1>.分析interface_cast是个什么鬼?
frameworks/native/include/binder/IInterface.h
template<typename INTERFACE>
inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj){
  return INTERFACE::asInterface(obj);
}
 
仅仅是一个模板函数,所以interface_cast<IServiceManager>()等价于:
inline sp<IServiceManager> interface_cast(const sp<IBinder>& obj){
  return IServiceManager::asInterface(obj);
}
 
<2>.在frameworks/native/include/binder/IServiceManager.h中,
IServiceManager类继承于IInterface类
 
class IServiceManager : public IInterface{
  //关键无比的宏!
  DECLARE_META_INTERFACE(ServiceManager);//宏里面的一些定义
  IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager”);//宏力面的实现
}
将IServiceManager的DELCARE宏进行相应的替换后得到的代码如下所示:
#define DECLARE_META_INTERFACE(ServiceManager)
//定义一个描述字符串
static const android::String16 descriptor;
 
//定义一个asInterface函数
static android::sp< IServiceManager>asInterface(constandroid::sp<android::IBinder>& obj)
 
//定义一个getInterfaceDescriptor函数,返回就是descriptor字符串
virtual const android::String16&getInterfaceDescriptor() const;
 
//定义IServiceManager的构造函数和析构函数
IServiceManager ();                                                   
virtual ~IServiceManager();
 
将IServiceManager中的IMPLEMENT宏的定义展开,如下所示:
#define IMPLEMENT_META_INTERFACE(ServiceManager, "android.os.IServiceManager")
//初始化函数列表:descriptor的赋值为:android.os.IServiceManager
const android::String16 IServiceManager::descriptor(“android.os.IServiceManager”);
 
//实现getInterfaceDescriptor函数
const android::String16& IServiceManager::getInterfaceDescriptor()const
{ 
   //返回字符串descriptor,值是“android.os.IServiceManager”
   return IServiceManager::descriptor;
} 
 
//实现asInterface函数
android::sp<IServiceManager> IServiceManager::asInterface(constandroid::sp<android::IBinder>& obj)
{
android::sp<IServiceManager> intr;
  if(obj != NULL) {                                              
     intr = static_cast<IServiceManager *>(obj->queryLocalInterface(IServiceManager::descriptor).get());  
       if (intr == NULL) {
         //obj是我们刚才创建的那个BpBinder(0)
          intr = new BpServiceManager(obj);
        }
      }
    return intr;//BpBinder(这里已经把BpBinder转换成了BpServiceManager)指针转换成一个IServiceManager
}
 
//实现构造函数和析构函数
IServiceManager::IServiceManager() {}
IServiceManager::~ IServiceManager() {}
 
//如何BpBinder(这里已经把BpBinder转换成了BpServiceManager)指针转换成一个IServiceManager?
interface_cast是如何把BpBinder指针转换成一个IServiceManager指针的呢?
答案就在asInterface函数的一行代码中,如下所示:intr = new BpServiceManager(obj);
 
<3>.frameworks/native/libs/binder/IServiceManager.cpp
class BpServiceManager : public BpInterface<IServiceManager>{
   public:
        BpServiceManager(const sp<IBinder>& impl):BpInterface<IServiceManager>(impl){}
}
 
<4>.frameworks/native/include/binder/IInterface.h
//在这里BpInterface类又继承于BpRefBase类
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote){
 
}
 
<5>.frameworks/native/libs/binder/Binder.cpp
    frameworks/native/include/binder/Binder.h
std::atomic<int32_t>    mState;
IBinder* const          mRemote;
RefBase::weakref_type*  mRefs;
 
//注意:sp<IBinder>& o中初始化函数列表:给成员函数赋初值.mRemote=o.get();mRefs=NULL; mState=0;这里o就是new BpServiceManager(obj)的obj==>new BpBinder(0);即IBinder
BpRefBase::BpRefBase(const sp<IBinder>& o): mRemote(o.get()), mRefs(NULL), mState(0){
   mRemote->incStrong(this);
}
 
 
10.分析addService()方法,解读transact中Java和Kernel建立通信流程.
frameworks/base/core/java/android/os/ServiceManager.java
<1>.mRemote.transact(ADD_SERVICE_TRANSACTION, data, reply, 0);
 
<2>.frameworks/native/libs/binder/IServiceManager.cpp
virtual status_t addService(const String16& name, const sp<IBinder>& service){
  data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());
  //remote()其实就是BpBinder
  status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
}
 
11.frameworks/native/libs/binder/IServiceManager.cpp
<1>.//这里注意BpInterface就是BpBinder
class BpServiceManager : public BpInterface<IServiceManager>{
virtual status_t addService(){
  //这里remote()的new BpServiceManager就是BpBinder
  status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);
 }
}
 
在frameworks/native/include/binder/IServiceManager.h中,IServiceManager类继承于IInterface类
class IServiceManager : public IInterface{
  //这里宏定义和宏实现,把BpBinder转换为IServiceManager对象,前面已经分析过了.
  DECLARE_META_INTERFACE(INTERFACE)
  IMPLEMENT_META_INTERFACE(INTERFACE, NAME)
}
 
/*******************************************************************************************/
分析remote()是从哪里来的?
<6>.frameworks/native/include/binder/IInterface.h
//在IInterface.h中BpInterface返回了remote()
template<typename INTERFACE>
inline IBinder* BpInterface<INTERFACE>::onAsBinder(){
  return remote();
}
 
注意:mRemote和remote()的类型其实是IBinder,其实就是BpInterface(即BpBinder)
<7>.在frameworks/native/include/binder/Binder.h中,remote()返回的是IBinder*类型的mRemote.
IBinder* const  mRemote;
//这个是模版函数
template<typename INTERFACE>
inline IBinder* remote(){ 
   return mRemote; 
}
 
//在这里BpInterface类又继承于BpRefBase类
template<typename INTERFACE>
inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote) : BpRefBase(remote){
 
}
 
//BpRefBase定义mRemote就是BpBinder
frameworks/native/include/binder/Binder.h
class BpRefBase : public virtual RefBase{
protected:
  inline  IBinder* remote(){ 
     return mRemote; 
   }
 
private:
     IBinder* const  mRemote;
};
 
//BnInterface继承于BBinder
template<typename INTERFACE>
class BnInterface : public INTERFACE, public BBinder{
protected:
      virtual IBinder*  onAsBinder();  
}
注意:BpInterface和BnInterface它们是基于 IBinder*类型连接起来的。
/*******************************************************************************************/
 
 
12.frameworks/native/libs/binder/BpBinder.cpp
status_t BpBinder::transact(){
  status_t status = IPCThreadState::self()->transact(mHandle, code, data, reply, flags));
}
 
13.frameworks/native/libs/binder/IPCThreadState.cpp
/*******************************************************************************************/
//打开”/dev/binder”设备节点和kernel通信
//IPCThreadState构造函数,初始化成员变量列表:mProcess = ProcessState::self();
IPCThreadState::IPCThreadState(): mProcess(ProcessState::self()){
  if(gHaveTLS)
    return new IPCThreadState; 
};
 
IPCThreadState::IPCThreadState(): mProcess(ProcessState::self())){
   pthread_setspecific(gTLS, this);
}
 
//ProcessState构造函数,初始化成员变量列表:mDriverFD = open_driver();
frameworks/native/libs/binder/ProcessState.cpp
ProcessState::ProcessState(): mDriverFD(open_driver()){
}
//打开/dev/binder
static int open_driver(){
  int fd = open("/dev/binder", O_RDWR | O_CLOEXEC);
  ioctl(fd, BINDER_VERSION, &vers); 
  ioctl(fd, BINDER_SET_MAX_THREADS, &maxThreads)
}
/*******************************************************************************************/
 
<1>.status_t IPCThreadState::transact(){
  err = waitForResponse(reply);
}
 
<2>.status_t IPCThreadState::waitForResponse(Parcel *reply, status_t *acquireResult){
   talkWithDriver();
 
<3>.status_t IPCThreadState::talkWithDriver(bool doReceive){
  ioctl(mProcess->mDriverFD, BINDER_WRITE_READ, &bwr);//通过ioctl()和Kernel通信.
}
 
 
14.kernel/msm-3.18/drivers/staging/android/binder.c
<1>.static long binder_ioctl(struct file *filp, unsigned int cmd, unsigned long arg){
  case BINDER_WRITE_READ:
       ret = binder_ioctl_write_read(filp, cmd, arg, thread);
}
 
<2>.static int binder_ioctl_write_read(struct file *filp,struct binder_thread *thread){
    binder_thread_write();
    trace_binder_write_done();
    binder_thread_read();
    trace_binder_read_done();
}

《通过AMS分析Binder流程(Java到Kernel)》

《通过AMS分析Binder流程(Java到Kernel)》

 

    原文作者:慢慢的燃烧
    原文地址: https://blog.csdn.net/u010164190/article/details/86069102
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞