Dowemo

directory (? ) [ + ]

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

( 1 ) init process process

( 2 ) native service startup

( 3 ) system server , android service startup

( 4 ) home

general start frame, such as:

image

first step: initial process (system/core/init)

init process, 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 a init how to complete the boot process. init always the first process .

init the process is up. init. rc a script file establishes several basic services:

  • servicemanamger
  • zygote

init don't quit, but play it. property service features.

1. 1 process starts.

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

[ cpp ] view copy print printing ?.
  • int main. int argc, 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 (;; )
  • %.
  • int nr, 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 ( );
  • else if ( ufds [ i ]. fd = = get_keychord_fd ( ) )
  • handle_keychord ( );
  • else if ( ufds [ i ]. fd = = get_signal_fd ( ) )
  • handle_signal ( );
  • %
  • %
  • %
  • %



init. rc . android initialization 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 ] view copy print printing ?.
  • static a list_declare ( service_list );
  • static a list_declare ( action_list );
  • static a 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 ] view copy print printing ?.
  • int do_class_start int ,, 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 );
  • return 0;
  • %

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

[ cpp ] view copy print printing ?.
  • static void service_start_if_not_disabled struct service * 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_fd handle system property service requests, such as: services, wlan, and dhcp.

a systemProperties service can refer to

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

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




step two. zygote

S ervicemanager zygote the process sets up. android base. Z ygote this process will set up a real way. android running space, initializing the established service it's all. navtive service. rc script file zygote description:

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

so. zygote frameworks/base/cmds/app_main.cpp main. ... ) start.

where:

[ cpp ] view copy print printing ?.
  • appruntime;

initialize runtime.

[ cpp ] view copy print 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 ] view copy print printing ?.
  • class appruntime: public AndroidRuntime

  • so call the start method of AndroidRuntime:

[ cpp ] view copy print printing ?.
  • void AndroidRuntime:: start ( const char *, const char * 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 ] view copy print printing ?.
  • int AndroidRuntime:: startvm ( vm * * pjavavm, barometer * * pEnv )
  • %.
  • int result = -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"" )
  • goto a 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 ] view copy print printing ?.
  • /*
  • * register android native functions with the vm.
  • */
  • /*static*/ int AndroidRuntime:: 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 );
  • return 0;/fameworks/base/core/java/com/android/internal/os/ZygoteInit.java
  • %


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

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

[ java ] view copy print printing ?.
  • public static void main ( string argv [ ] ) % 7b
  • try %.
  • //start profiling the zygote initialization.
  • samplingprofilerintegration. start ( );
  • registerzygotesocket ( );
  • ...
  • preload ( );
  • ...
  • if [ ( 1 ]. equals ( "start-system-server."" ) the % 7b
  • startsystemserver ( );
  • % else if (! argv [ ) 1 ]. equals ( "" ) the % 7b
  • throw new runtimeexception ( argv [ ) 0 ] + usage_string )
  • %
  • ...
  • %

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

  • preload ( ) classes and resources to speed up startup speed. preloadclass/frameworks/base/preloaded-classes .
  • [ java ] view copy print printing ?.
  • static void % preload )
  • preloadclasses ( );
  • preloadResources ( );
  • %

  • startsystemserver ( ) fork process:

[ java ] view copy print printing ?.
  • int pid;
  • try %.
  • parsedargs = new zygoteconnection. 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
  • throw new runtimeexception ( ex );
  • %


through these steps, zygote it's set up. use it. socket communication, receiving activitymanangerservice request



step three. system server

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

[ java ] view copy print printing ?.
  • public static void main ( 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. native space implementation ( com_andoird_server_systemserver. cpp )

the columns are as follows:

[ java ] view copy print printing ?.
  • static JNINativeMethod gmethods [ ] = %
  • /* name, signature, funcptr */
  • %. "init1."" , "([Ljava/lang/String;)V" , void a * ) android_server_systemserver_init1 %.
  • %;

  • [ java ] view copy print printing ?.
  • static void android_server_systemserver_init1 ( * env, jobject clazz )
  • %.
  • system_init ( );
  • %

in system_init. cpp system_init ( ) is implemented as follows:

[ cpp ] view copy print 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
  • return a unknown_error;
  • %
  • jclass clazz = env-> findclass ( "com/android/server/SystemServer" )
  • if ( clazz = = null ) %
  • return a unknown_error;
  • %
  • jmethodID methodid = env-> GetStaticMethodID ( clazz, "init2."" , "( ) v" )
  • if ( methodid = = null ) %
  • return a 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" )
  • return a 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 ] view copy print 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.
  • */
  • native public static void init1 ( 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.


., java init2 ( ) . android main system services ( windowmanagerserver ), activitymanagersystemservice ( ams ), packagemanagerserver ( IManager ),..

[ java ] view copy print printing ?.
  • public static final void init2 ( ) % 7b
  • slog. I ( tag, "enter the android system server!"" )
  • thread = new serverthread ( );
  • thr. setname ( "android. server. serverthread." )
  • thr. start ( );
  • %
  • . init2 ( ) set up a thread thr, serverthread thread 新建服务 addservice to establish a service:

[ java ] view copy print printing ?.
  • class serverthread list % thread
  • private static final string tag = "SystemServer."" ;
  • private static final string encrypting_state = "trigger_restart_min_framework."" ;
  • private static final string encrypted_state = "1"" ;
  • contentresolver;
  • ...
  • slog. I ( tag, "entropy mixer."" )
  • servicemanager. addservice (. ) "entropy."" , new a entropymixer ( );
  • slog. I ( tag, power manager" )
  • power = new PowerManagerService ( );
  • 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 ( new runnable ( ) % 7b
  • public void run ( ) % 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 ] view copy print printing ?.
  • public final class ActivityManagerService list ActivityManagerNative
  • implements watchdog. monitor, batterystatsimpl. batterycallback %
  • ..
  • public void systemready final runnable goingcallback ) % 7b
  • ..
  • 同步 ( this % )
  • ..
  • mmainstack. resumetopactivitylocked (. ) null )
  • %
  • %
  • ..
  • %

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

[ java ] view copy print printing ?.
  • final boolean resumetopactivitylocked ( 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 );
  • return mservice. 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 ] view copy print printing ?.
  • boolean starthomeactivitylocked int userid ) % 7b
  • ...
  • intent intent new intent.
  • ,,
  • 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 ( new componentname
  • ( 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 = new a 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 )
  • %
  • %
  • return true ;
  • %

  • 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 ] view copy print printing ?.
  • < activity
  • android: name = "com. android. mslauncher. LauncherActivity."
  • ...
  • < intent-filter >
  • < action android: name = "android. intent. action. main" />
  • < category categories android: name = "android. intent. category. home." />
  • < category categories android: name = "android. intent. category. default" />
  • < category categories android: name = "android. intent. category. monkey" />
  • </ intent-filter >
  • </ activity >
  • ...

  • run to ActivityStack. java:

[ java ] view copy print printing ?.
  • final int startactivitylocked ( iapplicationthread caller,
  • intent intent, string resolvedType,
  • uri [ ] granteduripermissions,
  • int grantedmode, ActivityInfoaInfo, resultto,
  • ..
  • ActivityRecord r = new ActivityRecord ( mservice, this , callerapp, callinguid,
  • intent, resolvedType, aInfo, mservice, mconfiguration,
  • a resultrecord, resultwho, requestcode, componentspecified;
  • ..
  • err = startactivityuncheckedlocked ( r, sourcerecord, startflags, true option )
  • ...
  • %

  • 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