Android4.4深入浅出之SurfaceFlinger(一)

来源:互联网 发布:人工智能和3d可视化 编辑:程序博客网 时间:2024/05/17 02:15

同样还是surfaceflinger,最近有点进展,特地分享!

一 开门见山

     Android 源代码中的类名真的是乱的一塌糊涂,经过一周多的研读The Fucking Source Code,终于有点眉头。首先surfaceflinger(以后简称SF),负责管理渲染UI的,他是个service,一直跟application交互,实时刷新surface。

     

知道这个,我从service这个点入手,之前尝试过直接看SF类等等,但是都搞不清楚头绪,所以改道service。

二 SF这个service的起源诞生

     在源码frameworks/native/service/surfaceflinger/main_surfaceflinger.cpp 中,让我们扒一扒是啥玩意。。

 

    

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. int main(int argc, char** argv) {  
  2.     // When SF is launched in its own process, limit the number of  
  3.     // binder threads to 4.  
  4.     ProcessState::self()->setThreadPoolMaxThreadCount(4); //忽略。。  
  5.   
  6.     // start the thread pool  
  7.     sp<ProcessState> ps(ProcessState::self());//忽略  
  8.     ps->startThreadPool(); // instantiate surfaceflinger   
  9.     sp<SurfaceFlinger> flinger = new SurfaceFlinger();//好戏从这里开始,得到一个SF对象  
  10.     #if defined(HAVE_PTHREADS)   
  11.     setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);  
  12.     #endif set_sched_policy(0, SP_FOREGROUND); // initialize before clients can connect   
  13.     flinger->init();//SF的初始化   
  14.     //publish surface flinger   
  15.     sm(defaultServiceManager()); //得到一个ServiceManager对象   
  16.     sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false); // // run in this thread   
  17.     flinger->run();//服务开始运行了!!! }  

 

    是不是无语了。。。对就是这么简单粗暴。但是丫的没这么简单吧。好了我们开始从

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<IServiceManager> sm(defaultServiceManager()); 开始,这里有个sp,简单介绍</span>  

一下,这是c++中为了防止指针出现段错误而设计的一种智能指针,smart pointer!用法是怎样的呢,其实很简单。sp<XXXX>  等同于 XXXX* ,比如 sp<char> == char* 很粗暴吧。。。
       回归正题,这里定义了一个IServiceManage的对象,sm(xx)就是把sm初始化为xx,所以现在看看sm被初始化成什么。我们跟踪下deafaultServieManager()。
     
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<IServiceManager> defaultServiceManager()  
  2. {  
  3.     if (gDefaultServiceManager != NULL) return gDefaultServiceManager;//忽略</span>  
  4.       
  5.     {  
  6.         AutoMutex _l(gDefaultServiceManagerLock); //这个就是上锁的意思</span>  
  7.         while (gDefaultServiceManager == NULL) {  
  8.             gDefaultServiceManager = interface_cast<IServiceManager>(    //重头戏在这                                                          ProcessState::self()->getContextObject(NULL));  
  9.             if (gDefaultServiceManager == NULL)  
  10.                 sleep(1);  
  11.         }  
  12.     }  
  13.       
  14.     return gDefaultServiceManager;  
  15. }  
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. gDefaultServiceManager是怎么来的。  
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. gDefaultServiceManager = interface_cast<IServiceManager>(    //重头戏在这                                                          ProcessState::self()->getContextObject(NULL));  
我FTSC!!又调用了函数,我们乖乖跟踪下interface_cast<IServiceManager>(  ProcessState::self()->getContextObject(NULL)) 这个函数。。首先看一下它那吓死人的参数:
   首先是一个self():

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<ProcessState> ProcessState::self()  
  2. {  
  3.     Mutex::Autolock _l(gProcessMutex);  
  4.     if (gProcess != NULL) {  
  5.         return gProcess;  
  6.     }  
  7.     gProcess = new ProcessState;  
  8.     return gProcess;  
  9. }  

他其实就是返回一个初始化好的ProcessState类对象,然后接着看getContextObject(NULL),这个函数在ProcessState中,是成员函数,注意了,传进去的是null,我们看下实体:
 
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<IBinder> ProcessState::getContextObject(const sp<IBinder>& caller)  
  2. {  
  3.     return getStrongProxyForHandle(0);  
  4. }  

不多说了,继续跟踪getStrongProxyForHandle(0);

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<IBinder> ProcessState::getStrongProxyForHandle(int32_t handle)  
  2. {  
  3.     sp<IBinder> result;   
  4.   
  5.     AutoMutex _l(mLock);//上锁  
  6.   
  7.     handle_entry* e = lookupHandleLocked(handle);//  
  8.     if (e != NULL) {   
  9.         IBinder* b = e->binder;  
  10.         if (b == NULL || !e->refs->attemptIncWeak(this)) //刚开始b肯定为NULL                                                                if (handle == 0) {//刚刚传进来的handle是0!                                                                                            Parcel data;         //下面做了什么我也不知道估计不影响  
  11.                 status_t status = IPCThreadState::self()->transact(  
  12.                         0, IBinder::PING_TRANSACTION, data, NULL, 0);  
  13.                 if (status == DEAD_OBJECT)  
  14.                    return NULL;  
  15.             }                                                                                                                                //这是重头戏啊 又来了个BpBinder?是啥玩意待会再说                                                                                  b = new BpBinder(handle);   
  16.             e->binder = b;  
  17.             if (b) e->refs = b->getWeakRefs();  
  18.             result = b;  
  19.         } else {  
  20.               
  21.             result.force_set(b);  
  22.             e->refs->decWeak(this);  
  23.         }  
  24.     }  
  25.   
  26.   
  27.     return result;//总之返回的是一个BpBinder类。}  
BpBinder是个强大深奥的东西,下面会专门讲一下,先接着看吧。
参数是BpBinder类的,接下俩看函数是怎么定义的。。
这里我们不妨留意一下 它的参数?函数的形参是IBinder类的,查了下才知道BpBinder继承了IBinder,所以形参是IBinder也不会有什么大问题。。。这这。。难道有一场阴谋??
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. template<typename INTERFACE>  
  2. inline sp<INTERFACE> interface_cast(const sp<IBinder>& obj)  
  3. {  
  4.     return INTERFACE::asInterface(obj);  
  5. }     

好吧,这是模板的使用,再看看原函数的调用在函数名后面有个尖括号<>,这下知道他的作用了吧,对!尖括号内的东西是用来代替   sp<INTERFACE> 中的INTERFACE,也就是IServiceManager代替INTERFACE
再看看函数体。。。。shit!!又是一个函数。我们继续跟踪
asInterface(obj);      
     好吧,我找了好半天,发现没有找到定义。。。但是看到了一个奇怪的东西。。就是发现他在宏定义里面申明的然后又在宏定义里面实现的!!是在IInterface.h中的定义的。
      
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #define DECLARE_META_INTERFACE(INTERFACE)                               \  
  2.     static const android::String16 descriptor;                          \  
  3.     static android::sp<I##INTERFACE> asInterface(                       \  
  4.             const android::sp<android::IBinder>& obj);                  \  
  5.     virtual const android::String16& getInterfaceDescriptor() const;    \  
  6.     I##INTERFACE();                                                     \  
  7.     virtual ~I##INTERFACE();                                            \  
