Android系统的启动流程

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/litao55555/article/details/80684723

每个系统都有一个引导文件,由引导文件去运行linux内核,内核程序开始启动的时候会加载各种驱动和数据结构,开始加载android应用层的第一个进程(init进程c代码(system\core\init目录) Init.c),由这个进程加载其它的进程开始启动,本节主讲从内核开始执行Init.c到启动完成锁屏的过程

1. system\core\init\Init.c

int main(int argc, char **argv)
{
        ...
        /*创建目录并且挂载该目录*/
    mkdir("/dev", 0755);
    mkdir("/proc", 0755);
    mkdir("/sys", 0755);
    mount("tmpfs", "/dev", "tmpfs", MS_NOSUID, "mode=0755");
    mkdir("/dev/pts", 0755);
    mkdir("/dev/socket", 0755);
    mount("devpts", "/dev/pts", "devpts", 0, NULL);
    mount("proc", "/proc", "proc", 0, NULL);
    mount("sysfs", "/sys", "sysfs", 0, NULL);
        ...
        /*初始化日志*/
    klog_init();i
    ...
    /*解析配置文件*/
    init_parse_config_file("/init.rc");     //init.c解析配置文件init.rc
        ...
    return 0;
}

2. 分析配置文件init.rc

system\core\roodir\init.rc:
...
import /init.trace.rc       /*软件相关的服务在此初始化*/
...
/*硬件相关的服务*/
service surfaceflinger /system/bin/surfaceflinger
    class core
    user system
    group graphics drmrpc
    onrestart restart zygote

service media /system/bin/mediaserver
    class main
    user media
    group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm
    ioprio rt 4

3. 分析各种服务

3.1 分析软件相关服务 — zygote服务

system\core\rootdir\Init.zygote32.rc:
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server  //init.rc启动zygote服务,可知孵化器的目录为app_process
    class main
    socket zygote stream 660 root system
    onrestart write /sys/android_power/request_state wake
    onrestart write /sys/power/state on
    onrestart restart media
    onrestart restart netd

3.1.1 分析孵化器进程

frameworks\base\cmds\app_process\App_main.cpp:
int main(int argc, char* const argv[])
{
        ...
    AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
        ...
    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit", args);      //有运行环境启动Java层的程序
    }
    ...
}

3.1.2 分析Java层的孵化器进程

frameworks\base\core\java\com\android\internal\os\ZygoteInit.java:
public class ZygoteInit {       //zygote服务预加载类和资源,并启动SystemServer系统服务
        ...
    public static void main(String argv[]) {
        try {
            ...
            preload();  //预加载类和资源
                        ...
                        gc();       //强制执行一次垃圾收集
            ...
            if (startSystemServer) {
                startSystemServer(abiList, socketName);     //启动系统服务
            }
        }
        ...
    }

    static void preload() {
        Log.d(TAG, "begin preload");
        preloadClasses();
        preloadResources();
        preloadOpenGL();
        preloadSharedLibraries();
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        Log.d(TAG, "end preload");
    }

    private static final String PRELOADED_CLASSES = "preloaded-classes";        //类的配置文件

    private static void preloadClasses() {
        final VMRuntime runtime = VMRuntime.getRuntime();
        InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream(PRELOADED_CLASSES);     //加载名为preloaded-classes的文件中所有的类,共1800多个
        ...
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is), 256);
            int count = 0;
            String line;
            while ((line = br.readLine()) != null) {
                ...
                try {
                    ...
                    Class.forName(line);        //加载每一个类
                    ...
                    count++;
                }
                ...
            }
        }
    }

    private static boolean startSystemServer(String abiList, String socketName)
            throws MethodAndArgsCaller, RuntimeException {
        ...
        /* Hardcoded command line to start the system server */
        String args[] = {
            "--setuid=1000",    //1000代表system用户
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1032,3001,3002,3003,3006,3007",
            "--capabilities=" + capabilities + "," + capabilities,
            "--runtime-init",
            "--nice-name=system_server",        //进程的名字system_server
            "com.android.server.SystemServer",  //启动的类名
        };
        ZygoteConnection.Arguments parsedArgs = null;
        int pid;
        try {
            parsedArgs = new ZygoteConnection.Arguments(args);  //把参数封装到对象中
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);
            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(  //分叉进程,由Zygote孵化出SystemServer进程
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        }
        ...
        return true;
    }
}

