android L 启动流程

android启动流程文章已经概述了android的启动流程,而andoird 5.0的流程其实也差不多,少数不同而已。

如下图:




整个启动流程与之前的一样,唯一不同的是android L支持64位的app,所以又起一个Zygote64来专门负责64位APK的孵化。

而且创建Zygote进程脚本在init.zygoteXX.rc里。

如下:

system/core/rootdir/init.zygote64_32.rc
system/core/rootdir/init.zygote64.rc
system/core/rootdir/init.zygote32.rc
system/core/rootdir/init.zygote32_64.rc

64位芯片通常会选择

system/core/rootdir/init.zygote64_32.rc

咱们来看下内容,分析创建了两个zygote。

service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote
    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

service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary
    class main
    socket zygote_secondary stream 660 root system
    onrestart restart zygote

言归正传:

1:Linux内核启动
2:init进程启动。
3:本地系统服务,Java系统服务 启动:
 1):init启动service manager,这个进程主要负责系统服务的注册管理,包括“java系统服务”“本地系统服务”
 2):init启动Media server,这个进程负责启动C/C++的“本地系统服务”。
 3):init启动Zygote,这个进程启动System server进程,这个进程启动"Java系统服务"---[包括power manager    service,sensor service]
 4):另外init启动system/bin下面的各种守护进程

4:Home启动。
第一:Linux内核启动
....
第二:init进程启动
kernel/init/main.c
asmlinkage void __init start_kernel(void)//这是kernel的入口,汇编head-common.S会链过来。
{
	...
	/* Do the rest non-__init'ed, we're now alive */
	rest_init();
}
static noinline void __init_refok rest_init(void)
{
	...
	kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND);
	...
}
static int __ref kernel_init(void *unused)
{
	kernel_init_freeable();//指定init文件位置,新增的函数,与之前的系统不同。
<span style="white-space:pre">	</span>...

	if (ramdisk_execute_command) {
		if (!run_init_process(ramdisk_execute_command))//调用run_init_process,init进程跑进来
			return 0;
		pr_err("Failed to execute %s\n", ramdisk_execute_command);
	}
<span style="white-space:pre">	</span>....
}
kernel_init_freeable()实现
static noinline void __init kernel_init_freeable(void)
{
	...

	if (!ramdisk_execute_command)
		ramdisk_execute_command = "/init";//指定init文件位置

	if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) {
		ramdisk_execute_command = NULL;
		prepare_namespace();
	}

	...
}

第三:启动servicemanager进程
init进程通过init.rc脚本启动servicemanager
init.rc
service servicemanager /system/bin/servicemanager//看到吧
    class core
    user system
    group system
    critical
    onrestart restart healthd
    onrestart restart zygote
    onrestart restart media
    onrestart restart surfaceflinger
    onrestart restart drm
下面是servicemanager部分代码,它负责管理本地系统服务和Java系统服务,为下面的本地系统系服,java系统服务的注册提供服务
frameworks/native/cmds/servicemanager/service_manager.c
uint32_t do_find_service(struct binder_state *bs, const uint16_t *s, size_t len, uid_t uid, pid_t spid)
{
}
int do_add_service(struct binder_state *bs,
                   const uint16_t *s, size_t len,
                   uint32_t handle, uid_t uid, int allow_isolated,
                   pid_t spid)
{
}
int main(int argc, char **argv)
{
    struct binder_state *bs;

    bs = binder_open(128*1024);
    ...

    selinux_enabled = is_selinux_enabled();
    sehandle = selinux_android_service_context_handle();//增加了selinux方面的内容

    if (selinux_enabled > 0) {
        if (sehandle == NULL) {
            ALOGE("SELinux: Failed to acquire sehandle. Aborting.\n");
            abort();
        }

        if (getcon(&service_manager_context) != 0) {
            ALOGE("SELinux: Failed to acquire service_manager context. Aborting.\n");
            abort();
        }
    }

    union selinux_callback cb;
    cb.func_audit = audit_callback;
    selinux_set_callback(SELINUX_CB_AUDIT, cb);//很多地方都用到
    cb.func_log = selinux_log_callback;
    selinux_set_callback(SELINUX_CB_LOG, cb);

    svcmgr_handle = BINDER_SERVICE_MANAGER;
    binder_loop(bs, svcmgr_handler);

    return 0;
}
从是上面知道servicemanager除了什么的service的注册服务外,还在SELinux安全领域做了工作,因为android L已经完全打开SELinux的功能。

init进程通过init.rc脚本启动mediaserver
init.rc
service media /system/bin/mediaserver//这样启动
    class main
    user media
    group audio camera inet net_bt net_bt_admin net_bw_acct drmrpc mediadrm qcom_diag
    ioprio rt 4

