android kernel 初始化 2

来源:互联网 发布:淘宝商城儿童女装坎肩 编辑:程序博客网 时间:2024/06/06 13:04

init is the firstprocess after kernel started. The corresponding source code lies in: /system/core/init.It does the following tasks step by step:

1.       Initialize log system.

2.       Parse /init.rc and/init.%hardware%.rc.

3.       Execute early-init action inthe two files parsed in step 2.

4.       Device specific initialize.For example, make all device node in /dev and download firmwares.

5.       Initialize property system.Actually the property system is working as a share memory. Logically it lookslike a registry under Windows system.

6.       Execute init action in thetwo files parsed in step 2.

7.       Start property service.

8.       Execute early-boot and bootactions in the two files parsed in step 2.

9.       Execute property action inthe two files parsed in step 2.

10.   Enter into an infinite loopto wait for device/property set/child process exit events. For example, if anSD card is plugged in, init will receive a device add event, so it can makenode for the device. Most of the important process is forked in init, so if anyof them crash, init will receive a SIGCHLD then translate it into a childprocess exit event, so in the loop init can handle the process exit event andexecute the commands defined in *.rc(it will run command onrestart).

 

The .rc file is a script file defined byAndroid. The default is /system/core/rootdir/init.rc. We can take a loot at thefile format (/system/core/init/readme.txt is a good overall introduction of thescript). Basically the script file contains actions and services.

 

Actions

-------

Actions are named sequences of commands. Actionshave a trigger which is used to determine when the action should occur.  When an event which matches anaction's trigger occurs, that action is added to the tail of a to-be-executedqueue (unless it is already on the queue).

Each action in the queue is dequeued in sequenceand each command in that action is executed in sequence.  Init handles other activities (devicecreation/destruction, property setting, process restarting) "between"the execution of the commands in activities.

Actions take the form of:

on <trigger>

   <command>

   <command>

   <command>

...

 

Services

--------

Services are programs which init launches and(optionally) restarts when they exit.  Servicestake the form of:

service <name> <pathname> [<argument> ]*

   <option>

   <option>

   ...

 

Options

-------

Options are modifiers to services.  They affect how and when init runs theservice.

 

Triggers

--------

Triggers are strings which can be used to matchcertain kinds of events and used to cause an action to occur.

 

The builtin supported commands are defined indevice/system/init/keywords.h. Commands are implementd indevice/system/init/bultins.c.

 

The init program only executes five kinds oftriggers: “early-init”, “init”, “early-boot”, “boot”, “property:*”. Take a lookat the following line in default init.rc.

class_startdefault

This line is a command for the actioncorresponding to “boot” trigger. It will start all services whose class nameequals to “default”. By default, if no class option is defined for a service,the service’s class name is “default”. So this line will start all the servicesin the order of position in the file by default. (BTW, you can start anyservice using start commands, if you like.) Any service is run as a forkedprocess of init, take a look at the source code of service_start in /system/core/init.c.

 

So according to the default init.rc, thefollowing services will be executed step by step:

console: star a shell. The source is indevice/system/bin/ash.

adbd: start adb daemon. The source is indevice/tools/adbd. By default is disabled.

servicemanager: start binder system. Thesource is in device/commands/binder.

mountd: mount all fs defined in/system/etc/mountd.conf if started, receive commands through local socket tomount any fs. The source is in device/system/bin/mountd.

debuggerd: start debug system. The source is indevice/system/bin/debuggerd.

rild: start radio interface layer daemon. The sourceis in device/commands/rind.

zygote: start Android Java Runtime and start systemserver. It’s the most important service. The source is in device/servers/app.

media: start AudioFlinger, MediaPlayerService andCameraService. The source is in device/commands/mediaserver.

bootsound: play the default boot sound/system/media/audio/ui/boot.mp3. The source is in device/commands/playmp3.

dbus: start dbus daemon, it’s only used by BlueZ.The source is in device/system/Bluetooth/dbus-daemon.

hcid: redirect hcid’s stdout and stderr to theAndroid logging system. The source is in device/system/bin/logwrapper. Bydefault is disabled.

hfag: start Bluetooth handsfree audio gateway, it’sonly used by BlueZ. The source is in device/system/Bluetooth/bluez-utils. Bydefault is disabled.

hsag: start Bluetooth headset audio gateway, it’sonly used by BlueZ. The source is in device/system/Bluetooth/bluez-utils. Bydefault is disabled.

installd: start install package daemon. The source is indevice/servers/installd.

flash_recovery: load /system/recovery.img.The source is in device/commands/recovery/mtdutils.

 

Zygote service does thefollowing tasks step by step:

1.       Create JAVA VM.

2.       Register android nativefunction for JAVA VM.

