注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

东东的博客

江南烟雨,同大家一起分享

 
 
 

日志

 
 

Android init 启动过程分析2  

2010-07-05 10:39:37|  分类: android相关 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |
主進程runSelectLoopMode()
5.Runs the zygote process's select loop runSelectLoopMode(), Accepts new connections as they happen, and reads commands from connections one spawn-reqst's worth at a time.
如果运行正常,则zygote进程会在runSelectLoopMode()中循环:



zygote 被siganl(11)终止
在  dalvik_system_Zygote.c (dalvik\vm\native)
的 static void sigchldHandler(int s) 函数中打印:              
"Process %d terminated by signal (%d)\n",
"Exit zygote because system server (%d) has terminated\n",




startSystemServer() ZygoteInit.java (frameworks\base\core\java\com\android\internal\os)
SystemServer 的mian()函数会调用
SystemServer.java (frameworks\base\services\java\com\android\server)中的 init1()函数。
init1()实际执行的是com_android_server_SystemServer.cpp (frameworks\base\services\jni)
中的 android_server_SystemServer_init1()。
android_server_SystemServer_init1()调用的是
System_init.cpp (frameworks\base\cmds\system_server\library) 中的 system_init()函数
system_init()函数定义如下:
extern "C" status_t system_init()
{
    ...
    sp<IServiceManager> sm = defaultServiceManager();
    ...
    property_get("system_init.startsurfaceflinger", propB, "1");
    if (strcmp(propB, "1") == 0) {
        //读取属性服务器,开启启动 SurfaceFlinger服务
        //接着会开始显示机器人图标
        //BootAnimation.cpp (frameworks\base\libs\surfaceflinger):status_t BootAnimation::readyToRun()
        SurfaceFlinger::instantiate();

    }
    //在模拟器上 a ioflinger 等几个服务与设备上的启动过程不一样,所以
    //我们在这里启动他们。

    if (!proc->supportsProcesses()) {
        //启动 A ioFlinger,media playback service,camera service服务
        A ioFlinger::instantiate();
        MediaPlayerService::instantiate();
        CameraService::instantiate();
    }
    //现在开始运行 the Android runtime ,我们这样做的目的是因为必须在 core system services
    //起来以后才能 Android runtime initialization,其他服务在调用他们自己的main()时,都会
    //调用 Android runtime
    //before calling the init function.
    LOGI("System server: starting Android runtime.\n");
    AndroidRuntime* runtime = AndroidRuntime::getRuntime();
    LOGI("System server: starting Android services.\n");
    //调用 SystemServer.java (frameworks\base\services\java\com\android\server)
    //中的init2函数
    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 contin 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;
}