mediaserver启动一系统本地系统服务
frameworks/av/media/mediaserver/main_mediaserver.cpp
int main(int argc __unused, char** argv)
{
...
        ALOGI("ServiceManager: %p", sm.get());
        AudioFlinger::instantiate();//启动AudioFlinger服务
        MediaPlayerService::instantiate();//启动MediaPlayerService服务
        CameraService::instantiate();//启动CameraService服务
#ifdef AUDIO_LISTEN_ENABLED
        ALOGI("ListenService instantiated");
        ListenService::instantiate();
#endif
        AudioPolicyService::instantiate();
        SoundTriggerHwService::instantiate();
        registerExtensions();
        ProcessState::self()->startThreadPool();
        IPCThreadState::self()->joinThreadPool();
    }
}

init进程通过init.zygoteXX.rc启动zygote
前面讲到andoird L是64位系统,与之配合的芯片如果是64位的话,那init.zygoteXX.rc = init.zygote64_32.rc
service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server --socket-name=zygote//zygote64通过app_process64进程启动
    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

service zygote_secondary /system/bin/app_process32 -Xzygote /system/bin --zygote --socket-name=zygote_secondary//zygote通过app_process32进程启动
    class main
    socket zygote_secondary stream 660 root system
    onrestart restart zygote
分别通过app_process64,app_process32两个app_process进程来启动zygote64,zygote。
frameworks/base/cmds/app_process/app_main.cpp
#if defined(__LP64__)
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist64";
static const char ZYGOTE_NICE_NAME[] = "zygote64";//64位zygote进程的名字
#else
static const char ABI_LIST_PROPERTY[] = "ro.product.cpu.abilist32";
static const char ZYGOTE_NICE_NAME[] = "zygote";
#endif

int main(int argc, char* const argv[])
{
     ...
    while (i < argc) {
        const char* arg = argv[i++];
        if (strcmp(arg, "--zygote") == 0) {
            zygote = true;
            niceName = ZYGOTE_NICE_NAME;//根据64还是32,指定zygote进程的名字
        } ...
    }

   ...

    if (!niceName.isEmpty()) {
        runtime.setArgv0(niceName.string());
        set_process_name(niceName.string());//设置进程名字
    }

    if (zygote) {
        runtime.start("com.android.internal.os.ZygoteInit", args);//启动zygote进程
    } ...
}
AndroidRuntime是android的运行环境,由于Dalvik VM的效率不高,在android4.4开始,google就开发了androidruntime即android运行环境。Dalvik下,应用每次运行,都要将字节码转成机器码,大大影响效率。ART不同,应用第一次安装的时候,字节码就会转成机器码,并保存起来,这样应用启动时就更快。
Zygote是Java编写的,需运行在AndroidRuntime上。

runtime.start()实现如下:

frameworks/base/core/jni/AndroidRuntime.cpp
void AndroidRuntime::start(const char* className, const Vector<String8>& options)
{
    ALOGD("\n>>>>>> AndroidRuntime START %s <<<<<<\n",
            className != NULL ? className : "(unknown)");

...
//下面就是启动java进程,调用了java中的main函数入口
    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
    char* slashClassName = toSlashClassName(className);
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class '%s'\n", slashClassName);
        /* keep going */
    } else {
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in '%s'\n", className);
            /* keep going */
        } else {
            env->CallStaticVoidMethod(startClass, startMeth, strArray);

#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
    free(slashClassName);

    ALOGD("Shutting down VM\n");
    if (mJavaVM->DetachCurrentThread() != JNI_OK)
        ALOGW("Warning: unable to detach main thread\n");
    if (mJavaVM->DestroyJavaVM() != 0)
        ALOGW("Warning: VM did not shut down cleanly\n");
}


zygote启动system server

frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
 public static void main(String argv[]) {
        try {
...

            registerZygoteSocket(socketName);//注册listener接口
            ...
            if (startSystemServer) {
                startSystemServer(abiList, socketName);//启动system server
            }

            Log.i(TAG, "Accepting command socket connections");
            runSelectLoop(abiList);

            closeServerSocket();
        } catch (MethodAndArgsCaller caller) {
            caller.run();
        } catch (RuntimeException ex) {
            Log.e(TAG, "Zygote died with exception", ex);
            closeServerSocket();
            throw ex;
        }
    }

Zygote除了启动system server,还注册socket通道,接收来自ActivityManagerService的请求,Fork应用程序

启动一系列Java系统服务

frameworks/base/services/java/com/android/server/SystemServer.java
public static void main(String[] args) {
        new SystemServer().run();//调用run()
    }
 
SystemServer的main函数直接调用run()

private void run() {
        
        ...
        // Start services.
        try {
            startBootstrapServices();//启动一系列Java系统服务
            startCoreServices();
            startOtherServices();
        } catch (Throwable ex) {
            Slog.e("System", "******************************************");
            Slog.e("System", "************ Failure starting system services", ex);
            throw ex;
        }

       ...
    }

