Dowemo
0 0 0 0

directory (? )[ + ]

android starts with 4 steps from kernel ( taking android4. 2 for example )

( 1 )initprocess process

( 2 )nativeservice startup

( 3 )system server,androidservice startup

( 4 )home

general start frame, such as:

image

first step: initialprocess(system/core/init)

initprocess, which is a process initiated by the kernel. after the kernel starts up ( memory, running, and initialization of all device drivers and data structures ), you start a user level program by starting ainithow to complete the boot process. initalways the first process.

initthe process is up.init. rca script file establishes several basic services:

  • servicemanamger
  • zygote

initdon't quit, but play it.property servicefeatures.

1. 1 process starts.

/system/core/Initi nit. c. entry:

[ cpp ]viewcopyprint printing?.
  • intmain.intargc,char* * argv )
  • %.
  • ...
  • ...
  • /* clear the aabb */
  • coa ( 0 );
  • /* get the basic filesystem setup we need put
  • * together in the initramdisk on/and then we &
  • the out the let *.
  • */
  • /**/
  • mkdir /dev"0755 )
  • mkdir /proc"0755 )
  • mkdir /sys"0755 )
  • ...
  • info: "reading filen."")
  • /*init.rc*/
  • init_parse_config_file /init. rc")
  • ...
  • /* execute all the boot actions to get us started */
  • /*action*/
  • action_for_each_trigger "", action_add_queue_tail );
  • ...
  • for(;; )
  • %.
  • intnr, I, timeout = -1;
  • /*actioncommand*/
  • execute_one_command ( );
  • ...
  • /* loop handles event */from property
  • for( I = 0; I <fd_count; I + + )
  • %.
  • if( ufds [ i ]. revents = = POLLIN )
  • %.
  • if( ufds [ i ]. fd = = get_property_set_fd ( ) )
  • handle_property_set_fd ( );
  • elseif( ufds [ i ]. fd = = get_keychord_fd ( ) )
  • handle_keychord ( );
  • elseif( ufds [ i ]. fd = = get_signal_fd ( ) )
  • handle_signal ( );
  • %
  • %
  • %
  • %



init. rc.androidinitialization scripts that are specified(android init language,,

the script contains four types of declarations:

  • actions
  • input
  • services
  • options.
1. 2 parsing service in init. rc

> -- init_parse_config_file (; parse_config,;,;,; (; ),; (;,; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ),; (; ).

add service to service list

init_parser. c parsing:

[ cpp ]viewcopyprint printing?.
  • statica list_declare ( service_list );
  • statica list_declare ( action_list );
  • statica list_declare ( action_queue );


1. 3 startup native service

execute_one_command ( ): move nodes from the action queue list ( action )

entry function for class_start default, primarily used to start native service

in system/core/init/builtins. c:

[ cpp ]viewcopyprint printing?.
  • intdo_class_startint,,char* * args )
  • %.
  • /* starting a class doesn't start services
  • * which are explicitly disabled. they must
  • * be started individually.
  • */
  • service_for_each_class ( args [ 1 ], service_start_if_not_disabled );
  • return0;
  • %

  • in init_parser. c.service_for_each_class (. ) all nodes on a list of service list lists

[ cpp ]viewcopyprint printing?.
  • staticvoidservice_start_if_not_disabledstructservice * svc )
  • %.
  • if(! svc-> flags & amp; svc_disabled )
  • service_start ( svc, null );
  • %
  • %

  • if not disabled, start the service.

service_start (. ) (. ) calls the ( ) to invoke the execve call to execute the new service.


system/core/init/property_service.c handle_property_set_fdhandle system property service requests, such as: services, wlan, and dhcp.

a systemProperties service can refer to

system/core/init/keycords.c中的 handle_keychordhandling keychord that's registered on service structure, typically started service.

system/core/init/signal_handler.c中的 handle_signalhandling sigchld ( zombie processes ).




step two.zygote

Servicemanagerzygotethe process sets up.androidbase.Zygotethis process will set up a real way.androidrunning space, initializing the establishedserviceit's all.navtive service.rcscript filezygotedescription:

