blob: 57418c8b98799988938fdf6b8d8d76ac0c21417b [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;
Gustav Senntonf0c52b52017-04-27 17:00:50 +010022import android.util.Slog;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010023
Robert Sesekded20982016-08-15 13:59:13 -040024import com.android.internal.annotations.GuardedBy;
Robert Sesek8f8d1872016-03-18 16:52:57 -040025import com.android.internal.os.Zygote;
Robert Sesekded20982016-08-15 13:59:13 -040026import com.android.internal.util.Preconditions;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010027
Robert Sesek8f8d1872016-03-18 16:52:57 -040028import java.io.BufferedWriter;
29import java.io.DataInputStream;
30import java.io.IOException;
31import java.io.OutputStreamWriter;
32import java.nio.charset.StandardCharsets;
33import java.util.ArrayList;
34import java.util.Arrays;
35import java.util.List;
Robert Sesekd0a190df2018-02-12 18:46:01 -050036import java.util.UUID;
Robert Sesek8f8d1872016-03-18 16:52:57 -040037
38/*package*/ class ZygoteStartFailedEx extends Exception {
39 ZygoteStartFailedEx(String s) {
40 super(s);
41 }
42
43 ZygoteStartFailedEx(Throwable cause) {
44 super(cause);
45 }
46
47 ZygoteStartFailedEx(String s, Throwable cause) {
48 super(s, cause);
49 }
50}
51
52/**
53 * Maintains communication state with the zygote processes. This class is responsible
54 * for the sockets opened to the zygotes and for starting processes on behalf of the
55 * {@link android.os.Process} class.
56 *
57 * {@hide}
58 */
59public class ZygoteProcess {
60 private static final String LOG_TAG = "ZygoteProcess";
61
62 /**
63 * The name of the socket used to communicate with the primary zygote.
64 */
Robert Sesek5ac8abf2018-01-26 14:26:53 -050065 private final LocalSocketAddress mSocket;
Robert Sesek8f8d1872016-03-18 16:52:57 -040066
67 /**
68 * The name of the secondary (alternate ABI) zygote socket.
69 */
Robert Sesek5ac8abf2018-01-26 14:26:53 -050070 private final LocalSocketAddress mSecondarySocket;
Robert Sesek8f8d1872016-03-18 16:52:57 -040071
72 public ZygoteProcess(String primarySocket, String secondarySocket) {
Robert Sesek5ac8abf2018-01-26 14:26:53 -050073 this(new LocalSocketAddress(primarySocket, LocalSocketAddress.Namespace.RESERVED),
74 new LocalSocketAddress(secondarySocket, LocalSocketAddress.Namespace.RESERVED));
75 }
76
77 public ZygoteProcess(LocalSocketAddress primarySocket, LocalSocketAddress secondarySocket) {
Robert Sesek8f8d1872016-03-18 16:52:57 -040078 mSocket = primarySocket;
79 mSecondarySocket = secondarySocket;
80 }
81
Robert Sesek5ac8abf2018-01-26 14:26:53 -050082 public LocalSocketAddress getPrimarySocketAddress() {
83 return mSocket;
84 }
85
Robert Sesek8f8d1872016-03-18 16:52:57 -040086 /**
87 * State for communicating with the zygote process.
88 */
89 public static class ZygoteState {
90 final LocalSocket socket;
91 final DataInputStream inputStream;
92 final BufferedWriter writer;
93 final List<String> abiList;
94
95 boolean mClosed;
96
97 private ZygoteState(LocalSocket socket, DataInputStream inputStream,
98 BufferedWriter writer, List<String> abiList) {
99 this.socket = socket;
100 this.inputStream = inputStream;
101 this.writer = writer;
102 this.abiList = abiList;
103 }
104
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500105 public static ZygoteState connect(LocalSocketAddress address) throws IOException {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400106 DataInputStream zygoteInputStream = null;
107 BufferedWriter zygoteWriter = null;
108 final LocalSocket zygoteSocket = new LocalSocket();
109
110 try {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500111 zygoteSocket.connect(address);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400112
113 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
114
115 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
116 zygoteSocket.getOutputStream()), 256);
117 } catch (IOException ex) {
118 try {
119 zygoteSocket.close();
120 } catch (IOException ignore) {
121 }
122
123 throw ex;
124 }
125
126 String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500127 Log.i("Zygote", "Process: zygote socket " + address.getNamespace() + "/"
128 + address.getName() + " opened, supported ABIS: " + abiListString);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400129
130 return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
131 Arrays.asList(abiListString.split(",")));
132 }
133
134 boolean matches(String abi) {
135 return abiList.contains(abi);
136 }
137
138 public void close() {
139 try {
140 socket.close();
141 } catch (IOException ex) {
142 Log.e(LOG_TAG,"I/O exception on routine close", ex);
143 }
144
145 mClosed = true;
146 }
147
148 boolean isClosed() {
149 return mClosed;
150 }
151 }
152
153 /**
Robert Sesekded20982016-08-15 13:59:13 -0400154 * Lock object to protect access to the two ZygoteStates below. This lock must be
155 * acquired while communicating over the ZygoteState's socket, to prevent
156 * interleaved access.
157 */
158 private final Object mLock = new Object();
159
160 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400161 * The state of the connection to the primary zygote.
162 */
163 private ZygoteState primaryZygoteState;
164
165 /**
166 * The state of the connection to the secondary zygote.
167 */
168 private ZygoteState secondaryZygoteState;
169
170 /**
171 * Start a new process.
172 *
173 * <p>If processes are enabled, a new process is created and the
174 * static main() function of a <var>processClass</var> is executed there.
175 * The process will continue running after this function returns.
176 *
177 * <p>If processes are not enabled, a new thread in the caller's
178 * process is created and main() of <var>processClass</var> called there.
179 *
180 * <p>The niceName parameter, if not an empty string, is a custom name to
181 * give to the process instead of using processClass. This allows you to
182 * make easily identifyable processes even if you are using the same base
183 * <var>processClass</var> to start them.
184 *
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000185 * When invokeWith is not null, the process will be started as a fresh app
Tamas Berghammer0ca16fa2016-11-11 16:08:26 +0000186 * and not a zygote fork. Note that this is only allowed for uid 0 or when
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100187 * runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000188 *
Robert Sesek8f8d1872016-03-18 16:52:57 -0400189 * @param processClass The class to use as the process's main entry
190 * point.
191 * @param niceName A more readable name to use for the process.
192 * @param uid The user-id under which the process will run.
193 * @param gid The group-id under which the process will run.
194 * @param gids Additional group-ids associated with the process.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100195 * @param runtimeFlags Additional flags.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400196 * @param targetSdkVersion The target SDK version for the app.
197 * @param seInfo null-ok SELinux information for the new process.
198 * @param abi non-null the ABI this app should be started with.
199 * @param instructionSet null-ok the instruction set to use.
200 * @param appDataDir null-ok the data directory of the app.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000201 * @param invokeWith null-ok the command to invoke with.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400202 * @param zygoteArgs Additional arguments to supply to the zygote process.
203 *
204 * @return An object that describes the result of the attempt to start the process.
205 * @throws RuntimeException on fatal start failure
206 */
207 public final Process.ProcessStartResult start(final String processClass,
208 final String niceName,
209 int uid, int gid, int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100210 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400211 int targetSdkVersion,
212 String seInfo,
213 String abi,
214 String instructionSet,
215 String appDataDir,
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000216 String invokeWith,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400217 String[] zygoteArgs) {
218 try {
219 return startViaZygote(processClass, niceName, uid, gid, gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100220 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500221 abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
222 zygoteArgs);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400223 } catch (ZygoteStartFailedEx ex) {
224 Log.e(LOG_TAG,
225 "Starting VM process through Zygote failed");
226 throw new RuntimeException(
227 "Starting VM process through Zygote failed", ex);
228 }
229 }
230
231 /** retry interval for opening a zygote socket */
232 static final int ZYGOTE_RETRY_MILLIS = 500;
233
234 /**
235 * Queries the zygote for the list of ABIS it supports.
236 *
237 * @throws ZygoteStartFailedEx if the query failed.
238 */
Robert Sesekded20982016-08-15 13:59:13 -0400239 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400240 private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
241 throws IOException {
242 // Each query starts with the argument count (1 in this case)
243 writer.write("1");
244 // ... followed by a new-line.
245 writer.newLine();
246 // ... followed by our only argument.
247 writer.write("--query-abi-list");
248 writer.newLine();
249 writer.flush();
250
251 // The response is a length prefixed stream of ASCII bytes.
252 int numBytes = inputStream.readInt();
253 byte[] bytes = new byte[numBytes];
254 inputStream.readFully(bytes);
255
256 return new String(bytes, StandardCharsets.US_ASCII);
257 }
258
259 /**
260 * Sends an argument list to the zygote process, which starts a new child
261 * and returns the child's pid. Please note: the present implementation
262 * replaces newlines in the argument list with spaces.
263 *
264 * @throws ZygoteStartFailedEx if process start failed for any reason
265 */
Robert Sesekded20982016-08-15 13:59:13 -0400266 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400267 private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
268 ZygoteState zygoteState, ArrayList<String> args)
269 throws ZygoteStartFailedEx {
270 try {
Robert Sesek0b58f192016-10-10 18:34:42 -0400271 // Throw early if any of the arguments are malformed. This means we can
272 // avoid writing a partial response to the zygote.
273 int sz = args.size();
274 for (int i = 0; i < sz; i++) {
275 if (args.get(i).indexOf('\n') >= 0) {
276 throw new ZygoteStartFailedEx("embedded newlines not allowed");
277 }
278 }
279
Robert Sesek8f8d1872016-03-18 16:52:57 -0400280 /**
281 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
282 * Presently the wire format to the zygote process is:
283 * a) a count of arguments (argc, in essence)
284 * b) a number of newline-separated argument strings equal to count
285 *
286 * After the zygote process reads these it will write the pid of
287 * the child or -1 on failure, followed by boolean to
288 * indicate whether a wrapper process was used.
289 */
290 final BufferedWriter writer = zygoteState.writer;
291 final DataInputStream inputStream = zygoteState.inputStream;
292
293 writer.write(Integer.toString(args.size()));
294 writer.newLine();
295
Robert Sesek8f8d1872016-03-18 16:52:57 -0400296 for (int i = 0; i < sz; i++) {
297 String arg = args.get(i);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400298 writer.write(arg);
299 writer.newLine();
300 }
301
302 writer.flush();
303
304 // Should there be a timeout on this?
305 Process.ProcessStartResult result = new Process.ProcessStartResult();
Robert Sesek0b58f192016-10-10 18:34:42 -0400306
307 // Always read the entire result from the input stream to avoid leaving
308 // bytes in the stream for future process starts to accidentally stumble
309 // upon.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400310 result.pid = inputStream.readInt();
Robert Sesek0b58f192016-10-10 18:34:42 -0400311 result.usingWrapper = inputStream.readBoolean();
312
Robert Sesek8f8d1872016-03-18 16:52:57 -0400313 if (result.pid < 0) {
314 throw new ZygoteStartFailedEx("fork() failed");
315 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400316 return result;
317 } catch (IOException ex) {
318 zygoteState.close();
319 throw new ZygoteStartFailedEx(ex);
320 }
321 }
322
323 /**
324 * Starts a new process via the zygote mechanism.
325 *
326 * @param processClass Class name whose static main() to run
327 * @param niceName 'nice' process name to appear in ps
328 * @param uid a POSIX uid that the new process should setuid() to
329 * @param gid a POSIX gid that the new process shuold setgid() to
330 * @param gids null-ok; a list of supplementary group IDs that the
331 * new process should setgroup() to.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100332 * @param runtimeFlags Additional flags for the runtime.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400333 * @param targetSdkVersion The target SDK version for the app.
334 * @param seInfo null-ok SELinux information for the new process.
335 * @param abi the ABI the process should use.
336 * @param instructionSet null-ok the instruction set to use.
337 * @param appDataDir null-ok the data directory of the app.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500338 * @param startChildZygote Start a sub-zygote. This creates a new zygote process
339 * that has its state cloned from this zygote process.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400340 * @param extraArgs Additional arguments to supply to the zygote process.
341 * @return An object that describes the result of the attempt to start the process.
342 * @throws ZygoteStartFailedEx if process start failed for any reason
343 */
344 private Process.ProcessStartResult startViaZygote(final String processClass,
345 final String niceName,
346 final int uid, final int gid,
347 final int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100348 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400349 int targetSdkVersion,
350 String seInfo,
351 String abi,
352 String instructionSet,
353 String appDataDir,
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000354 String invokeWith,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500355 boolean startChildZygote,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400356 String[] extraArgs)
357 throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400358 ArrayList<String> argsForZygote = new ArrayList<String>();
Robert Sesek8f8d1872016-03-18 16:52:57 -0400359
Robert Sesekded20982016-08-15 13:59:13 -0400360 // --runtime-args, --setuid=, --setgid=,
361 // and --setgroups= must go first
362 argsForZygote.add("--runtime-args");
363 argsForZygote.add("--setuid=" + uid);
364 argsForZygote.add("--setgid=" + gid);
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100365 argsForZygote.add("--runtime-flags=" + runtimeFlags);
Robert Sesekded20982016-08-15 13:59:13 -0400366 if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
367 argsForZygote.add("--mount-external-default");
368 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
369 argsForZygote.add("--mount-external-read");
370 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
371 argsForZygote.add("--mount-external-write");
372 }
373 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400374
Robert Sesekded20982016-08-15 13:59:13 -0400375 // --setgroups is a comma-separated list
376 if (gids != null && gids.length > 0) {
377 StringBuilder sb = new StringBuilder();
378 sb.append("--setgroups=");
Robert Sesek8f8d1872016-03-18 16:52:57 -0400379
Robert Sesekded20982016-08-15 13:59:13 -0400380 int sz = gids.length;
381 for (int i = 0; i < sz; i++) {
382 if (i != 0) {
383 sb.append(',');
Robert Sesek8f8d1872016-03-18 16:52:57 -0400384 }
Robert Sesekded20982016-08-15 13:59:13 -0400385 sb.append(gids[i]);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400386 }
387
Robert Sesekded20982016-08-15 13:59:13 -0400388 argsForZygote.add(sb.toString());
389 }
390
391 if (niceName != null) {
392 argsForZygote.add("--nice-name=" + niceName);
393 }
394
395 if (seInfo != null) {
396 argsForZygote.add("--seinfo=" + seInfo);
397 }
398
399 if (instructionSet != null) {
400 argsForZygote.add("--instruction-set=" + instructionSet);
401 }
402
403 if (appDataDir != null) {
404 argsForZygote.add("--app-data-dir=" + appDataDir);
405 }
406
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000407 if (invokeWith != null) {
408 argsForZygote.add("--invoke-with");
409 argsForZygote.add(invokeWith);
410 }
411
Robert Sesekd0a190df2018-02-12 18:46:01 -0500412 if (startChildZygote) {
413 argsForZygote.add("--start-child-zygote");
414 }
415
Robert Sesekded20982016-08-15 13:59:13 -0400416 argsForZygote.add(processClass);
417
418 if (extraArgs != null) {
419 for (String arg : extraArgs) {
420 argsForZygote.add(arg);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400421 }
Robert Sesekded20982016-08-15 13:59:13 -0400422 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400423
Robert Sesekded20982016-08-15 13:59:13 -0400424 synchronized(mLock) {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400425 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
426 }
427 }
428
429 /**
Robert Sesekd0a190df2018-02-12 18:46:01 -0500430 * Closes the connections to the zygote, if they exist.
431 */
432 public void close() {
433 if (primaryZygoteState != null) {
434 primaryZygoteState.close();
435 }
436 if (secondaryZygoteState != null) {
437 secondaryZygoteState.close();
438 }
439 }
440
441 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400442 * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
443 * and retry if the zygote is unresponsive. This method is a no-op if a connection is
444 * already open.
445 */
446 public void establishZygoteConnectionForAbi(String abi) {
447 try {
Robert Sesekded20982016-08-15 13:59:13 -0400448 synchronized(mLock) {
449 openZygoteSocketIfNeeded(abi);
450 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400451 } catch (ZygoteStartFailedEx ex) {
452 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
453 }
454 }
455
456 /**
457 * Tries to open socket to Zygote process if not already open. If
Robert Sesekded20982016-08-15 13:59:13 -0400458 * already open, does nothing. May block and retry. Requires that mLock be held.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400459 */
Robert Sesekded20982016-08-15 13:59:13 -0400460 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400461 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400462 Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
463
Robert Sesek8f8d1872016-03-18 16:52:57 -0400464 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
465 try {
466 primaryZygoteState = ZygoteState.connect(mSocket);
467 } catch (IOException ioe) {
468 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
469 }
470 }
471
472 if (primaryZygoteState.matches(abi)) {
473 return primaryZygoteState;
474 }
475
476 // The primary zygote didn't match. Try the secondary.
477 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
478 try {
479 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
480 } catch (IOException ioe) {
481 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
482 }
483 }
484
485 if (secondaryZygoteState.matches(abi)) {
486 return secondaryZygoteState;
487 }
488
489 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
490 }
Robert Sesekded20982016-08-15 13:59:13 -0400491
492 /**
493 * Instructs the zygote to pre-load the classes and native libraries at the given paths
494 * for the specified abi. Not all zygotes support this function.
495 */
Narayan Kamathbae484a2017-07-03 14:12:26 +0100496 public boolean preloadPackageForAbi(String packagePath, String libsPath, String cacheKey,
497 String abi) throws ZygoteStartFailedEx, IOException {
Robert Sesekded20982016-08-15 13:59:13 -0400498 synchronized(mLock) {
499 ZygoteState state = openZygoteSocketIfNeeded(abi);
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000500 state.writer.write("4");
Robert Sesekded20982016-08-15 13:59:13 -0400501 state.writer.newLine();
502
503 state.writer.write("--preload-package");
504 state.writer.newLine();
505
506 state.writer.write(packagePath);
507 state.writer.newLine();
508
509 state.writer.write(libsPath);
510 state.writer.newLine();
511
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000512 state.writer.write(cacheKey);
513 state.writer.newLine();
514
Robert Sesekded20982016-08-15 13:59:13 -0400515 state.writer.flush();
Narayan Kamathbae484a2017-07-03 14:12:26 +0100516
517 return (state.inputStream.readInt() == 0);
Robert Sesekded20982016-08-15 13:59:13 -0400518 }
519 }
Narayan Kamath669afcc2017-02-06 20:24:08 +0000520
521 /**
522 * Instructs the zygote to preload the default set of classes and resources. Returns
523 * {@code true} if a preload was performed as a result of this call, and {@code false}
524 * otherwise. The latter usually means that the zygote eagerly preloaded at startup
525 * or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
526 */
527 public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
528 synchronized (mLock) {
529 ZygoteState state = openZygoteSocketIfNeeded(abi);
530 // Each query starts with the argument count (1 in this case)
531 state.writer.write("1");
532 state.writer.newLine();
533 state.writer.write("--preload-default");
534 state.writer.newLine();
535 state.writer.flush();
536
537 return (state.inputStream.readInt() == 0);
538 }
539 }
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100540
541 /**
542 * Try connecting to the Zygote over and over again until we hit a time-out.
543 * @param socketName The name of the socket to connect to.
544 */
545 public static void waitForConnectionToZygote(String socketName) {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500546 final LocalSocketAddress address =
547 new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.RESERVED);
548 waitForConnectionToZygote(address);
549 }
550
551 /**
552 * Try connecting to the Zygote over and over again until we hit a time-out.
553 * @param address The name of the socket to connect to.
554 */
555 public static void waitForConnectionToZygote(LocalSocketAddress address) {
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100556 for (int n = 20; n >= 0; n--) {
557 try {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500558 final ZygoteState zs = ZygoteState.connect(address);
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100559 zs.close();
560 return;
561 } catch (IOException ioe) {
562 Log.w(LOG_TAG,
563 "Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
564 }
565
566 try {
567 Thread.sleep(1000);
568 } catch (InterruptedException ie) {
569 }
570 }
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500571 Slog.wtf(LOG_TAG, "Failed to connect to Zygote through socket " + address.getName());
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100572 }
Robert Sesekd0a190df2018-02-12 18:46:01 -0500573
574 /**
575 * Starts a new zygote process as a child of this zygote. This is used to create
576 * secondary zygotes that inherit data from the zygote that this object
577 * communicates with. This returns a new ZygoteProcess representing a connection
578 * to the newly created zygote. Throws an exception if the zygote cannot be started.
579 */
580 public ChildZygoteProcess startChildZygote(final String processClass,
581 final String niceName,
582 int uid, int gid, int[] gids,
583 int runtimeFlags,
584 String seInfo,
585 String abi,
586 String instructionSet) {
587 // Create an unguessable address in the global abstract namespace.
588 final LocalSocketAddress serverAddress = new LocalSocketAddress(
589 processClass + "/" + UUID.randomUUID().toString());
590
591 final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName()};
592
593 Process.ProcessStartResult result;
594 try {
595 result = startViaZygote(processClass, niceName, uid, gid,
596 gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
597 abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
598 true /* startChildZygote */, extraArgs);
599 } catch (ZygoteStartFailedEx ex) {
600 throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
601 }
602
603 return new ChildZygoteProcess(serverAddress, result.pid);
604 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400605}