当前位置:   article > 正文

AOSP 8.0 系统启动之五systemserver启动(一)_system_server:heaptaskdaemon

system_server:heaptaskdaemon

目录

前言

一、 systemserver进程创建

1.1 Zygote.forkSystemServer

1.1.1 ZygoteHooks.preFork

1.1.2 Daemon.stop

1.1.3 ZygoteHooks.nativePreFork

1.2.1 nativeForkSystemServer

1.2.2 zygote.callPostForkChildHooks

1.3.1 VM_HOOKS.postForkCommon

1.2 handleSystemServerProcess

二、Fork解释


前言

SystemServer就是系统用来启动Framework核心service的入口,如AMS,PMS,WMS等。
Android系统在启动的时候, 在启动两个重要的进程,一个是zygote进程
另一个是由zygote进程fork出来的system_server进程;

  1. /frameworks/base/core/java/com/android/internal/os/
  2. - ZygoteInit.java
  3. - RuntimeInit.java
  4. - Zygote.java
  5. /frameworks/base/core/services/java/com/android/server/
  6. - SystemServer.java
  7. /frameworks/base/core/jni/
  8. - com_android_internal_os_Zygote.cpp
  9. - AndroidRuntime.cpp
  10. /frameworks/base/cmds/app_process/App_main.cpp

一、 systemserver进程创建

  1. //ZygoteInit.java
  2. ZygoteInit.main(){
  3. .....
  4. if (startSystemServer) { //如果参数中包含“start-system-server”就是true
  5. startSystemServer(abiList, socketName);
  6. }
  7. }
  1. private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
  2. throws Zygote.MethodAndArgsCaller, RuntimeException {
  3. ......
  4. //准备参数, 其中进程名称为system_server
  5. String args[] = {
  6. "--setuid=1000",
  7. "--setgid=1000",
  8. "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1023,1032,3001,3002,3003,3006,3007,3009,3010",
  9. "--capabilities=" + capabilities + "," + capabilities,
  10. "--nice-name=system_server",
  11. "--runtime-args",
  12. "com.android.server.SystemServer",
  13. };
  14. ZygoteConnection.Arguments parsedArgs = null;
  15. int pid;
  16. try {
  17. parsedArgs = new ZygoteConnection.Arguments(args);
  18. //通过fork创建子进程
  19. pid = Zygote.forkSystemServer(
  20. parsedArgs.uid, parsedArgs.gid,
  21. parsedArgs.gids,
  22. parsedArgs.debugFlags,
  23. null,
  24. parsedArgs.permittedCapabilities,
  25. parsedArgs.effectiveCapabilities);
  26. } catch (IllegalArgumentException ex) {
  27. throw new RuntimeException(ex);
  28. }
  29. /* For child process */
  30. if (pid == 0) {
  31. if (hasSecondZygote(abiList)) {
  32. waitForSecondaryZygote(socketName);
  33. }
  34. //因为zygote进程socket创建, 子进程就要关闭,否则ams的socket请求就会错乱;
  35. zygoteServer.closeServerSocket();
  36. //子进程返回pid = 0 ,后续启动服务
  37. handleSystemServerProcess(parsedArgs);
  38. }
  39. return true;
  40. }

1.1 Zygote.forkSystemServer

  1. //该函数分为三阶段处理preFork、nativeForkAndSpecialize、postForkCommon。
  2. //VM_HOOKS是Zygote对象的静态成员变量:VM_HOOKS = new ZygoteHooks()
  3. public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
  4. int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
  5. VM_HOOKS.preFork(); // 先停止zygote进程中与gc相关的几个线程
  6. ...
  7. int pid = nativeForkSystemServer(
  8. uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
  9. ...
  10. VM_HOOKS.postForkCommon(); //fork新进程后将之前停掉的四个Daemon线程启动起来
  11. return pid;
  12. }

1.1.1 ZygoteHooks.preFork

  1. ///libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
  2. public void preFork() {
  3. Daemons.stop(); //停止4个Daemon子线程
  4. waitUntilAllThreadsStopped(); //等待所有子线程结束,只保留一个主线程
  5. token = nativePreFork(); //将当前C++中的thread对象地址强转long,保存到token之中,并且完成Runtime中堆的初始化工作
  6. }
  7. //Daemons.java
  8. public static void stop() {
  9. HeapTaskDaemon.INSTANCE.stop(); //Java堆整理线程, 先调用目标线程interrrupt()方法,然后再调用目标线程join()方法,抛出InterruptedException异常后 线程执行完成。
  10. ReferenceQueueDaemon.INSTANCE.stop(); //引用队列线程
  11. FinalizerDaemon.INSTANCE.stop(); //析构线程
  12. FinalizerWatchdogDaemon.INSTANCE.stop(); //析构监控线程
  13. }
  14. private static void waitUntilAllThreadsStopped() {
  15. File tasks = new File("/proc/self/task");
  16. 当/proc中线程数大于1,就出让CPU直到只有一个线程,才退出循环
  17. while (tasks.list().length > 1) {
  18. Thread.yield(); //调用yield是
  19. }
  20. }

