Linux内核启动后,Android系统启动有4个步骤;
(1)init进程启动
(2)Native服务启动
(3)System Server及Java服务启动
(4)Home启动
Init进程启动后,将根据init.rc及initXXX.rc的内容执行一系列的命令,包括创建mount目录,安装文件系统,设置属性,启动adb,systemserver,mediaserver
system/core/rootdir/init.rc 内容如下:
- # setup the global environment //设置环境变量
- export PATH /sbin:/vendor/bin:/system/sbin:/system/bin:/system/xbin
- export LD_LIBRARY_PATH /vendor/lib:/system/lib
- ...
- # Filesystem image public mount points. //mount文件系统
- mkdir /mnt/obb 0700 root system
- mount tmpfs tmpfs /mnt/obb mode=0755,gid=1000
- ...
- # Define the oom_adj values for the classes of processes that can be
- # killed by the kernel. These are used in ActivityManagerService.
- setprop ro.FOREGROUND_APP_ADJ 0
- ...
- service servicemanager /system/bin/servicemanager //在其他服务启动前必须启动ServiceManager
- class pre_zygote_services
- user system
- group system
- critical
- onrestart restart zygote
- onrestart restart media
- service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server //启动SystemServer
- class zygote_services
- socket zygote stream 666
- onrestart write /sys/android_power/request_state wake
- onrestart write /sys/power/state on
- onrestart restart media
- onrestart restart netd
- service media /system/bin/mediaserver //启动mediaserver,启动多媒体相关的camera/playback等服务
- class zygote_services
- user media
- group system audio camera graphics inet net_bt net_bt_admin net_raw mot_drm input mot_tpapi mot_secclkd mot_pwric mot_caif
- ioprio rt 4
代码中service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server将启动systemserver。
具体调用路径如下:
app_process主入口函数,启动system server时命令行为app_process -Xzygote /system/bin --zygote --start-system-server。
frameworks/base/cmds/app_process/app_main.cpp
- int main(int argc, const char* const argv[])
- {
- ...
- // Next arg is startup classname or "--zygote"
- if (i < argc) {
- arg = argv[i++];
- if (0 == strcmp("--zygote", arg)) { //命令行必须含 --zygote
- bool startSystemServer = (i < argc) ?
- strcmp(argv[i], "--start-system-server") == 0 : false; //命令行是否含--start-system-server
- setArgv0(argv0, "zygote");
- set_process_name("zygote");
- runtime.start("com.android.internal.os.ZygoteInit",
- startSystemServer); //此处启动systemserver
- } else {
- ...
- }
启动ZygoteInit进程,以后所有的java进程均须通过此进程fork而成。
frameworks/base/core/jni/AndroidRuntime.cpp
- void AndroidRuntime::start(const char* className, const bool startSystemServer)
- {
- ...
- /* start the virtual machine */
- if (startVm(&mJavaVM, &env) != 0)
- goto bail;
- /*
- * Register android functions.
- */
- if (startReg(env) < 0) {
- LOGE("Unable to register all android natives\n");
- goto bail;
- }
- ...
- if (startClass == NULL) {
- LOGE("JavaVM unable to locate class '%s'\n", slashClassName);
- /* keep going */
- } else {
- startMeth = env->GetStaticMethodID(startClass, "main",
- "([Ljava/lang/String;)V");
- if (startMeth == NULL) {
- LOGE("JavaVM unable to find main() in '%s'\n", className);
- /* keep going */
- } else {
- env->CallStaticVoidMethod(startClass, startMeth, strArray); //调用com.android.internal.os.ZygoteInit的main()方法
- }
- }
- bail:
- free(slashClassName);
- }
ZygoteInit进程入口函数:
frameworks/base/core/java/com/android/internal/os/ZygoteInit.java
- public static void main(String argv[]) {
- try {
- VMRuntime.getRuntime().setMinimumHeapSize(5 * 1024 * 1024);
- ... registerZygoteSocket();
- ... preloadClasses();
- ... preloadResources();
- // Do an initial gc to clean up after startup
- gc();
- ...
- if (argv[1].equals("true")) { //只支持true参数
- startSystemServer(); //此处启动systemserver
- }
- ...
- if (ZYGOTE_FORK_MODE) { //目前为false
- runForkMode();
- } else {
- runSelectLoopMode(); //将在Loop中顺序处理以后的For请求
- }
- closeServerSocket();
- } catch (MethodAndArgsCaller caller) {
- caller.run();
- } catch (RuntimeException ex) {
- Log.e(TAG, "Zygote died with exception", ex);
- closeServerSocket();
- throw ex;
- }
- }
- private static boolean startSystemServer()
- throws MethodAndArgsCaller, RuntimeException {
- /* Hardcoded command line to start the system server */
- String args[] = {
- "--setuid=1000",
- "--setgid=1000",
- ... "--capabilities=130104352,130104352",
- "--runtime-init",
- "--nice-name=system_server",
- "com.android.server.SystemServer", //指定要启动的类名
- };
- ZygoteConnection.Arguments parsedArgs = null;...
- try {
- parsedArgs = new ZygoteConnection.Arguments(args);
- ...
- /* Request to fork the system server process */
- pid = Zygote.forkSystemServer( //fork出进程
- parsedArgs.uid, parsedArgs.gid,
- parsedArgs.gids, debugFlags, null,
- parsedArgs.permittedCapabilities,
- parsedArgs.effectiveCapabilities);
- } catch (IllegalArgumentException ex) {
- throw new RuntimeException(ex);
- }
- /* For child process */
- if (pid == 0) {
- handleSystemServerProcess(parsedArgs); //在fork出的进程里执行systemserver启动
- }
- return true;
- }
进程fork出来后,关闭socket并初始化进程
- private static void handleSystemServerProcess(
- ZygoteConnection.Arguments parsedArgs)
- throws ZygoteInit.MethodAndArgsCaller {
- closeServerSocket();
- RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
- }
所有java进程的共同入口zygoteInit()。
- public static final void zygoteInit(String[] argv)
- throws ZygoteInit.MethodAndArgsCaller {
- ...
- commonInit(); //初始化时区,设置agent
- zygoteInitNative(); //调用到com_android_internal_os_RuntimeInit_zygoteInit@AndroidRuntime.cpp -> gCurRuntime->onZygoteInit(),此处启动ThreadPool
- ...
- invokeStaticMain(startClass, startArgs); //调用com.android.server.SystemServer的main方法
- }
zygoteInitNative()将调用到JNI方法,并最终调用到onZygoteInit以启动进程池。
frameworks/base/cmds/app_process/app_main.cpp
- virtual void onZygoteInit()
- {
- sp<ProcessState> proc = ProcessState::self();
- if (proc->supportsProcesses()) {
- LOGV("App process: starting thread pool.\n");
- proc->startThreadPool(); //启动线程池处理Binder事件
- }
- }
systemServer进程主函数入口:
frameworks/base/services/java/com/android/server/SystemServer.java
- public static void main(String[] args) {
- // The system server has to run all of the time, so it needs to be
- // as efficient as possible with its memory usage.
- VMRuntime.getRuntime().setTargetHeapUtilization(0.8f);
- System.loadLibrary("android_servers"); //Load JNI library here that is used by SystemServer
- init1(args); //这里调用到android_server_SystemServer_init1@com_android_server_SystemServer.cpp
- }
systemServer初始化函数1,用来启动进程内所有的native服务,因为其他java服务依赖这些服务。
frameworks/base/services/jni/com_android_server_SystemServer.cpp
- static void android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
- {
- system_init();
- }
frameworks/base/cmds/system_server/library/system_init.cpp
- extern "C" status_t 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) { //可以通过改变属性来设置SurfaceFlinger是否run在systemserver里
- // Start the SurfaceFlinger
- SurfaceFlinger::instantiate();
- }
- // Start the sensor service
- SensorService::instantiate(); //启动SensorService
- // 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()) { //在phone上,这些service在mediaserver中创建。模拟器上,以下service在此进程创建
- // 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();
- }
- AndroidRuntime* runtime = AndroidRuntime::getRuntime();
- runtime->callStatic("com/android/server/SystemServer", "init2");//调用init2@SystemServer.java,在这里创建工作线程以启动各java服务并进入循环处理各service请求
- if (proc->supportsProcesses()) {
- ProcessState::self()->startThreadPool(); //启动线程池,注意:由于前面已经调用过startThreadPool,故此次调用不做任何事情
- IPCThreadState::self()->joinThreadPool(); //主线程加入到线程池里
- }
- return NO_ERROR;
- }
进程初始化函数init2,用来启动进程内所有的java服务。
frameworks/base/services/java/com/android/server/SystemServer.java
- public class SystemServer
- {
- public static final void init2() {
- Slog.i(TAG, "Entered the Android system server!");
- Thread thr = new ServerThread(); //创建新线程
- thr.setName("android.server.ServerThread");
- thr.start(); //启动工作线程,在此线程启动各种服务
- }
此工作线程(线程1)实现Java Service注册初始化及进入SystemServer事件处理循环。
- class ServerThread extends Thread {
- @Override
- public void run() {
- Looper.prepare(); //在此线程内处理system server相关消息
- android.os.Process.setThreadPriority(
- android.os.Process.THREAD_PRIORITY_FOREGROUND);
- BinderInternal.disableBackgroundScheduling(true);
- android.os.Process.setCanSelfBackground(false);
- // Critical services...
- try {
- ServiceManager.addService("entropy", new EntropyService()); //注册Service到ServiceManager
- power = new PowerManagerService();
- ServiceManager.addService(Context.POWER_SERVICE, power);
- context = ActivityManagerService.main(factoryTest); //注意:此处启动ActivityManagerService
- ...
- pm = PackageManagerService.main(context,factoryTest != SystemServer.FACTORY_TEST_OFF);
- ActivityManagerService.setSystemProcess();
- ...
- ContentService.main(context,factoryTest == SystemServer.FACTORY_TEST_LOW_LEVEL);
- ActivityManagerService.installSystemProviders()
- ...
- wm = WindowManagerService.main(context, power,factoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL); //启动Windows Manager
- ServiceManager.addService(Context.WINDOW_SERVICE, wm);
- ((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
- ...
- wm.systemReady(); //通知SystemReady
- power.systemReady();
- try {
- pm.systemReady();
- } catch (RemoteException e) {
- }
- ...
- // We now tell the activity manager it is okay to run third party
- // code. It will call back into us once it has gotten to the state
- // where third party code can really run (but before it has actually
- // started launching the initial applications), for us to complete our
- // initialization.
- ((ActivityManagerService)ActivityManagerNative.getDefault())
- .systemReady(new Runnable() {
- public void run() {
- if (statusBarF != null) statusBarF.systemReady2();
- if (batteryF != null) batteryF.systemReady();
- if (connectivityF != null) connectivityF.systemReady();
- if (dockF != null) dockF.systemReady();
- if (usbF != null) usbF.systemReady();
- if (uiModeF != null) uiModeF.systemReady();
- if (recognitionF != null) recognitionF.systemReady();
- Watchdog.getInstance().start();
- // It is now okay to let the various system services start their
- // third party code...
- if (appWidgetF != null) appWidgetF.systemReady(safeMode);
- if (wallpaperF != null) wallpaperF.systemReady();
- if (immF != null) immF.systemReady();
- if (locationF != null) locationF.systemReady();
- if (throttleF != null) throttleF.systemReady();
- }
- ...
- Looper.loop(); //进入循环,处理请求
- }
- }
ActivityManagerService主入口:
frameworks/base/services/java/com/android/server/am/ActivityManagerService.java
- <span style="font-size:18px;"> public static final Context main(int factoryTest) {
- AThread thr = new AThread(); //创建工作线程2
- thr.start(); //启动线程
- synchronized (thr) { //等待</span><span style="font-size:16px;"><span style="font-size:18px;">ActivityManagerService对象创建完成
- while (thr.mService == null) {
- try {
- thr.wait();
- } catch (InterruptedException e) {
- }
- }
- }</span>
- ActivityManagerService m = thr.mService;
- mSelf = m;
- ActivityThread at = ActivityThread.systemMain(); //加载system应用,并把此线程(工作线程1)作为SystemServer进程的system线程
- mSystemThread = at;
- Context context = at.getSystemContext();
- m.mContext = context;
- m.mFactoryTest = factoryTest;
- m.mMainStack = new ActivityStack(m, context, true);
- m.mBatteryStatsService.publish(context);
- m.mUsageStatsService.publish(context);
- synchronized (thr) {
- thr.mReady = true;
- thr.notifyAll();
- }
- m.startRunning(null, null, null, null); //初始化变量并设置system ready为true
- return context;
- }</span>
线程2中作为ActivityManager的工作线程,在其中处理ActivityManager相关的消息。
- static class AThread extends Thread {
- ActivityManagerService mService;
- boolean mReady = false;
- public AThread() {
- super("ActivityManager");
- }
- public void run() {
- Looper.prepare();
- android.os.Process.setThreadPriority(
- android.os.Process.THREAD_PRIORITY_FOREGROUND);
- android.os.Process.setCanSelfBackground(false);
- ActivityManagerService m = new ActivityManagerService();
- synchronized (this) {
- mService = m;
- notifyAll();
- }
- synchronized (this) {
- while (!mReady) {
- try {
- wait();
- } catch (InterruptedException e) {
- }
- }
- }
- Looper.loop();
- }
- }
ActivityThread.systemMain()将加载系统应用apk:
ActivityThread.java
- public static final ActivityThread systemMain() {
- ActivityThread thread = new ActivityThread();
- thread.attach(true); //加载system应用
- return thread;
- }
- private final void attach(boolean system) {
- sThreadLocal.set(this);
- mSystemThread = system;
- if (!system) {...
- } else {
- // Don't set application object here -- if the system crashes,
- // we can't display an alert, we just want to die die die.
- android.ddm.DdmHandleAppName.setAppName("system_process");
- try {
- mInstrumentation = new Instrumentation();
- ContextImpl context = new ContextImpl();
- context.init(getSystemContext().mPackageInfo, null, this);
- Application app = Instrumentation.newApplication(Application.class, context); //创建Application对象并实例化android.app.Application对象
- mAllApplications.add(app);
- mInitialApplication = app;
- app.onCreate(); //调用onCreate
- } catch (Exception e) {
- throw new RuntimeException(
- "Unable to instantiate Application():" + e.toString(), e);
- }
- }
ActivityManagerService.java
- public final void startRunning(String pkg, String cls, String action,
- String data) {
- synchronized(this) {
- if (mStartRunning) {
- return;
- }
- mStartRunning = true;
- mTopComponent = pkg != null && cls != null
- ? new ComponentName(pkg, cls) : null;
- mTopAction = action != null ? action : Intent.ACTION_MAIN;
- mTopData = data;
- if (!mSystemReady) {
- return;
- }
- }
- systemReady(null); //设置system ready为true
- }
- public void systemReady(final Runnable goingCallback) {...
- synchronized(this) {
- if (mSystemReady) {
- if (goingCallback != null) goingCallback.run(); //如果有Runnable要运行
- return;
- }
- // Check to see if there are any update receivers to run.
- if (!mDidUpdate) {
- if (mWaitingUpdate) {
- return;
- }
- Intent intent = new Intent(Intent.ACTION_PRE_BOOT_COMPLETED);
- List<ResolveInfo> ris = null;
- try {
- ris = AppGlobals.getPackageManager().queryIntentReceivers(
- intent, null, 0);
- } catch (RemoteException e) {
- }
- if (ris != null) {
- for (int i=ris.size()-1; i>=0; i--) {
- if ((ris.get(i).activityInfo.applicationInfo.flags
- &ApplicationInfo.FLAG_SYSTEM) == 0) {
- ris.remove(i);
- }
- }
- intent.addFlags(Intent.FLAG_RECEIVER_BOOT_UPGRADE);
- ArrayList<ComponentName> lastDoneReceivers = readLastDonePreBootReceivers();
- final ArrayList<ComponentName> doneReceivers = new ArrayList<ComponentName>();
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- if (lastDoneReceivers.contains(comp)) {
- ris.remove(i);
- i--;
- }
- }
- for (int i=0; i<ris.size(); i++) {
- ActivityInfo ai = ris.get(i).activityInfo;
- ComponentName comp = new ComponentName(ai.packageName, ai.name);
- doneReceivers.add(comp);
- intent.setComponent(comp);
- IIntentReceiver finisher = null;
- if (i == ris.size()-1) {
- finisher = new IIntentReceiver.Stub() {
- public void performReceive(Intent intent, int resultCode,
- String data, Bundle extras, boolean ordered,
- boolean sticky) {
- // The raw IIntentReceiver interface is called
- // with the AM lock held, so redispatch to
- // execute our code without the lock.
- mHandler.post(new Runnable() {
- public void run() {
- synchronized (ActivityManagerService.this) {
- mDidUpdate = true;
- }
- writeLastDonePreBootReceivers(doneReceivers);
- systemReady(goingCallback);
- }
- });
- }
- };
- }
- broadcastIntentLocked(null, null, intent, null, finisher,
- 0, null, null, null, true, false, MY_PID, Process.SYSTEM_UID);
- if (finisher != null) {
- mWaitingUpdate = true;
- }
- }
- }
- if (mWaitingUpdate) {
- return;
- }
- mDidUpdate = true;
- }
- mSystemReady = true; //置位
- // silent reboot bit will be off on normal power down
- if (mContext.getResources().getBoolean(com.android.internal.R.bool.config_poweron_sound)) {
- ConfigInfo.pwrSnd_setSilentreboot(1);
- } else if (mContext.getResources()
- .getBoolean(com.android.internal.R.bool.config_mute_poweron_sound)) {
- // Request that the next BootAnimation plays its sound.
- ConfigInfo.pwrSnd_setSilentreboot(0);
- }
- if (!mStartRunning) { //如果ActivityManagerService.startRunning已运行过,则无需继续
- return;
- }
- }
- ArrayList<ProcessRecord> procsToKill = null;
- synchronized(mPidsSelfLocked) {
- for (int i=mPidsSelfLocked.size()-1; i>=0; i--) {
- ProcessRecord proc = mPidsSelfLocked.valueAt(i);
- if (!isAllowedWhileBooting(proc.info)){ //检查FLAG_PERSISTENT是否为真
- if (procsToKill == null) {
- procsToKill = new ArrayList<ProcessRecord>();
- }
- procsToKill.add(proc); //如果应用未指明为persistent,则不能在system ready前运行
- }
- }
- }
- synchronized(this) {
- if (procsToKill != null) {
- for (int i=procsToKill.size()-1; i>=0; i--) {
- ProcessRecord proc = procsToKill.get(i);
- Slog.i(TAG, "Removing system update proc: " + proc);
- removeProcessLocked(proc, true); //杀掉所有已运行的非persistent应用
- }
- }
- // Now that we have cleaned up any update processes, we
- // are ready to start launching real processes and know that
- // we won't trample on them any more.
- mProcessesReady = true; //为真时,才允许launch正常的应用
- }...
- synchronized(this) {
- // Make sure we have no pre-ready processes sitting around.
- ...
- retrieveSettings();
- if (goingCallback != null) goingCallback.run();
- synchronized (this) {
- if (mFactoryTest != SystemServer.FACTORY_TEST_LOW_LEVEL) {
- try {
- List apps = AppGlobals.getPackageManager().
- getPersistentApplications(STOCK_PM_FLAGS);
- if (apps != null) {
- int N = apps.size();
- int i;
- for (i=0; i<N; i++) {
- ApplicationInfo info
- = (ApplicationInfo)apps.get(i);
- if (info != null &&
- !info.packageName.equals("android")) {
- addAppLocked(info); //启动所有标为persistent的且package名字为android的应用
- }
- }
- }
- } catch (RemoteException ex) {
- // pm is in same process, this will never happen.
- }
- }
- // Start up initial activity.
- mBooting = true;
- try {
- if (AppGlobals.getPackageManager().hasSystemUidErrors()) { //如果/data/system文件夹的uid和当前system UID不匹配
- Message msg = Message.obtain();
- msg.what = SHOW_UID_ERROR_MSG;
- mHandler.sendMessage(msg);
- }
- } catch (RemoteException e) {
- }
- mMainStack.resumeTopActivityLocked(null); //启动初始进程Home
- }
- }