这是声明。。。。接下来是实现的宏定义:
[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. #define IMPLEMENT_META_INTERFACE(INTERFACE, NAME)                       \  
  2.     const android::String16 I##INTERFACE::descriptor(NAME);             \  
  3.     const android::String16&                                            \  
  4.             I##INTERFACE::getInterfaceDescriptor() const {              \  
  5.         return I##INTERFACE::descriptor;                                \  
  6.     }                                                                   \  
  7.     android::sp<I##INTERFACE> I##INTERFACE::asInterface(                \  
  8.             const android::sp<android::IBinder>& obj)                   \  
  9.     {                                                                   \  
  10.         android::sp<I##INTERFACE> intr;                                 \  
  11.         if (obj != NULL) {                                              \  
  12.             intr = static_cast<I##INTERFACE*>(                          \  
  13.                 obj->queryLocalInterface(                               \  
  14.                         I##INTERFACE::descriptor).get());               \  
  15.             if (intr == NULL) {                                         \  
  16.                 intr = new Bp##INTERFACE(obj);                          \  
  17.             }                                                           \  
  18.         }                                                               \  
  19.         return intr;                                                    \  
  20.     }                                                                  \  
  21.     I##INTERFACE::I##INTERFACE() { }                                    \  
  22.     I##INTERFACE::~I##INTERFACE() { }                                   \  
脑袋瓜表示不够用了,好一个乱七八糟,乱八九糟,乱九十糟。。。。。红色部分分别是asInterface的声明和定义。这个时候我在想这是两个宏而已,到底他在哪里被调用了。
    好!这里我们回到前一步 interface_cast 函数实体是 return IServiceManage::asInterface(obj);这个函数应该定义在
IServiceManage类中才是啊,于是我去跟踪了下IServiceManage这个类:
   
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. class IServiceManager : public IInterface  
  2.   
  3. {  
  4. public:  
  5.   
  6.     DECLARE_META_INTERFACE(ServiceManager);  
  7.   
  8.      virtual status_t   addService( const String16& name,  
  9.   
  10.                                             const sp<IBinder>& service) = 0;  
  11.       // 。。。。。。  
  12. };  

好吧,看到这个类的第三行顿时感觉世界有救了,这不就是之前的宏定义吗,原来着这里调用了。。。好,我们在穿越时空到那个宏定义。。。。
  发现了什么?他的参数是个INTERFACE 跟刚刚的模板很像吧,不管了把所有的INTERFACE换成 ServiceManager, 宏定义中还有类似 I##INTERFACE ,其实即使翻译成 IINTERFACE,看看上面那个ServiceManager类中的调用他的参数就是ServiceManager,所以 在宏定义里面就变成 IServiceManager,好吧!我把他翻译一下。声明翻译成以下:

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. static const android::String16 descriptor;   
  2.   
  3. static android::sp< IServiceManager > asInterface(const android::sp<android::IBinder>&  
  4.   
  5. obj)   
  6. virtual const android::String16& getInterfaceDescriptor() const;   
  7.   
  8. IServiceManager ();                                                     \  
  9. virtual ~IServiceManager();  

实现翻译如下:
[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. const android::String16 IServiceManager::descriptor(“android.os.IServiceManager”);  
  2.   
  3. const android::String16& IServiceManager::getInterfaceDescriptor() const  
  4.   
  5.  {  return IServiceManager::descriptor;//返回上面那个android.os.IServiceManager  
  6.   
  7.    }                                                                      android::sp<IServiceManager> IServiceManager::asInterface(  
  8.   
  9.             const android::sp<android::IBinder>& obj)  
  10.   
  11.     {  
  12.   
  13.         android::sp<IServiceManager> intr;  
  14.   
  15.         if (obj != NULL) {                                               
  16.   
  17.             intr = static_cast<IServiceManager *>(                           
  18.   
  19.                 obj->queryLocalInterface(IServiceManager::descriptor).get());                
  20.   
  21.             if (intr == NULL) {                                           
  22.   
  23.                 intr = new BpServiceManager(obj);                           
  24.   
  25.             }                                                            
  26.   
  27.         }                                                                 
  28.   
  29.         return intr;                                                     
  30.   
  31.     }                                                                   
  32.   
  33.     IServiceManager::IServiceManager () { }                                     
  34.   
  35.     IServiceManager::~ IServiceManager() { }  
  好我们重点看下 asInterface 这个函数体,妈的绕了这么久终于可以接下去走了。简单分析下,程序走到第一个if进去了,然后第一次intr还是null所以又走到第二个if,对intr被初始化成一个BpServiceManager对象。。。。
     问题来了,BpServiceManager是什么东西,暂且不管,携带着这个坑爹的结果然我们一步步退出苦海,来到最开始的
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. sp<IServiceManager> sm(defaultServiceManager());  
 发现,实质上也没做什么事啊,不行,我们再回去研究一下 BpServiceManager。。

三  关于BpServiceManager

   之前一篇文章说过Bp 中p是proxy的意思,也就是代理。B其实就是传说中的叱咤江湖的 ”Binder“。。。。有点阴谋了,记得之前提过的那个大阴谋?我们接下去看。先找到这个类的相关定义(在IServiceManager.h中):

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. class BpServiceManager : public BpInterface<IServiceManager>  
  2. {  
  3. public:  
  4.     BpServiceManager(const sp<IBinder>& impl)  
  5.         : BpInterface<IServiceManager>(impl)  
  6.     {  
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. //构造函数的形参是IBinder参数,但是实际上传进来的是new BpBinder(0) (ps:为什么呢?之前最开始的时候传进来的参数就是BpBinder类的,只是形参一直写成IBinder又是BpBinder,而且参数名是impl,敏感吗,不就是implement的缩写,实现?难道有猫腻?接着看。    }  
  2.   
  3.     virtual sp<IBinder> getService(const String16& name) const  
  4.     {  
  5.         //忽略  
  6.     }  
  7.   
  8.     virtual sp<IBinder> checkService( const String16& name) const  
  9.     {  
  10.       。。。。。忽略  
  11.     }  
  12. //这是个重要的函数 不能忽略先把他记在心里,待会会解释                                                                                     virtual status_t addService(const String16& name, const sp<IBinder>& service,  
  13.             bool allowIsolated)  
  14.     {  
  15.         Parcel data, reply;  
  16.         data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  17.         data.writeString16(name);  
  18.         data.writeStrongBinder(service);  
  19.         data.writeInt32(allowIsolated ? 1 : 0);  
  20.         status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  21.         return err == NO_ERROR ? reply.readExceptionCode() : err;  
  22.     }  
  23.   
  24.     virtual Vector<String16> listServices()  
  25.     {  
  26.        //忽略  
  27.     }  
  28. };  
   好了,我们知道上一环节有提到BpServiceManager的是这行代码 intr = new BpServiceManager(obj);传进去的obj参数是IBinder类的,构造函数是BpServiceManager(const sp<IBinder>& impl): BpInterface<IServiceManager>(impl)
传进去的参数 直接进入BpInterface()这个函数,内容如下:
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. template<typename INTERFACE>  
  2. inline BpInterface<INTERFACE>::BpInterface(const sp<IBinder>& remote)  
  3.     : BpRefBase(remote)  
  4. {  
  5. }  
我了个cacaca,传进来的impl改名为 remote,又来个BpRefBase(remote),android元老们,你爸妈造你这么吊吗。。。。继续跟踪这个函数:

[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. BpRefBase::BpRefBase(const sp<IBinder>& o)  
  2.     : mRemote(o.get()), mRefs(NULL), mState(0)  
  3. {  
  4.     extendObjectLifetime(OBJECT_LIFETIME_WEAK);  
  5.   
  6.     if (mRemote) {  
  7.         mRemote->incStrong(this);           // Removed on first IncStrong().  
  8.         mRefs = mRemote->createWeak(this);  // Held for our entire lifetime.  
  9.     }  
  10. }  

好吧,他的名字又变了,是 o,对参数是o,记住是BpBinder类的。看他做了什么。o.get();返回的是一个sp<XXX> 也就是返回一个XXX*的指针,也就是说mRemote被初始化成 BpBinder类对象,看他做了什么?shit?看不懂啊 。。。。不管了忽略掉!

   好好现在我们重新回到BpServiceManager,再回一步sp<IServiceManager>sm(defaultServiceManager());
//简单说返回的实际是BpServiceManager,它的remote对象是BpBinder,传入的那个handle参数是0。

四  添加service

 我们再回到之前最开始的main函数,继续往下走
[html] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. int main(int argc, char** argv) {  
  2.     // When SF is launched in its own process, limit the number of  
  3.     // binder threads to 4.  
  4.     ProcessState::self()->setThreadPoolMaxThreadCount(4); //忽略。。  
  5.   
  6.     // start the thread pool  
  7.     sp<ProcessState> ps(ProcessState::self());  
  8. //忽略。。  
  9.   
  10.     ps->startThreadPool();  
  11.   
  12.     // instantiate surfaceflinger  
  13.     sp<SurfaceFlinger> flinger = new SurfaceFlinger();//好戏从这里开始,得到一个SF对象  
  14.   
  15. #if defined(HAVE_PTHREADS)  
  16.     setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);  
  17. #endif  
  18.     set_sched_policy(0, SP_FOREGROUND);  
  19.   
  20.     // initialize before clients can connect  
  21.     flinger->init();//SF的初始化  
  22.   
  23.     // publish surface flinger  
  24.     sp<IServiceManager> sm(defaultServiceManager()); //得到一个ServiceManager对象  
  25.     sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false);  //  
  26.     // run in this thread  
  27.     flinger->run();//服务开始运行了!!!  
  28.   
  29.  }  
这个时候走到sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false);
  看函数明就知道,刚刚创建的服务要开始添加了,这是个怎样的机制了,其实ServiceManage是一个服务管理员,所有的service都要在这边登记信息,然后申请创建,有条不紊,便于管理。
  看一下addService的函数实体:
   
