到底是怎么wwW46fg回事为什么不管了鹿姐,老是无法46fgcOm登陆上去

Recommended for you:
Init is the starting point of all Linux applications, and Zygote Android, as it means in English, is all Java programs' incubator '(played Zerg brother know). The PS output can be see
&adb shell ps | grep -E 'init|926'
32 ffffffff b76801e0 S zygote
20 ffffffff b767fff6 S system_server
52 ffffffff b76819eb S com.android.systemui
24 ffffffff b76819eb S com.android.inputmethod.latin
16 ffffffff b76819eb S com.android.phone
44 ffffffff b76819eb S com.android.launcher
16 ffffffff b76819eb S com.android.providers.calendar
28 ffffffff b76819eb S com.android.musicfx
92 ffffffff b76819eb S android.process.acore
04 ffffffff b76819eb S com.android.calendar
Init zygote is the parent process, and the application of system_server and all other com.xxx ending are from zygote to fork. This paper will figure chart (secondary to a small amount of code) way to describe Zygote, system server and start the process of Android Application.
Cut the crap, presented the two big picture on our tour of Zygote. The first picture is Zygote related to all kinds of structure, the other one is the flow chart of Zygote promoter.
How to start the process of decomposition, we Zygote one one according to the drawing in a serial number.
1. App_Process
The application of APP_Process: to start the zygote and other Java programs, the code is in frameworks/base/cmds/app_process/app_main.cpp, specified in the init.rc.
service zygote /system/bin/app_process -Xzygote /system/bin --zygote --start-system-server
The following code
...else if (strcmp(arg, "--zygote") == 0) {
zygote = true;
niceName = "zygote";
} else if (strcmp(arg, "--start-system-server") == 0) {
startSystemServer = true;
} else if (strcmp(arg, "--application") == 0) {
application = true;
if (zygote) {
runtime.start("com.android.internal.os.ZygoteInit",
startSystemServer ? "start-system-server" : "");
} else if (className) {
// Remainder of args get passed to startup class main()
runtime.mClassName = classN
runtime.start("com.android.internal.os.RuntimeInit",
application ? "application" : "tool");
As you can see, app_process defines three types of applications:
com.android.internal.os.ZygoteInit
System Server, Not only, but by the Zygote promoter
Specify the name of the class of 3 other Java programs, such as the commonly used am. /system/bin/am is a shell program, it really is& & &
exec app_process $base/bin com.android.commands.am.Am "$@"
The application of these Java is through the AppRuntime.start (className) began. From the first big picture can be seen, in fact, AppRuntime is a subclass of AndroidRuntime, it mainly implements several callback function, and the start () method is implemented in AndroidRuntime this class. What is AnroidRuntime? Then we start.
Need to pay attention to is the first program in Zygote and not Init promoter, can be seen from the PID, before it, the important System Daemon Native implementation (background processes) may go up, such as ServiceManager (service DNS service).
2. AndroidRuntime
First of all, what is Runtime? Have a look of several Wiki give the explanation: & & &
Run time (program lifecycle phase), the period during which a computer program is executing
Runtime library, a program library designed to implement functions built into a programming language
I prefer here refers to the latter, have a look further explanation:
In computer programming, a runtime library is the API used by a compiler to invoke some of the behaviors of a runtime system. The runtime system implements the execution model and other fundamental behaviors of a programming language. The compiler inserts calls to the runtime library into the executable binary. During execution (run time) of that computer program, execution of those calls to the runtime library cause communication between the application and theruntime system. This often includes functions for input and output, or for memory management.
To sum up means that, Runtime is supporting base running, it is bound together with language. For example:
C Runtime: Is the C standard lib, is what we often say that the libc. (interestingly, Wiki will automatically redirect to & C runtime " "C Standard Library").
Java Runtime:, Wiki will be redirected to & Java Virtual Machine ", here of course includes a support library Java(.jar).
AndroidRuntime: obviously, is required for the Android application runtime environment. This environment includes the following.:
Java VM Dalvik VM: Android, explain the operation Dex format Java program. Each process running a virtual machine (what is called a virtual machine? To put it bluntly, is that some C code, stop the binary code to explain the Dex format (Bytecode), converted into machine code (Machine code), then, of course, now most of the Java virtual machine supports JIT, that is to say, bytecode may be in operation before it has been converted into machine code, which greatly improves the performance of. In the past a common understanding is the Java procedure than the C, C++, static compilation language slowly, but with the intervention and the development of JIT, this is already the past, run dynamic JIT allows virtual machine according to the runtime environment, generating optimized machine code, in some cases, Java can even than C/C++ run faster, and at the same time both platform independent characteristic, which is why Java is so popular is one of the reasons).
The Java class library Android, most from Apache Hamony, Java API open source implementations, such as java.lang, java.util, java.net. but removed AWT, Swing etc.
JNI: C and Java intermodulation interface.
Libc: Android also has a lot of C code, nature is little not the libc, that is, Android libc bionic C.
& &&& OK, Then you have a look AndroidRuntime is how to build up.
This gives Zygote start about process., Entrance is AndroidRuntime.start (), according to the arguments passed different can have two types of startup mode, One is "com.android.internal.os.RuntimeInit", another is "& com.android.internal.os.ZygoteInit, RuntimeInit and ZygoteInit of two types of corresponding,
Figure with green and pink, respectively. The main difference between the two types of lies in the Java end, can clearly see that, compared to ZygoteInit RuntimeInit to do a lot of things, such as & preload "," GC "etc. But in the end Native, they all do the same thing, startVM () and startReg (), let us begin from here.
& & & See from the diagram, JavaVM and JNIEnv are the only two levels between AndroidRuntim and Dalvik VM, it hides the implementation details, Dalvik. In fact, he is the two function pointer structure, provides access to the Java resource interface to the native code. JNIEnv is relative to the thread, through the JNIEnv pointer can be mapped to Thread Dalvik VM inside the body, all calls on this structure context. The JavaVM corresponds to the DVMGlobal, a process only structure inside, he maintains a thread queue threadList, each Thread object storage structure, and various state object list, structure and GC storage body, etc. This paper briefly introduces not deep,.
JavaVM and JNIENV
struct _JavaVM {
const struct JNIInvokeInterface* //The C function pointer
#if defined(__cplusplus)
jint GetEnv(void** env, jint version)
{ return functions-&GetEnv(this, env, version); }
#endif /*__cplusplus*/
struct JNIInvokeInterface {
reserved0;
(*DestroyJavaVM)(JavaVM*);
(*AttachCurrentThread)(JavaVM*, JNIEnv**, void*);
(*DetachCurrentThread)(JavaVM*);
(*GetEnv)(JavaVM*, void**, jint);
(*AttachCurrentThreadAsDaemon)(JavaVM*, JNIEnv**, void*);
GetEnv is the most common interface (inside), it returns a JNIEnv object, corresponding to each DVM thread. The definition of JNIEnv is very long, interested students can go to Jni.h, here we only have a look this object is how to obtain the jint GetEnv static(JavaVM* vm, void** env, jint version) {
Thread* self = dvmThreadSelf(); //Gets the current thread object.
if (version &JNI_VERSION_1_1 || version & JNI_VERSION_1_6) {
return JNI_EVERSION;
} //Check the version number, corresponding to 4.3 Android 1.6
*env = (void*) dvmGetThreadJNIEnv(self);
//Very simple, see the bottom line
dvmChangeStatus(self, THREAD_NATIVE);
return (*env != NULL) ? JNI_OK : JNI_EDETACHED;
INLINE JNIEnv* dvmGetThreadJNIEnv(Thread* self) { return self-&jniEnv; }
Is very simple, is originally from the structure of the thread object can be read, there seems no JavaVM. What do you want, why when parameter? Don't know, maybe Google is reserved for future expansion? But no matter how, want to call GetEnv, or JavaVM. Future is to write JNI code of the students can refer to the following code to see how to get JavaVM and JniENV.
JNIEnv* AndroidRuntime::getJNIEnv()
JavaVM* vm = AndroidRuntime::getJavaVM();
assert(vm != NULL);
if (vm-&GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK)
return NULL;
Here, we know that JavaVM and JNIEnv are local (C/C++) code used for intermodulation and Java code in Java the end, that is the Java virtual machine and the corresponding Java application. The Java virtual machine is what Dongdong, it is how to create? The answer from the AndroidRuntime:: startVM () function to start. startVM
int AndroidRuntime::startVm(JavaVM** pJavaVM, JNIEnv** pEnv)
property_get("dalvik.vm.checkjni", propBuf, "");
initArgs.version = JNI_VERSION_1_4;
//Create VM and return to JavaVM and JniEnv, pEnv corresponds to the current thread.
if (JNI_CreateJavaVM(pJavaVM, pEnv, &initArgs) &0) {
ALOGE("JNI_CreateJavaVM failed\n");
jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
memset(&gDvm, 0, sizeof(gDvm)); /* Here is the real VM structure*/
JavaVMExt* pVM = (JavaVMExt*) calloc(1, sizeof(JavaVMExt));
pVM-&funcTable = &gInvokeI //The initialization function pointer
pVM-&envList = NULL;
gDvmJni.jniVm = (JavaVM*) pVM; //Native JavaVM the original code with just JniVm.
JNIEnvExt* pEnv = (JNIEnvExt*) dvmCreateJNIEnv(NULL); //Create a JNIEnv, because the virtual machine to initialize the next need to access the C/C++ implementation
/* To start the initialization. */
gDvm.initializing = true;
std::string status =
dvmStartup(argc, argv.get(), args-&ignoreUnrecognized, (JNIEnv*)pEnv);
gDvm.initializing = false;
dvmChangeStatus(NULL, THREAD_NATIVE);
*p_env = (JNIEnv*) pE
*p_vm = (JavaVM*) pVM;
return JNI_OK;
std::string dvmStartup(int argc, const char* const argv[],
bool ignoreUnrecognized, JNIEnv* pEnv)
* Check the input and initializing parameters
int cc = processOptions(argc, argv, ignoreUnrecognized);
/* The real start initialization initialization, each module inside, and create a series of thread*/
if (!dvmAllocTrackerStartup()) {
return "dvmAllocTrackerStartup failed";
if (!dvmGcStartup()) {
return "dvmGcStartup failed";
if (!dvmThreadStartup()) {
return "dvmThreadStartup failed";
if (!dvmInlineNativeStartup()) {
return "dvmInlineNativeStartup";
if (!dvmRegisterMapStartup()) {
return "dvmRegisterMapStartup failed";
if (!dvmInstanceofStartup()) {
return "dvmInstanceofStartup failed";
if (!dvmClassStartup()) {
return "dvmClassStartup failed";
if (!dvmNativeStartup()) {
return "dvmNativeStartup failed";
if (!dvmInternalNativeStartup()) {
return "dvmInternalNativeStartup failed";
if (!dvmJniStartup()) {
return "dvmJniStartup failed";
if (!dvmProfilingStartup()) {
return "dvmProfilingStartup failed";
if (!dvmInitClass(gDvm.classJavaLangClass)) {
return "couldn't initialized java.lang.Class";
if (!registerSystemNatives(pEnv)) {
return "couldn't register system natives";
if (!dvmCreateStockExceptions()) {
return "dvmCreateStockExceptions failed";
if (!dvmPrepMainThread()) {
return "dvmPrepMainThread failed";
if (dvmReferenceTableEntries(&dvmThreadSelf()-&internalLocalRefTable) != 0)
ALOGW("Warning: tracked references remain post-initialization");
dvmDumpReferenceTable(&dvmThreadSelf()-&internalLocalRefTable, "MAIN");
if (!dvmDebuggerStartup()) {
return "dvmDebuggerStartup failed";
if (!dvmGcStartupClasses()) {
return "dvmGcStartupClasses failed";
if (gDvm.zygote) {
if (!initZygote()) {
return "initZygote failed";
if (!dvmInitAfterZygote()) {
return "dvmInitAfterZygote failed";
return "";
The Java virtual machine to start with too many details can not be carried out here, here we only need to know it to do the following things:
1 property read from a series of boot parameters. 2 create and initialize the structure of global object (each process) gDVM, the internal structure and the corresponding to the JavaVM and JNIEnv JavaVMExt, JNIEnvExt.3 to initialize the Java virtual machine, and create the virtual machine thread. "PS -t", you can find that each Android applications have the following thread
//Garbage collection
S Signal Catcher
//Java debugging
S Compiler
S ReferenceQueueD
S FinalizerDaemon
//Finalizer monitoring
S FinalizerWatchd
4 registration system JNI, Java program through the JNI interface to access the underlying resources.
loadJniLibrary("javacore");
loadJniLibrary("nativehelper");
5 for the Zygote to start the final preparations, including setting up SID/UID, and mount file system. 6 returns the JavaVM to the Native code, so it can be to access the Java interface. In addition to the JNI interface system (& javacore "," nativehelper "), Android framework and the amount of Native, Android will all these interfaces one-time through start_reg () to complete the,
startReg()
int AndroidRuntime::startReg(JNIEnv* env){
androidSetCreateThreadFunc((android_create_thread_fn) javaCreateThreadEtc); //Create a JVM can access the thread must through specific interfaces.
env-&PushLocalFrame(200);
if (register_jni_procs(gRegJNI, NELEM(gRegJNI), env) &0)
env-&PopLocalFrame(NULL);
return -1;
env-&PopLocalFrame(NULL);
Android native two Thread to create mode:
#threads.cpp
status_t Thread::run(const char* name, int32_t priority, size_t stack)
if (mCanCallJava) {
res = createThreadEtc(_threadLoop, this, name, priority, stack, &mThread);
res = androidCreateRawThreadEtc(_threadLoop,this, name, priority, stack, &mThread);
The difference between them is whether to invoke Java end function, common thread is the pthread_create package.
int androidCreateRawThreadEtc(android_thread_func_t entryFunction,
void *userData,
const char* threadName,
int32_t threadPriority,
size_t threadStackSize,
android_thread_id_t *threadId)
int result = pthread_create(&thread, &attr,android_pthread_entry)entryFunction, userData);
And access to the Java end of the thread needs to be bound to JVM, the following is the function of concrete& & & & &
#AndroidRuntime.cpp
int AndroidRuntime::javaCreateThreadEtc(
android_thread_func_t entryFunction,
void* userData,
const char* threadName,
int32_t threadPriority,
size_t threadStackSize,
android_thread_id_t* threadId)
args[0] = (void*) entryF //The entryFunc is temporarily stored in args[0]
args[1] = userD
args[2] = (void*) strdup(threadName);
result =AndroidCreateRawThreadEtc(AndroidRuntime::javaThreadShell, args, threadName, threadPriority, threadStackSize, threadId); //EntryFunc into javaThreadShell.
int AndroidRuntime::javaThreadShell(void* args) {
void* start = ((void**)args)[0];
void* userData = ((void **)args)[1];
char* name = (char*) ((void **)args)[2];
// we own this storage
/* With the VM binding */
if (javaAttachThread(name, &env) != JNI_OK)
return -1;
/* Run the real'entryFunc' */
result = (*(android_thread_func_t)start)(userData);
/* unhook us */
javaDetachThread();
attachVM() What things? The limited space can not be carried out, only need to know so few points:
There is a Java virtual machine a process, internal Java virtual machine has many threads, such as listed above to GC, FinalizeDaemon, and user created thread and so on.
Each Java thread maintains a JNIEnvExt object, which store a pointer to the DVM internal Thread object, that is to say, all calls from native to Java terminal, can refer to the object.
All the JVM created thread will be inside the VM record, but at present, we have not entered into the Java world, locally created thread VM naturally do not know, so we need the attach to notify VM to create the corresponding data structure.
Have a look the following code, you'll see, in fact, the Attach () is one important thing to do is to create a thread and JNIEnvExt.
bool dvmAttachCurrentThread(const JavaVMAttachArgs* pArgs, bool isDaemon)
Thread* self = NULL;
self = allocThread(gDvm.stackSize);
self-&jniEnv = dvmCreateJNIEnv(self);
gDvm.threadList-&next =
threadObj = dvmAllocObject(gDvm.classJavaLangThread, ALLOC_DEFAULT);
vmThreadObj = dvmAllocObject(gDvm.classJavaLangVMThread, ALLOC_DEFAULT);
self-&threadObj = threadO
Finished, began to register the JNI interface function local - register_jni_procs (), this function is actually to a global array gRegJni[] traversal call, the array expansion can get the following results
static const RegJNIRec gRegJNI[] = {
{register_android_debug_JNITest},
{register_com_android_internal_os_RuntimeInit}.
Each register_xxx is a function pointer
int jniRegisterNativeMethods(
C_JNIEnv* env,
const char* className,
const JNINativeMethod* gMethods,
int numMethods);
RegisterNativeMethods inside the VM, what happened? Also, here only need to know the following points.:
Well, after go through untold hardships, the Android runtime environment is ready, let's review the AndroidRuntime initialization what job to do,
Create a Dalvik VM.
The two interface object to obtain Native to access the Java, JavaVM and JNIENV.
Registered a number (see gRegJni[]) native interface for VM.
These operations are relatively time-consuming, if each process to do the same work is bound to affect the start-up speed, which is why we need the Zygote to create Android applications, because the mechanism through Linux fork copy_on_write, the sub process can the initialized memory mapped directly to its own process space., do not repeat work in need, so as to improve the application start speed.
May be, Android systems only need basic runtime environment is enough? The obvious answer is No. AndriodRuntime only provides a basic language level support, in a multi tasking operating system, graphics user fast hatching and run the application, we need more. This is the Zygote, which is why in Figure 2, the ZygoteInit will do more than RuntimeInit. Then, let us enter the real world of Zygote.
3. ZygoteInit
When the VM is ready, you can run the Java code, the system will also be the first to enter the Java world, remember app_main.cpp to Runtime.start () parameters, that is we want to run the Java class. Android supports two types as the starting point, one is & com.android.internal.os.ZygoteInit', another is'com.android.internal.os.RuntimeInit', ZygoteInit and RuntimeInit have what distinction? Have a look first joint part of their:
redirectLogStreams(): The System.out and System.err output redirected to Android Log system (defined in android.util.Log).
commonInit(): Initialize the system properties, one of the most important point is to setup a did not catch the exception of handler, when the code of any unknown exception, will perform it, debugging Android code of the students often see "* * * FATAL EXCEPTION IN SYSTEM PROCESS" printed on from here:
RuntimeInit the next work is relatively simple, back to the Native layer to create a Binder for Thread, and then began to run on the current Thread to jump to the Java code.
While ZygoteInit has done so many things, let us one one detailed analysis.
&&&&& 1. registerZygoteSocket();
&&&&& 2. startSystemServer();
&&&&& 3. runSelectLoopMode();
RegisterZygoteSocket()
In fact, do very simple, is to initialize the Server end (or Zygote) socket. It is worth mentioning that, here the use of the socket type is LocalSocket, it is a package of Android on Linux Local Socket. Local Socket is a Linux provides a means of communication among process based on Socket, on the Server end, the only difference is the bind to a local file descriptor (FD) rather than an IP address and port number. Android is used in many places Local Socket interprocess communication, init.rc search, you will see many such statements:
socket adbd stream 660 system system
socket vold stream 0660 root mount
socket netd stream 0660 root system
socket dnsproxyd stream 0660 root inet
socket mdns stream 0660 root system
socket rild stream 660 root radio
socket rild-debug stream 660 radio system
socket zygote stream 660 root system
socket installd stream 600 system system
socket racoon stream 600 system system
socket mtpd stream 600 system system
socket dumpstate stream 0660 shell log
socket mdnsd stream 0660 mdnsr inet
When the init analysis to such a statement, it will do a few things:
The 1 call create_socket () (system/core/init/util.c), create a Socket FD, the FD and a file (/dev/socket/xxx, XXX is listed above to name, for example, zygote) binding (bind), to set the user according to the init.rc definition, groups and permissions. Finally, return to the FD. & & & & &
2 the socket name (with & the ANDROID_SOCKET_'prefix) (such as zygote) and FD registered to the init process environment variables, so that all the other processes (all processes are init Zi Jincheng) are available through getenv (name) access to the fd.
ZygoteInit to complete the Socket Server terminal configuration by the following code:
private static final String ANDROID_SOCKET_ENV = "ANDROID_SOCKET_zygote";private static void registerZygoteSocket() {
String env = System.getenv(ANDROID_SOCKET_ENV);
fileDesc = Integer.parseInt(env);
sServerSocket = new LocalServerSocket(
createFileDescriptor(fileDesc));
The Server is created, you can then the corresponding client connection requests. We mentioned earlier, AndroidRuntime is a complex series of initialization work through fork to help the child process to simplify this process, the Zygote created Socket, server terminal is in response to the fork request. Who is that initiated the request? Who is the Zygote fork sub process? The answer is ActivityManagerService and Android Application. this process? The answer lies in the starting procedure of Andriod System in Server.
preload() Do two things:
static void preload() {
preloadClasses();
preloadResources();
This is the two thing is the most time consuming the Android startup process. PreloadClassess class load preloaded-classes framework.jar all the definition in the preloaded-classes compiler into memory, Android can be found in the framework/base. While the preloadResources system Resource (not defined in the user in the APK resource load into memory).
Resource preload to Zygoted of process address space, all the fork process will share this space without the need to load, which greatly reduces the application startup time, but increases the system boot time. Through adjusting the preload classes and the number of resources you can speed up the startup.
static void gc() {
final VMRuntime runtime = VMRuntime.getRuntime();
System.gc();
runtime.runFinalizationSync();
System.gc();
runtime.runFinalizationSync();
System.gc();
runtime.runFinalizationSync();
&&& Why is the System.gc (3) and runFinalizationSync ()? This is because the GC (VM) call just notice for garbage collection, whether the recovery, when recovery and VM algorithm. The recovery of GC have a complex state machine control, through repeated calls, can make as much as possible resources recovery. gc()Must be completed before fork (the next StartSystemServer will have fork operation), so that the future is to copy out the child process can be as little as possible memory space is pre occupied.
Start SystemServer
Think of the parameter init.rc to start zygote.,
"--start-system-server", System Server is the first Java process Zygote fork,
This process is very important, Because they have a lot of system threads, System service provides all of the core., We can use the'ps -t |grep &system server pid& 'to have a look what thread, Out of several Java virtual machine thread above, Also
b76c4ab6 S SensorService
b76c49eb S er.ServerThread
b76c49eb S UI
b76c49eb S WindowManager
b76c49eb S ActivityManager
b76c4d69 S ProcessStats
b76c2bb6 S FileObserver
b76c49eb S PackageManager
b76c49eb S AccountManagerS
b76c49eb S PackageMonitor
b76c4ab6 S UEventObserver
b76c4d69 S BatteryUpdateTi
b76c49eb S PowerManagerSer
b76c2ff6 S AlarmManager
b76c4d69 S SoundPool
b76c4d69 S SoundPoolThread
b76c49eb S InputDispatcher
b76c49eb S InputReader
b76c49eb S BluetoothManage
b76c49eb S MountService
b76c4483 S VoldConnector
b76c49eb S CallbackHandler
b76c4483 S NetdConnector
b76c49eb S CallbackHandler
b76c49eb S NetworkStats
b76c49eb S NetworkPolicy
b76c49eb S WifiP2pService
b76c49eb S WifiStateMachin
b76c49eb S WifiService
b76c49eb S ConnectivitySer
b76c49eb S WifiManager
b76c49eb S Tethering
b76c49eb S CaptivePortalTr
b76c49eb S WifiWatchdogSta
b76c49eb S NsdService
b76c4483 S mDnsConnector
b76c49eb S CallbackHandler
b76c49eb S SyncHandlerThre
b76c49eb S AudioService
b76c49eb S backup
b76c49eb S AppWidgetServic
44 c4d69 S AsyncTask #1
44 c42a3 S Thread-64
44 c4d69 S AsyncTask #2
b76c2bb6 S UsbService host
b76c4d69 S watchdog
b76c49eb S LocationManager
b76c2ff6 S Binder_3
b76c49eb S CountryDetector
b76c49eb S NetworkTimeUpda
b76c2ff6 S Binder_4
b76c2ff6 S Binder_5
b76c2ff6 S Binder_6
b76c2ff6 S Binder_7
b76c4d69 S SoundPool
b76c4d69 S SoundPoolThread
44 c4d69 S AsyncTask #3
44 c4d69 S AsyncTask #4
44 c4d69 S AsyncTask #5
44 c4d69 S pool-1-thread-1
b76c4d69 S AudioTrack
44 c49eb S KeyguardWidgetP
See the famous WindowManager, ActivityManager? Yes, they are running in the system_server process. There are a lot of & Binder-x "thread, they are all Service in response to application of remote calls and create. In addition, there are a lot of internal thread, such as & UI thread "," InputReader "," InputDispatch "and so on, we will in the following article will analyze these modules. In this paper, we are concerned only with System Server is how to create.
4 System Server boot process
This code a lot, involves a lot of class, we describe this process with a sequence diagram. The colors in the image represent running on a different thread.
1ZygoteInit fork. A new process, this process is SystemServer process.
2The child process in fork.handleSystemServerProcess In the beginning of initialization, the initialization is divided into two steps, one in native, the other part (most) in Java terminal. Native work in AppRuntime (subclass AndroidRuntime): onZygoteInit (), one thing to do is to start a Thread, the Thread is the main SystemServer thread (the pink box), responsible for receiving Binder calls to other processes. The following code
void ProcessState::spawnPooledThread(bool isMain)
if (mThreadPoolStarted) {
String8 name = makeBinderThreadName(); //&Binder_1"
sp&Thread& t = new PoolThread(isMain);
t-&run(name.string());
}virtual bool threadLoop() {
IPCThreadState::self()-&joinThreadPool(mIsMain); //Blocking know by Binder driver wake up& &
3. nativeZygoteInit() After the completion of the beginning of the next layer, Java initialization, this process is long, complicated, we divided into many steps to explain. The initialization of the entrance is SystemServer main () function, here called the Native Init1 (Init1). In com_android_server_SystemServer.cpp, the function call to system_init (system_init) () is implemented as follows.:
extern "C" status_t system_init()
sp&ProcessState& proc(ProcessState::self());
sp&IServiceManager& sm = defaultServiceManager();
sm-&asBinder()-&linkToDeath(grim, grim.get(), 0);
property_get("system_init.startsurfaceflinger", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the SurfaceFlinger
SurfaceFlinger::instantiate(); //The initialization of SurfaceFlinger
android_vt = 7;
property_get("system_init.startsensorservice", propBuf, "1");
if (strcmp(propBuf, "1") == 0) {
// Start the sensor service
SensorService::instantiate(); // The initialization of SensorService.
ALOGI("System server: starting Android runtime.\n");
AndroidRuntime* runtime = AndroidRuntime::getRuntime();
JNIEnv* env = runtime-&getJNIEnv();
jclass clazz = env-&FindClass("com/android/server/SystemServer");
jmethodID methodId = env-&GetStaticMethodID(clazz, "init2", "()V");
env-&CallStaticVoidMethod(clazz, methodId);
ProcessState::self()-&startThreadPool();
IPCThreadState::self()-&joinThreadPool();
return NO_ERROR;
Pay attention to several points:
A. SurfaceFlinger Service can be run in the System_Server process, can also be run in a separate process, if the latter is the case, need to add a sentence "init.rc setprop system_init.startsurfaceflinger=1" and ensure that service surfaceflinger is not &disable&
B. init2 is implemented in System_Server.java, we will detail.
4. system_init() Finally, the join_threadpool () of the current thread hang, waiting for the binder request. The thread name is "Binder_1". The internal mechanism for service and binder, please refer to the article
5Init2: so far, system server native initialization is complete, return to the Java terminal, here, a lot of very important system service will be launched.
These work will begin on a new thread, the thread name "android.server.ServerThread", the green bar. In ServerThread, SystemServer first creates two threads, UI thread and WindowManager thread, see the orange and peach slices, the two thread handle will be passed to the Service constructor, part of the start-up will be distributed to the two of Thread.
Each Thread is entering the final wait loop, the mechanism of Looper, Android Looper, Handler Android processes within the message delivery and processing mechanism, we will in this article in detail, here, we just need to know, Looper in a thread sleep for message queuing in the news, then in some a specific Handler to process the message. In other words, specify something processed in a thread.
6Next, System Server will launch a series of Service, one of the most important is the Acitivity Manager and Window Manager.
As can be seen from the graph, the Activity Manager has a Looper Thread, AThread. Please notice the difference between Binder Thread and Looper, we will have a special article describes them in behind. The Android amount used a combination of Binder and Looper, which is a very important reason is that in order to solve the synchronization problem of complex multi thread, through a Looper and the corresponding Message queue, can be a different process Binder call serialization, without the need to maintain complex and problematic lock.
His Handler Thread is similar to WindowManager, which we have just mentioned, one of the two Handler System server to start early to create threads, WMThread. his Binder thread by Kernel Binder Driver to specify.
In addition to ActivityManager Service and WindowManager Service, there are many other services have been started, not detailed here, just need to know a few steps needed to start Service:
&&&&& 1 initializing the Service object, IBinder object.
&&&&& 2 starting the background thread, and enter the Loop wait.
&&&&& 3 will register itself with the Service Manager object by name, so that other processes can be remote calls must be IBinder.
7No doubt, among so many services are dependent, for example, ActivityManager Service is unable to start the application before the WindowManager Service initialization is complete. How to control the order? Here by the System server start thread (green stripe below fast) through the SystemReady () interface to complete the. The realization of a SystemReady for each system service must be () interface, when invoked, show that the system has OK, the service can be accessed (directly or indirectly) other service resources. The last one was transferred to the service is AcitivyManager Service. AM (SystemReady) by Runnable in another thread, the arrow in the note 8 below. To do this Runnable thing, is the current row start - in an application of resumeTopActivityLocked (top), generally speaking, this is what we often say that the & HOME&, of course, here you can specify other applications as Startup applications, such as GoogleTV TV can be used as the start. The program, so that the user can see the program directly after the restart, similar to today's home set-top box. In addition, ActivityManager Service also broadcasts the BOOT_COMPLETED event for the whole system, in general, many application background Service can register the Event Receiver to monitor and start. Start the Home code.
boolean startHomeActivityLocked(int userId) {
Intent intent = new Intent(...);
... intent.addCategory(Intent.CATEGORY_HOME);
mMainStack.startActivityLocked(null, intent, null, aInfo,null, null, 0, 0, 0, null, 0, null, false, null);
8. Application of Android initiation complex, We will go to study in detail the ActivityManager special sections work, Here, We only need to know that ActivityStack is currently running the Activity stack, resumeTopActivityLocked() From where to find that one should start (in the beginning, The stack is empty, As required by moveTaskFromFrontLocked (& Home') onto the stack), If the application has never start, We need to create a process for AcitivyManagerService. Be careful. Progress is not created by ActivityManager, don't forget, we mentioned Zygote is the incubator, all Android applications on ActivityManager, just notice Zygote creation. This communication is implemented by Process.java, the specific code is as follows:
static LocalSocket sZygoteS
private static ProcessStartResult zygoteSendArgsAndGetResult(ArrayList&String& args)
throws ZygoteStartFailedEx {
openZygoteSocketIfNeeded();
sZygoteWriter.write(arg);
sZygoteWriter.flush(); //Send for...
result.pid = sZygoteInputStream.readInt();
sZygoteSocket = null;
So far, System Server start has been completed, the Zygote promoter has been completed, the next we introduce Zygote process in life to do only one thing, clone themselves.
Before Process.java sends a fork request, Zygote is ready to the server, this we have in front of the Zygote Init chapter introduced. Here we briefly analyze the Zygote Server terminal receives the request processing. The code in the ZygoteInit.java (runSelectLoop).,
private static void runSelectLoop() throws MethodAndArgsCaller {
ArrayList&FileDescriptor& fds = new ArrayList&FileDescriptor&();
ArrayList&ZygoteConnection& peers = new ArrayList&ZygoteConnection&();
FileDescriptor[] fdArray = new FileDescriptor[4];
fds.add(sServerSocket.getFileDescriptor());
peers.add(null);
while (true) {
/* Before the fork sub process do GC rather than do in each sub process, can improve efficiency, but also can not always do because GC is still very time-consuming. */
if (loopCount &= 0) {
loopCount = GC_LOOP_COUNT;
loopCount--;
fdArray = fds.toArray(fdArray);
index = selectReadable(fdArray); //Select blocking wait
} catch (IOException ex) {
/* Accepting new connections */
else if (index == 0) {
ZygoteConnection newPeer = acceptCommandPeer();
peers.add(newPeer);
fds.add(newPeer.getFileDesciptor());
/* To complete the fork operation here. */
done = peers.get(index).runOnce();
if (done) {
peers.remove(index);
fds.remove(index);
boolean runOnce() throws ZygoteInit.MethodAndArgsCaller {
args = readArgumentList();
descriptors = mSocket.getAncillaryFileDescriptors();
} catch (IOException ex) {
FileDescriptor childPipeFd = null;
FileDescriptor serverPipeFd = null;
if (parsedArgs.runtimeInit && parsedArgs.invokeWith != null) {
& & & & & &
FileDescriptor[] pipeFds = Libcore.os.pipe(); & & & & & &
childPipeFd = pipeFds[1];
& & & & & &
serverPipeFd = pipeFds[0];
& & & & & &
ZygoteInit.setCloseOnExec(serverPipeFd, true);
parsedArgs = new Arguments(args);
applyUidSecurityPolicy(parsedArgs, peer, peerSecurityContext);
pid = Zygote.forkAndSpecialize(parsedArgs.uid,parsedArgs.gid, parsedArgs.gids,parsedArgs.debugFlags, rlimits, parsedArgs.mountExternal, parsedArgs.seInfo,parsedArgs.niceName);
} catch (IOException ex) {
if (pid == 0) {
// The child process, release serverFd
serverPipeFd = null;
handleChildProc(parsedArgs, descriptors, childPipeFd, newStderr);
// The parent process, will not use the sub processes of PipeFd release
IoUtils.closeQuietly(childPipeFd);
childPipeFd = null;
return handleParentProc(pid, descriptors, serverPipeFd, parsedArgs);
} finally {
IoUtils.closeQuietly(childPipeFd);
IoUtils.closeQuietly(serverPipeFd);
Android application startup done in handleChildProc:
private void handleChildProc(Arguments parsedArgs,
FileDescriptor[] descriptors, FileDescriptor pipeFd, PrintStream newStderr)
throws ZygoteInit.MethodAndArgsCaller {
closeSocket(); // Don't need a server socket
ZygoteInit.closeServerSocket();
if (parsedArgs.runtimeInit) { //From Process.java to true for
if (parsedArgs.invokeWith != null) {
WrapperInit.execApplication(parsedArgs.invokeWith,
parsedArgs.niceName, parsedArgs.targetSdkVersion,
pipeFd, parsedArgs.remainingArgs); // Start command line program
RuntimeInit.zygoteInit(parsedArgs.targetSdkVersion,
parsedArgs.remainingArgs); // Almost all the applications start to go down this road
if (parsedArgs.invokeWith != null) {
WrapperInit.execStandalone(parsedArgs.invokeWith,
parsedArgs.classpath, className, mainArgs);
ZygoteInit.invokeStaticMain(cloader, className, mainArgs);
} catch (RuntimeException ex) {
Here is the RuntimeInit.ZygoteInit (), and startSystemServer (invokeStaticMain, at last, "" android.app.ActivityThread, "); invokeStatickMain () function is
static void invokeStaticMain(ClassLoader loader,String className, String[] argv)
throws zygoteInit.MethodAndArgsCaller {
throw new ZygoteInit.MethodAndArgsCaller(m, argv);
Careful readers may ask these questions:
1 why not directly on the Java function corresponding to the Call, but rather through a exception? MethodAndArgsCaller. here using Android clever to some design features of Java Exception. Execption has a major characteristic when or throws an exception when, can from the wrong place down the call stack backtrace until the capture code segment of the anomaly. Catch the exception code.
public static void main(String argv[]) {
runSelectLoop();
closeServerSocket();
} catch (MethodAndArgsCaller caller) {
caller.run(); //The real entrance here.
} catch (RuntimeException ex) {
Now you understand why the total in the dumpstate file to see the call stack.
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
2 why do all applications from the &ldquo android.app.ActivityThread "); begin? Leave a foreshadowing here, we will be in the system introduced Android Activity from the start to the whole process of display. Application startup is completed, Zygote had to sleep, waiting for new applications start request.
6 rehabilitation work
Is it right? Here, Zygote easy, can be Tiannian custody? But modern society, which the parents to raise the child can go? Especially the shoulder social responsibilities eldest son like Sytem Server, a problem or to help a parent. Here, Zygote will silently staring at this own son in the background, once found System Server hang, recycle them, and then he killed, to start a new life, poor parents ah. The implementation of:dalvik/vm/native/dalvik_system_zygote.cpp in code,
static void Dalvik_dalvik_system_Zygote_forkSystemServer(
const u4* args, JValue* pResult){
pid = forkAndSpecializeCommon(args, true);
if (pid & 0) {
gDvm.systemServerPid =
/* WNOHANG will let waitpid returns immediately, just to prevent the above assignment statement is not completed before the SystemServer crash*/
if (waitpid(pid, &status, WNOHANG) == pid) {
ALOGE("System server process %d has died. Restarting Zygote!", pid);
kill(getpid(), SIGKILL);
RETURN_INT(pid);
/* The real deal here. */
static void sigchldHandler(int s)
while ((pid = waitpid(-1, &status, WNOHANG)) & 0) {
if (pid == gDvm.systemServerPid) {
kill(getpid(), SIGKILL);
static void Dalvik_dalvik_system_Zygote_fork(const u4* args, JValue* pResult)
setSignalHandler(); //SignalHandler register here.
pid = fork();
RETURN_INT(pid);
In the Unix-like system, the parent must wait for the child process with waitpid exit, otherwise the child process will become the "Zombie" (zombie) process, not only the system resource leaks, and the system will collapse (no system server, all Android applications cannot run). But waitpid () is a blocking function (WNOHANG parameters except), so usually in signal processing functions are non blocking treatment, because each sub process, the system will issue a SIGCHID signal. Zygote will kill myself., the father died, all applications do not become orphans? No, because the parent process to be killed after the system automatically to all child processes occurring in the SIGHUP signal, the default processing the signal is to kill his exit from the current process. But some background processes (Daemon) by setting the SIG_IGN parameter to ignore the signal, so it can continue to run in the background.
The initiation process of Zygote and System Server finally introduced, let us at the above complete graphs and repeat the process.
1 init according to the init.rc running app_process, and with &lsquo --zygote'and & --startSystemServer'.
AndroidRuntime.cpp::start() Will start the JavaVM, and the registration of all framework related system JNI interface.
3 first entered into the Java world, ZygoteInit.java:: Main () function to initialize Zygote. Zygote and create Socket server terminal.
4 then fork a new process and the new process to initialize the SystemServer. before Fork, Zygote preload Java library is used, and the system of resources, and GC () to clean up memory space for the child process, eliminating duplication of work.
5 SystemServer initializes the system all the Service, including ActivityManager and WindowManager, they are the premise of application up and running.
6 are at the same time, Zygote monitor server Socket, waiting for the new application start request.
&ldquo search system after 7 ActivityM Startup& Application, the request to the Zygote.
8 Zygote after receipt of a request, a new process of fork.
SIGCHID 9 Zygote signal monitoring and processing SystemServer, once the System Server collapse, immediately to kill him. Init will restart Zygote.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch.
Posted by Kenny at December 24, 2013 - 5:46 PM}

我要回帖

更多关于 买了设备厂家不管了 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信