如下:
private void startOtherServices() {
...
Slog.i(TAG, "Content Manager");
            contentService = ContentService.main(context,
                    mFactoryTestMode == FactoryTest.FACTORY_TEST_LOW_LEVEL);

            Slog.i(TAG, "System Content Providers");
            mActivityManagerService.installSystemProviders();

            Slog.i(TAG, "Vibrator Service");
            vibrator = new VibratorService(context);
            ServiceManager.addService("vibrator", vibrator);

            Slog.i(TAG, "Consumer IR Service");
            consumerIr = new ConsumerIrService(context);
            ServiceManager.addService(Context.CONSUMER_IR_SERVICE, consumerIr);

            mAlarmManagerService = mSystemServiceManager.startService(AlarmManagerService.class);
            alarm = IAlarmManager.Stub.asInterface(
                    ServiceManager.getService(Context.ALARM_SERVICE));

            Slog.i(TAG, "Init Watchdog");
            final Watchdog watchdog = Watchdog.getInstance();
            watchdog.init(context, mActivityManagerService);
...
}

第四:Home启动

system server启动一系列Java系统服务后,ActivityManagerService系统服务里的Systemready()函数会被system server调用。
如下:

private void startOtherServices() {
...
mActivityManagerService.systemReady(new Runnable() {
            @Override
            public void run() {
               ... 
            }
        });
  
...
}

来到ActivityManagerService
frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

public void systemReady(final Runnable goingCallback) {
        synchronized(this) {
            if (mSystemReady) {
                // If we're done calling all the receivers, run the next "boot phase" passed in
                // by the SystemServer
                if (goingCallback != null) {
                    goingCallback.run();
                }
                return;
            }
...
            mStackSupervisor.resumeTopActivitiesLocked();//启动HomeActivity
            sendUserSwitchBroadcastsLocked(-1, mCurrentUserId);
        }
    }

 systemReady调用mStackSupervisor.resumeTopActivityesLocked启动HomeActivity

mStackSupervisor.resumeTopActivitiesLoked()实现

frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

boolean resumeTopActivitiesLocked() {
        return resumeTopActivitiesLocked(null, null, null);
    }
boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
        if (targetStack == null) {
            targetStack = getFocusedStack();
        }
        // Do targetStack first.
        boolean result = false;
        if (isFrontStack(targetStack)) {
            result = targetStack.resumeTopActivityLocked(target, targetOptions);
        }
        for (int displayNdx = mActivityDisplays.size() - 1; displayNdx >= 0; --displayNdx) {
            final ArrayList<ActivityStack> stacks = mActivityDisplays.valueAt(displayNdx).mStacks;
            for (int stackNdx = stacks.size() - 1; stackNdx >= 0; --stackNdx) {
                final ActivityStack stack = stacks.get(stackNdx);
                if (stack == targetStack) {
                    // Already started above.
                    continue;
                }
                if (isFrontStack(stack)) {
                    stack.resumeTopActivityLocked(null);//调用stack.resumeTopActivityLocked()
                }
            }
        }
        return result;
    }

要调用stack.resumeTopActivityLocked()的条件是stacks.size() = 1;那会=1吗?当然会
因为systemserver进程调用了setWindowManager(wm)创建第一个ActivityStack,并且是HOMD_STACK

如下设置setWindowManager(wm)

frameworks/base/services/java/com/android/server/SystemServer.java

private void startOtherServices() {
...
mActivityManagerService.setWindowManager(wm);
...
}

mActivityManagerService.setWindowManager(wm)实现

frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

    public void setWindowManager(WindowManagerService wm) {
        mWindowManager = wm;
        mStackSupervisor.setWindowManager(wm);//调用这里
    }

mStackSupervisor.setWindowManager(wm)实现

frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java

void setWindowManager(WindowManagerService wm) {
        synchronized (mService) {
            ...
            createStackOnDisplay(HOME_STACK_ID, Display.DEFAULT_DISPLAY);//创建HOME_STACK,与之前系统有所不同
            mHomeStack = mFocusedStack = mLastFocusedStack = getStack(HOME_STACK_ID);

...
        }
    }

createStackOnDisplay()实现

    private int createStackOnDisplay(int stackId, int displayId) {
        ActivityDisplay activityDisplay = mActivityDisplays.get(displayId);
        if (activityDisplay == null) {
            return -1;
        }

        ActivityContainer activityContainer = new ActivityContainer(stackId);
        mActivityContainers.put(stackId, activityContainer);//将HOME_STACK放入Activitycontainer中
        activityContainer.attachToDisplayLocked(activityDisplay);
        return stackId;
    }

