1/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.internal.os;
18
19
20import android.os.Trace;
21import dalvik.system.ZygoteHooks;
22import android.system.ErrnoException;
23import android.system.Os;
24
25import java.lang.reflect.InvocationTargetException;
26import java.lang.reflect.Method;
27
28/** @hide */
29public final class Zygote {
30    /*
31    * Bit values for "debugFlags" argument.  The definitions are duplicated
32    * in the native code.
33    */
34
35    /** enable debugging over JDWP */
36    public static final int DEBUG_ENABLE_JDWP   = 1;
37    /** enable JNI checks */
38    public static final int DEBUG_ENABLE_CHECKJNI   = 1 << 1;
39    /** enable Java programming language "assert" statements */
40    public static final int DEBUG_ENABLE_ASSERT     = 1 << 2;
41    /** disable the AOT compiler and JIT */
42    public static final int DEBUG_ENABLE_SAFEMODE   = 1 << 3;
43    /** Enable logging of third-party JNI activity. */
44    public static final int DEBUG_ENABLE_JNI_LOGGING = 1 << 4;
45    /** Force generation of native debugging information. */
46    public static final int DEBUG_GENERATE_DEBUG_INFO = 1 << 5;
47    /** Always use JIT-ed code. */
48    public static final int DEBUG_ALWAYS_JIT = 1 << 6;
49    /** Make the code native debuggable by turning off some optimizations. */
50    public static final int DEBUG_NATIVE_DEBUGGABLE = 1 << 7;
51    /** Make the code Java debuggable by turning off some optimizations. */
52    public static final int DEBUG_JAVA_DEBUGGABLE = 1 << 8;
53
54    /** No external storage should be mounted. */
55    public static final int MOUNT_EXTERNAL_NONE = 0;
56    /** Default external storage should be mounted. */
57    public static final int MOUNT_EXTERNAL_DEFAULT = 1;
58    /** Read-only external storage should be mounted. */
59    public static final int MOUNT_EXTERNAL_READ = 2;
60    /** Read-write external storage should be mounted. */
61    public static final int MOUNT_EXTERNAL_WRITE = 3;
62
63    private static final ZygoteHooks VM_HOOKS = new ZygoteHooks();
64
65    private Zygote() {}
66
67    /**
68     * Forks a new VM instance.  The current VM must have been started
69     * with the -Xzygote flag. <b>NOTE: new instance keeps all
70     * root capabilities. The new process is expected to call capset()</b>.
71     *
72     * @param uid the UNIX uid that the new process should setuid() to after
73     * fork()ing and and before spawning any threads.
74     * @param gid the UNIX gid that the new process should setgid() to after
75     * fork()ing and and before spawning any threads.
76     * @param gids null-ok; a list of UNIX gids that the new process should
77     * setgroups() to after fork and before spawning any threads.
78     * @param debugFlags bit flags that enable debugging features.
79     * @param rlimits null-ok an array of rlimit tuples, with the second
80     * dimension having a length of 3 and representing
81     * (resource, rlim_cur, rlim_max). These are set via the posix
82     * setrlimit(2) call.
83     * @param seInfo null-ok a string specifying SELinux information for
84     * the new process.
85     * @param niceName null-ok a string specifying the process name.
86     * @param fdsToClose an array of ints, holding one or more POSIX
87     * file descriptor numbers that are to be closed by the child
88     * (and replaced by /dev/null) after forking.  An integer value
89     * of -1 in any entry in the array means "ignore this one".
90     * @param fdsToIgnore null-ok an array of ints, either null or holding
91     * one or more POSIX file descriptor numbers that are to be ignored
92     * in the file descriptor table check.
93     * @param instructionSet null-ok the instruction set to use.
94     * @param appDataDir null-ok the data directory of the app.
95     *
96     * @return 0 if this is the child, pid of the child
97     * if this is the parent, or -1 on error.
98     */
99    public static int forkAndSpecialize(int uid, int gid, int[] gids, int debugFlags,
100          int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
101          int[] fdsToIgnore, String instructionSet, String appDataDir) {
102        VM_HOOKS.preFork();
103        // Resets nice priority for zygote process.
104        resetNicePriority();
105        int pid = nativeForkAndSpecialize(
106                  uid, gid, gids, debugFlags, rlimits, mountExternal, seInfo, niceName, fdsToClose,
107                  fdsToIgnore, instructionSet, appDataDir);
108        // Enable tracing as soon as possible for the child process.
109        if (pid == 0) {
110            Trace.setTracingEnabled(true);
111
112            // Note that this event ends at the end of handleChildProc,
113            Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "PostFork");
114        }
115        VM_HOOKS.postForkCommon();
116        return pid;
117    }
118
119    native private static int nativeForkAndSpecialize(int uid, int gid, int[] gids,int debugFlags,
120          int[][] rlimits, int mountExternal, String seInfo, String niceName, int[] fdsToClose,
121          int[] fdsToIgnore, String instructionSet, String appDataDir);
122
123    /**
124     * Special method to start the system server process. In addition to the
125     * common actions performed in forkAndSpecialize, the pid of the child
126     * process is recorded such that the death of the child process will cause
127     * zygote to exit.
128     *
129     * @param uid the UNIX uid that the new process should setuid() to after
130     * fork()ing and and before spawning any threads.
131     * @param gid the UNIX gid that the new process should setgid() to after
132     * fork()ing and and before spawning any threads.
133     * @param gids null-ok; a list of UNIX gids that the new process should
134     * setgroups() to after fork and before spawning any threads.
135     * @param debugFlags bit flags that enable debugging features.
136     * @param rlimits null-ok an array of rlimit tuples, with the second
137     * dimension having a length of 3 and representing
138     * (resource, rlim_cur, rlim_max). These are set via the posix
139     * setrlimit(2) call.
140     * @param permittedCapabilities argument for setcap()
141     * @param effectiveCapabilities argument for setcap()
142     *
143     * @return 0 if this is the child, pid of the child
144     * if this is the parent, or -1 on error.
145     */
146    public static int forkSystemServer(int uid, int gid, int[] gids, int debugFlags,
147            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities) {
148        VM_HOOKS.preFork();
149        // Resets nice priority for zygote process.
150        resetNicePriority();
151        int pid = nativeForkSystemServer(
152                uid, gid, gids, debugFlags, rlimits, permittedCapabilities, effectiveCapabilities);
153        // Enable tracing as soon as we enter the system_server.
154        if (pid == 0) {
155            Trace.setTracingEnabled(true);
156        }
157        VM_HOOKS.postForkCommon();
158        return pid;
159    }
160
161    native private static int nativeForkSystemServer(int uid, int gid, int[] gids, int debugFlags,
162            int[][] rlimits, long permittedCapabilities, long effectiveCapabilities);
163
164    /**
165     * Lets children of the zygote inherit open file descriptors to this path.
166     */
167    native protected static void nativeAllowFileAcrossFork(String path);
168
169    /**
170     * Zygote unmount storage space on initializing.
171     * This method is called once.
172     */
173    native protected static void nativeUnmountStorageOnInit();
174
175    private static void callPostForkChildHooks(int debugFlags, boolean isSystemServer,
176            String instructionSet) {
177        VM_HOOKS.postForkChild(debugFlags, isSystemServer, instructionSet);
178    }
179
180    /**
181     * Resets the calling thread priority to the default value (Thread.NORM_PRIORITY
182     * or nice value 0). This updates both the priority value in java.lang.Thread and
183     * the nice value (setpriority).
184     */
185    static void resetNicePriority() {
186        Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
187    }
188
189    /**
190     * Executes "/system/bin/sh -c &lt;command&gt;" using the exec() system call.
191     * This method throws a runtime exception if exec() failed, otherwise, this
192     * method never returns.
193     *
194     * @param command The shell command to execute.
195     */
196    public static void execShell(String command) {
197        String[] args = { "/system/bin/sh", "-c", command };
198        try {
199            Os.execv(args[0], args);
200        } catch (ErrnoException e) {
201            throw new RuntimeException(e);
202        }
203    }
204
205    /**
206     * Appends quotes shell arguments to the specified string builder.
207     * The arguments are quoted using single-quotes, escaped if necessary,
208     * prefixed with a space, and appended to the command.
209     *
210     * @param command A string builder for the shell command being constructed.
211     * @param args An array of argument strings to be quoted and appended to the command.
212     * @see #execShell(String)
213     */
214    public static void appendQuotedShellArgs(StringBuilder command, String[] args) {
215        for (String arg : args) {
216            command.append(" '").append(arg.replace("'", "'\\''")).append("'");
217        }
218    }
219
220    /**
221     * Helper exception class which holds a method and arguments and
222     * can call them. This is used as part of a trampoline to get rid of
223     * the initial process setup stack frames.
224     */
225    public static class MethodAndArgsCaller extends Exception
226            implements Runnable {
227        /** method to call */
228        private final Method mMethod;
229
230        /** argument array */
231        private final String[] mArgs;
232
233        public MethodAndArgsCaller(Method method, String[] args) {
234            mMethod = method;
235            mArgs = args;
236        }
237
238        public void run() {
239            try {
240                mMethod.invoke(null, new Object[] { mArgs });
241            } catch (IllegalAccessException ex) {
242                throw new RuntimeException(ex);
243            } catch (InvocationTargetException ex) {
244                Throwable cause = ex.getCause();
245                if (cause instanceof RuntimeException) {
246                    throw (RuntimeException) cause;
247                } else if (cause instanceof Error) {
248                    throw (Error) cause;
249                }
250                throw new RuntimeException(ex);
251            }
252        }
253    }
254}
255