Android源碼解析之MethodAndArgsCaller

如果你看過ZygoteInit.javamain方法可能會對這個類不陌生,在Android8.1之前,其main方法都是類似以下這樣:

以下代碼基于Android8.0

public static void main(String argv[]) {
    ZygoteServer zygoteServer = new ZygoteServer();
    // Mark zygote start. This ensures that thread creation will throw
    // an error.
    ZygoteHooks.startZygoteNoThreadCreation();
    try {
        ...
        // 創(chuàng)建server端的socket,name為"zygote"
        zygoteServer.registerServerSocket(socketName);
        ...
        if (startSystemServer) {
            // 啟動SystemServer進(jìn)程
            startSystemServer(abiList, socketName, zygoteServer);
        }
        Log.i(TAG, "Accepting command socket connections");
        // 等待AMS請求
        zygoteServer.runSelectLoop(abiList);
        zygoteServer.closeServerSocket();
    } catch (Zygote.MethodAndArgsCaller caller) {
        // 運(yùn)行MethodAndArgsCaller的run方法
        caller.run();
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        zygoteServer.closeServerSocket();
        throw ex;
    }
}

其中比較讓人疑惑的地方是caller.run();這句,為何一個Exception需要運(yùn)行?

我們先看下MethodAndArgsCaller這個類的源碼:

/**
 * Helper exception class which holds a method and arguments and
 * can call them. This is used as part of a trampoline to get rid of
 * the initial process setup stack frames.
 */
public static class MethodAndArgsCaller extends Exception
        implements Runnable {
    /** method to call */
    private final Method mMethod;
    /** argument array */
    private final String[] mArgs;
    public MethodAndArgsCaller(Method method, String[] args) {
        mMethod = method;
        mArgs = args;
    }
    public void run() {
        try {
            mMethod.invoke(null, new Object[] { mArgs });
        } catch (IllegalAccessException ex) {
            throw new RuntimeException(ex);
        } catch (InvocationTargetException ex) {
            Throwable cause = ex.getCause();
            if (cause instanceof RuntimeException) {
                throw (RuntimeException) cause;
            } else if (cause instanceof Error) {
                throw (Error) cause;
            }
            throw new RuntimeException(ex);
        }
    }
}

這個類的功能比較單一,可以看出這個類是協(xié)助反射調(diào)用的,調(diào)用了其run方法將通過反射調(diào)用傳入的方法。

這個類繼承了Exception類,我們看拋出這個異常的地方(RuntimeInit類中):

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
        throws Zygote.MethodAndArgsCaller {
    Class<?> cl;
    try {
        // 根據(jù)類名查找類
        cl = Class.forName(className, true, classLoader);
    } catch (ClassNotFoundException ex) {
        throw new RuntimeException(
                "Missing class when invoking static main " + className,
                ex);
    }
    Method m;
    try {
        // 找到該類的main方法
        m = cl.getMethod("main", new Class[] { String[].class });
    } catch (NoSuchMethodException ex) {
        throw new RuntimeException(
                "Missing static main on " + className, ex);
    } catch (SecurityException ex) {
        throw new RuntimeException(
                "Problem getting static main on " + className, ex);
    }
    int modifiers = m.getModifiers();
    if (! (Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
        throw new RuntimeException(
                "Main method is not public and static on " + className);
    }
    /*
     * This throw gets caught in ZygoteInit.main(), which responds
     * by invoking the exception's run() method. This arrangement
     * clears up all the stack frames that were required in setting
     * up the process.
     */
    throw new Zygote.MethodAndArgsCaller(m, argv);
}

到這個方法就可以看出,最終找到某個類的main方法和方法需要的參數(shù),將其傳入MethodAndArgsCaller這個Exception中,并在catch了這個Exception的地方調(diào)用。

那么為什么要使用這種奇技淫巧調(diào)用,而不直接調(diào)用某個類呢?

其實(shí)這個注釋已經(jīng)解釋了:

/*
 * This throw gets caught in ZygoteInit.main(), which responds
 * by invoking the exception's run() method. This arrangement
 * clears up all the stack frames that were required in setting
 * up the process.
 */
throw new Zygote.MethodAndArgsCaller(m, argv);

通過拋異常然后調(diào)用Exception的run方法的方式,可以清除調(diào)用過程的堆棧信息。

解釋一下,就是這樣做之后,調(diào)用的堆棧信息會是類似這樣:

...
at com.android.server.SystemServer.main(SystemServer.java:175)
at java.lang.reflect.Method.invoke!(Native method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:738)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:628)

