blob: f050d767556252b9c85c7ff89573d5076015d0f6 [file] [log] [blame]
Robert Sesek8f8d1872016-03-18 16:52:57 -04001/*
2 * Copyright (C) 2016 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 android.os;
18
19import android.net.LocalSocket;
20import android.net.LocalSocketAddress;
21import android.util.Log;
22import com.android.internal.os.Zygote;
23import java.io.BufferedWriter;
24import java.io.DataInputStream;
25import java.io.IOException;
26import java.io.OutputStreamWriter;
27import java.nio.charset.StandardCharsets;
28import java.util.ArrayList;
29import java.util.Arrays;
30import java.util.List;
31
32/*package*/ class ZygoteStartFailedEx extends Exception {
33 ZygoteStartFailedEx(String s) {
34 super(s);
35 }
36
37 ZygoteStartFailedEx(Throwable cause) {
38 super(cause);
39 }
40
41 ZygoteStartFailedEx(String s, Throwable cause) {
42 super(s, cause);
43 }
44}
45
46/**
47 * Maintains communication state with the zygote processes. This class is responsible
48 * for the sockets opened to the zygotes and for starting processes on behalf of the
49 * {@link android.os.Process} class.
50 *
51 * {@hide}
52 */
53public class ZygoteProcess {
54 private static final String LOG_TAG = "ZygoteProcess";
55
56 /**
57 * The name of the socket used to communicate with the primary zygote.
58 */
59 private final String mSocket;
60
61 /**
62 * The name of the secondary (alternate ABI) zygote socket.
63 */
64 private final String mSecondarySocket;
65
66 public ZygoteProcess(String primarySocket, String secondarySocket) {
67 mSocket = primarySocket;
68 mSecondarySocket = secondarySocket;
69 }
70
71 /**
72 * State for communicating with the zygote process.
73 */
74 public static class ZygoteState {
75 final LocalSocket socket;
76 final DataInputStream inputStream;
77 final BufferedWriter writer;
78 final List<String> abiList;
79
80 boolean mClosed;
81
82 private ZygoteState(LocalSocket socket, DataInputStream inputStream,
83 BufferedWriter writer, List<String> abiList) {
84 this.socket = socket;
85 this.inputStream = inputStream;
86 this.writer = writer;
87 this.abiList = abiList;
88 }
89
90 public static ZygoteState connect(String socketAddress) throws IOException {
91 DataInputStream zygoteInputStream = null;
92 BufferedWriter zygoteWriter = null;
93 final LocalSocket zygoteSocket = new LocalSocket();
94
95 try {
96 zygoteSocket.connect(new LocalSocketAddress(socketAddress,
97 LocalSocketAddress.Namespace.RESERVED));
98
99 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
100
101 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
102 zygoteSocket.getOutputStream()), 256);
103 } catch (IOException ex) {
104 try {
105 zygoteSocket.close();
106 } catch (IOException ignore) {
107 }
108
109 throw ex;
110 }
111
112 String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
113 Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);
114
115 return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
116 Arrays.asList(abiListString.split(",")));
117 }
118
119 boolean matches(String abi) {
120 return abiList.contains(abi);
121 }
122
123 public void close() {
124 try {
125 socket.close();
126 } catch (IOException ex) {
127 Log.e(LOG_TAG,"I/O exception on routine close", ex);
128 }
129
130 mClosed = true;
131 }
132
133 boolean isClosed() {
134 return mClosed;
135 }
136 }
137
138 /**
139 * The state of the connection to the primary zygote.
140 */
141 private ZygoteState primaryZygoteState;
142
143 /**
144 * The state of the connection to the secondary zygote.
145 */
146 private ZygoteState secondaryZygoteState;
147
148 /**
149 * Start a new process.
150 *
151 * <p>If processes are enabled, a new process is created and the
152 * static main() function of a <var>processClass</var> is executed there.
153 * The process will continue running after this function returns.
154 *
155 * <p>If processes are not enabled, a new thread in the caller's
156 * process is created and main() of <var>processClass</var> called there.
157 *
158 * <p>The niceName parameter, if not an empty string, is a custom name to
159 * give to the process instead of using processClass. This allows you to
160 * make easily identifyable processes even if you are using the same base
161 * <var>processClass</var> to start them.
162 *
163 * @param processClass The class to use as the process's main entry
164 * point.
165 * @param niceName A more readable name to use for the process.
166 * @param uid The user-id under which the process will run.
167 * @param gid The group-id under which the process will run.
168 * @param gids Additional group-ids associated with the process.
169 * @param debugFlags Additional flags.
170 * @param targetSdkVersion The target SDK version for the app.
171 * @param seInfo null-ok SELinux information for the new process.
172 * @param abi non-null the ABI this app should be started with.
173 * @param instructionSet null-ok the instruction set to use.
174 * @param appDataDir null-ok the data directory of the app.
175 * @param zygoteArgs Additional arguments to supply to the zygote process.
176 *
177 * @return An object that describes the result of the attempt to start the process.
178 * @throws RuntimeException on fatal start failure
179 */
180 public final Process.ProcessStartResult start(final String processClass,
181 final String niceName,
182 int uid, int gid, int[] gids,
183 int debugFlags, int mountExternal,
184 int targetSdkVersion,
185 String seInfo,
186 String abi,
187 String instructionSet,
188 String appDataDir,
189 String[] zygoteArgs) {
190 try {
191 return startViaZygote(processClass, niceName, uid, gid, gids,
192 debugFlags, mountExternal, targetSdkVersion, seInfo,
193 abi, instructionSet, appDataDir, zygoteArgs);
194 } catch (ZygoteStartFailedEx ex) {
195 Log.e(LOG_TAG,
196 "Starting VM process through Zygote failed");
197 throw new RuntimeException(
198 "Starting VM process through Zygote failed", ex);
199 }
200 }
201
202 /** retry interval for opening a zygote socket */
203 static final int ZYGOTE_RETRY_MILLIS = 500;
204
205 /**
206 * Queries the zygote for the list of ABIS it supports.
207 *
208 * @throws ZygoteStartFailedEx if the query failed.
209 */
210 private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
211 throws IOException {
212 // Each query starts with the argument count (1 in this case)
213 writer.write("1");
214 // ... followed by a new-line.
215 writer.newLine();
216 // ... followed by our only argument.
217 writer.write("--query-abi-list");
218 writer.newLine();
219 writer.flush();
220
221 // The response is a length prefixed stream of ASCII bytes.
222 int numBytes = inputStream.readInt();
223 byte[] bytes = new byte[numBytes];
224 inputStream.readFully(bytes);
225
226 return new String(bytes, StandardCharsets.US_ASCII);
227 }
228
229 /**
230 * Sends an argument list to the zygote process, which starts a new child
231 * and returns the child's pid. Please note: the present implementation
232 * replaces newlines in the argument list with spaces.
233 *
234 * @throws ZygoteStartFailedEx if process start failed for any reason
235 */
236 private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
237 ZygoteState zygoteState, ArrayList<String> args)
238 throws ZygoteStartFailedEx {
239 try {
Robert Sesek0b58f192016-10-10 18:34:42 -0400240 // Throw early if any of the arguments are malformed. This means we can
241 // avoid writing a partial response to the zygote.
242 int sz = args.size();
243 for (int i = 0; i < sz; i++) {
244 if (args.get(i).indexOf('\n') >= 0) {
245 throw new ZygoteStartFailedEx("embedded newlines not allowed");
246 }
247 }
248
Robert Sesek8f8d1872016-03-18 16:52:57 -0400249 /**
250 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
251 * Presently the wire format to the zygote process is:
252 * a) a count of arguments (argc, in essence)
253 * b) a number of newline-separated argument strings equal to count
254 *
255 * After the zygote process reads these it will write the pid of
256 * the child or -1 on failure, followed by boolean to
257 * indicate whether a wrapper process was used.
258 */
259 final BufferedWriter writer = zygoteState.writer;
260 final DataInputStream inputStream = zygoteState.inputStream;
261
262 writer.write(Integer.toString(args.size()));
263 writer.newLine();
264
Robert Sesek8f8d1872016-03-18 16:52:57 -0400265 for (int i = 0; i < sz; i++) {
266 String arg = args.get(i);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400267 writer.write(arg);
268 writer.newLine();
269 }
270
271 writer.flush();
272
273 // Should there be a timeout on this?
274 Process.ProcessStartResult result = new Process.ProcessStartResult();
Robert Sesek0b58f192016-10-10 18:34:42 -0400275
276 // Always read the entire result from the input stream to avoid leaving
277 // bytes in the stream for future process starts to accidentally stumble
278 // upon.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400279 result.pid = inputStream.readInt();
Robert Sesek0b58f192016-10-10 18:34:42 -0400280 result.usingWrapper = inputStream.readBoolean();
281
Robert Sesek8f8d1872016-03-18 16:52:57 -0400282 if (result.pid < 0) {
283 throw new ZygoteStartFailedEx("fork() failed");
284 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400285 return result;
286 } catch (IOException ex) {
287 zygoteState.close();
288 throw new ZygoteStartFailedEx(ex);
289 }
290 }
291
292 /**
293 * Starts a new process via the zygote mechanism.
294 *
295 * @param processClass Class name whose static main() to run
296 * @param niceName 'nice' process name to appear in ps
297 * @param uid a POSIX uid that the new process should setuid() to
298 * @param gid a POSIX gid that the new process shuold setgid() to
299 * @param gids null-ok; a list of supplementary group IDs that the
300 * new process should setgroup() to.
301 * @param debugFlags Additional flags.
302 * @param targetSdkVersion The target SDK version for the app.
303 * @param seInfo null-ok SELinux information for the new process.
304 * @param abi the ABI the process should use.
305 * @param instructionSet null-ok the instruction set to use.
306 * @param appDataDir null-ok the data directory of the app.
307 * @param extraArgs Additional arguments to supply to the zygote process.
308 * @return An object that describes the result of the attempt to start the process.
309 * @throws ZygoteStartFailedEx if process start failed for any reason
310 */
311 private Process.ProcessStartResult startViaZygote(final String processClass,
312 final String niceName,
313 final int uid, final int gid,
314 final int[] gids,
315 int debugFlags, int mountExternal,
316 int targetSdkVersion,
317 String seInfo,
318 String abi,
319 String instructionSet,
320 String appDataDir,
321 String[] extraArgs)
322 throws ZygoteStartFailedEx {
323 synchronized(Process.class) {
324 ArrayList<String> argsForZygote = new ArrayList<String>();
325
326 // --runtime-args, --setuid=, --setgid=,
327 // and --setgroups= must go first
328 argsForZygote.add("--runtime-args");
329 argsForZygote.add("--setuid=" + uid);
330 argsForZygote.add("--setgid=" + gid);
331 if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
332 argsForZygote.add("--enable-jni-logging");
333 }
334 if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
335 argsForZygote.add("--enable-safemode");
336 }
337 if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
338 argsForZygote.add("--enable-debugger");
339 }
340 if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
341 argsForZygote.add("--enable-checkjni");
342 }
343 if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) {
344 argsForZygote.add("--generate-debug-info");
345 }
346 if ((debugFlags & Zygote.DEBUG_ALWAYS_JIT) != 0) {
347 argsForZygote.add("--always-jit");
348 }
349 if ((debugFlags & Zygote.DEBUG_NATIVE_DEBUGGABLE) != 0) {
350 argsForZygote.add("--native-debuggable");
351 }
352 if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
353 argsForZygote.add("--enable-assert");
354 }
355 if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
356 argsForZygote.add("--mount-external-default");
357 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
358 argsForZygote.add("--mount-external-read");
359 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
360 argsForZygote.add("--mount-external-write");
361 }
362 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
363
364 //TODO optionally enable debuger
365 //argsForZygote.add("--enable-debugger");
366
367 // --setgroups is a comma-separated list
368 if (gids != null && gids.length > 0) {
369 StringBuilder sb = new StringBuilder();
370 sb.append("--setgroups=");
371
372 int sz = gids.length;
373 for (int i = 0; i < sz; i++) {
374 if (i != 0) {
375 sb.append(',');
376 }
377 sb.append(gids[i]);
378 }
379
380 argsForZygote.add(sb.toString());
381 }
382
383 if (niceName != null) {
384 argsForZygote.add("--nice-name=" + niceName);
385 }
386
387 if (seInfo != null) {
388 argsForZygote.add("--seinfo=" + seInfo);
389 }
390
391 if (instructionSet != null) {
392 argsForZygote.add("--instruction-set=" + instructionSet);
393 }
394
395 if (appDataDir != null) {
396 argsForZygote.add("--app-data-dir=" + appDataDir);
397 }
398
399 argsForZygote.add(processClass);
400
401 if (extraArgs != null) {
402 for (String arg : extraArgs) {
403 argsForZygote.add(arg);
404 }
405 }
406
407 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
408 }
409 }
410
411 /**
412 * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
413 * and retry if the zygote is unresponsive. This method is a no-op if a connection is
414 * already open.
415 */
416 public void establishZygoteConnectionForAbi(String abi) {
417 try {
418 openZygoteSocketIfNeeded(abi);
419 } catch (ZygoteStartFailedEx ex) {
420 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
421 }
422 }
423
424 /**
425 * Tries to open socket to Zygote process if not already open. If
426 * already open, does nothing. May block and retry.
427 */
428 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
429 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
430 try {
431 primaryZygoteState = ZygoteState.connect(mSocket);
432 } catch (IOException ioe) {
433 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
434 }
435 }
436
437 if (primaryZygoteState.matches(abi)) {
438 return primaryZygoteState;
439 }
440
441 // The primary zygote didn't match. Try the secondary.
442 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
443 try {
444 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
445 } catch (IOException ioe) {
446 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
447 }
448 }
449
450 if (secondaryZygoteState.matches(abi)) {
451 return secondaryZygoteState;
452 }
453
454 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
455 }
456}