3.1.3 分析系统服务进程

frameworks\base\services\java\com\android\server\SystemServer.java:
public final class SystemServer {
        ...
    public static void main(String[] args) {
        new SystemServer().run();
    }

    private void run() {
        ...
        // Initialize native services.
        System.loadLibrary("android_servers");  //加载libxxx.so文件,即libandroid_servers.so
        nativeInit();       //启动传感器服务
                ...
                // Start services.
        try {
            startBootstrapServices();       //会启动ActivityManagerService
            startCoreServices();
            startOtherServices();
        }
    }

    private void startCoreServices() {
        // Manages LEDs and display backlight.
        mSystemServiceManager.startService(LightsService.class);        //启动灯光服务

        // Tracks the battery level.  Requires LightService.
        mSystemServiceManager.startService(BatteryService.class);       //启动电池服务
                ...
    }

    private ActivityManagerService mActivityManagerService;
    private void startOtherServices() {
            ...
            mHdmiService = new HdmiService();                   //注册各种服务,例如:WindowManagerService、UsbService、SerialService、InputManagerService、AudioService

            inputManager = new InputManagerService(context);
            inputManager.start();           //启动InputManagerService

            wm = WindowManagerService.main(context, inputManager,           //启动WindowManagerService
                    mFactoryTestMode != FactoryTest.FACTORY_TEST_LOW_LEVEL,
                    !mFirstBoot, mOnlyCore);
            ServiceManager.addService(Context.WINDOW_SERVICE, wm);      //向ServiceManager注册WMS
            ServiceManager.addService(Context.INPUT_SERVICE, inputManager);     //向ServiceManager注册IMS

            imm = new InputMethodManagerService(context, wm);
        ServiceManager.addService(Context.INPUT_METHOD_SERVICE, imm);

        audioService = new AudioService(context);
        ServiceManager.addService(Context.AUDIO_SERVICE, audioService);

        mActivityManagerService.systemReady(new Runnable() {        //调用systemReady表明系统启动成功
            @Override
            public void run() {
                    /*tell the activity manager it is okay to run third party code*/
                    startSystemUi(context);         //启动systemUI
            }
                }
}

frameworks\base\services\core\jni\com_android_server_SystemServer.cpp:
static JNINativeMethod gMethods[] = {
    /* name, signature, funcPtr */
    { "nativeInit", "()V", (void*) android_server_SystemServer_nativeInit },
};

static void android_server_SystemServer_nativeInit(JNIEnv* env, jobject clazz) {
    char propBuf[PROPERTY_VALUE_MAX];
    property_get("system_init.startsensorservice", propBuf, "1");
    if (strcmp(propBuf, "1") == 0) {
        // Start the sensor service
        SensorService::instantiate();       //启动传感器服务,最终会执行addService
    }
}

frameworks\base\services\core\java\com\android\server\am\ActivityManagerService.java:
public final class ActivityManagerService extends ActivityManagerNative
        implements Watchdog.Monitor, BatteryStatsImpl.BatteryCallback {
        public void systemReady(final Runnable goingCallback) {
                ...
                startHomeActivityLocked(mCurrentUserId);        //启动开机锁屏画面
}

注意:surfaceflinger等硬件相关服务不由Zygote孵化出来,Zygote只孵化系统相关服务

3.2 分析硬件相关的服务

system\core\roodir\init.rc:
service surfaceflinger /system/bin/surfaceflinger
    class core
    user system
    group graphics drmrpc
    onrestart restart zygote

service media /system/bin/mediaserver
    class main
    user media
    group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm
    ioprio rt 4

3.2.1 分析surfaceflinger服务

frameworks\native\services\surfaceflinger\Main_surfaceflinger.cpp:
int main(int, char**) {
    ...
    // instantiate surfaceflinger
    sp<SurfaceFlinger> flinger = new SurfaceFlinger();
        ...
    flinger->init();

    // publish surface flinger
    sp<IServiceManager> sm(defaultServiceManager());
    sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false);

    // run in this thread
    flinger->run();
    return 0;
}

3.2.2 分析media进程

frameworks\av\media\mediaserver\Main_mediaserver.cpp:
int main(int argc __unused, char** argv)
{
    ...
    sp<ProcessState> proc(ProcessState::self());
    sp<IServiceManager> sm = defaultServiceManager();
    ALOGI("ServiceManager: %p", sm.get());
    AudioFlinger::instantiate();
    MediaPlayerService::instantiate();
    CameraService::instantiate();
    AudioPolicyService::instantiate();
    SoundTriggerHwService::instantiate();
    registerExtensions();
    ProcessState::self()->startThreadPool();
    IPCThreadState::self()->joinThreadPool();
}

4. 分析*::instantiate();

例如:AudioFlinger::instantiate();

class AudioFlinger :
    public BinderService<AudioFlinger>,
    public BnAudioFlinger
{
        ...
}

class BinderService
{
    ...
    static void instantiate() { publish(); }
        ...
        static status_t publish(bool allowIsolated = false) {
        sp<IServiceManager> sm(defaultServiceManager());
        return sm->addService(
                String16(SERVICE::getServiceName()),
                new SERVICE(), allowIsolated);
    }
}

注意:对于软件相关服务:初始化过程为new ***Service() -> addService
对于硬件相关服务:初始化过程为*::instantiate();

5. 总结

a. 独立类的访问权限只有public和默认,因为类和类只有同包和不同包
修饰类的成员有4种
b. Android系统的启动流程:
每个系统都有一个引导文件,由引导文件去运行linux内核,内核程序开始启动的时候会加载各种驱动和数据结构
开始加载android应用层的第一个进程,即Init.c的main函数开始
b.1 软件相关服务的启动过程
解析配置文件 init_parse_config_file(“/init.rc”); //Init.c的main函数
||
\/
软件相关的服务 service zygote /system/bin/app_process -Xzygote /system/bin –zygote –start-system-server //init.rc
||
\/
分析zygote进程 runtime.start(“com.android.internal.os.ZygoteInit”, args); // app_process\App_main.cpp的main函数
||由C++进入Java层的zygote进程
\/
预加载类和资源 preload(); //ZygoteInit.java的main函数 (加载名为preloaded-classes的文件中所有的类)
启动系统服务 startSystemServer(abiList, socketName); //ZygoteInit.java的main函数
||
\/
由Zygote启动SystemServer pid = Zygote.forkSystemServer(参数) 参数为android.server.SystemServer //ZygoteInit.java的startSystemServer函数
||
\/
启动本地服务(即传感器服务) System.loadLibrary(“android_servers”); nativeInit(); //SystemServer.java的main函数
启动相互依赖性比较强的Service startBootstrapServices();
启动CoreServices,例如:灯光服务、电池服务等 startCoreServices();
启动OtherServices,例如:WindowManagerService、UsbService、SerialService、InputManagerService、AudioService startOtherServices();
||
\/
audioService = new AudioService(context); //SystemServer.java的startOtherServices函数
ServiceManager.addService(Context.AUDIO_SERVICE, audioService);
…注册其他服务,上面仅分析声音服务
告诉activitymanager系统启动成功 mActivityManagerService.systemReady(run() {…})
||
\/
启动开机锁屏画面 startHomeActivityLocked(mCurrentUserId); //ActivityManagerService.java的systemReady方法中

b.2 硬件相关服务的启动过程
解析配置文件 init_parse_config_file(“/init.rc”); //Init.c
||
\/
硬件相关的服务 service media /system/bin/mediaserver //init.rc
||
\/
分析media进程 //mediaserver\Main_mediaserver的main函数
AudioFlinger::instantiate();
MediaPlayerService::instantiate();
CameraService::instantiate();
AudioPolicyService::instantiate();
SoundTriggerHwService::instantiate();

c. 修改开机动画:
http://www.cnblogs.com/jqyp/archive/2012/03/07/2383973.html

猜你喜欢

转载自blog.csdn.net/litao55555/article/details/80684723