service zygote/system/bin/app_process -xzygote/system/bin --zygote --start-system-server

so.zygoteframeworks/base/cmds/app_main.cpp main....)start.

where:

[ cpp ]viewcopyprint printing?.
  • appruntime;

initialize runtime.

[ cpp ]viewcopyprint printing?.
  • if( zygote ) % 7b
  • runtime. start ( "com. android. internal. os. ZygoteInit.",
  • startsystemserver? "start-system-server."":"")
  • %

  • runtime calls the start method, but appruntime doesn't have this method, and at its pare not class AndroidRuntime

[ cpp ]viewcopyprint printing?.
  • classappruntime:publicAndroidRuntime

  • so call the start method of AndroidRuntime:

[ cpp ]viewcopyprint printing?.
  • voidAndroidRuntime:: start (constchar*,constchar* option )
  • %.
  • alogd >.",
  • classname! = null? classname: ( unknown )")
  • blocksigpipe ( );
  • ...
  • /* start the virtual machine */
  • JNIEnv * env;
  • if( startvm ( & amp; mjavavm, & amp; env )! = 0 )
  • return;
  • %
  • onvmcreated ( env );
  • /*
  • * register android function.
  • */
  • if( startreg ( env ) <0 ) % 7b
  • ALOGE "unable to register all android nativesn")
  • return;
  • %
  • ...
  • a env-> CallStaticVoidMethod ( StartClass, startmeth, strarray );
  • ...
  • %

  • the startvm (. ) new vm:

[ cpp ]viewcopyprint printing?.
  • intAndroidRuntime:: startvm ( vm * * pjavavm, barometer * * pEnv )
  • %.
  • intresult = -1;
  • JavaVMInitArgs;
  • ...
  • /*
  • * middleware the vm.
  • *
  • * the vm * is essentially per-process, and the JNIEnv * is.
  • a * if this call succeeds, the vm is ready, and we can start issuing
  • * calls.
  • */
  • if( jni_createjavavm ( pjavavm, pEnv, & amp; initargs ) <0 ) % 7b
  • ALOGE jni_createjavavm"")
  • gotoa bail;
  • %
  • ...
  • %

  • it's called jni_createjavavm (. ) to create a vm.

onvmcreated ( env ) empty function, no use!


the startreg ( ) function is used to register the jni interface:

[ cpp ]viewcopyprint printing?.
  • /*
  • * register android native functions with the vm.
  • */
  • /*static*/intAndroidRuntime:: startreg ( * env )
  • %.
  • /*
  • a * this hook causes all threads created in this process to be
  • a * attached to the vm. ( this needs to go away in favor
  • * attach calls. )
  • */
  • a androidsetcreatethreadfunc ( android_create_thread_fn ) javacreatethreadetc;
  • alogv "--- registering native function ---n")
  • /*
  • call one or more things that return * every"register"function
  • * a local reference ( e. g. findclass ). because we haven & t really
  • * the vm yet, they 're all getting store in the base frame
  • a * and never released. use push/pop to manage the storage.
  • */
  • a env-> pushlocalframe ( 200 );
  • if( register_jni_procs ( gregjni, nelem ( gregjni ), env ) <0 ) % 7b
  • a env-> poplocalframe ( null );
  • return-1;
  • %
  • a env-> poplocalframe ( null );
  • a//createJavaThread("fubar", quicktest, ( void * ) & hello );
  • return0;/fameworks/base/core/java/com/android/internal/os/ZygoteInit.java
  • %


last call to AndroidRuntime 's start ( ) method[ cpp ]viewcopyprint printing?.
  • env-> CallStaticVoidMethod ( StartClass, startmeth, strarray )

(. ) function in 调用/fameworks/base/core/java/com/android/internal/os/ZygoteInit. java.

