成人国产在线小视频_日韩寡妇人妻调教在线播放_色成人www永久在线观看_2018国产精品久久_亚洲欧美高清在线30p_亚洲少妇综合一区_黄色在线播放国产_亚洲另类技巧小说校园_国产主播xx日韩_a级毛片在线免费

資訊專欄INFORMATION COLUMN

android源碼分析-Zygote

zhunjiee / 1844人閱讀

摘要:入口函數(shù)是創(chuàng)建確認(rèn)是進(jìn)程執(zhí)行進(jìn)程如果忽略掉參數(shù)這些細(xì)節(jié),剩下的就是的建立和調(diào)用的方法了,啟動(dòng)的是。下面再看下其實(shí)主要的就是這句話,前面的都是參數(shù)的配置。至此為止,的過(guò)程基本分析完畢。

android也是基于linux的系統(tǒng),因此所有的進(jìn)程都是從init進(jìn)程開始的(直接或間接的從init進(jìn)程fock出來(lái)的)。Zygote是受精卵進(jìn)程,也是系統(tǒng)啟動(dòng)過(guò)程中由init進(jìn)程創(chuàng)建的,具體的看下啟動(dòng)腳本/system/core/rootdir/init.zygote64.rc:

service zygote /system/bin/app_process64 -Xzygote /system/bin --zygote --start-system-server
class main
priority -20
user root
group root readproc
socket zygote stream 660 root system
onrestart write /sys/android_power/request_state wake
onrestart write /sys/power/state on
onrestart restart audioserver
onrestart restart cameraserver
onrestart restart media
onrestart restart netd
onrestart restart wificond
writepid /dev/cpuset/foreground/tasks

可以看出,要執(zhí)行的進(jìn)程是/system/bin/app_process64。代碼在/frameworks/base/cmds/app_process/app_main.cpp。入口函數(shù)是main:

