Zygote 服務概論:
Zygote 是android 系統中最重要的一個服務,它將一步一步完成下面的任務:
start Android Java Runtime and start system server. It’s the most important service. The source is in device/servers/app.
1. 建立JAVA 虛擬機
2. 爲JAVA 虛擬機註冊android 本地函數
3. 調用 com.android.internal.os.ZygoteInit 類中的main函數,android/com/android/internal/os/ZygoteInit.java.
a) 裝載ZygoteInit類
b) 註冊zygote socket
c) 裝載preload classes(the default file is device/java/android/preloaded-classes)
d) 裝載Load preload 資源
e) 調用 Zygote::forkSystemServer (定義在./dalvik/vm/InternalNative.c)來fork一個新的進程,在新進程中調用 com.android.server.SystemServer 的main函數。
a) 裝載 libandroid_servers.so庫
bb) 調用JNI native init1 函數 (device/libs/android_servers/com_android_server_SystemServers)
Load libandroid_servers.so
Call
JNI native init1 function implemented in
device/libs/android_servers/com_android_server_SystemServers. It only
calls system_init implemented in
device/servers/system/library/system_init.cpp.
If running on simulator, instantiate A ioFlinger, MediaPlayerService and CameraService here.
Call
init2 function in JAVA class named com.android.server.SystemServer,
whose source is in device/java/services/com/android/server. This
function is very critical for Android because it start all of Android
JAVA services.
If not running on simulator, call IPCThreadState::self()->joinThreadPool() to enter into service dispatcher.
SystemServer::init2 將會啓動一個新的線程來啓動下面的全部JAVA服務:
Core 服務:
1. Starting Power Manager(電源管理)
2. Creating Activity Manager(活動服務)
3. Starting Telephony Registry(電話註冊服務)
4. Starting Package Manager(包管理器)
5. Set Activity Manager Service as System Process
6. Starting Context Manager
7. Starting System Context Providers
8. Starting Battery Service(電池服務)
9. Starting Alarm Manager(鬧鐘服務)
10. Starting Sensor Service
11. Starting Window Manager(啓動窗口管理器)
12. Starting Bl tooth Service(藍牙服務)
13. Starting Mount Service
其餘services:
1. Starting Status Bar Service(狀態服務)
2. Starting Hardware Service(硬件服務)
3. Starting NetStat Service(網絡狀態服務)
4. Starting Connectivity Service
5. Starting Notification Manager
6. Starting DeviceStorageMonitor Service
7. Starting Location Manager
8. Starting Search Service(查詢服務)
9. Starting Clipboard Service
10. Starting Checkin Service
11. Starting Wallpaper Service
12. Starting A io Service
13. Starting HeadsetObserver
14. Starting AdbSettingsObserver
最後SystemServer::init2 將會調用 ActivityManagerService.systemReady 經過發送
Intent.CATEGORY_HOME intent來啓動第一個 activity.還有另一種啓動system server的方法是:
經過名爲 system_server的程序(源代碼:device/servers/system/system_main.cpp)它也是經過
調用 system_init 來啓動 system services,這時候就有個問題:爲何android 有兩種方式啓動system services?
個人猜測是:
My
g ss is that directly start system_server may have synchronous problem
with zygote because system_server will call JNI to start
SystemServer::init2, while at that time zygote may not start JAVA VM
yet. So Android uses another method. After zynote is initialized, fork
a new process to start system services.
Zygote服務啓動的詳細過程:
經過啓動服務列表的 app_process 進程,實際上進入的是
App_main.cpp (frameworks\base\cmds\app_process)
main()
根據 init.rc 中的 –zygote –start-system-server
分別調用的是
runtime.start(」com.android.internal.os.ZygoteInit」,startSystemServer);
或者
runtime.start();
start()函數在 AndroidRuntime.cpp (frameworks\base\core\jni)文件中
從打印信息:
D/AndroidRuntime(
56): >>>>>>>>>>>>>>
AndroidRuntime START
GetStaticMethodID(startClass, 「main」,」([Ljava/lang/String;)V");
從上面的調用能夠看出一類引用的過程都是從 main方法 因此接着調用了 ZygoteInit 類的main方法
main方法主要完成:
1.Register zygote socket, Registers a server socket for zygote command connections
2.Load preload classes(the default file is device/java/android/preloaded-classes).
3.Load preload resources, Load in commonly used resources, so they can be shared across processes.
4.Start SystemServer, Prepare the arguments and fork for the system server process.
具體執行過程以下:
ZygoteInit.java (frameworks\base\core\java\com\android\internal\os)中的mian
main()
registerZygoteSocket()
preloadClasses()
loadLibrary()
Log.i(TAG, "Preloading classes...");
Runtime.loadLibrary
Dalvik_java_lang_Runtime_nativeLoad()
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 A ioFlinger media playback camera service
A ioFlinger::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-req st’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 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 Bl tooth Service.」);
//若是是模擬器,那麼跳過藍牙服務。
// Skip Bl tooth 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); java
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, req stCode, -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()));
}android
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()
q OrSendMessage(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);
資料:
Simple Guide for Porting Android Kernel服務器
http://feixf1974.javaeye.com/blog/187773網絡