[ java ]viewcopyprint printing?.
  • publicstaticvoidmain ( string argv [ ] ) % 7b
  • try%.
  • //start profiling the zygote initialization.
  • samplingprofilerintegration. start ( );
  • registerzygotesocket ( );
  • ...
  • preload ( );
  • ...
  • if[ (1]. equals ("start-system-server."") the % 7b
  • startsystemserver ( );
  • % elseif(! argv [ )1]. equals ("") the % 7b
  • thrownewruntimeexception ( argv [ )0] + usage_string )
  • %
  • ...
  • %

registerzygotesocket ( ); a//来注册Socket的Listen端口 used to accept requests
  • [ java ]viewcopyprint printing?.
  • */
  • * registers a server socket for zygote command connections
  • *
  • * @ throws when open fails
  • */
  • privatestaticvoidregisterzygotesocket ( ) % 7b
  • if( sserversocket = =null% )
  • inta filedesc;
  • try%.
  • string env = system. IFormatProvider ( android_socket_env );
  • filedesc = integer. parseint ( env );
  • % catch( runtimeexception ex ) % 7b
  • thrownewruntimeexception
  • android_socket_env + "unset or invalid", ex );
  • %
  • try%.
  • sserversocket = newLocalServerSocket
  • a createfiledescriptor ( filedesc );
  • % catch( ioexception ex ) % 7b
  • thrownewruntimeexception
  • "error binding to local socket""+ filedesc +"", ex );
  • %
  • %
  • %

  • preload ( )classes and resources to speed up startup speed. preloadclass/frameworks/base/preloaded-classes.
  • [ java ]viewcopyprint printing?.
  • staticvoid% preload )
  • preloadclasses ( );
  • preloadResources ( );
  • %

  • startsystemserver ( )fork process:

[ java ]viewcopyprint printing?.
  • intpid;
  • try%.
  • parsedargs = newzygoteconnection. arguments ( args );
  • zygoteconnection. applydebuggersystemproperty ( parsedargs );
  • zygoteconnection. applyinvokewithsystemproperty ( parsedargs );
  • /* request to fork the system server process */
  • pid = zygote. forksystemserver (
  • parsedargs. uid, parsedArgs.gid,
  • parsedargs. gids,
  • parsedargs. debugflags,
  • null,
  • parsedargs. permittedcapabilities,
  • ( parsedargs. effectivecapabilities );
  • % catch( illegalargumentexception ex ) % 7b
  • thrownewruntimeexception ( ex );
  • %


through these steps,zygoteit's set up. use it.socketcommunication, receivingactivitymanangerservicerequest



step three.system server

zygote.fork的systemserver进程入口在/frameworks/base/services/java/com/android/server/SystemServer.java的,, .. androidall the service loop frameworks are built.SystemServeron.no loop structure can't be seen in SystemServer. java.

[ java ]viewcopyprint printing?.
  • publicstaticvoidmain ( string [ ] args ) % 7b
  • ...
  • ...
  • system. seaside ( "android_servers."")
  • init1 ( args );
  • %

  • load a local library called android servers, which provides a local method interface ( 源程序在framework/base/services/jni/目录中 ). then call the local method set service. code for specific execution settings in frameworks/base/cmds/system_server/library/system_init.cpp中.

init1 ( )it's.nativespace implementation (com_andoird_server_systemserver. cpp)

the columns are as follows:

[ java ]viewcopyprint printing?.
  • staticJNINativeMethod gmethods [ ] = %
  • /* name, signature, funcptr */
  • %. "init1."","([Ljava/lang/String;)V",voida * ) android_server_systemserver_init1 %.
  • %;

  • [ java ]viewcopyprint printing?.
  • staticvoidandroid_server_systemserver_init1 ( * env, jobject clazz )
  • %.
  • system_init ( );
  • %

in system_init. cppsystem_init ( ) is implemented as follows:

[ cpp ]viewcopyprint printing?.
  • extern""status_t system_init ( )
  • %.
  • ...
  • property_get "system_init. startsurfaceflinger.", propbuf,"1"")
  • if( propbuf,,"1"") = = 0 ) % 7b
  • //start the surfaceflinger
  • surfaceflinger:: instantiate ( );
  • %
  • property_get "system_init. startsensorservice.", propbuf,"1"")
  • if( propbuf,,"1"") = = 0 ) % 7b
  • //start the sensor service
  • sensorservice:: instantiate ( );
  • %
  • ...
  • alogi "system server: starting android services. n")
  • barometer * env = runtime-> getjnienv ( );
  • if( env = = null ) % 7b
  • returna unknown_error;
  • %
  • jclass clazz = env-> findclass ( "com/android/server/SystemServer")
  • if( clazz = = null ) %
  • returna unknown_error;
  • %
  • jmethodID methodid = env-> GetStaticMethodID ( clazz, "init2."","( ) v")
  • if( methodid = = null ) %
  • returna unknown_error;
  • %
  • a env-> CallStaticVoidMethod ( clazz, methodid );
  • alogi "system server: entering thread pool. n")
  • ProcessState:: self ( ) -> startthreadpool ( );
  • IPCThreadState:: self ( ) -> jointhreadpool ( );
  • alogi "system server: exiting thread pool. n")
  • returna no_error;
  • %

you can see. after initialization of sensors, video, audio and other services,> CallStaticVoidMethod ( clazz, methodid ). the callback is up. init2 ( ) ( ).

., java there's a story:

[ java ]viewcopyprint printing?.
  • */
  • * this method is called from zygote to initialize the system. this will cause
  • * services ( surfaceflinger, AudioFlinger, etc. ) to be started. after that it'll call
  • * up into init2 ( ) to start the android services.
  • */
  • nativepublicstaticvoidinit1 ( string [ ] args );
  • init2 will call back in the implementation of init1.!

system_init ( ) the thread pool is opened, join_threadpool ( ) suspend the current thread, wait for the binder request, the loop state started.


., javainit2 ( ) .androidmain system services ( windowmanagerserver ), activitymanagersystemservice ( ams ), packagemanagerserver ( IManager ),..

[ java ]viewcopyprint printing?.
  • publicstaticfinalvoidinit2 ( ) % 7b
  • slog. I ( tag, "enter the android system server!"")
  • thread = newserverthread ( );
  • thr. setname ( "android. server. serverthread.")
  • thr. start ( );
  • %
  • .init2( ) set up a thread thr, serverthread thread新建服务addserviceto establish a service:

[ java ]viewcopyprint printing?.
  • classserverthreadlist% thread
  • privatestaticfinalstring tag ="SystemServer."";
  • privatestaticfinalstring encrypting_state ="trigger_restart_min_framework."";
  • privatestaticfinalstring encrypted_state ="1"";
  • contentresolver;
  • ...
  • slog. I ( tag, "entropy mixer."")
  • servicemanager. addservice (. ) "entropy."",newa entropymixer ( );
  • slog. I ( tag, power manager")
  • power = newPowerManagerService ( );
  • servicemanager. addservice ( context, power_service, power );
  • slog. I ( tag, activity manager")
  • context = ActivityManagerService. main ( factorytest );
  • ...
  • //we now tell the activity manager it's okay to run
  • //code. it'll call back into us once it has gotten to state
  • //where third party code can really run ( but before it has
  • a//started launching the initial application ), for us to complete our
  • //.
  • ActivityManagerService. self ( ). systemready ( newrunnable ( ) % 7b
  • publicvoidrun ( ) % 7b
  • slog. I ( tag, making services ready")
  • if(! headless ) startsystemui ( contextf );
  • try%.
  • if( mountservicef! =null) mountservicef. systemready ( );
  • % catch( throwable ) % 7b
  • reportwtf making mount service ready", )
  • %
  • ...
  • %


after the systemready ( ) is executed, the systemready ( ) function of the associated service is started, and the overall initialization is completed.




step three.home


above serverthread calls to ActivityManagerService systemready ( ) and callback to frameworks/base/services/java/com/android/server/am/ActivityManagerServcie.java的 systemready (. ).

[ java ]viewcopyprint printing?.
  • publicfinalclassActivityManagerServicelistActivityManagerNative
  • implementswatchdog. monitor, batterystatsimpl. batterycallback %
  • ..
  • publicvoidsystemreadyfinalrunnable goingcallback ) % 7b
  • ..
  • 同步(this% )
  • ..
  • mmainstack. resumetopactivitylocked (. ) null)
  • %
  • %
  • ..
  • %

  • /frameworks/base/services/java/com/android/server/am/ActivityStack.java middle:

[ java ]viewcopyprint printing?.
  • finalbooleanresumetopactivitylocked ( ActivityRecord prev, bundle options ) %
  • //find the first activity that isn't finishing.
  • ActivityRecord next = toprunningactivitylocked ( null)
  • ...
  • if( next = =null% )
  • log. d ( tag, "jscese start launcher")
  • //are no more activities! let 's just start up the
  • a//launcher.
  • if( mmainstack ) % 7b
  • ActivityOptions. abort ( options );
  • returnmservice. starthomeactivitylocked ( mCurrentUser );
  • %
  • %
  • ...
  • %

  • next the activity at the top of the current system activity stack, or next = = null if none is, = = null.!

callback to activitymanagerservcie. java:

[ java ]viewcopyprint printing?.
  • booleanstarthomeactivitylockedintuserid ) % 7b
  • ...
  • intent intent newintent.
  • ,,
  • mtopdata! = null? uri. parse ( mtopdata ):null)
  • intent. setComponent ( mtopcomponent );
  • if( mfactorytest! = SystemServer. factory_test_low_level ) %
  • intent, addCategory ( intent, category_home );
  • %
  • ActivityInfoaInfo =
  • resolveactivityinfo ( intent, stock_pm_flags, userid );
  • if( aInfo! =null% )
  • intent. setComponent ( newcomponentname
  • ( aInfo, ApplicationInfo, packagename, aInfo, name );
  • log. d ( tag, "jscese first packagename = ="+ aInfo, ApplicationInfo, packagename );
  • //don 't do this if the home app is currently being
  • //.
  • aInfo = newa ActivityInfo ( aInfo );
  • aInfo. ApplicationInfo = getappinfoforuser ( aInfo. ApplicationInfo, userid );
  • ProcessRecord app = getprocessrecordlocked ( aInfo. processname,
  • a aInfo. ApplicationInfo. uid );
  • if( app = =null| | app. instrumentationclass = =null% )
  • intent. setflags ( intent, getFlags ( ) | intent, flag_activity_new_task );
  • mmainstack. startactivitylocked (. ) null,,null, aInfo,
  • null,null,0,0,0,0,null,false,null)
  • %
  • %
  • returntrue;
  • %

  • the category_home object type is created with an intent, and the resolveactivityinfo, function is the type of activity for the category type of the PackageManagerService query category!

the launcher. visible in androidmanifest. xml file:

[ html ]viewcopyprint printing?.
  • <activity
  • android: name="com. android. mslauncher. LauncherActivity."
  • ...
  • <intent-filter>
  • <actionandroid: name="android. intent. action. main"/>
  • <category categoriesandroid: name="android. intent. category. home."/>
  • <category categoriesandroid: name="android. intent. category. default"/>
  • <category categoriesandroid: name="android. intent. category. monkey"/>
  • </intent-filter>
  • </activity>
  • ...

  • run to ActivityStack. java:

[ java ]viewcopyprint printing?.
  • finalintstartactivitylocked ( iapplicationthread caller,
  • intent intent, string resolvedType,
  • uri [ ] granteduripermissions,
  • intgrantedmode, ActivityInfoaInfo, resultto,
  • ..
  • ActivityRecord r = newActivityRecord ( mservice,this, callerapp, callinguid,
  • intent, resolvedType, aInfo, mservice, mconfiguration,
  • a resultrecord, resultwho, requestcode, componentspecified;
  • ..
  • err = startactivityuncheckedlocked ( r, sourcerecord, startflags, trueoption )
  • ...
  • %

  • and is the process of starting an activity, and eventually starting the launcher. oncreate method!

this is complete.!

this blog post image model comes from http://blog.csdn.net/maxleng/article/details/5508372

it isn't easy to write, please. please note the http://blog.csdn.net/jscese/article/details/17115395.





Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs