blob: e1b7fdad25e7dff4f30f3c9ca725e2ac36ae700e [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2006 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
Srinath Sridharan1b15d132016-07-19 15:16:11 -070019import android.annotation.TestApi;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080020import android.net.LocalSocket;
Narayan Kamath973b4662014-03-31 13:41:26 +010021import android.net.LocalSocketAddress;
Elliott Hughes34385d32014-04-28 11:11:32 -070022import android.system.Os;
Tim Murrayb89970e2016-07-01 10:42:20 -070023import android.system.OsConstants;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080024import android.util.Log;
Narayan Kamath973b4662014-03-31 13:41:26 +010025import com.android.internal.os.Zygote;
Andreas Gampeee0cdce2015-06-08 20:47:50 -070026import dalvik.system.VMRuntime;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080027import java.io.BufferedWriter;
28import java.io.DataInputStream;
29import java.io.IOException;
30import java.io.OutputStreamWriter;
Narayan Kamath4444dcd2014-04-03 20:15:15 +010031import java.nio.charset.StandardCharsets;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080032import java.util.ArrayList;
Narayan Kamath4444dcd2014-04-03 20:15:15 +010033import java.util.Arrays;
34import java.util.List;
Jeff Hao406ec152013-07-30 10:13:41 -070035
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036/*package*/ class ZygoteStartFailedEx extends Exception {
Narayan Kamath64cd9072014-05-13 13:35:14 +010037 ZygoteStartFailedEx(String s) {
38 super(s);
39 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040
Narayan Kamath64cd9072014-05-13 13:35:14 +010041 ZygoteStartFailedEx(Throwable cause) {
42 super(cause);
43 }
44
45 ZygoteStartFailedEx(String s, Throwable cause) {
46 super(s, cause);
47 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048}
49
50/**
51 * Tools for managing OS processes.
52 */
53public class Process {
54 private static final String LOG_TAG = "Process";
55
Narayan Kamath64cd9072014-05-13 13:35:14 +010056 /**
57 * @hide for internal use only.
58 */
59 public static final String ZYGOTE_SOCKET = "zygote";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060
Narayan Kamath64cd9072014-05-13 13:35:14 +010061 /**
62 * @hide for internal use only.
63 */
64 public static final String SECONDARY_ZYGOTE_SOCKET = "zygote_secondary";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065
66 /**
Jeff Sharkey1cb2d0d2014-07-30 16:45:01 -070067 * Defines the root UID.
68 * @hide
69 */
70 public static final int ROOT_UID = 0;
71
72 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080073 * Defines the UID/GID under which system code runs.
74 */
75 public static final int SYSTEM_UID = 1000;
76
77 /**
78 * Defines the UID/GID under which the telephony code runs.
79 */
80 public static final int PHONE_UID = 1001;
81
82 /**
Dianne Hackborn854060af2009-07-09 18:14:31 -070083 * Defines the UID/GID for the user shell.
84 * @hide
85 */
86 public static final int SHELL_UID = 2000;
87
88 /**
Mike Lockwoodd42685d2009-09-03 09:25:22 -040089 * Defines the UID/GID for the log group.
90 * @hide
91 */
92 public static final int LOG_UID = 1007;
93
94 /**
Amith Yamasanid1582142009-07-08 20:04:55 -070095 * Defines the UID/GID for the WIFI supplicant process.
96 * @hide
97 */
98 public static final int WIFI_UID = 1010;
99
100 /**
Glenn Kasten8b7d1b42011-07-13 16:23:22 -0700101 * Defines the UID/GID for the mediaserver process.
102 * @hide
103 */
104 public static final int MEDIA_UID = 1013;
105
106 /**
Jeff Sharkey5294a2f2012-04-24 17:07:22 -0700107 * Defines the UID/GID for the DRM process.
108 * @hide
109 */
110 public static final int DRM_UID = 1019;
111
112 /**
Kenny Root26993b32012-03-19 15:07:51 -0700113 * Defines the UID/GID for the group that controls VPN services.
114 * @hide
115 */
116 public static final int VPN_UID = 1016;
117
118 /**
Nick Pellycd0e8392010-10-13 17:25:24 -0700119 * Defines the UID/GID for the NFC service process.
120 * @hide
121 */
Nick Pellya5cb9f42011-11-21 14:54:46 -0800122 public static final int NFC_UID = 1027;
Nick Pellycd0e8392010-10-13 17:25:24 -0700123
124 /**
Jaikumar Ganesh1abb1cb2012-01-25 16:14:50 -0800125 * Defines the UID/GID for the Bluetooth service process.
126 * @hide
127 */
128 public static final int BLUETOOTH_UID = 1002;
129
130 /**
Mike Lockwooddcaa10c2010-12-16 12:50:44 -0800131 * Defines the GID for the group that allows write access to the internal media storage.
132 * @hide
133 */
134 public static final int MEDIA_RW_GID = 1023;
135
136 /**
Jeff Sharkey184a0102013-07-10 16:19:52 -0700137 * Access to installed package details
138 * @hide
139 */
140 public static final int PACKAGE_INFO_GID = 1032;
141
142 /**
Torne (Richard Coles)08cfaf62014-05-08 16:07:05 +0100143 * Defines the UID/GID for the shared RELRO file updater process.
144 * @hide
145 */
146 public static final int SHARED_RELRO_UID = 1037;
147
148 /**
Andy Hunged0ea402015-10-30 14:11:46 -0700149 * Defines the UID/GID for the audioserver process.
150 * @hide
151 */
152 public static final int AUDIOSERVER_UID = 1041;
153
154 /**
Chien-Yu Chen75cade02016-01-11 10:56:21 -0800155 * Defines the UID/GID for the cameraserver process
156 * @hide
157 */
Chien-Yu Chenb8b4e852016-01-29 12:02:28 -0800158 public static final int CAMERASERVER_UID = 1047;
Chien-Yu Chen75cade02016-01-11 10:56:21 -0800159
160 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800161 * Defines the start of a range of UIDs (and GIDs), going from this
162 * number to {@link #LAST_APPLICATION_UID} that are reserved for assigning
163 * to applications.
164 */
165 public static final int FIRST_APPLICATION_UID = 10000;
Jeff Sharkey184a0102013-07-10 16:19:52 -0700166
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167 /**
168 * Last of application-specific UIDs starting at
169 * {@link #FIRST_APPLICATION_UID}.
170 */
Dianne Hackborn21fbd1f2012-02-10 10:38:10 -0800171 public static final int LAST_APPLICATION_UID = 19999;
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800172
173 /**
174 * First uid used for fully isolated sandboxed processes (with no permissions of their own)
175 * @hide
176 */
177 public static final int FIRST_ISOLATED_UID = 99000;
178
179 /**
180 * Last uid used for fully isolated sandboxed processes (with no permissions of their own)
181 * @hide
182 */
183 public static final int LAST_ISOLATED_UID = 99999;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800184
185 /**
Robin Leee66b6892014-04-29 12:36:47 +0100186 * Defines the gid shared by all applications running under the same profile.
187 * @hide
188 */
189 public static final int SHARED_USER_GID = 9997;
190
191 /**
Kenny Roote091f222012-09-11 15:01:26 -0700192 * First gid for applications to share resources. Used when forward-locking
193 * is enabled but all UserHandles need to be able to read the resources.
194 * @hide
195 */
196 public static final int FIRST_SHARED_APPLICATION_GID = 50000;
197
198 /**
199 * Last gid for applications to share resources. Used when forward-locking
200 * is enabled but all UserHandles need to be able to read the resources.
201 * @hide
202 */
203 public static final int LAST_SHARED_APPLICATION_GID = 59999;
204
205 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 * Standard priority of application threads.
207 * Use with {@link #setThreadPriority(int)} and
208 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
209 * {@link java.lang.Thread} class.
210 */
211 public static final int THREAD_PRIORITY_DEFAULT = 0;
212
213 /*
214 * ***************************************
215 * ** Keep in sync with utils/threads.h **
216 * ***************************************
217 */
218
219 /**
220 * Lowest available thread priority. Only for those who really, really
221 * don't want to run if anything else is happening.
222 * Use with {@link #setThreadPriority(int)} and
223 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
224 * {@link java.lang.Thread} class.
225 */
226 public static final int THREAD_PRIORITY_LOWEST = 19;
227
228 /**
229 * Standard priority background threads. This gives your thread a slightly
230 * lower than normal priority, so that it will have less chance of impacting
231 * the responsiveness of the user interface.
232 * Use with {@link #setThreadPriority(int)} and
233 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
234 * {@link java.lang.Thread} class.
235 */
236 public static final int THREAD_PRIORITY_BACKGROUND = 10;
237
238 /**
239 * Standard priority of threads that are currently running a user interface
240 * that the user is interacting with. Applications can not normally
241 * change to this priority; the system will automatically adjust your
242 * application threads as the user moves through the UI.
243 * Use with {@link #setThreadPriority(int)} and
244 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
245 * {@link java.lang.Thread} class.
246 */
247 public static final int THREAD_PRIORITY_FOREGROUND = -2;
248
249 /**
250 * Standard priority of system display threads, involved in updating
251 * the user interface. Applications can not
252 * normally change to this priority.
253 * Use with {@link #setThreadPriority(int)} and
254 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
255 * {@link java.lang.Thread} class.
256 */
257 public static final int THREAD_PRIORITY_DISPLAY = -4;
258
259 /**
260 * Standard priority of the most important display threads, for compositing
261 * the screen and retrieving input events. Applications can not normally
262 * change to this priority.
263 * Use with {@link #setThreadPriority(int)} and
264 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
265 * {@link java.lang.Thread} class.
266 */
267 public static final int THREAD_PRIORITY_URGENT_DISPLAY = -8;
268
269 /**
270 * Standard priority of audio threads. Applications can not normally
271 * change to this priority.
272 * Use with {@link #setThreadPriority(int)} and
273 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
274 * {@link java.lang.Thread} class.
275 */
276 public static final int THREAD_PRIORITY_AUDIO = -16;
277
278 /**
279 * Standard priority of the most important audio threads.
280 * Applications can not normally change to this priority.
281 * Use with {@link #setThreadPriority(int)} and
282 * {@link #setThreadPriority(int, int)}, <b>not</b> with the normal
283 * {@link java.lang.Thread} class.
284 */
285 public static final int THREAD_PRIORITY_URGENT_AUDIO = -19;
286
287 /**
288 * Minimum increment to make a priority more favorable.
289 */
290 public static final int THREAD_PRIORITY_MORE_FAVORABLE = -1;
291
292 /**
293 * Minimum increment to make a priority less favorable.
294 */
295 public static final int THREAD_PRIORITY_LESS_FAVORABLE = +1;
296
San Mehate9d376b2009-04-21 14:06:36 -0700297 /**
Glenn Kasten6793ac92011-07-13 12:44:12 -0700298 * Default scheduling policy
299 * @hide
300 */
301 public static final int SCHED_OTHER = 0;
302
303 /**
304 * First-In First-Out scheduling policy
305 * @hide
306 */
307 public static final int SCHED_FIFO = 1;
308
309 /**
310 * Round-Robin scheduling policy
311 * @hide
312 */
313 public static final int SCHED_RR = 2;
314
315 /**
316 * Batch scheduling policy
317 * @hide
318 */
319 public static final int SCHED_BATCH = 3;
320
321 /**
322 * Idle scheduling policy
323 * @hide
324 */
325 public static final int SCHED_IDLE = 5;
326
Srinath Sridharane535a582016-06-27 18:13:47 -0700327 /**
328 * Reset scheduler choice on fork.
329 * @hide
330 */
331 public static final int SCHED_RESET_ON_FORK = 0x40000000;
332
Glenn Kastenf1b56442012-03-15 16:33:43 -0700333 // Keep in sync with SP_* constants of enum type SchedPolicy
334 // declared in system/core/include/cutils/sched_policy.h,
335 // except THREAD_GROUP_DEFAULT does not correspond to any SP_* value.
San Mehate9d376b2009-04-21 14:06:36 -0700336
337 /**
Glenn Kastenf1b56442012-03-15 16:33:43 -0700338 * Default thread group -
339 * has meaning with setProcessGroup() only, cannot be used with setThreadGroup().
340 * When used with setProcessGroup(), the group of each thread in the process
341 * is conditionally changed based on that thread's current priority, as follows:
342 * threads with priority numerically less than THREAD_PRIORITY_BACKGROUND
343 * are moved to foreground thread group. All other threads are left unchanged.
344 * @hide
345 */
346 public static final int THREAD_GROUP_DEFAULT = -1;
347
348 /**
349 * Background thread group - All threads in
San Mehate9d376b2009-04-21 14:06:36 -0700350 * this group are scheduled with a reduced share of the CPU.
Glenn Kastenf1b56442012-03-15 16:33:43 -0700351 * Value is same as constant SP_BACKGROUND of enum SchedPolicy.
352 * FIXME rename to THREAD_GROUP_BACKGROUND.
San Mehate9d376b2009-04-21 14:06:36 -0700353 * @hide
354 */
Glenn Kastenf1b56442012-03-15 16:33:43 -0700355 public static final int THREAD_GROUP_BG_NONINTERACTIVE = 0;
San Mehate9d376b2009-04-21 14:06:36 -0700356
357 /**
Glenn Kastenf1b56442012-03-15 16:33:43 -0700358 * Foreground thread group - All threads in
359 * this group are scheduled with a normal share of the CPU.
360 * Value is same as constant SP_FOREGROUND of enum SchedPolicy.
361 * Not used at this level.
San Mehate9d376b2009-04-21 14:06:36 -0700362 * @hide
363 **/
Glenn Kastenf1b56442012-03-15 16:33:43 -0700364 private static final int THREAD_GROUP_FOREGROUND = 1;
San Mehate9d376b2009-04-21 14:06:36 -0700365
Glenn Kasten07b04652012-04-23 15:00:43 -0700366 /**
367 * System thread group.
368 * @hide
369 **/
370 public static final int THREAD_GROUP_SYSTEM = 2;
371
372 /**
373 * Application audio thread group.
374 * @hide
375 **/
376 public static final int THREAD_GROUP_AUDIO_APP = 3;
377
378 /**
379 * System audio thread group.
380 * @hide
381 **/
382 public static final int THREAD_GROUP_AUDIO_SYS = 4;
383
Tim Murrayece6a222016-01-14 11:22:57 -0800384 /**
385 * Thread group for top foreground app.
386 * @hide
387 **/
388 public static final int THREAD_GROUP_TOP_APP = 5;
389
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800390 public static final int SIGNAL_QUIT = 3;
391 public static final int SIGNAL_KILL = 9;
392 public static final int SIGNAL_USR1 = 10;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800393
Dianne Hackbornd98885c2016-03-01 17:13:03 -0800394 private static long sStartElapsedRealtime;
395 private static long sStartUptimeMillis;
396
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100397 /**
398 * State for communicating with the zygote process.
Narayan Kamath64cd9072014-05-13 13:35:14 +0100399 *
400 * @hide for internal use only.
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100401 */
Narayan Kamath64cd9072014-05-13 13:35:14 +0100402 public static class ZygoteState {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100403 final LocalSocket socket;
404 final DataInputStream inputStream;
405 final BufferedWriter writer;
406 final List<String> abiList;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800407
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100408 boolean mClosed;
409
410 private ZygoteState(LocalSocket socket, DataInputStream inputStream,
411 BufferedWriter writer, List<String> abiList) {
412 this.socket = socket;
413 this.inputStream = inputStream;
414 this.writer = writer;
415 this.abiList = abiList;
416 }
417
Narayan Kamath64cd9072014-05-13 13:35:14 +0100418 public static ZygoteState connect(String socketAddress) throws IOException {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100419 DataInputStream zygoteInputStream = null;
420 BufferedWriter zygoteWriter = null;
Narayan Kamath64cd9072014-05-13 13:35:14 +0100421 final LocalSocket zygoteSocket = new LocalSocket();
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100422
Narayan Kamath64cd9072014-05-13 13:35:14 +0100423 try {
424 zygoteSocket.connect(new LocalSocketAddress(socketAddress,
425 LocalSocketAddress.Namespace.RESERVED));
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100426
Narayan Kamath64cd9072014-05-13 13:35:14 +0100427 zygoteInputStream = new DataInputStream(zygoteSocket.getInputStream());
428
429 zygoteWriter = new BufferedWriter(new OutputStreamWriter(
430 zygoteSocket.getOutputStream()), 256);
431 } catch (IOException ex) {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100432 try {
Narayan Kamath64cd9072014-05-13 13:35:14 +0100433 zygoteSocket.close();
434 } catch (IOException ignore) {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100435 }
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100436
Narayan Kamath64cd9072014-05-13 13:35:14 +0100437 throw ex;
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100438 }
439
440 String abiListString = getAbiList(zygoteWriter, zygoteInputStream);
441 Log.i("Zygote", "Process: zygote socket opened, supported ABIS: " + abiListString);
442
443 return new ZygoteState(zygoteSocket, zygoteInputStream, zygoteWriter,
444 Arrays.asList(abiListString.split(",")));
445 }
446
447 boolean matches(String abi) {
448 return abiList.contains(abi);
449 }
450
Narayan Kamath64cd9072014-05-13 13:35:14 +0100451 public void close() {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100452 try {
453 socket.close();
454 } catch (IOException ex) {
455 Log.e(LOG_TAG,"I/O exception on routine close", ex);
456 }
457
458 mClosed = true;
459 }
460
461 boolean isClosed() {
462 return mClosed;
463 }
464 }
465
466 /**
467 * The state of the connection to the primary zygote.
468 */
469 static ZygoteState primaryZygoteState;
470
471 /**
472 * The state of the connection to the secondary zygote.
473 */
474 static ZygoteState secondaryZygoteState;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800475
476 /**
477 * Start a new process.
478 *
479 * <p>If processes are enabled, a new process is created and the
480 * static main() function of a <var>processClass</var> is executed there.
481 * The process will continue running after this function returns.
482 *
483 * <p>If processes are not enabled, a new thread in the caller's
484 * process is created and main() of <var>processClass</var> called there.
485 *
486 * <p>The niceName parameter, if not an empty string, is a custom name to
487 * give to the process instead of using processClass. This allows you to
488 * make easily identifyable processes even if you are using the same base
489 * <var>processClass</var> to start them.
490 *
491 * @param processClass The class to use as the process's main entry
492 * point.
493 * @param niceName A more readable name to use for the process.
494 * @param uid The user-id under which the process will run.
495 * @param gid The group-id under which the process will run.
496 * @param gids Additional group-ids associated with the process.
Elliott Hughese1dfcb72011-07-08 11:08:07 -0700497 * @param debugFlags Additional flags.
498 * @param targetSdkVersion The target SDK version for the app.
Stephen Smalleybd19b9e2013-04-12 14:49:38 -0400499 * @param seInfo null-ok SELinux information for the new process.
Ramin Zaghiff0c4702014-04-01 15:02:29 +0100500 * @param abi non-null the ABI this app should be started with.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700501 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400502 * @param appDataDir null-ok the data directory of the app.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800503 * @param zygoteArgs Additional arguments to supply to the zygote process.
504 *
Jeff Brown3f9dd282011-07-08 20:02:19 -0700505 * @return An object that describes the result of the attempt to start the process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800506 * @throws RuntimeException on fatal start failure
507 *
508 * {@hide}
509 */
Jeff Brown3f9dd282011-07-08 20:02:19 -0700510 public static final ProcessStartResult start(final String processClass,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800511 final String niceName,
512 int uid, int gid, int[] gids,
Jeff Sharkey5b1ada22012-08-14 18:47:09 -0700513 int debugFlags, int mountExternal,
514 int targetSdkVersion,
Stephen Smalley83d9eda2012-01-13 08:34:17 -0500515 String seInfo,
Ramin Zaghiff0c4702014-04-01 15:02:29 +0100516 String abi,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700517 String instructionSet,
jgu212eacd062014-09-10 06:55:07 -0400518 String appDataDir,
Jeff Brown10e89712011-07-08 18:52:57 -0700519 String[] zygoteArgs) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800520 try {
Jeff Brown10e89712011-07-08 18:52:57 -0700521 return startViaZygote(processClass, niceName, uid, gid, gids,
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100522 debugFlags, mountExternal, targetSdkVersion, seInfo,
jgu212eacd062014-09-10 06:55:07 -0400523 abi, instructionSet, appDataDir, zygoteArgs);
Jeff Brown10e89712011-07-08 18:52:57 -0700524 } catch (ZygoteStartFailedEx ex) {
525 Log.e(LOG_TAG,
526 "Starting VM process through Zygote failed");
527 throw new RuntimeException(
528 "Starting VM process through Zygote failed", ex);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800529 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800530 }
531
532 /** retry interval for opening a zygote socket */
533 static final int ZYGOTE_RETRY_MILLIS = 500;
534
535 /**
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100536 * Queries the zygote for the list of ABIS it supports.
537 *
538 * @throws ZygoteStartFailedEx if the query failed.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800539 */
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100540 private static String getAbiList(BufferedWriter writer, DataInputStream inputStream)
Narayan Kamath64cd9072014-05-13 13:35:14 +0100541 throws IOException {
542 // Each query starts with the argument count (1 in this case)
543 writer.write("1");
544 // ... followed by a new-line.
545 writer.newLine();
546 // ... followed by our only argument.
547 writer.write("--query-abi-list");
548 writer.newLine();
549 writer.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800550
Narayan Kamath64cd9072014-05-13 13:35:14 +0100551 // The response is a length prefixed stream of ASCII bytes.
552 int numBytes = inputStream.readInt();
553 byte[] bytes = new byte[numBytes];
554 inputStream.readFully(bytes);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800555
Narayan Kamath64cd9072014-05-13 13:35:14 +0100556 return new String(bytes, StandardCharsets.US_ASCII);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800557 }
558
559 /**
560 * Sends an argument list to the zygote process, which starts a new child
561 * and returns the child's pid. Please note: the present implementation
562 * replaces newlines in the argument list with spaces.
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100563 *
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800564 * @throws ZygoteStartFailedEx if process start failed for any reason
565 */
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100566 private static ProcessStartResult zygoteSendArgsAndGetResult(
567 ZygoteState zygoteState, ArrayList<String> args)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800568 throws ZygoteStartFailedEx {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800569 try {
Narayan Kamath448be0a2016-08-09 17:00:25 +0100570 // Throw early if any of the arguments are malformed. This means we can
571 // avoid writing a partial response to the zygote.
572 int sz = args.size();
573 for (int i = 0; i < sz; i++) {
574 if (args.get(i).indexOf('\n') >= 0) {
575 throw new ZygoteStartFailedEx("embedded newlines not allowed");
576 }
577 }
578
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800579 /**
580 * See com.android.internal.os.ZygoteInit.readArgumentList()
581 * Presently the wire format to the zygote process is:
582 * a) a count of arguments (argc, in essence)
583 * b) a number of newline-separated argument strings equal to count
584 *
585 * After the zygote process reads these it will write the pid of
Jeff Brown3f9dd282011-07-08 20:02:19 -0700586 * the child or -1 on failure, followed by boolean to
587 * indicate whether a wrapper process was used.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800588 */
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100589 final BufferedWriter writer = zygoteState.writer;
590 final DataInputStream inputStream = zygoteState.inputStream;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800591
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100592 writer.write(Integer.toString(args.size()));
593 writer.newLine();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800594
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800595 for (int i = 0; i < sz; i++) {
596 String arg = args.get(i);
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100597 writer.write(arg);
598 writer.newLine();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800599 }
600
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100601 writer.flush();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800602
603 // Should there be a timeout on this?
Jeff Brown3f9dd282011-07-08 20:02:19 -0700604 ProcessStartResult result = new ProcessStartResult();
Narayan Kamath448be0a2016-08-09 17:00:25 +0100605
606 // Always read the entire result from the input stream to avoid leaving
607 // bytes in the stream for future process starts to accidentally stumble
608 // upon.
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100609 result.pid = inputStream.readInt();
Narayan Kamath448be0a2016-08-09 17:00:25 +0100610 result.usingWrapper = inputStream.readBoolean();
611
Jeff Brown3f9dd282011-07-08 20:02:19 -0700612 if (result.pid < 0) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800613 throw new ZygoteStartFailedEx("fork() failed");
614 }
Jeff Brown3f9dd282011-07-08 20:02:19 -0700615 return result;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800616 } catch (IOException ex) {
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100617 zygoteState.close();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800618 throw new ZygoteStartFailedEx(ex);
619 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800620 }
621
622 /**
623 * Starts a new process via the zygote mechanism.
624 *
625 * @param processClass Class name whose static main() to run
626 * @param niceName 'nice' process name to appear in ps
627 * @param uid a POSIX uid that the new process should setuid() to
628 * @param gid a POSIX gid that the new process shuold setgid() to
629 * @param gids null-ok; a list of supplementary group IDs that the
630 * new process should setgroup() to.
Elliott Hughese1dfcb72011-07-08 11:08:07 -0700631 * @param debugFlags Additional flags.
632 * @param targetSdkVersion The target SDK version for the app.
Stephen Smalleybd19b9e2013-04-12 14:49:38 -0400633 * @param seInfo null-ok SELinux information for the new process.
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100634 * @param abi the ABI the process should use.
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700635 * @param instructionSet null-ok the instruction set to use.
jgu212eacd062014-09-10 06:55:07 -0400636 * @param appDataDir null-ok the data directory of the app.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800637 * @param extraArgs Additional arguments to supply to the zygote process.
Jeff Brown3f9dd282011-07-08 20:02:19 -0700638 * @return An object that describes the result of the attempt to start the process.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800639 * @throws ZygoteStartFailedEx if process start failed for any reason
640 */
Jeff Brown3f9dd282011-07-08 20:02:19 -0700641 private static ProcessStartResult startViaZygote(final String processClass,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800642 final String niceName,
643 final int uid, final int gid,
644 final int[] gids,
Jeff Sharkey5b1ada22012-08-14 18:47:09 -0700645 int debugFlags, int mountExternal,
646 int targetSdkVersion,
Stephen Smalley83d9eda2012-01-13 08:34:17 -0500647 String seInfo,
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100648 String abi,
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700649 String instructionSet,
jgu212eacd062014-09-10 06:55:07 -0400650 String appDataDir,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800651 String[] extraArgs)
652 throws ZygoteStartFailedEx {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800653 synchronized(Process.class) {
654 ArrayList<String> argsForZygote = new ArrayList<String>();
655
Narayan Kamathf48029f2015-01-08 12:45:37 +0000656 // --runtime-args, --setuid=, --setgid=,
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800657 // and --setgroups= must go first
Narayan Kamathf48029f2015-01-08 12:45:37 +0000658 argsForZygote.add("--runtime-args");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800659 argsForZygote.add("--setuid=" + uid);
660 argsForZygote.add("--setgid=" + gid);
Elliott Hughesae07ecf2011-07-06 17:33:27 -0700661 if ((debugFlags & Zygote.DEBUG_ENABLE_JNI_LOGGING) != 0) {
662 argsForZygote.add("--enable-jni-logging");
663 }
Ben Cheng23085b72010-02-08 16:06:32 -0800664 if ((debugFlags & Zygote.DEBUG_ENABLE_SAFEMODE) != 0) {
665 argsForZygote.add("--enable-safemode");
666 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800667 if ((debugFlags & Zygote.DEBUG_ENABLE_DEBUGGER) != 0) {
668 argsForZygote.add("--enable-debugger");
669 }
670 if ((debugFlags & Zygote.DEBUG_ENABLE_CHECKJNI) != 0) {
671 argsForZygote.add("--enable-checkjni");
672 }
David Srbecky065075e2015-05-28 17:16:09 +0100673 if ((debugFlags & Zygote.DEBUG_GENERATE_DEBUG_INFO) != 0) {
674 argsForZygote.add("--generate-debug-info");
Andreas Gampe27c39f12015-04-27 18:28:18 +0000675 }
Tamas Berghammerdf6cb282016-01-29 12:07:00 +0000676 if ((debugFlags & Zygote.DEBUG_ALWAYS_JIT) != 0) {
677 argsForZygote.add("--always-jit");
678 }
679 if ((debugFlags & Zygote.DEBUG_NATIVE_DEBUGGABLE) != 0) {
680 argsForZygote.add("--native-debuggable");
681 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800682 if ((debugFlags & Zygote.DEBUG_ENABLE_ASSERT) != 0) {
683 argsForZygote.add("--enable-assert");
684 }
Jeff Sharkey48877892015-03-18 11:27:19 -0700685 if (mountExternal == Zygote.MOUNT_EXTERNAL_DEFAULT) {
686 argsForZygote.add("--mount-external-default");
Jeff Sharkey9527b222015-06-24 15:24:48 -0700687 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_READ) {
688 argsForZygote.add("--mount-external-read");
689 } else if (mountExternal == Zygote.MOUNT_EXTERNAL_WRITE) {
690 argsForZygote.add("--mount-external-write");
Jeff Sharkey5b1ada22012-08-14 18:47:09 -0700691 }
Elliott Hughese1dfcb72011-07-08 11:08:07 -0700692 argsForZygote.add("--target-sdk-version=" + targetSdkVersion);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800693
694 //TODO optionally enable debuger
695 //argsForZygote.add("--enable-debugger");
696
697 // --setgroups is a comma-separated list
698 if (gids != null && gids.length > 0) {
699 StringBuilder sb = new StringBuilder();
700 sb.append("--setgroups=");
701
702 int sz = gids.length;
703 for (int i = 0; i < sz; i++) {
704 if (i != 0) {
705 sb.append(',');
706 }
707 sb.append(gids[i]);
708 }
709
710 argsForZygote.add(sb.toString());
711 }
712
713 if (niceName != null) {
714 argsForZygote.add("--nice-name=" + niceName);
715 }
716
Stephen Smalley83d9eda2012-01-13 08:34:17 -0500717 if (seInfo != null) {
718 argsForZygote.add("--seinfo=" + seInfo);
719 }
720
Andreas Gampeaec67dc2014-09-02 21:23:06 -0700721 if (instructionSet != null) {
722 argsForZygote.add("--instruction-set=" + instructionSet);
723 }
724
jgu212eacd062014-09-10 06:55:07 -0400725 if (appDataDir != null) {
726 argsForZygote.add("--app-data-dir=" + appDataDir);
727 }
728
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800729 argsForZygote.add(processClass);
730
731 if (extraArgs != null) {
732 for (String arg : extraArgs) {
733 argsForZygote.add(arg);
734 }
735 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800736
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100737 return zygoteSendArgsAndGetResult(openZygoteSocketIfNeeded(abi), argsForZygote);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800738 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800739 }
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100740
741 /**
Narayan Kamath343f4782014-11-10 14:23:41 +0000742 * Tries to establish a connection to the zygote that handles a given {@code abi}. Might block and retry if the
743 * zygote is unresponsive. This method is a no-op if a connection is already open.
744 *
745 * @hide
746 */
747 public static void establishZygoteConnectionForAbi(String abi) {
748 try {
749 openZygoteSocketIfNeeded(abi);
750 } catch (ZygoteStartFailedEx ex) {
751 throw new RuntimeException("Unable to connect to zygote for abi: " + abi, ex);
752 }
753 }
754
755 /**
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100756 * Tries to open socket to Zygote process if not already open. If
757 * already open, does nothing. May block and retry.
758 */
759 private static ZygoteState openZygoteSocketIfNeeded(String abi) throws ZygoteStartFailedEx {
760 if (primaryZygoteState == null || primaryZygoteState.isClosed()) {
Narayan Kamath64cd9072014-05-13 13:35:14 +0100761 try {
762 primaryZygoteState = ZygoteState.connect(ZYGOTE_SOCKET);
763 } catch (IOException ioe) {
764 throw new ZygoteStartFailedEx("Error connecting to primary zygote", ioe);
765 }
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100766 }
767
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100768 if (primaryZygoteState.matches(abi)) {
769 return primaryZygoteState;
770 }
771
772 // The primary zygote didn't match. Try the secondary.
773 if (secondaryZygoteState == null || secondaryZygoteState.isClosed()) {
Narayan Kamath64cd9072014-05-13 13:35:14 +0100774 try {
775 secondaryZygoteState = ZygoteState.connect(SECONDARY_ZYGOTE_SOCKET);
776 } catch (IOException ioe) {
777 throw new ZygoteStartFailedEx("Error connecting to secondary zygote", ioe);
778 }
Narayan Kamath4444dcd2014-04-03 20:15:15 +0100779 }
780
781 if (secondaryZygoteState.matches(abi)) {
782 return secondaryZygoteState;
783 }
784
785 throw new ZygoteStartFailedEx("Unsupported zygote ABI: " + abi);
786 }
787
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800788 /**
789 * Returns elapsed milliseconds of the time this process has run.
790 * @return Returns the number of milliseconds this process has return.
791 */
792 public static final native long getElapsedCpuTime();
Andreas Gampeee0cdce2015-06-08 20:47:50 -0700793
794 /**
Dianne Hackbornd98885c2016-03-01 17:13:03 -0800795 * Return the {@link SystemClock#elapsedRealtime()} at which this process was started.
796 */
797 public static final long getStartElapsedRealtime() {
798 return sStartElapsedRealtime;
799 }
800
801 /**
802 * Return the {@link SystemClock#uptimeMillis()} at which this process was started.
803 */
804 public static final long getStartUptimeMillis() {
805 return sStartUptimeMillis;
806 }
807
808 /** @hide */
809 public static final void setStartTimes(long elapsedRealtime, long uptimeMillis) {
810 sStartElapsedRealtime = elapsedRealtime;
811 sStartUptimeMillis = uptimeMillis;
812 }
813
814 /**
Andreas Gampeee0cdce2015-06-08 20:47:50 -0700815 * Returns true if the current process is a 64-bit runtime.
816 */
817 public static final boolean is64Bit() {
818 return VMRuntime.getRuntime().is64Bit();
819 }
820
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800821 /**
822 * Returns the identifier of this process, which can be used with
823 * {@link #killProcess} and {@link #sendSignal}.
824 */
Jeff Hao406ec152013-07-30 10:13:41 -0700825 public static final int myPid() {
Elliott Hughes34385d32014-04-28 11:11:32 -0700826 return Os.getpid();
Jeff Hao406ec152013-07-30 10:13:41 -0700827 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800828
829 /**
Romain Guy80b12fc2013-05-29 15:54:25 -0700830 * Returns the identifier of this process' parent.
831 * @hide
832 */
Elliott Hughes2a805f92013-07-31 18:25:47 -0700833 public static final int myPpid() {
Elliott Hughes34385d32014-04-28 11:11:32 -0700834 return Os.getppid();
Elliott Hughes2a805f92013-07-31 18:25:47 -0700835 }
Romain Guy80b12fc2013-05-29 15:54:25 -0700836
837 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800838 * Returns the identifier of the calling thread, which be used with
839 * {@link #setThreadPriority(int, int)}.
840 */
Elliott Hughes6d4b1e22013-07-31 17:38:11 -0700841 public static final int myTid() {
Elliott Hughes34385d32014-04-28 11:11:32 -0700842 return Os.gettid();
Elliott Hughes6d4b1e22013-07-31 17:38:11 -0700843 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844
845 /**
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700846 * Returns the identifier of this process's uid. This is the kernel uid
847 * that the process is running under, which is the identity of its
848 * app-specific sandbox. It is different from {@link #myUserHandle} in that
849 * a uid identifies a specific app sandbox in a specific user.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 */
Jeff Hao406ec152013-07-30 10:13:41 -0700851 public static final int myUid() {
Elliott Hughes34385d32014-04-28 11:11:32 -0700852 return Os.getuid();
Jeff Hao406ec152013-07-30 10:13:41 -0700853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800854
855 /**
Dianne Hackborn79af1dd2012-08-16 16:42:52 -0700856 * Returns this process's user handle. This is the
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700857 * user the process is running under. It is distinct from
858 * {@link #myUid()} in that a particular user will have multiple
859 * distinct apps running under it each with their own uid.
860 */
Fyodor Kupolov02cb6e72015-09-18 18:20:55 -0700861 public static UserHandle myUserHandle() {
862 return UserHandle.of(UserHandle.getUserId(myUid()));
Dianne Hackborn7d19e022012-08-07 19:12:33 -0700863 }
864
865 /**
Jeff Davidson48aa86b2016-02-10 14:15:42 -0800866 * Returns whether the given uid belongs to an application.
867 * @param uid A kernel uid.
868 * @return Whether the uid corresponds to an application sandbox running in
869 * a specific user.
870 */
871 public static boolean isApplicationUid(int uid) {
872 return UserHandle.isApp(uid);
873 }
874
875 /**
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800876 * Returns whether the current process is in an isolated sandbox.
877 * @hide
878 */
879 public static final boolean isIsolated() {
Jeff Sharkey9527b222015-06-24 15:24:48 -0700880 return isIsolated(myUid());
881 }
882
883 /** {@hide} */
884 public static final boolean isIsolated(int uid) {
885 uid = UserHandle.getAppId(uid);
Dianne Hackborna0c283e2012-02-09 10:47:01 -0800886 return uid >= FIRST_ISOLATED_UID && uid <= LAST_ISOLATED_UID;
887 }
888
889 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800890 * Returns the UID assigned to a particular user name, or -1 if there is
891 * none. If the given string consists of only numbers, it is converted
892 * directly to a uid.
893 */
894 public static final native int getUidForName(String name);
895
896 /**
897 * Returns the GID assigned to a particular user name, or -1 if there is
898 * none. If the given string consists of only numbers, it is converted
899 * directly to a gid.
900 */
901 public static final native int getGidForName(String name);
Amith Yamasani819f9282009-06-24 23:18:15 -0700902
903 /**
904 * Returns a uid for a currently running process.
905 * @param pid the process id
906 * @return the uid of the process, or -1 if the process is not running.
907 * @hide pending API council review
908 */
909 public static final int getUidForPid(int pid) {
910 String[] procStatusLabels = { "Uid:" };
911 long[] procStatusValues = new long[1];
912 procStatusValues[0] = -1;
913 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
914 return (int) procStatusValues[0];
915 }
916
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 /**
Jeff Brownebed7d62011-05-16 17:08:42 -0700918 * Returns the parent process id for a currently running process.
919 * @param pid the process id
920 * @return the parent process id of the process, or -1 if the process is not running.
921 * @hide
922 */
923 public static final int getParentPid(int pid) {
924 String[] procStatusLabels = { "PPid:" };
925 long[] procStatusValues = new long[1];
926 procStatusValues[0] = -1;
927 Process.readProcLines("/proc/" + pid + "/status", procStatusLabels, procStatusValues);
928 return (int) procStatusValues[0];
929 }
930
931 /**
Glenn Kasten07b04652012-04-23 15:00:43 -0700932 * Returns the thread group leader id for a currently running thread.
933 * @param tid the thread id
934 * @return the thread group leader id of the thread, or -1 if the thread is not running.
935 * This is same as what getpid(2) would return if called by tid.
936 * @hide
937 */
938 public static final int getThreadGroupLeader(int tid) {
939 String[] procStatusLabels = { "Tgid:" };
940 long[] procStatusValues = new long[1];
941 procStatusValues[0] = -1;
942 Process.readProcLines("/proc/" + tid + "/status", procStatusLabels, procStatusValues);
943 return (int) procStatusValues[0];
944 }
945
946 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800947 * Set the priority of a thread, based on Linux priorities.
948 *
949 * @param tid The identifier of the thread/process to change.
950 * @param priority A Linux priority level, from -20 for highest scheduling
951 * priority to 19 for lowest scheduling priority.
952 *
953 * @throws IllegalArgumentException Throws IllegalArgumentException if
954 * <var>tid</var> does not exist.
955 * @throws SecurityException Throws SecurityException if your process does
956 * not have permission to modify the given thread, or to use the given
957 * priority.
958 */
959 public static final native void setThreadPriority(int tid, int priority)
960 throws IllegalArgumentException, SecurityException;
San Mehate9d376b2009-04-21 14:06:36 -0700961
962 /**
Christopher Tate160edb32010-06-30 17:46:30 -0700963 * Call with 'false' to cause future calls to {@link #setThreadPriority(int)} to
964 * throw an exception if passed a background-level thread priority. This is only
965 * effective if the JNI layer is built with GUARD_THREAD_PRIORITY defined to 1.
966 *
967 * @hide
968 */
969 public static final native void setCanSelfBackground(boolean backgroundOk);
970
971 /**
San Mehate9d376b2009-04-21 14:06:36 -0700972 * Sets the scheduling group for a thread.
973 * @hide
Glenn Kastenf1b56442012-03-15 16:33:43 -0700974 * @param tid The identifier of the thread to change.
975 * @param group The target group for this thread from THREAD_GROUP_*.
San Mehate9d376b2009-04-21 14:06:36 -0700976 *
977 * @throws IllegalArgumentException Throws IllegalArgumentException if
978 * <var>tid</var> does not exist.
979 * @throws SecurityException Throws SecurityException if your process does
980 * not have permission to modify the given thread, or to use the given
981 * priority.
Glenn Kastenf1b56442012-03-15 16:33:43 -0700982 * If the thread is a thread group leader, that is it's gettid() == getpid(),
983 * then the other threads in the same thread group are _not_ affected.
Tim Murray4074ad02016-07-08 15:45:45 -0700984 *
985 * Does not set cpuset for some historical reason, just calls
986 * libcutils::set_sched_policy().
San Mehate9d376b2009-04-21 14:06:36 -0700987 */
988 public static final native void setThreadGroup(int tid, int group)
989 throws IllegalArgumentException, SecurityException;
Glenn Kastenf1b56442012-03-15 16:33:43 -0700990
San Mehat3e458242009-05-19 14:44:16 -0700991 /**
992 * Sets the scheduling group for a process and all child threads
993 * @hide
Glenn Kastenf1b56442012-03-15 16:33:43 -0700994 * @param pid The identifier of the process to change.
995 * @param group The target group for this process from THREAD_GROUP_*.
San Mehat3e458242009-05-19 14:44:16 -0700996 *
997 * @throws IllegalArgumentException Throws IllegalArgumentException if
998 * <var>tid</var> does not exist.
999 * @throws SecurityException Throws SecurityException if your process does
1000 * not have permission to modify the given thread, or to use the given
1001 * priority.
Glenn Kastenf1b56442012-03-15 16:33:43 -07001002 *
1003 * group == THREAD_GROUP_DEFAULT means to move all non-background priority
1004 * threads to the foreground scheduling group, but to leave background
1005 * priority threads alone. group == THREAD_GROUP_BG_NONINTERACTIVE moves all
1006 * threads, regardless of priority, to the background scheduling group.
1007 * group == THREAD_GROUP_FOREGROUND is not allowed.
Tim Murray4074ad02016-07-08 15:45:45 -07001008 *
1009 * Always sets cpusets.
San Mehat3e458242009-05-19 14:44:16 -07001010 */
1011 public static final native void setProcessGroup(int pid, int group)
1012 throws IllegalArgumentException, SecurityException;
Jeff Sharkey9e57c412013-01-17 14:12:41 -08001013
1014 /**
1015 * Return the scheduling group of requested process.
1016 *
1017 * @hide
1018 */
1019 public static final native int getProcessGroup(int pid)
1020 throws IllegalArgumentException, SecurityException;
1021
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001022 /**
Martijn Coenencd4bdf32016-03-03 17:30:52 +01001023 * On some devices, the foreground process may have one or more CPU
1024 * cores exclusively reserved for it. This method can be used to
1025 * retrieve which cores that are (if any), so the calling process
1026 * can then use sched_setaffinity() to lock a thread to these cores.
1027 * Note that the calling process must currently be running in the
1028 * foreground for this method to return any cores.
1029 *
1030 * The CPU core(s) exclusively reserved for the foreground process will
1031 * stay reserved for as long as the process stays in the foreground.
1032 *
1033 * As soon as a process leaves the foreground, those CPU cores will
1034 * no longer be reserved for it, and will most likely be reserved for
1035 * the new foreground process. It's not necessary to change the affinity
1036 * of your process when it leaves the foreground (if you had previously
1037 * set it to use a reserved core); the OS will automatically take care
1038 * of resetting the affinity at that point.
1039 *
1040 * @return an array of integers, indicating the CPU cores exclusively
1041 * reserved for this process. The array will have length zero if no
1042 * CPU cores are exclusively reserved for this process at this point
1043 * in time.
1044 */
1045 public static final native int[] getExclusiveCores();
1046
1047 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 * Set the priority of the calling thread, based on Linux priorities. See
1049 * {@link #setThreadPriority(int, int)} for more information.
1050 *
1051 * @param priority A Linux priority level, from -20 for highest scheduling
1052 * priority to 19 for lowest scheduling priority.
1053 *
1054 * @throws IllegalArgumentException Throws IllegalArgumentException if
1055 * <var>tid</var> does not exist.
1056 * @throws SecurityException Throws SecurityException if your process does
1057 * not have permission to modify the given thread, or to use the given
1058 * priority.
1059 *
1060 * @see #setThreadPriority(int, int)
1061 */
1062 public static final native void setThreadPriority(int priority)
1063 throws IllegalArgumentException, SecurityException;
1064
1065 /**
1066 * Return the current priority of a thread, based on Linux priorities.
1067 *
1068 * @param tid The identifier of the thread/process to change.
1069 *
1070 * @return Returns the current priority, as a Linux priority level,
1071 * from -20 for highest scheduling priority to 19 for lowest scheduling
1072 * priority.
1073 *
1074 * @throws IllegalArgumentException Throws IllegalArgumentException if
1075 * <var>tid</var> does not exist.
1076 */
1077 public static final native int getThreadPriority(int tid)
1078 throws IllegalArgumentException;
1079
1080 /**
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001081 * Return the current scheduling policy of a thread, based on Linux.
1082 *
1083 * @param tid The identifier of the thread/process to get the scheduling policy.
1084 *
1085 * @throws IllegalArgumentException Throws IllegalArgumentException if
1086 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1087 * @throws SecurityException Throws SecurityException if your process does
1088 * not have permission to modify the given thread, or to use the given
1089 * scheduling policy or priority.
1090 *
1091 * {@hide}
1092 */
1093
1094 @TestApi
1095 public static final native int getThreadScheduler(int tid)
1096 throws IllegalArgumentException;
1097
1098 /**
Glenn Kasten6793ac92011-07-13 12:44:12 -07001099 * Set the scheduling policy and priority of a thread, based on Linux.
1100 *
1101 * @param tid The identifier of the thread/process to change.
1102 * @param policy A Linux scheduling policy such as SCHED_OTHER etc.
1103 * @param priority A Linux priority level in a range appropriate for the given policy.
1104 *
1105 * @throws IllegalArgumentException Throws IllegalArgumentException if
1106 * <var>tid</var> does not exist, or if <var>priority</var> is out of range for the policy.
1107 * @throws SecurityException Throws SecurityException if your process does
1108 * not have permission to modify the given thread, or to use the given
1109 * scheduling policy or priority.
1110 *
1111 * {@hide}
1112 */
Srinath Sridharan1b15d132016-07-19 15:16:11 -07001113
Glenn Kasten6793ac92011-07-13 12:44:12 -07001114 public static final native void setThreadScheduler(int tid, int policy, int priority)
1115 throws IllegalArgumentException;
1116
1117 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001118 * Determine whether the current environment supports multiple processes.
1119 *
1120 * @return Returns true if the system can run in multiple processes, else
1121 * false if everything is running in a single process.
Jeff Brown10e89712011-07-08 18:52:57 -07001122 *
1123 * @deprecated This method always returns true. Do not use.
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 */
Jeff Brown10e89712011-07-08 18:52:57 -07001125 @Deprecated
1126 public static final boolean supportsProcesses() {
1127 return true;
1128 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129
1130 /**
Rom Lemarchand5534ba92013-07-12 16:15:36 -07001131 * Adjust the swappiness level for a process.
1132 *
1133 * @param pid The process identifier to set.
1134 * @param is_increased Whether swappiness should be increased or default.
1135 *
1136 * @return Returns true if the underlying system supports this
1137 * feature, else false.
1138 *
1139 * {@hide}
1140 */
1141 public static final native boolean setSwappiness(int pid, boolean is_increased);
1142
1143 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 * Change this process's argv[0] parameter. This can be useful to show
1145 * more descriptive information in things like the 'ps' command.
1146 *
1147 * @param text The new name of this process.
1148 *
1149 * {@hide}
1150 */
1151 public static final native void setArgV0(String text);
1152
1153 /**
1154 * Kill the process with the given PID.
1155 * Note that, though this API allows us to request to
1156 * kill any process based on its PID, the kernel will
1157 * still impose standard restrictions on which PIDs you
1158 * are actually able to kill. Typically this means only
1159 * the process running the caller's packages/application
1160 * and any additional processes created by that app; packages
1161 * sharing a common UID will also be able to kill each
1162 * other's processes.
1163 */
1164 public static final void killProcess(int pid) {
1165 sendSignal(pid, SIGNAL_KILL);
1166 }
1167
1168 /** @hide */
1169 public static final native int setUid(int uid);
1170
1171 /** @hide */
1172 public static final native int setGid(int uid);
1173
1174 /**
1175 * Send a signal to the given process.
1176 *
1177 * @param pid The pid of the target process.
1178 * @param signal The signal to send.
1179 */
1180 public static final native void sendSignal(int pid, int signal);
1181
Dianne Hackborn906497c2010-05-10 15:57:38 -07001182 /**
1183 * @hide
1184 * Private impl for avoiding a log message... DO NOT USE without doing
1185 * your own log, or the Android Illuminati will find you some night and
1186 * beat you up.
1187 */
1188 public static final void killProcessQuiet(int pid) {
1189 sendSignalQuiet(pid, SIGNAL_KILL);
1190 }
1191
1192 /**
1193 * @hide
1194 * Private impl for avoiding a log message... DO NOT USE without doing
1195 * your own log, or the Android Illuminati will find you some night and
1196 * beat you up.
1197 */
1198 public static final native void sendSignalQuiet(int pid, int signal);
1199
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001200 /** @hide */
Marco Nelissen0bca96b2009-07-17 12:59:25 -07001201 public static final native long getFreeMemory();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202
1203 /** @hide */
Dianne Hackborn59325eb2012-05-09 18:45:20 -07001204 public static final native long getTotalMemory();
1205
1206 /** @hide */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001207 public static final native void readProcLines(String path,
1208 String[] reqFields, long[] outSizes);
1209
1210 /** @hide */
1211 public static final native int[] getPids(String path, int[] lastArray);
1212
1213 /** @hide */
1214 public static final int PROC_TERM_MASK = 0xff;
1215 /** @hide */
1216 public static final int PROC_ZERO_TERM = 0;
1217 /** @hide */
1218 public static final int PROC_SPACE_TERM = (int)' ';
1219 /** @hide */
Evan Millarc64edde2009-04-18 12:26:32 -07001220 public static final int PROC_TAB_TERM = (int)'\t';
1221 /** @hide */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 public static final int PROC_COMBINE = 0x100;
1223 /** @hide */
1224 public static final int PROC_PARENS = 0x200;
1225 /** @hide */
Dianne Hackborn13ac0412013-06-25 19:34:49 -07001226 public static final int PROC_QUOTES = 0x400;
1227 /** @hide */
Dianne Hackborn4de5a3a2016-06-20 15:20:15 -07001228 public static final int PROC_CHAR = 0x800;
1229 /** @hide */
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001230 public static final int PROC_OUT_STRING = 0x1000;
1231 /** @hide */
1232 public static final int PROC_OUT_LONG = 0x2000;
1233 /** @hide */
1234 public static final int PROC_OUT_FLOAT = 0x4000;
1235
1236 /** @hide */
1237 public static final native boolean readProcFile(String file, int[] format,
1238 String[] outStrings, long[] outLongs, float[] outFloats);
Evan Millarc64edde2009-04-18 12:26:32 -07001239
1240 /** @hide */
1241 public static final native boolean parseProcLine(byte[] buffer, int startIndex,
1242 int endIndex, int[] format, String[] outStrings, long[] outLongs, float[] outFloats);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243
Dianne Hackbornf72467a2012-06-08 17:23:59 -07001244 /** @hide */
1245 public static final native int[] getPidsForCommands(String[] cmds);
1246
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001247 /**
1248 * Gets the total Pss value for a given process, in bytes.
1249 *
1250 * @param pid the process to the Pss for
1251 * @return the total Pss value for the given process in bytes,
1252 * or -1 if the value cannot be determined
1253 * @hide
1254 */
1255 public static final native long getPss(int pid);
Jeff Brown3f9dd282011-07-08 20:02:19 -07001256
1257 /**
1258 * Specifies the outcome of having started a process.
1259 * @hide
1260 */
1261 public static final class ProcessStartResult {
1262 /**
1263 * The PID of the newly started process.
1264 * Always >= 0. (If the start failed, an exception will have been thrown instead.)
1265 */
1266 public int pid;
1267
1268 /**
1269 * True if the process was started with a wrapper attached.
1270 */
1271 public boolean usingWrapper;
1272 }
Colin Cross0769e552014-06-03 13:25:35 -07001273
1274 /**
1275 * Kill all processes in a process group started for the given
1276 * pid.
1277 * @hide
1278 */
1279 public static final native int killProcessGroup(int uid, int pid);
1280
1281 /**
1282 * Remove all process groups. Expected to be called when ActivityManager
1283 * is restarted.
1284 * @hide
1285 */
1286 public static final native void removeAllProcessGroups();
Tim Murrayb89970e2016-07-01 10:42:20 -07001287
1288 /**
1289 * Check to see if a thread belongs to a given process. This may require
1290 * more permissions than apps generally have.
1291 * @return true if this thread belongs to a process
1292 * @hide
1293 */
1294 public static final boolean isThreadInProcess(int tid, int pid) {
Tim Murray9bc12a82016-07-16 11:28:40 -07001295 StrictMode.ThreadPolicy oldPolicy = StrictMode.allowThreadDiskReads();
Tim Murrayb89970e2016-07-01 10:42:20 -07001296 try {
1297 if (Os.access("/proc/" + tid + "/task/" + pid, OsConstants.F_OK)) {
1298 return true;
1299 } else {
1300 return false;
1301 }
1302 } catch (Exception e) {
1303 return false;
Tim Murray9bc12a82016-07-16 11:28:40 -07001304 } finally {
1305 StrictMode.setThreadPolicy(oldPolicy);
Tim Murrayb89970e2016-07-01 10:42:20 -07001306 }
Tim Murray9bc12a82016-07-16 11:28:40 -07001307
Tim Murrayb89970e2016-07-01 10:42:20 -07001308 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001309}