将HOME_STACK放入ActivityContainer中,这里就创建了第一个ActivityStack,并且stackId = HOME_STACK_ID
所以说stack.size() = 1,并且是 launcher
而通过下面的getStack()函数获取HOME_STACK_ID

    ActivityStack getStack(int stackId) {
        ActivityContainer activityContainer = mActivityContainers.get(stackId);
        if (activityContainer != null) {
            return activityContainer.mStack;
        }
        return null;
    }

回到刚才的函数

frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java


boolean resumeTopActivitiesLocked(ActivityStack targetStack, ActivityRecord target,
            Bundle targetOptions) {
.....
                if (stack == targetStack) {
                    // Already started above.
                    continue;
                }
                if (isFrontStack(stack)) {
                    stack.resumeTopActivityLocked(null);//调用stack.resumeTopActivityLocked()
                }
   ....
    }

stack.resumeTopActivityLocked()实现

frameworks/base/services/core/java/com/android/server/am/ActivityStack.java

final boolean resumeTopActivityLocked(ActivityRecord prev) {
        return resumeTopActivityLocked(prev, null);
    }

    final boolean resumeTopActivityLocked(ActivityRecord prev, Bundle options) {
...
            result = resumeTopActivityInnerLocked(prev, options);
...
    }

    final boolean resumeTopActivityInnerLocked(ActivityRecord prev, Bundle options) {
        ...
        final TaskRecord prevTask = prev != null ? prev.task : null;
        if (next == null) {
            // There are no more activities!  Let's just start up the
            // Launcher...
            ActivityOptions.abort(options);
            if (DEBUG_STATES) Slog.d(TAG, "resumeTopActivityLocked: No more activities go home");
            if (DEBUG_STACK) mStackSupervisor.validateTopActivitiesLocked();
            // Only resume home if on home display
            final int returnTaskType = prevTask == null || !prevTask.isOverHomeStack() ?
                    HOME_ACTIVITY_TYPE : prevTask.getTaskToReturnTo();
            return isOnHomeDisplay() &&
                    mStackSupervisor.resumeHomeStackTask(returnTaskType, prev);//调用
        }
...
}

由于prev = null ,而launcher又是第一个应用,所以next = null。
mStackSupervisor.resumeHomeStackTask()实现

frameworks/base/services/core/java/com/android/server/am/ActivityStackSupervisor.java
   
 boolean resumeHomeStackTask(int homeStackTaskType, ActivityRecord prev) {
        if (!mService.mBooting && !mService.mBooted) {
            // Not ready yet!
            return false;
        }

        if (homeStackTaskType == RECENTS_ACTIVITY_TYPE) {
            mWindowManager.showRecentApps();
            return false;
        }
        moveHomeStackTaskToTop(homeStackTaskType);
        if (prev != null) {
            prev.task.setTaskToReturnTo(APPLICATION_ACTIVITY_TYPE);
        }

        ActivityRecord r = mHomeStack.topRunningActivityLocked(null);
        // if (r != null && (r.isHomeActivity() || r.isRecentsActivity())) {
        if (r != null && r.isHomeActivity()) {
            mService.setFocusedActivityLocked(r);
            return resumeTopActivitiesLocked(mHomeStack, prev, null);
        }
        return mService.startHomeActivityLocked(mCurrentUser);//调用
    }

由于prev =null, 而第一个应用Launcher还没跑起来,所以r = null
mService.startHomeActivityLocked()实现


frameworks/base/services/core/java/com/android/server/am/ActivityManagerService.java

boolean startHomeActivityLocked(int userId) {
        if (mFactoryTest == FactoryTest.FACTORY_TEST_LOW_LEVEL
                && mTopAction == null) {
            // We are running in factory test mode, but unable to find
            // the factory test app, so just sit around displaying the
            // error message and don't try to start anything.
            return false;
        }
        Intent intent = getHomeIntent();
        ActivityInfo aInfo =
            resolveActivityInfo(intent, STOCK_PM_FLAGS, userId);
        if (aInfo != null) {
            intent.setComponent(new ComponentName(
                    aInfo.applicationInfo.packageName, aInfo.name));
            // Don't do this if the home app is currently being
            // instrumented.
            aInfo = new ActivityInfo(aInfo);
            aInfo.applicationInfo = getAppInfoForUser(aInfo.applicationInfo, userId);
            ProcessRecord app = getProcessRecordLocked(aInfo.processName,
                    aInfo.applicationInfo.uid, true);
            if (app == null || app.instrumentationClass == null) {
                intent.setFlags(intent.getFlags() | Intent.FLAG_ACTIVITY_NEW_TASK);
                mStackSupervisor.startHomeActivity(intent, aInfo);
            }
        }

        return true;
    }

最后跑回到ActivityManagerService启动Home。

谢谢
















发布了28 篇原创文章 · 获赞 9 · 访问量 14万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览