[cpp] view plain copy
 print?在CODE上查看代码片派生到我的代码片
  1. virtual status_t addService(const String16& name, const sp<IBinder>& service,  
  2.            bool allowIsolated)  
  3.    {  
  4.        Parcel data, reply;  
  5.        data.writeInterfaceToken(IServiceManager::getInterfaceDescriptor());  
  6.        data.writeString16(name);  
  7.        data.writeStrongBinder(service);  
  8.        data.writeInt32(allowIsolated ? 1 : 0);  
  9.        status_t err = remote()->transact(ADD_SERVICE_TRANSACTION, data, &reply);  
  10.        return err == NO_ERROR ? reply.readExceptionCode() : err;  
  11.    }  

先看它的三个参数,第一个是一个字符串服务的名字,第二个就是这个service ,是IBinder类的,虽然传进来的是flinger 是SF类的,但是SF继承了IBinder,所以这里是可以的。
       Parcel的对象data,顾名思义是个数据包吧or缓冲区,接下去的四行都是把相关的一些信息比如interface描述信息,服务名称,本身service的binder都写到data里,然后通过transact()进行处理,这里的remote()是不是很眼熟,对,他其实就是BpBinder::remote(),接着往下看看到他返回的不是什么好东西,算了忽略掉,我们研究的是SF,这些在深入就是Binder机制的问题了。总结说,这个函数就是向管理者注册了SF这个service的一些基本信息。
        到这里我们是不是忽略了一行程序,flinger->init(); 这行说是SF的一些初始化,但是也是有很多的内容的。好,从此刻开始 ,我们终于开始进军SF的敌军大营,看看它内部到底是怎么回事。
0 0
原创粉丝点击