......
// 創(chuàng)建AppRuntime
AppRuntime runtime(argv[0], computeArgBlockSize(argc, argv));
......
while (i < argc) {
    const char* arg = argv[i++];
    if (strcmp(arg, "--zygote") == 0) {
        // 確認(rèn)是zygote進(jìn)程
        zygote = true;
        niceName = ZYGOTE_NICE_NAME;
    } else if (strcmp(arg, "--start-system-server") == 0) {
        startSystemServer = true;
    } else if (strcmp(arg, "--application") == 0) {
        application = true;
    } else if (strncmp(arg, "--nice-name=", 12) == 0) {
        niceName.setTo(arg + 12);
    } else if (strncmp(arg, "--", 2) != 0) {
        className.setTo(arg);
        break;
    } else {
        --i;
        break;
    }
}
......
if (zygote) {
    // 執(zhí)行zygote進(jìn)程
    runtime.start("com.android.internal.os.ZygoteInit", args, zygote);
} else if (className) {
    runtime.start("com.android.internal.os.RuntimeInit", args, zygote);
} else {
    fprintf(stderr, "Error: no class name or --zygote supplied.
");
    app_usage();
    LOG_ALWAYS_FATAL("app_process: no class name or --zygote supplied.");
}
......

如果忽略掉參數(shù)這些細(xì)節(jié),剩下的就是AppRuntime的建立和調(diào)用AppRuntime的start方法了,啟動(dòng)的是com.android.internal.os.ZygoteInit。
看下AppRuntime:

class AppRuntime : public AndroidRuntime
{
public:
    AppRuntime(char* argBlockStart, const size_t argBlockLength)
        : AndroidRuntime(argBlockStart, argBlockLength)
        , mClass(NULL)
    {
    }
    ......
};

構(gòu)造函數(shù)中調(diào)用了基類的構(gòu)造方法,基類在/frameworks/base/core/jni/AndroidRuntime.cpp:

AndroidRuntime::AndroidRuntime(char* argBlockStart, const size_t argBlockLength) :
        mExitWithoutCleanup(false),
        mArgBlockStart(argBlockStart),
        mArgBlockLength(argBlockLength)
{
    SkGraphics::Init();
    // There is also a global font cache, but its budget is specified by
    // SK_DEFAULT_FONT_CACHE_COUNT_LIMIT and SK_DEFAULT_FONT_CACHE_LIMIT.

    // Pre-allocate enough space to hold a fair number of options.
    mOptions.setCapacity(20);

    assert(gCurRuntime == NULL);        // one per process
    gCurRuntime = this;
}

保留了自己作為全局gCurRuntime。
直接看start方法:

void AndroidRuntime::start(const char* className, const Vector& options, bool zygote)
{
    ......
    JniInvocation jni_invocation;
    jni_invocation.Init(NULL);
    JNIEnv* env;
    // 啟動(dòng)虛擬機(jī)
    if (startVm(&mJavaVM, &env, zygote) != 0) {
        return;
    }
    // 回調(diào)虛擬機(jī)的創(chuàng)建
    onVmCreated(env);

    /*
     * Register android functions.
     */
     // 注冊(cè)函數(shù)
    if (startReg(env) < 0) {
        ALOGE("Unable to register all android natives
");
        return;
    }
    ......
    jclass stringClass;
    jobjectArray strArray;
    jstring classNameStr;

    // 獲得一個(gè)string的對(duì)象的引用
    stringClass = env->FindClass("java/lang/String");
    assert(stringClass != NULL);
    // 創(chuàng)建一個(gè)String數(shù)組對(duì)象
    strArray = env->NewObjectArray(options.size() + 1, stringClass, NULL);
    assert(strArray != NULL);
    classNameStr = env->NewStringUTF(className);
    assert(classNameStr != NULL);
    // 設(shè)置第一個(gè)string數(shù)組的第一個(gè)元素是classNameStr,在這里就是ZygoteInit的全名
    env->SetObjectArrayElement(strArray, 0, classNameStr);
    // 設(shè)置其他參數(shù)
    for (size_t i = 0; i < options.size(); ++i) {
        jstring optionsStr = env->NewStringUTF(options.itemAt(i).string());
        assert(optionsStr != NULL);
        env->SetObjectArrayElement(strArray, i + 1, optionsStr);
    }

    /*
     * Start VM.  This thread becomes the main thread of the VM, and will
     * not return until the VM exits.
     */
     // 轉(zhuǎn)換類中間的.為/,這里是轉(zhuǎn)換格式
    char* slashClassName = toSlashClassName(className);
    // 從jni環(huán)境中找到這個(gè)類
    jclass startClass = env->FindClass(slashClassName);
    if (startClass == NULL) {
        ALOGE("JavaVM unable to locate class "%s"
", slashClassName);
        /* keep going */
    } else {
        // 調(diào)用找到的類的main方法,這里就是調(diào)用ZygoteInit的main方法
        jmethodID startMeth = env->GetStaticMethodID(startClass, "main",
            "([Ljava/lang/String;)V");
        if (startMeth == NULL) {
            ALOGE("JavaVM unable to find main() in "%s"
", className);
            /* keep going */
        } else {
            env->CallStaticVoidMethod(startClass, startMeth, strArray);

#if 0
            if (env->ExceptionCheck())
                threadExitUncaughtException(env);
#endif
        }
    }
    free(slashClassName);
    ......
}

關(guān)鍵部分已經(jīng)給出了注釋??偨Y(jié)一下:
1.啟動(dòng)虛擬機(jī)startVM;
2.通過(guò)startReg注冊(cè)jni方法;
3.調(diào)用ZygoteInit類的main方法;
startVm基本上就是為這個(gè)進(jìn)程建立一個(gè)Dalvik虛擬機(jī)環(huán)境,為當(dāng)前線程初始化一個(gè)jni環(huán)境。startReg基本上是注冊(cè)一大堆的jni方法,以供后面調(diào)用。不是本文重點(diǎn),因此這里不再累述。

下面我們要關(guān)注的是ZygoteInit類的main方法了。
/frameworks/base/core/java/com/android/internal/os/ZygoteInit.java:

public static void main(String argv[]) {
    ZygoteServer zygoteServer = new ZygoteServer();
    ......
    zygoteServer.registerServerSocket(socketName);
    ......
    preload();
    ......
    if (startSystemServer) {
        startSystemServer(abiList, socketName, zygoteServer);
    }
    ......
    zygoteServer.runSelectLoop(abiList);
    ......
}

1.創(chuàng)建ZygoteServer(可以看出是個(gè)cs架構(gòu)的東西);
2.注冊(cè)socket(使用socket進(jìn)行通訊方式);
3.預(yù)加載;
4.啟動(dòng)SystemServer;
5.運(yùn)行select循環(huán)體;
里面涉及到ZygoteHooks的運(yùn)轉(zhuǎn),為了不影響整體,暫時(shí)做個(gè)標(biāo)記,后面再閱讀。
這里可以看到Zygote基本上是個(gè)cs架構(gòu)的情況,并且通過(guò)socket進(jìn)行這種架構(gòu)的通訊。先來(lái)看看預(yù)加載過(guò)程:

    static void preload() {
        Log.d(TAG, "begin preload");
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "BeginIcuCachePinning");
        beginIcuCachePinning();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadClasses");
        //預(yù)加載位于framework/base/preload-classes文件中的類
        preloadClasses();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadResources");
        // 預(yù)加載資源
        preloadResources();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        Trace.traceBegin(Trace.TRACE_TAG_DALVIK, "PreloadOpenGL");
        // 預(yù)加載資源
        preloadOpenGL();
        Trace.traceEnd(Trace.TRACE_TAG_DALVIK);
        //通過(guò)System.loadLibrary()方法,預(yù)加載"android","compiler_rt","jnigraphics"這3個(gè)共享庫(kù)
        preloadSharedLibraries();
        //預(yù)加載文本連接符資源
        preloadTextResources();
        // webview的初始化
        // Ask the WebViewFactory to do any initialization that must run in the zygote process,
        // for memory sharing purposes.
        WebViewFactory.prepareWebViewInZygote();
        endIcuCachePinning();
        warmUpJcaProviders();
        Log.d(TAG, "end preload");
    }

看到了吧,都是android本身的一些資源的初始化過(guò)程,就是在這里完成的。
下面再看下startSystemServer:

private static boolean startSystemServer(String abiList, String socketName, ZygoteServer zygoteServer)
            throws Zygote.MethodAndArgsCaller, RuntimeException {
        long capabilities = posixCapabilitiesAsBits(
            OsConstants.CAP_IPC_LOCK,
            OsConstants.CAP_KILL,
            OsConstants.CAP_NET_ADMIN,
            OsConstants.CAP_NET_BIND_SERVICE,
            OsConstants.CAP_NET_BROADCAST,
            OsConstants.CAP_NET_RAW,
            OsConstants.CAP_SYS_MODULE,
            OsConstants.CAP_SYS_NICE,
            OsConstants.CAP_SYS_RESOURCE,
            OsConstants.CAP_SYS_TIME,
            OsConstants.CAP_SYS_TTY_CONFIG,
            OsConstants.CAP_WAKE_ALARM
        );
        /* Containers run without this capability, so avoid setting it in that case */
        if (!SystemProperties.getBoolean(PROPERTY_RUNNING_IN_CONTAINER, false)) {
            capabilities |= posixCapabilitiesAsBits(OsConstants.CAP_BLOCK_SUSPEND);
        }
        /* Hardcoded command line to start the system server */
        String args[] = {
            "--setuid=1000",
            "--setgid=1000",
            "--setgroups=1001,1002,1003,1004,1005,1006,1007,1008,1009,1010,1018,1021,1032,3001,3002,3003,3006,3007,3009,3010",
            "--capabilities=" + capabilities + "," + capabilities,
            "--nice-name=system_server",
            "--runtime-args",
            "com.android.server.SystemServer",
        };
        ZygoteConnection.Arguments parsedArgs = null;

        int pid;

        try {
            parsedArgs = new ZygoteConnection.Arguments(args);
            ZygoteConnection.applyDebuggerSystemProperty(parsedArgs);
            ZygoteConnection.applyInvokeWithSystemProperty(parsedArgs);

            /* Request to fork the system server process */
            pid = Zygote.forkSystemServer(
                    parsedArgs.uid, parsedArgs.gid,
                    parsedArgs.gids,
                    parsedArgs.debugFlags,
                    null,
                    parsedArgs.permittedCapabilities,
                    parsedArgs.effectiveCapabilities);
        } catch (IllegalArgumentException ex) {
            throw new RuntimeException(ex);
        }

        /* For child process */
        if (pid == 0) {
            if (hasSecondZygote(abiList)) {
                waitForSecondaryZygote(socketName);
            }

            zygoteServer.closeServerSocket();
            handleSystemServerProcess(parsedArgs);
        }

        return true;
    }

其實(shí)主要的就是Zygote.forkSystemServer這句話,前面的都是參數(shù)的配置。再向下看一層/frameworks/base/core/java/com/android/internal/os/Zygote.java:

public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
        VM_HOOKS.preFork();
        int pid = nativeForkSystemServer(
                uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
        // Enable tracing as soon as we enter the system_server.
        if (pid == 0) {
            Trace.setTracingEnabled(true);
        }
        VM_HOOKS.postForkCommon();
        return pid;
    }
    

根據(jù)傳遞進(jìn)來(lái)的uid,gid等調(diào)用函數(shù)nativeForkSystemServer,最終會(huì)在/frameworks/base/core/jni/com_android_internal_os_Zygote.cpp下的ForkAndSpecializeCommon中調(diào)用fork函數(shù),那么實(shí)際上就可以知道,就是在c層fork分裂出一個(gè)進(jìn)程來(lái)作為SystemServer。

現(xiàn)在我們回來(lái)看java層的ZygoteInit.java,繼續(xù)看看與socket相關(guān)的部分,首先是registerServerSocket:

void registerServerSocket(String socketName) {
        if (mServerSocket == null) {
            int fileDesc;
            final String fullSocketName = ANDROID_SOCKET_PREFIX + socketName;
            try {
                String env = System.getenv(fullSocketName);
                fileDesc = Integer.parseInt(env);
            } catch (RuntimeException ex) {
                throw new RuntimeException(fullSocketName + " unset or invalid", ex);
            }

            try {
                FileDescriptor fd = new FileDescriptor();
                fd.setInt$(fileDesc);
                mServerSocket = new LocalServerSocket(fd);
            } catch (IOException ex) {
                throw new RuntimeException(
                        "Error binding to local socket "" + fileDesc + """, ex);
            }
        }
    }

這里設(shè)置了文件描述符,然后創(chuàng)建了LocalServerSocket賦值給了mServerSocket。/frameworks/base/core/java/android/net/LocalServerSocket.java:

public LocalServerSocket(FileDescriptor fd) throws IOException
    {
        impl = new LocalSocketImpl(fd);
        impl.listen(LISTEN_BACKLOG);
        localAddress = impl.getSockAddress();
    }

new出LocalSocketImpl后,直接就開始listen了。下面暫時(shí)不用特別看了吧,就是一個(gè)走的正常的網(wǎng)絡(luò)socket了。這里應(yīng)該就可以證明是以socket的方法進(jìn)行的通訊。然后再來(lái)看看runSelectLoop:

void runSelectLoop(String abiList) throws Zygote.MethodAndArgsCaller {
        ArrayList fds = new ArrayList();
        ArrayList peers = new ArrayList();

        fds.add(mServerSocket.getFileDescriptor());
        peers.add(null);

        while (true) {
            StructPollfd[] pollFds = new StructPollfd[fds.size()];
            for (int i = 0; i < pollFds.length; ++i) {
                pollFds[i] = new StructPollfd();
                pollFds[i].fd = fds.get(i);
                pollFds[i].events = (short) POLLIN;
            }
            try {
                Os.poll(pollFds, -1);
            } catch (ErrnoException ex) {
                throw new RuntimeException("poll failed", ex);
            }
            for (int i = pollFds.length - 1; i >= 0; --i) {
                if ((pollFds[i].revents & POLLIN) == 0) {
                    continue;
                }
                if (i == 0) {
                    ZygoteConnection newPeer = acceptCommandPeer(abiList);
                    peers.add(newPeer);
                    fds.add(newPeer.getFileDesciptor());
                } else {
                    boolean done = peers.get(i).runOnce(this);
                    if (done) {
                        peers.remove(i);
                        fds.remove(i);
                    }
                }
            }
        }
    }
    

進(jìn)入一個(gè)死循環(huán),每次都將所有要觀察的fd建立成數(shù)組,然后調(diào)用Os.poll(pollFds, -1)阻塞等待fd的變化。后面一個(gè)for循環(huán)是當(dāng)fd有變化(即有客戶端連接,也就是說(shuō)有其他進(jìn)程想要與ZygoteServer通訊),此時(shí)調(diào)用ZygoteConnection的runOnce方法。這個(gè)方法如果簡(jiǎn)單看下的話,最終是要調(diào)用Zygote.forkAndSpecialize分裂出進(jìn)程來(lái)的,也就是說(shuō)這個(gè)方法是一旦有連接建立后就表示有app啟動(dòng)了,此時(shí)就要fork分裂出新的進(jìn)程來(lái),代碼暫時(shí)就不貼了。

至此為止,Zygote的過(guò)程基本分析完畢。總結(jié)一下:
1.系統(tǒng)啟動(dòng),通過(guò)init進(jìn)程會(huì)啟動(dòng)Zygote進(jìn)程。確切的將是通過(guò)runtime調(diào)用了ZygoteInit,這個(gè)初始化過(guò)程;
2.Zygote是cs架構(gòu)的,基于socket通訊機(jī)制的,在ZygoteInit過(guò)程中會(huì)啟動(dòng)ZygoteServer,為了等待接收socket的通訊來(lái)進(jìn)行啟動(dòng)app進(jìn)程的處理;
3.分裂出SystemServer進(jìn)程,負(fù)責(zé)啟動(dòng)系統(tǒng)的一些關(guān)鍵服務(wù)。包括3類(廣播類、核心類、其他類);

最后附圖一張便于理解:

文章版權(quán)歸作者所有,未經(jīng)允許請(qǐng)勿轉(zhuǎn)載,若此文章存在違規(guī)行為,您可以聯(lián)系管理員刪除。

轉(zhuǎn)載請(qǐng)注明本文地址:http://systransis.cn/yun/66824.html

相關(guān)文章

  • android源碼分析Zygote和SystemServer啟動(dòng)

    摘要:注此次分析以源碼為例。孵化器受精卵名字是受精卵,其實(shí)就是幫助或其他進(jìn)程啟動(dòng)的一個(gè)玩意兒。啟動(dòng)系統(tǒng)服務(wù)是系統(tǒng)的大核心之一,和一并重要,專管所有的系統(tǒng)服務(wù)。每個(gè)進(jìn)程都走這一步這個(gè)分支到此先不往下跟蹤了,和啟動(dòng)的過(guò)程關(guān)系不大了。 注:此次分析以6.0源碼為例。 android系統(tǒng)是從linux改過(guò)來(lái)的,因此這里從init進(jìn)程開始進(jìn)行分析。 init初始化過(guò)程 讓我們進(jìn)入init.cpp來(lái)看看...

    RyanHoo 評(píng)論0 收藏0

發(fā)表評(píng)論

0條評(píng)論

最新活動(dòng)
閱讀需要支付1元查看
<