blob: 7fd0a4b66d66b33a2056a9b983fb4e0fcc4d3a03 [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
Sudheer Shankad81b1d72018-09-05 16:37:30 -070019import android.annotation.NonNull;
20import android.annotation.Nullable;
Robert Sesek8f8d1872016-03-18 16:52:57 -040021import android.net.LocalSocket;
22import android.net.LocalSocketAddress;
23import android.util.Log;
Gustav Senntonf0c52b52017-04-27 17:00:50 +010024import android.util.Slog;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010025
Robert Sesekded20982016-08-15 13:59:13 -040026import com.android.internal.annotations.GuardedBy;
Robert Sesek8f8d1872016-03-18 16:52:57 -040027import com.android.internal.os.Zygote;
Robert Sesekded20982016-08-15 13:59:13 -040028import com.android.internal.util.Preconditions;
Nicolas Geoffray81edac42017-09-07 14:13:29 +010029
Robert Sesek8f8d1872016-03-18 16:52:57 -040030import java.io.BufferedWriter;
31import java.io.DataInputStream;
32import java.io.IOException;
33import java.io.OutputStreamWriter;
34import java.nio.charset.StandardCharsets;
35import java.util.ArrayList;
36import java.util.Arrays;
Mathew Inwood8faeab82018-03-16 14:26:08 +000037import java.util.Collections;
Robert Sesek8f8d1872016-03-18 16:52:57 -040038import java.util.List;
Robert Sesekd0a190df2018-02-12 18:46:01 -050039import java.util.UUID;
Robert Sesek8f8d1872016-03-18 16:52:57 -040040
41/*package*/ class ZygoteStartFailedEx extends Exception {
42 ZygoteStartFailedEx(String s) {
43 super(s);
44 }
45
46 ZygoteStartFailedEx(Throwable cause) {
47 super(cause);
48 }
49
50 ZygoteStartFailedEx(String s, Throwable cause) {
51 super(s, cause);
52 }
53}
54
55/**
56 * Maintains communication state with the zygote processes. This class is responsible
57 * for the sockets opened to the zygotes and for starting processes on behalf of the
58 * {@link android.os.Process} class.
59 *
60 * {@hide}
61 */
62public class ZygoteProcess {
63 private static final String LOG_TAG = "ZygoteProcess";
64
65 /**
66 * The name of the socket used to communicate with the primary zygote.
67 */
Robert Sesek5ac8abf2018-01-26 14:26:53 -050068 private final LocalSocketAddress mSocket;
Robert Sesek8f8d1872016-03-18 16:52:57 -040069
70 /**
71 * The name of the secondary (alternate ABI) zygote socket.
72 */
Robert Sesek5ac8abf2018-01-26 14:26:53 -050073 private final LocalSocketAddress mSecondarySocket;
Robert Sesek8f8d1872016-03-18 16:52:57 -040074
75 public ZygoteProcess(String primarySocket, String secondarySocket) {
Robert Sesek5ac8abf2018-01-26 14:26:53 -050076 this(new LocalSocketAddress(primarySocket, LocalSocketAddress.Namespace.RESERVED),
77 new LocalSocketAddress(secondarySocket, LocalSocketAddress.Namespace.RESERVED));
78 }
79
80 public ZygoteProcess(LocalSocketAddress primarySocket, LocalSocketAddress secondarySocket) {
Robert Sesek8f8d1872016-03-18 16:52:57 -040081 mSocket = primarySocket;
82 mSecondarySocket = secondarySocket;
83 }
84
Robert Sesek5ac8abf2018-01-26 14:26:53 -050085 public LocalSocketAddress getPrimarySocketAddress() {
86 return mSocket;
87 }
88
Robert Sesek8f8d1872016-03-18 16:52:57 -040089 /**
90 * State for communicating with the zygote process.
91 */
92 public static class ZygoteState {
93 final LocalSocket socket;
94 final DataInputStream inputStream;
95 final BufferedWriter writer;
96 final List<String> abiList;
97
98 boolean mClosed;
99
100 private ZygoteState(LocalSocket socket, DataInputStream inputStream,
101 BufferedWriter writer, List<String> abiList) {
102 this.socket = socket;
103 this.inputStream = inputStream;
104 this.writer = writer;
105 this.abiList = abiList;
106 }
107
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500108 public static ZygoteState connect(LocalSocketAddress address) throws IOException {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400109 DataInputStream zygoteInputStream = null;
110 BufferedWriter zygoteWriter = null;
111 final LocalSocket zygoteSocket = new LocalSocket();
112
113 try {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500114 zygoteSocket.connect(address);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400115
116 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
117
118 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
119 zygoteSocket.getOutputStream()), 256);
120 } catch (IOException ex) {
121 try {
122 zygoteSocket.close();
123 } catch (IOException ignore) {
124 }
125
126 throw ex;
127 }
128
129 String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500130 Log.i("Zygote", "Process: zygote socket " + address.getNamespace() + "/"
131 + address.getName() + " opened, supported ABIS: " + abiListString);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400132
133 return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
134 Arrays.asList(abiListString.split(",")));
135 }
136
137 boolean matches(String abi) {
138 return abiList.contains(abi);
139 }
140
141 public void close() {
142 try {
143 socket.close();
144 } catch (IOException ex) {
145 Log.e(LOG_TAG,"I/O exception on routine close", ex);
146 }
147
148 mClosed = true;
149 }
150
151 boolean isClosed() {
152 return mClosed;
153 }
154 }
155
156 /**
Robert Sesekded20982016-08-15 13:59:13 -0400157 * Lock object to protect access to the two ZygoteStates below. This lock must be
158 * acquired while communicating over the ZygoteState's socket, to prevent
159 * interleaved access.
160 */
161 private final Object mLock = new Object();
162
163 /**
Mathew Inwood8faeab82018-03-16 14:26:08 +0000164 * List of exemptions to the API blacklist. These are prefix matches on the runtime format
165 * symbol signature. Any matching symbol is treated by the runtime as being on the light grey
166 * list.
167 */
168 private List<String> mApiBlacklistExemptions = Collections.emptyList();
169
170 /**
Mathew Inwood04194fe2018-04-04 14:48:03 +0100171 * Proportion of hidden API accesses that should be logged to the event log; 0 - 0x10000.
172 */
173 private int mHiddenApiAccessLogSampleRate;
174
175 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400176 * The state of the connection to the primary zygote.
177 */
178 private ZygoteState primaryZygoteState;
179
180 /**
181 * The state of the connection to the secondary zygote.
182 */
183 private ZygoteState secondaryZygoteState;
184
185 /**
186 * Start a new process.
187 *
188 * <p>If processes are enabled, a new process is created and the
189 * static main() function of a <var>processClass</var> is executed there.
190 * The process will continue running after this function returns.
191 *
192 * <p>If processes are not enabled, a new thread in the caller's
Mathew Inwood8faeab82018-03-16 14:26:08 +0000193 * process is created and main() of <var>processclass</var> called there.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400194 *
195 * <p>The niceName parameter, if not an empty string, is a custom name to
196 * give to the process instead of using processClass. This allows you to
197 * make easily identifyable processes even if you are using the same base
198 * <var>processClass</var> to start them.
199 *
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000200 * When invokeWith is not null, the process will be started as a fresh app
Tamas Berghammer0ca16fa2016-11-11 16:08:26 +0000201 * and not a zygote fork. Note that this is only allowed for uid 0 or when
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100202 * runtimeFlags contains DEBUG_ENABLE_DEBUGGER.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000203 *
Robert Sesek8f8d1872016-03-18 16:52:57 -0400204 * @param processClass The class to use as the process's main entry
205 * point.
206 * @param niceName A more readable name to use for the process.
207 * @param uid The user-id under which the process will run.
208 * @param gid The group-id under which the process will run.
209 * @param gids Additional group-ids associated with the process.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100210 * @param runtimeFlags Additional flags.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400211 * @param targetSdkVersion The target SDK version for the app.
212 * @param seInfo null-ok SELinux information for the new process.
213 * @param abi non-null the ABI this app should be started with.
214 * @param instructionSet null-ok the instruction set to use.
215 * @param appDataDir null-ok the data directory of the app.
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000216 * @param invokeWith null-ok the command to invoke with.
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700217 * @param packageName null-ok the name of the package this process belongs to.
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700218 * @param packagesForUid null-ok all the packages with the same uid as this process.
219 * @param visibleVols null-ok storage volumes that can be accessed by this process.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400220 * @param zygoteArgs Additional arguments to supply to the zygote process.
221 *
222 * @return An object that describes the result of the attempt to start the process.
223 * @throws RuntimeException on fatal start failure
224 */
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700225 public final Process.ProcessStartResult start(@NonNull final String processClass,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400226 final String niceName,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700227 int uid, int gid, @Nullable int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100228 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400229 int targetSdkVersion,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700230 @Nullable String seInfo,
231 @NonNull String abi,
232 @Nullable String instructionSet,
233 @Nullable String appDataDir,
234 @Nullable String invokeWith,
235 @Nullable String packageName,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700236 @Nullable String[] packagesForUid,
237 @Nullable String[] visibleVols,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700238 @Nullable String[] zygoteArgs) {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400239 try {
240 return startViaZygote(processClass, niceName, uid, gid, gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100241 runtimeFlags, mountExternal, targetSdkVersion, seInfo,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500242 abi, instructionSet, appDataDir, invokeWith, false /* startChildZygote */,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700243 packageName, packagesForUid, visibleVols, zygoteArgs);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400244 } catch (ZygoteStartFailedEx ex) {
245 Log.e(LOG_TAG,
246 "Starting VM process through Zygote failed");
247 throw new RuntimeException(
248 "Starting VM process through Zygote failed", ex);
249 }
250 }
251
252 /** retry interval for opening a zygote socket */
253 static final int ZYGOTE_RETRY_MILLIS = 500;
254
255 /**
256 * Queries the zygote for the list of ABIS it supports.
257 *
258 * @throws ZygoteStartFailedEx if the query failed.
259 */
Robert Sesekded20982016-08-15 13:59:13 -0400260 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400261 private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
262 throws IOException {
263 // Each query starts with the argument count (1 in this case)
264 writer.write("1");
265 // ... followed by a new-line.
266 writer.newLine();
267 // ... followed by our only argument.
268 writer.write("--query-abi-list");
269 writer.newLine();
270 writer.flush();
271
272 // The response is a length prefixed stream of ASCII bytes.
273 int numBytes = inputStream.readInt();
274 byte[] bytes = new byte[numBytes];
275 inputStream.readFully(bytes);
276
277 return new String(bytes, StandardCharsets.US_ASCII);
278 }
279
280 /**
281 * Sends an argument list to the zygote process, which starts a new child
282 * and returns the child's pid. Please note: the present implementation
283 * replaces newlines in the argument list with spaces.
284 *
285 * @throws ZygoteStartFailedEx if process start failed for any reason
286 */
Robert Sesekded20982016-08-15 13:59:13 -0400287 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400288 private static Process.ProcessStartResult zygoteSendArgsAndGetResult(
289 ZygoteState zygoteState, ArrayList<String> args)
290 throws ZygoteStartFailedEx {
291 try {
Robert Sesek0b58f192016-10-10 18:34:42 -0400292 // Throw early if any of the arguments are malformed. This means we can
293 // avoid writing a partial response to the zygote.
294 int sz = args.size();
295 for (int i = 0; i < sz; i++) {
296 if (args.get(i).indexOf('\n') >= 0) {
297 throw new ZygoteStartFailedEx("embedded newlines not allowed");
298 }
299 }
300
Robert Sesek8f8d1872016-03-18 16:52:57 -0400301 /**
302 * See com.android.internal.os.SystemZygoteInit.readArgumentList()
303 * Presently the wire format to the zygote process is:
304 * a) a count of arguments (argc, in essence)
305 * b) a number of newline-separated argument strings equal to count
306 *
307 * After the zygote process reads these it will write the pid of
308 * the child or -1 on failure, followed by boolean to
309 * indicate whether a wrapper process was used.
310 */
311 final BufferedWriter writer = zygoteState.writer;
312 final DataInputStream inputStream = zygoteState.inputStream;
313
314 writer.write(Integer.toString(args.size()));
315 writer.newLine();
316
Robert Sesek8f8d1872016-03-18 16:52:57 -0400317 for (int i = 0; i < sz; i++) {
318 String arg = args.get(i);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400319 writer.write(arg);
320 writer.newLine();
321 }
322
323 writer.flush();
324
325 // Should there be a timeout on this?
326 Process.ProcessStartResult result = new Process.ProcessStartResult();
Robert Sesek0b58f192016-10-10 18:34:42 -0400327
328 // Always read the entire result from the input stream to avoid leaving
329 // bytes in the stream for future process starts to accidentally stumble
330 // upon.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400331 result.pid = inputStream.readInt();
Robert Sesek0b58f192016-10-10 18:34:42 -0400332 result.usingWrapper = inputStream.readBoolean();
333
Robert Sesek8f8d1872016-03-18 16:52:57 -0400334 if (result.pid < 0) {
335 throw new ZygoteStartFailedEx("fork() failed");
336 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400337 return result;
338 } catch (IOException ex) {
339 zygoteState.close();
340 throw new ZygoteStartFailedEx(ex);
341 }
342 }
343
344 /**
345 * Starts a new process via the zygote mechanism.
346 *
347 * @param processClass Class name whose static main() to run
348 * @param niceName 'nice' process name to appear in ps
349 * @param uid a POSIX uid that the new process should setuid() to
350 * @param gid a POSIX gid that the new process shuold setgid() to
351 * @param gids null-ok; a list of supplementary group IDs that the
352 * new process should setgroup() to.
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100353 * @param runtimeFlags Additional flags for the runtime.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400354 * @param targetSdkVersion The target SDK version for the app.
355 * @param seInfo null-ok SELinux information for the new process.
356 * @param abi the ABI the process should use.
357 * @param instructionSet null-ok the instruction set to use.
358 * @param appDataDir null-ok the data directory of the app.
Robert Sesekd0a190df2018-02-12 18:46:01 -0500359 * @param startChildZygote Start a sub-zygote. This creates a new zygote process
360 * that has its state cloned from this zygote process.
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700361 * @param packageName null-ok the name of the package this process belongs to.
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700362 * @param packagesForUid null-ok all the packages with the same uid as this process.
363 * @param visibleVols null-ok storage volumes that can be accessed by this process.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400364 * @param extraArgs Additional arguments to supply to the zygote process.
365 * @return An object that describes the result of the attempt to start the process.
366 * @throws ZygoteStartFailedEx if process start failed for any reason
367 */
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700368 private Process.ProcessStartResult startViaZygote(@NonNull final String processClass,
369 @Nullable final String niceName,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400370 final int uid, final int gid,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700371 @Nullable final int[] gids,
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100372 int runtimeFlags, int mountExternal,
Robert Sesek8f8d1872016-03-18 16:52:57 -0400373 int targetSdkVersion,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700374 @Nullable String seInfo,
375 @NonNull String abi,
376 @Nullable String instructionSet,
377 @Nullable String appDataDir,
378 @Nullable String invokeWith,
Robert Sesekd0a190df2018-02-12 18:46:01 -0500379 boolean startChildZygote,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700380 @Nullable String packageName,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700381 @Nullable String[] packagesForUid,
382 @Nullable String[] visibleVols,
Sudheer Shankad81b1d72018-09-05 16:37:30 -0700383 @Nullable String[] extraArgs)
Robert Sesek8f8d1872016-03-18 16:52:57 -0400384 throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400385 ArrayList<String> argsForZygote = new ArrayList<String>();
Robert Sesek8f8d1872016-03-18 16:52:57 -0400386
Robert Sesekded20982016-08-15 13:59:13 -0400387 // --runtime-args, --setuid=, --setgid=,
388 // and --setgroups= must go first
389 argsForZygote.add("--runtime-args");
390 argsForZygote.add("--setuid=" + uid);
391 argsForZygote.add("--setgid=" + gid);
Nicolas Geoffray81edac42017-09-07 14:13:29 +0100392 argsForZygote.add("--runtime-flags=" + runtimeFlags);
Robert Sesekded20982016-08-15 13:59:13 -0400393 if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
394 argsForZygote.add("--mount-external-default");
395 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
396 argsForZygote.add("--mount-external-read");
397 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
398 argsForZygote.add("--mount-external-write");
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700399 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_FULL) {
400 argsForZygote.add("--mount-external-full");
Robert Sesekded20982016-08-15 13:59:13 -0400401 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700402
Robert Sesekded20982016-08-15 13:59:13 -0400403 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400404
Robert Sesekded20982016-08-15 13:59:13 -0400405 // --setgroups is a comma-separated list
406 if (gids != null && gids.length > 0) {
407 StringBuilder sb = new StringBuilder();
408 sb.append("--setgroups=");
Robert Sesek8f8d1872016-03-18 16:52:57 -0400409
Robert Sesekded20982016-08-15 13:59:13 -0400410 int sz = gids.length;
411 for (int i = 0; i < sz; i++) {
412 if (i != 0) {
413 sb.append(',');
Robert Sesek8f8d1872016-03-18 16:52:57 -0400414 }
Robert Sesekded20982016-08-15 13:59:13 -0400415 sb.append(gids[i]);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400416 }
417
Robert Sesekded20982016-08-15 13:59:13 -0400418 argsForZygote.add(sb.toString());
419 }
420
421 if (niceName != null) {
422 argsForZygote.add("--nice-name=" + niceName);
423 }
424
425 if (seInfo != null) {
426 argsForZygote.add("--seinfo=" + seInfo);
427 }
428
429 if (instructionSet != null) {
430 argsForZygote.add("--instruction-set=" + instructionSet);
431 }
432
433 if (appDataDir != null) {
434 argsForZygote.add("--app-data-dir=" + appDataDir);
435 }
436
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000437 if (invokeWith != null) {
438 argsForZygote.add("--invoke-with");
439 argsForZygote.add(invokeWith);
440 }
441
Robert Sesekd0a190df2018-02-12 18:46:01 -0500442 if (startChildZygote) {
443 argsForZygote.add("--start-child-zygote");
444 }
445
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700446 if (packageName != null) {
447 argsForZygote.add("--package-name=" + packageName);
448 }
449
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700450 if (packagesForUid != null && packagesForUid.length > 0) {
451 final StringBuilder sb = new StringBuilder();
452 sb.append("--packages-for-uid=");
453
454 for (int i = 0; i < packagesForUid.length; ++i) {
455 if (i != 0) {
456 sb.append(',');
457 }
458 sb.append(packagesForUid[i]);
459 }
460 argsForZygote.add(sb.toString());
461 }
462
463 if (visibleVols != null && visibleVols.length > 0) {
464 final StringBuilder sb = new StringBuilder();
465 sb.append("--visible-vols=");
466
467 for (int i = 0; i < visibleVols.length; ++i) {
468 if (i != 0) {
469 sb.append(',');
470 }
471 sb.append(visibleVols[i]);
472 }
473 argsForZygote.add(sb.toString());
474 }
475
Robert Sesekded20982016-08-15 13:59:13 -0400476 argsForZygote.add(processClass);
477
478 if (extraArgs != null) {
479 for (String arg : extraArgs) {
480 argsForZygote.add(arg);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400481 }
Robert Sesekded20982016-08-15 13:59:13 -0400482 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400483
Robert Sesekded20982016-08-15 13:59:13 -0400484 synchronized(mLock) {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400485 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
486 }
487 }
488
489 /**
Robert Sesekd0a190df2018-02-12 18:46:01 -0500490 * Closes the connections to the zygote, if they exist.
491 */
492 public void close() {
493 if (primaryZygoteState != null) {
494 primaryZygoteState.close();
495 }
496 if (secondaryZygoteState != null) {
497 secondaryZygoteState.close();
498 }
499 }
500
501 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400502 * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
503 * and retry if the zygote is unresponsive. This method is a no-op if a connection is
504 * already open.
505 */
506 public void establishZygoteConnectionForAbi(String abi) {
507 try {
Robert Sesekded20982016-08-15 13:59:13 -0400508 synchronized(mLock) {
509 openZygoteSocketIfNeeded(abi);
510 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400511 } catch (ZygoteStartFailedEx ex) {
512 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
513 }
514 }
515
516 /**
Andreas Gampe8444dca2018-05-01 13:31:28 -0700517 * Attempt to retrieve the PID of the zygote serving the given abi.
518 */
519 public int getZygotePid(String abi) {
520 try {
521 synchronized (mLock) {
522 ZygoteState state = openZygoteSocketIfNeeded(abi);
523
524 // Each query starts with the argument count (1 in this case)
525 state.writer.write("1");
526 // ... followed by a new-line.
527 state.writer.newLine();
528 // ... followed by our only argument.
529 state.writer.write("--get-pid");
530 state.writer.newLine();
531 state.writer.flush();
532
533 // The response is a length prefixed stream of ASCII bytes.
534 int numBytes = state.inputStream.readInt();
535 byte[] bytes = new byte[numBytes];
536 state.inputStream.readFully(bytes);
537
538 return Integer.parseInt(new String(bytes, StandardCharsets.US_ASCII));
539 }
540 } catch (Exception ex) {
541 throw new RuntimeException("Failure retrieving pid", ex);
542 }
543 }
544
545 /**
Mathew Inwood8faeab82018-03-16 14:26:08 +0000546 * Push hidden API blacklisting exemptions into the zygote process(es).
547 *
548 * <p>The list of exemptions will take affect for all new processes forked from the zygote after
549 * this call.
550 *
Mathew Inwood33d51382018-04-05 13:56:39 +0100551 * @param exemptions List of hidden API exemption prefixes. Any matching members are treated as
552 * whitelisted/public APIs (i.e. allowed, no logging of usage).
Mathew Inwood8faeab82018-03-16 14:26:08 +0000553 */
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100554 public boolean setApiBlacklistExemptions(List<String> exemptions) {
Mathew Inwood8faeab82018-03-16 14:26:08 +0000555 synchronized (mLock) {
556 mApiBlacklistExemptions = exemptions;
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100557 boolean ok = maybeSetApiBlacklistExemptions(primaryZygoteState, true);
558 if (ok) {
559 ok = maybeSetApiBlacklistExemptions(secondaryZygoteState, true);
560 }
561 return ok;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000562 }
563 }
564
Mathew Inwood04194fe2018-04-04 14:48:03 +0100565 /**
566 * Set the precentage of detected hidden API accesses that are logged to the event log.
567 *
568 * <p>This rate will take affect for all new processes forked from the zygote after this call.
569 *
570 * @param rate An integer between 0 and 0x10000 inclusive. 0 means no event logging.
571 */
572 public void setHiddenApiAccessLogSampleRate(int rate) {
573 synchronized (mLock) {
574 mHiddenApiAccessLogSampleRate = rate;
575 maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
576 maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
577 }
578 }
579
Mathew Inwood8faeab82018-03-16 14:26:08 +0000580 @GuardedBy("mLock")
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100581 private boolean maybeSetApiBlacklistExemptions(ZygoteState state, boolean sendIfEmpty) {
Mathew Inwood8faeab82018-03-16 14:26:08 +0000582 if (state == null || state.isClosed()) {
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100583 Slog.e(LOG_TAG, "Can't set API blacklist exemptions: no zygote connection");
584 return false;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000585 }
586 if (!sendIfEmpty && mApiBlacklistExemptions.isEmpty()) {
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100587 return true;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000588 }
589 try {
590 state.writer.write(Integer.toString(mApiBlacklistExemptions.size() + 1));
591 state.writer.newLine();
592 state.writer.write("--set-api-blacklist-exemptions");
593 state.writer.newLine();
594 for (int i = 0; i < mApiBlacklistExemptions.size(); ++i) {
595 state.writer.write(mApiBlacklistExemptions.get(i));
596 state.writer.newLine();
597 }
598 state.writer.flush();
599 int status = state.inputStream.readInt();
600 if (status != 0) {
601 Slog.e(LOG_TAG, "Failed to set API blacklist exemptions; status " + status);
602 }
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100603 return true;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000604 } catch (IOException ioe) {
605 Slog.e(LOG_TAG, "Failed to set API blacklist exemptions", ioe);
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100606 mApiBlacklistExemptions = Collections.emptyList();
607 return false;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000608 }
609 }
610
Mathew Inwood04194fe2018-04-04 14:48:03 +0100611 private void maybeSetHiddenApiAccessLogSampleRate(ZygoteState state) {
612 if (state == null || state.isClosed()) {
613 return;
614 }
615 if (mHiddenApiAccessLogSampleRate == -1) {
616 return;
617 }
618 try {
619 state.writer.write(Integer.toString(1));
620 state.writer.newLine();
621 state.writer.write("--hidden-api-log-sampling-rate="
622 + Integer.toString(mHiddenApiAccessLogSampleRate));
623 state.writer.newLine();
624 state.writer.flush();
625 int status = state.inputStream.readInt();
626 if (status != 0) {
627 Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate; status " + status);
628 }
629 } catch (IOException ioe) {
630 Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate", ioe);
631 }
632 }
633
Mathew Inwood8faeab82018-03-16 14:26:08 +0000634 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400635 * Tries to open socket to Zygote process if not already open. If
Robert Sesekded20982016-08-15 13:59:13 -0400636 * already open, does nothing. May block and retry. Requires that mLock be held.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400637 */
Robert Sesekded20982016-08-15 13:59:13 -0400638 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400639 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400640 Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
641
Robert Sesek8f8d1872016-03-18 16:52:57 -0400642 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
643 try {
644 primaryZygoteState = ZygoteState.connect(mSocket);
645 } catch (IOException ioe) {
646 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
647 }
Mathew Inwood8faeab82018-03-16 14:26:08 +0000648 maybeSetApiBlacklistExemptions(primaryZygoteState, false);
Mathew Inwood04194fe2018-04-04 14:48:03 +0100649 maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400650 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400651 if (primaryZygoteState.matches(abi)) {
652 return primaryZygoteState;
653 }
654
655 // The primary zygote didn't match. Try the secondary.
656 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
657 try {
658 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
659 } catch (IOException ioe) {
660 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
661 }
Mathew Inwood8faeab82018-03-16 14:26:08 +0000662 maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
Mathew Inwood04194fe2018-04-04 14:48:03 +0100663 maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400664 }
665
666 if (secondaryZygoteState.matches(abi)) {
667 return secondaryZygoteState;
668 }
669
670 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
671 }
Robert Sesekded20982016-08-15 13:59:13 -0400672
673 /**
674 * Instructs the zygote to pre-load the classes and native libraries at the given paths
675 * for the specified abi. Not all zygotes support this function.
676 */
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500677 public boolean preloadPackageForAbi(String packagePath, String libsPath, String libFileName,
678 String cacheKey, String abi) throws ZygoteStartFailedEx,
679 IOException {
Robert Sesekded20982016-08-15 13:59:13 -0400680 synchronized(mLock) {
681 ZygoteState state = openZygoteSocketIfNeeded(abi);
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500682 state.writer.write("5");
Robert Sesekded20982016-08-15 13:59:13 -0400683 state.writer.newLine();
684
685 state.writer.write("--preload-package");
686 state.writer.newLine();
687
688 state.writer.write(packagePath);
689 state.writer.newLine();
690
691 state.writer.write(libsPath);
692 state.writer.newLine();
693
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500694 state.writer.write(libFileName);
695 state.writer.newLine();
696
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000697 state.writer.write(cacheKey);
698 state.writer.newLine();
699
Robert Sesekded20982016-08-15 13:59:13 -0400700 state.writer.flush();
Narayan Kamathbae484a2017-07-03 14:12:26 +0100701
702 return (state.inputStream.readInt() == 0);
Robert Sesekded20982016-08-15 13:59:13 -0400703 }
704 }
Narayan Kamath669afcc2017-02-06 20:24:08 +0000705
706 /**
707 * Instructs the zygote to preload the default set of classes and resources. Returns
708 * {@code true} if a preload was performed as a result of this call, and {@code false}
709 * otherwise. The latter usually means that the zygote eagerly preloaded at startup
710 * or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
711 */
712 public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
713 synchronized (mLock) {
714 ZygoteState state = openZygoteSocketIfNeeded(abi);
715 // Each query starts with the argument count (1 in this case)
716 state.writer.write("1");
717 state.writer.newLine();
718 state.writer.write("--preload-default");
719 state.writer.newLine();
720 state.writer.flush();
721
722 return (state.inputStream.readInt() == 0);
723 }
724 }
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100725
726 /**
727 * Try connecting to the Zygote over and over again until we hit a time-out.
728 * @param socketName The name of the socket to connect to.
729 */
730 public static void waitForConnectionToZygote(String socketName) {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500731 final LocalSocketAddress address =
732 new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.RESERVED);
733 waitForConnectionToZygote(address);
734 }
735
736 /**
737 * Try connecting to the Zygote over and over again until we hit a time-out.
738 * @param address The name of the socket to connect to.
739 */
740 public static void waitForConnectionToZygote(LocalSocketAddress address) {
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100741 for (int n = 20; n >= 0; n--) {
742 try {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500743 final ZygoteState zs = ZygoteState.connect(address);
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100744 zs.close();
745 return;
746 } catch (IOException ioe) {
747 Log.w(LOG_TAG,
748 "Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
749 }
750
751 try {
752 Thread.sleep(1000);
753 } catch (InterruptedException ie) {
754 }
755 }
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500756 Slog.wtf(LOG_TAG, "Failed to connect to Zygote through socket " + address.getName());
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100757 }
Robert Sesekd0a190df2018-02-12 18:46:01 -0500758
759 /**
760 * Starts a new zygote process as a child of this zygote. This is used to create
761 * secondary zygotes that inherit data from the zygote that this object
762 * communicates with. This returns a new ZygoteProcess representing a connection
763 * to the newly created zygote. Throws an exception if the zygote cannot be started.
764 */
765 public ChildZygoteProcess startChildZygote(final String processClass,
766 final String niceName,
767 int uid, int gid, int[] gids,
768 int runtimeFlags,
769 String seInfo,
770 String abi,
771 String instructionSet) {
772 // Create an unguessable address in the global abstract namespace.
773 final LocalSocketAddress serverAddress = new LocalSocketAddress(
774 processClass + "/" + UUID.randomUUID().toString());
775
776 final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName()};
777
778 Process.ProcessStartResult result;
779 try {
780 result = startViaZygote(processClass, niceName, uid, gid,
781 gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
782 abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700783 true /* startChildZygote */, null /* packageName */,
784 null /* packagesForUid */, null /* visibleVolumes */, extraArgs);
Robert Sesekd0a190df2018-02-12 18:46:01 -0500785 } catch (ZygoteStartFailedEx ex) {
786 throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
787 }
788
789 return new ChildZygoteProcess(serverAddress, result.pid);
790 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400791}