1.1.2 Daemon.stop

  1. public void stop() {
  2. Thread threadToStop;
  3. synchronized (this) {
  4. threadToStop = thread;
  5. thread = null;
  6. }
  7. if (threadToStop == null) {
  8. throw new IllegalStateException("not running");
  9. }
  10. interrupt(threadToStop); //调用thread.interrupt
  11. while (true) {
  12. try {
  13. threadToStop.join(); //当线程被interrupt之后,再调用join唤醒线程,就会抛出InterruptedException异常,线程结束
  14. return;
  15. } catch (InterruptedException ignored) {
  16. } catch (OutOfMemoryError ignored) {
  17. // An OOME may be thrown if allocating the InterruptedException failed.
  18. }
  19. }
  20. }
  21. /libcore/ojluni/src/main/java/java/lang/Thread.java
  22. public void interrupt() {
  23. nativeInterrupt(); //调用JNI
  24. }
  25. /art/runtime/native/java_lang_Thread.cc
  26. static void Thread_nativeInterrupt(JNIEnv* env, jobject java_thread) {
  27. ScopedFastNativeObjectAccess soa(env);
  28. MutexLock mu(soa.Self(), *Locks::thread_list_lock_);
  29. Thread* thread = Thread::FromManagedThread(soa, java_thread);
  30. if (thread != nullptr) {
  31. thread->Interrupt(soa.Self());
  32. }
  33. }
  34. /art/runtime/thread.cc
  35. void Thread::Interrupt(Thread* self) {
  36. MutexLock mu(self, *wait_mutex_);
  37. if (interrupted_) {
  38. return;
  39. }
  40. interrupted_ = true; //设置interrupted_为true即可;
  41. NotifyLocked(self);
  42. }
  43. //参数millis = 0, 当线程被interrupt之后,再调用join唤醒线程,就会抛出InterruptedException异常,线程结束
  44. public final void join(long millis) throws InterruptedException {
  45. synchronized(lock) {
  46. long base = System.currentTimeMillis();
  47. long now = 0;
  48. if (millis == 0) {
  49. while (isAlive()) {
  50. lock.wait(0);
  51. }
  52. } else {
  53. while (isAlive()) {
  54. long delay = millis - now;
  55. if (delay <= 0) {
  56. break;
  57. }
  58. lock.wait(delay);
  59. now = System.currentTimeMillis() - base;
  60. }
  61. }
  62. }
  63. }

1.1.3 ZygoteHooks.nativePreFork

  1. /*art/runtime/native/dalvik_system_ZygoteHooks.cc*/
  2. static jlong ZygoteHooks_nativePreFork(JNIEnv* env, jclass) {
  3. Runtime* runtime = Runtime::Current();
  4. runtime->PreZygoteFork(); // runtime的GC堆初始化,不继续分析了
  5. //将C++ 中的Thread对象 线程转换为long型并保存到token,该过程是非安全的
  6. return reinterpret_cast<jlong>(ThreadForEnv(env));
  7. }
  8. static inline Thread* ThreadForEnv(JNIEnv* env) {
  9. JNIEnvExt* full_env(down_cast<JNIEnvExt*>(env));
  10. return full_env->self; //此处就是C++ 中的Thread对象
  11. }