我們看到上面異常信息中只有SystemServer.mainMethodAndArgsCaller.runZygoteInit.main,而沒有中間的調(diào)用過程。這樣使得每個被ZygoteInit啟動的類看起來都像是直接被啟動了,而看不到啟動前的設(shè)置過程,看起來比較清爽。

額外的收獲

我下載的源碼是Android9.0,發(fā)現(xiàn)MethodAndArgsCaller方法已經(jīng)不再繼承Exception類了,而是僅實(shí)現(xiàn)了Runnable接口,同時ZygoteInit類的main方法也不再通過catch Exception的方法運(yùn)行。

我就很奇怪,難道不再需要清除堆棧信息了嗎?

我按照Android9.0的代碼實(shí)現(xiàn)了一遍上述的調(diào)用過程,代碼如下:

Main2.java

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

public class Main2 {

    public static void main(String[] args) {
        new Main2().b().run();
    }

    private Runnable b(){
        return a();
    }

    private Runnable a() {
        return findStaticMain("method_invoke.ClassTwo", new String[]{"111111"}, this.getClass().getClassLoader());
    }


    /**
     * Invokes a static "main(argv[]) method on class "className".
     * Converts various failing exceptions into RuntimeExceptions, with
     * the assumption that they will then cause the VM instance to exit.
     *
     * @param className   Fully-qualified class name
     * @param argv        Argument vector for main()
     * @param classLoader the classLoader to load {@className} with
     */
    protected static Runnable findStaticMain(String className, String[] argv,
                                             ClassLoader classLoader) {
        Class<?> cl;

        try {
            cl = Class.forName(className, true, classLoader);
        } catch (ClassNotFoundException ex) {
            throw new RuntimeException(
                    "Missing class when invoking static main " + className,
                    ex);
        }

        Method m;
        try {
            m = cl.getMethod("main", new Class[]{String[].class});
        } catch (NoSuchMethodException ex) {
            throw new RuntimeException(
                    "Missing static main on " + className, ex);
        } catch (SecurityException ex) {
            throw new RuntimeException(
                    "Problem getting static main on " + className, ex);
        }

        int modifiers = m.getModifiers();
        if (!(Modifier.isStatic(modifiers) && Modifier.isPublic(modifiers))) {
            throw new RuntimeException(
                    "Main method is not public and static on " + className);
        }

        /*
         * This throw gets caught in ZygoteInit.main(), which responds
         * by invoking the exception's run() method. This arrangement
         * clears up all the stack frames that were required in setting
         * up the process.
         */
        return new MethodAndArgsCaller(m, argv);
    }


    /**
     * Helper class which holds a method and arguments and can call them. This is used as part of
     * a trampoline to get rid of the initial process setup stack frames.
     */
    static class MethodAndArgsCaller implements Runnable {
        /**
         * method to call
         */
        private final Method mMethod;

        /**
         * argument array
         */
        private final String[] mArgs;

        public MethodAndArgsCaller(Method method, String[] args) {
            mMethod = method;
            mArgs = args;
        }

        public void run() {
            try {
                mMethod.invoke(null, new Object[]{mArgs});
            } catch (IllegalAccessException ex) {
                throw new RuntimeException(ex);
            } catch (InvocationTargetException ex) {
                Throwable cause = ex.getCause();
                if (cause instanceof RuntimeException) {
                    throw (RuntimeException) cause;
                } else if (cause instanceof Error) {
                    throw (Error) cause;
                }
                throw new RuntimeException(ex);
            }
        }
    }
}

ClassTwo.java

public class ClassTwo {
    public static void main(String[] args) {

        System.out.println(args[0]);
        try {
            // 制造除0異常
            System.out.println(1/0);
        } catch (InterruptedException e) {
            // 輸出堆棧信息
            e.printStackTrace();
        }
    }
}

發(fā)現(xiàn)其調(diào)用鏈信息同樣是被清除了的:

Exception in thread "main" java.lang.ArithmeticException: / by zero
    at method_invoke.ClassTwo.main(ClassTwo.java:9)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at method_invoke.Main2$MethodAndArgsCaller.run(Main2.java:93)
    at method_invoke.Main2.main(Main2.java:10)

這沒有用什么奇技淫巧,也沒有額外的堆棧信息,Android哪個catch Exception的操作在搞什么?

我這時以為是Runnable接口有什么魔力,然后自己寫了個接口,讓MethodAndArgsCaller繼承,結(jié)果沒有什么兩樣。

也就是說,將所需要的結(jié)果封裝成一個對象,最終返回到main方法,main方法中調(diào)用就可以了--并不會有中間設(shè)置對象的堆棧信息被保留。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。