blob: f136cd6699a7fc7a96cf339cb6f811007c1c02cf [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");
Sudheer Shanka3a0df3b2018-12-12 12:43:43 -0800401 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_INSTALLER) {
402 argsForZygote.add("--mount-external-installer");
Robert Sesekded20982016-08-15 13:59:13 -0400403 }
Sudheer Shanka98cb3f02018-08-17 16:10:29 -0700404
Robert Sesekded20982016-08-15 13:59:13 -0400405 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400406
Robert Sesekded20982016-08-15 13:59:13 -0400407 // --setgroups is a comma-separated list
408 if (gids != null && gids.length > 0) {
409 StringBuilder sb = new StringBuilder();
410 sb.append("--setgroups=");
Robert Sesek8f8d1872016-03-18 16:52:57 -0400411
Robert Sesekded20982016-08-15 13:59:13 -0400412 int sz = gids.length;
413 for (int i = 0; i < sz; i++) {
414 if (i != 0) {
415 sb.append(',');
Robert Sesek8f8d1872016-03-18 16:52:57 -0400416 }
Robert Sesekded20982016-08-15 13:59:13 -0400417 sb.append(gids[i]);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400418 }
419
Robert Sesekded20982016-08-15 13:59:13 -0400420 argsForZygote.add(sb.toString());
421 }
422
423 if (niceName != null) {
424 argsForZygote.add("--nice-name=" + niceName);
425 }
426
427 if (seInfo != null) {
428 argsForZygote.add("--seinfo=" + seInfo);
429 }
430
431 if (instructionSet != null) {
432 argsForZygote.add("--instruction-set=" + instructionSet);
433 }
434
435 if (appDataDir != null) {
436 argsForZygote.add("--app-data-dir=" + appDataDir);
437 }
438
Tamas Berghammerb8f7c352016-11-11 16:08:26 +0000439 if (invokeWith != null) {
440 argsForZygote.add("--invoke-with");
441 argsForZygote.add(invokeWith);
442 }
443
Robert Sesekd0a190df2018-02-12 18:46:01 -0500444 if (startChildZygote) {
445 argsForZygote.add("--start-child-zygote");
446 }
447
Sudheer Shanka154fe3f2018-07-30 14:44:26 -0700448 if (packageName != null) {
449 argsForZygote.add("--package-name=" + packageName);
450 }
451
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700452 if (packagesForUid != null && packagesForUid.length > 0) {
453 final StringBuilder sb = new StringBuilder();
454 sb.append("--packages-for-uid=");
455
456 for (int i = 0; i < packagesForUid.length; ++i) {
457 if (i != 0) {
458 sb.append(',');
459 }
460 sb.append(packagesForUid[i]);
461 }
462 argsForZygote.add(sb.toString());
463 }
464
465 if (visibleVols != null && visibleVols.length > 0) {
466 final StringBuilder sb = new StringBuilder();
467 sb.append("--visible-vols=");
468
469 for (int i = 0; i < visibleVols.length; ++i) {
470 if (i != 0) {
471 sb.append(',');
472 }
473 sb.append(visibleVols[i]);
474 }
475 argsForZygote.add(sb.toString());
476 }
477
Robert Sesekded20982016-08-15 13:59:13 -0400478 argsForZygote.add(processClass);
479
480 if (extraArgs != null) {
481 for (String arg : extraArgs) {
482 argsForZygote.add(arg);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400483 }
Robert Sesekded20982016-08-15 13:59:13 -0400484 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400485
Robert Sesekded20982016-08-15 13:59:13 -0400486 synchronized(mLock) {
Robert Sesek8f8d1872016-03-18 16:52:57 -0400487 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
488 }
489 }
490
491 /**
Robert Sesekd0a190df2018-02-12 18:46:01 -0500492 * Closes the connections to the zygote, if they exist.
493 */
494 public void close() {
495 if (primaryZygoteState != null) {
496 primaryZygoteState.close();
497 }
498 if (secondaryZygoteState != null) {
499 secondaryZygoteState.close();
500 }
501 }
502
503 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400504 * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block
505 * and retry if the zygote is unresponsive. This method is a no-op if a connection is
506 * already open.
507 */
508 public void establishZygoteConnectionForAbi(String abi) {
509 try {
Robert Sesekded20982016-08-15 13:59:13 -0400510 synchronized(mLock) {
511 openZygoteSocketIfNeeded(abi);
512 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400513 } catch (ZygoteStartFailedEx ex) {
514 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
515 }
516 }
517
518 /**
Andreas Gampe8444dca2018-05-01 13:31:28 -0700519 * Attempt to retrieve the PID of the zygote serving the given abi.
520 */
521 public int getZygotePid(String abi) {
522 try {
523 synchronized (mLock) {
524 ZygoteState state = openZygoteSocketIfNeeded(abi);
525
526 // Each query starts with the argument count (1 in this case)
527 state.writer.write("1");
528 // ... followed by a new-line.
529 state.writer.newLine();
530 // ... followed by our only argument.
531 state.writer.write("--get-pid");
532 state.writer.newLine();
533 state.writer.flush();
534
535 // The response is a length prefixed stream of ASCII bytes.
536 int numBytes = state.inputStream.readInt();
537 byte[] bytes = new byte[numBytes];
538 state.inputStream.readFully(bytes);
539
540 return Integer.parseInt(new String(bytes, StandardCharsets.US_ASCII));
541 }
542 } catch (Exception ex) {
543 throw new RuntimeException("Failure retrieving pid", ex);
544 }
545 }
546
547 /**
Mathew Inwood8faeab82018-03-16 14:26:08 +0000548 * Push hidden API blacklisting exemptions into the zygote process(es).
549 *
550 * <p>The list of exemptions will take affect for all new processes forked from the zygote after
551 * this call.
552 *
Mathew Inwood33d51382018-04-05 13:56:39 +0100553 * @param exemptions List of hidden API exemption prefixes. Any matching members are treated as
554 * whitelisted/public APIs (i.e. allowed, no logging of usage).
Mathew Inwood8faeab82018-03-16 14:26:08 +0000555 */
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100556 public boolean setApiBlacklistExemptions(List<String> exemptions) {
Mathew Inwood8faeab82018-03-16 14:26:08 +0000557 synchronized (mLock) {
558 mApiBlacklistExemptions = exemptions;
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100559 boolean ok = maybeSetApiBlacklistExemptions(primaryZygoteState, true);
560 if (ok) {
561 ok = maybeSetApiBlacklistExemptions(secondaryZygoteState, true);
562 }
563 return ok;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000564 }
565 }
566
Mathew Inwood04194fe2018-04-04 14:48:03 +0100567 /**
568 * Set the precentage of detected hidden API accesses that are logged to the event log.
569 *
570 * <p>This rate will take affect for all new processes forked from the zygote after this call.
571 *
572 * @param rate An integer between 0 and 0x10000 inclusive. 0 means no event logging.
573 */
574 public void setHiddenApiAccessLogSampleRate(int rate) {
575 synchronized (mLock) {
576 mHiddenApiAccessLogSampleRate = rate;
577 maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
578 maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
579 }
580 }
581
Mathew Inwood8faeab82018-03-16 14:26:08 +0000582 @GuardedBy("mLock")
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100583 private boolean maybeSetApiBlacklistExemptions(ZygoteState state, boolean sendIfEmpty) {
Mathew Inwood8faeab82018-03-16 14:26:08 +0000584 if (state == null || state.isClosed()) {
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100585 Slog.e(LOG_TAG, "Can't set API blacklist exemptions: no zygote connection");
586 return false;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000587 }
588 if (!sendIfEmpty && mApiBlacklistExemptions.isEmpty()) {
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100589 return true;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000590 }
591 try {
592 state.writer.write(Integer.toString(mApiBlacklistExemptions.size() + 1));
593 state.writer.newLine();
594 state.writer.write("--set-api-blacklist-exemptions");
595 state.writer.newLine();
596 for (int i = 0; i < mApiBlacklistExemptions.size(); ++i) {
597 state.writer.write(mApiBlacklistExemptions.get(i));
598 state.writer.newLine();
599 }
600 state.writer.flush();
601 int status = state.inputStream.readInt();
602 if (status != 0) {
603 Slog.e(LOG_TAG, "Failed to set API blacklist exemptions; status " + status);
604 }
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100605 return true;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000606 } catch (IOException ioe) {
607 Slog.e(LOG_TAG, "Failed to set API blacklist exemptions", ioe);
Mathew Inwood9f6bb5b2018-04-09 17:29:12 +0100608 mApiBlacklistExemptions = Collections.emptyList();
609 return false;
Mathew Inwood8faeab82018-03-16 14:26:08 +0000610 }
611 }
612
Mathew Inwood04194fe2018-04-04 14:48:03 +0100613 private void maybeSetHiddenApiAccessLogSampleRate(ZygoteState state) {
614 if (state == null || state.isClosed()) {
615 return;
616 }
617 if (mHiddenApiAccessLogSampleRate == -1) {
618 return;
619 }
620 try {
621 state.writer.write(Integer.toString(1));
622 state.writer.newLine();
623 state.writer.write("--hidden-api-log-sampling-rate="
624 + Integer.toString(mHiddenApiAccessLogSampleRate));
625 state.writer.newLine();
626 state.writer.flush();
627 int status = state.inputStream.readInt();
628 if (status != 0) {
629 Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate; status " + status);
630 }
631 } catch (IOException ioe) {
632 Slog.e(LOG_TAG, "Failed to set hidden API log sampling rate", ioe);
633 }
634 }
635
Mathew Inwood8faeab82018-03-16 14:26:08 +0000636 /**
Robert Sesek8f8d1872016-03-18 16:52:57 -0400637 * Tries to open socket to Zygote process if not already open. If
Robert Sesekded20982016-08-15 13:59:13 -0400638 * already open, does nothing. May block and retry. Requires that mLock be held.
Robert Sesek8f8d1872016-03-18 16:52:57 -0400639 */
Robert Sesekded20982016-08-15 13:59:13 -0400640 @GuardedBy("mLock")
Robert Sesek8f8d1872016-03-18 16:52:57 -0400641 private ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
Robert Sesekded20982016-08-15 13:59:13 -0400642 Preconditions.checkState(Thread.holdsLock(mLock), "ZygoteProcess lock not held");
643
Robert Sesek8f8d1872016-03-18 16:52:57 -0400644 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
645 try {
646 primaryZygoteState = ZygoteState.connect(mSocket);
647 } catch (IOException ioe) {
648 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
649 }
Mathew Inwood8faeab82018-03-16 14:26:08 +0000650 maybeSetApiBlacklistExemptions(primaryZygoteState, false);
Mathew Inwood04194fe2018-04-04 14:48:03 +0100651 maybeSetHiddenApiAccessLogSampleRate(primaryZygoteState);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400652 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400653 if (primaryZygoteState.matches(abi)) {
654 return primaryZygoteState;
655 }
656
657 // The primary zygote didn't match. Try the secondary.
658 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
659 try {
660 secondaryZygoteState = ZygoteState.connect(mSecondarySocket);
661 } catch (IOException ioe) {
662 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
663 }
Mathew Inwood8faeab82018-03-16 14:26:08 +0000664 maybeSetApiBlacklistExemptions(secondaryZygoteState, false);
Mathew Inwood04194fe2018-04-04 14:48:03 +0100665 maybeSetHiddenApiAccessLogSampleRate(secondaryZygoteState);
Robert Sesek8f8d1872016-03-18 16:52:57 -0400666 }
667
668 if (secondaryZygoteState.matches(abi)) {
669 return secondaryZygoteState;
670 }
671
672 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
673 }
Robert Sesekded20982016-08-15 13:59:13 -0400674
675 /**
676 * Instructs the zygote to pre-load the classes and native libraries at the given paths
677 * for the specified abi. Not all zygotes support this function.
678 */
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500679 public boolean preloadPackageForAbi(String packagePath, String libsPath, String libFileName,
680 String cacheKey, String abi) throws ZygoteStartFailedEx,
681 IOException {
Robert Sesekded20982016-08-15 13:59:13 -0400682 synchronized(mLock) {
683 ZygoteState state = openZygoteSocketIfNeeded(abi);
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500684 state.writer.write("5");
Robert Sesekded20982016-08-15 13:59:13 -0400685 state.writer.newLine();
686
687 state.writer.write("--preload-package");
688 state.writer.newLine();
689
690 state.writer.write(packagePath);
691 state.writer.newLine();
692
693 state.writer.write(libsPath);
694 state.writer.newLine();
695
Torne (Richard Coles)f4f647e2018-02-21 16:12:36 -0500696 state.writer.write(libFileName);
697 state.writer.newLine();
698
Torne (Richard Coles)04526702017-01-13 14:19:39 +0000699 state.writer.write(cacheKey);
700 state.writer.newLine();
701
Robert Sesekded20982016-08-15 13:59:13 -0400702 state.writer.flush();
Narayan Kamathbae484a2017-07-03 14:12:26 +0100703
704 return (state.inputStream.readInt() == 0);
Robert Sesekded20982016-08-15 13:59:13 -0400705 }
706 }
Narayan Kamath669afcc2017-02-06 20:24:08 +0000707
708 /**
709 * Instructs the zygote to preload the default set of classes and resources. Returns
710 * {@code true} if a preload was performed as a result of this call, and {@code false}
711 * otherwise. The latter usually means that the zygote eagerly preloaded at startup
712 * or due to a previous call to {@code preloadDefault}. Note that this call is synchronous.
713 */
714 public boolean preloadDefault(String abi) throws ZygoteStartFailedEx, IOException {
715 synchronized (mLock) {
716 ZygoteState state = openZygoteSocketIfNeeded(abi);
717 // Each query starts with the argument count (1 in this case)
718 state.writer.write("1");
719 state.writer.newLine();
720 state.writer.write("--preload-default");
721 state.writer.newLine();
722 state.writer.flush();
723
724 return (state.inputStream.readInt() == 0);
725 }
726 }
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100727
728 /**
729 * Try connecting to the Zygote over and over again until we hit a time-out.
730 * @param socketName The name of the socket to connect to.
731 */
732 public static void waitForConnectionToZygote(String socketName) {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500733 final LocalSocketAddress address =
734 new LocalSocketAddress(socketName, LocalSocketAddress.Namespace.RESERVED);
735 waitForConnectionToZygote(address);
736 }
737
738 /**
739 * Try connecting to the Zygote over and over again until we hit a time-out.
740 * @param address The name of the socket to connect to.
741 */
742 public static void waitForConnectionToZygote(LocalSocketAddress address) {
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100743 for (int n = 20; n >= 0; n--) {
744 try {
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500745 final ZygoteState zs = ZygoteState.connect(address);
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100746 zs.close();
747 return;
748 } catch (IOException ioe) {
749 Log.w(LOG_TAG,
750 "Got error connecting to zygote, retrying. msg= " + ioe.getMessage());
751 }
752
753 try {
754 Thread.sleep(1000);
755 } catch (InterruptedException ie) {
756 }
757 }
Robert Sesek5ac8abf2018-01-26 14:26:53 -0500758 Slog.wtf(LOG_TAG, "Failed to connect to Zygote through socket " + address.getName());
Gustav Senntonf0c52b52017-04-27 17:00:50 +0100759 }
Robert Sesekd0a190df2018-02-12 18:46:01 -0500760
761 /**
762 * Starts a new zygote process as a child of this zygote. This is used to create
763 * secondary zygotes that inherit data from the zygote that this object
764 * communicates with. This returns a new ZygoteProcess representing a connection
765 * to the newly created zygote. Throws an exception if the zygote cannot be started.
766 */
767 public ChildZygoteProcess startChildZygote(final String processClass,
768 final String niceName,
769 int uid, int gid, int[] gids,
770 int runtimeFlags,
771 String seInfo,
772 String abi,
773 String instructionSet) {
774 // Create an unguessable address in the global abstract namespace.
775 final LocalSocketAddress serverAddress = new LocalSocketAddress(
776 processClass + "/" + UUID.randomUUID().toString());
777
778 final String[] extraArgs = {Zygote.CHILD_ZYGOTE_SOCKET_NAME_ARG + serverAddress.getName()};
779
780 Process.ProcessStartResult result;
781 try {
782 result = startViaZygote(processClass, niceName, uid, gid,
783 gids, runtimeFlags, 0 /* mountExternal */, 0 /* targetSdkVersion */, seInfo,
784 abi, instructionSet, null /* appDataDir */, null /* invokeWith */,
Sudheer Shanka3f0645b2018-09-18 13:07:59 -0700785 true /* startChildZygote */, null /* packageName */,
786 null /* packagesForUid */, null /* visibleVolumes */, extraArgs);
Robert Sesekd0a190df2018-02-12 18:46:01 -0500787 } catch (ZygoteStartFailedEx ex) {
788 throw new RuntimeException("Starting child-zygote through Zygote failed", ex);
789 }
790
791 return new ChildZygoteProcess(serverAddress, result.pid);
792 }
Robert Sesek8f8d1872016-03-18 16:52:57 -0400793}