Android源码之SurfaceFlinger的启动(一)

page1

在Android系统中,显示系统在底层是通过SurfaceFlinger服务来完成的,因此从今天开始,我们从SurfaceFlinger服务作为入口来分析一下Android显示系统.

SurfaceFlinger服务是在System进程中,而System进程是由Zygote进程启动的,并且是以Java层的SystemServer类的静态成员函数main为入口函数的。

因此,接下来我们就从SystemServer类(定义在SystemServer.java文件中)的静态成员函数main开始,分析SurfaceFlinger服务的启动过程:

1publicstaticvoidmain(String[]args){

2if(System.currentTimeMillis()<EARLIEST_SUPPORTED_TIME){

3//Ifadevice'sclockisbefore1970(before0),alotof

4//APIscrashdealingwithnegativenumbers,notably

5//java.io.File#setLastModified,soinsteadwefakeitand

6//hopethattimefromcelltowersorNTPfixesit

7//shortly.

8Slog.w(TAG,"Systemclockisbefore1970;settingto1970.");

9SystemClock.setCurrentTimeMillis(EARLIEST_SUPPORTED_TIME);

10}

11if(SamplingProfilerIntegration.isEnabled()){

12SamplingProfilerIntegration.start();

13timer=newTimer();

14timer.schedule(newTimerTask(){

15@Override

16publicvoidrun(){

17SamplingProfilerIntegration.writeSnapshot("system_server",null);

18}

19},SNAPSHOT_INTERVAL,SNAPSHOT_INTERVAL);

20}

//Mmmmmm...morememory!

21dalvik.system.VMRuntime.getRuntime().clearGrowthLimit();

//Thesystemserverhastorunallofthetime,soitneedstobe

//asefficientaspossiblewithitsmemoryusage.

22VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);

23System.loadLibrary("android_servers");

24init1(args);

25}

第24行(SystemServer.main)会调用init1函数来进行初始化操作,init1函数是个native函数来初始化C++层的服务,会导致com_android_server_SystemServer.cpp的android_server_SystemServer_init1函数的调用,关于com_android_server_SystemServer.cpp的android_server_SystemServer_init1函数的详细分析可以参考page2文件.

page2

1staticvoidandroid_server_SystemServer_init1(JNIEnv*env,jobjectclazz)

2{

3system_init();

4}

第3行(com_android_server_SystemServer->android_server_SystemServer_init1)会调用system_init函数,system_init函数是在system_init.cpp文件中定义的,system_init函数的定义如下:

1extern"C"status_tsystem_init()

2{

3ALOGI("Enteredsystem_init()");

4sp<ProcessState>proc(ProcessState::self());

5sp<IServiceManager>sm=defaultServiceManager();

6ALOGI("ServiceManager:%p\n",sm.get());

7sp<GrimReaper>grim=newGrimReaper();

8sm->asBinder()->linkToDeath(grim,grim.get(),0);

9charpropBuf[PROPERTY_VALUE_MAX];

10property_get("system_init.startsurfaceflinger",propBuf,"1");

11if(strcmp(propBuf,"1")==0){

12//StarttheSurfaceFlinger

13SurfaceFlinger::instantiate();

14}

15property_get("system_init.startsensorservice",propBuf,"1");

16if(strcmp(propBuf,"1")==0){

17//Startthesensorservice

18SensorService::instantiate();

19}

//AndnowstarttheAndroidruntime.Wehavetodothisbit

//ofnastinessbecausetheAndroidruntimeinitializationrequires

//someofthecoresystemservicestoalreadybestarted.

//AllotherserversshouldjuststarttheAndroidruntimeat

//thebeginningoftheirprocesses'smain(),beforecalling

//theinitfunction.

20ALOGI("Systemserver:startingAndroidruntime.\n");

21AndroidRuntime*runtime=AndroidRuntime::getRuntime();

22ALOGI("Systemserver:startingAndroidservices.\n");

23JNIEnv*env=runtime->getJNIEnv();

24if(env==NULL){

25returnUNKNOWN_ERROR;

26}

27jclassclazz=env->FindClass("com/android/server/SystemServer");

28if(clazz==NULL){

29returnUNKNOWN_ERROR;

30}

31jmethodIDmethodId=env->GetStaticMethodID(clazz,"init2","()V");

32if(methodId==NULL){

33returnUNKNOWN_ERROR;

34}

35env->CallStaticVoidMethod(clazz,methodId);

36ALOGI("Systemserver:enteringthreadpool.\n");

37ProcessState::self()->startThreadPool();

38IPCThreadState::self()->joinThreadPool();

39ALOGI("Systemserver:exitingthreadpool.\n");

40returnNO_ERROR;

41}

第9-14行(system_init->system_init)如果发现系统属性中设置了启动SurfaceFlinger服务,第13行(system_init->system_init)会调用SurfaceFlinger的instantiate函数来启动SurfaceFlinger服务,关于SurfaceFlinger的instantiate的详细分析可以参考page3文件.