3.       Call the main function in theJAVA class named com.android.internal.os.ZygoteInit whose source isdevice/java/android/com/android/internal/os/ZygoteInit.java.

a)         Load ZygoteInit class

b)        Register zygote socket

c)        Load preload classes(thedefault file is device/java/android/preloaded-classes)

d)        Load preload resources

e)         Call Zygote::forkSystemServer(implemented in device/dalvik/vm/InternalNative.c) to fork a new process. Inthe new process, call the main function in the JAVA class namedcom.android.server.SystemServer, whose source is indevice/java/services/com/android/server.

                         i.              Load libandroid_servers.so

                       ii.              Call JNI native init1function implemented indevice/libs/android_servers/com_android_server_SystemServers. It only callssystem_init implemented in device/servers/system/library/system_init.cpp.

l         If running on simulator,instantiate AudioFlinger, MediaPlayerService and CameraService here.

l         Call init2 function in JAVAclass named com.android.server.SystemServer, whose source is indevice/java/services/com/android/server. This function is very critical forAndroid because it start all of Android JAVA services.

l         If not running on simulator,call IPCThreadState::self()->joinThreadPool() to enter into servicedispatcher.

 

init1 初始化一些本地库,包括audio, media , camero  ,内部 执行过程  /system_init.cpp

extern "C" status_t system_init()
{
    LOGI("Entered system_init()");
   
    sp<ProcessState> proc(ProcessState::self());
   
    sp<IServiceManager> sm = defaultServiceManager();
    LOGI("ServiceManager: %p/n", sm.get());
   
    sp<GrimReaper> grim = new GrimReaper();
    sm->asBinder()->linkToDeath(grim, grim.get(), 0);
   
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsurfaceflinger", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the SurfaceFlinger
        SurfaceFlinger::instantiate();
    }

    // On the simulator, audioflinger et al don't get started the
    // same way as on the device, and we need to start them here
    if (!proc->supportsProcesses()) {

        // Start the AudioFlinger
        AudioFlinger::instantiate();

        // Start the media playback service
        MediaPlayerService::instantiate();

        // Start the camera service
        CameraService::instantiate();

        // Start the audio policy service
        AudioPolicyService::instantiate();
    }

    // And now start the Android runtime.  We have to do this bit
    // of nastiness because the Android runtime initialization requires
    // some of the core system services to already be started.
    // All other servers should just start the Android runtime at
    // the beginning of their processes's main(), before calling
    // the init function.
    LOGI("System server: starting Android runtime./n");
   
    AndroidRuntime* runtime = AndroidRuntime::getRuntime();

    LOGI("System server: starting Android services./n");
    runtime->callStatic("com/android/server/SystemServer", "init2");
       
    // If running in our own process, just go into the thread
    // pool.  Otherwise, call the initialization finished
    // func to let this process continue its initilization.
    if (proc->supportsProcesses()) {
        LOGI("System server: entering thread pool./n");
        ProcessState::self()->startThreadPool();
        IPCThreadState::self()->joinThreadPool();
        LOGI("System server: exiting thread pool./n");
    }
    return NO_ERROR;
}

 

调用 init2初始化系统服务

    runtime->callStatic("com/android/server/SystemServer", "init2");


SystemServer::init2 will start a new thread tostart all JAVA services as follows:

Core Services:

1.       Starting Power Manager

2.       Creating Activity Manager

3.       Starting Telephony Registry

4.       Starting Package Manager

5.       Set Activity Manager Serviceas System Process

6.       Starting Context Manager

7.       Starting System ContextProviders

8.       Starting BatteryService

9.       Starting Alarm Manager

10.   Starting Sensor Service

11.   Starting Window Manager

12.   Starting Bluetooth Service

13.   Starting Mount Service

Other services

1.       Starting Status Bar Service

2.       Starting Hardware Service

3.       Starting NetStat Service

4.       Starting Connectivity Service

5.       Starting Notification Manager

6.       Starting DeviceStorageMonitorService

7.       Starting Location Manager

8.       Starting Search Service

9.       Starting Clipboard Service

10.   Starting Checkin Service

11.   Starting Wallpaper Service

12.   Starting Audio Service

13.   Starting HeadsetObserver

14.   Starting AdbSettingsObserver

Finally SystemServer::init2 will callActivityManagerService.systemReady to launch the first activity by sentingIntent.CATEGORY_HOME intent.

 

There is another way to start system server,which is through a program named system_server whose source isdevice/servers/system/system_main.cpp. It also calls system_init to startsystem services. So there is a question: why does Android have two methods tostart system services? My guess is that directly start system_server may havesynchronous problem with zygote because system_server will call JNI to startSystemServer::init2, while at that time zygote may not start JAVA VM yet. SoAndroid uses another method. After zynote is initialized, fork a new process tostart system services.

原创粉丝点击