System server: entering thread pool 表明已经进入服务线程 ServerThread
在 ServerThread 类的run 服务中开启核心服务:
    @Override
    p lic void run() {
        EventLog.writeEvent(LOG_BOOT_PROGRESS_SYSTEM_RUN,
            SystemClock.uptimeMillis());

        ActivityManagerService.prepareTraceFile(false);     // create dir

        Looper.prepare();
    //设置线程的优先级
        android.os.Process.setThreadPriority(
                android.os.Process.THREAD_PRIORITY_FOREGROUND);
    ...
        //关键(核心)服务
        try {
            Log.i(TAG, "Starting Power Manager.");
            Log.i(TAG, "Starting activity Manager.");
            Log.i(TAG, "Starting telephony registry");
            Log.i(TAG, "Starting Package Manager.");
            Log.i(TAG, "tarting Content Manager.");
            Log.i(TAG, "Starting System Content Providers.");
            Log.i(TAG, "Starting Battery Service.");
            Log.i(TAG, "Starting Alarm Manager.");
            Log.i(TAG, "Starting Sensor Service.");
            Log.i(TAG, "Starting Window Manager.");
            Log.i(TAG, "Starting Bltooth Service.");
            //如果是模拟器,那么跳过蓝牙服务。
            // Skip Bltooth if we have an emulator kernel
         //其他的服务
            Log.i(TAG, "Starting Status Bar Service.");
            Log.i(TAG, "Starting Clipboard Service.");
            Log.i(TAG, "Starting Input Method Service.");
            Log.i(TAG, "Starting Hardware Service.");
            Log.i(TAG, "Starting NetStat Service.");
            Log.i(TAG, "Starting Connectivity Service.");
            Log.i(TAG, "Starting Notification Manager.");
            // MountService must start after NotificationManagerService
            Log.i(TAG, "Starting Mount Service.");
        Log.i(TAG, "Starting DeviceStorageMonitor service");
            Log.i(TAG, "Starting Location Manager.");
            Log.i(TAG, "Starting Search Service.");
            ...
            if (INCL E_DEMO) {
                Log.i(TAG, "Installing demo data...");
                (new DemoThread(context)).start();
            }
            try {
                Log.i(TAG, "Starting Checkin Service.");
                Intent intent = new Intent().setComponent(new ComponentName(
                        "com.google.android.server.checkin",
                        "com.google.android.server.checkin.CheckinService"));
                if (context.startService(intent) == null) {
                    Log.w(TAG, "Using fallback Checkin Service.");
                    ServiceManager.addService("checkin", new FallbackCheckinService(context));
                }
            } catch (Throwable e) {
                Log.e(TAG, "Failure starting Checkin Service", e);
            }


            Log.i(TAG, "Starting Wallpaper Service");
        Log.i(TAG, "Starting A io Service");
            Log.i(TAG, "Starting HeadsetObserver");
            Log.i(TAG, "Starting AppWidget Service");
        ...
            try {
                com.android.server.status.StatusBarPolicy.installIcons(context, statusBar);
            } catch (Throwable e) {
                Log.e(TAG, "Failure installing status bar icons", e);
            }
        }

        // make sure the ADB_ENABLED setting val matches the secure property val
        Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
                "1".eq ls(SystemProperties.get("persist.service.adb.enable")) ? 1 : 0);

        // register observer to listen for settings changes
        mContentResolver.registerContentObserver(Settings.Secure.getUriFor(Settings.Secure.ADB_ENABLED),
                false, new AdbSettingsObserver());

        // It is now time to start up the app processes...
        boolean safeMode = wm.detectSafeMode();
        if (statusBar != null) {
            statusBar.systemReady();
        }
        if (imm != null) {
            imm.systemReady();
        }
        wm.systemReady();
        power.systemReady();
        try {
            pm.systemReady();
        } catch (RemoteException e) {
        }
        if (appWidget != null) {
            appWidget.systemReady(safeMode);
        }

        // After making the following code, third party code may be running...
        try {
            ActivityManagerNative.getDefault().systemReady();
        } catch (RemoteException e) {
        }

        Watchdog.getInstance().start();

        Looper.loop();
        Log.d(TAG, "System ServerThread is exiting!");
    }



startActivity()
  mRemote.transact(START_ACTIVITY_TRANSACTION, data, reply, 0);
 

ActivityManagerService.java 3136p (frameworks\base\services\java\com\android\server\am)
  startActivity()
    startActivityLocked() //3184
    int res = startActivityLocked(caller, intent, resolvedType,grantedUriPermissions, grantedMode, aInfo,
                    resultTo, resultWho, reqstCode, -1, -1,
                    onlyIfNeeded, componentSpecified);


p lic abstract class ActivityManagerNative extends Binder implements IActivityManager
ActivityManagerService.java 1071p  (frameworks\base\services\java\com\android\server\am)
ActivityManagerService.main()
  //ActivityManagerService.java 7375p (frameworks\base\services\java\com\android\server\am)
  m.startRunning(null, null, null, null);
    //ActivityManagerService.java 7421p (frameworks\base\services\java\com\android\server\am)
    systemReady();

