blob: 70452006da2761eff2787c84895a7bcd69822a20 [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;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010022
Robert Sesekded20982016-08-15 13:59:13 -040023import com.android.internal.annotations.GuardedBy;
Robert Sesek8f8d1872016-03-18 16:52:57 -040024import com.android.internal.os.Zygote;
Robert Sesekded20982016-08-15 13:59:13 -040025import com.android.internal.util.Preconditions;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010026
Robert Sesek8f8d1872016-03-18 16:52:57 -040027import java.io.BufferedWriter;
28import java.io.DataInputStream;
29import java.io.IOException;
30import java.io.OutputStreamWriter;
31import java.nio.charset.StandardCharsets;
32import java.util.ArrayList;
33import java.util.Arrays;
34import java.util.List;
35
36/*package*/ class ZygoteStartFailedEx extends Exception {
37 ZygoteStartFailedEx(String s) {
38 super(s);
39 }
40
41 ZygoteStartFailedEx(Throwable cause) {
42 super(cause);
43 }
44
45 ZygoteStartFailedEx(String s, Throwable cause) {
46 super(s, cause);
47 }
48}
49
50/**
51 * Maintains communication state with the zygote processes. This class is responsible
52 * for the sockets opened to the zygotes and for starting processes on behalf of the
53 * {@link android.os.Process} class.
54 *
55 * {@hide}
56 */
57public class ZygoteProcess {
58 private static final String LOG_TAG = "ZygoteProcess";
59
60 /**
61 * The name of the socket used to communicate with the primary zygote.
62 */
63 private final String mSocket;
64
65 /**
66 * The name of the secondary (alternate ABI) zygote socket.
67 */
68 private final String mSecondarySocket;
69
70 public ZygoteProcess(String primarySocket, String secondarySocket) {
71 mSocket = primarySocket;
72 mSecondarySocket = secondarySocket;
73 }
74
75 /**
76 * State for communicating with the zygote process.
77 */
78 public static class ZygoteState {
79 final LocalSocket socket;
80 final DataInputStream inputStream;
81 final BufferedWriter writer;
82 final List<String> abiList;
83
84 boolean mClosed;
85
86 private ZygoteState(LocalSocket socket, DataInputStream inputStream,
87 BufferedWriter writer, List<String> abiList) {
88 this.socket = socket;
89 this.inputStream = inputStream;
90 this.writer = writer;
91 this.abiList = abiList;
92 }
93
94 public static ZygoteState connect(String socketAddress) throws IOException {
95 DataInputStream zygoteInputStream = null;
96 BufferedWriter zygoteWriter = null;
97 final LocalSocket zygoteSocket = new LocalSocket();
98
99 try {
100 zygoteSocket.connect(new LocalSocketAddress(socketAddress,
101 LocalSocketAddress.Namespace.RESERVED));
102
103 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
104
105 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
106 zygoteSocket.getOutputStream()), 256);
107 } catch (IOException ex) {
108 try {
109 zygoteSocket.close();
110 } catch (IOException ignore) {
111 }
112
113 throw ex;
114 }
115
116 String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
Robert Sesekded20982016-08-15 13:59:13 -0400117 Log.i("Zygote", "Process: zygote socket " + socketAddress + " opened, supported ABIS: "
118 + abiListString);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400119
120 return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
121 Arrays.asList(abiListString.split(",")));
122 }
123
124 boolean matches(String abi) {
125 return abiList.contains(abi);
126 }
127
128 public void close() {
129 try {
130 socket.close();
131 } catch (IOException ex) {
132 Log.e(LOG_TAG,"I/O exception on routine close", ex);
133 }
134
135 mClosed = true;
136 }
137
138 boolean isClosed() {
139 return mClosed;
140 }
141 }
142
143 /**
Robert Sesekded20982016-08-15 13:59:13 -0400144 * Lock object to protect access to the two ZygoteStates below. This lock must be
145 * acquired while communicating over the ZygoteState's socket, to prevent
146 * interleaved access.
147 */
148 private final Object mLock = new Object();
149
150 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400151 * The state of the connection to the primary zygote.
152 */
153 private ZygoteState primaryZygoteState;
154
155 /**
156 * The state of the connection to the secondary zygote.
157 */
158 private ZygoteState secondaryZygoteState;
159
160 /**
161 * Start a new process.
162 *
163 * <p>If processes are enabled, a new process is created and the
164 * static main() function of a <var>processClass</var> is executed there.
165 * The process will continue running after this function returns.
166 *
167 * <p>If processes are not enabled, a new thread in the caller's
168 * process is created and main() of <var>processClass</var> called there.
169 *
170 * <p>The niceName parameter, if not an empty string, is a custom name to
171 * give to the process instead of using processClass. This allows you to
172 * make easily identifyable processes even if you are using the same base
173 * <var>processClass</var> to start them.
174 *
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000175 * When invokeWith is not null, the process will be started as a fresh app
Tamas Berghammer0ca16fa2016-11-11 16:08:26 +0000176 * and not a zygote fork. Note that this is only allowed for uid 0 or when
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100177 * runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000178 *
Robert Sesek8f8d1872016-03-18 16:52:57 -0400179 * @param processClass The class to use as the process's main entry
180 * point.
181 * @param niceName A more readable name to use for the process.
182 * @param uid The user-id under which the process will run.
183 * @param gid The group-id under which the process will run.
184 * @param gids Additional group-ids associated with the process.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100185 * @param runtimeFlags Additional flags.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400186 * @param targetSdkVersion The target SDK version for the app.
187 * @param seInfo null-ok SELinux information for the new process.
188 * @param abi non-null the ABI this app should be started with.
189 * @param instructionSet null-ok the instruction set to use.
190 * @param appDataDir null-ok the data directory of the app.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000191 * @param invokeWith null-ok the command to invoke with.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400192 * @param zygoteArgs Additional arguments to supply to the zygote process.
193 *
194 * @return An object that describes the result of the attempt to start the process.
195 * @throws RuntimeException on fatal start failure
196 */
197 public final Process.ProcessStartResult start(final String processClass,
198 final String niceName,
199 int uid, int gid, int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100200 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400201 int targetSdkVersion,
202 String seInfo,
203 String abi,
204 String instructionSet,
205 String appDataDir,
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000206 String invokeWith,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400207 String[] zygoteArgs) {
208 try {
209 return startViaZygote(processClass, niceName, uid, gid, gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100210 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000211 abi, instructionSet, appDataDir, invokeWith, zygoteArgs);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400212 } catch (ZygoteStartFailedEx ex) {
213 Log.e(LOG_TAG,
214 "Starting VM process through Zygote failed");
215 throw new RuntimeException(
216 "Starting VM process through Zygote failed", ex);
217 }
218 }
219
220 /** retry interval for opening a zygote socket */
221 static final int ZYGOTE_RETRY_MILLIS = 500;
222
223 /**
224 * Queries the zygote for the list of ABIS it supports.
225 *
226 * @throws ZygoteStartFailedEx if the query failed.
227 */
Robert Sesekded20982016-08-15 13:59:13 -0400228 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400229 private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
230 throws IOException {
231 // Each query starts with the argument count (1 in this case)
232 writer.write("1");
233 // ... followed by a new-line.
234 writer.newLine();
235 // ... followed by our only argument.
236 writer.write("--query-abi-list");
237 writer.newLine();
238 writer.flush();
239
240 // The response is a length prefixed stream of ASCII bytes.
241 int numBytes = inputStream.readInt();
242 byte[] bytes = new byte[numBytes];
243 inputStream.readFully(bytes);
244
245 return new String(bytes, StandardCharsets.US_ASCII);
246 }
247
248 /**
249 * Sends an argument list to the zygote process, which starts a new child
250 * and returns the child's pid. Please note: the present implementation
251 * replaces newlines in the argument list with spaces.
252 *
253 * @throws ZygoteStartFailedEx if process start failed for any reason
254 */
Robert Sesekded20982016-08-15 13:59:13 -0400255 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400256 private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
257 ZygoteState zygoteState, ArrayList<String> args)
258 throws ZygoteStartFailedEx {
259 try {
Robert Sesek0b58f192016-10-10 18:34:42 -0400260 // Throw early if any of the arguments are malformed. This means we can
261 // avoid writing a partial response to the zygote.
262 int sz = args.size();
263 for (int i = 0; i < sz; i++) {
264 if (args.get(i).indexOf('\n') >= 0) {
265 throw new ZygoteStartFailedEx("embedded newlines not allowed");
266 }
267 }
268
Robert Sesek8f8d1872016-03-18 16:52:57 -0400269 /**
270 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
271 * Presently the wire format to the zygote process is:
272 * a) a count of arguments (argc, in essence)
273 * b) a number of newline-separated argument strings equal to count
274 *
275 * After the zygote process reads these it will write the pid of
276 * the child or -1 on failure, followed by boolean to
277 * indicate whether a wrapper process was used.
278 */
279 final BufferedWriter writer = zygoteState.writer;
280 final DataInputStream inputStream = zygoteState.inputStream;
281
282 writer.write(Integer.toString(args.size()));
283 writer.newLine();
284
Robert Sesek8f8d1872016-03-18 16:52:57 -0400285 for (int i = 0; i < sz; i++) {
286 String arg = args.get(i);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400287 writer.write(arg);
288 writer.newLine();
289 }
290
291 writer.flush();
292
293 // Should there be a timeout on this?
294 Process.ProcessStartResult result = new Process.ProcessStartResult();
Robert Sesek0b58f192016-10-10 18:34:42 -0400295
296 // Always read the entire result from the input stream to avoid leaving
297 // bytes in the stream for future process starts to accidentally stumble
298 // upon.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400299 result.pid = inputStream.readInt();
Robert Sesek0b58f192016-10-10 18:34:42 -0400300 result.usingWrapper = inputStream.readBoolean();
301
Robert Sesek8f8d1872016-03-18 16:52:57 -0400302 if (result.pid < 0) {
303 throw new ZygoteStartFailedEx("fork() failed");
304 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400305 return result;
306 } catch (IOException ex) {
307 zygoteState.close();
308 throw new ZygoteStartFailedEx(ex);
309 }
310 }
311
312 /**
313 * Starts a new process via the zygote mechanism.
314 *
315 * @param processClass Class name whose static main() to run
316 * @param niceName 'nice' process name to appear in ps
317 * @param uid a POSIX uid that the new process should setuid() to
318 * @param gid a POSIX gid that the new process shuold setgid() to
319 * @param gids null-ok; a list of supplementary group IDs that the
320 * new process should setgroup() to.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100321 * @param runtimeFlags Additional flags for the runtime.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400322 * @param targetSdkVersion The target SDK version for the app.
323 * @param seInfo null-ok SELinux information for the new process.
324 * @param abi the ABI the process should use.
325 * @param instructionSet null-ok the instruction set to use.
326 * @param appDataDir null-ok the data directory of the app.
327 * @param extraArgs Additional arguments to supply to the zygote process.
328 * @return An object that describes the result of the attempt to start the process.
329 * @throws ZygoteStartFailedEx if process start failed for any reason
330 */
331 private Process.ProcessStartResult startViaZygote(final String processClass,
332 final String niceName,
333 final int uid, final int gid,
334 final int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100335 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400336 int targetSdkVersion,
337 String seInfo,
338 String abi,
339 String instructionSet,
340 String appDataDir,
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000341 String invokeWith,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400342 String[] extraArgs)
343 throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400344 ArrayList<String> argsForZygote = new ArrayList<String>();
Robert Sesek8f8d1872016-03-18 16:52:57 -0400345
Robert Sesekded20982016-08-15 13:59:13 -0400346 // --runtime-args, --setuid=, --setgid=,
347 // and --setgroups= must go first
348 argsForZygote.add("--runtime-args");
349 argsForZygote.add("--setuid=" + uid);
350 argsForZygote.add("--setgid=" + gid);
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100351 argsForZygote.add("--runtime-flags=" + runtimeFlags);
Robert Sesekded20982016-08-15 13:59:13 -0400352 if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
353 argsForZygote.add("--mount-external-default");
354 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
355 argsForZygote.add("--mount-external-read");
356 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
357 argsForZygote.add("--mount-external-write");
358 }
359 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400360
Robert Sesekded20982016-08-15 13:59:13 -0400361 // --setgroups is a comma-separated list
362 if (gids != null && gids.length > 0) {
363 StringBuilder sb = new StringBuilder();
364 sb.append("--setgroups=");
Robert Sesek8f8d1872016-03-18 16:52:57 -0400365
Robert Sesekded20982016-08-15 13:59:13 -0400366 int sz = gids.length;
367 for (int i = 0; i < sz; i++) {
368 if (i != 0) {
369 sb.append(',');
Robert Sesek8f8d1872016-03-18 16:52:57 -0400370 }
Robert Sesekded20982016-08-15 13:59:13 -0400371 sb.append(gids[i]);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400372 }
373
Robert Sesekded20982016-08-15 13:59:13 -0400374 argsForZygote.add(sb.toString());
375 }
376
377 if (niceName != null) {
378 argsForZygote.add("--nice-name=" + niceName);
379 }
380
381 if (seInfo != null) {
382 argsForZygote.add("--seinfo=" + seInfo);
383 }
384
385 if (instructionSet != null) {
386 argsForZygote.add("--instruction-set=" + instructionSet);
387 }
388
389 if (appDataDir != null) {
390 argsForZygote.add("--app-data-dir=" + appDataDir);
391 }
392
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000393 if (invokeWith != null) {
394 argsForZygote.add("--invoke-with");
395 argsForZygote.add(invokeWith);
396 }
397
Robert Sesekded20982016-08-15 13:59:13 -0400398 argsForZygote.add(processClass);
399
400 if (extraArgs != null) {
401 for (String arg : extraArgs) {
402 argsForZygote.add(arg);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400403 }
Robert Sesekded20982016-08-15 13:59:13 -0400404 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400405
Robert Sesekded20982016-08-15 13:59:13 -0400406 synchronized(mLock) {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400407 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 {
Robert Sesekded20982016-08-15 13:59:13 -0400418 synchronized(mLock) {
419 openZygoteSocketIfNeeded(abi);
420 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400421 } catch (ZygoteStartFailedEx ex) {
422 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
423 }
424 }
425
426 /**
427 * Tries to open socket to Zygote process if not already open. If
Robert Sesekded20982016-08-15 13:59:13 -0400428 * already open, does nothing. May block and retry. Requires that mLock be held.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400429 */
Robert Sesekded20982016-08-15 13:59:13 -0400430 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400431 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400432 Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
433
Robert Sesek8f8d1872016-03-18 16:52:57 -0400434 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
435 try {
436 primaryZygoteState = ZygoteState.connect(mSocket);
437 } catch (IOException ioe) {
438 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
439 }
440 }
441
442 if (primaryZygoteState.matches(abi)) {
443 return primaryZygoteState;
444 }
445
446 // The primary zygote didn't match. Try the secondary.
447 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
448 try {
449 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
450 } catch (IOException ioe) {
451 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
452 }
453 }
454
455 if (secondaryZygoteState.matches(abi)) {
456 return secondaryZygoteState;
457 }
458
459 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
460 }
Robert Sesekded20982016-08-15 13:59:13 -0400461
462 /**
463 * Instructs the zygote to pre-load the classes and native libraries at the given paths
464 * for the specified abi. Not all zygotes support this function.
465 */
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000466 public void preloadPackageForAbi(String packagePath, String libsPath, String cacheKey,
467 String abi) throws ZygoteStartFailedEx, IOException {
Robert Sesekded20982016-08-15 13:59:13 -0400468 synchronized(mLock) {
469 ZygoteState state = openZygoteSocketIfNeeded(abi);
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000470 state.writer.write("4");
Robert Sesekded20982016-08-15 13:59:13 -0400471 state.writer.newLine();
472
473 state.writer.write("--preload-package");
474 state.writer.newLine();
475
476 state.writer.write(packagePath);
477 state.writer.newLine();
478
479 state.writer.write(libsPath);
480 state.writer.newLine();
481
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000482 state.writer.write(cacheKey);
483 state.writer.newLine();
484
Robert Sesekded20982016-08-15 13:59:13 -0400485 state.writer.flush();
486 }
487 }
Narayan Kamath669afcc2017-02-06 20:24:08 +0000488
489 /**
490 * Instructs the zygote to preload the default set of classes and resources. Returns
491 * {@code true} if a preload was performed as a result of this call, and {@code false}
492 * otherwise. The latter usually means that the zygote eagerly preloaded at startup
493 * or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
494 */
495 public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
496 synchronized (mLock) {
497 ZygoteState state = openZygoteSocketIfNeeded(abi);
498 // Each query starts with the argument count (1 in this case)
499 state.writer.write("1");
500 state.writer.newLine();
501 state.writer.write("--preload-default");
502 state.writer.newLine();
503 state.writer.flush();
504
505 return (state.inputStream.readInt() == 0);
506 }
507 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400508}