dvmLoadNativeCode()
LOGD("Trying to load lib %s %p\n", pathName, classLoader);
System.loadLibrary("media_jni");
preloadResources();
startSystemServer()
Zygote.forkSystemServer(parsedArgs.uid, parsedArgs.gid,parsedArgs.gids, debugFlags, null);
//Zygote.java (dalvik\libcore\dalvik\src\main\java\dalvik\system)
forkSystemServer()
forkAndSpecialize() //Zygote.java (dalvik\libcore\dalvik\src\main\java\dalvik\system)
Dalvik_dalvik_system_Zygote_forkAndSpecialize() //dalvik_system_Zygote.c (dalvik\vm\native)
Dalvik_dalvik_system_Zygote_forkAndSpecialize()
setSignalHandler()
fork()
handleSystemServerProcess() //handleChildProc(parsedArgs, descriptors, newStderr);
closeServerSocket();
RuntimeInit.zygoteInit(parsedArgs.remainingArgs);
zygoteInit() //RuntimeInit.java (frameworks\base\core\java\com\android\internal\os)
zygoteInitNative()
invokeStaticMain()
System.loadLibrary("android_servers");
//com.android.server.SystemServer startSystemServer() 函数中
m = cl.getMethod("main", new Class[] { String[].class });
//执行的是SystemServer 类的main函数 SystemServer.java (frameworks\base\services\java\com\android\server)
init1() //SystemServer.java (frameworks\base\services\java\com\android\server)
//init1()实际上是调用android_server_SystemServer_init1(JNIEnv* env, jobject clazz)
//com_android_server_SystemServer.cpp (frameworks\base\services\jni)
android_server_SystemServer_init1()//JNI 调用
system_init() //System_init.cpp (frameworks\base\cmds\system_server\library)
// Start the SurfaceFlinger
SurfaceFlinger::instantiate();
//Start the AudioFlinger media playback camera service
AudioFlinger::instantiate();
MediaPlayerService::instantiate();
CameraService::instantiate();
//调用 SystemServer 类的init2
runtime->callStatic("com/android/server/SystemServer", "init2");
init2()//SystemServer.java (frameworks\base\services\java\com\android\server)
ServerThread()
run()//在run中启动电源管理,蓝牙,等核心服务以及状态,查找等其他服务
((ActivityManagerService)ServiceManager.getService("activity")).setWindowManager(wm);
...
ActivityManagerNative.getDefault().systemReady();
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);
closeServerSocket();
见附A
主進程runSelectLoopMode()
5.Runs the zygote process's select loop runSelectLoopMode(), Accepts new connections as they happen, and reads commands from connections one spawn-request'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", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
//读取属性服务器,开启启动 SurfaceFlinger服务
//接着会开始显示机器人图标
//BootAnimation.cpp (frameworks\base\libs\surfaceflinger):status_t BootAnimation::readyToRun()
SurfaceFlinger::instantiate();
}
//在模拟器上 audioflinger 等几个服务与设备上的启动过程不一样,所以
//我们在这里启动他们。
if (!proc->supportsProcesses()) {
//启动 AudioFlinger,media playback service,camera service服务
AudioFlinger::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 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;
}
System server: entering thread pool 表明已经进入服务线程 ServerThread
在 ServerThread 类的run 服务中开启核心服务:
@Override
public 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 Bluetooth Service.");
//如果是模拟器,那么跳过蓝牙服务。
// Skip Bluetooth 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 (INCLUDE_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 Audio 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 value matches the secure property value
Settings.Secure.putInt(mContentResolver, Settings.Secure.ADB_ENABLED,
"1".equals(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, requestCode, -1, -1,
onlyIfNeeded, componentSpecified);
public 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, true, false); //2439L 定义:1628L
realStartActivityLocked() //1640L 定义:1524L
//1651L 定义:1654L
startProcessLocked(r.processName, r.info.applicationInfo, true, 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)
,&,nbsp; forkAndSpecializeCommo,n()
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, true, true)) //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()
queueOrSendMessage(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_queue();
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()
struct 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(struct 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);