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 {
        ...
        // 创建server端的socket,name为"zygote"
        zygoteServer.registerServerSocket(socketName);
        ...
        if (startSystemServer) {
            // 启动SystemServer进程
            startSystemServer(abiList, socketName, zygoteServer);
        }
        Log.i(TAG, "Accepting command socket connections");
        // 等待AMS请求
        zygoteServer.runSelectLoop(abiList);
        zygoteServer.closeServerSocket();
    } catch (Zygote.MethodAndArgsCaller caller) {
        // 运行MethodAndArgsCaller的run方法
        caller.run();
    } catch (Throwable ex) {
        Log.e(TAG, "System zygote died with exception", ex);
        zygoteServer.closeServerSocket();
        throw ex;
    }
}

其中比较让人疑惑的地方是caller.run();这句,为何一个Exception需要运行?

我们先看下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);
        }
    }
}

这个类的功能比较单一,可以看出这个类是协助反射调用的,调用了其run方法将通过反射调用传入的方法。

这个类继承了Exception类,我们看抛出这个异常的地方(RuntimeInit类中):

private static void invokeStaticMain(String className, String[] argv, ClassLoader classLoader)
        throws Zygote.MethodAndArgsCaller {
    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 {
        // 找到该类的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方法和方法需要的参数,将其传入MethodAndArgsCaller这个Exception中,并在catch了这个Exception的地方调用。

那么为什么要使用这种奇技淫巧调用,而不直接调用某个类呢?

其实这个注释已经解释了:

/*
 * 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);

通过抛异常然后调用Exception的run方法的方式,可以清除调用过程的堆栈信息。

解释一下,就是这样做之后,调用的堆栈信息会是类似这样:

...
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,而没有中间的调用过程。这样使得每个被ZygoteInit启动的类看起来都像是直接被启动了,而看不到启动前的设置过程,看起来比较清爽。

额外的收获

我下载的源码是Android9.0,发现MethodAndArgsCaller方法已经不再继承Exception类了,而是仅实现了Runnable接口,同时ZygoteInit类的main方法也不再通过catch Exception的方法运行。

我就很奇怪,难道不再需要清除堆栈信息了吗?

我按照Android9.0的代码实现了一遍上述的调用过程,代码如下:

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();
        }
    }
}

发现其调用链信息同样是被清除了的:

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继承,结果没有什么两样。

也就是说,将所需要的结果封装成一个对象,最终返回到main方法,main方法中调用就可以了--并不会有中间设置对象的堆栈信息被保留。