ActivityManagerService.java 3136p (frameworks\base\services\java\com\android\server\am)
  startActivity(IApplicationThread caller,Intent intent,...)
    int startActivityLocked(caller, intent,...)    //3184L 定义:2691L
      void startActivityLocked()       //3132L 定义:2445L
        resumeTopActivityLocked(null); //2562p 定义:2176L
        if(next=NULL)
        {
          intent.addCategory(Intent.CATEGORY_HOME);
          startActivityLocked(null, intent, null, null, 0, aInfo,null, null, 0, 0, 0, false, false);
        }
        else
        {
          startSpecificActivityLocked(next, tr, false); //2439L 定义:1628L
            realStartActivityLocked() //1640L    定义:1524L
            //1651L 定义:1654L
            startProcessLocked(r.processName, r.info.applicationInfo, tr, 0,"activity", r.intent.getComponent());
              //1717L 定义:1721L
              startProcessLocked(app, hostingType, hostingNameStr);
                //1768L  定义:Process.java 222L(frameworks\base\core\java\android\os)
                int pid = Process.start("android.app.ActivityThread",...)
                  startViaZygote(processClass, niceName, uid, gid, gids,debugFlags, zygoteArgs);
                    pid = zygoteSendArgsAndGetPid(argsForZygote);
                      sZygoteWriter.write(Integer.toString(args.size()));
        }
 
  runSelectLoopMode();
    done = peers.get(index).runOnce();
      forkAndSpecialize()   //Zygote.java (dalvik\libcore\dalvik\src\main\java\dalvik\system)
        Dalvik_dalvik_system_Zygote_forkAndSpecialize() //dalvik_system_Zygote.c (dalvik\vm\native)
          forkAndSpecializeCommon()      
            setSignalHandler()
          RETURN_INT(pid);

           
       ActivityThread main()
         ActivityThread attach() //ActivityThread.java 3870p (frameworks\base\core\java\android\app)     
           mgr.attachApplication(mAppThread)
           //ActivityManagerService.java 4677p (frameworks\base\services\java\com\android\server\am)
           attachApplication()
             //ActivityManagerService.java 4677p (frameworks\base\services\java\com\android\server\am)
             attachApplicationLocked()
               if (realStartActivityLocked(hr, app, tr, tr)) //ActivityManagerService.java 4609p (frameworks\base\services\java\com\android\server\am)
               realStartActivityLocked()
                 //ActivityManagerService.java (frameworks\base\services\java\com\android\server\am)
                 app.thread.scheduleLaunchActivity(new Intent(r.intent), r,r.info, r.icicle, results, newIntents, !andResume,isNextTransitionForward());
                 scheduleLaunchActivity()
                   qOrSendMessage(H.LAUNCH_ACTIVITY, r);
                     ActivityThread.H.handleMessage()
                       handleLaunchActivity()    //ActivityThread.java (frameworks\base\core\java\android\app)
                         performLaunchActivity() //ActivityThread.java (frameworks\base\core\java\android\app)
                           activity = mInstrumentation.newActivity(cl, component.getClassName(), r.intent);

     
             
/////////////////////////////////////////////////       

init 守护进程:
//andriod init 函数启动过程分析:
在main循环中会重复调用
drain_action_q();
restart_processes();
static void restart_processes()
{
    process_needs_restart = 0;
    service_for_each_flags(SVC_RESTARTING,
                           restart_service_if_needed);
}
通过循环检测服务列表service_list 中每个服务的 svc->flags 标记,如果为 SVC_RESTARTING,
那么在满足条件的情况下调用:restart_service_if_needed
通过 service_start 来再次启动该服务。

ActivityManagerService.main





I/SystemServer(   45): Starting Power Manager.
I/ServiceManager(   26): service 'SurfaceFlinger' died
D/Zygote  (   30): Process 45 terminated by signal (11)
I/Zygote  (   30): Exit zygote because system server (45) has terminated
通过错误信息发现程序在调用 SurfaceFlinger服务的时候被中止。
Service_manager.c (frameworks\base\cmds\servicemanager):
LOGI("service '%s' died\n", str8(si->name));
Binder.c (frameworks\base\cmds\servicemanager):
death->func(bs, death->ptr);


Binder.c (kernel\drivers\misc)中的函数
binder_thread_read()
str t binder_work *w;
switch (w->type)
为 BINDER_WORK_DEAD_BINDER 的时候
binder_parse()中
当 cmd 为 BR_DEAD_BINDER的时候
执行 death->func(bs, death->ptr)
因为函数
int do_add_service(str t binder_state *bs,
                   uint16_t *s, unsigned len,
                   void *ptr, unsigned uid)
的 si->death.func = svcinfo_death;
所以 death->func(bs, death->ptr) 实际上执行的是
svcinfo_death()//Service_manager.c (frameworks\base\cmds\servicemanager)
所以会打印出:service 'SurfaceFlinger' died
I/ServiceManager(   26): service 'SurfaceFlinger' died



Thread::run
  _threadLoop() // Threads.cpp (frameworks\base\libs\utils)
    status_t SurfaceFlinger::readyToRun()
      mBootAnimation = new BootAnimation(this);

转自:http://blog.csdn.net/ruixj/archive/2010/05/26/5626820.aspx
  评论这张
 
阅读(2029)| 评论(0)
推荐 转载

历史上的今天

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017