1.2.1 nativeForkSystemServer

  1. //在该函数中通过调用fork方法,成功的创建了新进程-system_server进程
  2. static pid_t ForkAndSpecializeCommon(JNIEnv* env, uid_t uid, gid_t gid, jintArray javaGids,
  3. jint debug_flags, jobjectArray javaRlimits,
  4. jlong permittedCapabilities, jlong effectiveCapabilities,
  5. jint mount_external,
  6. jstring java_se_info, jstring java_se_name,
  7. bool is_system_server, jintArray fdsToClose,
  8. jstring instructionSet, jstring dataDir) {
  9. //设置子进程的signal信号处理函数
  10. // zygote监听所有子进程的死亡,如果system_server挂掉,则kill掉zygote ,又因为init监听zygote,继而继续重启相关服务
  11. SetSigChldHandler();
  12. //fork子进程
  13. pid_t pid = fork();
  14. if (pid == 0) { //进入子进程
  15. DetachDescriptors(env, fdsToClose); //关闭并清除文件描述符
  16. ....
  17. int rc = setresgid(gid, gid, gid);
  18. rc = setresuid(uid, uid, uid);
  19. SetCapabilities(env, permittedCapabilities, effectiveCapabilities);
  20. SetSchedulerPolicy(env); //设置调度策略
  21. if (se_info_c_str == NULL && is_system_server) {
  22. se_name_c_str = "system_server";
  23. }
  24. if (se_info_c_str != NULL) {
  25. SetThreadName(se_name_c_str); //设置线程名为system_server,方便调试
  26. }
  27. //在Zygote子进程中,设置信号SIGCHLD的处理器恢复为默认行为
  28. UnsetSigChldHandler();
  29. //等价于调用zygote.callPostForkChildHooks()
  30. env->CallStaticVoidMethod(gZygoteClass, gCallPostForkChildHooks, debug_flags,
  31. is_system_server ? NULL : instructionSet);
  32. ...
  33. } else if (pid > 0) {
  34. //进入父进程,即Zygote进程
  35. }
  36. return pid;
  37. }

1.2.2 zygote.callPostForkChildHooks

先进入了Java世界, 然后其内部调用JNI 方法;

  1. ///libcore/dalvik/src/main/java/dalvik/system/ZygoteHooks.java
  2. private static void callPostForkChildHooks(int runtimeFlags, boolean isSystemServer,
  3. boolean isZygote, String instructionSet) {
  4. ZygoteHooks.postForkChild(runtimeFlags, isSystemServer, isZygote, instructionSet);
  5. }
  6. //有进入到JNI 世界
  7. static void ZygoteHooks_nativePostForkChild(JNIEnv* env,
  8. jclass,
  9. jlong token,
  10. jint debug_flags,
  11. jboolean is_system_server,
  12. jstring instruction_set) {
  13. Thread* thread = reinterpret_cast<Thread*>(token);
  14. // Our system thread ID, etc, has changed so reset Thread state.
  15. thread->InitAfterFork(); //获取tid值
  16. .....
  17. if (instruction_set != nullptr && !is_system_server) {
  18. ......
  19. } else {
  20. //走这个分支
  21. Runtime::Current()->InitNonZygoteOrPostFork(
  22. env, is_system_server, Runtime::NativeBridgeAction::kUnload, nullptr);
  23. }
  24. }
  25. void Runtime::InitNonZygoteOrPostFork(
  26. JNIEnv* env, bool is_system_server, NativeBridgeAction action, const char* isa) {
  27. is_zygote_ = false;
  28. ......
  29. // Create the thread pools.
  30. heap_->CreateThreadPool();
  31. // Reset the gc performance data at zygote fork so that the GCs
  32. // before fork aren't attributed to an app.
  33. heap_->ResetGcPerformanceInfo();
  34. ....
  35. StartSignalCatcher(); //启动子线程,专门用于捕获3(ANR),10 两个信号
  36. }

1.3.1 VM_HOOKS.postForkCommon

  1. //重新启动4个线程来处理GC内容
  2. public void postForkCommon() {
  3. Daemons.start();
  4. }
  5. public static void start() {
  6. ReferenceQueueDaemon.INSTANCE.start();
  7. FinalizerDaemon.INSTANCE.start();
  8. FinalizerWatchdogDaemon.INSTANCE.start();
  9. HeapTaskDaemon.INSTANCE.start();
  10. }

1.2 handleSystemServerProcess

至此system_server进程就创建出来了,system_server进程的才开始真正工作,那handleSystemServerProcess具体做了些什么呢?

等待下篇文章分析;

二、Fork解释

Fork不需要参数并且返回一个整数值;
fork()返回的不同值:
负值:创建子进程失败;
:返回到新创建的子进程;
正值:返回父进程或者调用者。该值包含新创建的子进程的进程ID;

Fork函数用来创建一个与当前进程映像一样的子进程,所创建的子进程将复制父进程的代码段,数据 段,BSS段,堆,栈等所有用户空间信息;在内核中操作系统会重新为其申请一个子进程执行的位置;


当进程调用fork后控制转入内核,内核会做4件事;
1.分配新的内存块和内核数据结构给子进程
2.将父进程部分数据结构内容(数据结构,堆栈等)拷贝到子进程
3.添加子进程到系统进程列表中
4.fork返回开始调度器调度

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/227850
推荐阅读
相关标签
  

闽ICP备14008679号