第37-38行(system_init->system_init)是启动Binder的线程池,从此开始,SystemServer进程就可以接受Binder的进程间通信了.

page3

我们从SurfaceFlinger的instantiate函数作为入口来分析SurfaceFinger服务的启动.

我们先来看一下SurfaceFlinger类的继承体系:

classSurfaceFlinger:publicBinderService<SurfaceFlinger>,

publicBnSurfaceComposer,

privateIBinder::DeathRecipient,

privateThread,

privateHWComposer::EventHandler

我靠!SurfaceFlinger继承了5个父类.

不管了,先分析instantiate函数,instantiate函数是从BinderService继承而来的,我们先来看一下BinderService类的声明:

template<typenameSERVICE>classBinderService

BinderService接受一个模板参数.

BinderService的instantiate函数定义如下:

staticvoidinstantiate(){

publish();

}

instantiate函数只是调用了publish函数,publish函数的定义如下:

1staticstatus_tpublish(boolallowIsolated=false){

2sp<IServiceManager>sm(defaultServiceManager());

3returnsm->addService(String16(SERVICE::getServiceName()),newSERVICE(),allowIsolated);

4}

第2行(BinderService->publish)获得ServiceManager.

第3行(BinderService->publish)会new一个SERVICE实例,并调用ServiceManager的addService函数来交给ServiceManager管理,这是Binder机制的基础.

因此这里会new一个SurfaceFlinger对象,关于SurfaceFlinger的构造函数的分析可以参考page4文件.

因为ServiceManager的addService函数的参数是个SP类型的,因此这里会导致SurfaceFlinger的onFirstRef函数的调用,onFirstRef函数的定义如下:

1voidSurfaceFlinger::onFirstRef()

2{

3mEventQueue.init(this);

4

5run("SurfaceFlinger",PRIORITY_URGENT_DISPLAY);

6

7//Waitforthemainthreadtobedonewithitsinitialization

8mReadyToRunBarrier.wait();

9}

第3行(SurfaceFlinger->onFirstRef)成员变量mEventQueue是一个MessageQueue类型的,因此这里会调用MessageQueue的init函数.关于MessageQueue的init函数的实现可以参考page5文件.

第5行(SurfaceFlinger->onFirstRef)会调用run函数,run函数是从Thread类继承下来的.关于Thread的run函数的详细分析可以参考page6文件.

page4

我们分析一下SurfaceFlinger的构造函数的实现:

1SurfaceFlinger::SurfaceFlinger()

2:BnSurfaceComposer(),Thread(false),

3mTransactionFlags(0),

4mTransactionPending(false),

5mAnimTransactionPending(false),

6mLayersRemoved(false),

7mRepaintEverything(0),

8mBootTime(systemTime()),

9mVisibleRegionsDirty(false),

10mHwWorkListDirty(false),

11mDebugRegion(0),

12mDebugDDMS(0),

13mDebugDisableHWC(0),

14mDebugDisableTransformHint(0),

15mDebugInSwapBuffers(0),

16mLastSwapBufferTime(0),

17mDebugInTransaction(0),

18mLastTransactionTime(0),

19mBootFinished(false)

20{

21ALOGI("SurfaceFlingerisstarting");

22

23//debuggingstuff...

24charvalue[PROPERTY_VALUE_MAX];

25

26property_get("debug.sf.showupdates",value,"0");

27mDebugRegion=atoi(value);

28

29property_get("debug.sf.ddms",value,"0");

30mDebugDDMS=atoi(value);

31if(mDebugDDMS){

32if(!startDdmConnection()){

33//startfailed,andDDMSdebuggingnotenabled

34mDebugDDMS=0;

35}

36}

37ALOGI_IF(mDebugRegion,"showupdatesenabled");

38ALOGI_IF(mDebugDDMS,"DDMSdebuggingenabled");

39}

可以看到,SurfaceFlinger的构造函数除了初始化成员变量之外,没有什么额外的逻辑.

page5

我们分析一下MessageQueue的init函数的实现,如下所示:

1voidMessageQueue::init(constsp<SurfaceFlinger>&flinger)

2{

3mFlinger=flinger;

4mLooper=newLooper(true);

5mHandler=newHandler(*this);

6}

第3行(MessageQueue->init)会将SurfaceFlinger对象保存到MessageQueue里.

第4行(MessageQueue->init)会new一个Looper对象,用于分发消息.

第5行(MessageQueue->init)会用本MessageQueue去初始化一个Handler对象,注意,Handler是在MessageQueue类里定义的一个内部类,定义如下:

classHandler:publicMessageHandler{

enum{

eventMaskInvalidate=0x1,

eventMaskRefresh=0x2

};

MessageQueue&mQueue;

int32_tmEventMask;

public:

Handler(MessageQueue&queue):mQueue(queue),mEventMask(0){}

virtualvoidhandleMessage(constMessage&message);

voiddispatchRefresh();

voiddispatchInvalidate();

};

相关推荐